2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
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.
11 #include "webrtc/modules/audio_device/audio_device_config.h"
12 #include "webrtc/modules/audio_device/audio_device_utility.h"
13 #include "webrtc/modules/audio_device/win/audio_device_wave_win.h"
15 #include "webrtc/system_wrappers/interface/event_wrapper.h"
16 #include "webrtc/system_wrappers/interface/thread_wrapper.h"
17 #include "webrtc/system_wrappers/interface/trace.h"
20 #include <objbase.h> // CoTaskMemAlloc, CoTaskMemFree
21 #include <strsafe.h> // StringCchCopy(), StringCchCat(), StringCchPrintf()
24 // Avoids the need of Windows 7 SDK
25 #ifndef WAVE_MAPPED_DEFAULT_COMMUNICATION_DEVICE
26 #define WAVE_MAPPED_DEFAULT_COMMUNICATION_DEVICE 0x0010
29 // Supported in Windows Vista and Windows 7.
30 // http://msdn.microsoft.com/en-us/library/dd370819(v=VS.85).aspx
31 // Taken from Mmddk.h.
32 #define DRV_RESERVED 0x0800
33 #define DRV_QUERYFUNCTIONINSTANCEID (DRV_RESERVED + 17)
34 #define DRV_QUERYFUNCTIONINSTANCEIDSIZE (DRV_RESERVED + 18)
36 #define POW2(A) (2 << ((A) - 1))
40 // ============================================================================
41 // Construction & Destruction
42 // ============================================================================
44 // ----------------------------------------------------------------------------
45 // AudioDeviceWindowsWave - ctor
46 // ----------------------------------------------------------------------------
48 AudioDeviceWindowsWave::AudioDeviceWindowsWave(const int32_t id) :
49 _ptrAudioBuffer(NULL),
50 _critSect(*CriticalSectionWrapper::CreateCriticalSection()),
51 _timeEvent(*EventWrapper::Create()),
52 _recStartEvent(*EventWrapper::Create()),
53 _playStartEvent(*EventWrapper::Create()),
54 _hGetCaptureVolumeThread(NULL),
55 _hShutdownGetVolumeEvent(NULL),
56 _hSetCaptureVolumeThread(NULL),
57 _hShutdownSetVolumeEvent(NULL),
58 _hSetCaptureVolumeEvent(NULL),
61 _critSectCb(*CriticalSectionWrapper::CreateCriticalSection()),
64 _usingInputDeviceIndex(false),
65 _usingOutputDeviceIndex(false),
66 _inputDevice(AudioDeviceModule::kDefaultDevice),
67 _outputDevice(AudioDeviceModule::kDefaultDevice),
69 _outputDeviceIndex(0),
70 _inputDeviceIsSpecified(false),
71 _outputDeviceIsSpecified(false),
73 _recIsInitialized(false),
74 _playIsInitialized(false),
84 _recChannels(N_REC_CHANNELS),
85 _playChannels(N_PLAY_CHANNELS),
92 _prevTimerCheckTime(0),
95 _timerRestartAttempts(0),
96 _no_of_msecleft_warnings(0),
99 _dTcheckPlayBufDelay(10),
101 _playBufDelayFixed(80),
102 _minPlayBufDelay(20),
104 _sndCardPlayDelay(0),
108 _playBufType(AudioDeviceModule::kAdaptiveBufferSize),
118 WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, id, "%s created", __FUNCTION__);
120 // Initialize value, set to 0 if it fails
121 if (!QueryPerformanceFrequency(&_perfFreq))
123 _perfFreq.QuadPart = 0;
126 _hShutdownGetVolumeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
127 _hShutdownSetVolumeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
128 _hSetCaptureVolumeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
131 // ----------------------------------------------------------------------------
132 // AudioDeviceWindowsWave - dtor
133 // ----------------------------------------------------------------------------
135 AudioDeviceWindowsWave::~AudioDeviceWindowsWave()
137 WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, _id, "%s destroyed", __FUNCTION__);
141 delete &_recStartEvent;
142 delete &_playStartEvent;
147 if (NULL != _hShutdownGetVolumeEvent)
149 CloseHandle(_hShutdownGetVolumeEvent);
150 _hShutdownGetVolumeEvent = NULL;
153 if (NULL != _hShutdownSetVolumeEvent)
155 CloseHandle(_hShutdownSetVolumeEvent);
156 _hShutdownSetVolumeEvent = NULL;
159 if (NULL != _hSetCaptureVolumeEvent)
161 CloseHandle(_hSetCaptureVolumeEvent);
162 _hSetCaptureVolumeEvent = NULL;
166 // ============================================================================
168 // ============================================================================
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
174 void AudioDeviceWindowsWave::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer)
177 CriticalSectionScoped lock(&_critSect);
179 _ptrAudioBuffer = audioBuffer;
181 // inform the AudioBuffer about default settings for this implementation
182 _ptrAudioBuffer->SetRecordingSampleRate(N_REC_SAMPLES_PER_SEC);
183 _ptrAudioBuffer->SetPlayoutSampleRate(N_PLAY_SAMPLES_PER_SEC);
184 _ptrAudioBuffer->SetRecordingChannels(N_REC_CHANNELS);
185 _ptrAudioBuffer->SetPlayoutChannels(N_PLAY_CHANNELS);
188 // ----------------------------------------------------------------------------
190 // ----------------------------------------------------------------------------
192 int32_t AudioDeviceWindowsWave::ActiveAudioLayer(AudioDeviceModule::AudioLayer& audioLayer) const
194 audioLayer = AudioDeviceModule::kWindowsWaveAudio;
198 // ----------------------------------------------------------------------------
200 // ----------------------------------------------------------------------------
202 int32_t AudioDeviceWindowsWave::Init()
205 CriticalSectionScoped lock(&_critSect);
212 const uint32_t nowTime(AudioDeviceUtility::GetTimeInMS());
215 _prevRecByteCheckTime = nowTime;
216 _prevRecTime = nowTime;
217 _prevPlayTime = nowTime;
218 _prevTimerCheckTime = nowTime;
225 _mixerManager.EnumerateAll();
229 // thread is already created and active
233 const char* threadName = "webrtc_audio_module_thread";
234 _ptrThread = ThreadWrapper::CreateThread(ThreadFunc,
238 if (_ptrThread == NULL)
240 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
241 "failed to create the audio thread");
245 unsigned int threadID(0);
246 if (!_ptrThread->Start(threadID))
248 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
249 "failed to start the audio thread");
254 _threadID = threadID;
256 const bool periodic(true);
257 if (!_timeEvent.StartTimer(periodic, TIMER_PERIOD_MS))
259 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
260 "failed to start the timer event");
261 if (_ptrThread->Stop())
268 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
269 "unable to stop the activated thread");
273 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
274 "periodic timer (dT=%d) is now active", TIMER_PERIOD_MS);
276 _hGetCaptureVolumeThread = CreateThread(NULL,
278 GetCaptureVolumeThread,
282 if (_hGetCaptureVolumeThread == NULL)
284 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
285 " failed to create the volume getter thread");
289 SetThreadPriority(_hGetCaptureVolumeThread, THREAD_PRIORITY_NORMAL);
291 _hSetCaptureVolumeThread = CreateThread(NULL,
293 SetCaptureVolumeThread,
297 if (_hSetCaptureVolumeThread == NULL)
299 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
300 " failed to create the volume setter thread");
304 SetThreadPriority(_hSetCaptureVolumeThread, THREAD_PRIORITY_NORMAL);
311 // ----------------------------------------------------------------------------
313 // ----------------------------------------------------------------------------
315 int32_t AudioDeviceWindowsWave::Terminate()
325 _mixerManager.Close();
329 ThreadWrapper* tmpThread = _ptrThread;
333 tmpThread->SetNotAlive();
336 if (tmpThread->Stop())
343 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
344 "failed to close down the audio thread");
354 SetEvent(_hShutdownGetVolumeEvent);
356 int32_t ret = WaitForSingleObject(_hGetCaptureVolumeThread, 2000);
357 if (ret != WAIT_OBJECT_0)
359 // the thread did not stop as it should
360 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
361 " failed to close down volume getter thread");
362 CloseHandle(_hGetCaptureVolumeThread);
363 _hGetCaptureVolumeThread = NULL;
367 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
368 " volume getter thread is now closed");
370 SetEvent(_hShutdownSetVolumeEvent);
372 ret = WaitForSingleObject(_hSetCaptureVolumeThread, 2000);
373 if (ret != WAIT_OBJECT_0)
375 // the thread did not stop as it should
376 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
377 " failed to close down volume setter thread");
378 CloseHandle(_hSetCaptureVolumeThread);
379 _hSetCaptureVolumeThread = NULL;
383 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
384 " volume setter thread is now closed");
386 CloseHandle(_hGetCaptureVolumeThread);
387 _hGetCaptureVolumeThread = NULL;
389 CloseHandle(_hSetCaptureVolumeThread);
390 _hSetCaptureVolumeThread = NULL;
394 _timeEvent.StopTimer();
396 _initialized = false;
397 _outputDeviceIsSpecified = false;
398 _inputDeviceIsSpecified = false;
404 DWORD WINAPI AudioDeviceWindowsWave::GetCaptureVolumeThread(LPVOID context)
406 return(((AudioDeviceWindowsWave*)context)->DoGetCaptureVolumeThread());
409 DWORD WINAPI AudioDeviceWindowsWave::SetCaptureVolumeThread(LPVOID context)
411 return(((AudioDeviceWindowsWave*)context)->DoSetCaptureVolumeThread());
414 DWORD AudioDeviceWindowsWave::DoGetCaptureVolumeThread()
416 HANDLE waitObject = _hShutdownGetVolumeEvent;
420 DWORD waitResult = WaitForSingleObject(waitObject,
421 GET_MIC_VOLUME_INTERVAL_MS);
424 case WAIT_OBJECT_0: // _hShutdownGetVolumeEvent
426 case WAIT_TIMEOUT: // timeout notification
428 default: // unexpected error
429 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
430 " unknown wait termination on get volume thread");
436 uint32_t currentMicLevel = 0;
437 if (MicrophoneVolume(currentMicLevel) == 0)
439 // This doesn't set the system volume, just stores it.
443 _ptrAudioBuffer->SetCurrentMicLevel(currentMicLevel);
451 DWORD AudioDeviceWindowsWave::DoSetCaptureVolumeThread()
453 HANDLE waitArray[2] = {_hShutdownSetVolumeEvent, _hSetCaptureVolumeEvent};
457 DWORD waitResult = WaitForMultipleObjects(2, waitArray, FALSE, INFINITE);
460 case WAIT_OBJECT_0: // _hShutdownSetVolumeEvent
462 case WAIT_OBJECT_0 + 1: // _hSetCaptureVolumeEvent
464 default: // unexpected error
465 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
466 " unknown wait termination on set volume thread");
471 uint32_t newMicLevel = _newMicLevel;
474 if (SetMicrophoneVolume(newMicLevel) == -1)
476 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
477 " the required modification of the microphone volume failed");
483 // ----------------------------------------------------------------------------
485 // ----------------------------------------------------------------------------
487 bool AudioDeviceWindowsWave::Initialized() const
489 return (_initialized);
492 // ----------------------------------------------------------------------------
494 // ----------------------------------------------------------------------------
496 int32_t AudioDeviceWindowsWave::InitSpeaker()
499 CriticalSectionScoped lock(&_critSect);
506 if (_mixerManager.EnumerateSpeakers() == -1)
508 // failed to locate any valid/controllable speaker
512 if (IsUsingOutputDeviceIndex())
514 if (_mixerManager.OpenSpeaker(OutputDeviceIndex()) == -1)
521 if (_mixerManager.OpenSpeaker(OutputDevice()) == -1)
530 // ----------------------------------------------------------------------------
532 // ----------------------------------------------------------------------------
534 int32_t AudioDeviceWindowsWave::InitMicrophone()
537 CriticalSectionScoped lock(&_critSect);
544 if (_mixerManager.EnumerateMicrophones() == -1)
546 // failed to locate any valid/controllable microphone
550 if (IsUsingInputDeviceIndex())
552 if (_mixerManager.OpenMicrophone(InputDeviceIndex()) == -1)
559 if (_mixerManager.OpenMicrophone(InputDevice()) == -1)
566 if (_mixerManager.MaxMicrophoneVolume(maxVol) == -1)
568 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
569 " unable to retrieve max microphone volume");
571 _maxMicVolume = maxVol;
574 if (_mixerManager.MinMicrophoneVolume(minVol) == -1)
576 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
577 " unable to retrieve min microphone volume");
579 _minMicVolume = minVol;
584 // ----------------------------------------------------------------------------
585 // SpeakerIsInitialized
586 // ----------------------------------------------------------------------------
588 bool AudioDeviceWindowsWave::SpeakerIsInitialized() const
590 return (_mixerManager.SpeakerIsInitialized());
593 // ----------------------------------------------------------------------------
594 // MicrophoneIsInitialized
595 // ----------------------------------------------------------------------------
597 bool AudioDeviceWindowsWave::MicrophoneIsInitialized() const
599 return (_mixerManager.MicrophoneIsInitialized());
602 // ----------------------------------------------------------------------------
603 // SpeakerVolumeIsAvailable
604 // ----------------------------------------------------------------------------
606 int32_t AudioDeviceWindowsWave::SpeakerVolumeIsAvailable(bool& available)
609 bool isAvailable(false);
611 // Enumerate all avaliable speakers and make an attempt to open up the
612 // output mixer corresponding to the currently selected output device.
614 if (InitSpeaker() == -1)
616 // failed to find a valid speaker
621 // Check if the selected speaker has a volume control
623 _mixerManager.SpeakerVolumeIsAvailable(isAvailable);
624 available = isAvailable;
626 // Close the initialized output mixer
628 _mixerManager.CloseSpeaker();
633 // ----------------------------------------------------------------------------
635 // ----------------------------------------------------------------------------
637 int32_t AudioDeviceWindowsWave::SetSpeakerVolume(uint32_t volume)
640 return (_mixerManager.SetSpeakerVolume(volume));
643 // ----------------------------------------------------------------------------
645 // ----------------------------------------------------------------------------
647 int32_t AudioDeviceWindowsWave::SpeakerVolume(uint32_t& volume) const
652 if (_mixerManager.SpeakerVolume(level) == -1)
661 // ----------------------------------------------------------------------------
664 // The low-order word contains the left-channel volume setting, and the
665 // high-order word contains the right-channel setting.
666 // A value of 0xFFFF represents full volume, and a value of 0x0000 is silence.
668 // If a device does not support both left and right volume control,
669 // the low-order word of dwVolume specifies the volume level,
670 // and the high-order word is ignored.
672 // Most devices do not support the full 16 bits of volume-level control
673 // and will not use the least-significant bits of the requested volume setting.
674 // For example, if a device supports 4 bits of volume control, the values
675 // 0x4000, 0x4FFF, and 0x43BE will all be truncated to 0x4000.
676 // ----------------------------------------------------------------------------
678 int32_t AudioDeviceWindowsWave::SetWaveOutVolume(uint16_t volumeLeft, uint16_t volumeRight)
684 CriticalSectionScoped lock(&_critSect);
686 if (_hWaveOut == NULL)
688 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "no open playout device exists => using default");
691 // To determine whether the device supports volume control on both
692 // the left and right channels, use the WAVECAPS_LRVOLUME flag.
694 res = waveOutGetDevCaps((UINT_PTR)_hWaveOut, &caps, sizeof(WAVEOUTCAPS));
695 if (MMSYSERR_NOERROR != res)
697 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutGetDevCaps() failed (err=%d)", res);
698 TraceWaveOutError(res);
700 if (!(caps.dwSupport & WAVECAPS_VOLUME))
702 // this device does not support volume control using the waveOutSetVolume API
703 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "device does not support volume control using the Wave API");
706 if (!(caps.dwSupport & WAVECAPS_LRVOLUME))
708 // high-order word (right channel) is ignored
709 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "device does not support volume control on both channels");
712 DWORD dwVolume(0x00000000);
713 dwVolume = (DWORD)(((volumeRight & 0xFFFF) << 16) | (volumeLeft & 0xFFFF));
715 res = waveOutSetVolume(_hWaveOut, dwVolume);
716 if (MMSYSERR_NOERROR != res)
718 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "waveOutSetVolume() failed (err=%d)", res);
719 TraceWaveOutError(res);
726 // ----------------------------------------------------------------------------
729 // The low-order word of this location contains the left-channel volume setting,
730 // and the high-order word contains the right-channel setting.
731 // A value of 0xFFFF (65535) represents full volume, and a value of 0x0000
734 // If a device does not support both left and right volume control,
735 // the low-order word of the specified location contains the mono volume level.
737 // The full 16-bit setting(s) set with the waveOutSetVolume function is returned,
738 // regardless of whether the device supports the full 16 bits of volume-level
740 // ----------------------------------------------------------------------------
742 int32_t AudioDeviceWindowsWave::WaveOutVolume(uint16_t& volumeLeft, uint16_t& volumeRight) const
748 CriticalSectionScoped lock(&_critSect);
750 if (_hWaveOut == NULL)
752 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "no open playout device exists => using default");
755 // To determine whether the device supports volume control on both
756 // the left and right channels, use the WAVECAPS_LRVOLUME flag.
758 res = waveOutGetDevCaps((UINT_PTR)_hWaveOut, &caps, sizeof(WAVEOUTCAPS));
759 if (MMSYSERR_NOERROR != res)
761 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutGetDevCaps() failed (err=%d)", res);
762 TraceWaveOutError(res);
764 if (!(caps.dwSupport & WAVECAPS_VOLUME))
766 // this device does not support volume control using the waveOutSetVolume API
767 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "device does not support volume control using the Wave API");
770 if (!(caps.dwSupport & WAVECAPS_LRVOLUME))
772 // high-order word (right channel) is ignored
773 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "device does not support volume control on both channels");
776 DWORD dwVolume(0x00000000);
778 res = waveOutGetVolume(_hWaveOut, &dwVolume);
779 if (MMSYSERR_NOERROR != res)
781 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "waveOutGetVolume() failed (err=%d)", res);
782 TraceWaveOutError(res);
786 WORD wVolumeLeft = LOWORD(dwVolume);
787 WORD wVolumeRight = HIWORD(dwVolume);
789 volumeLeft = static_cast<uint16_t> (wVolumeLeft);
790 volumeRight = static_cast<uint16_t> (wVolumeRight);
795 // ----------------------------------------------------------------------------
797 // ----------------------------------------------------------------------------
799 int32_t AudioDeviceWindowsWave::MaxSpeakerVolume(uint32_t& maxVolume) const
804 if (_mixerManager.MaxSpeakerVolume(maxVol) == -1)
813 // ----------------------------------------------------------------------------
815 // ----------------------------------------------------------------------------
817 int32_t AudioDeviceWindowsWave::MinSpeakerVolume(uint32_t& minVolume) const
822 if (_mixerManager.MinSpeakerVolume(minVol) == -1)
831 // ----------------------------------------------------------------------------
832 // SpeakerVolumeStepSize
833 // ----------------------------------------------------------------------------
835 int32_t AudioDeviceWindowsWave::SpeakerVolumeStepSize(uint16_t& stepSize) const
840 if (_mixerManager.SpeakerVolumeStepSize(delta) == -1)
849 // ----------------------------------------------------------------------------
850 // SpeakerMuteIsAvailable
851 // ----------------------------------------------------------------------------
853 int32_t AudioDeviceWindowsWave::SpeakerMuteIsAvailable(bool& available)
856 bool isAvailable(false);
858 // Enumerate all avaliable speakers and make an attempt to open up the
859 // output mixer corresponding to the currently selected output device.
861 if (InitSpeaker() == -1)
863 // If we end up here it means that the selected speaker has no volume
864 // control, hence it is safe to state that there is no mute control
865 // already at this stage.
870 // Check if the selected speaker has a mute control
872 _mixerManager.SpeakerMuteIsAvailable(isAvailable);
873 available = isAvailable;
875 // Close the initialized output mixer
877 _mixerManager.CloseSpeaker();
882 // ----------------------------------------------------------------------------
884 // ----------------------------------------------------------------------------
886 int32_t AudioDeviceWindowsWave::SetSpeakerMute(bool enable)
888 return (_mixerManager.SetSpeakerMute(enable));
891 // ----------------------------------------------------------------------------
893 // ----------------------------------------------------------------------------
895 int32_t AudioDeviceWindowsWave::SpeakerMute(bool& enabled) const
900 if (_mixerManager.SpeakerMute(muted) == -1)
909 // ----------------------------------------------------------------------------
910 // MicrophoneMuteIsAvailable
911 // ----------------------------------------------------------------------------
913 int32_t AudioDeviceWindowsWave::MicrophoneMuteIsAvailable(bool& available)
916 bool isAvailable(false);
918 // Enumerate all avaliable microphones and make an attempt to open up the
919 // input mixer corresponding to the currently selected input device.
921 if (InitMicrophone() == -1)
923 // If we end up here it means that the selected microphone has no volume
924 // control, hence it is safe to state that there is no boost control
925 // already at this stage.
930 // Check if the selected microphone has a mute control
932 _mixerManager.MicrophoneMuteIsAvailable(isAvailable);
933 available = isAvailable;
935 // Close the initialized input mixer
937 _mixerManager.CloseMicrophone();
942 // ----------------------------------------------------------------------------
944 // ----------------------------------------------------------------------------
946 int32_t AudioDeviceWindowsWave::SetMicrophoneMute(bool enable)
948 return (_mixerManager.SetMicrophoneMute(enable));
951 // ----------------------------------------------------------------------------
953 // ----------------------------------------------------------------------------
955 int32_t AudioDeviceWindowsWave::MicrophoneMute(bool& enabled) const
960 if (_mixerManager.MicrophoneMute(muted) == -1)
969 // ----------------------------------------------------------------------------
970 // MicrophoneBoostIsAvailable
971 // ----------------------------------------------------------------------------
973 int32_t AudioDeviceWindowsWave::MicrophoneBoostIsAvailable(bool& available)
976 bool isAvailable(false);
978 // Enumerate all avaliable microphones and make an attempt to open up the
979 // input mixer corresponding to the currently selected input device.
981 if (InitMicrophone() == -1)
983 // If we end up here it means that the selected microphone has no volume
984 // control, hence it is safe to state that there is no boost control
985 // already at this stage.
990 // Check if the selected microphone has a boost control
992 _mixerManager.MicrophoneBoostIsAvailable(isAvailable);
993 available = isAvailable;
995 // Close the initialized input mixer
997 _mixerManager.CloseMicrophone();
1002 // ----------------------------------------------------------------------------
1003 // SetMicrophoneBoost
1004 // ----------------------------------------------------------------------------
1006 int32_t AudioDeviceWindowsWave::SetMicrophoneBoost(bool enable)
1009 return (_mixerManager.SetMicrophoneBoost(enable));
1012 // ----------------------------------------------------------------------------
1014 // ----------------------------------------------------------------------------
1016 int32_t AudioDeviceWindowsWave::MicrophoneBoost(bool& enabled) const
1021 if (_mixerManager.MicrophoneBoost(onOff) == -1)
1030 // ----------------------------------------------------------------------------
1031 // StereoRecordingIsAvailable
1032 // ----------------------------------------------------------------------------
1034 int32_t AudioDeviceWindowsWave::StereoRecordingIsAvailable(bool& available)
1040 // ----------------------------------------------------------------------------
1041 // SetStereoRecording
1042 // ----------------------------------------------------------------------------
1044 int32_t AudioDeviceWindowsWave::SetStereoRecording(bool enable)
1055 // ----------------------------------------------------------------------------
1057 // ----------------------------------------------------------------------------
1059 int32_t AudioDeviceWindowsWave::StereoRecording(bool& enabled) const
1062 if (_recChannels == 2)
1070 // ----------------------------------------------------------------------------
1071 // StereoPlayoutIsAvailable
1072 // ----------------------------------------------------------------------------
1074 int32_t AudioDeviceWindowsWave::StereoPlayoutIsAvailable(bool& available)
1080 // ----------------------------------------------------------------------------
1083 // Specifies the number of output channels.
1085 // NOTE - the setting will only have an effect after InitPlayout has
1090 // Each sample is 2 bytes. Sample 1 is followed by samples 2, 3, 4, and so on.
1091 // For each sample, the first byte is the low-order byte of channel 0 and the
1092 // second byte is the high-order byte of channel 0.
1096 // Each sample is 4 bytes. Sample 1 is followed by samples 2, 3, 4, and so on.
1097 // For each sample, the first byte is the low-order byte of channel 0 (left channel);
1098 // the second byte is the high-order byte of channel 0; the third byte is the
1099 // low-order byte of channel 1 (right channel); and the fourth byte is the
1100 // high-order byte of channel 1.
1101 // ----------------------------------------------------------------------------
1103 int32_t AudioDeviceWindowsWave::SetStereoPlayout(bool enable)
1114 // ----------------------------------------------------------------------------
1116 // ----------------------------------------------------------------------------
1118 int32_t AudioDeviceWindowsWave::StereoPlayout(bool& enabled) const
1121 if (_playChannels == 2)
1129 // ----------------------------------------------------------------------------
1131 // ----------------------------------------------------------------------------
1133 int32_t AudioDeviceWindowsWave::SetAGC(bool enable)
1141 // ----------------------------------------------------------------------------
1143 // ----------------------------------------------------------------------------
1145 bool AudioDeviceWindowsWave::AGC() const
1150 // ----------------------------------------------------------------------------
1151 // MicrophoneVolumeIsAvailable
1152 // ----------------------------------------------------------------------------
1154 int32_t AudioDeviceWindowsWave::MicrophoneVolumeIsAvailable(bool& available)
1157 bool isAvailable(false);
1159 // Enumerate all avaliable microphones and make an attempt to open up the
1160 // input mixer corresponding to the currently selected output device.
1162 if (InitMicrophone() == -1)
1164 // Failed to find valid microphone
1169 // Check if the selected microphone has a volume control
1171 _mixerManager.MicrophoneVolumeIsAvailable(isAvailable);
1172 available = isAvailable;
1174 // Close the initialized input mixer
1176 _mixerManager.CloseMicrophone();
1181 // ----------------------------------------------------------------------------
1182 // SetMicrophoneVolume
1183 // ----------------------------------------------------------------------------
1185 int32_t AudioDeviceWindowsWave::SetMicrophoneVolume(uint32_t volume)
1187 return (_mixerManager.SetMicrophoneVolume(volume));
1190 // ----------------------------------------------------------------------------
1192 // ----------------------------------------------------------------------------
1194 int32_t AudioDeviceWindowsWave::MicrophoneVolume(uint32_t& volume) const
1198 if (_mixerManager.MicrophoneVolume(level) == -1)
1200 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "failed to retrive current microphone level");
1208 // ----------------------------------------------------------------------------
1209 // MaxMicrophoneVolume
1210 // ----------------------------------------------------------------------------
1212 int32_t AudioDeviceWindowsWave::MaxMicrophoneVolume(uint32_t& maxVolume) const
1214 // _maxMicVolume can be zero in AudioMixerManager::MaxMicrophoneVolume():
1215 // (1) API GetLineControl() returns failure at querying the max Mic level.
1216 // (2) API GetLineControl() returns maxVolume as zero in rare cases.
1217 // Both cases show we don't have access to the mixer controls.
1218 // We return -1 here to indicate that.
1219 if (_maxMicVolume == 0)
1224 maxVolume = _maxMicVolume;;
1228 // ----------------------------------------------------------------------------
1229 // MinMicrophoneVolume
1230 // ----------------------------------------------------------------------------
1232 int32_t AudioDeviceWindowsWave::MinMicrophoneVolume(uint32_t& minVolume) const
1234 minVolume = _minMicVolume;
1238 // ----------------------------------------------------------------------------
1239 // MicrophoneVolumeStepSize
1240 // ----------------------------------------------------------------------------
1242 int32_t AudioDeviceWindowsWave::MicrophoneVolumeStepSize(uint16_t& stepSize) const
1247 if (_mixerManager.MicrophoneVolumeStepSize(delta) == -1)
1256 // ----------------------------------------------------------------------------
1258 // ----------------------------------------------------------------------------
1260 int16_t AudioDeviceWindowsWave::PlayoutDevices()
1263 return (waveOutGetNumDevs());
1266 // ----------------------------------------------------------------------------
1267 // SetPlayoutDevice I (II)
1268 // ----------------------------------------------------------------------------
1270 int32_t AudioDeviceWindowsWave::SetPlayoutDevice(uint16_t index)
1273 if (_playIsInitialized)
1278 UINT nDevices = waveOutGetNumDevs();
1279 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "number of availiable waveform-audio output devices is %u", nDevices);
1281 if (index < 0 || index > (nDevices-1))
1283 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "device index is out of range [0,%u]", (nDevices-1));
1287 _usingOutputDeviceIndex = true;
1288 _outputDeviceIndex = index;
1289 _outputDeviceIsSpecified = true;
1294 // ----------------------------------------------------------------------------
1295 // SetPlayoutDevice II (II)
1296 // ----------------------------------------------------------------------------
1298 int32_t AudioDeviceWindowsWave::SetPlayoutDevice(AudioDeviceModule::WindowsDeviceType device)
1300 if (_playIsInitialized)
1305 if (device == AudioDeviceModule::kDefaultDevice)
1308 else if (device == AudioDeviceModule::kDefaultCommunicationDevice)
1312 _usingOutputDeviceIndex = false;
1313 _outputDevice = device;
1314 _outputDeviceIsSpecified = true;
1319 // ----------------------------------------------------------------------------
1320 // PlayoutDeviceName
1321 // ----------------------------------------------------------------------------
1323 int32_t AudioDeviceWindowsWave::PlayoutDeviceName(
1325 char name[kAdmMaxDeviceNameSize],
1326 char guid[kAdmMaxGuidSize])
1329 uint16_t nDevices(PlayoutDevices());
1331 // Special fix for the case when the user asks for the name of the default device.
1333 if (index == (uint16_t)(-1))
1338 if ((index > (nDevices-1)) || (name == NULL))
1343 memset(name, 0, kAdmMaxDeviceNameSize);
1347 memset(guid, 0, kAdmMaxGuidSize);
1350 WAVEOUTCAPSW caps; // szPname member (product name (NULL terminated) is a WCHAR
1353 res = waveOutGetDevCapsW(index, &caps, sizeof(WAVEOUTCAPSW));
1354 if (res != MMSYSERR_NOERROR)
1356 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutGetDevCapsW() failed (err=%d)", res);
1359 if (WideCharToMultiByte(CP_UTF8, 0, caps.szPname, -1, name, kAdmMaxDeviceNameSize, NULL, NULL) == 0)
1361 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d - 1", GetLastError());
1369 // It is possible to get the unique endpoint ID string using the Wave API.
1370 // However, it is only supported on Windows Vista and Windows 7.
1372 size_t cbEndpointId(0);
1374 // Get the size (including the terminating null) of the endpoint ID string of the waveOut device.
1375 // Windows Vista supports the DRV_QUERYFUNCTIONINSTANCEIDSIZE and DRV_QUERYFUNCTIONINSTANCEID messages.
1376 res = waveOutMessage((HWAVEOUT)IntToPtr(index),
1377 DRV_QUERYFUNCTIONINSTANCEIDSIZE,
1378 (DWORD_PTR)&cbEndpointId, NULL);
1379 if (res != MMSYSERR_NOERROR)
1381 // DRV_QUERYFUNCTIONINSTANCEIDSIZE is not supported <=> earlier version of Windows than Vista
1382 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "waveOutMessage(DRV_QUERYFUNCTIONINSTANCEIDSIZE) failed (err=%d)", res);
1383 TraceWaveOutError(res);
1384 // Best we can do is to copy the friendly name and use it as guid
1385 if (WideCharToMultiByte(CP_UTF8, 0, caps.szPname, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1387 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d - 2", GetLastError());
1392 // waveOutMessage(DRV_QUERYFUNCTIONINSTANCEIDSIZE) worked => we are on a Vista or Windows 7 device
1394 WCHAR *pstrEndpointId = NULL;
1395 pstrEndpointId = (WCHAR*)CoTaskMemAlloc(cbEndpointId);
1397 // Get the endpoint ID string for this waveOut device.
1398 res = waveOutMessage((HWAVEOUT)IntToPtr(index),
1399 DRV_QUERYFUNCTIONINSTANCEID,
1400 (DWORD_PTR)pstrEndpointId,
1402 if (res != MMSYSERR_NOERROR)
1404 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "waveOutMessage(DRV_QUERYFUNCTIONINSTANCEID) failed (err=%d)", res);
1405 TraceWaveOutError(res);
1406 // Best we can do is to copy the friendly name and use it as guid
1407 if (WideCharToMultiByte(CP_UTF8, 0, caps.szPname, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1409 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d - 3", GetLastError());
1411 CoTaskMemFree(pstrEndpointId);
1415 if (WideCharToMultiByte(CP_UTF8, 0, pstrEndpointId, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1417 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d - 4", GetLastError());
1419 CoTaskMemFree(pstrEndpointId);
1424 // ----------------------------------------------------------------------------
1425 // RecordingDeviceName
1426 // ----------------------------------------------------------------------------
1428 int32_t AudioDeviceWindowsWave::RecordingDeviceName(
1430 char name[kAdmMaxDeviceNameSize],
1431 char guid[kAdmMaxGuidSize])
1434 uint16_t nDevices(RecordingDevices());
1436 // Special fix for the case when the user asks for the name of the default device.
1438 if (index == (uint16_t)(-1))
1443 if ((index > (nDevices-1)) || (name == NULL))
1448 memset(name, 0, kAdmMaxDeviceNameSize);
1452 memset(guid, 0, kAdmMaxGuidSize);
1455 WAVEINCAPSW caps; // szPname member (product name (NULL terminated) is a WCHAR
1458 res = waveInGetDevCapsW(index, &caps, sizeof(WAVEINCAPSW));
1459 if (res != MMSYSERR_NOERROR)
1461 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInGetDevCapsW() failed (err=%d)", res);
1464 if (WideCharToMultiByte(CP_UTF8, 0, caps.szPname, -1, name, kAdmMaxDeviceNameSize, NULL, NULL) == 0)
1466 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d - 1", GetLastError());
1474 // It is possible to get the unique endpoint ID string using the Wave API.
1475 // However, it is only supported on Windows Vista and Windows 7.
1477 size_t cbEndpointId(0);
1479 // Get the size (including the terminating null) of the endpoint ID string of the waveOut device.
1480 // Windows Vista supports the DRV_QUERYFUNCTIONINSTANCEIDSIZE and DRV_QUERYFUNCTIONINSTANCEID messages.
1481 res = waveInMessage((HWAVEIN)IntToPtr(index),
1482 DRV_QUERYFUNCTIONINSTANCEIDSIZE,
1483 (DWORD_PTR)&cbEndpointId, NULL);
1484 if (res != MMSYSERR_NOERROR)
1486 // DRV_QUERYFUNCTIONINSTANCEIDSIZE is not supported <=> earlier version of Windows than Vista
1487 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "waveInMessage(DRV_QUERYFUNCTIONINSTANCEIDSIZE) failed (err=%d)", res);
1488 TraceWaveInError(res);
1489 // Best we can do is to copy the friendly name and use it as guid
1490 if (WideCharToMultiByte(CP_UTF8, 0, caps.szPname, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1492 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d - 2", GetLastError());
1497 // waveOutMessage(DRV_QUERYFUNCTIONINSTANCEIDSIZE) worked => we are on a Vista or Windows 7 device
1499 WCHAR *pstrEndpointId = NULL;
1500 pstrEndpointId = (WCHAR*)CoTaskMemAlloc(cbEndpointId);
1502 // Get the endpoint ID string for this waveOut device.
1503 res = waveInMessage((HWAVEIN)IntToPtr(index),
1504 DRV_QUERYFUNCTIONINSTANCEID,
1505 (DWORD_PTR)pstrEndpointId,
1507 if (res != MMSYSERR_NOERROR)
1509 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "waveInMessage(DRV_QUERYFUNCTIONINSTANCEID) failed (err=%d)", res);
1510 TraceWaveInError(res);
1511 // Best we can do is to copy the friendly name and use it as guid
1512 if (WideCharToMultiByte(CP_UTF8, 0, caps.szPname, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1514 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d - 3", GetLastError());
1516 CoTaskMemFree(pstrEndpointId);
1520 if (WideCharToMultiByte(CP_UTF8, 0, pstrEndpointId, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1522 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d - 4", GetLastError());
1524 CoTaskMemFree(pstrEndpointId);
1529 // ----------------------------------------------------------------------------
1531 // ----------------------------------------------------------------------------
1533 int16_t AudioDeviceWindowsWave::RecordingDevices()
1536 return (waveInGetNumDevs());
1539 // ----------------------------------------------------------------------------
1540 // SetRecordingDevice I (II)
1541 // ----------------------------------------------------------------------------
1543 int32_t AudioDeviceWindowsWave::SetRecordingDevice(uint16_t index)
1546 if (_recIsInitialized)
1551 UINT nDevices = waveInGetNumDevs();
1552 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "number of availiable waveform-audio input devices is %u", nDevices);
1554 if (index < 0 || index > (nDevices-1))
1556 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "device index is out of range [0,%u]", (nDevices-1));
1560 _usingInputDeviceIndex = true;
1561 _inputDeviceIndex = index;
1562 _inputDeviceIsSpecified = true;
1567 // ----------------------------------------------------------------------------
1568 // SetRecordingDevice II (II)
1569 // ----------------------------------------------------------------------------
1571 int32_t AudioDeviceWindowsWave::SetRecordingDevice(AudioDeviceModule::WindowsDeviceType device)
1573 if (device == AudioDeviceModule::kDefaultDevice)
1576 else if (device == AudioDeviceModule::kDefaultCommunicationDevice)
1580 if (_recIsInitialized)
1585 _usingInputDeviceIndex = false;
1586 _inputDevice = device;
1587 _inputDeviceIsSpecified = true;
1592 // ----------------------------------------------------------------------------
1593 // PlayoutIsAvailable
1594 // ----------------------------------------------------------------------------
1596 int32_t AudioDeviceWindowsWave::PlayoutIsAvailable(bool& available)
1601 // Try to initialize the playout side
1602 int32_t res = InitPlayout();
1604 // Cancel effect of initialization
1615 // ----------------------------------------------------------------------------
1616 // RecordingIsAvailable
1617 // ----------------------------------------------------------------------------
1619 int32_t AudioDeviceWindowsWave::RecordingIsAvailable(bool& available)
1624 // Try to initialize the recording side
1625 int32_t res = InitRecording();
1627 // Cancel effect of initialization
1638 // ----------------------------------------------------------------------------
1640 // ----------------------------------------------------------------------------
1642 int32_t AudioDeviceWindowsWave::InitPlayout()
1645 CriticalSectionScoped lock(&_critSect);
1652 if (!_outputDeviceIsSpecified)
1657 if (_playIsInitialized)
1662 // Initialize the speaker (devices might have been added or removed)
1663 if (InitSpeaker() == -1)
1665 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "InitSpeaker() failed");
1668 // Enumerate all availiable output devices
1669 EnumeratePlayoutDevices();
1671 // Start by closing any existing wave-output devices
1673 MMRESULT res(MMSYSERR_ERROR);
1675 if (_hWaveOut != NULL)
1677 res = waveOutClose(_hWaveOut);
1678 if (MMSYSERR_NOERROR != res)
1680 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutClose() failed (err=%d)", res);
1681 TraceWaveOutError(res);
1685 // Set the output wave format
1687 WAVEFORMATEX waveFormat;
1689 waveFormat.wFormatTag = WAVE_FORMAT_PCM;
1690 waveFormat.nChannels = _playChannels; // mono <=> 1, stereo <=> 2
1691 waveFormat.nSamplesPerSec = N_PLAY_SAMPLES_PER_SEC;
1692 waveFormat.wBitsPerSample = 16;
1693 waveFormat.nBlockAlign = waveFormat.nChannels * (waveFormat.wBitsPerSample/8);
1694 waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
1695 waveFormat.cbSize = 0;
1697 // Open the given waveform-audio output device for playout
1699 HWAVEOUT hWaveOut(NULL);
1701 if (IsUsingOutputDeviceIndex())
1703 // verify settings first
1704 res = waveOutOpen(NULL, _outputDeviceIndex, &waveFormat, 0, 0, CALLBACK_NULL | WAVE_FORMAT_QUERY);
1705 if (MMSYSERR_NOERROR == res)
1707 // open the given waveform-audio output device for recording
1708 res = waveOutOpen(&hWaveOut, _outputDeviceIndex, &waveFormat, 0, 0, CALLBACK_NULL);
1709 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "opening output device corresponding to device ID %u", _outputDeviceIndex);
1714 if (_outputDevice == AudioDeviceModule::kDefaultCommunicationDevice)
1716 // check if it is possible to open the default communication device (supported on Windows 7)
1717 res = waveOutOpen(NULL, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL | WAVE_MAPPED_DEFAULT_COMMUNICATION_DEVICE | WAVE_FORMAT_QUERY);
1718 if (MMSYSERR_NOERROR == res)
1720 // if so, open the default communication device for real
1721 res = waveOutOpen(&hWaveOut, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL | WAVE_MAPPED_DEFAULT_COMMUNICATION_DEVICE);
1722 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "opening default communication device");
1726 // use default device since default communication device was not avaliable
1727 res = waveOutOpen(&hWaveOut, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL);
1728 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "unable to open default communication device => using default instead");
1731 else if (_outputDevice == AudioDeviceModule::kDefaultDevice)
1733 // open default device since it has been requested
1734 res = waveOutOpen(NULL, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL | WAVE_FORMAT_QUERY);
1735 if (MMSYSERR_NOERROR == res)
1737 res = waveOutOpen(&hWaveOut, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL);
1738 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "opening default output device");
1743 if (MMSYSERR_NOERROR != res)
1745 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "waveOutOpen() failed (err=%d)", res);
1746 TraceWaveOutError(res);
1750 // Log information about the aquired output device
1754 res = waveOutGetDevCaps((UINT_PTR)hWaveOut, &caps, sizeof(WAVEOUTCAPS));
1755 if (res != MMSYSERR_NOERROR)
1757 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutGetDevCaps() failed (err=%d)", res);
1758 TraceWaveOutError(res);
1762 res = waveOutGetID(hWaveOut, &deviceID);
1763 if (res != MMSYSERR_NOERROR)
1765 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutGetID() failed (err=%d)", res);
1766 TraceWaveOutError(res);
1768 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "utilized device ID : %u", deviceID);
1769 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "product name : %s", caps.szPname);
1771 // Store valid handle for the open waveform-audio output device
1772 _hWaveOut = hWaveOut;
1774 // Store the input wave header as well
1775 _waveFormatOut = waveFormat;
1777 // Prepare wave-out headers
1779 const uint8_t bytesPerSample = 2*_playChannels;
1781 for (int n = 0; n < N_BUFFERS_OUT; n++)
1783 // set up the output wave header
1784 _waveHeaderOut[n].lpData = reinterpret_cast<LPSTR>(&_playBuffer[n]);
1785 _waveHeaderOut[n].dwBufferLength = bytesPerSample*PLAY_BUF_SIZE_IN_SAMPLES;
1786 _waveHeaderOut[n].dwFlags = 0;
1787 _waveHeaderOut[n].dwLoops = 0;
1789 memset(_playBuffer[n], 0, bytesPerSample*PLAY_BUF_SIZE_IN_SAMPLES);
1791 // The waveOutPrepareHeader function prepares a waveform-audio data block for playback.
1792 // The lpData, dwBufferLength, and dwFlags members of the WAVEHDR structure must be set
1793 // before calling this function.
1795 res = waveOutPrepareHeader(_hWaveOut, &_waveHeaderOut[n], sizeof(WAVEHDR));
1796 if (MMSYSERR_NOERROR != res)
1798 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutPrepareHeader(%d) failed (err=%d)", n, res);
1799 TraceWaveOutError(res);
1802 // perform extra check to ensure that the header is prepared
1803 if (_waveHeaderOut[n].dwFlags != WHDR_PREPARED)
1805 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutPrepareHeader(%d) failed (dwFlags != WHDR_PREPARED)", n);
1809 // Mark playout side as initialized
1810 _playIsInitialized = true;
1812 _dTcheckPlayBufDelay = 10; // check playback buffer delay every 10 ms
1813 _playBufCount = 0; // index of active output wave header (<=> output buffer index)
1814 _playBufDelay = 80; // buffer delay/size is initialized to 80 ms and slowly decreased until er < 25
1815 _minPlayBufDelay = 25; // minimum playout buffer delay
1816 _MAX_minBuffer = 65; // adaptive minimum playout buffer delay cannot be larger than this value
1817 _intro = 1; // Used to make sure that adaption starts after (2000-1700)/100 seconds
1818 _waitCounter = 1700; // Counter for start of adaption of playback buffer
1819 _erZeroCounter = 0; // Log how many times er = 0 in consequtive calls to RecTimeProc
1820 _useHeader = 0; // Counts number of "useHeader" detections. Stops at 2.
1822 _writtenSamples = 0;
1823 _writtenSamplesOld = 0;
1824 _playedSamplesOld = 0;
1825 _sndCardPlayDelay = 0;
1826 _sndCardRecDelay = 0;
1828 WEBRTC_TRACE(kTraceInfo, kTraceUtility, _id,"initial playout status: _playBufDelay=%d, _minPlayBufDelay=%d",
1829 _playBufDelay, _minPlayBufDelay);
1834 // ----------------------------------------------------------------------------
1836 // ----------------------------------------------------------------------------
1838 int32_t AudioDeviceWindowsWave::InitRecording()
1841 CriticalSectionScoped lock(&_critSect);
1848 if (!_inputDeviceIsSpecified)
1853 if (_recIsInitialized)
1861 // Initialize the microphone (devices might have been added or removed)
1862 if (InitMicrophone() == -1)
1864 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "InitMicrophone() failed");
1867 // Enumerate all availiable input devices
1868 EnumerateRecordingDevices();
1870 // Start by closing any existing wave-input devices
1872 MMRESULT res(MMSYSERR_ERROR);
1874 if (_hWaveIn != NULL)
1876 res = waveInClose(_hWaveIn);
1877 if (MMSYSERR_NOERROR != res)
1879 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInClose() failed (err=%d)", res);
1880 TraceWaveInError(res);
1884 // Set the input wave format
1886 WAVEFORMATEX waveFormat;
1888 waveFormat.wFormatTag = WAVE_FORMAT_PCM;
1889 waveFormat.nChannels = _recChannels; // mono <=> 1, stereo <=> 2
1890 waveFormat.nSamplesPerSec = N_REC_SAMPLES_PER_SEC;
1891 waveFormat.wBitsPerSample = 16;
1892 waveFormat.nBlockAlign = waveFormat.nChannels * (waveFormat.wBitsPerSample/8);
1893 waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
1894 waveFormat.cbSize = 0;
1896 // Open the given waveform-audio input device for recording
1898 HWAVEIN hWaveIn(NULL);
1900 if (IsUsingInputDeviceIndex())
1902 // verify settings first
1903 res = waveInOpen(NULL, _inputDeviceIndex, &waveFormat, 0, 0, CALLBACK_NULL | WAVE_FORMAT_QUERY);
1904 if (MMSYSERR_NOERROR == res)
1906 // open the given waveform-audio input device for recording
1907 res = waveInOpen(&hWaveIn, _inputDeviceIndex, &waveFormat, 0, 0, CALLBACK_NULL);
1908 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "opening input device corresponding to device ID %u", _inputDeviceIndex);
1913 if (_inputDevice == AudioDeviceModule::kDefaultCommunicationDevice)
1915 // check if it is possible to open the default communication device (supported on Windows 7)
1916 res = waveInOpen(NULL, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL | WAVE_MAPPED_DEFAULT_COMMUNICATION_DEVICE | WAVE_FORMAT_QUERY);
1917 if (MMSYSERR_NOERROR == res)
1919 // if so, open the default communication device for real
1920 res = waveInOpen(&hWaveIn, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL | WAVE_MAPPED_DEFAULT_COMMUNICATION_DEVICE);
1921 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "opening default communication device");
1925 // use default device since default communication device was not avaliable
1926 res = waveInOpen(&hWaveIn, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL);
1927 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "unable to open default communication device => using default instead");
1930 else if (_inputDevice == AudioDeviceModule::kDefaultDevice)
1932 // open default device since it has been requested
1933 res = waveInOpen(NULL, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL | WAVE_FORMAT_QUERY);
1934 if (MMSYSERR_NOERROR == res)
1936 res = waveInOpen(&hWaveIn, WAVE_MAPPER, &waveFormat, 0, 0, CALLBACK_NULL);
1937 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "opening default input device");
1942 if (MMSYSERR_NOERROR != res)
1944 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "waveInOpen() failed (err=%d)", res);
1945 TraceWaveInError(res);
1949 // Log information about the aquired input device
1953 res = waveInGetDevCaps((UINT_PTR)hWaveIn, &caps, sizeof(WAVEINCAPS));
1954 if (res != MMSYSERR_NOERROR)
1956 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInGetDevCaps() failed (err=%d)", res);
1957 TraceWaveInError(res);
1961 res = waveInGetID(hWaveIn, &deviceID);
1962 if (res != MMSYSERR_NOERROR)
1964 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInGetID() failed (err=%d)", res);
1965 TraceWaveInError(res);
1967 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "utilized device ID : %u", deviceID);
1968 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "product name : %s", caps.szPname);
1970 // Store valid handle for the open waveform-audio input device
1973 // Store the input wave header as well
1974 _waveFormatIn = waveFormat;
1976 // Mark recording side as initialized
1977 _recIsInitialized = true;
1979 _recBufCount = 0; // index of active input wave header (<=> input buffer index)
1980 _recDelayCount = 0; // ensures that input buffers are returned with certain delay
1985 // ----------------------------------------------------------------------------
1987 // ----------------------------------------------------------------------------
1989 int32_t AudioDeviceWindowsWave::StartRecording()
1992 if (!_recIsInitialized)
2002 // set state to ensure that the recording starts from the audio thread
2005 // the audio thread will signal when recording has stopped
2006 if (kEventTimeout == _recStartEvent.Wait(10000))
2010 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "failed to activate recording");
2016 // the recording state is set by the audio thread after recording has started
2020 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "failed to activate recording");
2027 // ----------------------------------------------------------------------------
2029 // ----------------------------------------------------------------------------
2031 int32_t AudioDeviceWindowsWave::StopRecording()
2034 CriticalSectionScoped lock(&_critSect);
2036 if (!_recIsInitialized)
2041 if (_hWaveIn == NULL)
2046 bool wasRecording = _recording;
2047 _recIsInitialized = false;
2052 // Stop waveform-adio input. If there are any buffers in the queue, the
2053 // current buffer will be marked as done (the dwBytesRecorded member in
2054 // the header will contain the length of data), but any empty buffers in
2055 // the queue will remain there.
2057 res = waveInStop(_hWaveIn);
2058 if (MMSYSERR_NOERROR != res)
2060 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInStop() failed (err=%d)", res);
2061 TraceWaveInError(res);
2064 // Stop input on the given waveform-audio input device and resets the current
2065 // position to zero. All pending buffers are marked as done and returned to
2068 res = waveInReset(_hWaveIn);
2069 if (MMSYSERR_NOERROR != res)
2071 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInReset() failed (err=%d)", res);
2072 TraceWaveInError(res);
2075 // Clean up the preparation performed by the waveInPrepareHeader function.
2076 // Only unprepare header if recording was ever started (and headers are prepared).
2080 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "waveInUnprepareHeader() will be performed");
2081 for (int n = 0; n < N_BUFFERS_IN; n++)
2083 res = waveInUnprepareHeader(_hWaveIn, &_waveHeaderIn[n], sizeof(WAVEHDR));
2084 if (MMSYSERR_NOERROR != res)
2086 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInUnprepareHeader() failed (err=%d)", res);
2087 TraceWaveInError(res);
2092 // Close the given waveform-audio input device.
2094 res = waveInClose(_hWaveIn);
2095 if (MMSYSERR_NOERROR != res)
2097 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInClose() failed (err=%d)", res);
2098 TraceWaveInError(res);
2101 // Set the wave input handle to NULL
2104 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_hWaveIn is now set to NULL");
2109 // ----------------------------------------------------------------------------
2110 // RecordingIsInitialized
2111 // ----------------------------------------------------------------------------
2113 bool AudioDeviceWindowsWave::RecordingIsInitialized() const
2115 return (_recIsInitialized);
2118 // ----------------------------------------------------------------------------
2120 // ----------------------------------------------------------------------------
2122 bool AudioDeviceWindowsWave::Recording() const
2124 return (_recording);
2127 // ----------------------------------------------------------------------------
2128 // PlayoutIsInitialized
2129 // ----------------------------------------------------------------------------
2131 bool AudioDeviceWindowsWave::PlayoutIsInitialized() const
2133 return (_playIsInitialized);
2136 // ----------------------------------------------------------------------------
2138 // ----------------------------------------------------------------------------
2140 int32_t AudioDeviceWindowsWave::StartPlayout()
2143 if (!_playIsInitialized)
2153 // set state to ensure that playout starts from the audio thread
2156 // the audio thread will signal when recording has started
2157 if (kEventTimeout == _playStartEvent.Wait(10000))
2161 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "failed to activate playout");
2167 // the playing state is set by the audio thread after playout has started
2171 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "failed to activate playing");
2178 // ----------------------------------------------------------------------------
2180 // ----------------------------------------------------------------------------
2182 int32_t AudioDeviceWindowsWave::StopPlayout()
2185 CriticalSectionScoped lock(&_critSect);
2187 if (!_playIsInitialized)
2192 if (_hWaveOut == NULL)
2197 _playIsInitialized = false;
2199 _sndCardPlayDelay = 0;
2200 _sndCardRecDelay = 0;
2204 // The waveOutReset function stops playback on the given waveform-audio
2205 // output device and resets the current position to zero. All pending
2206 // playback buffers are marked as done (WHDR_DONE) and returned to the application.
2207 // After this function returns, the application can send new playback buffers
2208 // to the device by calling waveOutWrite, or close the device by calling waveOutClose.
2210 res = waveOutReset(_hWaveOut);
2211 if (MMSYSERR_NOERROR != res)
2213 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutReset() failed (err=%d)", res);
2214 TraceWaveOutError(res);
2217 // The waveOutUnprepareHeader function cleans up the preparation performed
2218 // by the waveOutPrepareHeader function. This function must be called after
2219 // the device driver is finished with a data block.
2220 // You must call this function before freeing the buffer.
2222 for (int n = 0; n < N_BUFFERS_OUT; n++)
2224 res = waveOutUnprepareHeader(_hWaveOut, &_waveHeaderOut[n], sizeof(WAVEHDR));
2225 if (MMSYSERR_NOERROR != res)
2227 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutUnprepareHeader() failed (err=%d)", res);
2228 TraceWaveOutError(res);
2232 // The waveOutClose function closes the given waveform-audio output device.
2233 // The close operation fails if the device is still playing a waveform-audio
2234 // buffer that was previously sent by calling waveOutWrite. Before calling
2235 // waveOutClose, the application must wait for all buffers to finish playing
2236 // or call the waveOutReset function to terminate playback.
2238 res = waveOutClose(_hWaveOut);
2239 if (MMSYSERR_NOERROR != res)
2241 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutClose() failed (err=%d)", res);
2242 TraceWaveOutError(res);
2246 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_hWaveOut is now set to NULL");
2251 // ----------------------------------------------------------------------------
2253 // ----------------------------------------------------------------------------
2255 int32_t AudioDeviceWindowsWave::PlayoutDelay(uint16_t& delayMS) const
2257 CriticalSectionScoped lock(&_critSect);
2258 delayMS = (uint16_t)_sndCardPlayDelay;
2262 // ----------------------------------------------------------------------------
2264 // ----------------------------------------------------------------------------
2266 int32_t AudioDeviceWindowsWave::RecordingDelay(uint16_t& delayMS) const
2268 CriticalSectionScoped lock(&_critSect);
2269 delayMS = (uint16_t)_sndCardRecDelay;
2273 // ----------------------------------------------------------------------------
2275 // ----------------------------------------------------------------------------
2277 bool AudioDeviceWindowsWave::Playing() const
2281 // ----------------------------------------------------------------------------
2283 // ----------------------------------------------------------------------------
2285 int32_t AudioDeviceWindowsWave::SetPlayoutBuffer(const AudioDeviceModule::BufferType type, uint16_t sizeMS)
2287 CriticalSectionScoped lock(&_critSect);
2288 _playBufType = type;
2289 if (type == AudioDeviceModule::kFixedBufferSize)
2291 _playBufDelayFixed = sizeMS;
2296 // ----------------------------------------------------------------------------
2298 // ----------------------------------------------------------------------------
2300 int32_t AudioDeviceWindowsWave::PlayoutBuffer(AudioDeviceModule::BufferType& type, uint16_t& sizeMS) const
2302 CriticalSectionScoped lock(&_critSect);
2303 type = _playBufType;
2304 if (type == AudioDeviceModule::kFixedBufferSize)
2306 sizeMS = _playBufDelayFixed;
2310 sizeMS = _playBufDelay;
2316 // ----------------------------------------------------------------------------
2318 // ----------------------------------------------------------------------------
2320 int32_t AudioDeviceWindowsWave::CPULoad(uint16_t& load) const
2323 load = static_cast<uint16_t>(100*_avgCPULoad);
2328 // ----------------------------------------------------------------------------
2330 // ----------------------------------------------------------------------------
2332 bool AudioDeviceWindowsWave::PlayoutWarning() const
2334 return ( _playWarning > 0);
2337 // ----------------------------------------------------------------------------
2339 // ----------------------------------------------------------------------------
2341 bool AudioDeviceWindowsWave::PlayoutError() const
2343 return ( _playError > 0);
2346 // ----------------------------------------------------------------------------
2348 // ----------------------------------------------------------------------------
2350 bool AudioDeviceWindowsWave::RecordingWarning() const
2352 return ( _recWarning > 0);
2355 // ----------------------------------------------------------------------------
2357 // ----------------------------------------------------------------------------
2359 bool AudioDeviceWindowsWave::RecordingError() const
2361 return ( _recError > 0);
2364 // ----------------------------------------------------------------------------
2365 // ClearPlayoutWarning
2366 // ----------------------------------------------------------------------------
2368 void AudioDeviceWindowsWave::ClearPlayoutWarning()
2373 // ----------------------------------------------------------------------------
2374 // ClearPlayoutError
2375 // ----------------------------------------------------------------------------
2377 void AudioDeviceWindowsWave::ClearPlayoutError()
2382 // ----------------------------------------------------------------------------
2383 // ClearRecordingWarning
2384 // ----------------------------------------------------------------------------
2386 void AudioDeviceWindowsWave::ClearRecordingWarning()
2391 // ----------------------------------------------------------------------------
2392 // ClearRecordingError
2393 // ----------------------------------------------------------------------------
2395 void AudioDeviceWindowsWave::ClearRecordingError()
2400 // ============================================================================
2402 // ============================================================================
2404 // ----------------------------------------------------------------------------
2405 // InputSanityCheckAfterUnlockedPeriod
2406 // ----------------------------------------------------------------------------
2408 int32_t AudioDeviceWindowsWave::InputSanityCheckAfterUnlockedPeriod() const
2410 if (_hWaveIn == NULL)
2412 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "input state has been modified during unlocked period");
2418 // ----------------------------------------------------------------------------
2419 // OutputSanityCheckAfterUnlockedPeriod
2420 // ----------------------------------------------------------------------------
2422 int32_t AudioDeviceWindowsWave::OutputSanityCheckAfterUnlockedPeriod() const
2424 if (_hWaveOut == NULL)
2426 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "output state has been modified during unlocked period");
2432 // ----------------------------------------------------------------------------
2433 // EnumeratePlayoutDevices
2434 // ----------------------------------------------------------------------------
2436 int32_t AudioDeviceWindowsWave::EnumeratePlayoutDevices()
2439 uint16_t nDevices(PlayoutDevices());
2440 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "===============================================================");
2441 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#output devices: %u", nDevices);
2446 for (UINT deviceID = 0; deviceID < nDevices; deviceID++)
2448 res = waveOutGetDevCaps(deviceID, &caps, sizeof(WAVEOUTCAPS));
2449 if (res != MMSYSERR_NOERROR)
2451 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutGetDevCaps() failed (err=%d)", res);
2454 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "===============================================================");
2455 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Device ID %u:", deviceID);
2456 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "manufacturer ID : %u", caps.wMid);
2457 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "product ID : %u",caps.wPid);
2458 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "version of driver : %u.%u", HIBYTE(caps.vDriverVersion), LOBYTE(caps.vDriverVersion));
2459 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "product name : %s", caps.szPname);
2460 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "dwFormats : 0x%x", caps.dwFormats);
2461 if (caps.dwFormats & WAVE_FORMAT_48S16)
2463 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, " 48kHz,stereo,16bit : SUPPORTED");
2467 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, " 48kHz,stereo,16bit : *NOT* SUPPORTED");
2469 if (caps.dwFormats & WAVE_FORMAT_48M16)
2471 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, " 48kHz,mono,16bit : SUPPORTED");
2475 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, " 48kHz,mono,16bit : *NOT* SUPPORTED");
2477 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wChannels : %u", caps.wChannels);
2478 TraceSupportFlags(caps.dwSupport);
2484 // ----------------------------------------------------------------------------
2485 // EnumerateRecordingDevices
2486 // ----------------------------------------------------------------------------
2488 int32_t AudioDeviceWindowsWave::EnumerateRecordingDevices()
2491 uint16_t nDevices(RecordingDevices());
2492 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "===============================================================");
2493 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#input devices: %u", nDevices);
2498 for (UINT deviceID = 0; deviceID < nDevices; deviceID++)
2500 res = waveInGetDevCaps(deviceID, &caps, sizeof(WAVEINCAPS));
2501 if (res != MMSYSERR_NOERROR)
2503 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInGetDevCaps() failed (err=%d)", res);
2506 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "===============================================================");
2507 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Device ID %u:", deviceID);
2508 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "manufacturer ID : %u", caps.wMid);
2509 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "product ID : %u",caps.wPid);
2510 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "version of driver : %u.%u", HIBYTE(caps.vDriverVersion), LOBYTE(caps.vDriverVersion));
2511 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "product name : %s", caps.szPname);
2512 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "dwFormats : 0x%x", caps.dwFormats);
2513 if (caps.dwFormats & WAVE_FORMAT_48S16)
2515 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, " 48kHz,stereo,16bit : SUPPORTED");
2519 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, " 48kHz,stereo,16bit : *NOT* SUPPORTED");
2521 if (caps.dwFormats & WAVE_FORMAT_48M16)
2523 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, " 48kHz,mono,16bit : SUPPORTED");
2527 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, " 48kHz,mono,16bit : *NOT* SUPPORTED");
2529 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wChannels : %u", caps.wChannels);
2535 // ----------------------------------------------------------------------------
2536 // TraceSupportFlags
2537 // ----------------------------------------------------------------------------
2539 void AudioDeviceWindowsWave::TraceSupportFlags(DWORD dwSupport) const
2543 StringCchPrintf(buf, 128, TEXT("support flags : 0x%x "), dwSupport);
2545 if (dwSupport & WAVECAPS_PITCH)
2547 // supports pitch control
2548 StringCchCat(buf, 256, TEXT("(PITCH)"));
2550 if (dwSupport & WAVECAPS_PLAYBACKRATE)
2552 // supports playback rate control
2553 StringCchCat(buf, 256, TEXT("(PLAYBACKRATE)"));
2555 if (dwSupport & WAVECAPS_VOLUME)
2557 // supports volume control
2558 StringCchCat(buf, 256, TEXT("(VOLUME)"));
2560 if (dwSupport & WAVECAPS_LRVOLUME)
2562 // supports separate left and right volume control
2563 StringCchCat(buf, 256, TEXT("(LRVOLUME)"));
2565 if (dwSupport & WAVECAPS_SYNC)
2567 // the driver is synchronous and will block while playing a buffer
2568 StringCchCat(buf, 256, TEXT("(SYNC)"));
2570 if (dwSupport & WAVECAPS_SAMPLEACCURATE)
2572 // returns sample-accurate position information
2573 StringCchCat(buf, 256, TEXT("(SAMPLEACCURATE)"));
2576 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%S", buf);
2579 // ----------------------------------------------------------------------------
2581 // ----------------------------------------------------------------------------
2583 void AudioDeviceWindowsWave::TraceWaveInError(MMRESULT error) const
2585 TCHAR buf[MAXERRORLENGTH];
2586 TCHAR msg[MAXERRORLENGTH];
2588 StringCchPrintf(buf, MAXERRORLENGTH, TEXT("Error details: "));
2589 waveInGetErrorText(error, msg, MAXERRORLENGTH);
2590 StringCchCat(buf, MAXERRORLENGTH, msg);
2591 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%S", buf);
2594 // ----------------------------------------------------------------------------
2595 // TraceWaveOutError
2596 // ----------------------------------------------------------------------------
2598 void AudioDeviceWindowsWave::TraceWaveOutError(MMRESULT error) const
2600 TCHAR buf[MAXERRORLENGTH];
2601 TCHAR msg[MAXERRORLENGTH];
2603 StringCchPrintf(buf, MAXERRORLENGTH, TEXT("Error details: "));
2604 waveOutGetErrorText(error, msg, MAXERRORLENGTH);
2605 StringCchCat(buf, MAXERRORLENGTH, msg);
2606 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%S", buf);
2609 // ----------------------------------------------------------------------------
2610 // PrepareStartPlayout
2611 // ----------------------------------------------------------------------------
2613 int32_t AudioDeviceWindowsWave::PrepareStartPlayout()
2616 CriticalSectionScoped lock(&_critSect);
2618 if (_hWaveOut == NULL)
2623 // A total of 30ms of data is immediately placed in the SC buffer
2625 int8_t zeroVec[4*PLAY_BUF_SIZE_IN_SAMPLES]; // max allocation
2626 memset(zeroVec, 0, 4*PLAY_BUF_SIZE_IN_SAMPLES);
2629 Write(zeroVec, PLAY_BUF_SIZE_IN_SAMPLES);
2630 Write(zeroVec, PLAY_BUF_SIZE_IN_SAMPLES);
2631 Write(zeroVec, PLAY_BUF_SIZE_IN_SAMPLES);
2639 _dc_penalty_counter = 20;
2646 // ----------------------------------------------------------------------------
2647 // PrepareStartRecording
2648 // ----------------------------------------------------------------------------
2650 int32_t AudioDeviceWindowsWave::PrepareStartRecording()
2653 CriticalSectionScoped lock(&_critSect);
2655 if (_hWaveIn == NULL)
2662 _recPutBackDelay = REC_PUT_BACK_DELAY;
2666 mmtime.wType = TIME_SAMPLES;
2668 res = waveInGetPosition(_hWaveIn, &mmtime, sizeof(mmtime));
2669 if (MMSYSERR_NOERROR != res)
2671 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInGetPosition(TIME_SAMPLES) failed (err=%d)", res);
2672 TraceWaveInError(res);
2675 _read_samples = mmtime.u.sample;
2676 _read_samples_old = _read_samples;
2677 _rec_samples_old = mmtime.u.sample;
2680 for (int n = 0; n < N_BUFFERS_IN; n++)
2682 const uint8_t nBytesPerSample = 2*_recChannels;
2684 // set up the input wave header
2685 _waveHeaderIn[n].lpData = reinterpret_cast<LPSTR>(&_recBuffer[n]);
2686 _waveHeaderIn[n].dwBufferLength = nBytesPerSample * REC_BUF_SIZE_IN_SAMPLES;
2687 _waveHeaderIn[n].dwFlags = 0;
2688 _waveHeaderIn[n].dwBytesRecorded = 0;
2689 _waveHeaderIn[n].dwUser = 0;
2691 memset(_recBuffer[n], 0, nBytesPerSample * REC_BUF_SIZE_IN_SAMPLES);
2693 // prepare a buffer for waveform-audio input
2694 res = waveInPrepareHeader(_hWaveIn, &_waveHeaderIn[n], sizeof(WAVEHDR));
2695 if (MMSYSERR_NOERROR != res)
2697 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInPrepareHeader(%d) failed (err=%d)", n, res);
2698 TraceWaveInError(res);
2701 // send an input buffer to the given waveform-audio input device
2702 res = waveInAddBuffer(_hWaveIn, &_waveHeaderIn[n], sizeof(WAVEHDR));
2703 if (MMSYSERR_NOERROR != res)
2705 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInAddBuffer(%d) failed (err=%d)", n, res);
2706 TraceWaveInError(res);
2710 // start input on the given waveform-audio input device
2711 res = waveInStart(_hWaveIn);
2712 if (MMSYSERR_NOERROR != res)
2714 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInStart() failed (err=%d)", res);
2715 TraceWaveInError(res);
2721 // ----------------------------------------------------------------------------
2722 // GetPlayoutBufferDelay
2723 // ----------------------------------------------------------------------------
2725 int32_t AudioDeviceWindowsWave::GetPlayoutBufferDelay(uint32_t& writtenSamples, uint32_t& playedSamples)
2729 long playedDifference;
2730 int msecInPlayoutBuffer(0); // #milliseconds of audio in the playout buffer
2732 const uint16_t nSamplesPerMs = (uint16_t)(N_PLAY_SAMPLES_PER_SEC/1000); // default is 48000/1000 = 48
2743 // Retrieve the current playback position.
2745 mmtime.wType = TIME_SAMPLES; // number of waveform-audio samples
2746 res = waveOutGetPosition(_hWaveOut, &mmtime, sizeof(mmtime));
2747 if (MMSYSERR_NOERROR != res)
2749 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveOutGetPosition() failed (err=%d)", res);
2750 TraceWaveOutError(res);
2753 writtenSamples = _writtenSamples; // #samples written to the playout buffer
2754 playedSamples = mmtime.u.sample; // current playout position in the playout buffer
2756 // derive remaining amount (in ms) of data in the playout buffer
2757 msecInPlayoutBuffer = ((writtenSamples - playedSamples)/nSamplesPerMs);
2759 playedDifference = (long) (_playedSamplesOld - playedSamples);
2761 if (playedDifference > 64000)
2763 // If the sound cards number-of-played-out-samples variable wraps around before
2764 // written_sampels wraps around this needs to be adjusted. This can happen on
2765 // sound cards that uses less than 32 bits to keep track of number of played out
2766 // sampels. To avoid being fooled by sound cards that sometimes produces false
2767 // output we compare old value minus the new value with a large value. This is
2768 // neccessary because some SC:s produce an output like 153, 198, 175, 230 which
2769 // would trigger the wrap-around function if we didn't compare with a large value.
2770 // The value 64000 is chosen because 2^16=65536 so we allow wrap around at 16 bits.
2773 while((_playedSamplesOld <= (unsigned long)POW2(i)) && (i > 14)) {
2777 if((i < 31) && (i > 14)) {
2778 // Avoid adjusting when there is 32-bit wrap-around since that is
2779 // something neccessary.
2781 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "msecleft() => wrap around occured: %d bits used by sound card)", (i+1));
2783 _writtenSamples = _writtenSamples - POW2(i + 1);
2784 writtenSamples = _writtenSamples;
2785 msecInPlayoutBuffer = ((writtenSamples - playedSamples)/nSamplesPerMs);
2788 else if ((_writtenSamplesOld > POW2(31)) && (writtenSamples < 96000))
2790 // Wrap around as expected after having used all 32 bits. (But we still
2791 // test if the wrap around happened earlier which it should not)
2794 while (_writtenSamplesOld <= (unsigned long)POW2(i)) {
2798 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, " msecleft() (wrap around occured after having used all 32 bits)");
2800 _writtenSamplesOld = writtenSamples;
2801 _playedSamplesOld = playedSamples;
2802 msecInPlayoutBuffer = (int)((writtenSamples + POW2(i + 1) - playedSamples)/nSamplesPerMs);
2805 else if ((writtenSamples < 96000) && (playedSamples > POW2(31)))
2807 // Wrap around has, as expected, happened for written_sampels before
2808 // playedSampels so we have to adjust for this until also playedSampels
2809 // has had wrap around.
2811 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, " msecleft() (wrap around occured: correction of output is done)");
2813 _writtenSamplesOld = writtenSamples;
2814 _playedSamplesOld = playedSamples;
2815 msecInPlayoutBuffer = (int)((writtenSamples + POW2(32) - playedSamples)/nSamplesPerMs);
2818 _writtenSamplesOld = writtenSamples;
2819 _playedSamplesOld = playedSamples;
2822 // We use the following formaula to track that playout works as it should
2823 // y=playedSamples/48 - timeGetTime();
2824 // y represent the clock drift between system clock and sound card clock - should be fairly stable
2825 // When the exponential mean value of diff(y) goes away from zero something is wrong
2826 // The exponential formula will accept 1% clock drift but not more
2827 // The driver error means that we will play to little audio and have a high negative clock drift
2828 // We kick in our alternative method when the clock drift reaches 20%
2831 int unsigned time =0;
2833 // If we have other problems that causes playout glitches
2834 // we don't want to switch playout method.
2835 // Check if playout buffer is extremely low, or if we haven't been able to
2836 // exectue our code in more than 40 ms
2838 time = timeGetTime();
2840 if ((msecInPlayoutBuffer < 20) || (time - _dc_prevtime > 40))
2842 _dc_penalty_counter = 100;
2845 if ((playedSamples != 0))
2847 y = playedSamples/48 - time;
2848 if ((_dc_y_prev != 0) && (_dc_penalty_counter == 0))
2850 diff = y - _dc_y_prev;
2851 _dc_diff_mean = (990*_dc_diff_mean)/1000 + 10*diff;
2856 if (_dc_penalty_counter)
2858 _dc_penalty_counter--;
2861 if (_dc_diff_mean < -200)
2863 // Always reset the filter
2866 // Problem is detected. Switch delay method and set min buffer to 80.
2867 // Reset the filter and keep monitoring the filter output.
2868 // If issue is detected a second time, increase min buffer to 100.
2869 // If that does not help, we must modify this scheme further.
2872 if (_useHeader == 1)
2874 _minPlayBufDelay = 80;
2875 _playWarning = 1; // only warn first time
2876 WEBRTC_TRACE(kTraceInfo, kTraceUtility, -1, "Modification #1: _useHeader = %d, _minPlayBufDelay = %d", _useHeader, _minPlayBufDelay);
2878 else if (_useHeader == 2)
2880 _minPlayBufDelay = 100; // add some more safety
2881 WEBRTC_TRACE(kTraceInfo, kTraceUtility, -1, "Modification #2: _useHeader = %d, _minPlayBufDelay = %d", _useHeader, _minPlayBufDelay);
2885 // This state should not be entered... (HA)
2886 WEBRTC_TRACE (kTraceWarning, kTraceUtility, -1, "further actions are required!");
2888 if (_playWarning == 1)
2890 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, "pending playout warning exists");
2892 _playWarning = 1; // triggers callback from module process thread
2893 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, "kPlayoutWarning message posted: switching to alternative playout delay method");
2895 _dc_prevtime = time;
2896 _dc_prevplay = playedSamples;
2898 // Try a very rough method of looking at how many buffers are still playing
2900 for (i = 0; i < N_BUFFERS_OUT; i++) {
2901 if ((_waveHeaderOut[i].dwFlags & WHDR_INQUEUE)!=0) {
2906 if ((ms_Header-50) > msecInPlayoutBuffer) {
2907 // Test for cases when GetPosition appears to be screwed up (currently just log....)
2909 if (_no_of_msecleft_warnings%20==0)
2911 StringCchPrintf(infoStr, 300, TEXT("writtenSamples=%i, playedSamples=%i, msecInPlayoutBuffer=%i, ms_Header=%i"), writtenSamples, playedSamples, msecInPlayoutBuffer, ms_Header);
2912 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, "%S", infoStr);
2914 _no_of_msecleft_warnings++;
2917 // If this is true we have had a problem with the playout
2924 if (ms_Header < msecInPlayoutBuffer)
2926 if (_no_of_msecleft_warnings % 100 == 0)
2929 StringCchPrintf(str, 300, TEXT("_no_of_msecleft_warnings=%i, msecInPlayoutBuffer=%i ms_Header=%i (minBuffer=%i buffersize=%i writtenSamples=%i playedSamples=%i)"),
2930 _no_of_msecleft_warnings, msecInPlayoutBuffer, ms_Header, _minPlayBufDelay, _playBufDelay, writtenSamples, playedSamples);
2931 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, "%S", str);
2933 _no_of_msecleft_warnings++;
2934 ms_Header -= 6; // Round off as we only have 10ms resolution + Header info is usually slightly delayed compared to GetPosition
2943 return (msecInPlayoutBuffer);
2947 // ----------------------------------------------------------------------------
2948 // GetRecordingBufferDelay
2949 // ----------------------------------------------------------------------------
2951 int32_t AudioDeviceWindowsWave::GetRecordingBufferDelay(uint32_t& readSamples, uint32_t& recSamples)
2957 const uint16_t nSamplesPerMs = (uint16_t)(N_REC_SAMPLES_PER_SEC/1000); // default is 48000/1000 = 48
2959 // Retrieve the current input position of the given waveform-audio input device
2961 mmtime.wType = TIME_SAMPLES;
2962 mmr = waveInGetPosition(_hWaveIn, &mmtime, sizeof(mmtime));
2963 if (MMSYSERR_NOERROR != mmr)
2965 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInGetPosition() failed (err=%d)", mmr);
2966 TraceWaveInError(mmr);
2969 readSamples = _read_samples; // updated for each full fram in RecProc()
2970 recSamples = mmtime.u.sample; // remaining time in input queue (recorded but not read yet)
2972 recDifference = (long) (_rec_samples_old - recSamples);
2974 if( recDifference > 64000) {
2975 WEBRTC_TRACE (kTraceDebug, kTraceUtility, -1,"WRAP 1 (recDifference =%d)", recDifference);
2976 // If the sound cards number-of-recorded-samples variable wraps around before
2977 // read_sampels wraps around this needs to be adjusted. This can happen on
2978 // sound cards that uses less than 32 bits to keep track of number of played out
2979 // sampels. To avoid being fooled by sound cards that sometimes produces false
2980 // output we compare old value minus the new value with a large value. This is
2981 // neccessary because some SC:s produce an output like 153, 198, 175, 230 which
2982 // would trigger the wrap-around function if we didn't compare with a large value.
2983 // The value 64000 is chosen because 2^16=65536 so we allow wrap around at 16 bits.
2986 while((_rec_samples_old <= (unsigned long)POW2(i)) && (i > 14))
2989 if((i < 31) && (i > 14)) {
2990 // Avoid adjusting when there is 32-bit wrap-around since that is
2991 // somethying neccessary.
2993 _read_samples = _read_samples - POW2(i + 1);
2994 readSamples = _read_samples;
2997 WEBRTC_TRACE (kTraceWarning, kTraceUtility, -1,"AEC (_rec_samples_old %d recSamples %d)",_rec_samples_old, recSamples);
3001 if((_wrapCounter>200)){
3002 // Do nothing, handled later
3004 else if((_rec_samples_old > POW2(31)) && (recSamples < 96000)) {
3005 WEBRTC_TRACE (kTraceDebug, kTraceUtility, -1,"WRAP 2 (_rec_samples_old %d recSamples %d)",_rec_samples_old, recSamples);
3006 // Wrap around as expected after having used all 32 bits.
3007 _read_samples_old = readSamples;
3008 _rec_samples_old = recSamples;
3010 return (int)((recSamples + POW2(32) - readSamples)/nSamplesPerMs);
3013 } else if((recSamples < 96000) && (readSamples > POW2(31))) {
3014 WEBRTC_TRACE (kTraceDebug, kTraceUtility, -1,"WRAP 3 (readSamples %d recSamples %d)",readSamples, recSamples);
3015 // Wrap around has, as expected, happened for rec_sampels before
3016 // readSampels so we have to adjust for this until also readSampels
3017 // has had wrap around.
3018 _read_samples_old = readSamples;
3019 _rec_samples_old = recSamples;
3021 return (int)((recSamples + POW2(32) - readSamples)/nSamplesPerMs);
3024 _read_samples_old = _read_samples;
3025 _rec_samples_old = recSamples;
3026 int res=(((int)_rec_samples_old - (int)_read_samples_old)/nSamplesPerMs);
3028 if((res > 2000)||(res < 0)||(_wrapCounter>200)){
3030 WEBRTC_TRACE (kTraceWarning, kTraceUtility, -1,"msec_read error (res %d wrapCounter %d)",res, _wrapCounter);
3032 mmtime.wType = TIME_SAMPLES;
3034 mmr=waveInGetPosition(_hWaveIn, &mmtime, sizeof(mmtime));
3035 if (mmr != MMSYSERR_NOERROR) {
3036 WEBRTC_TRACE (kTraceWarning, kTraceUtility, -1, "waveInGetPosition failed (mmr=%d)", mmr);
3038 _read_samples=mmtime.u.sample;
3039 _read_samples_old=_read_samples;
3040 _rec_samples_old=mmtime.u.sample;
3042 // Guess a decent value
3050 // ============================================================================
3052 // ============================================================================
3054 // ----------------------------------------------------------------------------
3056 // ----------------------------------------------------------------------------
3058 bool AudioDeviceWindowsWave::ThreadFunc(void* pThis)
3060 return (static_cast<AudioDeviceWindowsWave*>(pThis)->ThreadProcess());
3063 // ----------------------------------------------------------------------------
3065 // ----------------------------------------------------------------------------
3067 bool AudioDeviceWindowsWave::ThreadProcess()
3070 uint32_t playDiff(0);
3071 uint32_t recDiff(0);
3073 LONGLONG playTime(0);
3074 LONGLONG recTime(0);
3076 switch (_timeEvent.Wait(1000))
3078 case kEventSignaled:
3081 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "EventWrapper::Wait() failed => restarting timer");
3082 _timeEvent.StopTimer();
3083 _timeEvent.StartTimer(true, TIMER_PERIOD_MS);
3089 time = AudioDeviceUtility::GetTimeInMS();
3093 if (PrepareStartPlayout() == 0)
3095 _prevTimerCheckTime = time;
3096 _prevPlayTime = time;
3099 _playStartEvent.Set();
3105 if (PrepareStartRecording() == 0)
3107 _prevTimerCheckTime = time;
3108 _prevRecTime = time;
3109 _prevRecByteCheckTime = time;
3112 _recStartEvent.Set();
3118 playDiff = time - _prevPlayTime;
3123 recDiff = time - _prevRecTime;
3126 if (_playing || _recording)
3128 RestartTimerIfNeeded(time);
3132 (playDiff > (uint32_t)(_dTcheckPlayBufDelay - 1)) ||
3138 if (PlayProc(playTime) == -1)
3140 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "PlayProc() failed");
3142 _prevPlayTime = time;
3144 _playAcc += playTime;
3149 if (_playing && (playDiff > 12))
3151 // It has been a long time since we were able to play out, try to
3152 // compensate by calling PlayProc again.
3157 if (PlayProc(playTime))
3159 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "PlayProc() failed");
3161 _prevPlayTime = time;
3163 _playAcc += playTime;
3169 (recDiff > REC_CHECK_TIME_PERIOD_MS) ||
3175 int32_t nRecordedBytes(0);
3176 uint16_t maxIter(10);
3178 // Deliver all availiable recorded buffers and update the CPU load measurement.
3179 // We use a while loop here to compensate for the fact that the multi-media timer
3180 // can sometimed enter a "bad state" after hibernation where the resolution is
3181 // reduced from ~1ms to ~10-15 ms.
3183 while ((nRecordedBytes = RecProc(recTime)) > 0)
3186 _recordedBytes += nRecordedBytes;
3187 if (recTime && _perfFreq.QuadPart)
3189 // Measure the average CPU load:
3190 // This is a simplified expression where an exponential filter is used:
3191 // _avgCPULoad = 0.99 * _avgCPULoad + 0.01 * newCPU,
3192 // newCPU = (recTime+playAcc)/f is time in seconds
3193 // newCPU / 0.01 is the fraction of a 10 ms period
3194 // The two 0.01 cancels each other.
3195 // NOTE - assumes 10ms audio buffers.
3197 _avgCPULoad = (float)(_avgCPULoad*.99 + (recTime+_playAcc)/(double)(_perfFreq.QuadPart));
3202 // If we get this message ofte, our compensation scheme is not sufficient.
3203 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "failed to compensate for reduced MM-timer resolution");
3207 if (nRecordedBytes == -1)
3209 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "RecProc() failed");
3212 _prevRecTime = time;
3214 // Monitor the recording process and generate error/warning callbacks if needed
3215 MonitorRecording(time);
3222 _prevRecByteCheckTime = time;
3229 // ----------------------------------------------------------------------------
3231 // ----------------------------------------------------------------------------
3233 int32_t AudioDeviceWindowsWave::RecProc(LONGLONG& consumedTime)
3236 uint32_t bufCount(0);
3237 uint32_t nBytesRecorded(0);
3241 // count modulo N_BUFFERS_IN (0,1,2,...,(N_BUFFERS_IN-1),0,1,2,..)
3242 if (_recBufCount == N_BUFFERS_IN)
3247 bufCount = _recBufCount;
3249 // take mono/stereo mode into account when deriving size of a full buffer
3250 const uint16_t bytesPerSample = 2*_recChannels;
3251 const uint32_t fullBufferSizeInBytes = bytesPerSample * REC_BUF_SIZE_IN_SAMPLES;
3253 // read number of recorded bytes for the given input-buffer
3254 nBytesRecorded = _waveHeaderIn[bufCount].dwBytesRecorded;
3256 if (nBytesRecorded == fullBufferSizeInBytes ||
3257 (nBytesRecorded > 0))
3259 int32_t msecOnPlaySide;
3260 int32_t msecOnRecordSide;
3261 uint32_t writtenSamples;
3262 uint32_t playedSamples;
3263 uint32_t readSamples, recSamples;
3266 uint32_t nSamplesRecorded = (nBytesRecorded/bytesPerSample); // divide by 2 or 4 depending on mono or stereo
3268 if (nBytesRecorded == fullBufferSizeInBytes)
3274 // Test if it is stuck on this buffer
3276 if (_timesdwBytes < 5)
3283 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id,"nBytesRecorded=%d => don't use", nBytesRecorded);
3289 // store the recorded buffer (no action will be taken if the #recorded samples is not a full buffer)
3290 _ptrAudioBuffer->SetRecordedBuffer(_waveHeaderIn[bufCount].lpData, nSamplesRecorded);
3292 // update #samples read
3293 _read_samples += nSamplesRecorded;
3295 // Check how large the playout and recording buffers are on the sound card.
3296 // This info is needed by the AEC.
3298 msecOnPlaySide = GetPlayoutBufferDelay(writtenSamples, playedSamples);
3299 msecOnRecordSide = GetRecordingBufferDelay(readSamples, recSamples);
3301 // If we use the alternative playout delay method, skip the clock drift compensation
3302 // since it will be an unreliable estimate and might degrade AEC performance.
3303 int32_t drift = (_useHeader > 0) ? 0 : GetClockDrift(playedSamples, recSamples);
3305 _ptrAudioBuffer->SetVQEData(msecOnPlaySide, msecOnRecordSide, drift);
3307 _ptrAudioBuffer->SetTypingStatus(KeyPressed());
3309 // Store the play and rec delay values for video synchronization
3310 _sndCardPlayDelay = msecOnPlaySide;
3311 _sndCardRecDelay = msecOnRecordSide;
3313 LARGE_INTEGER t1,t2;
3317 QueryPerformanceCounter(&t1);
3319 // deliver recorded samples at specified sample rate, mic level etc. to the observer using callback
3321 _ptrAudioBuffer->DeliverRecordedData();
3324 QueryPerformanceCounter(&t2);
3326 if (InputSanityCheckAfterUnlockedPeriod() == -1)
3335 uint32_t newMicLevel = _ptrAudioBuffer->NewMicLevel();
3336 if (newMicLevel != 0)
3338 // The VQE will only deliver non-zero microphone levels when a change is needed.
3339 WEBRTC_TRACE(kTraceStream, kTraceUtility, _id,"AGC change of volume: => new=%u", newMicLevel);
3341 // We store this outside of the audio buffer to avoid
3342 // having it overwritten by the getter thread.
3343 _newMicLevel = newMicLevel;
3344 SetEvent(_hSetCaptureVolumeEvent);
3348 // return utilized buffer to queue after specified delay (default is 4)
3349 if (_recDelayCount > (_recPutBackDelay-1))
3351 // deley buffer counter to compensate for "put-back-delay"
3352 bufCount = (bufCount + N_BUFFERS_IN - _recPutBackDelay) % N_BUFFERS_IN;
3354 // reset counter so we can make new detection
3355 _waveHeaderIn[bufCount].dwBytesRecorded = 0;
3357 // return the utilized wave-header after certain delay (given by _recPutBackDelay)
3358 res = waveInUnprepareHeader(_hWaveIn, &(_waveHeaderIn[bufCount]), sizeof(WAVEHDR));
3359 if (MMSYSERR_NOERROR != res)
3361 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "waveInUnprepareHeader(%d) failed (err=%d)", bufCount, res);
3362 TraceWaveInError(res);
3365 // ensure that the utilized header can be used again
3366 res = waveInPrepareHeader(_hWaveIn, &(_waveHeaderIn[bufCount]), sizeof(WAVEHDR));
3367 if (res != MMSYSERR_NOERROR)
3369 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "waveInPrepareHeader(%d) failed (err=%d)", bufCount, res);
3370 TraceWaveInError(res);
3374 // add the utilized buffer to the queue again
3375 res = waveInAddBuffer(_hWaveIn, &(_waveHeaderIn[bufCount]), sizeof(WAVEHDR));
3376 if (res != MMSYSERR_NOERROR)
3378 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "waveInAddBuffer(%d) failed (err=%d)", bufCount, res);
3379 TraceWaveInError(res);
3380 if (_recPutBackDelay < 50)
3383 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "_recPutBackDelay increased to %d", _recPutBackDelay);
3389 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, "pending recording error exists");
3391 _recError = 1; // triggers callback from module process thread
3392 WEBRTC_TRACE(kTraceError, kTraceUtility, _id, "kRecordingError message posted: _recPutBackDelay=%u", _recPutBackDelay);
3395 } // if (_recDelayCount > (_recPutBackDelay-1))
3397 if (_recDelayCount < (_recPutBackDelay+1))
3402 // increase main buffer count since one complete buffer has now been delivered
3406 // Calculate processing time
3407 consumedTime = (int)(t2.QuadPart-t1.QuadPart);
3408 // handle wraps, time should not be higher than a second
3409 if ((consumedTime > _perfFreq.QuadPart) || (consumedTime < 0))
3413 } // if ((nBytesRecorded == fullBufferSizeInBytes))
3415 return nBytesRecorded;
3418 // ----------------------------------------------------------------------------
3420 // ----------------------------------------------------------------------------
3422 int AudioDeviceWindowsWave::PlayProc(LONGLONG& consumedTime)
3424 int32_t remTimeMS(0);
3425 int8_t playBuffer[4*PLAY_BUF_SIZE_IN_SAMPLES];
3426 uint32_t writtenSamples(0);
3427 uint32_t playedSamples(0);
3435 // Get number of ms of sound that remains in the sound card buffer for playback.
3437 remTimeMS = GetPlayoutBufferDelay(writtenSamples, playedSamples);
3439 // The threshold can be adaptive or fixed. The adaptive scheme is updated
3440 // also for fixed mode but the updated threshold is not utilized.
3442 const uint16_t thresholdMS =
3443 (_playBufType == AudioDeviceModule::kAdaptiveBufferSize) ? _playBufDelay : _playBufDelayFixed;
3445 if (remTimeMS < thresholdMS + 9)
3447 _dTcheckPlayBufDelay = 5;
3451 WEBRTC_TRACE(kTraceInfo, kTraceUtility, _id, "playout buffer is empty => we must adapt...");
3452 if (_waitCounter > 30)
3455 if (_erZeroCounter == 2)
3457 _playBufDelay += 15;
3458 _minPlayBufDelay += 20;
3460 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "New playout states (er=0,erZero=2): minPlayBufDelay=%u, playBufDelay=%u", _minPlayBufDelay, _playBufDelay);
3462 else if (_erZeroCounter == 3)
3465 _playBufDelay += 30;
3466 _minPlayBufDelay += 25;
3468 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "New playout states (er=0, erZero=3): minPlayBufDelay=%u, playBufDelay=%u", _minPlayBufDelay, _playBufDelay);
3472 _minPlayBufDelay += 10;
3473 _playBufDelay += 15;
3475 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "New playout states (er=0, erZero=1): minPlayBufDelay=%u, playBufDelay=%u", _minPlayBufDelay, _playBufDelay);
3479 else if (remTimeMS < _minPlayBufDelay)
3481 // If there is less than 25 ms of audio in the play out buffer
3482 // increase the buffersize limit value. _waitCounter prevents
3483 // _playBufDelay to be increased every time this function is called.
3485 if (_waitCounter > 30)
3487 _playBufDelay += 10;
3490 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "Playout threshold is increased: playBufDelay=%u", _playBufDelay);
3493 else if (remTimeMS < thresholdMS - 9)
3500 _dTcheckPlayBufDelay = 10;
3503 QueryPerformanceCounter(&t1); // measure time: START
3505 // Ask for new PCM data to be played out using the AudioDeviceBuffer.
3506 // Ensure that this callback is executed without taking the audio-thread lock.
3509 uint32_t nSamples = _ptrAudioBuffer->RequestPlayoutData(PLAY_BUF_SIZE_IN_SAMPLES);
3512 if (OutputSanityCheckAfterUnlockedPeriod() == -1)
3518 nSamples = _ptrAudioBuffer->GetPlayoutData(playBuffer);
3519 if (nSamples != PLAY_BUF_SIZE_IN_SAMPLES)
3521 WEBRTC_TRACE(kTraceError, kTraceUtility, _id, "invalid number of output samples(%d)", nSamples);
3524 QueryPerformanceCounter(&t2); // measure time: STOP
3525 consumedTime = (int)(t2.QuadPart - t1.QuadPart);
3527 Write(playBuffer, PLAY_BUF_SIZE_IN_SAMPLES);
3529 } // if (er < thresholdMS + 9)
3530 else if (thresholdMS + 9 < remTimeMS )
3533 _dTcheckPlayBufDelay = 2; // check buffer more often
3534 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "Need to check playout buffer more often (dT=%u, remTimeMS=%u)", _dTcheckPlayBufDelay, remTimeMS);
3537 // If the buffersize has been stable for 20 seconds try to decrease the buffer size
3538 if (_waitCounter > 2000)
3542 _waitCounter = 1990;
3543 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "Playout threshold is decreased: playBufDelay=%u", _playBufDelay);
3546 // Limit the minimum sound card (playback) delay to adaptive minimum delay
3547 if (_playBufDelay < _minPlayBufDelay)
3549 _playBufDelay = _minPlayBufDelay;
3550 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "Playout threshold is limited to %u", _minPlayBufDelay);
3553 // Limit the maximum sound card (playback) delay to 150 ms
3554 if (_playBufDelay > 150)
3556 _playBufDelay = 150;
3557 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "Playout threshold is limited to %d", _playBufDelay);
3560 // Upper limit of the minimum sound card (playback) delay to 65 ms.
3561 // Deactivated during "useHeader mode" (_useHeader > 0).
3562 if (_minPlayBufDelay > _MAX_minBuffer &&
3565 _minPlayBufDelay = _MAX_minBuffer;
3566 WEBRTC_TRACE(kTraceDebug, kTraceUtility, _id, "Minimum playout threshold is limited to %d", _MAX_minBuffer);
3572 // ----------------------------------------------------------------------------
3574 // ----------------------------------------------------------------------------
3576 int32_t AudioDeviceWindowsWave::Write(int8_t* data, uint16_t nSamples)
3578 if (_hWaveOut == NULL)
3583 if (_playIsInitialized)
3587 const uint16_t bufCount(_playBufCount);
3589 // Place data in the memory associated with _waveHeaderOut[bufCount]
3591 const int16_t nBytes = (2*_playChannels)*nSamples;
3592 memcpy(&_playBuffer[bufCount][0], &data[0], nBytes);
3594 // Send a data block to the given waveform-audio output device.
3596 // When the buffer is finished, the WHDR_DONE bit is set in the dwFlags
3597 // member of the WAVEHDR structure. The buffer must be prepared with the
3598 // waveOutPrepareHeader function before it is passed to waveOutWrite.
3599 // Unless the device is paused by calling the waveOutPause function,
3600 // playback begins when the first data block is sent to the device.
3602 res = waveOutWrite(_hWaveOut, &_waveHeaderOut[bufCount], sizeof(_waveHeaderOut[bufCount]));
3603 if (MMSYSERR_NOERROR != res)
3605 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "waveOutWrite(%d) failed (err=%d)", bufCount, res);
3606 TraceWaveOutError(res);
3609 if (_writeErrors > 10)
3611 if (_playError == 1)
3613 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, "pending playout error exists");
3615 _playError = 1; // triggers callback from module process thread
3616 WEBRTC_TRACE(kTraceError, kTraceUtility, _id, "kPlayoutError message posted: _writeErrors=%u", _writeErrors);
3622 _playBufCount = (_playBufCount+1) % N_BUFFERS_OUT; // increase buffer counter modulo size of total buffer
3623 _writtenSamples += nSamples; // each sample is 2 or 4 bytes
3630 // ----------------------------------------------------------------------------
3632 // ----------------------------------------------------------------------------
3634 int32_t AudioDeviceWindowsWave::GetClockDrift(const uint32_t plSamp, const uint32_t rcSamp)
3637 unsigned int plSampDiff = 0, rcSampDiff = 0;
3639 if (plSamp >= _plSampOld)
3641 plSampDiff = plSamp - _plSampOld;
3647 while(_plSampOld <= (unsigned int)POW2(i))
3652 // Add the amount remaining prior to wrapping
3653 plSampDiff = plSamp + POW2(i + 1) - _plSampOld;
3656 if (rcSamp >= _rcSampOld)
3658 rcSampDiff = rcSamp - _rcSampOld;
3663 while(_rcSampOld <= (unsigned int)POW2(i))
3668 rcSampDiff = rcSamp + POW2(i + 1) - _rcSampOld;
3671 drift = plSampDiff - rcSampDiff;
3673 _plSampOld = plSamp;
3674 _rcSampOld = rcSamp;
3679 // ----------------------------------------------------------------------------
3681 // ----------------------------------------------------------------------------
3683 int32_t AudioDeviceWindowsWave::MonitorRecording(const uint32_t time)
3685 const uint16_t bytesPerSample = 2*_recChannels;
3686 const uint32_t nRecordedSamples = _recordedBytes/bytesPerSample;
3688 if (nRecordedSamples > 5*N_REC_SAMPLES_PER_SEC)
3690 // 5 seconds of audio has been recorded...
3691 if ((time - _prevRecByteCheckTime) > 5700)
3693 // ...and it was more than 5.7 seconds since we last did this check <=>
3694 // we have not been able to record 5 seconds of audio in 5.7 seconds,
3695 // hence a problem should be reported.
3696 // This problem can be related to USB overload.
3698 if (_recWarning == 1)
3700 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, "pending recording warning exists");
3702 _recWarning = 1; // triggers callback from module process thread
3703 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, "kRecordingWarning message posted: time-_prevRecByteCheckTime=%d", time - _prevRecByteCheckTime);
3706 _recordedBytes = 0; // restart "check again when 5 seconds are recorded"
3707 _prevRecByteCheckTime = time; // reset timer to measure time for recording of 5 seconds
3710 if ((time - _prevRecByteCheckTime) > 8000)
3712 // It has been more than 8 seconds since we able to confirm that 5 seconds of
3713 // audio was recorded, hence we have not been able to record 5 seconds in
3714 // 8 seconds => the complete recording process is most likely dead.
3718 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, "pending recording error exists");
3720 _recError = 1; // triggers callback from module process thread
3721 WEBRTC_TRACE(kTraceError, kTraceUtility, _id, "kRecordingError message posted: time-_prevRecByteCheckTime=%d", time - _prevRecByteCheckTime);
3723 _prevRecByteCheckTime = time;
3729 // ----------------------------------------------------------------------------
3732 // Restart timer if needed (they seem to be messed up after a hibernate).
3733 // ----------------------------------------------------------------------------
3735 int32_t AudioDeviceWindowsWave::RestartTimerIfNeeded(const uint32_t time)
3737 const uint32_t diffMS = time - _prevTimerCheckTime;
3738 _prevTimerCheckTime = time;
3742 // one timer-issue detected...
3744 if (_timerFaults > 5 && _timerRestartAttempts < 2)
3746 // Reinitialize timer event if event fails to execute at least every 5ms.
3747 // On some machines it helps and the timer starts working as it should again;
3748 // however, not all machines (we have seen issues on e.g. IBM T60).
3749 // Therefore, the scheme below ensures that we do max 2 attempts to restart the timer.
3750 // For the cases where restart does not do the trick, we compensate for the reduced
3751 // resolution on both the recording and playout sides.
3752 WEBRTC_TRACE(kTraceWarning, kTraceUtility, _id, " timer issue detected => timer is restarted");
3753 _timeEvent.StopTimer();
3754 _timeEvent.StartTimer(true, TIMER_PERIOD_MS);
3755 // make sure timer gets time to start up and we don't kill/start timer serveral times over and over again
3757 _timerRestartAttempts++;
3762 // restart timer-check scheme since we are OK
3764 _timerRestartAttempts = 0;
3771 bool AudioDeviceWindowsWave::KeyPressed() const{
3774 for (int key = VK_SPACE; key < VK_NUMLOCK; key++) {
3775 short res = GetAsyncKeyState(key);
3776 key_down |= res & 0x1; // Get the LSB
3778 return (key_down > 0);
3780 } // namespace webrtc