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 #pragma warning(disable: 4995) // name was marked as #pragma deprecated
13 #if (_MSC_VER >= 1310) && (_MSC_VER < 1400)
14 // Reports the major and minor versions of the compiler.
15 // For example, 1310 for Microsoft Visual C++ .NET 2003. 1310 represents version 13 and a 1.0 point release.
16 // The Visual C++ 2005 compiler version is 1400.
17 // Type cl /? at the command line to see the major and minor versions of your compiler along with the build number.
18 #pragma message(">> INFO: Windows Core Audio is not supported in VS 2003")
21 #include "webrtc/modules/audio_device/audio_device_config.h"
23 #ifdef WEBRTC_WINDOWS_CORE_AUDIO_BUILD
25 #include "webrtc/modules/audio_device/win/audio_device_core_win.h"
33 #include <Functiondiscoverykeys_devpkey.h>
38 #include "webrtc/modules/audio_device/audio_device_utility.h"
39 #include "webrtc/system_wrappers/interface/sleep.h"
40 #include "webrtc/system_wrappers/interface/trace.h"
42 // Macro that calls a COM method returning HRESULT value.
43 #define EXIT_ON_ERROR(hres) do { if (FAILED(hres)) goto Exit; } while(0)
45 // Macro that continues to a COM error.
46 #define CONTINUE_ON_ERROR(hres) do { if (FAILED(hres)) goto Next; } while(0)
48 // Macro that releases a COM object if not NULL.
49 #define SAFE_RELEASE(p) do { if ((p)) { (p)->Release(); (p) = NULL; } } while(0)
51 #define ROUND(x) ((x) >=0 ? (int)((x) + 0.5) : (int)((x) - 0.5))
53 // REFERENCE_TIME time units per millisecond
54 #define REFTIMES_PER_MILLISEC 10000
56 typedef struct tagTHREADNAME_INFO
58 DWORD dwType; // must be 0x1000
59 LPCSTR szName; // pointer to name (in user addr space)
60 DWORD dwThreadID; // thread ID (-1=caller thread)
61 DWORD dwFlags; // reserved for future use, must be zero
67 enum { COM_THREADING_MODEL = COINIT_MULTITHREADED };
71 kAecCaptureStreamIndex = 0,
72 kAecRenderStreamIndex = 1
75 // An implementation of IMediaBuffer, as required for
76 // IMediaObject::ProcessOutput(). After consuming data provided by
77 // ProcessOutput(), call SetLength() to update the buffer availability.
79 // Example implementation:
80 // http://msdn.microsoft.com/en-us/library/dd376684(v=vs.85).aspx
81 class MediaBufferImpl : public IMediaBuffer
84 explicit MediaBufferImpl(DWORD maxLength)
85 : _data(new BYTE[maxLength]),
87 _maxLength(maxLength),
91 // IMediaBuffer methods.
92 STDMETHOD(GetBufferAndLength(BYTE** ppBuffer, DWORD* pcbLength))
94 if (!ppBuffer || !pcbLength)
100 *pcbLength = _length;
105 STDMETHOD(GetMaxLength(DWORD* pcbMaxLength))
112 *pcbMaxLength = _maxLength;
116 STDMETHOD(SetLength(DWORD cbLength))
118 if (cbLength > _maxLength)
128 STDMETHOD_(ULONG, AddRef())
130 return InterlockedIncrement(&_refCount);
133 STDMETHOD(QueryInterface(REFIID riid, void** ppv))
139 else if (riid != IID_IMediaBuffer && riid != IID_IUnknown)
141 return E_NOINTERFACE;
144 *ppv = static_cast<IMediaBuffer*>(this);
149 STDMETHOD_(ULONG, Release())
151 LONG refCount = InterlockedDecrement(&_refCount);
168 const DWORD _maxLength;
173 // ============================================================================
175 // ============================================================================
177 // ----------------------------------------------------------------------------
178 // CoreAudioIsSupported
179 // ----------------------------------------------------------------------------
181 bool AudioDeviceWindowsCore::CoreAudioIsSupported()
183 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, -1, "%s", __FUNCTION__);
185 bool MMDeviceIsAvailable(false);
186 bool coreAudioIsSupported(false);
189 TCHAR buf[MAXERRORLENGTH];
190 TCHAR errorText[MAXERRORLENGTH];
192 // 1) Check if Windows version is Vista SP1 or later.
194 // CoreAudio is only available on Vista SP1 and later.
196 OSVERSIONINFOEX osvi;
197 DWORDLONG dwlConditionMask = 0;
198 int op = VER_LESS_EQUAL;
200 // Initialize the OSVERSIONINFOEX structure.
201 ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
202 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
203 osvi.dwMajorVersion = 6;
204 osvi.dwMinorVersion = 0;
205 osvi.wServicePackMajor = 0;
206 osvi.wServicePackMinor = 0;
207 osvi.wProductType = VER_NT_WORKSTATION;
209 // Initialize the condition mask.
210 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, op);
211 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, op);
212 VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMAJOR, op);
213 VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMINOR, op);
214 VER_SET_CONDITION(dwlConditionMask, VER_PRODUCT_TYPE, VER_EQUAL);
216 DWORD dwTypeMask = VER_MAJORVERSION | VER_MINORVERSION |
217 VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR |
221 BOOL isVistaRTMorXP = VerifyVersionInfo(&osvi, dwTypeMask,
223 if (isVistaRTMorXP != 0)
225 WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, -1,
226 "*** Windows Core Audio is only supported on Vista SP1 or later "
227 "=> will revert to the Wave API ***");
231 // 2) Initializes the COM library for use by the calling thread.
233 // The COM init wrapper sets the thread's concurrency model to MTA,
234 // and creates a new apartment for the thread if one is required. The
235 // wrapper also ensures that each call to CoInitializeEx is balanced
236 // by a corresponding call to CoUninitialize.
238 ScopedCOMInitializer comInit(ScopedCOMInitializer::kMTA);
239 if (!comInit.succeeded()) {
240 // Things will work even if an STA thread is calling this method but we
241 // want to ensure that MTA is used and therefore return false here.
245 // 3) Check if the MMDevice API is available.
247 // The Windows Multimedia Device (MMDevice) API enables audio clients to
248 // discover audio endpoint devices, determine their capabilities, and create
249 // driver instances for those devices.
250 // Header file Mmdeviceapi.h defines the interfaces in the MMDevice API.
251 // The MMDevice API consists of several interfaces. The first of these is the
252 // IMMDeviceEnumerator interface. To access the interfaces in the MMDevice API,
253 // a client obtains a reference to the IMMDeviceEnumerator interface of a
254 // device-enumerator object by calling the CoCreateInstance function.
256 // Through the IMMDeviceEnumerator interface, the client can obtain references
257 // to the other interfaces in the MMDevice API. The MMDevice API implements
258 // the following interfaces:
260 // IMMDevice Represents an audio device.
261 // IMMDeviceCollection Represents a collection of audio devices.
262 // IMMDeviceEnumerator Provides methods for enumerating audio devices.
263 // IMMEndpoint Represents an audio endpoint device.
265 IMMDeviceEnumerator* pIMMD(NULL);
266 const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
267 const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
269 hr = CoCreateInstance(
270 CLSID_MMDeviceEnumerator, // GUID value of MMDeviceEnumerator coclass
273 IID_IMMDeviceEnumerator, // GUID value of the IMMDeviceEnumerator interface
278 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
279 "AudioDeviceWindowsCore::CoreAudioIsSupported() Failed to create the required COM object", hr);
280 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, -1,
281 "AudioDeviceWindowsCore::CoreAudioIsSupported() CoCreateInstance(MMDeviceEnumerator) failed (hr=0x%x)", hr);
283 const DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM |
284 FORMAT_MESSAGE_IGNORE_INSERTS;
285 const DWORD dwLangID = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
287 // Gets the system's human readable message string for this HRESULT.
288 // All error message in English by default.
289 DWORD messageLength = ::FormatMessageW(dwFlags,
297 assert(messageLength <= MAXERRORLENGTH);
299 // Trims tailing white space (FormatMessage() leaves a trailing cr-lf.).
300 for (; messageLength && ::isspace(errorText[messageLength - 1]);
303 errorText[messageLength - 1] = '\0';
306 StringCchPrintf(buf, MAXERRORLENGTH, TEXT("Error details: "));
307 StringCchCat(buf, MAXERRORLENGTH, errorText);
308 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, -1, "%S", buf);
312 MMDeviceIsAvailable = true;
313 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, -1,
314 "AudioDeviceWindowsCore::CoreAudioIsSupported() CoCreateInstance(MMDeviceEnumerator) succeeded", hr);
318 // 4) Verify that we can create and initialize our Core Audio class.
320 // Also, perform a limited "API test" to ensure that Core Audio is supported for all devices.
322 if (MMDeviceIsAvailable)
324 coreAudioIsSupported = false;
326 AudioDeviceWindowsCore* p = new AudioDeviceWindowsCore(-1);
334 bool available(false);
338 int16_t numDevsRec = p->RecordingDevices();
339 for (uint16_t i = 0; i < numDevsRec; i++)
341 ok |= p->SetRecordingDevice(i);
342 temp_ok = p->RecordingIsAvailable(available);
344 ok |= (available == false);
347 ok |= p->InitMicrophone();
351 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, -1,
352 "AudioDeviceWindowsCore::CoreAudioIsSupported() Failed to use Core Audio Recording for device id=%i", i);
356 int16_t numDevsPlay = p->PlayoutDevices();
357 for (uint16_t i = 0; i < numDevsPlay; i++)
359 ok |= p->SetPlayoutDevice(i);
360 temp_ok = p->PlayoutIsAvailable(available);
362 ok |= (available == false);
365 ok |= p->InitSpeaker();
369 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, -1 ,
370 "AudioDeviceWindowsCore::CoreAudioIsSupported() Failed to use Core Audio Playout for device id=%i", i);
374 ok |= p->Terminate();
378 coreAudioIsSupported = true;
384 if (coreAudioIsSupported)
386 WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, -1, "*** Windows Core Audio is supported ***");
390 WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, -1, "*** Windows Core Audio is NOT supported => will revert to the Wave API ***");
393 return (coreAudioIsSupported);
396 // ============================================================================
397 // Construction & Destruction
398 // ============================================================================
400 // ----------------------------------------------------------------------------
401 // AudioDeviceWindowsCore() - ctor
402 // ----------------------------------------------------------------------------
404 AudioDeviceWindowsCore::AudioDeviceWindowsCore(const int32_t id) :
405 _comInit(ScopedCOMInitializer::kMTA),
406 _critSect(*CriticalSectionWrapper::CreateCriticalSection()),
407 _volumeMutex(*CriticalSectionWrapper::CreateCriticalSection()),
409 _ptrAudioBuffer(NULL),
410 _ptrEnumerator(NULL),
411 _ptrRenderCollection(NULL),
412 _ptrCaptureCollection(NULL),
417 _ptrRenderClient(NULL),
418 _ptrCaptureClient(NULL),
419 _ptrCaptureVolume(NULL),
420 _ptrRenderSimpleVolume(NULL),
423 _builtInAecEnabled(false),
424 _playAudioFrameSize(0),
428 _sndCardPlayDelay(0),
433 _recAudioFrameSize(0),
438 _winSupportAvrt(false),
439 _hRenderSamplesReadyEvent(NULL),
441 _hCaptureSamplesReadyEvent(NULL),
443 _hShutdownRenderEvent(NULL),
444 _hShutdownCaptureEvent(NULL),
445 _hRenderStartedEvent(NULL),
446 _hCaptureStartedEvent(NULL),
447 _hGetCaptureVolumeThread(NULL),
448 _hSetCaptureVolumeThread(NULL),
449 _hSetCaptureVolumeEvent(NULL),
454 _recIsInitialized(false),
455 _playIsInitialized(false),
456 _speakerIsInitialized(false),
457 _microphoneIsInitialized(false),
463 _playBufType(AudioDeviceModule::kAdaptiveBufferSize),
465 _playBufDelayFixed(80),
466 _usingInputDeviceIndex(false),
467 _usingOutputDeviceIndex(false),
468 _inputDevice(AudioDeviceModule::kDefaultCommunicationDevice),
469 _outputDevice(AudioDeviceModule::kDefaultCommunicationDevice),
470 _inputDeviceIndex(0),
471 _outputDeviceIndex(0),
474 WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, id, "%s created", __FUNCTION__);
475 assert(_comInit.succeeded());
477 // Try to load the Avrt DLL
480 // Get handle to the Avrt DLL module.
481 _avrtLibrary = LoadLibrary(TEXT("Avrt.dll"));
484 // Handle is valid (should only happen if OS larger than vista & win7).
485 // Try to get the function addresses.
486 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::AudioDeviceWindowsCore() The Avrt DLL module is now loaded");
488 _PAvRevertMmThreadCharacteristics = (PAvRevertMmThreadCharacteristics)GetProcAddress(_avrtLibrary, "AvRevertMmThreadCharacteristics");
489 _PAvSetMmThreadCharacteristicsA = (PAvSetMmThreadCharacteristicsA)GetProcAddress(_avrtLibrary, "AvSetMmThreadCharacteristicsA");
490 _PAvSetMmThreadPriority = (PAvSetMmThreadPriority)GetProcAddress(_avrtLibrary, "AvSetMmThreadPriority");
492 if ( _PAvRevertMmThreadCharacteristics &&
493 _PAvSetMmThreadCharacteristicsA &&
494 _PAvSetMmThreadPriority)
496 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::AudioDeviceWindowsCore() AvRevertMmThreadCharacteristics() is OK");
497 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::AudioDeviceWindowsCore() AvSetMmThreadCharacteristicsA() is OK");
498 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::AudioDeviceWindowsCore() AvSetMmThreadPriority() is OK");
499 _winSupportAvrt = true;
504 // Create our samples ready events - we want auto reset events that start in the not-signaled state.
505 // The state of an auto-reset event object remains signaled until a single waiting thread is released,
506 // at which time the system automatically sets the state to nonsignaled. If no threads are waiting,
507 // the event object's state remains signaled.
508 // (Except for _hShutdownCaptureEvent, which is used to shutdown multiple threads).
509 _hRenderSamplesReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
510 _hCaptureSamplesReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
511 _hShutdownRenderEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
512 _hShutdownCaptureEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
513 _hRenderStartedEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
514 _hCaptureStartedEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
515 _hSetCaptureVolumeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
517 _perfCounterFreq.QuadPart = 1;
518 _perfCounterFactor = 0.0;
521 // list of number of channels to use on recording side
522 _recChannelsPrioList[0] = 2; // stereo is prio 1
523 _recChannelsPrioList[1] = 1; // mono is prio 2
525 // list of number of channels to use on playout side
526 _playChannelsPrioList[0] = 2; // stereo is prio 1
527 _playChannelsPrioList[1] = 1; // mono is prio 2
531 // We know that this API will work since it has already been verified in
532 // CoreAudioIsSupported, hence no need to check for errors here as well.
534 // Retrive the IMMDeviceEnumerator API (should load the MMDevAPI.dll)
535 // TODO(henrika): we should probably move this allocation to Init() instead
536 // and deallocate in Terminate() to make the implementation more symmetric.
538 __uuidof(MMDeviceEnumerator),
541 __uuidof(IMMDeviceEnumerator),
542 reinterpret_cast<void**>(&_ptrEnumerator));
543 assert(NULL != _ptrEnumerator);
545 // DMO initialization for built-in WASAPI AEC.
547 IMediaObject* ptrDMO = NULL;
548 hr = CoCreateInstance(CLSID_CWMAudioAEC,
550 CLSCTX_INPROC_SERVER,
552 reinterpret_cast<void**>(&ptrDMO));
553 if (FAILED(hr) || ptrDMO == NULL)
555 // Since we check that _dmo is non-NULL in EnableBuiltInAEC(), the
556 // feature is prevented from being enabled.
557 _builtInAecEnabled = false;
561 SAFE_RELEASE(ptrDMO);
565 // ----------------------------------------------------------------------------
566 // AudioDeviceWindowsCore() - dtor
567 // ----------------------------------------------------------------------------
569 AudioDeviceWindowsCore::~AudioDeviceWindowsCore()
571 WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, _id, "%s destroyed", __FUNCTION__);
575 // The IMMDeviceEnumerator is created during construction. Must release
576 // it here and not in Terminate() since we don't recreate it in Init().
577 SAFE_RELEASE(_ptrEnumerator);
579 _ptrAudioBuffer = NULL;
581 if (NULL != _hRenderSamplesReadyEvent)
583 CloseHandle(_hRenderSamplesReadyEvent);
584 _hRenderSamplesReadyEvent = NULL;
587 if (NULL != _hCaptureSamplesReadyEvent)
589 CloseHandle(_hCaptureSamplesReadyEvent);
590 _hCaptureSamplesReadyEvent = NULL;
593 if (NULL != _hRenderStartedEvent)
595 CloseHandle(_hRenderStartedEvent);
596 _hRenderStartedEvent = NULL;
599 if (NULL != _hCaptureStartedEvent)
601 CloseHandle(_hCaptureStartedEvent);
602 _hCaptureStartedEvent = NULL;
605 if (NULL != _hShutdownRenderEvent)
607 CloseHandle(_hShutdownRenderEvent);
608 _hShutdownRenderEvent = NULL;
611 if (NULL != _hShutdownCaptureEvent)
613 CloseHandle(_hShutdownCaptureEvent);
614 _hShutdownCaptureEvent = NULL;
617 if (NULL != _hSetCaptureVolumeEvent)
619 CloseHandle(_hSetCaptureVolumeEvent);
620 _hSetCaptureVolumeEvent = NULL;
625 BOOL freeOK = FreeLibrary(_avrtLibrary);
628 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
629 "AudioDeviceWindowsCore::~AudioDeviceWindowsCore() failed to free the loaded Avrt DLL module correctly");
633 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
634 "AudioDeviceWindowsCore::~AudioDeviceWindowsCore() the Avrt DLL module is now unloaded");
639 delete &_volumeMutex;
642 // ============================================================================
644 // ============================================================================
646 // ----------------------------------------------------------------------------
648 // ----------------------------------------------------------------------------
650 void AudioDeviceWindowsCore::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer)
653 _ptrAudioBuffer = audioBuffer;
655 // Inform the AudioBuffer about default settings for this implementation.
656 // Set all values to zero here since the actual settings will be done by
657 // InitPlayout and InitRecording later.
658 _ptrAudioBuffer->SetRecordingSampleRate(0);
659 _ptrAudioBuffer->SetPlayoutSampleRate(0);
660 _ptrAudioBuffer->SetRecordingChannels(0);
661 _ptrAudioBuffer->SetPlayoutChannels(0);
664 // ----------------------------------------------------------------------------
666 // ----------------------------------------------------------------------------
668 int32_t AudioDeviceWindowsCore::ActiveAudioLayer(AudioDeviceModule::AudioLayer& audioLayer) const
670 audioLayer = AudioDeviceModule::kWindowsCoreAudio;
674 // ----------------------------------------------------------------------------
676 // ----------------------------------------------------------------------------
678 int32_t AudioDeviceWindowsCore::Init()
681 CriticalSectionScoped lock(&_critSect);
693 // Enumerate all audio rendering and capturing endpoint devices.
694 // Note that, some of these will not be able to select by the user.
695 // The complete collection is for internal use only.
697 _EnumerateEndpointDevicesAll(eRender);
698 _EnumerateEndpointDevicesAll(eCapture);
705 // ----------------------------------------------------------------------------
707 // ----------------------------------------------------------------------------
709 int32_t AudioDeviceWindowsCore::Terminate()
712 CriticalSectionScoped lock(&_critSect);
718 _initialized = false;
719 _speakerIsInitialized = false;
720 _microphoneIsInitialized = false;
724 SAFE_RELEASE(_ptrRenderCollection);
725 SAFE_RELEASE(_ptrCaptureCollection);
726 SAFE_RELEASE(_ptrDeviceOut);
727 SAFE_RELEASE(_ptrDeviceIn);
728 SAFE_RELEASE(_ptrClientOut);
729 SAFE_RELEASE(_ptrClientIn);
730 SAFE_RELEASE(_ptrRenderClient);
731 SAFE_RELEASE(_ptrCaptureClient);
732 SAFE_RELEASE(_ptrCaptureVolume);
733 SAFE_RELEASE(_ptrRenderSimpleVolume);
738 // ----------------------------------------------------------------------------
740 // ----------------------------------------------------------------------------
742 bool AudioDeviceWindowsCore::Initialized() const
744 return (_initialized);
747 // ----------------------------------------------------------------------------
749 // ----------------------------------------------------------------------------
751 int32_t AudioDeviceWindowsCore::InitSpeaker()
754 CriticalSectionScoped lock(&_critSect);
761 if (_ptrDeviceOut == NULL)
766 if (_usingOutputDeviceIndex)
768 int16_t nDevices = PlayoutDevices();
769 if (_outputDeviceIndex > (nDevices - 1))
771 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "current device selection is invalid => unable to initialize");
778 SAFE_RELEASE(_ptrDeviceOut);
779 if (_usingOutputDeviceIndex)
781 // Refresh the selected rendering endpoint device using current index
782 ret = _GetListDevice(eRender, _outputDeviceIndex, &_ptrDeviceOut);
787 (_outputDevice == AudioDeviceModule::kDefaultDevice) ? role = eConsole : role = eCommunications;
788 // Refresh the selected rendering endpoint device using role
789 ret = _GetDefaultDevice(eRender, role, &_ptrDeviceOut);
792 if (ret != 0 || (_ptrDeviceOut == NULL))
794 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "failed to initialize the rendering enpoint device");
795 SAFE_RELEASE(_ptrDeviceOut);
799 IAudioSessionManager* pManager = NULL;
800 ret = _ptrDeviceOut->Activate(__uuidof(IAudioSessionManager),
804 if (ret != 0 || pManager == NULL)
806 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
807 " failed to initialize the render manager");
808 SAFE_RELEASE(pManager);
812 SAFE_RELEASE(_ptrRenderSimpleVolume);
813 ret = pManager->GetSimpleAudioVolume(NULL, FALSE, &_ptrRenderSimpleVolume);
814 if (ret != 0 || _ptrRenderSimpleVolume == NULL)
816 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
817 " failed to initialize the render simple volume");
818 SAFE_RELEASE(pManager);
819 SAFE_RELEASE(_ptrRenderSimpleVolume);
822 SAFE_RELEASE(pManager);
824 _speakerIsInitialized = true;
829 // ----------------------------------------------------------------------------
831 // ----------------------------------------------------------------------------
833 int32_t AudioDeviceWindowsCore::InitMicrophone()
836 CriticalSectionScoped lock(&_critSect);
843 if (_ptrDeviceIn == NULL)
848 if (_usingInputDeviceIndex)
850 int16_t nDevices = RecordingDevices();
851 if (_inputDeviceIndex > (nDevices - 1))
853 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "current device selection is invalid => unable to initialize");
860 SAFE_RELEASE(_ptrDeviceIn);
861 if (_usingInputDeviceIndex)
863 // Refresh the selected capture endpoint device using current index
864 ret = _GetListDevice(eCapture, _inputDeviceIndex, &_ptrDeviceIn);
869 (_inputDevice == AudioDeviceModule::kDefaultDevice) ? role = eConsole : role = eCommunications;
870 // Refresh the selected capture endpoint device using role
871 ret = _GetDefaultDevice(eCapture, role, &_ptrDeviceIn);
874 if (ret != 0 || (_ptrDeviceIn == NULL))
876 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "failed to initialize the capturing enpoint device");
877 SAFE_RELEASE(_ptrDeviceIn);
881 ret = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume),
884 reinterpret_cast<void **>(&_ptrCaptureVolume));
885 if (ret != 0 || _ptrCaptureVolume == NULL)
887 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
888 " failed to initialize the capture volume");
889 SAFE_RELEASE(_ptrCaptureVolume);
893 _microphoneIsInitialized = true;
898 // ----------------------------------------------------------------------------
899 // SpeakerIsInitialized
900 // ----------------------------------------------------------------------------
902 bool AudioDeviceWindowsCore::SpeakerIsInitialized() const
905 return (_speakerIsInitialized);
908 // ----------------------------------------------------------------------------
909 // MicrophoneIsInitialized
910 // ----------------------------------------------------------------------------
912 bool AudioDeviceWindowsCore::MicrophoneIsInitialized() const
915 return (_microphoneIsInitialized);
918 // ----------------------------------------------------------------------------
919 // SpeakerVolumeIsAvailable
920 // ----------------------------------------------------------------------------
922 int32_t AudioDeviceWindowsCore::SpeakerVolumeIsAvailable(bool& available)
925 CriticalSectionScoped lock(&_critSect);
927 if (_ptrDeviceOut == NULL)
933 IAudioSessionManager* pManager = NULL;
934 ISimpleAudioVolume* pVolume = NULL;
936 hr = _ptrDeviceOut->Activate(__uuidof(IAudioSessionManager), CLSCTX_ALL, NULL, (void**)&pManager);
939 hr = pManager->GetSimpleAudioVolume(NULL, FALSE, &pVolume);
943 hr = pVolume->GetMasterVolume(&volume);
950 SAFE_RELEASE(pManager);
951 SAFE_RELEASE(pVolume);
957 SAFE_RELEASE(pManager);
958 SAFE_RELEASE(pVolume);
962 // ----------------------------------------------------------------------------
964 // ----------------------------------------------------------------------------
966 int32_t AudioDeviceWindowsCore::SetSpeakerVolume(uint32_t volume)
970 CriticalSectionScoped lock(&_critSect);
972 if (!_speakerIsInitialized)
977 if (_ptrDeviceOut == NULL)
983 if (volume < (uint32_t)MIN_CORE_SPEAKER_VOLUME ||
984 volume > (uint32_t)MAX_CORE_SPEAKER_VOLUME)
991 // scale input volume to valid range (0.0 to 1.0)
992 const float fLevel = (float)volume/MAX_CORE_SPEAKER_VOLUME;
993 _volumeMutex.Enter();
994 hr = _ptrRenderSimpleVolume->SetMasterVolume(fLevel,NULL);
995 _volumeMutex.Leave();
1005 // ----------------------------------------------------------------------------
1007 // ----------------------------------------------------------------------------
1009 int32_t AudioDeviceWindowsCore::SpeakerVolume(uint32_t& volume) const
1013 CriticalSectionScoped lock(&_critSect);
1015 if (!_speakerIsInitialized)
1020 if (_ptrDeviceOut == NULL)
1029 _volumeMutex.Enter();
1030 hr = _ptrRenderSimpleVolume->GetMasterVolume(&fLevel);
1031 _volumeMutex.Leave();
1034 // scale input volume range [0.0,1.0] to valid output range
1035 volume = static_cast<uint32_t> (fLevel*MAX_CORE_SPEAKER_VOLUME);
1044 // ----------------------------------------------------------------------------
1046 // ----------------------------------------------------------------------------
1048 int32_t AudioDeviceWindowsCore::SetWaveOutVolume(uint16_t volumeLeft, uint16_t volumeRight)
1053 // ----------------------------------------------------------------------------
1055 // ----------------------------------------------------------------------------
1057 int32_t AudioDeviceWindowsCore::WaveOutVolume(uint16_t& volumeLeft, uint16_t& volumeRight) const
1062 // ----------------------------------------------------------------------------
1065 // The internal range for Core Audio is 0.0 to 1.0, where 0.0 indicates
1066 // silence and 1.0 indicates full volume (no attenuation).
1067 // We add our (webrtc-internal) own max level to match the Wave API and
1068 // how it is used today in VoE.
1069 // ----------------------------------------------------------------------------
1071 int32_t AudioDeviceWindowsCore::MaxSpeakerVolume(uint32_t& maxVolume) const
1074 if (!_speakerIsInitialized)
1079 maxVolume = static_cast<uint32_t> (MAX_CORE_SPEAKER_VOLUME);
1084 // ----------------------------------------------------------------------------
1086 // ----------------------------------------------------------------------------
1088 int32_t AudioDeviceWindowsCore::MinSpeakerVolume(uint32_t& minVolume) const
1091 if (!_speakerIsInitialized)
1096 minVolume = static_cast<uint32_t> (MIN_CORE_SPEAKER_VOLUME);
1101 // ----------------------------------------------------------------------------
1102 // SpeakerVolumeStepSize
1103 // ----------------------------------------------------------------------------
1105 int32_t AudioDeviceWindowsCore::SpeakerVolumeStepSize(uint16_t& stepSize) const
1108 if (!_speakerIsInitialized)
1113 stepSize = CORE_SPEAKER_VOLUME_STEP_SIZE;
1118 // ----------------------------------------------------------------------------
1119 // SpeakerMuteIsAvailable
1120 // ----------------------------------------------------------------------------
1122 int32_t AudioDeviceWindowsCore::SpeakerMuteIsAvailable(bool& available)
1125 CriticalSectionScoped lock(&_critSect);
1127 if (_ptrDeviceOut == NULL)
1133 IAudioEndpointVolume* pVolume = NULL;
1135 // Query the speaker system mute state.
1136 hr = _ptrDeviceOut->Activate(__uuidof(IAudioEndpointVolume),
1137 CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1141 hr = pVolume->GetMute(&mute);
1147 SAFE_RELEASE(pVolume);
1153 SAFE_RELEASE(pVolume);
1157 // ----------------------------------------------------------------------------
1159 // ----------------------------------------------------------------------------
1161 int32_t AudioDeviceWindowsCore::SetSpeakerMute(bool enable)
1164 CriticalSectionScoped lock(&_critSect);
1166 if (!_speakerIsInitialized)
1171 if (_ptrDeviceOut == NULL)
1177 IAudioEndpointVolume* pVolume = NULL;
1179 // Set the speaker system mute state.
1180 hr = _ptrDeviceOut->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1183 const BOOL mute(enable);
1184 hr = pVolume->SetMute(mute, NULL);
1187 SAFE_RELEASE(pVolume);
1193 SAFE_RELEASE(pVolume);
1197 // ----------------------------------------------------------------------------
1199 // ----------------------------------------------------------------------------
1201 int32_t AudioDeviceWindowsCore::SpeakerMute(bool& enabled) const
1204 if (!_speakerIsInitialized)
1209 if (_ptrDeviceOut == NULL)
1215 IAudioEndpointVolume* pVolume = NULL;
1217 // Query the speaker system mute state.
1218 hr = _ptrDeviceOut->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1222 hr = pVolume->GetMute(&mute);
1225 enabled = (mute == TRUE) ? true : false;
1227 SAFE_RELEASE(pVolume);
1233 SAFE_RELEASE(pVolume);
1237 // ----------------------------------------------------------------------------
1238 // MicrophoneMuteIsAvailable
1239 // ----------------------------------------------------------------------------
1241 int32_t AudioDeviceWindowsCore::MicrophoneMuteIsAvailable(bool& available)
1244 CriticalSectionScoped lock(&_critSect);
1246 if (_ptrDeviceIn == NULL)
1252 IAudioEndpointVolume* pVolume = NULL;
1254 // Query the microphone system mute state.
1255 hr = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1259 hr = pVolume->GetMute(&mute);
1265 SAFE_RELEASE(pVolume);
1270 SAFE_RELEASE(pVolume);
1274 // ----------------------------------------------------------------------------
1275 // SetMicrophoneMute
1276 // ----------------------------------------------------------------------------
1278 int32_t AudioDeviceWindowsCore::SetMicrophoneMute(bool enable)
1281 if (!_microphoneIsInitialized)
1286 if (_ptrDeviceIn == NULL)
1292 IAudioEndpointVolume* pVolume = NULL;
1294 // Set the microphone system mute state.
1295 hr = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1298 const BOOL mute(enable);
1299 hr = pVolume->SetMute(mute, NULL);
1302 SAFE_RELEASE(pVolume);
1307 SAFE_RELEASE(pVolume);
1311 // ----------------------------------------------------------------------------
1313 // ----------------------------------------------------------------------------
1315 int32_t AudioDeviceWindowsCore::MicrophoneMute(bool& enabled) const
1318 if (!_microphoneIsInitialized)
1324 IAudioEndpointVolume* pVolume = NULL;
1326 // Query the microphone system mute state.
1327 hr = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1331 hr = pVolume->GetMute(&mute);
1334 enabled = (mute == TRUE) ? true : false;
1336 SAFE_RELEASE(pVolume);
1341 SAFE_RELEASE(pVolume);
1345 // ----------------------------------------------------------------------------
1346 // MicrophoneBoostIsAvailable
1347 // ----------------------------------------------------------------------------
1349 int32_t AudioDeviceWindowsCore::MicrophoneBoostIsAvailable(bool& available)
1356 // ----------------------------------------------------------------------------
1357 // SetMicrophoneBoost
1358 // ----------------------------------------------------------------------------
1360 int32_t AudioDeviceWindowsCore::SetMicrophoneBoost(bool enable)
1363 if (!_microphoneIsInitialized)
1371 // ----------------------------------------------------------------------------
1373 // ----------------------------------------------------------------------------
1375 int32_t AudioDeviceWindowsCore::MicrophoneBoost(bool& enabled) const
1378 if (!_microphoneIsInitialized)
1386 // ----------------------------------------------------------------------------
1387 // StereoRecordingIsAvailable
1388 // ----------------------------------------------------------------------------
1390 int32_t AudioDeviceWindowsCore::StereoRecordingIsAvailable(bool& available)
1397 // ----------------------------------------------------------------------------
1398 // SetStereoRecording
1399 // ----------------------------------------------------------------------------
1401 int32_t AudioDeviceWindowsCore::SetStereoRecording(bool enable)
1404 CriticalSectionScoped lock(&_critSect);
1408 _recChannelsPrioList[0] = 2; // try stereo first
1409 _recChannelsPrioList[1] = 1;
1414 _recChannelsPrioList[0] = 1; // try mono first
1415 _recChannelsPrioList[1] = 2;
1422 // ----------------------------------------------------------------------------
1424 // ----------------------------------------------------------------------------
1426 int32_t AudioDeviceWindowsCore::StereoRecording(bool& enabled) const
1429 if (_recChannels == 2)
1437 // ----------------------------------------------------------------------------
1438 // StereoPlayoutIsAvailable
1439 // ----------------------------------------------------------------------------
1441 int32_t AudioDeviceWindowsCore::StereoPlayoutIsAvailable(bool& available)
1448 // ----------------------------------------------------------------------------
1450 // ----------------------------------------------------------------------------
1452 int32_t AudioDeviceWindowsCore::SetStereoPlayout(bool enable)
1455 CriticalSectionScoped lock(&_critSect);
1459 _playChannelsPrioList[0] = 2; // try stereo first
1460 _playChannelsPrioList[1] = 1;
1465 _playChannelsPrioList[0] = 1; // try mono first
1466 _playChannelsPrioList[1] = 2;
1473 // ----------------------------------------------------------------------------
1475 // ----------------------------------------------------------------------------
1477 int32_t AudioDeviceWindowsCore::StereoPlayout(bool& enabled) const
1480 if (_playChannels == 2)
1488 // ----------------------------------------------------------------------------
1490 // ----------------------------------------------------------------------------
1492 int32_t AudioDeviceWindowsCore::SetAGC(bool enable)
1494 CriticalSectionScoped lock(&_critSect);
1499 // ----------------------------------------------------------------------------
1501 // ----------------------------------------------------------------------------
1503 bool AudioDeviceWindowsCore::AGC() const
1505 CriticalSectionScoped lock(&_critSect);
1509 // ----------------------------------------------------------------------------
1510 // MicrophoneVolumeIsAvailable
1511 // ----------------------------------------------------------------------------
1513 int32_t AudioDeviceWindowsCore::MicrophoneVolumeIsAvailable(bool& available)
1516 CriticalSectionScoped lock(&_critSect);
1518 if (_ptrDeviceIn == NULL)
1524 IAudioEndpointVolume* pVolume = NULL;
1526 hr = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1530 hr = pVolume->GetMasterVolumeLevelScalar(&volume);
1537 SAFE_RELEASE(pVolume);
1542 SAFE_RELEASE(pVolume);
1546 // ----------------------------------------------------------------------------
1547 // SetMicrophoneVolume
1548 // ----------------------------------------------------------------------------
1550 int32_t AudioDeviceWindowsCore::SetMicrophoneVolume(uint32_t volume)
1552 WEBRTC_TRACE(kTraceStream, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::SetMicrophoneVolume(volume=%u)", volume);
1555 CriticalSectionScoped lock(&_critSect);
1557 if (!_microphoneIsInitialized)
1562 if (_ptrDeviceIn == NULL)
1568 if (volume < static_cast<uint32_t>(MIN_CORE_MICROPHONE_VOLUME) ||
1569 volume > static_cast<uint32_t>(MAX_CORE_MICROPHONE_VOLUME))
1575 // scale input volume to valid range (0.0 to 1.0)
1576 const float fLevel = static_cast<float>(volume)/MAX_CORE_MICROPHONE_VOLUME;
1577 _volumeMutex.Enter();
1578 _ptrCaptureVolume->SetMasterVolumeLevelScalar(fLevel, NULL);
1579 _volumeMutex.Leave();
1589 // ----------------------------------------------------------------------------
1591 // ----------------------------------------------------------------------------
1593 int32_t AudioDeviceWindowsCore::MicrophoneVolume(uint32_t& volume) const
1596 CriticalSectionScoped lock(&_critSect);
1598 if (!_microphoneIsInitialized)
1603 if (_ptrDeviceIn == NULL)
1612 _volumeMutex.Enter();
1613 hr = _ptrCaptureVolume->GetMasterVolumeLevelScalar(&fLevel);
1614 _volumeMutex.Leave();
1617 // scale input volume range [0.0,1.0] to valid output range
1618 volume = static_cast<uint32_t> (fLevel*MAX_CORE_MICROPHONE_VOLUME);
1627 // ----------------------------------------------------------------------------
1628 // MaxMicrophoneVolume
1630 // The internal range for Core Audio is 0.0 to 1.0, where 0.0 indicates
1631 // silence and 1.0 indicates full volume (no attenuation).
1632 // We add our (webrtc-internal) own max level to match the Wave API and
1633 // how it is used today in VoE.
1634 // ----------------------------------------------------------------------------
1636 int32_t AudioDeviceWindowsCore::MaxMicrophoneVolume(uint32_t& maxVolume) const
1638 WEBRTC_TRACE(kTraceStream, kTraceAudioDevice, _id, "%s", __FUNCTION__);
1640 if (!_microphoneIsInitialized)
1645 maxVolume = static_cast<uint32_t> (MAX_CORE_MICROPHONE_VOLUME);
1650 // ----------------------------------------------------------------------------
1651 // MinMicrophoneVolume
1652 // ----------------------------------------------------------------------------
1654 int32_t AudioDeviceWindowsCore::MinMicrophoneVolume(uint32_t& minVolume) const
1657 if (!_microphoneIsInitialized)
1662 minVolume = static_cast<uint32_t> (MIN_CORE_MICROPHONE_VOLUME);
1667 // ----------------------------------------------------------------------------
1668 // MicrophoneVolumeStepSize
1669 // ----------------------------------------------------------------------------
1671 int32_t AudioDeviceWindowsCore::MicrophoneVolumeStepSize(uint16_t& stepSize) const
1674 if (!_microphoneIsInitialized)
1679 stepSize = CORE_MICROPHONE_VOLUME_STEP_SIZE;
1684 // ----------------------------------------------------------------------------
1686 // ----------------------------------------------------------------------------
1688 int16_t AudioDeviceWindowsCore::PlayoutDevices()
1691 CriticalSectionScoped lock(&_critSect);
1693 if (_RefreshDeviceList(eRender) != -1)
1695 return (_DeviceListCount(eRender));
1701 // ----------------------------------------------------------------------------
1702 // SetPlayoutDevice I (II)
1703 // ----------------------------------------------------------------------------
1705 int32_t AudioDeviceWindowsCore::SetPlayoutDevice(uint16_t index)
1708 if (_playIsInitialized)
1713 // Get current number of available rendering endpoint devices and refresh the rendering collection.
1714 UINT nDevices = PlayoutDevices();
1716 if (index < 0 || index > (nDevices-1))
1718 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "device index is out of range [0,%u]", (nDevices-1));
1722 CriticalSectionScoped lock(&_critSect);
1726 assert(_ptrRenderCollection != NULL);
1728 // Select an endpoint rendering device given the specified index
1729 SAFE_RELEASE(_ptrDeviceOut);
1730 hr = _ptrRenderCollection->Item(
1736 SAFE_RELEASE(_ptrDeviceOut);
1740 WCHAR szDeviceName[MAX_PATH];
1741 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
1743 // Get the endpoint device's friendly-name
1744 if (_GetDeviceName(_ptrDeviceOut, szDeviceName, bufferLen) == 0)
1746 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", szDeviceName);
1749 _usingOutputDeviceIndex = true;
1750 _outputDeviceIndex = index;
1755 // ----------------------------------------------------------------------------
1756 // SetPlayoutDevice II (II)
1757 // ----------------------------------------------------------------------------
1759 int32_t AudioDeviceWindowsCore::SetPlayoutDevice(AudioDeviceModule::WindowsDeviceType device)
1761 if (_playIsInitialized)
1766 ERole role(eCommunications);
1768 if (device == AudioDeviceModule::kDefaultDevice)
1772 else if (device == AudioDeviceModule::kDefaultCommunicationDevice)
1774 role = eCommunications;
1777 CriticalSectionScoped lock(&_critSect);
1779 // Refresh the list of rendering endpoint devices
1780 _RefreshDeviceList(eRender);
1784 assert(_ptrEnumerator != NULL);
1786 // Select an endpoint rendering device given the specified role
1787 SAFE_RELEASE(_ptrDeviceOut);
1788 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
1795 SAFE_RELEASE(_ptrDeviceOut);
1799 WCHAR szDeviceName[MAX_PATH];
1800 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
1802 // Get the endpoint device's friendly-name
1803 if (_GetDeviceName(_ptrDeviceOut, szDeviceName, bufferLen) == 0)
1805 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", szDeviceName);
1808 _usingOutputDeviceIndex = false;
1809 _outputDevice = device;
1814 // ----------------------------------------------------------------------------
1815 // PlayoutDeviceName
1816 // ----------------------------------------------------------------------------
1818 int32_t AudioDeviceWindowsCore::PlayoutDeviceName(
1820 char name[kAdmMaxDeviceNameSize],
1821 char guid[kAdmMaxGuidSize])
1824 bool defaultCommunicationDevice(false);
1825 const int16_t nDevices(PlayoutDevices()); // also updates the list of devices
1827 // Special fix for the case when the user selects '-1' as index (<=> Default Communication Device)
1828 if (index == (uint16_t)(-1))
1830 defaultCommunicationDevice = true;
1832 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Default Communication endpoint device will be used");
1835 if ((index > (nDevices-1)) || (name == NULL))
1840 memset(name, 0, kAdmMaxDeviceNameSize);
1844 memset(guid, 0, kAdmMaxGuidSize);
1847 CriticalSectionScoped lock(&_critSect);
1850 WCHAR szDeviceName[MAX_PATH];
1851 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
1853 // Get the endpoint device's friendly-name
1854 if (defaultCommunicationDevice)
1856 ret = _GetDefaultDeviceName(eRender, eCommunications, szDeviceName, bufferLen);
1860 ret = _GetListDeviceName(eRender, index, szDeviceName, bufferLen);
1865 // Convert the endpoint device's friendly-name to UTF-8
1866 if (WideCharToMultiByte(CP_UTF8, 0, szDeviceName, -1, name, kAdmMaxDeviceNameSize, NULL, NULL) == 0)
1868 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d", GetLastError());
1872 // Get the endpoint ID string (uniquely identifies the device among all audio endpoint devices)
1873 if (defaultCommunicationDevice)
1875 ret = _GetDefaultDeviceID(eRender, eCommunications, szDeviceName, bufferLen);
1879 ret = _GetListDeviceID(eRender, index, szDeviceName, bufferLen);
1882 if (guid != NULL && ret == 0)
1884 // Convert the endpoint device's ID string to UTF-8
1885 if (WideCharToMultiByte(CP_UTF8, 0, szDeviceName, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1887 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d", GetLastError());
1894 // ----------------------------------------------------------------------------
1895 // RecordingDeviceName
1896 // ----------------------------------------------------------------------------
1898 int32_t AudioDeviceWindowsCore::RecordingDeviceName(
1900 char name[kAdmMaxDeviceNameSize],
1901 char guid[kAdmMaxGuidSize])
1904 bool defaultCommunicationDevice(false);
1905 const int16_t nDevices(RecordingDevices()); // also updates the list of devices
1907 // Special fix for the case when the user selects '-1' as index (<=> Default Communication Device)
1908 if (index == (uint16_t)(-1))
1910 defaultCommunicationDevice = true;
1912 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Default Communication endpoint device will be used");
1915 if ((index > (nDevices-1)) || (name == NULL))
1920 memset(name, 0, kAdmMaxDeviceNameSize);
1924 memset(guid, 0, kAdmMaxGuidSize);
1927 CriticalSectionScoped lock(&_critSect);
1930 WCHAR szDeviceName[MAX_PATH];
1931 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
1933 // Get the endpoint device's friendly-name
1934 if (defaultCommunicationDevice)
1936 ret = _GetDefaultDeviceName(eCapture, eCommunications, szDeviceName, bufferLen);
1940 ret = _GetListDeviceName(eCapture, index, szDeviceName, bufferLen);
1945 // Convert the endpoint device's friendly-name to UTF-8
1946 if (WideCharToMultiByte(CP_UTF8, 0, szDeviceName, -1, name, kAdmMaxDeviceNameSize, NULL, NULL) == 0)
1948 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d", GetLastError());
1952 // Get the endpoint ID string (uniquely identifies the device among all audio endpoint devices)
1953 if (defaultCommunicationDevice)
1955 ret = _GetDefaultDeviceID(eCapture, eCommunications, szDeviceName, bufferLen);
1959 ret = _GetListDeviceID(eCapture, index, szDeviceName, bufferLen);
1962 if (guid != NULL && ret == 0)
1964 // Convert the endpoint device's ID string to UTF-8
1965 if (WideCharToMultiByte(CP_UTF8, 0, szDeviceName, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1967 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d", GetLastError());
1974 // ----------------------------------------------------------------------------
1976 // ----------------------------------------------------------------------------
1978 int16_t AudioDeviceWindowsCore::RecordingDevices()
1981 CriticalSectionScoped lock(&_critSect);
1983 if (_RefreshDeviceList(eCapture) != -1)
1985 return (_DeviceListCount(eCapture));
1991 // ----------------------------------------------------------------------------
1992 // SetRecordingDevice I (II)
1993 // ----------------------------------------------------------------------------
1995 int32_t AudioDeviceWindowsCore::SetRecordingDevice(uint16_t index)
1998 if (_recIsInitialized)
2003 // Get current number of available capture endpoint devices and refresh the capture collection.
2004 UINT nDevices = RecordingDevices();
2006 if (index < 0 || index > (nDevices-1))
2008 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "device index is out of range [0,%u]", (nDevices-1));
2012 CriticalSectionScoped lock(&_critSect);
2016 assert(_ptrCaptureCollection != NULL);
2018 // Select an endpoint capture device given the specified index
2019 SAFE_RELEASE(_ptrDeviceIn);
2020 hr = _ptrCaptureCollection->Item(
2026 SAFE_RELEASE(_ptrDeviceIn);
2030 WCHAR szDeviceName[MAX_PATH];
2031 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
2033 // Get the endpoint device's friendly-name
2034 if (_GetDeviceName(_ptrDeviceIn, szDeviceName, bufferLen) == 0)
2036 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", szDeviceName);
2039 _usingInputDeviceIndex = true;
2040 _inputDeviceIndex = index;
2045 // ----------------------------------------------------------------------------
2046 // SetRecordingDevice II (II)
2047 // ----------------------------------------------------------------------------
2049 int32_t AudioDeviceWindowsCore::SetRecordingDevice(AudioDeviceModule::WindowsDeviceType device)
2051 if (_recIsInitialized)
2056 ERole role(eCommunications);
2058 if (device == AudioDeviceModule::kDefaultDevice)
2062 else if (device == AudioDeviceModule::kDefaultCommunicationDevice)
2064 role = eCommunications;
2067 CriticalSectionScoped lock(&_critSect);
2069 // Refresh the list of capture endpoint devices
2070 _RefreshDeviceList(eCapture);
2074 assert(_ptrEnumerator != NULL);
2076 // Select an endpoint capture device given the specified role
2077 SAFE_RELEASE(_ptrDeviceIn);
2078 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
2085 SAFE_RELEASE(_ptrDeviceIn);
2089 WCHAR szDeviceName[MAX_PATH];
2090 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
2092 // Get the endpoint device's friendly-name
2093 if (_GetDeviceName(_ptrDeviceIn, szDeviceName, bufferLen) == 0)
2095 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", szDeviceName);
2098 _usingInputDeviceIndex = false;
2099 _inputDevice = device;
2104 // ----------------------------------------------------------------------------
2105 // PlayoutIsAvailable
2106 // ----------------------------------------------------------------------------
2108 int32_t AudioDeviceWindowsCore::PlayoutIsAvailable(bool& available)
2113 // Try to initialize the playout side
2114 int32_t res = InitPlayout();
2116 // Cancel effect of initialization
2127 // ----------------------------------------------------------------------------
2128 // RecordingIsAvailable
2129 // ----------------------------------------------------------------------------
2131 int32_t AudioDeviceWindowsCore::RecordingIsAvailable(bool& available)
2136 // Try to initialize the recording side
2137 int32_t res = InitRecording();
2139 // Cancel effect of initialization
2150 // ----------------------------------------------------------------------------
2152 // ----------------------------------------------------------------------------
2154 int32_t AudioDeviceWindowsCore::InitPlayout()
2157 CriticalSectionScoped lock(&_critSect);
2164 if (_playIsInitialized)
2169 if (_ptrDeviceOut == NULL)
2174 // Initialize the speaker (devices might have been added or removed)
2175 if (InitSpeaker() == -1)
2177 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "InitSpeaker() failed");
2180 // Ensure that the updated rendering endpoint device is valid
2181 if (_ptrDeviceOut == NULL)
2186 if (_builtInAecEnabled && _recIsInitialized)
2188 // Ensure the correct render device is configured in case
2189 // InitRecording() was called before InitPlayout().
2190 if (SetDMOProperties() == -1)
2197 WAVEFORMATEX* pWfxOut = NULL;
2198 WAVEFORMATEX Wfx = WAVEFORMATEX();
2199 WAVEFORMATEX* pWfxClosestMatch = NULL;
2201 // Create COM object with IAudioClient interface.
2202 SAFE_RELEASE(_ptrClientOut);
2203 hr = _ptrDeviceOut->Activate(
2204 __uuidof(IAudioClient),
2207 (void**)&_ptrClientOut);
2210 // Retrieve the stream format that the audio engine uses for its internal
2211 // processing (mixing) of shared-mode streams.
2212 hr = _ptrClientOut->GetMixFormat(&pWfxOut);
2215 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Audio Engine's current rendering mix format:");
2217 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wFormatTag : 0x%X (%u)", pWfxOut->wFormatTag, pWfxOut->wFormatTag);
2218 // number of channels (i.e. mono, stereo...)
2219 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels : %d", pWfxOut->nChannels);
2221 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nSamplesPerSec : %d", pWfxOut->nSamplesPerSec);
2222 // for buffer estimation
2223 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nAvgBytesPerSec: %d", pWfxOut->nAvgBytesPerSec);
2224 // block size of data
2225 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nBlockAlign : %d", pWfxOut->nBlockAlign);
2226 // number of bits per sample of mono data
2227 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wBitsPerSample : %d", pWfxOut->wBitsPerSample);
2228 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "cbSize : %d", pWfxOut->cbSize);
2232 Wfx.wFormatTag = WAVE_FORMAT_PCM;
2233 Wfx.wBitsPerSample = 16;
2236 const int freqs[] = {48000, 44100, 16000, 96000, 32000, 8000};
2239 // Iterate over frequencies and channels, in order of priority
2240 for (int freq = 0; freq < sizeof(freqs)/sizeof(freqs[0]); freq++)
2242 for (int chan = 0; chan < sizeof(_playChannelsPrioList)/sizeof(_playChannelsPrioList[0]); chan++)
2244 Wfx.nChannels = _playChannelsPrioList[chan];
2245 Wfx.nSamplesPerSec = freqs[freq];
2246 Wfx.nBlockAlign = Wfx.nChannels * Wfx.wBitsPerSample / 8;
2247 Wfx.nAvgBytesPerSec = Wfx.nSamplesPerSec * Wfx.nBlockAlign;
2248 // If the method succeeds and the audio endpoint device supports the specified stream format,
2249 // it returns S_OK. If the method succeeds and provides a closest match to the specified format,
2250 // it returns S_FALSE.
2251 hr = _ptrClientOut->IsFormatSupported(
2252 AUDCLNT_SHAREMODE_SHARED,
2261 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels=%d, nSamplesPerSec=%d is not supported",
2262 Wfx.nChannels, Wfx.nSamplesPerSec);
2269 // TODO(andrew): what happens in the event of failure in the above loop?
2270 // Is _ptrClientOut->Initialize expected to fail?
2271 // Same in InitRecording().
2274 _playAudioFrameSize = Wfx.nBlockAlign;
2275 _playBlockSize = Wfx.nSamplesPerSec/100;
2276 _playSampleRate = Wfx.nSamplesPerSec;
2277 _devicePlaySampleRate = Wfx.nSamplesPerSec; // The device itself continues to run at 44.1 kHz.
2278 _devicePlayBlockSize = Wfx.nSamplesPerSec/100;
2279 _playChannels = Wfx.nChannels;
2281 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "VoE selected this rendering format:");
2282 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wFormatTag : 0x%X (%u)", Wfx.wFormatTag, Wfx.wFormatTag);
2283 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels : %d", Wfx.nChannels);
2284 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nSamplesPerSec : %d", Wfx.nSamplesPerSec);
2285 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nAvgBytesPerSec : %d", Wfx.nAvgBytesPerSec);
2286 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nBlockAlign : %d", Wfx.nBlockAlign);
2287 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wBitsPerSample : %d", Wfx.wBitsPerSample);
2288 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "cbSize : %d", Wfx.cbSize);
2289 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Additional settings:");
2290 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_playAudioFrameSize: %d", _playAudioFrameSize);
2291 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_playBlockSize : %d", _playBlockSize);
2292 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_playChannels : %d", _playChannels);
2295 // Create a rendering stream.
2297 // ****************************************************************************
2298 // For a shared-mode stream that uses event-driven buffering, the caller must
2299 // set both hnsPeriodicity and hnsBufferDuration to 0. The Initialize method
2300 // determines how large a buffer to allocate based on the scheduling period
2301 // of the audio engine. Although the client's buffer processing thread is
2302 // event driven, the basic buffer management process, as described previously,
2304 // Each time the thread awakens, it should call IAudioClient::GetCurrentPadding
2305 // to determine how much data to write to a rendering buffer or read from a capture
2306 // buffer. In contrast to the two buffers that the Initialize method allocates
2307 // for an exclusive-mode stream that uses event-driven buffering, a shared-mode
2308 // stream requires a single buffer.
2309 // ****************************************************************************
2311 REFERENCE_TIME hnsBufferDuration = 0; // ask for minimum buffer size (default)
2312 if (_devicePlaySampleRate == 44100)
2314 // Ask for a larger buffer size (30ms) when using 44.1kHz as render rate.
2315 // There seems to be a larger risk of underruns for 44.1 compared
2316 // with the default rate (48kHz). When using default, we set the requested
2317 // buffer duration to 0, which sets the buffer to the minimum size
2318 // required by the engine thread. The actual buffer size can then be
2319 // read by GetBufferSize() and it is 20ms on most machines.
2320 hnsBufferDuration = 30*10000;
2322 hr = _ptrClientOut->Initialize(
2323 AUDCLNT_SHAREMODE_SHARED, // share Audio Engine with other applications
2324 AUDCLNT_STREAMFLAGS_EVENTCALLBACK, // processing of the audio buffer by the client will be event driven
2325 hnsBufferDuration, // requested buffer capacity as a time value (in 100-nanosecond units)
2327 &Wfx, // selected wave format
2328 NULL); // session GUID
2332 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "IAudioClient::Initialize() failed:");
2333 if (pWfxClosestMatch != NULL)
2335 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "closest mix format: #channels=%d, samples/sec=%d, bits/sample=%d",
2336 pWfxClosestMatch->nChannels, pWfxClosestMatch->nSamplesPerSec, pWfxClosestMatch->wBitsPerSample);
2340 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "no format suggested");
2345 if (_ptrAudioBuffer)
2347 // Update the audio buffer with the selected parameters
2348 _ptrAudioBuffer->SetPlayoutSampleRate(_playSampleRate);
2349 _ptrAudioBuffer->SetPlayoutChannels((uint8_t)_playChannels);
2353 // We can enter this state during CoreAudioIsSupported() when no AudioDeviceImplementation
2354 // has been created, hence the AudioDeviceBuffer does not exist.
2355 // It is OK to end up here since we don't initiate any media in CoreAudioIsSupported().
2356 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceBuffer must be attached before streaming can start");
2359 // Get the actual size of the shared (endpoint buffer).
2360 // Typical value is 960 audio frames <=> 20ms @ 48kHz sample rate.
2361 UINT bufferFrameCount(0);
2362 hr = _ptrClientOut->GetBufferSize(
2366 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "IAudioClient::GetBufferSize() => %u (<=> %u bytes)",
2367 bufferFrameCount, bufferFrameCount*_playAudioFrameSize);
2370 // Set the event handle that the system signals when an audio buffer is ready
2371 // to be processed by the client.
2372 hr = _ptrClientOut->SetEventHandle(
2373 _hRenderSamplesReadyEvent);
2376 // Get an IAudioRenderClient interface.
2377 SAFE_RELEASE(_ptrRenderClient);
2378 hr = _ptrClientOut->GetService(
2379 __uuidof(IAudioRenderClient),
2380 (void**)&_ptrRenderClient);
2383 // Mark playout side as initialized
2384 _playIsInitialized = true;
2386 CoTaskMemFree(pWfxOut);
2387 CoTaskMemFree(pWfxClosestMatch);
2389 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "render side is now initialized");
2394 CoTaskMemFree(pWfxOut);
2395 CoTaskMemFree(pWfxClosestMatch);
2396 SAFE_RELEASE(_ptrClientOut);
2397 SAFE_RELEASE(_ptrRenderClient);
2401 // Capture initialization when the built-in AEC DirectX Media Object (DMO) is
2402 // used. Called from InitRecording(), most of which is skipped over. The DMO
2403 // handles device initialization itself.
2404 // Reference: http://msdn.microsoft.com/en-us/library/ff819492(v=vs.85).aspx
2405 int32_t AudioDeviceWindowsCore::InitRecordingDMO()
2407 assert(_builtInAecEnabled);
2408 assert(_dmo != NULL);
2410 if (SetDMOProperties() == -1)
2415 DMO_MEDIA_TYPE mt = {0};
2416 HRESULT hr = MoInitMediaType(&mt, sizeof(WAVEFORMATEX));
2419 MoFreeMediaType(&mt);
2423 mt.majortype = MEDIATYPE_Audio;
2424 mt.subtype = MEDIASUBTYPE_PCM;
2425 mt.formattype = FORMAT_WaveFormatEx;
2427 // Supported formats
2428 // nChannels: 1 (in AEC-only mode)
2429 // nSamplesPerSec: 8000, 11025, 16000, 22050
2430 // wBitsPerSample: 16
2431 WAVEFORMATEX* ptrWav = reinterpret_cast<WAVEFORMATEX*>(mt.pbFormat);
2432 ptrWav->wFormatTag = WAVE_FORMAT_PCM;
2433 ptrWav->nChannels = 1;
2434 // 16000 is the highest we can support with our resampler.
2435 ptrWav->nSamplesPerSec = 16000;
2436 ptrWav->nAvgBytesPerSec = 32000;
2437 ptrWav->nBlockAlign = 2;
2438 ptrWav->wBitsPerSample = 16;
2441 // Set the VoE format equal to the AEC output format.
2442 _recAudioFrameSize = ptrWav->nBlockAlign;
2443 _recSampleRate = ptrWav->nSamplesPerSec;
2444 _recBlockSize = ptrWav->nSamplesPerSec / 100;
2445 _recChannels = ptrWav->nChannels;
2447 // Set the DMO output format parameters.
2448 hr = _dmo->SetOutputType(kAecCaptureStreamIndex, &mt, 0);
2449 MoFreeMediaType(&mt);
2456 if (_ptrAudioBuffer)
2458 _ptrAudioBuffer->SetRecordingSampleRate(_recSampleRate);
2459 _ptrAudioBuffer->SetRecordingChannels(_recChannels);
2463 // Refer to InitRecording() for comments.
2464 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2465 "AudioDeviceBuffer must be attached before streaming can start");
2468 _mediaBuffer = new MediaBufferImpl(_recBlockSize * _recAudioFrameSize);
2470 // Optional, but if called, must be after media types are set.
2471 hr = _dmo->AllocateStreamingResources();
2478 _recIsInitialized = true;
2479 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2480 "Capture side is now initialized");
2485 // ----------------------------------------------------------------------------
2487 // ----------------------------------------------------------------------------
2489 int32_t AudioDeviceWindowsCore::InitRecording()
2492 CriticalSectionScoped lock(&_critSect);
2499 if (_recIsInitialized)
2504 if (QueryPerformanceFrequency(&_perfCounterFreq) == 0)
2508 _perfCounterFactor = 10000000.0 / (double)_perfCounterFreq.QuadPart;
2510 if (_ptrDeviceIn == NULL)
2515 // Initialize the microphone (devices might have been added or removed)
2516 if (InitMicrophone() == -1)
2518 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "InitMicrophone() failed");
2521 // Ensure that the updated capturing endpoint device is valid
2522 if (_ptrDeviceIn == NULL)
2527 if (_builtInAecEnabled)
2529 // The DMO will configure the capture device.
2530 return InitRecordingDMO();
2534 WAVEFORMATEX* pWfxIn = NULL;
2535 WAVEFORMATEX Wfx = WAVEFORMATEX();
2536 WAVEFORMATEX* pWfxClosestMatch = NULL;
2538 // Create COM object with IAudioClient interface.
2539 SAFE_RELEASE(_ptrClientIn);
2540 hr = _ptrDeviceIn->Activate(
2541 __uuidof(IAudioClient),
2544 (void**)&_ptrClientIn);
2547 // Retrieve the stream format that the audio engine uses for its internal
2548 // processing (mixing) of shared-mode streams.
2549 hr = _ptrClientIn->GetMixFormat(&pWfxIn);
2552 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Audio Engine's current capturing mix format:");
2554 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wFormatTag : 0x%X (%u)", pWfxIn->wFormatTag, pWfxIn->wFormatTag);
2555 // number of channels (i.e. mono, stereo...)
2556 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels : %d", pWfxIn->nChannels);
2558 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nSamplesPerSec : %d", pWfxIn->nSamplesPerSec);
2559 // for buffer estimation
2560 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nAvgBytesPerSec: %d", pWfxIn->nAvgBytesPerSec);
2561 // block size of data
2562 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nBlockAlign : %d", pWfxIn->nBlockAlign);
2563 // number of bits per sample of mono data
2564 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wBitsPerSample : %d", pWfxIn->wBitsPerSample);
2565 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "cbSize : %d", pWfxIn->cbSize);
2569 Wfx.wFormatTag = WAVE_FORMAT_PCM;
2570 Wfx.wBitsPerSample = 16;
2573 const int freqs[6] = {48000, 44100, 16000, 96000, 32000, 8000};
2576 // Iterate over frequencies and channels, in order of priority
2577 for (int freq = 0; freq < sizeof(freqs)/sizeof(freqs[0]); freq++)
2579 for (int chan = 0; chan < sizeof(_recChannelsPrioList)/sizeof(_recChannelsPrioList[0]); chan++)
2581 Wfx.nChannels = _recChannelsPrioList[chan];
2582 Wfx.nSamplesPerSec = freqs[freq];
2583 Wfx.nBlockAlign = Wfx.nChannels * Wfx.wBitsPerSample / 8;
2584 Wfx.nAvgBytesPerSec = Wfx.nSamplesPerSec * Wfx.nBlockAlign;
2585 // If the method succeeds and the audio endpoint device supports the specified stream format,
2586 // it returns S_OK. If the method succeeds and provides a closest match to the specified format,
2587 // it returns S_FALSE.
2588 hr = _ptrClientIn->IsFormatSupported(
2589 AUDCLNT_SHAREMODE_SHARED,
2598 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels=%d, nSamplesPerSec=%d is not supported",
2599 Wfx.nChannels, Wfx.nSamplesPerSec);
2608 _recAudioFrameSize = Wfx.nBlockAlign;
2609 _recSampleRate = Wfx.nSamplesPerSec;
2610 _recBlockSize = Wfx.nSamplesPerSec/100;
2611 _recChannels = Wfx.nChannels;
2613 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "VoE selected this capturing format:");
2614 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wFormatTag : 0x%X (%u)", Wfx.wFormatTag, Wfx.wFormatTag);
2615 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels : %d", Wfx.nChannels);
2616 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nSamplesPerSec : %d", Wfx.nSamplesPerSec);
2617 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nAvgBytesPerSec : %d", Wfx.nAvgBytesPerSec);
2618 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nBlockAlign : %d", Wfx.nBlockAlign);
2619 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wBitsPerSample : %d", Wfx.wBitsPerSample);
2620 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "cbSize : %d", Wfx.cbSize);
2621 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Additional settings:");
2622 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_recAudioFrameSize: %d", _recAudioFrameSize);
2623 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_recBlockSize : %d", _recBlockSize);
2624 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_recChannels : %d", _recChannels);
2627 // Create a capturing stream.
2628 hr = _ptrClientIn->Initialize(
2629 AUDCLNT_SHAREMODE_SHARED, // share Audio Engine with other applications
2630 AUDCLNT_STREAMFLAGS_EVENTCALLBACK | // processing of the audio buffer by the client will be event driven
2631 AUDCLNT_STREAMFLAGS_NOPERSIST, // volume and mute settings for an audio session will not persist across system restarts
2632 0, // required for event-driven shared mode
2634 &Wfx, // selected wave format
2635 NULL); // session GUID
2640 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "IAudioClient::Initialize() failed:");
2641 if (pWfxClosestMatch != NULL)
2643 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "closest mix format: #channels=%d, samples/sec=%d, bits/sample=%d",
2644 pWfxClosestMatch->nChannels, pWfxClosestMatch->nSamplesPerSec, pWfxClosestMatch->wBitsPerSample);
2648 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "no format suggested");
2653 if (_ptrAudioBuffer)
2655 // Update the audio buffer with the selected parameters
2656 _ptrAudioBuffer->SetRecordingSampleRate(_recSampleRate);
2657 _ptrAudioBuffer->SetRecordingChannels((uint8_t)_recChannels);
2661 // We can enter this state during CoreAudioIsSupported() when no AudioDeviceImplementation
2662 // has been created, hence the AudioDeviceBuffer does not exist.
2663 // It is OK to end up here since we don't initiate any media in CoreAudioIsSupported().
2664 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceBuffer must be attached before streaming can start");
2667 // Get the actual size of the shared (endpoint buffer).
2668 // Typical value is 960 audio frames <=> 20ms @ 48kHz sample rate.
2669 UINT bufferFrameCount(0);
2670 hr = _ptrClientIn->GetBufferSize(
2674 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "IAudioClient::GetBufferSize() => %u (<=> %u bytes)",
2675 bufferFrameCount, bufferFrameCount*_recAudioFrameSize);
2678 // Set the event handle that the system signals when an audio buffer is ready
2679 // to be processed by the client.
2680 hr = _ptrClientIn->SetEventHandle(
2681 _hCaptureSamplesReadyEvent);
2684 // Get an IAudioCaptureClient interface.
2685 SAFE_RELEASE(_ptrCaptureClient);
2686 hr = _ptrClientIn->GetService(
2687 __uuidof(IAudioCaptureClient),
2688 (void**)&_ptrCaptureClient);
2691 // Mark capture side as initialized
2692 _recIsInitialized = true;
2694 CoTaskMemFree(pWfxIn);
2695 CoTaskMemFree(pWfxClosestMatch);
2697 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "capture side is now initialized");
2702 CoTaskMemFree(pWfxIn);
2703 CoTaskMemFree(pWfxClosestMatch);
2704 SAFE_RELEASE(_ptrClientIn);
2705 SAFE_RELEASE(_ptrCaptureClient);
2709 // ----------------------------------------------------------------------------
2711 // ----------------------------------------------------------------------------
2713 int32_t AudioDeviceWindowsCore::StartRecording()
2716 if (!_recIsInitialized)
2721 if (_hRecThread != NULL)
2732 CriticalSectionScoped critScoped(&_critSect);
2734 // Create thread which will drive the capturing
2735 LPTHREAD_START_ROUTINE lpStartAddress = WSAPICaptureThread;
2736 if (_builtInAecEnabled)
2738 // Redirect to the DMO polling method.
2739 lpStartAddress = WSAPICaptureThreadPollDMO;
2743 // The DMO won't provide us captured output data unless we
2744 // give it render data to process.
2745 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2746 "Playout must be started before recording when using the "
2752 assert(_hRecThread == NULL);
2753 _hRecThread = CreateThread(NULL,
2759 if (_hRecThread == NULL)
2761 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2762 "failed to create the recording thread");
2766 // Set thread priority to highest possible
2767 SetThreadPriority(_hRecThread, THREAD_PRIORITY_TIME_CRITICAL);
2769 assert(_hGetCaptureVolumeThread == NULL);
2770 _hGetCaptureVolumeThread = CreateThread(NULL,
2772 GetCaptureVolumeThread,
2776 if (_hGetCaptureVolumeThread == NULL)
2778 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2779 " failed to create the volume getter thread");
2783 assert(_hSetCaptureVolumeThread == NULL);
2784 _hSetCaptureVolumeThread = CreateThread(NULL,
2786 SetCaptureVolumeThread,
2790 if (_hSetCaptureVolumeThread == NULL)
2792 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2793 " failed to create the volume setter thread");
2798 DWORD ret = WaitForSingleObject(_hCaptureStartedEvent, 1000);
2799 if (ret != WAIT_OBJECT_0)
2801 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2802 "capturing did not start up properly");
2805 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2806 "capture audio stream has now started...");
2815 // ----------------------------------------------------------------------------
2817 // ----------------------------------------------------------------------------
2819 int32_t AudioDeviceWindowsCore::StopRecording()
2823 if (!_recIsInitialized)
2830 if (_hRecThread == NULL)
2832 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2833 "no capturing stream is active => close down WASAPI only");
2834 SAFE_RELEASE(_ptrClientIn);
2835 SAFE_RELEASE(_ptrCaptureClient);
2836 _recIsInitialized = false;
2842 // Stop the driving thread...
2843 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2844 "closing down the webrtc_core_audio_capture_thread...");
2845 // Manual-reset event; it will remain signalled to stop all capture threads.
2846 SetEvent(_hShutdownCaptureEvent);
2849 DWORD ret = WaitForSingleObject(_hRecThread, 2000);
2850 if (ret != WAIT_OBJECT_0)
2852 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2853 "failed to close down webrtc_core_audio_capture_thread");
2858 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2859 "webrtc_core_audio_capture_thread is now closed");
2862 ret = WaitForSingleObject(_hGetCaptureVolumeThread, 2000);
2863 if (ret != WAIT_OBJECT_0)
2865 // the thread did not stop as it should
2866 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2867 " failed to close down volume getter thread");
2872 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2873 " volume getter thread is now closed");
2876 ret = WaitForSingleObject(_hSetCaptureVolumeThread, 2000);
2877 if (ret != WAIT_OBJECT_0)
2879 // the thread did not stop as it should
2880 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2881 " failed to close down volume setter thread");
2886 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2887 " volume setter thread is now closed");
2891 ResetEvent(_hShutdownCaptureEvent); // Must be manually reset.
2892 // Ensure that the thread has released these interfaces properly.
2893 assert(err == -1 || _ptrClientIn == NULL);
2894 assert(err == -1 || _ptrCaptureClient == NULL);
2896 _recIsInitialized = false;
2899 // These will create thread leaks in the result of an error,
2900 // but we can at least resume the call.
2901 CloseHandle(_hRecThread);
2904 CloseHandle(_hGetCaptureVolumeThread);
2905 _hGetCaptureVolumeThread = NULL;
2907 CloseHandle(_hSetCaptureVolumeThread);
2908 _hSetCaptureVolumeThread = NULL;
2910 if (_builtInAecEnabled)
2912 assert(_dmo != NULL);
2913 // This is necessary. Otherwise the DMO can generate garbage render
2914 // audio even after rendering has stopped.
2915 HRESULT hr = _dmo->FreeStreamingResources();
2923 // Reset the recording delay value.
2924 _sndCardRecDelay = 0;
2931 // ----------------------------------------------------------------------------
2932 // RecordingIsInitialized
2933 // ----------------------------------------------------------------------------
2935 bool AudioDeviceWindowsCore::RecordingIsInitialized() const
2937 return (_recIsInitialized);
2940 // ----------------------------------------------------------------------------
2942 // ----------------------------------------------------------------------------
2944 bool AudioDeviceWindowsCore::Recording() const
2946 return (_recording);
2949 // ----------------------------------------------------------------------------
2950 // PlayoutIsInitialized
2951 // ----------------------------------------------------------------------------
2953 bool AudioDeviceWindowsCore::PlayoutIsInitialized() const
2956 return (_playIsInitialized);
2959 // ----------------------------------------------------------------------------
2961 // ----------------------------------------------------------------------------
2963 int32_t AudioDeviceWindowsCore::StartPlayout()
2966 if (!_playIsInitialized)
2971 if (_hPlayThread != NULL)
2982 CriticalSectionScoped critScoped(&_critSect);
2984 // Create thread which will drive the rendering.
2985 assert(_hPlayThread == NULL);
2986 _hPlayThread = CreateThread(
2993 if (_hPlayThread == NULL)
2995 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2996 "failed to create the playout thread");
3000 // Set thread priority to highest possible.
3001 SetThreadPriority(_hPlayThread, THREAD_PRIORITY_TIME_CRITICAL);
3004 DWORD ret = WaitForSingleObject(_hRenderStartedEvent, 1000);
3005 if (ret != WAIT_OBJECT_0)
3007 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3008 "rendering did not start up properly");
3013 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3014 "rendering audio stream has now started...");
3019 // ----------------------------------------------------------------------------
3021 // ----------------------------------------------------------------------------
3023 int32_t AudioDeviceWindowsCore::StopPlayout()
3026 if (!_playIsInitialized)
3032 CriticalSectionScoped critScoped(&_critSect) ;
3034 if (_hPlayThread == NULL)
3036 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3037 "no rendering stream is active => close down WASAPI only");
3038 SAFE_RELEASE(_ptrClientOut);
3039 SAFE_RELEASE(_ptrRenderClient);
3040 _playIsInitialized = false;
3045 // stop the driving thread...
3046 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3047 "closing down the webrtc_core_audio_render_thread...");
3048 SetEvent(_hShutdownRenderEvent);
3051 DWORD ret = WaitForSingleObject(_hPlayThread, 2000);
3052 if (ret != WAIT_OBJECT_0)
3054 // the thread did not stop as it should
3055 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
3056 "failed to close down webrtc_core_audio_render_thread");
3057 CloseHandle(_hPlayThread);
3058 _hPlayThread = NULL;
3059 _playIsInitialized = false;
3065 CriticalSectionScoped critScoped(&_critSect);
3066 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3067 "webrtc_core_audio_render_thread is now closed");
3069 // to reset this event manually at each time we finish with it,
3070 // in case that the render thread has exited before StopPlayout(),
3071 // this event might be caught by the new render thread within same VoE instance.
3072 ResetEvent(_hShutdownRenderEvent);
3074 SAFE_RELEASE(_ptrClientOut);
3075 SAFE_RELEASE(_ptrRenderClient);
3077 _playIsInitialized = false;
3080 CloseHandle(_hPlayThread);
3081 _hPlayThread = NULL;
3083 if (_builtInAecEnabled && _recording)
3085 // The DMO won't provide us captured output data unless we
3086 // give it render data to process.
3088 // We still permit the playout to shutdown, and trace a warning.
3089 // Otherwise, VoE can get into a state which will never permit
3090 // playout to stop properly.
3091 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3092 "Recording should be stopped before playout when using the "
3096 // Reset the playout delay value.
3097 _sndCardPlayDelay = 0;
3103 // ----------------------------------------------------------------------------
3105 // ----------------------------------------------------------------------------
3107 int32_t AudioDeviceWindowsCore::PlayoutDelay(uint16_t& delayMS) const
3109 CriticalSectionScoped critScoped(&_critSect);
3110 delayMS = static_cast<uint16_t>(_sndCardPlayDelay);
3114 // ----------------------------------------------------------------------------
3116 // ----------------------------------------------------------------------------
3118 int32_t AudioDeviceWindowsCore::RecordingDelay(uint16_t& delayMS) const
3120 CriticalSectionScoped critScoped(&_critSect);
3121 delayMS = static_cast<uint16_t>(_sndCardRecDelay);
3125 // ----------------------------------------------------------------------------
3127 // ----------------------------------------------------------------------------
3129 bool AudioDeviceWindowsCore::Playing() const
3133 // ----------------------------------------------------------------------------
3135 // ----------------------------------------------------------------------------
3137 int32_t AudioDeviceWindowsCore::SetPlayoutBuffer(const AudioDeviceModule::BufferType type, uint16_t sizeMS)
3140 CriticalSectionScoped lock(&_critSect);
3142 _playBufType = type;
3144 if (type == AudioDeviceModule::kFixedBufferSize)
3146 _playBufDelayFixed = sizeMS;
3152 // ----------------------------------------------------------------------------
3154 // ----------------------------------------------------------------------------
3156 int32_t AudioDeviceWindowsCore::PlayoutBuffer(AudioDeviceModule::BufferType& type, uint16_t& sizeMS) const
3158 CriticalSectionScoped lock(&_critSect);
3159 type = _playBufType;
3161 if (type == AudioDeviceModule::kFixedBufferSize)
3163 sizeMS = _playBufDelayFixed;
3167 // Use same value as for PlayoutDelay
3168 sizeMS = static_cast<uint16_t>(_sndCardPlayDelay);
3174 // ----------------------------------------------------------------------------
3176 // ----------------------------------------------------------------------------
3178 int32_t AudioDeviceWindowsCore::CPULoad(uint16_t& load) const
3181 load = static_cast<uint16_t> (100*_avgCPULoad);
3186 // ----------------------------------------------------------------------------
3188 // ----------------------------------------------------------------------------
3190 bool AudioDeviceWindowsCore::PlayoutWarning() const
3192 return ( _playWarning > 0);
3195 // ----------------------------------------------------------------------------
3197 // ----------------------------------------------------------------------------
3199 bool AudioDeviceWindowsCore::PlayoutError() const
3201 return ( _playError > 0);
3204 // ----------------------------------------------------------------------------
3206 // ----------------------------------------------------------------------------
3208 bool AudioDeviceWindowsCore::RecordingWarning() const
3210 return ( _recWarning > 0);
3213 // ----------------------------------------------------------------------------
3215 // ----------------------------------------------------------------------------
3217 bool AudioDeviceWindowsCore::RecordingError() const
3219 return ( _recError > 0);
3222 // ----------------------------------------------------------------------------
3223 // ClearPlayoutWarning
3224 // ----------------------------------------------------------------------------
3226 void AudioDeviceWindowsCore::ClearPlayoutWarning()
3231 // ----------------------------------------------------------------------------
3232 // ClearPlayoutError
3233 // ----------------------------------------------------------------------------
3235 void AudioDeviceWindowsCore::ClearPlayoutError()
3240 // ----------------------------------------------------------------------------
3241 // ClearRecordingWarning
3242 // ----------------------------------------------------------------------------
3244 void AudioDeviceWindowsCore::ClearRecordingWarning()
3249 // ----------------------------------------------------------------------------
3250 // ClearRecordingError
3251 // ----------------------------------------------------------------------------
3253 void AudioDeviceWindowsCore::ClearRecordingError()
3258 // ============================================================================
3260 // ============================================================================
3262 // ----------------------------------------------------------------------------
3263 // [static] WSAPIRenderThread
3264 // ----------------------------------------------------------------------------
3266 DWORD WINAPI AudioDeviceWindowsCore::WSAPIRenderThread(LPVOID context)
3268 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3272 // ----------------------------------------------------------------------------
3273 // [static] WSAPICaptureThread
3274 // ----------------------------------------------------------------------------
3276 DWORD WINAPI AudioDeviceWindowsCore::WSAPICaptureThread(LPVOID context)
3278 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3282 DWORD WINAPI AudioDeviceWindowsCore::WSAPICaptureThreadPollDMO(LPVOID context)
3284 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3285 DoCaptureThreadPollDMO();
3288 DWORD WINAPI AudioDeviceWindowsCore::GetCaptureVolumeThread(LPVOID context)
3290 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3291 DoGetCaptureVolumeThread();
3294 DWORD WINAPI AudioDeviceWindowsCore::SetCaptureVolumeThread(LPVOID context)
3296 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3297 DoSetCaptureVolumeThread();
3300 DWORD AudioDeviceWindowsCore::DoGetCaptureVolumeThread()
3302 HANDLE waitObject = _hShutdownCaptureEvent;
3308 uint32_t currentMicLevel = 0;
3309 if (MicrophoneVolume(currentMicLevel) == 0)
3311 // This doesn't set the system volume, just stores it.
3313 if (_ptrAudioBuffer)
3315 _ptrAudioBuffer->SetCurrentMicLevel(currentMicLevel);
3321 DWORD waitResult = WaitForSingleObject(waitObject,
3322 GET_MIC_VOLUME_INTERVAL_MS);
3325 case WAIT_OBJECT_0: // _hShutdownCaptureEvent
3327 case WAIT_TIMEOUT: // timeout notification
3329 default: // unexpected error
3330 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3331 " unknown wait termination on get volume thread");
3337 DWORD AudioDeviceWindowsCore::DoSetCaptureVolumeThread()
3339 HANDLE waitArray[2] = {_hShutdownCaptureEvent, _hSetCaptureVolumeEvent};
3343 DWORD waitResult = WaitForMultipleObjects(2, waitArray, FALSE, INFINITE);
3346 case WAIT_OBJECT_0: // _hShutdownCaptureEvent
3348 case WAIT_OBJECT_0 + 1: // _hSetCaptureVolumeEvent
3350 default: // unexpected error
3351 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3352 " unknown wait termination on set volume thread");
3357 uint32_t newMicLevel = _newMicLevel;
3360 if (SetMicrophoneVolume(newMicLevel) == -1)
3362 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3363 " the required modification of the microphone volume failed");
3368 // ----------------------------------------------------------------------------
3370 // ----------------------------------------------------------------------------
3372 DWORD AudioDeviceWindowsCore::DoRenderThread()
3375 bool keepPlaying = true;
3376 HANDLE waitArray[2] = {_hShutdownRenderEvent, _hRenderSamplesReadyEvent};
3378 HANDLE hMmTask = NULL;
3384 // Initialize COM as MTA in this thread.
3385 ScopedCOMInitializer comInit(ScopedCOMInitializer::kMTA);
3386 if (!comInit.succeeded()) {
3387 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
3388 "failed to initialize COM in render thread");
3392 _SetThreadName(0, "webrtc_core_audio_render_thread");
3394 // Use Multimedia Class Scheduler Service (MMCSS) to boost the thread priority.
3396 if (_winSupportAvrt)
3399 hMmTask = _PAvSetMmThreadCharacteristicsA("Pro Audio", &taskIndex);
3402 if (FALSE == _PAvSetMmThreadPriority(hMmTask, AVRT_PRIORITY_CRITICAL))
3404 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "failed to boost play-thread using MMCSS");
3406 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "render thread is now registered with MMCSS (taskIndex=%d)", taskIndex);
3410 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "failed to enable MMCSS on render thread (err=%d)", GetLastError());
3411 _TraceCOMError(GetLastError());
3417 IAudioClock* clock = NULL;
3419 // Get size of rendering buffer (length is expressed as the number of audio frames the buffer can hold).
3420 // This value is fixed during the rendering session.
3422 UINT32 bufferLength = 0;
3423 hr = _ptrClientOut->GetBufferSize(&bufferLength);
3425 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[REND] size of buffer : %u", bufferLength);
3427 // Get maximum latency for the current stream (will not change for the lifetime of the IAudioClient object).
3429 REFERENCE_TIME latency;
3430 _ptrClientOut->GetStreamLatency(&latency);
3431 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[REND] max stream latency : %u (%3.2f ms)",
3432 (DWORD)latency, (double)(latency/10000.0));
3434 // Get the length of the periodic interval separating successive processing passes by
3435 // the audio engine on the data in the endpoint buffer.
3437 // The period between processing passes by the audio engine is fixed for a particular
3438 // audio endpoint device and represents the smallest processing quantum for the audio engine.
3439 // This period plus the stream latency between the buffer and endpoint device represents
3440 // the minimum possible latency that an audio application can achieve.
3441 // Typical value: 100000 <=> 0.01 sec = 10ms.
3443 REFERENCE_TIME devPeriod = 0;
3444 REFERENCE_TIME devPeriodMin = 0;
3445 _ptrClientOut->GetDevicePeriod(&devPeriod, &devPeriodMin);
3446 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[REND] device period : %u (%3.2f ms)",
3447 (DWORD)devPeriod, (double)(devPeriod/10000.0));
3449 // Derive initial rendering delay.
3450 // Example: 10*(960/480) + 15 = 20 + 15 = 35ms
3452 int playout_delay = 10 * (bufferLength / _playBlockSize) +
3453 (int)((latency + devPeriod) / 10000);
3454 _sndCardPlayDelay = playout_delay;
3455 _writtenSamples = 0;
3456 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3457 "[REND] initial delay : %u", playout_delay);
3459 double endpointBufferSizeMS = 10.0 * ((double)bufferLength / (double)_devicePlayBlockSize);
3460 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[REND] endpointBufferSizeMS : %3.2f", endpointBufferSizeMS);
3462 // Before starting the stream, fill the rendering buffer with silence.
3465 hr = _ptrRenderClient->GetBuffer(bufferLength, &pData);
3468 hr = _ptrRenderClient->ReleaseBuffer(bufferLength, AUDCLNT_BUFFERFLAGS_SILENT);
3471 _writtenSamples += bufferLength;
3473 hr = _ptrClientOut->GetService(__uuidof(IAudioClock), (void**)&clock);
3475 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3476 "failed to get IAudioClock interface from the IAudioClient");
3479 // Start up the rendering audio stream.
3480 hr = _ptrClientOut->Start();
3485 // Set event which will ensure that the calling thread modifies the playing state to true.
3487 SetEvent(_hRenderStartedEvent);
3489 // >> ------------------ THREAD LOOP ------------------
3493 // Wait for a render notification event or a shutdown event
3494 DWORD waitResult = WaitForMultipleObjects(2, waitArray, FALSE, 500);
3497 case WAIT_OBJECT_0 + 0: // _hShutdownRenderEvent
3498 keepPlaying = false;
3500 case WAIT_OBJECT_0 + 1: // _hRenderSamplesReadyEvent
3502 case WAIT_TIMEOUT: // timeout notification
3503 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "render event timed out after 0.5 seconds");
3505 default: // unexpected error
3506 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "unknown wait termination on render side");
3514 // Sanity check to ensure that essential states are not modified
3515 // during the unlocked period.
3516 if (_ptrRenderClient == NULL || _ptrClientOut == NULL)
3519 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
3520 "output state has been modified during unlocked period");
3524 // Get the number of frames of padding (queued up to play) in the endpoint buffer.
3526 hr = _ptrClientOut->GetCurrentPadding(&padding);
3529 // Derive the amount of available space in the output buffer
3530 uint32_t framesAvailable = bufferLength - padding;
3531 // WEBRTC_TRACE(kTraceStream, kTraceAudioDevice, _id, "#avaliable audio frames = %u", framesAvailable);
3533 // Do we have 10 ms available in the render buffer?
3534 if (framesAvailable < _playBlockSize)
3536 // Not enough space in render buffer to store next render packet.
3541 // Write n*10ms buffers to the render buffer
3542 const uint32_t n10msBuffers = (framesAvailable / _playBlockSize);
3543 for (uint32_t n = 0; n < n10msBuffers; n++)
3545 // Get pointer (i.e., grab the buffer) to next space in the shared render buffer.
3546 hr = _ptrRenderClient->GetBuffer(_playBlockSize, &pData);
3549 QueryPerformanceCounter(&t1); // measure time: START
3551 if (_ptrAudioBuffer)
3553 // Request data to be played out (#bytes = _playBlockSize*_audioFrameSize)
3556 _ptrAudioBuffer->RequestPlayoutData(_playBlockSize);
3562 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
3563 "failed to read data from render client");
3567 // Sanity check to ensure that essential states are not modified during the unlocked period
3568 if (_ptrRenderClient == NULL || _ptrClientOut == NULL)
3571 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id, "output state has been modified during unlocked period");
3574 if (nSamples != static_cast<int32_t>(_playBlockSize))
3576 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "nSamples(%d) != _playBlockSize(%d)", nSamples, _playBlockSize);
3579 // Get the actual (stored) data
3580 nSamples = _ptrAudioBuffer->GetPlayoutData((int8_t*)pData);
3583 QueryPerformanceCounter(&t2); // measure time: STOP
3584 time = (int)(t2.QuadPart-t1.QuadPart);
3588 hr = _ptrRenderClient->ReleaseBuffer(_playBlockSize, dwFlags);
3589 // See http://msdn.microsoft.com/en-us/library/dd316605(VS.85).aspx
3590 // for more details regarding AUDCLNT_E_DEVICE_INVALIDATED.
3593 _writtenSamples += _playBlockSize;
3596 // Check the current delay on the playout side.
3600 clock->GetPosition(&pos, NULL);
3601 clock->GetFrequency(&freq);
3602 playout_delay = ROUND((double(_writtenSamples) /
3603 _devicePlaySampleRate - double(pos) / freq) * 1000.0);
3604 _sndCardPlayDelay = playout_delay;
3611 // ------------------ THREAD LOOP ------------------ <<
3613 SleepMs(static_cast<DWORD>(endpointBufferSizeMS+0.5));
3614 hr = _ptrClientOut->Stop();
3617 SAFE_RELEASE(clock);
3621 _ptrClientOut->Stop();
3626 if (_winSupportAvrt)
3628 if (NULL != hMmTask)
3630 _PAvRevertMmThreadCharacteristics(hMmTask);
3638 if (_ptrClientOut != NULL)
3640 hr = _ptrClientOut->Stop();
3645 hr = _ptrClientOut->Reset();
3651 // Trigger callback from module process thread
3653 WEBRTC_TRACE(kTraceError, kTraceUtility, _id, "kPlayoutError message posted: rendering thread has ended pre-maturely");
3657 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_Rendering thread is now terminated properly");
3665 DWORD AudioDeviceWindowsCore::InitCaptureThreadPriority()
3669 _SetThreadName(0, "webrtc_core_audio_capture_thread");
3671 // Use Multimedia Class Scheduler Service (MMCSS) to boost the thread
3673 if (_winSupportAvrt)
3676 _hMmTask = _PAvSetMmThreadCharacteristicsA("Pro Audio", &taskIndex);
3679 if (!_PAvSetMmThreadPriority(_hMmTask, AVRT_PRIORITY_CRITICAL))
3681 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3682 "failed to boost rec-thread using MMCSS");
3684 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3685 "capture thread is now registered with MMCSS (taskIndex=%d)",
3690 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3691 "failed to enable MMCSS on capture thread (err=%d)",
3693 _TraceCOMError(GetLastError());
3700 void AudioDeviceWindowsCore::RevertCaptureThreadPriority()
3702 if (_winSupportAvrt)
3704 if (NULL != _hMmTask)
3706 _PAvRevertMmThreadCharacteristics(_hMmTask);
3713 DWORD AudioDeviceWindowsCore::DoCaptureThreadPollDMO()
3715 assert(_mediaBuffer != NULL);
3716 bool keepRecording = true;
3718 // Initialize COM as MTA in this thread.
3719 ScopedCOMInitializer comInit(ScopedCOMInitializer::kMTA);
3720 if (!comInit.succeeded()) {
3721 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
3722 "failed to initialize COM in polling DMO thread");
3726 HRESULT hr = InitCaptureThreadPriority();
3732 // Set event which will ensure that the calling thread modifies the
3733 // recording state to true.
3734 SetEvent(_hCaptureStartedEvent);
3736 // >> ---------------------------- THREAD LOOP ----------------------------
3737 while (keepRecording)
3739 // Poll the DMO every 5 ms.
3740 // (The same interval used in the Wave implementation.)
3741 DWORD waitResult = WaitForSingleObject(_hShutdownCaptureEvent, 5);
3744 case WAIT_OBJECT_0: // _hShutdownCaptureEvent
3745 keepRecording = false;
3747 case WAIT_TIMEOUT: // timeout notification
3749 default: // unexpected error
3750 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3751 "Unknown wait termination on capture side");
3752 hr = -1; // To signal an error callback.
3753 keepRecording = false;
3757 while (keepRecording)
3759 CriticalSectionScoped critScoped(&_critSect);
3763 DMO_OUTPUT_DATA_BUFFER dmoBuffer = {0};
3764 dmoBuffer.pBuffer = _mediaBuffer;
3765 dmoBuffer.pBuffer->AddRef();
3767 // Poll the DMO for AEC processed capture data. The DMO will
3768 // copy available data to |dmoBuffer|, and should only return
3769 // 10 ms frames. The value of |dwStatus| should be ignored.
3770 hr = _dmo->ProcessOutput(0, 1, &dmoBuffer, &dwStatus);
3771 SAFE_RELEASE(dmoBuffer.pBuffer);
3772 dwStatus = dmoBuffer.dwStatus;
3777 keepRecording = false;
3782 ULONG bytesProduced = 0;
3784 // Get a pointer to the data buffer. This should be valid until
3785 // the next call to ProcessOutput.
3786 hr = _mediaBuffer->GetBufferAndLength(&data, &bytesProduced);
3790 keepRecording = false;
3795 // TODO(andrew): handle AGC.
3797 if (bytesProduced > 0)
3799 const int kSamplesProduced = bytesProduced / _recAudioFrameSize;
3800 // TODO(andrew): verify that this is always satisfied. It might
3801 // be that ProcessOutput will try to return more than 10 ms if
3802 // we fail to call it frequently enough.
3803 assert(kSamplesProduced == static_cast<int>(_recBlockSize));
3804 assert(sizeof(BYTE) == sizeof(int8_t));
3805 _ptrAudioBuffer->SetRecordedBuffer(
3806 reinterpret_cast<int8_t*>(data),
3808 _ptrAudioBuffer->SetVQEData(0, 0, 0);
3810 _UnLock(); // Release lock while making the callback.
3811 _ptrAudioBuffer->DeliverRecordedData();
3815 // Reset length to indicate buffer availability.
3816 hr = _mediaBuffer->SetLength(0);
3820 keepRecording = false;
3825 if (!(dwStatus & DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE))
3827 // The DMO cannot currently produce more data. This is the
3828 // normal case; otherwise it means the DMO had more than 10 ms
3829 // of data available and ProcessOutput should be called again.
3834 // ---------------------------- THREAD LOOP ---------------------------- <<
3836 RevertCaptureThreadPriority();
3840 // Trigger callback from module process thread
3842 WEBRTC_TRACE(kTraceError, kTraceUtility, _id,
3843 "kRecordingError message posted: capturing thread has ended "
3848 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3849 "Capturing thread is now terminated properly");
3856 // ----------------------------------------------------------------------------
3858 // ----------------------------------------------------------------------------
3860 DWORD AudioDeviceWindowsCore::DoCaptureThread()
3863 bool keepRecording = true;
3864 HANDLE waitArray[2] = {_hShutdownCaptureEvent, _hCaptureSamplesReadyEvent};
3871 BYTE* syncBuffer = NULL;
3872 UINT32 syncBufIndex = 0;
3876 // Initialize COM as MTA in this thread.
3877 ScopedCOMInitializer comInit(ScopedCOMInitializer::kMTA);
3878 if (!comInit.succeeded()) {
3879 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
3880 "failed to initialize COM in capture thread");
3884 hr = InitCaptureThreadPriority();
3892 // Get size of capturing buffer (length is expressed as the number of audio frames the buffer can hold).
3893 // This value is fixed during the capturing session.
3895 UINT32 bufferLength = 0;
3896 hr = _ptrClientIn->GetBufferSize(&bufferLength);
3898 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] size of buffer : %u", bufferLength);
3900 // Allocate memory for sync buffer.
3901 // It is used for compensation between native 44.1 and internal 44.0 and
3902 // for cases when the capture buffer is larger than 10ms.
3904 const UINT32 syncBufferSize = 2*(bufferLength * _recAudioFrameSize);
3905 syncBuffer = new BYTE[syncBufferSize];
3906 if (syncBuffer == NULL)
3908 return (DWORD)E_POINTER;
3910 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] size of sync buffer : %u [bytes]", syncBufferSize);
3912 // Get maximum latency for the current stream (will not change for the lifetime of the IAudioClient object).
3914 REFERENCE_TIME latency;
3915 _ptrClientIn->GetStreamLatency(&latency);
3916 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] max stream latency : %u (%3.2f ms)",
3917 (DWORD)latency, (double)(latency / 10000.0));
3919 // Get the length of the periodic interval separating successive processing passes by
3920 // the audio engine on the data in the endpoint buffer.
3922 REFERENCE_TIME devPeriod = 0;
3923 REFERENCE_TIME devPeriodMin = 0;
3924 _ptrClientIn->GetDevicePeriod(&devPeriod, &devPeriodMin);
3925 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] device period : %u (%3.2f ms)",
3926 (DWORD)devPeriod, (double)(devPeriod / 10000.0));
3928 double extraDelayMS = (double)((latency + devPeriod) / 10000.0);
3929 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] extraDelayMS : %3.2f", extraDelayMS);
3931 double endpointBufferSizeMS = 10.0 * ((double)bufferLength / (double)_recBlockSize);
3932 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] endpointBufferSizeMS : %3.2f", endpointBufferSizeMS);
3934 // Start up the capturing stream.
3936 hr = _ptrClientIn->Start();
3941 // Set event which will ensure that the calling thread modifies the recording state to true.
3943 SetEvent(_hCaptureStartedEvent);
3945 // >> ---------------------------- THREAD LOOP ----------------------------
3947 while (keepRecording)
3949 // Wait for a capture notification event or a shutdown event
3950 DWORD waitResult = WaitForMultipleObjects(2, waitArray, FALSE, 500);
3953 case WAIT_OBJECT_0 + 0: // _hShutdownCaptureEvent
3954 keepRecording = false;
3956 case WAIT_OBJECT_0 + 1: // _hCaptureSamplesReadyEvent
3958 case WAIT_TIMEOUT: // timeout notification
3959 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "capture event timed out after 0.5 seconds");
3961 default: // unexpected error
3962 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "unknown wait termination on capture side");
3966 while (keepRecording)
3969 UINT32 framesAvailable = 0;
3976 // Sanity check to ensure that essential states are not modified
3977 // during the unlocked period.
3978 if (_ptrCaptureClient == NULL || _ptrClientIn == NULL)
3981 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
3982 "input state has been modified during unlocked period");
3986 // Find out how much capture data is available
3988 hr = _ptrCaptureClient->GetBuffer(&pData, // packet which is ready to be read by used
3989 &framesAvailable, // #frames in the captured packet (can be zero)
3990 &flags, // support flags (check)
3991 &recPos, // device position of first audio frame in data packet
3992 &recTime); // value of performance counter at the time of recording the first audio frame
3996 if (AUDCLNT_S_BUFFER_EMPTY == hr)
3998 // Buffer was empty => start waiting for a new capture notification event
4003 if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
4005 // Treat all of the data in the packet as silence and ignore the actual data values.
4006 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "AUDCLNT_BUFFERFLAGS_SILENT");
4010 assert(framesAvailable != 0);
4014 CopyMemory(&syncBuffer[syncBufIndex*_recAudioFrameSize], pData, framesAvailable*_recAudioFrameSize);
4018 ZeroMemory(&syncBuffer[syncBufIndex*_recAudioFrameSize], framesAvailable*_recAudioFrameSize);
4020 assert(syncBufferSize >= (syncBufIndex*_recAudioFrameSize)+framesAvailable*_recAudioFrameSize);
4022 // Release the capture buffer
4024 hr = _ptrCaptureClient->ReleaseBuffer(framesAvailable);
4027 _readSamples += framesAvailable;
4028 syncBufIndex += framesAvailable;
4030 QueryPerformanceCounter(&t1);
4032 // Get the current recording and playout delay.
4033 uint32_t sndCardRecDelay = (uint32_t)
4034 (((((UINT64)t1.QuadPart * _perfCounterFactor) - recTime)
4035 / 10000) + (10*syncBufIndex) / _recBlockSize - 10);
4036 uint32_t sndCardPlayDelay =
4037 static_cast<uint32_t>(_sndCardPlayDelay);
4039 _sndCardRecDelay = sndCardRecDelay;
4041 while (syncBufIndex >= _recBlockSize)
4043 if (_ptrAudioBuffer)
4045 _ptrAudioBuffer->SetRecordedBuffer((const int8_t*)syncBuffer, _recBlockSize);
4046 _ptrAudioBuffer->SetVQEData(sndCardPlayDelay,
4050 _ptrAudioBuffer->SetTypingStatus(KeyPressed());
4052 QueryPerformanceCounter(&t1); // measure time: START
4054 _UnLock(); // release lock while making the callback
4055 _ptrAudioBuffer->DeliverRecordedData();
4056 _Lock(); // restore the lock
4058 QueryPerformanceCounter(&t2); // measure time: STOP
4060 // Measure "average CPU load".
4061 // Basically what we do here is to measure how many percent of our 10ms period
4062 // is used for encoding and decoding. This value shuld be used as a warning indicator
4063 // only and not seen as an absolute value. Running at ~100% will lead to bad QoS.
4064 time = (int)(t2.QuadPart - t1.QuadPart);
4065 _avgCPULoad = (float)(_avgCPULoad*.99 + (time + _playAcc) / (double)(_perfCounterFreq.QuadPart));
4068 // Sanity check to ensure that essential states are not modified during the unlocked period
4069 if (_ptrCaptureClient == NULL || _ptrClientIn == NULL)
4072 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id, "input state has been modified during unlocked period");
4077 // store remaining data which was not able to deliver as 10ms segment
4078 MoveMemory(&syncBuffer[0], &syncBuffer[_recBlockSize*_recAudioFrameSize], (syncBufIndex-_recBlockSize)*_recAudioFrameSize);
4079 syncBufIndex -= _recBlockSize;
4080 sndCardRecDelay -= 10;
4085 uint32_t newMicLevel = _ptrAudioBuffer->NewMicLevel();
4086 if (newMicLevel != 0)
4088 // The VQE will only deliver non-zero microphone levels when a change is needed.
4089 // Set this new mic level (received from the observer as return value in the callback).
4090 WEBRTC_TRACE(kTraceStream, kTraceAudioDevice, _id, "AGC change of volume: new=%u", newMicLevel);
4091 // We store this outside of the audio buffer to avoid
4092 // having it overwritten by the getter thread.
4093 _newMicLevel = newMicLevel;
4094 SetEvent(_hSetCaptureVolumeEvent);
4100 // If GetBuffer returns AUDCLNT_E_BUFFER_ERROR, the thread consuming the audio samples
4101 // must wait for the next processing pass. The client might benefit from keeping a count
4102 // of the failed GetBuffer calls. If GetBuffer returns this error repeatedly, the client
4103 // can start a new processing loop after shutting down the current client by calling
4104 // IAudioClient::Stop, IAudioClient::Reset, and releasing the audio client.
4105 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4106 "IAudioCaptureClient::GetBuffer returned AUDCLNT_E_BUFFER_ERROR, hr = 0x%08X", hr);
4114 // ---------------------------- THREAD LOOP ---------------------------- <<
4116 hr = _ptrClientIn->Stop();
4121 _ptrClientIn->Stop();
4126 RevertCaptureThreadPriority();
4132 if (_ptrClientIn != NULL)
4134 hr = _ptrClientIn->Stop();
4139 hr = _ptrClientIn->Reset();
4146 // Trigger callback from module process thread
4148 WEBRTC_TRACE(kTraceError, kTraceUtility, _id, "kRecordingError message posted: capturing thread has ended pre-maturely");
4152 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_Capturing thread is now terminated properly");
4155 SAFE_RELEASE(_ptrClientIn);
4156 SAFE_RELEASE(_ptrCaptureClient);
4162 delete [] syncBuffer;
4168 int32_t AudioDeviceWindowsCore::EnableBuiltInAEC(bool enable)
4171 if (_recIsInitialized)
4173 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4174 "Attempt to set Windows AEC with recording already initialized");
4180 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4181 "Built-in AEC DMO was not initialized properly at create time");
4185 _builtInAecEnabled = enable;
4189 bool AudioDeviceWindowsCore::BuiltInAECIsEnabled() const
4191 return _builtInAecEnabled;
4194 int AudioDeviceWindowsCore::SetDMOProperties()
4197 assert(_dmo != NULL);
4199 scoped_refptr<IPropertyStore> ps;
4201 IPropertyStore* ptrPS = NULL;
4202 hr = _dmo->QueryInterface(IID_IPropertyStore,
4203 reinterpret_cast<void**>(&ptrPS));
4204 if (FAILED(hr) || ptrPS == NULL)
4210 SAFE_RELEASE(ptrPS);
4213 // Set the AEC system mode.
4214 // SINGLE_CHANNEL_AEC - AEC processing only.
4215 if (SetVtI4Property(ps,
4216 MFPKEY_WMAAECMA_SYSTEM_MODE,
4217 SINGLE_CHANNEL_AEC))
4222 // Set the AEC source mode.
4223 // VARIANT_TRUE - Source mode (we poll the AEC for captured data).
4224 if (SetBoolProperty(ps,
4225 MFPKEY_WMAAECMA_DMO_SOURCE_MODE,
4226 VARIANT_TRUE) == -1)
4231 // Enable the feature mode.
4232 // This lets us override all the default processing settings below.
4233 if (SetBoolProperty(ps,
4234 MFPKEY_WMAAECMA_FEATURE_MODE,
4235 VARIANT_TRUE) == -1)
4240 // Disable analog AGC (default enabled).
4241 if (SetBoolProperty(ps,
4242 MFPKEY_WMAAECMA_MIC_GAIN_BOUNDER,
4243 VARIANT_FALSE) == -1)
4248 // Disable noise suppression (default enabled).
4249 // 0 - Disabled, 1 - Enabled
4250 if (SetVtI4Property(ps,
4251 MFPKEY_WMAAECMA_FEATR_NS,
4257 // Relevant parameters to leave at default settings:
4258 // MFPKEY_WMAAECMA_FEATR_AGC - Digital AGC (disabled).
4259 // MFPKEY_WMAAECMA_FEATR_CENTER_CLIP - AEC center clipping (enabled).
4260 // MFPKEY_WMAAECMA_FEATR_ECHO_LENGTH - Filter length (256 ms).
4261 // TODO(andrew): investigate decresing the length to 128 ms.
4262 // MFPKEY_WMAAECMA_FEATR_FRAME_SIZE - Frame size (0).
4263 // 0 is automatic; defaults to 160 samples (or 10 ms frames at the
4264 // selected 16 kHz) as long as mic array processing is disabled.
4265 // MFPKEY_WMAAECMA_FEATR_NOISE_FILL - Comfort noise (enabled).
4266 // MFPKEY_WMAAECMA_FEATR_VAD - VAD (disabled).
4268 // Set the devices selected by VoE. If using a default device, we need to
4269 // search for the device index.
4270 int inDevIndex = _inputDeviceIndex;
4271 int outDevIndex = _outputDeviceIndex;
4272 if (!_usingInputDeviceIndex)
4274 ERole role = eCommunications;
4275 if (_inputDevice == AudioDeviceModule::kDefaultDevice)
4280 if (_GetDefaultDeviceIndex(eCapture, role, &inDevIndex) == -1)
4286 if (!_usingOutputDeviceIndex)
4288 ERole role = eCommunications;
4289 if (_outputDevice == AudioDeviceModule::kDefaultDevice)
4294 if (_GetDefaultDeviceIndex(eRender, role, &outDevIndex) == -1)
4300 DWORD devIndex = static_cast<uint32_t>(outDevIndex << 16) +
4301 static_cast<uint32_t>(0x0000ffff & inDevIndex);
4302 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
4303 "Capture device index: %d, render device index: %d",
4304 inDevIndex, outDevIndex);
4305 if (SetVtI4Property(ps,
4306 MFPKEY_WMAAECMA_DEVICE_INDEXES,
4315 int AudioDeviceWindowsCore::SetBoolProperty(IPropertyStore* ptrPS,
4320 PropVariantInit(&pv);
4323 HRESULT hr = ptrPS->SetValue(key, pv);
4324 PropVariantClear(&pv);
4333 int AudioDeviceWindowsCore::SetVtI4Property(IPropertyStore* ptrPS,
4338 PropVariantInit(&pv);
4341 HRESULT hr = ptrPS->SetValue(key, pv);
4342 PropVariantClear(&pv);
4351 // ----------------------------------------------------------------------------
4352 // _RefreshDeviceList
4354 // Creates a new list of endpoint rendering or capture devices after
4355 // deleting any previously created (and possibly out-of-date) list of
4357 // ----------------------------------------------------------------------------
4359 int32_t AudioDeviceWindowsCore::_RefreshDeviceList(EDataFlow dir)
4361 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4364 IMMDeviceCollection *pCollection = NULL;
4366 assert(dir == eRender || dir == eCapture);
4367 assert(_ptrEnumerator != NULL);
4369 // Create a fresh list of devices using the specified direction
4370 hr = _ptrEnumerator->EnumAudioEndpoints(
4372 DEVICE_STATE_ACTIVE,
4377 SAFE_RELEASE(pCollection);
4383 SAFE_RELEASE(_ptrRenderCollection);
4384 _ptrRenderCollection = pCollection;
4388 SAFE_RELEASE(_ptrCaptureCollection);
4389 _ptrCaptureCollection = pCollection;
4395 // ----------------------------------------------------------------------------
4398 // Gets a count of the endpoint rendering or capture devices in the
4399 // current list of such devices.
4400 // ----------------------------------------------------------------------------
4402 int16_t AudioDeviceWindowsCore::_DeviceListCount(EDataFlow dir)
4404 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4409 assert(eRender == dir || eCapture == dir);
4411 if (eRender == dir && NULL != _ptrRenderCollection)
4413 hr = _ptrRenderCollection->GetCount(&count);
4415 else if (NULL != _ptrCaptureCollection)
4417 hr = _ptrCaptureCollection->GetCount(&count);
4426 return static_cast<int16_t> (count);
4429 // ----------------------------------------------------------------------------
4430 // _GetListDeviceName
4432 // Gets the friendly name of an endpoint rendering or capture device
4433 // from the current list of such devices. The caller uses an index
4434 // into the list to identify the device.
4436 // Uses: _ptrRenderCollection or _ptrCaptureCollection which is updated
4437 // in _RefreshDeviceList().
4438 // ----------------------------------------------------------------------------
4440 int32_t AudioDeviceWindowsCore::_GetListDeviceName(EDataFlow dir, int index, LPWSTR szBuffer, int bufferLen)
4442 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4445 IMMDevice *pDevice = NULL;
4447 assert(dir == eRender || dir == eCapture);
4449 if (eRender == dir && NULL != _ptrRenderCollection)
4451 hr = _ptrRenderCollection->Item(index, &pDevice);
4453 else if (NULL != _ptrCaptureCollection)
4455 hr = _ptrCaptureCollection->Item(index, &pDevice);
4461 SAFE_RELEASE(pDevice);
4465 int32_t res = _GetDeviceName(pDevice, szBuffer, bufferLen);
4466 SAFE_RELEASE(pDevice);
4470 // ----------------------------------------------------------------------------
4471 // _GetDefaultDeviceName
4473 // Gets the friendly name of an endpoint rendering or capture device
4474 // given a specified device role.
4476 // Uses: _ptrEnumerator
4477 // ----------------------------------------------------------------------------
4479 int32_t AudioDeviceWindowsCore::_GetDefaultDeviceName(EDataFlow dir, ERole role, LPWSTR szBuffer, int bufferLen)
4481 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4484 IMMDevice *pDevice = NULL;
4486 assert(dir == eRender || dir == eCapture);
4487 assert(role == eConsole || role == eCommunications);
4488 assert(_ptrEnumerator != NULL);
4490 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
4498 SAFE_RELEASE(pDevice);
4502 int32_t res = _GetDeviceName(pDevice, szBuffer, bufferLen);
4503 SAFE_RELEASE(pDevice);
4507 // ----------------------------------------------------------------------------
4510 // Gets the unique ID string of an endpoint rendering or capture device
4511 // from the current list of such devices. The caller uses an index
4512 // into the list to identify the device.
4514 // Uses: _ptrRenderCollection or _ptrCaptureCollection which is updated
4515 // in _RefreshDeviceList().
4516 // ----------------------------------------------------------------------------
4518 int32_t AudioDeviceWindowsCore::_GetListDeviceID(EDataFlow dir, int index, LPWSTR szBuffer, int bufferLen)
4520 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4523 IMMDevice *pDevice = NULL;
4525 assert(dir == eRender || dir == eCapture);
4527 if (eRender == dir && NULL != _ptrRenderCollection)
4529 hr = _ptrRenderCollection->Item(index, &pDevice);
4531 else if (NULL != _ptrCaptureCollection)
4533 hr = _ptrCaptureCollection->Item(index, &pDevice);
4539 SAFE_RELEASE(pDevice);
4543 int32_t res = _GetDeviceID(pDevice, szBuffer, bufferLen);
4544 SAFE_RELEASE(pDevice);
4548 // ----------------------------------------------------------------------------
4549 // _GetDefaultDeviceID
4551 // Gets the uniqe device ID of an endpoint rendering or capture device
4552 // given a specified device role.
4554 // Uses: _ptrEnumerator
4555 // ----------------------------------------------------------------------------
4557 int32_t AudioDeviceWindowsCore::_GetDefaultDeviceID(EDataFlow dir, ERole role, LPWSTR szBuffer, int bufferLen)
4559 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4562 IMMDevice *pDevice = NULL;
4564 assert(dir == eRender || dir == eCapture);
4565 assert(role == eConsole || role == eCommunications);
4566 assert(_ptrEnumerator != NULL);
4568 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
4576 SAFE_RELEASE(pDevice);
4580 int32_t res = _GetDeviceID(pDevice, szBuffer, bufferLen);
4581 SAFE_RELEASE(pDevice);
4585 int32_t AudioDeviceWindowsCore::_GetDefaultDeviceIndex(EDataFlow dir,
4589 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4592 WCHAR szDefaultDeviceID[MAX_PATH] = {0};
4593 WCHAR szDeviceID[MAX_PATH] = {0};
4595 const size_t kDeviceIDLength = sizeof(szDeviceID)/sizeof(szDeviceID[0]);
4596 assert(kDeviceIDLength ==
4597 sizeof(szDefaultDeviceID) / sizeof(szDefaultDeviceID[0]));
4599 if (_GetDefaultDeviceID(dir,
4602 kDeviceIDLength) == -1)
4607 IMMDeviceCollection* collection = _ptrCaptureCollection;
4610 collection = _ptrRenderCollection;
4615 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4616 "Device collection not valid");
4621 hr = collection->GetCount(&count);
4629 for (UINT i = 0; i < count; i++)
4631 memset(szDeviceID, 0, sizeof(szDeviceID));
4632 scoped_refptr<IMMDevice> device;
4634 IMMDevice* ptrDevice = NULL;
4635 hr = collection->Item(i, &ptrDevice);
4636 if (FAILED(hr) || ptrDevice == NULL)
4642 SAFE_RELEASE(ptrDevice);
4645 if (_GetDeviceID(device, szDeviceID, kDeviceIDLength) == -1)
4650 if (wcsncmp(szDefaultDeviceID, szDeviceID, kDeviceIDLength) == 0)
4661 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4662 "Unable to find collection index for default device");
4669 // ----------------------------------------------------------------------------
4671 // ----------------------------------------------------------------------------
4673 int32_t AudioDeviceWindowsCore::_GetDeviceName(IMMDevice* pDevice,
4677 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4679 static const WCHAR szDefault[] = L"<Device not available>";
4681 HRESULT hr = E_FAIL;
4682 IPropertyStore *pProps = NULL;
4683 PROPVARIANT varName;
4685 assert(pszBuffer != NULL);
4686 assert(bufferLen > 0);
4688 if (pDevice != NULL)
4690 hr = pDevice->OpenPropertyStore(STGM_READ, &pProps);
4693 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4694 "IMMDevice::OpenPropertyStore failed, hr = 0x%08X", hr);
4698 // Initialize container for property value.
4699 PropVariantInit(&varName);
4703 // Get the endpoint device's friendly-name property.
4704 hr = pProps->GetValue(PKEY_Device_FriendlyName, &varName);
4707 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4708 "IPropertyStore::GetValue failed, hr = 0x%08X", hr);
4712 if ((SUCCEEDED(hr)) && (VT_EMPTY == varName.vt))
4715 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4716 "IPropertyStore::GetValue returned no value, hr = 0x%08X", hr);
4719 if ((SUCCEEDED(hr)) && (VT_LPWSTR != varName.vt))
4721 // The returned value is not a wide null terminated string.
4723 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4724 "IPropertyStore::GetValue returned unexpected type, hr = 0x%08X", hr);
4727 if (SUCCEEDED(hr) && (varName.pwszVal != NULL))
4729 // Copy the valid device name to the provided ouput buffer.
4730 wcsncpy_s(pszBuffer, bufferLen, varName.pwszVal, _TRUNCATE);
4734 // Failed to find the device name.
4735 wcsncpy_s(pszBuffer, bufferLen, szDefault, _TRUNCATE);
4738 PropVariantClear(&varName);
4739 SAFE_RELEASE(pProps);
4744 // ----------------------------------------------------------------------------
4746 // ----------------------------------------------------------------------------
4748 int32_t AudioDeviceWindowsCore::_GetDeviceID(IMMDevice* pDevice, LPWSTR pszBuffer, int bufferLen)
4750 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4752 static const WCHAR szDefault[] = L"<Device not available>";
4754 HRESULT hr = E_FAIL;
4755 LPWSTR pwszID = NULL;
4757 assert(pszBuffer != NULL);
4758 assert(bufferLen > 0);
4760 if (pDevice != NULL)
4762 hr = pDevice->GetId(&pwszID);
4767 // Found the device ID.
4768 wcsncpy_s(pszBuffer, bufferLen, pwszID, _TRUNCATE);
4772 // Failed to find the device ID.
4773 wcsncpy_s(pszBuffer, bufferLen, szDefault, _TRUNCATE);
4776 CoTaskMemFree(pwszID);
4780 // ----------------------------------------------------------------------------
4781 // _GetDefaultDevice
4782 // ----------------------------------------------------------------------------
4784 int32_t AudioDeviceWindowsCore::_GetDefaultDevice(EDataFlow dir, ERole role, IMMDevice** ppDevice)
4786 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4790 assert(_ptrEnumerator != NULL);
4792 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
4805 // ----------------------------------------------------------------------------
4807 // ----------------------------------------------------------------------------
4809 int32_t AudioDeviceWindowsCore::_GetListDevice(EDataFlow dir, int index, IMMDevice** ppDevice)
4813 assert(_ptrEnumerator != NULL);
4815 IMMDeviceCollection *pCollection = NULL;
4817 hr = _ptrEnumerator->EnumAudioEndpoints(
4819 DEVICE_STATE_ACTIVE, // only active endpoints are OK
4824 SAFE_RELEASE(pCollection);
4828 hr = pCollection->Item(
4834 SAFE_RELEASE(pCollection);
4841 // ----------------------------------------------------------------------------
4842 // _EnumerateEndpointDevicesAll
4843 // ----------------------------------------------------------------------------
4845 int32_t AudioDeviceWindowsCore::_EnumerateEndpointDevicesAll(EDataFlow dataFlow) const
4847 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4849 assert(_ptrEnumerator != NULL);
4852 IMMDeviceCollection *pCollection = NULL;
4853 IMMDevice *pEndpoint = NULL;
4854 IPropertyStore *pProps = NULL;
4855 IAudioEndpointVolume* pEndpointVolume = NULL;
4856 LPWSTR pwszID = NULL;
4858 // Generate a collection of audio endpoint devices in the system.
4859 // Get states for *all* endpoint devices.
4860 // Output: IMMDeviceCollection interface.
4861 hr = _ptrEnumerator->EnumAudioEndpoints(
4862 dataFlow, // data-flow direction (input parameter)
4863 DEVICE_STATE_ACTIVE | DEVICE_STATE_DISABLED | DEVICE_STATE_UNPLUGGED,
4864 &pCollection); // release interface when done
4868 // use the IMMDeviceCollection interface...
4872 // Retrieve a count of the devices in the device collection.
4873 hr = pCollection->GetCount(&count);
4875 if (dataFlow == eRender)
4876 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#rendering endpoint devices (counting all): %u", count);
4877 else if (dataFlow == eCapture)
4878 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#capturing endpoint devices (counting all): %u", count);
4885 // Each loop prints the name of an endpoint device.
4886 for (ULONG i = 0; i < count; i++)
4888 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Endpoint %d:", i);
4890 // Get pointer to endpoint number i.
4891 // Output: IMMDevice interface.
4892 hr = pCollection->Item(
4895 CONTINUE_ON_ERROR(hr);
4897 // use the IMMDevice interface of the specified endpoint device...
4899 // Get the endpoint ID string (uniquely identifies the device among all audio endpoint devices)
4900 hr = pEndpoint->GetId(&pwszID);
4901 CONTINUE_ON_ERROR(hr);
4902 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "ID string : %S", pwszID);
4904 // Retrieve an interface to the device's property store.
4905 // Output: IPropertyStore interface.
4906 hr = pEndpoint->OpenPropertyStore(
4909 CONTINUE_ON_ERROR(hr);
4911 // use the IPropertyStore interface...
4913 PROPVARIANT varName;
4914 // Initialize container for property value.
4915 PropVariantInit(&varName);
4917 // Get the endpoint's friendly-name property.
4918 // Example: "Speakers (Realtek High Definition Audio)"
4919 hr = pProps->GetValue(
4920 PKEY_Device_FriendlyName,
4922 CONTINUE_ON_ERROR(hr);
4923 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", varName.pwszVal);
4925 // Get the endpoint's current device state
4927 hr = pEndpoint->GetState(&dwState);
4928 CONTINUE_ON_ERROR(hr);
4929 if (dwState & DEVICE_STATE_ACTIVE)
4930 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "state (0x%x) : *ACTIVE*", dwState);
4931 if (dwState & DEVICE_STATE_DISABLED)
4932 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "state (0x%x) : DISABLED", dwState);
4933 if (dwState & DEVICE_STATE_NOTPRESENT)
4934 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "state (0x%x) : NOTPRESENT", dwState);
4935 if (dwState & DEVICE_STATE_UNPLUGGED)
4936 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "state (0x%x) : UNPLUGGED", dwState);
4938 // Check the hardware volume capabilities.
4939 DWORD dwHwSupportMask = 0;
4940 hr = pEndpoint->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL,
4941 NULL, (void**)&pEndpointVolume);
4942 CONTINUE_ON_ERROR(hr);
4943 hr = pEndpointVolume->QueryHardwareSupport(&dwHwSupportMask);
4944 CONTINUE_ON_ERROR(hr);
4945 if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_VOLUME)
4946 // The audio endpoint device supports a hardware volume control
4947 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "hwmask (0x%x) : HARDWARE_SUPPORT_VOLUME", dwHwSupportMask);
4948 if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_MUTE)
4949 // The audio endpoint device supports a hardware mute control
4950 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "hwmask (0x%x) : HARDWARE_SUPPORT_MUTE", dwHwSupportMask);
4951 if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_METER)
4952 // The audio endpoint device supports a hardware peak meter
4953 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "hwmask (0x%x) : HARDWARE_SUPPORT_METER", dwHwSupportMask);
4955 // Check the channel count (#channels in the audio stream that enters or leaves the audio endpoint device)
4956 UINT nChannelCount(0);
4957 hr = pEndpointVolume->GetChannelCount(
4959 CONTINUE_ON_ERROR(hr);
4960 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#channels : %u", nChannelCount);
4962 if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_VOLUME)
4964 // Get the volume range.
4965 float fLevelMinDB(0.0);
4966 float fLevelMaxDB(0.0);
4967 float fVolumeIncrementDB(0.0);
4968 hr = pEndpointVolume->GetVolumeRange(
4971 &fVolumeIncrementDB);
4972 CONTINUE_ON_ERROR(hr);
4973 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "volume range : %4.2f (min), %4.2f (max), %4.2f (inc) [dB]",
4974 fLevelMinDB, fLevelMaxDB, fVolumeIncrementDB);
4976 // The volume range from vmin = fLevelMinDB to vmax = fLevelMaxDB is divided
4977 // into n uniform intervals of size vinc = fVolumeIncrementDB, where
4978 // n = (vmax ?vmin) / vinc.
4979 // The values vmin, vmax, and vinc are measured in decibels. The client can set
4980 // the volume level to one of n + 1 discrete values in the range from vmin to vmax.
4981 int n = (int)((fLevelMaxDB-fLevelMinDB)/fVolumeIncrementDB);
4982 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#intervals : %d", n);
4984 // Get information about the current step in the volume range.
4985 // This method represents the volume level of the audio stream that enters or leaves
4986 // the audio endpoint device as an index or "step" in a range of discrete volume levels.
4987 // Output value nStepCount is the number of steps in the range. Output value nStep
4988 // is the step index of the current volume level. If the number of steps is n = nStepCount,
4989 // then step index nStep can assume values from 0 (minimum volume) to n ?1 (maximum volume).
4992 hr = pEndpointVolume->GetVolumeStepInfo(
4995 CONTINUE_ON_ERROR(hr);
4996 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "volume steps : %d (nStep), %d (nStepCount)", nStep, nStepCount);
5000 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
5001 "Error when logging device information");
5003 CoTaskMemFree(pwszID);
5005 PropVariantClear(&varName);
5006 SAFE_RELEASE(pProps);
5007 SAFE_RELEASE(pEndpoint);
5008 SAFE_RELEASE(pEndpointVolume);
5010 SAFE_RELEASE(pCollection);
5015 CoTaskMemFree(pwszID);
5017 SAFE_RELEASE(pCollection);
5018 SAFE_RELEASE(pEndpoint);
5019 SAFE_RELEASE(pEndpointVolume);
5020 SAFE_RELEASE(pProps);
5024 // ----------------------------------------------------------------------------
5026 // ----------------------------------------------------------------------------
5028 void AudioDeviceWindowsCore::_TraceCOMError(HRESULT hr) const
5030 TCHAR buf[MAXERRORLENGTH];
5031 TCHAR errorText[MAXERRORLENGTH];
5033 const DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM |
5034 FORMAT_MESSAGE_IGNORE_INSERTS;
5035 const DWORD dwLangID = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
5037 // Gets the system's human readable message string for this HRESULT.
5038 // All error message in English by default.
5039 DWORD messageLength = ::FormatMessageW(dwFlags,
5047 assert(messageLength <= MAXERRORLENGTH);
5049 // Trims tailing white space (FormatMessage() leaves a trailing cr-lf.).
5050 for (; messageLength && ::isspace(errorText[messageLength - 1]);
5053 errorText[messageLength - 1] = '\0';
5056 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
5057 "Core Audio method failed (hr=0x%x)", hr);
5058 StringCchPrintf(buf, MAXERRORLENGTH, TEXT("Error details: "));
5059 StringCchCat(buf, MAXERRORLENGTH, errorText);
5060 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "%s", WideToUTF8(buf));
5063 // ----------------------------------------------------------------------------
5065 // ----------------------------------------------------------------------------
5067 void AudioDeviceWindowsCore::_SetThreadName(DWORD dwThreadID, LPCSTR szThreadName)
5069 // See http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx for details on the code
5070 // in this function. Name of article is "Setting a Thread Name (Unmanaged)".
5072 THREADNAME_INFO info;
5073 info.dwType = 0x1000;
5074 info.szName = szThreadName;
5075 info.dwThreadID = dwThreadID;
5080 RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD), (ULONG_PTR *)&info );
5082 __except (EXCEPTION_CONTINUE_EXECUTION)
5087 // ----------------------------------------------------------------------------
5089 // ----------------------------------------------------------------------------
5091 char* AudioDeviceWindowsCore::WideToUTF8(const TCHAR* src) const {
5093 const size_t kStrLen = sizeof(_str);
5094 memset(_str, 0, kStrLen);
5095 // Get required size (in bytes) to be able to complete the conversion.
5096 int required_size = WideCharToMultiByte(CP_UTF8, 0, src, -1, _str, 0, 0, 0);
5097 if (required_size <= kStrLen)
5099 // Process the entire input string, including the terminating null char.
5100 if (WideCharToMultiByte(CP_UTF8, 0, src, -1, _str, kStrLen, 0, 0) == 0)
5101 memset(_str, 0, kStrLen);
5105 return const_cast<char*>(src);
5110 bool AudioDeviceWindowsCore::KeyPressed() const{
5113 for (int key = VK_SPACE; key < VK_NUMLOCK; key++) {
5114 short res = GetAsyncKeyState(key);
5115 key_down |= res & 0x1; // Get the LSB
5117 return (key_down > 0);
5119 } // namespace webrtc
5121 #endif // WEBRTC_WINDOWS_CORE_AUDIO_BUILD