Home | History | Annotate | Download | only in win
      1 /*
      2  *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
      3  *
      4  *  Use of this source code is governed by a BSD-style license
      5  *  that can be found in the LICENSE file in the root of the source
      6  *  tree. An additional intellectual property rights grant can be found
      7  *  in the file PATENTS.  All contributing project authors may
      8  *  be found in the AUTHORS file in the root of the source tree.
      9  */
     10 
     11 #ifndef WEBRTC_AUDIO_DEVICE_AUDIO_DEVICE_WAVE_WIN_H
     12 #define WEBRTC_AUDIO_DEVICE_AUDIO_DEVICE_WAVE_WIN_H
     13 
     14 #include "webrtc/modules/audio_device/audio_device_generic.h"
     15 #include "webrtc/modules/audio_device/win/audio_mixer_manager_win.h"
     16 
     17 #pragma comment( lib, "winmm.lib" )
     18 
     19 namespace webrtc {
     20 class EventWrapper;
     21 class ThreadWrapper;
     22 
     23 const uint32_t TIMER_PERIOD_MS = 2;
     24 const uint32_t REC_CHECK_TIME_PERIOD_MS = 4;
     25 const uint16_t REC_PUT_BACK_DELAY = 4;
     26 
     27 const uint32_t N_REC_SAMPLES_PER_SEC = 48000;
     28 const uint32_t N_PLAY_SAMPLES_PER_SEC = 48000;
     29 
     30 const uint32_t N_REC_CHANNELS = 1;  // default is mono recording
     31 const uint32_t N_PLAY_CHANNELS = 2; // default is stereo playout
     32 
     33 // NOTE - CPU load will not be correct for other sizes than 10ms
     34 const uint32_t REC_BUF_SIZE_IN_SAMPLES = (N_REC_SAMPLES_PER_SEC/100);
     35 const uint32_t PLAY_BUF_SIZE_IN_SAMPLES = (N_PLAY_SAMPLES_PER_SEC/100);
     36 
     37 enum { N_BUFFERS_IN = 200 };
     38 enum { N_BUFFERS_OUT = 200 };
     39 
     40 class AudioDeviceWindowsWave : public AudioDeviceGeneric
     41 {
     42 public:
     43     AudioDeviceWindowsWave(const int32_t id);
     44     ~AudioDeviceWindowsWave();
     45 
     46     // Retrieve the currently utilized audio layer
     47     virtual int32_t ActiveAudioLayer(AudioDeviceModule::AudioLayer& audioLayer) const;
     48 
     49     // Main initializaton and termination
     50     virtual int32_t Init();
     51     virtual int32_t Terminate();
     52     virtual bool Initialized() const;
     53 
     54     // Device enumeration
     55     virtual int16_t PlayoutDevices();
     56     virtual int16_t RecordingDevices();
     57     virtual int32_t PlayoutDeviceName(
     58         uint16_t index,
     59         char name[kAdmMaxDeviceNameSize],
     60         char guid[kAdmMaxGuidSize]);
     61     virtual int32_t RecordingDeviceName(
     62         uint16_t index,
     63         char name[kAdmMaxDeviceNameSize],
     64         char guid[kAdmMaxGuidSize]);
     65 
     66     // Device selection
     67     virtual int32_t SetPlayoutDevice(uint16_t index);
     68     virtual int32_t SetPlayoutDevice(AudioDeviceModule::WindowsDeviceType device);
     69     virtual int32_t SetRecordingDevice(uint16_t index);
     70     virtual int32_t SetRecordingDevice(AudioDeviceModule::WindowsDeviceType device);
     71 
     72     // Audio transport initialization
     73     virtual int32_t PlayoutIsAvailable(bool& available);
     74     virtual int32_t InitPlayout();
     75     virtual bool PlayoutIsInitialized() const;
     76     virtual int32_t RecordingIsAvailable(bool& available);
     77     virtual int32_t InitRecording();
     78     virtual bool RecordingIsInitialized() const;
     79 
     80     // Audio transport control
     81     virtual int32_t StartPlayout();
     82     virtual int32_t StopPlayout();
     83     virtual bool Playing() const;
     84     virtual int32_t StartRecording();
     85     virtual int32_t StopRecording();
     86     virtual bool Recording() const;
     87 
     88     // Microphone Automatic Gain Control (AGC)
     89     virtual int32_t SetAGC(bool enable);
     90     virtual bool AGC() const;
     91 
     92     // Volume control based on the Windows Wave API (Windows only)
     93     virtual int32_t SetWaveOutVolume(uint16_t volumeLeft, uint16_t volumeRight);
     94     virtual int32_t WaveOutVolume(uint16_t& volumeLeft, uint16_t& volumeRight) const;
     95 
     96     // Audio mixer initialization
     97     virtual int32_t InitSpeaker();
     98     virtual bool SpeakerIsInitialized() const;
     99     virtual int32_t InitMicrophone();
    100     virtual bool MicrophoneIsInitialized() const;
    101 
    102     // Speaker volume controls
    103     virtual int32_t SpeakerVolumeIsAvailable(bool& available);
    104     virtual int32_t SetSpeakerVolume(uint32_t volume);
    105     virtual int32_t SpeakerVolume(uint32_t& volume) const;
    106     virtual int32_t MaxSpeakerVolume(uint32_t& maxVolume) const;
    107     virtual int32_t MinSpeakerVolume(uint32_t& minVolume) const;
    108     virtual int32_t SpeakerVolumeStepSize(uint16_t& stepSize) const;
    109 
    110     // Microphone volume controls
    111     virtual int32_t MicrophoneVolumeIsAvailable(bool& available);
    112     virtual int32_t SetMicrophoneVolume(uint32_t volume);
    113     virtual int32_t MicrophoneVolume(uint32_t& volume) const;
    114     virtual int32_t MaxMicrophoneVolume(uint32_t& maxVolume) const;
    115     virtual int32_t MinMicrophoneVolume(uint32_t& minVolume) const;
    116     virtual int32_t MicrophoneVolumeStepSize(uint16_t& stepSize) const;
    117 
    118     // Speaker mute control
    119     virtual int32_t SpeakerMuteIsAvailable(bool& available);
    120     virtual int32_t SetSpeakerMute(bool enable);
    121     virtual int32_t SpeakerMute(bool& enabled) const;
    122 
    123     // Microphone mute control
    124     virtual int32_t MicrophoneMuteIsAvailable(bool& available);
    125     virtual int32_t SetMicrophoneMute(bool enable);
    126     virtual int32_t MicrophoneMute(bool& enabled) const;
    127 
    128     // Microphone boost control
    129     virtual int32_t MicrophoneBoostIsAvailable(bool& available);
    130     virtual int32_t SetMicrophoneBoost(bool enable);
    131     virtual int32_t MicrophoneBoost(bool& enabled) const;
    132 
    133     // Stereo support
    134     virtual int32_t StereoPlayoutIsAvailable(bool& available);
    135     virtual int32_t SetStereoPlayout(bool enable);
    136     virtual int32_t StereoPlayout(bool& enabled) const;
    137     virtual int32_t StereoRecordingIsAvailable(bool& available);
    138     virtual int32_t SetStereoRecording(bool enable);
    139     virtual int32_t StereoRecording(bool& enabled) const;
    140 
    141     // Delay information and control
    142     virtual int32_t SetPlayoutBuffer(const AudioDeviceModule::BufferType type, uint16_t sizeMS);
    143     virtual int32_t PlayoutBuffer(AudioDeviceModule::BufferType& type, uint16_t& sizeMS) const;
    144     virtual int32_t PlayoutDelay(uint16_t& delayMS) const;
    145     virtual int32_t RecordingDelay(uint16_t& delayMS) const;
    146 
    147     // CPU load
    148     virtual int32_t CPULoad(uint16_t& load) const;
    149 
    150 public:
    151     virtual bool PlayoutWarning() const;
    152     virtual bool PlayoutError() const;
    153     virtual bool RecordingWarning() const;
    154     virtual bool RecordingError() const;
    155     virtual void ClearPlayoutWarning();
    156     virtual void ClearPlayoutError();
    157     virtual void ClearRecordingWarning();
    158     virtual void ClearRecordingError();
    159 
    160 public:
    161     virtual void AttachAudioBuffer(AudioDeviceBuffer* audioBuffer);
    162 
    163 private:
    164     void Lock() { _critSect.Enter(); };
    165     void UnLock() { _critSect.Leave(); };
    166     int32_t Id() {return _id;}
    167     bool IsUsingOutputDeviceIndex() const {return _usingOutputDeviceIndex;}
    168     AudioDeviceModule::WindowsDeviceType OutputDevice() const {return _outputDevice;}
    169     uint16_t OutputDeviceIndex() const {return _outputDeviceIndex;}
    170     bool IsUsingInputDeviceIndex() const {return _usingInputDeviceIndex;}
    171     AudioDeviceModule::WindowsDeviceType InputDevice() const {return _inputDevice;}
    172     uint16_t InputDeviceIndex() const {return _inputDeviceIndex;}
    173 
    174 private:
    175     inline int32_t InputSanityCheckAfterUnlockedPeriod() const;
    176     inline int32_t OutputSanityCheckAfterUnlockedPeriod() const;
    177 
    178 private:
    179     bool KeyPressed() const;
    180 
    181 private:
    182     int32_t EnumeratePlayoutDevices();
    183     int32_t EnumerateRecordingDevices();
    184     void TraceSupportFlags(DWORD dwSupport) const;
    185     void TraceWaveInError(MMRESULT error) const;
    186     void TraceWaveOutError(MMRESULT error) const;
    187     int32_t PrepareStartRecording();
    188     int32_t PrepareStartPlayout();
    189 
    190     int32_t RecProc(LONGLONG& consumedTime);
    191     int PlayProc(LONGLONG& consumedTime);
    192 
    193     int32_t GetPlayoutBufferDelay(uint32_t& writtenSamples, uint32_t& playedSamples);
    194     int32_t GetRecordingBufferDelay(uint32_t& readSamples, uint32_t& recSamples);
    195     int32_t Write(int8_t* data, uint16_t nSamples);
    196     int32_t GetClockDrift(const uint32_t plSamp, const uint32_t rcSamp);
    197     int32_t MonitorRecording(const uint32_t time);
    198     int32_t RestartTimerIfNeeded(const uint32_t time);
    199 
    200 private:
    201     static bool ThreadFunc(void*);
    202     bool ThreadProcess();
    203 
    204     static DWORD WINAPI GetCaptureVolumeThread(LPVOID context);
    205     DWORD DoGetCaptureVolumeThread();
    206 
    207     static DWORD WINAPI SetCaptureVolumeThread(LPVOID context);
    208     DWORD DoSetCaptureVolumeThread();
    209 
    210 private:
    211     AudioDeviceBuffer*                      _ptrAudioBuffer;
    212 
    213     CriticalSectionWrapper&                 _critSect;
    214     EventWrapper&                           _timeEvent;
    215     EventWrapper&                           _recStartEvent;
    216     EventWrapper&                           _playStartEvent;
    217 
    218     HANDLE                                  _hGetCaptureVolumeThread;
    219     HANDLE                                  _hShutdownGetVolumeEvent;
    220     HANDLE                                  _hSetCaptureVolumeThread;
    221     HANDLE                                  _hShutdownSetVolumeEvent;
    222     HANDLE                                  _hSetCaptureVolumeEvent;
    223 
    224     ThreadWrapper*                          _ptrThread;
    225     uint32_t                                _threadID;
    226 
    227     CriticalSectionWrapper&                 _critSectCb;
    228 
    229     int32_t                                 _id;
    230 
    231     AudioMixerManager                       _mixerManager;
    232 
    233     bool                                    _usingInputDeviceIndex;
    234     bool                                    _usingOutputDeviceIndex;
    235     AudioDeviceModule::WindowsDeviceType    _inputDevice;
    236     AudioDeviceModule::WindowsDeviceType    _outputDevice;
    237     uint16_t                                _inputDeviceIndex;
    238     uint16_t                                _outputDeviceIndex;
    239     bool                                    _inputDeviceIsSpecified;
    240     bool                                    _outputDeviceIsSpecified;
    241 
    242     WAVEFORMATEX                            _waveFormatIn;
    243     WAVEFORMATEX                            _waveFormatOut;
    244 
    245     HWAVEIN                                 _hWaveIn;
    246     HWAVEOUT                                _hWaveOut;
    247 
    248     WAVEHDR                                 _waveHeaderIn[N_BUFFERS_IN];
    249     WAVEHDR                                 _waveHeaderOut[N_BUFFERS_OUT];
    250 
    251     uint8_t                                 _recChannels;
    252     uint8_t                                 _playChannels;
    253     uint16_t                                _recBufCount;
    254     uint16_t                                _recDelayCount;
    255     uint16_t                                _recPutBackDelay;
    256 
    257     int8_t               _recBuffer[N_BUFFERS_IN][4*REC_BUF_SIZE_IN_SAMPLES];
    258     int8_t               _playBuffer[N_BUFFERS_OUT][4*PLAY_BUF_SIZE_IN_SAMPLES];
    259 
    260     AudioDeviceModule::BufferType           _playBufType;
    261 
    262 private:
    263     bool                                    _initialized;
    264     bool                                    _recording;
    265     bool                                    _playing;
    266     bool                                    _recIsInitialized;
    267     bool                                    _playIsInitialized;
    268     bool                                    _startRec;
    269     bool                                    _stopRec;
    270     bool                                    _startPlay;
    271     bool                                    _stopPlay;
    272     bool                                    _AGC;
    273 
    274 private:
    275     uint32_t                          _prevPlayTime;
    276     uint32_t                          _prevRecTime;
    277     uint32_t                          _prevTimerCheckTime;
    278 
    279     uint16_t                          _playBufCount;          // playout buffer index
    280     uint16_t                          _dTcheckPlayBufDelay;   // dT for check of play buffer, {2,5,10} [ms]
    281     uint16_t                          _playBufDelay;          // playback delay
    282     uint16_t                          _playBufDelayFixed;     // fixed playback delay
    283     uint16_t                          _minPlayBufDelay;       // minimum playback delay
    284     uint16_t                          _MAX_minBuffer;         // level of (adaptive) min threshold must be < _MAX_minBuffer
    285 
    286     int32_t                           _erZeroCounter;         // counts "buffer-is-empty" events
    287     int32_t                           _intro;
    288     int32_t                           _waitCounter;
    289 
    290     uint32_t                          _writtenSamples;
    291     uint32_t                          _writtenSamplesOld;
    292     uint32_t                          _playedSamplesOld;
    293 
    294     uint32_t                          _sndCardPlayDelay;
    295     uint32_t                          _sndCardRecDelay;
    296 
    297     uint32_t                          _plSampOld;
    298     uint32_t                          _rcSampOld;
    299 
    300     uint32_t                          _read_samples;
    301     uint32_t                          _read_samples_old;
    302     uint32_t                          _rec_samples_old;
    303 
    304     // State that detects driver problems:
    305     int32_t                           _dc_diff_mean;
    306     int32_t                           _dc_y_prev;
    307     int32_t                           _dc_penalty_counter;
    308     int32_t                           _dc_prevtime;
    309     uint32_t                          _dc_prevplay;
    310 
    311     uint32_t                          _recordedBytes;         // accumulated #recorded bytes (reset periodically)
    312     uint32_t                          _prevRecByteCheckTime;  // time when we last checked the recording process
    313 
    314     // CPU load measurements
    315     LARGE_INTEGER                           _perfFreq;
    316     LONGLONG                                _playAcc;               // accumulated time for playout callback
    317     float                                   _avgCPULoad;            // average total (rec+play) CPU load
    318 
    319     int32_t                           _wrapCounter;
    320 
    321     int32_t                           _useHeader;
    322     int16_t                           _timesdwBytes;
    323     int32_t                           _no_of_msecleft_warnings;
    324     int32_t                           _writeErrors;
    325     int32_t                           _timerFaults;
    326     int32_t                           _timerRestartAttempts;
    327 
    328     uint16_t                          _playWarning;
    329     uint16_t                          _playError;
    330     uint16_t                          _recWarning;
    331     uint16_t                          _recError;
    332 
    333     uint32_t                          _newMicLevel;
    334     uint32_t                          _minMicVolume;
    335     uint32_t                          _maxMicVolume;
    336 };
    337 
    338 }  // namespace webrtc
    339 
    340 #endif  // WEBRTC_AUDIO_DEVICE_AUDIO_DEVICE_WAVE_WIN_H
    341