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 #if defined(WEBRTC_WINDOWS_CORE_AUDIO_BUILD)
24 #pragma message(">> INFO: WEBRTC_WINDOWS_CORE_AUDIO_BUILD is defined")
26 #pragma message(">> INFO: WEBRTC_WINDOWS_CORE_AUDIO_BUILD is *not* defined")
29 #ifdef WEBRTC_WINDOWS_CORE_AUDIO_BUILD
31 #include "webrtc/modules/audio_device/win/audio_device_core_win.h"
39 #include <Functiondiscoverykeys_devpkey.h>
44 #include "webrtc/modules/audio_device/audio_device_utility.h"
45 #include "webrtc/system_wrappers/interface/sleep.h"
46 #include "webrtc/system_wrappers/interface/trace.h"
48 // Macro that calls a COM method returning HRESULT value.
49 #define EXIT_ON_ERROR(hres) do { if (FAILED(hres)) goto Exit; } while(0)
51 // Macro that continues to a COM error.
52 #define CONTINUE_ON_ERROR(hres) do { if (FAILED(hres)) goto Next; } while(0)
54 // Macro that releases a COM object if not NULL.
55 #define SAFE_RELEASE(p) do { if ((p)) { (p)->Release(); (p) = NULL; } } while(0)
57 #define ROUND(x) ((x) >=0 ? (int)((x) + 0.5) : (int)((x) - 0.5))
59 // REFERENCE_TIME time units per millisecond
60 #define REFTIMES_PER_MILLISEC 10000
62 typedef struct tagTHREADNAME_INFO
64 DWORD dwType; // must be 0x1000
65 LPCSTR szName; // pointer to name (in user addr space)
66 DWORD dwThreadID; // thread ID (-1=caller thread)
67 DWORD dwFlags; // reserved for future use, must be zero
73 enum { COM_THREADING_MODEL = COINIT_MULTITHREADED };
77 kAecCaptureStreamIndex = 0,
78 kAecRenderStreamIndex = 1
81 // An implementation of IMediaBuffer, as required for
82 // IMediaObject::ProcessOutput(). After consuming data provided by
83 // ProcessOutput(), call SetLength() to update the buffer availability.
85 // Example implementation:
86 // http://msdn.microsoft.com/en-us/library/dd376684(v=vs.85).aspx
87 class MediaBufferImpl : public IMediaBuffer
90 explicit MediaBufferImpl(DWORD maxLength)
91 : _data(new BYTE[maxLength]),
93 _maxLength(maxLength),
97 // IMediaBuffer methods.
98 STDMETHOD(GetBufferAndLength(BYTE** ppBuffer, DWORD* pcbLength))
100 if (!ppBuffer || !pcbLength)
106 *pcbLength = _length;
111 STDMETHOD(GetMaxLength(DWORD* pcbMaxLength))
118 *pcbMaxLength = _maxLength;
122 STDMETHOD(SetLength(DWORD cbLength))
124 if (cbLength > _maxLength)
134 STDMETHOD_(ULONG, AddRef())
136 return InterlockedIncrement(&_refCount);
139 STDMETHOD(QueryInterface(REFIID riid, void** ppv))
145 else if (riid != IID_IMediaBuffer && riid != IID_IUnknown)
147 return E_NOINTERFACE;
150 *ppv = static_cast<IMediaBuffer*>(this);
155 STDMETHOD_(ULONG, Release())
157 LONG refCount = InterlockedDecrement(&_refCount);
174 const DWORD _maxLength;
179 // ============================================================================
181 // ============================================================================
183 // ----------------------------------------------------------------------------
184 // CoreAudioIsSupported
185 // ----------------------------------------------------------------------------
187 bool AudioDeviceWindowsCore::CoreAudioIsSupported()
189 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, -1, "%s", __FUNCTION__);
191 bool MMDeviceIsAvailable(false);
192 bool coreAudioIsSupported(false);
195 TCHAR buf[MAXERRORLENGTH];
196 TCHAR errorText[MAXERRORLENGTH];
198 // 1) Check if Windows version is Vista SP1 or later.
200 // CoreAudio is only available on Vista SP1 and later.
202 OSVERSIONINFOEX osvi;
203 DWORDLONG dwlConditionMask = 0;
204 int op = VER_LESS_EQUAL;
206 // Initialize the OSVERSIONINFOEX structure.
207 ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
208 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
209 osvi.dwMajorVersion = 6;
210 osvi.dwMinorVersion = 0;
211 osvi.wServicePackMajor = 0;
212 osvi.wServicePackMinor = 0;
213 osvi.wProductType = VER_NT_WORKSTATION;
215 // Initialize the condition mask.
216 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, op);
217 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, op);
218 VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMAJOR, op);
219 VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMINOR, op);
220 VER_SET_CONDITION(dwlConditionMask, VER_PRODUCT_TYPE, VER_EQUAL);
222 DWORD dwTypeMask = VER_MAJORVERSION | VER_MINORVERSION |
223 VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR |
227 BOOL isVistaRTMorXP = VerifyVersionInfo(&osvi, dwTypeMask,
229 if (isVistaRTMorXP != 0)
231 WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, -1,
232 "*** Windows Core Audio is only supported on Vista SP1 or later "
233 "=> will revert to the Wave API ***");
237 // 2) Initializes the COM library for use by the calling thread.
239 // The COM init wrapper sets the thread's concurrency model to MTA,
240 // and creates a new apartment for the thread if one is required. The
241 // wrapper also ensures that each call to CoInitializeEx is balanced
242 // by a corresponding call to CoUninitialize.
244 ScopedCOMInitializer comInit(ScopedCOMInitializer::kMTA);
245 if (!comInit.succeeded()) {
246 // Things will work even if an STA thread is calling this method but we
247 // want to ensure that MTA is used and therefore return false here.
251 // 3) Check if the MMDevice API is available.
253 // The Windows Multimedia Device (MMDevice) API enables audio clients to
254 // discover audio endpoint devices, determine their capabilities, and create
255 // driver instances for those devices.
256 // Header file Mmdeviceapi.h defines the interfaces in the MMDevice API.
257 // The MMDevice API consists of several interfaces. The first of these is the
258 // IMMDeviceEnumerator interface. To access the interfaces in the MMDevice API,
259 // a client obtains a reference to the IMMDeviceEnumerator interface of a
260 // device-enumerator object by calling the CoCreateInstance function.
262 // Through the IMMDeviceEnumerator interface, the client can obtain references
263 // to the other interfaces in the MMDevice API. The MMDevice API implements
264 // the following interfaces:
266 // IMMDevice Represents an audio device.
267 // IMMDeviceCollection Represents a collection of audio devices.
268 // IMMDeviceEnumerator Provides methods for enumerating audio devices.
269 // IMMEndpoint Represents an audio endpoint device.
271 IMMDeviceEnumerator* pIMMD(NULL);
272 const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
273 const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
275 hr = CoCreateInstance(
276 CLSID_MMDeviceEnumerator, // GUID value of MMDeviceEnumerator coclass
279 IID_IMMDeviceEnumerator, // GUID value of the IMMDeviceEnumerator interface
284 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
285 "AudioDeviceWindowsCore::CoreAudioIsSupported() Failed to create the required COM object", hr);
286 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, -1,
287 "AudioDeviceWindowsCore::CoreAudioIsSupported() CoCreateInstance(MMDeviceEnumerator) failed (hr=0x%x)", hr);
289 const DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM |
290 FORMAT_MESSAGE_IGNORE_INSERTS;
291 const DWORD dwLangID = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
293 // Gets the system's human readable message string for this HRESULT.
294 // All error message in English by default.
295 DWORD messageLength = ::FormatMessageW(dwFlags,
303 assert(messageLength <= MAXERRORLENGTH);
305 // Trims tailing white space (FormatMessage() leaves a trailing cr-lf.).
306 for (; messageLength && ::isspace(errorText[messageLength - 1]);
309 errorText[messageLength - 1] = '\0';
312 StringCchPrintf(buf, MAXERRORLENGTH, TEXT("Error details: "));
313 StringCchCat(buf, MAXERRORLENGTH, errorText);
314 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, -1, "%S", buf);
318 MMDeviceIsAvailable = true;
319 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, -1,
320 "AudioDeviceWindowsCore::CoreAudioIsSupported() CoCreateInstance(MMDeviceEnumerator) succeeded", hr);
324 // 4) Verify that we can create and initialize our Core Audio class.
326 // Also, perform a limited "API test" to ensure that Core Audio is supported for all devices.
328 if (MMDeviceIsAvailable)
330 coreAudioIsSupported = false;
332 AudioDeviceWindowsCore* p = new AudioDeviceWindowsCore(-1);
340 bool available(false);
344 int16_t numDevsRec = p->RecordingDevices();
345 for (uint16_t i = 0; i < numDevsRec; i++)
347 ok |= p->SetRecordingDevice(i);
348 temp_ok = p->RecordingIsAvailable(available);
350 ok |= (available == false);
353 ok |= p->InitMicrophone();
357 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, -1,
358 "AudioDeviceWindowsCore::CoreAudioIsSupported() Failed to use Core Audio Recording for device id=%i", i);
362 int16_t numDevsPlay = p->PlayoutDevices();
363 for (uint16_t i = 0; i < numDevsPlay; i++)
365 ok |= p->SetPlayoutDevice(i);
366 temp_ok = p->PlayoutIsAvailable(available);
368 ok |= (available == false);
371 ok |= p->InitSpeaker();
375 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, -1 ,
376 "AudioDeviceWindowsCore::CoreAudioIsSupported() Failed to use Core Audio Playout for device id=%i", i);
380 ok |= p->Terminate();
384 coreAudioIsSupported = true;
390 if (coreAudioIsSupported)
392 WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, -1, "*** Windows Core Audio is supported ***");
396 WEBRTC_TRACE(kTraceStateInfo, kTraceAudioDevice, -1, "*** Windows Core Audio is NOT supported => will revert to the Wave API ***");
399 return (coreAudioIsSupported);
402 // ============================================================================
403 // Construction & Destruction
404 // ============================================================================
406 // ----------------------------------------------------------------------------
407 // AudioDeviceWindowsCore() - ctor
408 // ----------------------------------------------------------------------------
410 AudioDeviceWindowsCore::AudioDeviceWindowsCore(const int32_t id) :
411 _comInit(ScopedCOMInitializer::kMTA),
412 _critSect(*CriticalSectionWrapper::CreateCriticalSection()),
413 _volumeMutex(*CriticalSectionWrapper::CreateCriticalSection()),
415 _ptrAudioBuffer(NULL),
416 _ptrEnumerator(NULL),
417 _ptrRenderCollection(NULL),
418 _ptrCaptureCollection(NULL),
423 _ptrRenderClient(NULL),
424 _ptrCaptureClient(NULL),
425 _ptrCaptureVolume(NULL),
426 _ptrRenderSimpleVolume(NULL),
429 _builtInAecEnabled(false),
430 _playAudioFrameSize(0),
434 _sndCardPlayDelay(0),
439 _recAudioFrameSize(0),
444 _winSupportAvrt(false),
445 _hRenderSamplesReadyEvent(NULL),
447 _hCaptureSamplesReadyEvent(NULL),
449 _hShutdownRenderEvent(NULL),
450 _hShutdownCaptureEvent(NULL),
451 _hRenderStartedEvent(NULL),
452 _hCaptureStartedEvent(NULL),
453 _hGetCaptureVolumeThread(NULL),
454 _hSetCaptureVolumeThread(NULL),
455 _hSetCaptureVolumeEvent(NULL),
460 _recIsInitialized(false),
461 _playIsInitialized(false),
462 _speakerIsInitialized(false),
463 _microphoneIsInitialized(false),
469 _playBufType(AudioDeviceModule::kAdaptiveBufferSize),
471 _playBufDelayFixed(80),
472 _usingInputDeviceIndex(false),
473 _usingOutputDeviceIndex(false),
474 _inputDevice(AudioDeviceModule::kDefaultCommunicationDevice),
475 _outputDevice(AudioDeviceModule::kDefaultCommunicationDevice),
476 _inputDeviceIndex(0),
477 _outputDeviceIndex(0),
480 WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, id, "%s created", __FUNCTION__);
481 assert(_comInit.succeeded());
483 // Try to load the Avrt DLL
486 // Get handle to the Avrt DLL module.
487 _avrtLibrary = LoadLibrary(TEXT("Avrt.dll"));
490 // Handle is valid (should only happen if OS larger than vista & win7).
491 // Try to get the function addresses.
492 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::AudioDeviceWindowsCore() The Avrt DLL module is now loaded");
494 _PAvRevertMmThreadCharacteristics = (PAvRevertMmThreadCharacteristics)GetProcAddress(_avrtLibrary, "AvRevertMmThreadCharacteristics");
495 _PAvSetMmThreadCharacteristicsA = (PAvSetMmThreadCharacteristicsA)GetProcAddress(_avrtLibrary, "AvSetMmThreadCharacteristicsA");
496 _PAvSetMmThreadPriority = (PAvSetMmThreadPriority)GetProcAddress(_avrtLibrary, "AvSetMmThreadPriority");
498 if ( _PAvRevertMmThreadCharacteristics &&
499 _PAvSetMmThreadCharacteristicsA &&
500 _PAvSetMmThreadPriority)
502 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::AudioDeviceWindowsCore() AvRevertMmThreadCharacteristics() is OK");
503 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::AudioDeviceWindowsCore() AvSetMmThreadCharacteristicsA() is OK");
504 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::AudioDeviceWindowsCore() AvSetMmThreadPriority() is OK");
505 _winSupportAvrt = true;
510 // Create our samples ready events - we want auto reset events that start in the not-signaled state.
511 // The state of an auto-reset event object remains signaled until a single waiting thread is released,
512 // at which time the system automatically sets the state to nonsignaled. If no threads are waiting,
513 // the event object's state remains signaled.
514 // (Except for _hShutdownCaptureEvent, which is used to shutdown multiple threads).
515 _hRenderSamplesReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
516 _hCaptureSamplesReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
517 _hShutdownRenderEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
518 _hShutdownCaptureEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
519 _hRenderStartedEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
520 _hCaptureStartedEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
521 _hSetCaptureVolumeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
523 _perfCounterFreq.QuadPart = 1;
524 _perfCounterFactor = 0.0;
527 // list of number of channels to use on recording side
528 _recChannelsPrioList[0] = 2; // stereo is prio 1
529 _recChannelsPrioList[1] = 1; // mono is prio 2
531 // list of number of channels to use on playout side
532 _playChannelsPrioList[0] = 2; // stereo is prio 1
533 _playChannelsPrioList[1] = 1; // mono is prio 2
537 // We know that this API will work since it has already been verified in
538 // CoreAudioIsSupported, hence no need to check for errors here as well.
540 // Retrive the IMMDeviceEnumerator API (should load the MMDevAPI.dll)
541 // TODO(henrika): we should probably move this allocation to Init() instead
542 // and deallocate in Terminate() to make the implementation more symmetric.
544 __uuidof(MMDeviceEnumerator),
547 __uuidof(IMMDeviceEnumerator),
548 reinterpret_cast<void**>(&_ptrEnumerator));
549 assert(NULL != _ptrEnumerator);
551 // DMO initialization for built-in WASAPI AEC.
553 IMediaObject* ptrDMO = NULL;
554 hr = CoCreateInstance(CLSID_CWMAudioAEC,
556 CLSCTX_INPROC_SERVER,
558 reinterpret_cast<void**>(&ptrDMO));
559 if (FAILED(hr) || ptrDMO == NULL)
561 // Since we check that _dmo is non-NULL in EnableBuiltInAEC(), the
562 // feature is prevented from being enabled.
563 _builtInAecEnabled = false;
567 SAFE_RELEASE(ptrDMO);
571 // ----------------------------------------------------------------------------
572 // AudioDeviceWindowsCore() - dtor
573 // ----------------------------------------------------------------------------
575 AudioDeviceWindowsCore::~AudioDeviceWindowsCore()
577 WEBRTC_TRACE(kTraceMemory, kTraceAudioDevice, _id, "%s destroyed", __FUNCTION__);
581 // The IMMDeviceEnumerator is created during construction. Must release
582 // it here and not in Terminate() since we don't recreate it in Init().
583 SAFE_RELEASE(_ptrEnumerator);
585 _ptrAudioBuffer = NULL;
587 if (NULL != _hRenderSamplesReadyEvent)
589 CloseHandle(_hRenderSamplesReadyEvent);
590 _hRenderSamplesReadyEvent = NULL;
593 if (NULL != _hCaptureSamplesReadyEvent)
595 CloseHandle(_hCaptureSamplesReadyEvent);
596 _hCaptureSamplesReadyEvent = NULL;
599 if (NULL != _hRenderStartedEvent)
601 CloseHandle(_hRenderStartedEvent);
602 _hRenderStartedEvent = NULL;
605 if (NULL != _hCaptureStartedEvent)
607 CloseHandle(_hCaptureStartedEvent);
608 _hCaptureStartedEvent = NULL;
611 if (NULL != _hShutdownRenderEvent)
613 CloseHandle(_hShutdownRenderEvent);
614 _hShutdownRenderEvent = NULL;
617 if (NULL != _hShutdownCaptureEvent)
619 CloseHandle(_hShutdownCaptureEvent);
620 _hShutdownCaptureEvent = NULL;
623 if (NULL != _hSetCaptureVolumeEvent)
625 CloseHandle(_hSetCaptureVolumeEvent);
626 _hSetCaptureVolumeEvent = NULL;
631 BOOL freeOK = FreeLibrary(_avrtLibrary);
634 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
635 "AudioDeviceWindowsCore::~AudioDeviceWindowsCore() failed to free the loaded Avrt DLL module correctly");
639 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
640 "AudioDeviceWindowsCore::~AudioDeviceWindowsCore() the Avrt DLL module is now unloaded");
645 delete &_volumeMutex;
648 // ============================================================================
650 // ============================================================================
652 // ----------------------------------------------------------------------------
654 // ----------------------------------------------------------------------------
656 void AudioDeviceWindowsCore::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer)
659 _ptrAudioBuffer = audioBuffer;
661 // Inform the AudioBuffer about default settings for this implementation.
662 // Set all values to zero here since the actual settings will be done by
663 // InitPlayout and InitRecording later.
664 _ptrAudioBuffer->SetRecordingSampleRate(0);
665 _ptrAudioBuffer->SetPlayoutSampleRate(0);
666 _ptrAudioBuffer->SetRecordingChannels(0);
667 _ptrAudioBuffer->SetPlayoutChannels(0);
670 // ----------------------------------------------------------------------------
672 // ----------------------------------------------------------------------------
674 int32_t AudioDeviceWindowsCore::ActiveAudioLayer(AudioDeviceModule::AudioLayer& audioLayer) const
676 audioLayer = AudioDeviceModule::kWindowsCoreAudio;
680 // ----------------------------------------------------------------------------
682 // ----------------------------------------------------------------------------
684 int32_t AudioDeviceWindowsCore::Init()
687 CriticalSectionScoped lock(&_critSect);
699 // Enumerate all audio rendering and capturing endpoint devices.
700 // Note that, some of these will not be able to select by the user.
701 // The complete collection is for internal use only.
703 _EnumerateEndpointDevicesAll(eRender);
704 _EnumerateEndpointDevicesAll(eCapture);
711 // ----------------------------------------------------------------------------
713 // ----------------------------------------------------------------------------
715 int32_t AudioDeviceWindowsCore::Terminate()
718 CriticalSectionScoped lock(&_critSect);
724 _initialized = false;
725 _speakerIsInitialized = false;
726 _microphoneIsInitialized = false;
730 SAFE_RELEASE(_ptrRenderCollection);
731 SAFE_RELEASE(_ptrCaptureCollection);
732 SAFE_RELEASE(_ptrDeviceOut);
733 SAFE_RELEASE(_ptrDeviceIn);
734 SAFE_RELEASE(_ptrClientOut);
735 SAFE_RELEASE(_ptrClientIn);
736 SAFE_RELEASE(_ptrRenderClient);
737 SAFE_RELEASE(_ptrCaptureClient);
738 SAFE_RELEASE(_ptrCaptureVolume);
739 SAFE_RELEASE(_ptrRenderSimpleVolume);
744 // ----------------------------------------------------------------------------
746 // ----------------------------------------------------------------------------
748 bool AudioDeviceWindowsCore::Initialized() const
750 return (_initialized);
753 // ----------------------------------------------------------------------------
755 // ----------------------------------------------------------------------------
757 int32_t AudioDeviceWindowsCore::InitSpeaker()
760 CriticalSectionScoped lock(&_critSect);
767 if (_ptrDeviceOut == NULL)
772 if (_usingOutputDeviceIndex)
774 int16_t nDevices = PlayoutDevices();
775 if (_outputDeviceIndex > (nDevices - 1))
777 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "current device selection is invalid => unable to initialize");
784 SAFE_RELEASE(_ptrDeviceOut);
785 if (_usingOutputDeviceIndex)
787 // Refresh the selected rendering endpoint device using current index
788 ret = _GetListDevice(eRender, _outputDeviceIndex, &_ptrDeviceOut);
793 (_outputDevice == AudioDeviceModule::kDefaultDevice) ? role = eConsole : role = eCommunications;
794 // Refresh the selected rendering endpoint device using role
795 ret = _GetDefaultDevice(eRender, role, &_ptrDeviceOut);
798 if (ret != 0 || (_ptrDeviceOut == NULL))
800 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "failed to initialize the rendering enpoint device");
801 SAFE_RELEASE(_ptrDeviceOut);
805 IAudioSessionManager* pManager = NULL;
806 ret = _ptrDeviceOut->Activate(__uuidof(IAudioSessionManager),
810 if (ret != 0 || pManager == NULL)
812 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
813 " failed to initialize the render manager");
814 SAFE_RELEASE(pManager);
818 SAFE_RELEASE(_ptrRenderSimpleVolume);
819 ret = pManager->GetSimpleAudioVolume(NULL, FALSE, &_ptrRenderSimpleVolume);
820 if (ret != 0 || _ptrRenderSimpleVolume == NULL)
822 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
823 " failed to initialize the render simple volume");
824 SAFE_RELEASE(pManager);
825 SAFE_RELEASE(_ptrRenderSimpleVolume);
828 SAFE_RELEASE(pManager);
830 _speakerIsInitialized = true;
835 // ----------------------------------------------------------------------------
837 // ----------------------------------------------------------------------------
839 int32_t AudioDeviceWindowsCore::InitMicrophone()
842 CriticalSectionScoped lock(&_critSect);
849 if (_ptrDeviceIn == NULL)
854 if (_usingInputDeviceIndex)
856 int16_t nDevices = RecordingDevices();
857 if (_inputDeviceIndex > (nDevices - 1))
859 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "current device selection is invalid => unable to initialize");
866 SAFE_RELEASE(_ptrDeviceIn);
867 if (_usingInputDeviceIndex)
869 // Refresh the selected capture endpoint device using current index
870 ret = _GetListDevice(eCapture, _inputDeviceIndex, &_ptrDeviceIn);
875 (_inputDevice == AudioDeviceModule::kDefaultDevice) ? role = eConsole : role = eCommunications;
876 // Refresh the selected capture endpoint device using role
877 ret = _GetDefaultDevice(eCapture, role, &_ptrDeviceIn);
880 if (ret != 0 || (_ptrDeviceIn == NULL))
882 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "failed to initialize the capturing enpoint device");
883 SAFE_RELEASE(_ptrDeviceIn);
887 ret = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume),
890 reinterpret_cast<void **>(&_ptrCaptureVolume));
891 if (ret != 0 || _ptrCaptureVolume == NULL)
893 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
894 " failed to initialize the capture volume");
895 SAFE_RELEASE(_ptrCaptureVolume);
899 _microphoneIsInitialized = true;
904 // ----------------------------------------------------------------------------
905 // SpeakerIsInitialized
906 // ----------------------------------------------------------------------------
908 bool AudioDeviceWindowsCore::SpeakerIsInitialized() const
911 return (_speakerIsInitialized);
914 // ----------------------------------------------------------------------------
915 // MicrophoneIsInitialized
916 // ----------------------------------------------------------------------------
918 bool AudioDeviceWindowsCore::MicrophoneIsInitialized() const
921 return (_microphoneIsInitialized);
924 // ----------------------------------------------------------------------------
925 // SpeakerVolumeIsAvailable
926 // ----------------------------------------------------------------------------
928 int32_t AudioDeviceWindowsCore::SpeakerVolumeIsAvailable(bool& available)
931 CriticalSectionScoped lock(&_critSect);
933 if (_ptrDeviceOut == NULL)
939 IAudioSessionManager* pManager = NULL;
940 ISimpleAudioVolume* pVolume = NULL;
942 hr = _ptrDeviceOut->Activate(__uuidof(IAudioSessionManager), CLSCTX_ALL, NULL, (void**)&pManager);
945 hr = pManager->GetSimpleAudioVolume(NULL, FALSE, &pVolume);
949 hr = pVolume->GetMasterVolume(&volume);
956 SAFE_RELEASE(pManager);
957 SAFE_RELEASE(pVolume);
963 SAFE_RELEASE(pManager);
964 SAFE_RELEASE(pVolume);
968 // ----------------------------------------------------------------------------
970 // ----------------------------------------------------------------------------
972 int32_t AudioDeviceWindowsCore::SetSpeakerVolume(uint32_t volume)
976 CriticalSectionScoped lock(&_critSect);
978 if (!_speakerIsInitialized)
983 if (_ptrDeviceOut == NULL)
989 if (volume < (uint32_t)MIN_CORE_SPEAKER_VOLUME ||
990 volume > (uint32_t)MAX_CORE_SPEAKER_VOLUME)
997 // scale input volume to valid range (0.0 to 1.0)
998 const float fLevel = (float)volume/MAX_CORE_SPEAKER_VOLUME;
999 _volumeMutex.Enter();
1000 hr = _ptrRenderSimpleVolume->SetMasterVolume(fLevel,NULL);
1001 _volumeMutex.Leave();
1011 // ----------------------------------------------------------------------------
1013 // ----------------------------------------------------------------------------
1015 int32_t AudioDeviceWindowsCore::SpeakerVolume(uint32_t& volume) const
1019 CriticalSectionScoped lock(&_critSect);
1021 if (!_speakerIsInitialized)
1026 if (_ptrDeviceOut == NULL)
1035 _volumeMutex.Enter();
1036 hr = _ptrRenderSimpleVolume->GetMasterVolume(&fLevel);
1037 _volumeMutex.Leave();
1040 // scale input volume range [0.0,1.0] to valid output range
1041 volume = static_cast<uint32_t> (fLevel*MAX_CORE_SPEAKER_VOLUME);
1050 // ----------------------------------------------------------------------------
1052 // ----------------------------------------------------------------------------
1054 int32_t AudioDeviceWindowsCore::SetWaveOutVolume(uint16_t volumeLeft, uint16_t volumeRight)
1059 // ----------------------------------------------------------------------------
1061 // ----------------------------------------------------------------------------
1063 int32_t AudioDeviceWindowsCore::WaveOutVolume(uint16_t& volumeLeft, uint16_t& volumeRight) const
1068 // ----------------------------------------------------------------------------
1071 // The internal range for Core Audio is 0.0 to 1.0, where 0.0 indicates
1072 // silence and 1.0 indicates full volume (no attenuation).
1073 // We add our (webrtc-internal) own max level to match the Wave API and
1074 // how it is used today in VoE.
1075 // ----------------------------------------------------------------------------
1077 int32_t AudioDeviceWindowsCore::MaxSpeakerVolume(uint32_t& maxVolume) const
1080 if (!_speakerIsInitialized)
1085 maxVolume = static_cast<uint32_t> (MAX_CORE_SPEAKER_VOLUME);
1090 // ----------------------------------------------------------------------------
1092 // ----------------------------------------------------------------------------
1094 int32_t AudioDeviceWindowsCore::MinSpeakerVolume(uint32_t& minVolume) const
1097 if (!_speakerIsInitialized)
1102 minVolume = static_cast<uint32_t> (MIN_CORE_SPEAKER_VOLUME);
1107 // ----------------------------------------------------------------------------
1108 // SpeakerVolumeStepSize
1109 // ----------------------------------------------------------------------------
1111 int32_t AudioDeviceWindowsCore::SpeakerVolumeStepSize(uint16_t& stepSize) const
1114 if (!_speakerIsInitialized)
1119 stepSize = CORE_SPEAKER_VOLUME_STEP_SIZE;
1124 // ----------------------------------------------------------------------------
1125 // SpeakerMuteIsAvailable
1126 // ----------------------------------------------------------------------------
1128 int32_t AudioDeviceWindowsCore::SpeakerMuteIsAvailable(bool& available)
1131 CriticalSectionScoped lock(&_critSect);
1133 if (_ptrDeviceOut == NULL)
1139 IAudioEndpointVolume* pVolume = NULL;
1141 // Query the speaker system mute state.
1142 hr = _ptrDeviceOut->Activate(__uuidof(IAudioEndpointVolume),
1143 CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1147 hr = pVolume->GetMute(&mute);
1153 SAFE_RELEASE(pVolume);
1159 SAFE_RELEASE(pVolume);
1163 // ----------------------------------------------------------------------------
1165 // ----------------------------------------------------------------------------
1167 int32_t AudioDeviceWindowsCore::SetSpeakerMute(bool enable)
1170 CriticalSectionScoped lock(&_critSect);
1172 if (!_speakerIsInitialized)
1177 if (_ptrDeviceOut == NULL)
1183 IAudioEndpointVolume* pVolume = NULL;
1185 // Set the speaker system mute state.
1186 hr = _ptrDeviceOut->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1189 const BOOL mute(enable);
1190 hr = pVolume->SetMute(mute, NULL);
1193 SAFE_RELEASE(pVolume);
1199 SAFE_RELEASE(pVolume);
1203 // ----------------------------------------------------------------------------
1205 // ----------------------------------------------------------------------------
1207 int32_t AudioDeviceWindowsCore::SpeakerMute(bool& enabled) const
1210 if (!_speakerIsInitialized)
1215 if (_ptrDeviceOut == NULL)
1221 IAudioEndpointVolume* pVolume = NULL;
1223 // Query the speaker system mute state.
1224 hr = _ptrDeviceOut->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1228 hr = pVolume->GetMute(&mute);
1231 enabled = (mute == TRUE) ? true : false;
1233 SAFE_RELEASE(pVolume);
1239 SAFE_RELEASE(pVolume);
1243 // ----------------------------------------------------------------------------
1244 // MicrophoneMuteIsAvailable
1245 // ----------------------------------------------------------------------------
1247 int32_t AudioDeviceWindowsCore::MicrophoneMuteIsAvailable(bool& available)
1250 CriticalSectionScoped lock(&_critSect);
1252 if (_ptrDeviceIn == NULL)
1258 IAudioEndpointVolume* pVolume = NULL;
1260 // Query the microphone system mute state.
1261 hr = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1265 hr = pVolume->GetMute(&mute);
1271 SAFE_RELEASE(pVolume);
1276 SAFE_RELEASE(pVolume);
1280 // ----------------------------------------------------------------------------
1281 // SetMicrophoneMute
1282 // ----------------------------------------------------------------------------
1284 int32_t AudioDeviceWindowsCore::SetMicrophoneMute(bool enable)
1287 if (!_microphoneIsInitialized)
1292 if (_ptrDeviceIn == NULL)
1298 IAudioEndpointVolume* pVolume = NULL;
1300 // Set the microphone system mute state.
1301 hr = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1304 const BOOL mute(enable);
1305 hr = pVolume->SetMute(mute, NULL);
1308 SAFE_RELEASE(pVolume);
1313 SAFE_RELEASE(pVolume);
1317 // ----------------------------------------------------------------------------
1319 // ----------------------------------------------------------------------------
1321 int32_t AudioDeviceWindowsCore::MicrophoneMute(bool& enabled) const
1324 if (!_microphoneIsInitialized)
1330 IAudioEndpointVolume* pVolume = NULL;
1332 // Query the microphone system mute state.
1333 hr = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1337 hr = pVolume->GetMute(&mute);
1340 enabled = (mute == TRUE) ? true : false;
1342 SAFE_RELEASE(pVolume);
1347 SAFE_RELEASE(pVolume);
1351 // ----------------------------------------------------------------------------
1352 // MicrophoneBoostIsAvailable
1353 // ----------------------------------------------------------------------------
1355 int32_t AudioDeviceWindowsCore::MicrophoneBoostIsAvailable(bool& available)
1362 // ----------------------------------------------------------------------------
1363 // SetMicrophoneBoost
1364 // ----------------------------------------------------------------------------
1366 int32_t AudioDeviceWindowsCore::SetMicrophoneBoost(bool enable)
1369 if (!_microphoneIsInitialized)
1377 // ----------------------------------------------------------------------------
1379 // ----------------------------------------------------------------------------
1381 int32_t AudioDeviceWindowsCore::MicrophoneBoost(bool& enabled) const
1384 if (!_microphoneIsInitialized)
1392 // ----------------------------------------------------------------------------
1393 // StereoRecordingIsAvailable
1394 // ----------------------------------------------------------------------------
1396 int32_t AudioDeviceWindowsCore::StereoRecordingIsAvailable(bool& available)
1403 // ----------------------------------------------------------------------------
1404 // SetStereoRecording
1405 // ----------------------------------------------------------------------------
1407 int32_t AudioDeviceWindowsCore::SetStereoRecording(bool enable)
1410 CriticalSectionScoped lock(&_critSect);
1414 _recChannelsPrioList[0] = 2; // try stereo first
1415 _recChannelsPrioList[1] = 1;
1420 _recChannelsPrioList[0] = 1; // try mono first
1421 _recChannelsPrioList[1] = 2;
1428 // ----------------------------------------------------------------------------
1430 // ----------------------------------------------------------------------------
1432 int32_t AudioDeviceWindowsCore::StereoRecording(bool& enabled) const
1435 if (_recChannels == 2)
1443 // ----------------------------------------------------------------------------
1444 // StereoPlayoutIsAvailable
1445 // ----------------------------------------------------------------------------
1447 int32_t AudioDeviceWindowsCore::StereoPlayoutIsAvailable(bool& available)
1454 // ----------------------------------------------------------------------------
1456 // ----------------------------------------------------------------------------
1458 int32_t AudioDeviceWindowsCore::SetStereoPlayout(bool enable)
1461 CriticalSectionScoped lock(&_critSect);
1465 _playChannelsPrioList[0] = 2; // try stereo first
1466 _playChannelsPrioList[1] = 1;
1471 _playChannelsPrioList[0] = 1; // try mono first
1472 _playChannelsPrioList[1] = 2;
1479 // ----------------------------------------------------------------------------
1481 // ----------------------------------------------------------------------------
1483 int32_t AudioDeviceWindowsCore::StereoPlayout(bool& enabled) const
1486 if (_playChannels == 2)
1494 // ----------------------------------------------------------------------------
1496 // ----------------------------------------------------------------------------
1498 int32_t AudioDeviceWindowsCore::SetAGC(bool enable)
1500 CriticalSectionScoped lock(&_critSect);
1505 // ----------------------------------------------------------------------------
1507 // ----------------------------------------------------------------------------
1509 bool AudioDeviceWindowsCore::AGC() const
1511 CriticalSectionScoped lock(&_critSect);
1515 // ----------------------------------------------------------------------------
1516 // MicrophoneVolumeIsAvailable
1517 // ----------------------------------------------------------------------------
1519 int32_t AudioDeviceWindowsCore::MicrophoneVolumeIsAvailable(bool& available)
1522 CriticalSectionScoped lock(&_critSect);
1524 if (_ptrDeviceIn == NULL)
1530 IAudioEndpointVolume* pVolume = NULL;
1532 hr = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL, reinterpret_cast<void**>(&pVolume));
1536 hr = pVolume->GetMasterVolumeLevelScalar(&volume);
1543 SAFE_RELEASE(pVolume);
1548 SAFE_RELEASE(pVolume);
1552 // ----------------------------------------------------------------------------
1553 // SetMicrophoneVolume
1554 // ----------------------------------------------------------------------------
1556 int32_t AudioDeviceWindowsCore::SetMicrophoneVolume(uint32_t volume)
1558 WEBRTC_TRACE(kTraceStream, kTraceAudioDevice, _id, "AudioDeviceWindowsCore::SetMicrophoneVolume(volume=%u)", volume);
1561 CriticalSectionScoped lock(&_critSect);
1563 if (!_microphoneIsInitialized)
1568 if (_ptrDeviceIn == NULL)
1574 if (volume < static_cast<uint32_t>(MIN_CORE_MICROPHONE_VOLUME) ||
1575 volume > static_cast<uint32_t>(MAX_CORE_MICROPHONE_VOLUME))
1581 // scale input volume to valid range (0.0 to 1.0)
1582 const float fLevel = static_cast<float>(volume)/MAX_CORE_MICROPHONE_VOLUME;
1583 _volumeMutex.Enter();
1584 _ptrCaptureVolume->SetMasterVolumeLevelScalar(fLevel, NULL);
1585 _volumeMutex.Leave();
1595 // ----------------------------------------------------------------------------
1597 // ----------------------------------------------------------------------------
1599 int32_t AudioDeviceWindowsCore::MicrophoneVolume(uint32_t& volume) const
1602 CriticalSectionScoped lock(&_critSect);
1604 if (!_microphoneIsInitialized)
1609 if (_ptrDeviceIn == NULL)
1618 _volumeMutex.Enter();
1619 hr = _ptrCaptureVolume->GetMasterVolumeLevelScalar(&fLevel);
1620 _volumeMutex.Leave();
1623 // scale input volume range [0.0,1.0] to valid output range
1624 volume = static_cast<uint32_t> (fLevel*MAX_CORE_MICROPHONE_VOLUME);
1633 // ----------------------------------------------------------------------------
1634 // MaxMicrophoneVolume
1636 // The internal range for Core Audio is 0.0 to 1.0, where 0.0 indicates
1637 // silence and 1.0 indicates full volume (no attenuation).
1638 // We add our (webrtc-internal) own max level to match the Wave API and
1639 // how it is used today in VoE.
1640 // ----------------------------------------------------------------------------
1642 int32_t AudioDeviceWindowsCore::MaxMicrophoneVolume(uint32_t& maxVolume) const
1644 WEBRTC_TRACE(kTraceStream, kTraceAudioDevice, _id, "%s", __FUNCTION__);
1646 if (!_microphoneIsInitialized)
1651 maxVolume = static_cast<uint32_t> (MAX_CORE_MICROPHONE_VOLUME);
1656 // ----------------------------------------------------------------------------
1657 // MinMicrophoneVolume
1658 // ----------------------------------------------------------------------------
1660 int32_t AudioDeviceWindowsCore::MinMicrophoneVolume(uint32_t& minVolume) const
1663 if (!_microphoneIsInitialized)
1668 minVolume = static_cast<uint32_t> (MIN_CORE_MICROPHONE_VOLUME);
1673 // ----------------------------------------------------------------------------
1674 // MicrophoneVolumeStepSize
1675 // ----------------------------------------------------------------------------
1677 int32_t AudioDeviceWindowsCore::MicrophoneVolumeStepSize(uint16_t& stepSize) const
1680 if (!_microphoneIsInitialized)
1685 stepSize = CORE_MICROPHONE_VOLUME_STEP_SIZE;
1690 // ----------------------------------------------------------------------------
1692 // ----------------------------------------------------------------------------
1694 int16_t AudioDeviceWindowsCore::PlayoutDevices()
1697 CriticalSectionScoped lock(&_critSect);
1699 if (_RefreshDeviceList(eRender) != -1)
1701 return (_DeviceListCount(eRender));
1707 // ----------------------------------------------------------------------------
1708 // SetPlayoutDevice I (II)
1709 // ----------------------------------------------------------------------------
1711 int32_t AudioDeviceWindowsCore::SetPlayoutDevice(uint16_t index)
1714 if (_playIsInitialized)
1719 // Get current number of available rendering endpoint devices and refresh the rendering collection.
1720 UINT nDevices = PlayoutDevices();
1722 if (index < 0 || index > (nDevices-1))
1724 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "device index is out of range [0,%u]", (nDevices-1));
1728 CriticalSectionScoped lock(&_critSect);
1732 assert(_ptrRenderCollection != NULL);
1734 // Select an endpoint rendering device given the specified index
1735 SAFE_RELEASE(_ptrDeviceOut);
1736 hr = _ptrRenderCollection->Item(
1742 SAFE_RELEASE(_ptrDeviceOut);
1746 WCHAR szDeviceName[MAX_PATH];
1747 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
1749 // Get the endpoint device's friendly-name
1750 if (_GetDeviceName(_ptrDeviceOut, szDeviceName, bufferLen) == 0)
1752 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", szDeviceName);
1755 _usingOutputDeviceIndex = true;
1756 _outputDeviceIndex = index;
1761 // ----------------------------------------------------------------------------
1762 // SetPlayoutDevice II (II)
1763 // ----------------------------------------------------------------------------
1765 int32_t AudioDeviceWindowsCore::SetPlayoutDevice(AudioDeviceModule::WindowsDeviceType device)
1767 if (_playIsInitialized)
1772 ERole role(eCommunications);
1774 if (device == AudioDeviceModule::kDefaultDevice)
1778 else if (device == AudioDeviceModule::kDefaultCommunicationDevice)
1780 role = eCommunications;
1783 CriticalSectionScoped lock(&_critSect);
1785 // Refresh the list of rendering endpoint devices
1786 _RefreshDeviceList(eRender);
1790 assert(_ptrEnumerator != NULL);
1792 // Select an endpoint rendering device given the specified role
1793 SAFE_RELEASE(_ptrDeviceOut);
1794 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
1801 SAFE_RELEASE(_ptrDeviceOut);
1805 WCHAR szDeviceName[MAX_PATH];
1806 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
1808 // Get the endpoint device's friendly-name
1809 if (_GetDeviceName(_ptrDeviceOut, szDeviceName, bufferLen) == 0)
1811 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", szDeviceName);
1814 _usingOutputDeviceIndex = false;
1815 _outputDevice = device;
1820 // ----------------------------------------------------------------------------
1821 // PlayoutDeviceName
1822 // ----------------------------------------------------------------------------
1824 int32_t AudioDeviceWindowsCore::PlayoutDeviceName(
1826 char name[kAdmMaxDeviceNameSize],
1827 char guid[kAdmMaxGuidSize])
1830 bool defaultCommunicationDevice(false);
1831 const int16_t nDevices(PlayoutDevices()); // also updates the list of devices
1833 // Special fix for the case when the user selects '-1' as index (<=> Default Communication Device)
1834 if (index == (uint16_t)(-1))
1836 defaultCommunicationDevice = true;
1838 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Default Communication endpoint device will be used");
1841 if ((index > (nDevices-1)) || (name == NULL))
1846 memset(name, 0, kAdmMaxDeviceNameSize);
1850 memset(guid, 0, kAdmMaxGuidSize);
1853 CriticalSectionScoped lock(&_critSect);
1856 WCHAR szDeviceName[MAX_PATH];
1857 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
1859 // Get the endpoint device's friendly-name
1860 if (defaultCommunicationDevice)
1862 ret = _GetDefaultDeviceName(eRender, eCommunications, szDeviceName, bufferLen);
1866 ret = _GetListDeviceName(eRender, index, szDeviceName, bufferLen);
1871 // Convert the endpoint device's friendly-name to UTF-8
1872 if (WideCharToMultiByte(CP_UTF8, 0, szDeviceName, -1, name, kAdmMaxDeviceNameSize, NULL, NULL) == 0)
1874 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d", GetLastError());
1878 // Get the endpoint ID string (uniquely identifies the device among all audio endpoint devices)
1879 if (defaultCommunicationDevice)
1881 ret = _GetDefaultDeviceID(eRender, eCommunications, szDeviceName, bufferLen);
1885 ret = _GetListDeviceID(eRender, index, szDeviceName, bufferLen);
1888 if (guid != NULL && ret == 0)
1890 // Convert the endpoint device's ID string to UTF-8
1891 if (WideCharToMultiByte(CP_UTF8, 0, szDeviceName, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1893 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d", GetLastError());
1900 // ----------------------------------------------------------------------------
1901 // RecordingDeviceName
1902 // ----------------------------------------------------------------------------
1904 int32_t AudioDeviceWindowsCore::RecordingDeviceName(
1906 char name[kAdmMaxDeviceNameSize],
1907 char guid[kAdmMaxGuidSize])
1910 bool defaultCommunicationDevice(false);
1911 const int16_t nDevices(RecordingDevices()); // also updates the list of devices
1913 // Special fix for the case when the user selects '-1' as index (<=> Default Communication Device)
1914 if (index == (uint16_t)(-1))
1916 defaultCommunicationDevice = true;
1918 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Default Communication endpoint device will be used");
1921 if ((index > (nDevices-1)) || (name == NULL))
1926 memset(name, 0, kAdmMaxDeviceNameSize);
1930 memset(guid, 0, kAdmMaxGuidSize);
1933 CriticalSectionScoped lock(&_critSect);
1936 WCHAR szDeviceName[MAX_PATH];
1937 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
1939 // Get the endpoint device's friendly-name
1940 if (defaultCommunicationDevice)
1942 ret = _GetDefaultDeviceName(eCapture, eCommunications, szDeviceName, bufferLen);
1946 ret = _GetListDeviceName(eCapture, index, szDeviceName, bufferLen);
1951 // Convert the endpoint device's friendly-name to UTF-8
1952 if (WideCharToMultiByte(CP_UTF8, 0, szDeviceName, -1, name, kAdmMaxDeviceNameSize, NULL, NULL) == 0)
1954 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d", GetLastError());
1958 // Get the endpoint ID string (uniquely identifies the device among all audio endpoint devices)
1959 if (defaultCommunicationDevice)
1961 ret = _GetDefaultDeviceID(eCapture, eCommunications, szDeviceName, bufferLen);
1965 ret = _GetListDeviceID(eCapture, index, szDeviceName, bufferLen);
1968 if (guid != NULL && ret == 0)
1970 // Convert the endpoint device's ID string to UTF-8
1971 if (WideCharToMultiByte(CP_UTF8, 0, szDeviceName, -1, guid, kAdmMaxGuidSize, NULL, NULL) == 0)
1973 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "WideCharToMultiByte(CP_UTF8) failed with error code %d", GetLastError());
1980 // ----------------------------------------------------------------------------
1982 // ----------------------------------------------------------------------------
1984 int16_t AudioDeviceWindowsCore::RecordingDevices()
1987 CriticalSectionScoped lock(&_critSect);
1989 if (_RefreshDeviceList(eCapture) != -1)
1991 return (_DeviceListCount(eCapture));
1997 // ----------------------------------------------------------------------------
1998 // SetRecordingDevice I (II)
1999 // ----------------------------------------------------------------------------
2001 int32_t AudioDeviceWindowsCore::SetRecordingDevice(uint16_t index)
2004 if (_recIsInitialized)
2009 // Get current number of available capture endpoint devices and refresh the capture collection.
2010 UINT nDevices = RecordingDevices();
2012 if (index < 0 || index > (nDevices-1))
2014 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "device index is out of range [0,%u]", (nDevices-1));
2018 CriticalSectionScoped lock(&_critSect);
2022 assert(_ptrCaptureCollection != NULL);
2024 // Select an endpoint capture device given the specified index
2025 SAFE_RELEASE(_ptrDeviceIn);
2026 hr = _ptrCaptureCollection->Item(
2032 SAFE_RELEASE(_ptrDeviceIn);
2036 WCHAR szDeviceName[MAX_PATH];
2037 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
2039 // Get the endpoint device's friendly-name
2040 if (_GetDeviceName(_ptrDeviceIn, szDeviceName, bufferLen) == 0)
2042 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", szDeviceName);
2045 _usingInputDeviceIndex = true;
2046 _inputDeviceIndex = index;
2051 // ----------------------------------------------------------------------------
2052 // SetRecordingDevice II (II)
2053 // ----------------------------------------------------------------------------
2055 int32_t AudioDeviceWindowsCore::SetRecordingDevice(AudioDeviceModule::WindowsDeviceType device)
2057 if (_recIsInitialized)
2062 ERole role(eCommunications);
2064 if (device == AudioDeviceModule::kDefaultDevice)
2068 else if (device == AudioDeviceModule::kDefaultCommunicationDevice)
2070 role = eCommunications;
2073 CriticalSectionScoped lock(&_critSect);
2075 // Refresh the list of capture endpoint devices
2076 _RefreshDeviceList(eCapture);
2080 assert(_ptrEnumerator != NULL);
2082 // Select an endpoint capture device given the specified role
2083 SAFE_RELEASE(_ptrDeviceIn);
2084 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
2091 SAFE_RELEASE(_ptrDeviceIn);
2095 WCHAR szDeviceName[MAX_PATH];
2096 const int bufferLen = sizeof(szDeviceName)/sizeof(szDeviceName)[0];
2098 // Get the endpoint device's friendly-name
2099 if (_GetDeviceName(_ptrDeviceIn, szDeviceName, bufferLen) == 0)
2101 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", szDeviceName);
2104 _usingInputDeviceIndex = false;
2105 _inputDevice = device;
2110 // ----------------------------------------------------------------------------
2111 // PlayoutIsAvailable
2112 // ----------------------------------------------------------------------------
2114 int32_t AudioDeviceWindowsCore::PlayoutIsAvailable(bool& available)
2119 // Try to initialize the playout side
2120 int32_t res = InitPlayout();
2122 // Cancel effect of initialization
2133 // ----------------------------------------------------------------------------
2134 // RecordingIsAvailable
2135 // ----------------------------------------------------------------------------
2137 int32_t AudioDeviceWindowsCore::RecordingIsAvailable(bool& available)
2142 // Try to initialize the recording side
2143 int32_t res = InitRecording();
2145 // Cancel effect of initialization
2156 // ----------------------------------------------------------------------------
2158 // ----------------------------------------------------------------------------
2160 int32_t AudioDeviceWindowsCore::InitPlayout()
2163 CriticalSectionScoped lock(&_critSect);
2170 if (_playIsInitialized)
2175 if (_ptrDeviceOut == NULL)
2180 // Initialize the speaker (devices might have been added or removed)
2181 if (InitSpeaker() == -1)
2183 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "InitSpeaker() failed");
2186 // Ensure that the updated rendering endpoint device is valid
2187 if (_ptrDeviceOut == NULL)
2192 if (_builtInAecEnabled && _recIsInitialized)
2194 // Ensure the correct render device is configured in case
2195 // InitRecording() was called before InitPlayout().
2196 if (SetDMOProperties() == -1)
2203 WAVEFORMATEX* pWfxOut = NULL;
2205 WAVEFORMATEX* pWfxClosestMatch = NULL;
2207 // Create COM object with IAudioClient interface.
2208 SAFE_RELEASE(_ptrClientOut);
2209 hr = _ptrDeviceOut->Activate(
2210 __uuidof(IAudioClient),
2213 (void**)&_ptrClientOut);
2216 // Retrieve the stream format that the audio engine uses for its internal
2217 // processing (mixing) of shared-mode streams.
2218 hr = _ptrClientOut->GetMixFormat(&pWfxOut);
2221 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Audio Engine's current rendering mix format:");
2223 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wFormatTag : 0x%X (%u)", pWfxOut->wFormatTag, pWfxOut->wFormatTag);
2224 // number of channels (i.e. mono, stereo...)
2225 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels : %d", pWfxOut->nChannels);
2227 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nSamplesPerSec : %d", pWfxOut->nSamplesPerSec);
2228 // for buffer estimation
2229 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nAvgBytesPerSec: %d", pWfxOut->nAvgBytesPerSec);
2230 // block size of data
2231 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nBlockAlign : %d", pWfxOut->nBlockAlign);
2232 // number of bits per sample of mono data
2233 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wBitsPerSample : %d", pWfxOut->wBitsPerSample);
2234 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "cbSize : %d", pWfxOut->cbSize);
2238 Wfx.wFormatTag = WAVE_FORMAT_PCM;
2239 Wfx.wBitsPerSample = 16;
2242 const int freqs[] = {48000, 44100, 16000, 96000, 32000, 8000};
2245 // Iterate over frequencies and channels, in order of priority
2246 for (int freq = 0; freq < sizeof(freqs)/sizeof(freqs[0]); freq++)
2248 for (int chan = 0; chan < sizeof(_playChannelsPrioList)/sizeof(_playChannelsPrioList[0]); chan++)
2250 Wfx.nChannels = _playChannelsPrioList[chan];
2251 Wfx.nSamplesPerSec = freqs[freq];
2252 Wfx.nBlockAlign = Wfx.nChannels * Wfx.wBitsPerSample / 8;
2253 Wfx.nAvgBytesPerSec = Wfx.nSamplesPerSec * Wfx.nBlockAlign;
2254 // If the method succeeds and the audio endpoint device supports the specified stream format,
2255 // it returns S_OK. If the method succeeds and provides a closest match to the specified format,
2256 // it returns S_FALSE.
2257 hr = _ptrClientOut->IsFormatSupported(
2258 AUDCLNT_SHAREMODE_SHARED,
2267 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels=%d, nSamplesPerSec=%d is not supported",
2268 Wfx.nChannels, Wfx.nSamplesPerSec);
2275 // TODO(andrew): what happens in the event of failure in the above loop?
2276 // Is _ptrClientOut->Initialize expected to fail?
2277 // Same in InitRecording().
2280 _playAudioFrameSize = Wfx.nBlockAlign;
2281 _playBlockSize = Wfx.nSamplesPerSec/100;
2282 _playSampleRate = Wfx.nSamplesPerSec;
2283 _devicePlaySampleRate = Wfx.nSamplesPerSec; // The device itself continues to run at 44.1 kHz.
2284 _devicePlayBlockSize = Wfx.nSamplesPerSec/100;
2285 _playChannels = Wfx.nChannels;
2287 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "VoE selected this rendering format:");
2288 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wFormatTag : 0x%X (%u)", Wfx.wFormatTag, Wfx.wFormatTag);
2289 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels : %d", Wfx.nChannels);
2290 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nSamplesPerSec : %d", Wfx.nSamplesPerSec);
2291 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nAvgBytesPerSec : %d", Wfx.nAvgBytesPerSec);
2292 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nBlockAlign : %d", Wfx.nBlockAlign);
2293 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wBitsPerSample : %d", Wfx.wBitsPerSample);
2294 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "cbSize : %d", Wfx.cbSize);
2295 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Additional settings:");
2296 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_playAudioFrameSize: %d", _playAudioFrameSize);
2297 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_playBlockSize : %d", _playBlockSize);
2298 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_playChannels : %d", _playChannels);
2301 // Create a rendering stream.
2303 // ****************************************************************************
2304 // For a shared-mode stream that uses event-driven buffering, the caller must
2305 // set both hnsPeriodicity and hnsBufferDuration to 0. The Initialize method
2306 // determines how large a buffer to allocate based on the scheduling period
2307 // of the audio engine. Although the client's buffer processing thread is
2308 // event driven, the basic buffer management process, as described previously,
2310 // Each time the thread awakens, it should call IAudioClient::GetCurrentPadding
2311 // to determine how much data to write to a rendering buffer or read from a capture
2312 // buffer. In contrast to the two buffers that the Initialize method allocates
2313 // for an exclusive-mode stream that uses event-driven buffering, a shared-mode
2314 // stream requires a single buffer.
2315 // ****************************************************************************
2317 REFERENCE_TIME hnsBufferDuration = 0; // ask for minimum buffer size (default)
2318 if (_devicePlaySampleRate == 44100)
2320 // Ask for a larger buffer size (30ms) when using 44.1kHz as render rate.
2321 // There seems to be a larger risk of underruns for 44.1 compared
2322 // with the default rate (48kHz). When using default, we set the requested
2323 // buffer duration to 0, which sets the buffer to the minimum size
2324 // required by the engine thread. The actual buffer size can then be
2325 // read by GetBufferSize() and it is 20ms on most machines.
2326 hnsBufferDuration = 30*10000;
2328 hr = _ptrClientOut->Initialize(
2329 AUDCLNT_SHAREMODE_SHARED, // share Audio Engine with other applications
2330 AUDCLNT_STREAMFLAGS_EVENTCALLBACK, // processing of the audio buffer by the client will be event driven
2331 hnsBufferDuration, // requested buffer capacity as a time value (in 100-nanosecond units)
2333 &Wfx, // selected wave format
2334 NULL); // session GUID
2338 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "IAudioClient::Initialize() failed:");
2339 if (pWfxClosestMatch != NULL)
2341 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "closest mix format: #channels=%d, samples/sec=%d, bits/sample=%d",
2342 pWfxClosestMatch->nChannels, pWfxClosestMatch->nSamplesPerSec, pWfxClosestMatch->wBitsPerSample);
2346 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "no format suggested");
2351 if (_ptrAudioBuffer)
2353 // Update the audio buffer with the selected parameters
2354 _ptrAudioBuffer->SetPlayoutSampleRate(_playSampleRate);
2355 _ptrAudioBuffer->SetPlayoutChannels((uint8_t)_playChannels);
2359 // We can enter this state during CoreAudioIsSupported() when no AudioDeviceImplementation
2360 // has been created, hence the AudioDeviceBuffer does not exist.
2361 // It is OK to end up here since we don't initiate any media in CoreAudioIsSupported().
2362 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceBuffer must be attached before streaming can start");
2365 // Get the actual size of the shared (endpoint buffer).
2366 // Typical value is 960 audio frames <=> 20ms @ 48kHz sample rate.
2367 UINT bufferFrameCount(0);
2368 hr = _ptrClientOut->GetBufferSize(
2372 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "IAudioClient::GetBufferSize() => %u (<=> %u bytes)",
2373 bufferFrameCount, bufferFrameCount*_playAudioFrameSize);
2376 // Set the event handle that the system signals when an audio buffer is ready
2377 // to be processed by the client.
2378 hr = _ptrClientOut->SetEventHandle(
2379 _hRenderSamplesReadyEvent);
2382 // Get an IAudioRenderClient interface.
2383 SAFE_RELEASE(_ptrRenderClient);
2384 hr = _ptrClientOut->GetService(
2385 __uuidof(IAudioRenderClient),
2386 (void**)&_ptrRenderClient);
2389 // Mark playout side as initialized
2390 _playIsInitialized = true;
2392 CoTaskMemFree(pWfxOut);
2393 CoTaskMemFree(pWfxClosestMatch);
2395 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "render side is now initialized");
2400 CoTaskMemFree(pWfxOut);
2401 CoTaskMemFree(pWfxClosestMatch);
2402 SAFE_RELEASE(_ptrClientOut);
2403 SAFE_RELEASE(_ptrRenderClient);
2407 // Capture initialization when the built-in AEC DirectX Media Object (DMO) is
2408 // used. Called from InitRecording(), most of which is skipped over. The DMO
2409 // handles device initialization itself.
2410 // Reference: http://msdn.microsoft.com/en-us/library/ff819492(v=vs.85).aspx
2411 int32_t AudioDeviceWindowsCore::InitRecordingDMO()
2413 assert(_builtInAecEnabled);
2414 assert(_dmo != NULL);
2416 if (SetDMOProperties() == -1)
2421 DMO_MEDIA_TYPE mt = {0};
2422 HRESULT hr = MoInitMediaType(&mt, sizeof(WAVEFORMATEX));
2425 MoFreeMediaType(&mt);
2429 mt.majortype = MEDIATYPE_Audio;
2430 mt.subtype = MEDIASUBTYPE_PCM;
2431 mt.formattype = FORMAT_WaveFormatEx;
2433 // Supported formats
2434 // nChannels: 1 (in AEC-only mode)
2435 // nSamplesPerSec: 8000, 11025, 16000, 22050
2436 // wBitsPerSample: 16
2437 WAVEFORMATEX* ptrWav = reinterpret_cast<WAVEFORMATEX*>(mt.pbFormat);
2438 ptrWav->wFormatTag = WAVE_FORMAT_PCM;
2439 ptrWav->nChannels = 1;
2440 // 16000 is the highest we can support with our resampler.
2441 ptrWav->nSamplesPerSec = 16000;
2442 ptrWav->nAvgBytesPerSec = 32000;
2443 ptrWav->nBlockAlign = 2;
2444 ptrWav->wBitsPerSample = 16;
2447 // Set the VoE format equal to the AEC output format.
2448 _recAudioFrameSize = ptrWav->nBlockAlign;
2449 _recSampleRate = ptrWav->nSamplesPerSec;
2450 _recBlockSize = ptrWav->nSamplesPerSec / 100;
2451 _recChannels = ptrWav->nChannels;
2453 // Set the DMO output format parameters.
2454 hr = _dmo->SetOutputType(kAecCaptureStreamIndex, &mt, 0);
2455 MoFreeMediaType(&mt);
2462 if (_ptrAudioBuffer)
2464 _ptrAudioBuffer->SetRecordingSampleRate(_recSampleRate);
2465 _ptrAudioBuffer->SetRecordingChannels(_recChannels);
2469 // Refer to InitRecording() for comments.
2470 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2471 "AudioDeviceBuffer must be attached before streaming can start");
2474 _mediaBuffer = new MediaBufferImpl(_recBlockSize * _recAudioFrameSize);
2476 // Optional, but if called, must be after media types are set.
2477 hr = _dmo->AllocateStreamingResources();
2484 _recIsInitialized = true;
2485 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2486 "Capture side is now initialized");
2491 // ----------------------------------------------------------------------------
2493 // ----------------------------------------------------------------------------
2495 int32_t AudioDeviceWindowsCore::InitRecording()
2498 CriticalSectionScoped lock(&_critSect);
2505 if (_recIsInitialized)
2510 if (QueryPerformanceFrequency(&_perfCounterFreq) == 0)
2514 _perfCounterFactor = 10000000.0 / (double)_perfCounterFreq.QuadPart;
2516 if (_ptrDeviceIn == NULL)
2521 // Initialize the microphone (devices might have been added or removed)
2522 if (InitMicrophone() == -1)
2524 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "InitMicrophone() failed");
2527 // Ensure that the updated capturing endpoint device is valid
2528 if (_ptrDeviceIn == NULL)
2533 if (_builtInAecEnabled)
2535 // The DMO will configure the capture device.
2536 return InitRecordingDMO();
2540 WAVEFORMATEX* pWfxIn = NULL;
2542 WAVEFORMATEX* pWfxClosestMatch = NULL;
2544 // Create COM object with IAudioClient interface.
2545 SAFE_RELEASE(_ptrClientIn);
2546 hr = _ptrDeviceIn->Activate(
2547 __uuidof(IAudioClient),
2550 (void**)&_ptrClientIn);
2553 // Retrieve the stream format that the audio engine uses for its internal
2554 // processing (mixing) of shared-mode streams.
2555 hr = _ptrClientIn->GetMixFormat(&pWfxIn);
2558 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Audio Engine's current capturing mix format:");
2560 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wFormatTag : 0x%X (%u)", pWfxIn->wFormatTag, pWfxIn->wFormatTag);
2561 // number of channels (i.e. mono, stereo...)
2562 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels : %d", pWfxIn->nChannels);
2564 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nSamplesPerSec : %d", pWfxIn->nSamplesPerSec);
2565 // for buffer estimation
2566 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nAvgBytesPerSec: %d", pWfxIn->nAvgBytesPerSec);
2567 // block size of data
2568 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nBlockAlign : %d", pWfxIn->nBlockAlign);
2569 // number of bits per sample of mono data
2570 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wBitsPerSample : %d", pWfxIn->wBitsPerSample);
2571 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "cbSize : %d", pWfxIn->cbSize);
2575 Wfx.wFormatTag = WAVE_FORMAT_PCM;
2576 Wfx.wBitsPerSample = 16;
2579 const int freqs[6] = {48000, 44100, 16000, 96000, 32000, 8000};
2582 // Iterate over frequencies and channels, in order of priority
2583 for (int freq = 0; freq < sizeof(freqs)/sizeof(freqs[0]); freq++)
2585 for (int chan = 0; chan < sizeof(_recChannelsPrioList)/sizeof(_recChannelsPrioList[0]); chan++)
2587 Wfx.nChannels = _recChannelsPrioList[chan];
2588 Wfx.nSamplesPerSec = freqs[freq];
2589 Wfx.nBlockAlign = Wfx.nChannels * Wfx.wBitsPerSample / 8;
2590 Wfx.nAvgBytesPerSec = Wfx.nSamplesPerSec * Wfx.nBlockAlign;
2591 // If the method succeeds and the audio endpoint device supports the specified stream format,
2592 // it returns S_OK. If the method succeeds and provides a closest match to the specified format,
2593 // it returns S_FALSE.
2594 hr = _ptrClientIn->IsFormatSupported(
2595 AUDCLNT_SHAREMODE_SHARED,
2604 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels=%d, nSamplesPerSec=%d is not supported",
2605 Wfx.nChannels, Wfx.nSamplesPerSec);
2614 _recAudioFrameSize = Wfx.nBlockAlign;
2615 _recSampleRate = Wfx.nSamplesPerSec;
2616 _recBlockSize = Wfx.nSamplesPerSec/100;
2617 _recChannels = Wfx.nChannels;
2619 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "VoE selected this capturing format:");
2620 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wFormatTag : 0x%X (%u)", Wfx.wFormatTag, Wfx.wFormatTag);
2621 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nChannels : %d", Wfx.nChannels);
2622 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nSamplesPerSec : %d", Wfx.nSamplesPerSec);
2623 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nAvgBytesPerSec : %d", Wfx.nAvgBytesPerSec);
2624 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "nBlockAlign : %d", Wfx.nBlockAlign);
2625 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "wBitsPerSample : %d", Wfx.wBitsPerSample);
2626 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "cbSize : %d", Wfx.cbSize);
2627 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Additional settings:");
2628 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_recAudioFrameSize: %d", _recAudioFrameSize);
2629 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_recBlockSize : %d", _recBlockSize);
2630 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_recChannels : %d", _recChannels);
2633 // Create a capturing stream.
2634 hr = _ptrClientIn->Initialize(
2635 AUDCLNT_SHAREMODE_SHARED, // share Audio Engine with other applications
2636 AUDCLNT_STREAMFLAGS_EVENTCALLBACK | // processing of the audio buffer by the client will be event driven
2637 AUDCLNT_STREAMFLAGS_NOPERSIST, // volume and mute settings for an audio session will not persist across system restarts
2638 0, // required for event-driven shared mode
2640 &Wfx, // selected wave format
2641 NULL); // session GUID
2646 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "IAudioClient::Initialize() failed:");
2647 if (pWfxClosestMatch != NULL)
2649 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "closest mix format: #channels=%d, samples/sec=%d, bits/sample=%d",
2650 pWfxClosestMatch->nChannels, pWfxClosestMatch->nSamplesPerSec, pWfxClosestMatch->wBitsPerSample);
2654 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "no format suggested");
2659 if (_ptrAudioBuffer)
2661 // Update the audio buffer with the selected parameters
2662 _ptrAudioBuffer->SetRecordingSampleRate(_recSampleRate);
2663 _ptrAudioBuffer->SetRecordingChannels((uint8_t)_recChannels);
2667 // We can enter this state during CoreAudioIsSupported() when no AudioDeviceImplementation
2668 // has been created, hence the AudioDeviceBuffer does not exist.
2669 // It is OK to end up here since we don't initiate any media in CoreAudioIsSupported().
2670 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "AudioDeviceBuffer must be attached before streaming can start");
2673 // Get the actual size of the shared (endpoint buffer).
2674 // Typical value is 960 audio frames <=> 20ms @ 48kHz sample rate.
2675 UINT bufferFrameCount(0);
2676 hr = _ptrClientIn->GetBufferSize(
2680 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "IAudioClient::GetBufferSize() => %u (<=> %u bytes)",
2681 bufferFrameCount, bufferFrameCount*_recAudioFrameSize);
2684 // Set the event handle that the system signals when an audio buffer is ready
2685 // to be processed by the client.
2686 hr = _ptrClientIn->SetEventHandle(
2687 _hCaptureSamplesReadyEvent);
2690 // Get an IAudioCaptureClient interface.
2691 SAFE_RELEASE(_ptrCaptureClient);
2692 hr = _ptrClientIn->GetService(
2693 __uuidof(IAudioCaptureClient),
2694 (void**)&_ptrCaptureClient);
2697 // Mark capture side as initialized
2698 _recIsInitialized = true;
2700 CoTaskMemFree(pWfxIn);
2701 CoTaskMemFree(pWfxClosestMatch);
2703 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "capture side is now initialized");
2708 CoTaskMemFree(pWfxIn);
2709 CoTaskMemFree(pWfxClosestMatch);
2710 SAFE_RELEASE(_ptrClientIn);
2711 SAFE_RELEASE(_ptrCaptureClient);
2715 // ----------------------------------------------------------------------------
2717 // ----------------------------------------------------------------------------
2719 int32_t AudioDeviceWindowsCore::StartRecording()
2722 if (!_recIsInitialized)
2727 if (_hRecThread != NULL)
2738 CriticalSectionScoped critScoped(&_critSect);
2740 // Create thread which will drive the capturing
2741 LPTHREAD_START_ROUTINE lpStartAddress = WSAPICaptureThread;
2742 if (_builtInAecEnabled)
2744 // Redirect to the DMO polling method.
2745 lpStartAddress = WSAPICaptureThreadPollDMO;
2749 // The DMO won't provide us captured output data unless we
2750 // give it render data to process.
2751 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2752 "Playout must be started before recording when using the "
2758 assert(_hRecThread == NULL);
2759 _hRecThread = CreateThread(NULL,
2765 if (_hRecThread == NULL)
2767 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2768 "failed to create the recording thread");
2772 // Set thread priority to highest possible
2773 SetThreadPriority(_hRecThread, THREAD_PRIORITY_TIME_CRITICAL);
2775 assert(_hGetCaptureVolumeThread == NULL);
2776 _hGetCaptureVolumeThread = CreateThread(NULL,
2778 GetCaptureVolumeThread,
2782 if (_hGetCaptureVolumeThread == NULL)
2784 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2785 " failed to create the volume getter thread");
2789 assert(_hSetCaptureVolumeThread == NULL);
2790 _hSetCaptureVolumeThread = CreateThread(NULL,
2792 SetCaptureVolumeThread,
2796 if (_hSetCaptureVolumeThread == NULL)
2798 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2799 " failed to create the volume setter thread");
2804 DWORD ret = WaitForSingleObject(_hCaptureStartedEvent, 1000);
2805 if (ret != WAIT_OBJECT_0)
2807 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2808 "capturing did not start up properly");
2811 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2812 "capture audio stream has now started...");
2821 // ----------------------------------------------------------------------------
2823 // ----------------------------------------------------------------------------
2825 int32_t AudioDeviceWindowsCore::StopRecording()
2829 if (!_recIsInitialized)
2836 if (_hRecThread == NULL)
2838 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2839 "no capturing stream is active => close down WASAPI only");
2840 SAFE_RELEASE(_ptrClientIn);
2841 SAFE_RELEASE(_ptrCaptureClient);
2842 _recIsInitialized = false;
2848 // Stop the driving thread...
2849 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2850 "closing down the webrtc_core_audio_capture_thread...");
2851 // Manual-reset event; it will remain signalled to stop all capture threads.
2852 SetEvent(_hShutdownCaptureEvent);
2855 DWORD ret = WaitForSingleObject(_hRecThread, 2000);
2856 if (ret != WAIT_OBJECT_0)
2858 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2859 "failed to close down webrtc_core_audio_capture_thread");
2864 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2865 "webrtc_core_audio_capture_thread is now closed");
2868 ret = WaitForSingleObject(_hGetCaptureVolumeThread, 2000);
2869 if (ret != WAIT_OBJECT_0)
2871 // the thread did not stop as it should
2872 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2873 " failed to close down volume getter thread");
2878 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2879 " volume getter thread is now closed");
2882 ret = WaitForSingleObject(_hSetCaptureVolumeThread, 2000);
2883 if (ret != WAIT_OBJECT_0)
2885 // the thread did not stop as it should
2886 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
2887 " failed to close down volume setter thread");
2892 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
2893 " volume setter thread is now closed");
2897 ResetEvent(_hShutdownCaptureEvent); // Must be manually reset.
2898 // Ensure that the thread has released these interfaces properly.
2899 assert(err == -1 || _ptrClientIn == NULL);
2900 assert(err == -1 || _ptrCaptureClient == NULL);
2902 _recIsInitialized = false;
2905 // These will create thread leaks in the result of an error,
2906 // but we can at least resume the call.
2907 CloseHandle(_hRecThread);
2910 CloseHandle(_hGetCaptureVolumeThread);
2911 _hGetCaptureVolumeThread = NULL;
2913 CloseHandle(_hSetCaptureVolumeThread);
2914 _hSetCaptureVolumeThread = NULL;
2916 if (_builtInAecEnabled)
2918 assert(_dmo != NULL);
2919 // This is necessary. Otherwise the DMO can generate garbage render
2920 // audio even after rendering has stopped.
2921 HRESULT hr = _dmo->FreeStreamingResources();
2929 // Reset the recording delay value.
2930 _sndCardRecDelay = 0;
2937 // ----------------------------------------------------------------------------
2938 // RecordingIsInitialized
2939 // ----------------------------------------------------------------------------
2941 bool AudioDeviceWindowsCore::RecordingIsInitialized() const
2943 return (_recIsInitialized);
2946 // ----------------------------------------------------------------------------
2948 // ----------------------------------------------------------------------------
2950 bool AudioDeviceWindowsCore::Recording() const
2952 return (_recording);
2955 // ----------------------------------------------------------------------------
2956 // PlayoutIsInitialized
2957 // ----------------------------------------------------------------------------
2959 bool AudioDeviceWindowsCore::PlayoutIsInitialized() const
2962 return (_playIsInitialized);
2965 // ----------------------------------------------------------------------------
2967 // ----------------------------------------------------------------------------
2969 int32_t AudioDeviceWindowsCore::StartPlayout()
2972 if (!_playIsInitialized)
2977 if (_hPlayThread != NULL)
2988 CriticalSectionScoped critScoped(&_critSect);
2990 // Create thread which will drive the rendering.
2991 assert(_hPlayThread == NULL);
2992 _hPlayThread = CreateThread(
2999 if (_hPlayThread == NULL)
3001 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
3002 "failed to create the playout thread");
3006 // Set thread priority to highest possible.
3007 SetThreadPriority(_hPlayThread, THREAD_PRIORITY_TIME_CRITICAL);
3010 DWORD ret = WaitForSingleObject(_hRenderStartedEvent, 1000);
3011 if (ret != WAIT_OBJECT_0)
3013 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3014 "rendering did not start up properly");
3019 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3020 "rendering audio stream has now started...");
3025 // ----------------------------------------------------------------------------
3027 // ----------------------------------------------------------------------------
3029 int32_t AudioDeviceWindowsCore::StopPlayout()
3032 if (!_playIsInitialized)
3038 CriticalSectionScoped critScoped(&_critSect) ;
3040 if (_hPlayThread == NULL)
3042 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3043 "no rendering stream is active => close down WASAPI only");
3044 SAFE_RELEASE(_ptrClientOut);
3045 SAFE_RELEASE(_ptrRenderClient);
3046 _playIsInitialized = false;
3051 // stop the driving thread...
3052 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3053 "closing down the webrtc_core_audio_render_thread...");
3054 SetEvent(_hShutdownRenderEvent);
3057 DWORD ret = WaitForSingleObject(_hPlayThread, 2000);
3058 if (ret != WAIT_OBJECT_0)
3060 // the thread did not stop as it should
3061 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
3062 "failed to close down webrtc_core_audio_render_thread");
3063 CloseHandle(_hPlayThread);
3064 _hPlayThread = NULL;
3065 _playIsInitialized = false;
3071 CriticalSectionScoped critScoped(&_critSect);
3072 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3073 "webrtc_core_audio_render_thread is now closed");
3075 // to reset this event manually at each time we finish with it,
3076 // in case that the render thread has exited before StopPlayout(),
3077 // this event might be caught by the new render thread within same VoE instance.
3078 ResetEvent(_hShutdownRenderEvent);
3080 SAFE_RELEASE(_ptrClientOut);
3081 SAFE_RELEASE(_ptrRenderClient);
3083 _playIsInitialized = false;
3086 CloseHandle(_hPlayThread);
3087 _hPlayThread = NULL;
3089 if (_builtInAecEnabled && _recording)
3091 // The DMO won't provide us captured output data unless we
3092 // give it render data to process.
3094 // We still permit the playout to shutdown, and trace a warning.
3095 // Otherwise, VoE can get into a state which will never permit
3096 // playout to stop properly.
3097 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3098 "Recording should be stopped before playout when using the "
3102 // Reset the playout delay value.
3103 _sndCardPlayDelay = 0;
3109 // ----------------------------------------------------------------------------
3111 // ----------------------------------------------------------------------------
3113 int32_t AudioDeviceWindowsCore::PlayoutDelay(uint16_t& delayMS) const
3115 CriticalSectionScoped critScoped(&_critSect);
3116 delayMS = static_cast<uint16_t>(_sndCardPlayDelay);
3120 // ----------------------------------------------------------------------------
3122 // ----------------------------------------------------------------------------
3124 int32_t AudioDeviceWindowsCore::RecordingDelay(uint16_t& delayMS) const
3126 CriticalSectionScoped critScoped(&_critSect);
3127 delayMS = static_cast<uint16_t>(_sndCardRecDelay);
3131 // ----------------------------------------------------------------------------
3133 // ----------------------------------------------------------------------------
3135 bool AudioDeviceWindowsCore::Playing() const
3139 // ----------------------------------------------------------------------------
3141 // ----------------------------------------------------------------------------
3143 int32_t AudioDeviceWindowsCore::SetPlayoutBuffer(const AudioDeviceModule::BufferType type, uint16_t sizeMS)
3146 CriticalSectionScoped lock(&_critSect);
3148 _playBufType = type;
3150 if (type == AudioDeviceModule::kFixedBufferSize)
3152 _playBufDelayFixed = sizeMS;
3158 // ----------------------------------------------------------------------------
3160 // ----------------------------------------------------------------------------
3162 int32_t AudioDeviceWindowsCore::PlayoutBuffer(AudioDeviceModule::BufferType& type, uint16_t& sizeMS) const
3164 CriticalSectionScoped lock(&_critSect);
3165 type = _playBufType;
3167 if (type == AudioDeviceModule::kFixedBufferSize)
3169 sizeMS = _playBufDelayFixed;
3173 // Use same value as for PlayoutDelay
3174 sizeMS = static_cast<uint16_t>(_sndCardPlayDelay);
3180 // ----------------------------------------------------------------------------
3182 // ----------------------------------------------------------------------------
3184 int32_t AudioDeviceWindowsCore::CPULoad(uint16_t& load) const
3187 load = static_cast<uint16_t> (100*_avgCPULoad);
3192 // ----------------------------------------------------------------------------
3194 // ----------------------------------------------------------------------------
3196 bool AudioDeviceWindowsCore::PlayoutWarning() const
3198 return ( _playWarning > 0);
3201 // ----------------------------------------------------------------------------
3203 // ----------------------------------------------------------------------------
3205 bool AudioDeviceWindowsCore::PlayoutError() const
3207 return ( _playError > 0);
3210 // ----------------------------------------------------------------------------
3212 // ----------------------------------------------------------------------------
3214 bool AudioDeviceWindowsCore::RecordingWarning() const
3216 return ( _recWarning > 0);
3219 // ----------------------------------------------------------------------------
3221 // ----------------------------------------------------------------------------
3223 bool AudioDeviceWindowsCore::RecordingError() const
3225 return ( _recError > 0);
3228 // ----------------------------------------------------------------------------
3229 // ClearPlayoutWarning
3230 // ----------------------------------------------------------------------------
3232 void AudioDeviceWindowsCore::ClearPlayoutWarning()
3237 // ----------------------------------------------------------------------------
3238 // ClearPlayoutError
3239 // ----------------------------------------------------------------------------
3241 void AudioDeviceWindowsCore::ClearPlayoutError()
3246 // ----------------------------------------------------------------------------
3247 // ClearRecordingWarning
3248 // ----------------------------------------------------------------------------
3250 void AudioDeviceWindowsCore::ClearRecordingWarning()
3255 // ----------------------------------------------------------------------------
3256 // ClearRecordingError
3257 // ----------------------------------------------------------------------------
3259 void AudioDeviceWindowsCore::ClearRecordingError()
3264 // ============================================================================
3266 // ============================================================================
3268 // ----------------------------------------------------------------------------
3269 // [static] WSAPIRenderThread
3270 // ----------------------------------------------------------------------------
3272 DWORD WINAPI AudioDeviceWindowsCore::WSAPIRenderThread(LPVOID context)
3274 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3278 // ----------------------------------------------------------------------------
3279 // [static] WSAPICaptureThread
3280 // ----------------------------------------------------------------------------
3282 DWORD WINAPI AudioDeviceWindowsCore::WSAPICaptureThread(LPVOID context)
3284 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3288 DWORD WINAPI AudioDeviceWindowsCore::WSAPICaptureThreadPollDMO(LPVOID context)
3290 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3291 DoCaptureThreadPollDMO();
3294 DWORD WINAPI AudioDeviceWindowsCore::GetCaptureVolumeThread(LPVOID context)
3296 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3297 DoGetCaptureVolumeThread();
3300 DWORD WINAPI AudioDeviceWindowsCore::SetCaptureVolumeThread(LPVOID context)
3302 return reinterpret_cast<AudioDeviceWindowsCore*>(context)->
3303 DoSetCaptureVolumeThread();
3306 DWORD AudioDeviceWindowsCore::DoGetCaptureVolumeThread()
3308 HANDLE waitObject = _hShutdownCaptureEvent;
3314 uint32_t currentMicLevel = 0;
3315 if (MicrophoneVolume(currentMicLevel) == 0)
3317 // This doesn't set the system volume, just stores it.
3319 if (_ptrAudioBuffer)
3321 _ptrAudioBuffer->SetCurrentMicLevel(currentMicLevel);
3327 DWORD waitResult = WaitForSingleObject(waitObject,
3328 GET_MIC_VOLUME_INTERVAL_MS);
3331 case WAIT_OBJECT_0: // _hShutdownCaptureEvent
3333 case WAIT_TIMEOUT: // timeout notification
3335 default: // unexpected error
3336 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3337 " unknown wait termination on get volume thread");
3343 DWORD AudioDeviceWindowsCore::DoSetCaptureVolumeThread()
3345 HANDLE waitArray[2] = {_hShutdownCaptureEvent, _hSetCaptureVolumeEvent};
3349 DWORD waitResult = WaitForMultipleObjects(2, waitArray, FALSE, INFINITE);
3352 case WAIT_OBJECT_0: // _hShutdownCaptureEvent
3354 case WAIT_OBJECT_0 + 1: // _hSetCaptureVolumeEvent
3356 default: // unexpected error
3357 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3358 " unknown wait termination on set volume thread");
3363 uint32_t newMicLevel = _newMicLevel;
3366 if (SetMicrophoneVolume(newMicLevel) == -1)
3368 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3369 " the required modification of the microphone volume failed");
3374 // ----------------------------------------------------------------------------
3376 // ----------------------------------------------------------------------------
3378 DWORD AudioDeviceWindowsCore::DoRenderThread()
3381 bool keepPlaying = true;
3382 HANDLE waitArray[2] = {_hShutdownRenderEvent, _hRenderSamplesReadyEvent};
3384 HANDLE hMmTask = NULL;
3390 // Initialize COM as MTA in this thread.
3391 ScopedCOMInitializer comInit(ScopedCOMInitializer::kMTA);
3392 if (!comInit.succeeded()) {
3393 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
3394 "failed to initialize COM in render thread");
3398 _SetThreadName(-1, "webrtc_core_audio_render_thread");
3400 // Use Multimedia Class Scheduler Service (MMCSS) to boost the thread priority.
3402 if (_winSupportAvrt)
3405 hMmTask = _PAvSetMmThreadCharacteristicsA("Pro Audio", &taskIndex);
3408 if (FALSE == _PAvSetMmThreadPriority(hMmTask, AVRT_PRIORITY_CRITICAL))
3410 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "failed to boost play-thread using MMCSS");
3412 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "render thread is now registered with MMCSS (taskIndex=%d)", taskIndex);
3416 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "failed to enable MMCSS on render thread (err=%d)", GetLastError());
3417 _TraceCOMError(GetLastError());
3423 IAudioClock* clock = NULL;
3425 // Get size of rendering buffer (length is expressed as the number of audio frames the buffer can hold).
3426 // This value is fixed during the rendering session.
3428 UINT32 bufferLength = 0;
3429 hr = _ptrClientOut->GetBufferSize(&bufferLength);
3431 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[REND] size of buffer : %u", bufferLength);
3433 // Get maximum latency for the current stream (will not change for the lifetime of the IAudioClient object).
3435 REFERENCE_TIME latency;
3436 _ptrClientOut->GetStreamLatency(&latency);
3437 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[REND] max stream latency : %u (%3.2f ms)",
3438 (DWORD)latency, (double)(latency/10000.0));
3440 // Get the length of the periodic interval separating successive processing passes by
3441 // the audio engine on the data in the endpoint buffer.
3443 // The period between processing passes by the audio engine is fixed for a particular
3444 // audio endpoint device and represents the smallest processing quantum for the audio engine.
3445 // This period plus the stream latency between the buffer and endpoint device represents
3446 // the minimum possible latency that an audio application can achieve.
3447 // Typical value: 100000 <=> 0.01 sec = 10ms.
3449 REFERENCE_TIME devPeriod = 0;
3450 REFERENCE_TIME devPeriodMin = 0;
3451 _ptrClientOut->GetDevicePeriod(&devPeriod, &devPeriodMin);
3452 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[REND] device period : %u (%3.2f ms)",
3453 (DWORD)devPeriod, (double)(devPeriod/10000.0));
3455 // Derive initial rendering delay.
3456 // Example: 10*(960/480) + 15 = 20 + 15 = 35ms
3458 int playout_delay = 10 * (bufferLength / _playBlockSize) +
3459 (int)((latency + devPeriod) / 10000);
3460 _sndCardPlayDelay = playout_delay;
3461 _writtenSamples = 0;
3462 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3463 "[REND] initial delay : %u", playout_delay);
3465 double endpointBufferSizeMS = 10.0 * ((double)bufferLength / (double)_devicePlayBlockSize);
3466 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[REND] endpointBufferSizeMS : %3.2f", endpointBufferSizeMS);
3468 // Before starting the stream, fill the rendering buffer with silence.
3471 hr = _ptrRenderClient->GetBuffer(bufferLength, &pData);
3474 hr = _ptrRenderClient->ReleaseBuffer(bufferLength, AUDCLNT_BUFFERFLAGS_SILENT);
3477 _writtenSamples += bufferLength;
3479 hr = _ptrClientOut->GetService(__uuidof(IAudioClock), (void**)&clock);
3481 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3482 "failed to get IAudioClock interface from the IAudioClient");
3485 // Start up the rendering audio stream.
3486 hr = _ptrClientOut->Start();
3491 // Set event which will ensure that the calling thread modifies the playing state to true.
3493 SetEvent(_hRenderStartedEvent);
3495 // >> ------------------ THREAD LOOP ------------------
3499 // Wait for a render notification event or a shutdown event
3500 DWORD waitResult = WaitForMultipleObjects(2, waitArray, FALSE, 500);
3503 case WAIT_OBJECT_0 + 0: // _hShutdownRenderEvent
3504 keepPlaying = false;
3506 case WAIT_OBJECT_0 + 1: // _hRenderSamplesReadyEvent
3508 case WAIT_TIMEOUT: // timeout notification
3509 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "render event timed out after 0.5 seconds");
3511 default: // unexpected error
3512 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "unknown wait termination on render side");
3520 // Sanity check to ensure that essential states are not modified
3521 // during the unlocked period.
3522 if (_ptrRenderClient == NULL || _ptrClientOut == NULL)
3525 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
3526 "output state has been modified during unlocked period");
3530 // Get the number of frames of padding (queued up to play) in the endpoint buffer.
3532 hr = _ptrClientOut->GetCurrentPadding(&padding);
3535 // Derive the amount of available space in the output buffer
3536 uint32_t framesAvailable = bufferLength - padding;
3537 // WEBRTC_TRACE(kTraceStream, kTraceAudioDevice, _id, "#avaliable audio frames = %u", framesAvailable);
3539 // Do we have 10 ms available in the render buffer?
3540 if (framesAvailable < _playBlockSize)
3542 // Not enough space in render buffer to store next render packet.
3547 // Write n*10ms buffers to the render buffer
3548 const uint32_t n10msBuffers = (framesAvailable / _playBlockSize);
3549 for (uint32_t n = 0; n < n10msBuffers; n++)
3551 // Get pointer (i.e., grab the buffer) to next space in the shared render buffer.
3552 hr = _ptrRenderClient->GetBuffer(_playBlockSize, &pData);
3555 QueryPerformanceCounter(&t1); // measure time: START
3557 if (_ptrAudioBuffer)
3559 // Request data to be played out (#bytes = _playBlockSize*_audioFrameSize)
3562 _ptrAudioBuffer->RequestPlayoutData(_playBlockSize);
3568 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
3569 "failed to read data from render client");
3573 // Sanity check to ensure that essential states are not modified during the unlocked period
3574 if (_ptrRenderClient == NULL || _ptrClientOut == NULL)
3577 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id, "output state has been modified during unlocked period");
3580 if (nSamples != static_cast<int32_t>(_playBlockSize))
3582 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "nSamples(%d) != _playBlockSize(%d)", nSamples, _playBlockSize);
3585 // Get the actual (stored) data
3586 nSamples = _ptrAudioBuffer->GetPlayoutData((int8_t*)pData);
3589 QueryPerformanceCounter(&t2); // measure time: STOP
3590 time = (int)(t2.QuadPart-t1.QuadPart);
3594 hr = _ptrRenderClient->ReleaseBuffer(_playBlockSize, dwFlags);
3595 // See http://msdn.microsoft.com/en-us/library/dd316605(VS.85).aspx
3596 // for more details regarding AUDCLNT_E_DEVICE_INVALIDATED.
3599 _writtenSamples += _playBlockSize;
3602 // Check the current delay on the playout side.
3606 clock->GetPosition(&pos, NULL);
3607 clock->GetFrequency(&freq);
3608 playout_delay = ROUND((double(_writtenSamples) /
3609 _devicePlaySampleRate - double(pos) / freq) * 1000.0);
3610 _sndCardPlayDelay = playout_delay;
3617 // ------------------ THREAD LOOP ------------------ <<
3619 SleepMs(static_cast<DWORD>(endpointBufferSizeMS+0.5));
3620 hr = _ptrClientOut->Stop();
3623 SAFE_RELEASE(clock);
3627 _ptrClientOut->Stop();
3632 if (_winSupportAvrt)
3634 if (NULL != hMmTask)
3636 _PAvRevertMmThreadCharacteristics(hMmTask);
3644 if (_ptrClientOut != NULL)
3646 hr = _ptrClientOut->Stop();
3651 hr = _ptrClientOut->Reset();
3657 // Trigger callback from module process thread
3659 WEBRTC_TRACE(kTraceError, kTraceUtility, _id, "kPlayoutError message posted: rendering thread has ended pre-maturely");
3663 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_Rendering thread is now terminated properly");
3671 DWORD AudioDeviceWindowsCore::InitCaptureThreadPriority()
3675 _SetThreadName(-1, "webrtc_core_audio_capture_thread");
3677 // Use Multimedia Class Scheduler Service (MMCSS) to boost the thread
3679 if (_winSupportAvrt)
3682 _hMmTask = _PAvSetMmThreadCharacteristicsA("Pro Audio", &taskIndex);
3685 if (!_PAvSetMmThreadPriority(_hMmTask, AVRT_PRIORITY_CRITICAL))
3687 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3688 "failed to boost rec-thread using MMCSS");
3690 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3691 "capture thread is now registered with MMCSS (taskIndex=%d)",
3696 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3697 "failed to enable MMCSS on capture thread (err=%d)",
3699 _TraceCOMError(GetLastError());
3706 void AudioDeviceWindowsCore::RevertCaptureThreadPriority()
3708 if (_winSupportAvrt)
3710 if (NULL != _hMmTask)
3712 _PAvRevertMmThreadCharacteristics(_hMmTask);
3719 DWORD AudioDeviceWindowsCore::DoCaptureThreadPollDMO()
3721 assert(_mediaBuffer != NULL);
3722 bool keepRecording = true;
3724 // Initialize COM as MTA in this thread.
3725 ScopedCOMInitializer comInit(ScopedCOMInitializer::kMTA);
3726 if (!comInit.succeeded()) {
3727 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
3728 "failed to initialize COM in polling DMO thread");
3732 HRESULT hr = InitCaptureThreadPriority();
3738 // Set event which will ensure that the calling thread modifies the
3739 // recording state to true.
3740 SetEvent(_hCaptureStartedEvent);
3742 // >> ---------------------------- THREAD LOOP ----------------------------
3743 while (keepRecording)
3745 // Poll the DMO every 5 ms.
3746 // (The same interval used in the Wave implementation.)
3747 DWORD waitResult = WaitForSingleObject(_hShutdownCaptureEvent, 5);
3750 case WAIT_OBJECT_0: // _hShutdownCaptureEvent
3751 keepRecording = false;
3753 case WAIT_TIMEOUT: // timeout notification
3755 default: // unexpected error
3756 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id,
3757 "Unknown wait termination on capture side");
3758 hr = -1; // To signal an error callback.
3759 keepRecording = false;
3763 while (keepRecording)
3765 CriticalSectionScoped critScoped(&_critSect);
3769 DMO_OUTPUT_DATA_BUFFER dmoBuffer = {0};
3770 dmoBuffer.pBuffer = _mediaBuffer;
3771 dmoBuffer.pBuffer->AddRef();
3773 // Poll the DMO for AEC processed capture data. The DMO will
3774 // copy available data to |dmoBuffer|, and should only return
3775 // 10 ms frames. The value of |dwStatus| should be ignored.
3776 hr = _dmo->ProcessOutput(0, 1, &dmoBuffer, &dwStatus);
3777 SAFE_RELEASE(dmoBuffer.pBuffer);
3778 dwStatus = dmoBuffer.dwStatus;
3783 keepRecording = false;
3788 ULONG bytesProduced = 0;
3790 // Get a pointer to the data buffer. This should be valid until
3791 // the next call to ProcessOutput.
3792 hr = _mediaBuffer->GetBufferAndLength(&data, &bytesProduced);
3796 keepRecording = false;
3801 // TODO(andrew): handle AGC.
3803 if (bytesProduced > 0)
3805 const int kSamplesProduced = bytesProduced / _recAudioFrameSize;
3806 // TODO(andrew): verify that this is always satisfied. It might
3807 // be that ProcessOutput will try to return more than 10 ms if
3808 // we fail to call it frequently enough.
3809 assert(kSamplesProduced == static_cast<int>(_recBlockSize));
3810 assert(sizeof(BYTE) == sizeof(int8_t));
3811 _ptrAudioBuffer->SetRecordedBuffer(
3812 reinterpret_cast<int8_t*>(data),
3814 _ptrAudioBuffer->SetVQEData(0, 0, 0);
3816 _UnLock(); // Release lock while making the callback.
3817 _ptrAudioBuffer->DeliverRecordedData();
3821 // Reset length to indicate buffer availability.
3822 hr = _mediaBuffer->SetLength(0);
3826 keepRecording = false;
3831 if (!(dwStatus & DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE))
3833 // The DMO cannot currently produce more data. This is the
3834 // normal case; otherwise it means the DMO had more than 10 ms
3835 // of data available and ProcessOutput should be called again.
3840 // ---------------------------- THREAD LOOP ---------------------------- <<
3842 RevertCaptureThreadPriority();
3846 // Trigger callback from module process thread
3848 WEBRTC_TRACE(kTraceError, kTraceUtility, _id,
3849 "kRecordingError message posted: capturing thread has ended "
3854 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
3855 "Capturing thread is now terminated properly");
3862 // ----------------------------------------------------------------------------
3864 // ----------------------------------------------------------------------------
3866 DWORD AudioDeviceWindowsCore::DoCaptureThread()
3869 bool keepRecording = true;
3870 HANDLE waitArray[2] = {_hShutdownCaptureEvent, _hCaptureSamplesReadyEvent};
3877 BYTE* syncBuffer = NULL;
3878 UINT32 syncBufIndex = 0;
3882 // Initialize COM as MTA in this thread.
3883 ScopedCOMInitializer comInit(ScopedCOMInitializer::kMTA);
3884 if (!comInit.succeeded()) {
3885 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
3886 "failed to initialize COM in capture thread");
3890 hr = InitCaptureThreadPriority();
3898 // Get size of capturing buffer (length is expressed as the number of audio frames the buffer can hold).
3899 // This value is fixed during the capturing session.
3901 UINT32 bufferLength = 0;
3902 hr = _ptrClientIn->GetBufferSize(&bufferLength);
3904 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] size of buffer : %u", bufferLength);
3906 // Allocate memory for sync buffer.
3907 // It is used for compensation between native 44.1 and internal 44.0 and
3908 // for cases when the capture buffer is larger than 10ms.
3910 const UINT32 syncBufferSize = 2*(bufferLength * _recAudioFrameSize);
3911 syncBuffer = new BYTE[syncBufferSize];
3912 if (syncBuffer == NULL)
3916 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] size of sync buffer : %u [bytes]", syncBufferSize);
3918 // Get maximum latency for the current stream (will not change for the lifetime of the IAudioClient object).
3920 REFERENCE_TIME latency;
3921 _ptrClientIn->GetStreamLatency(&latency);
3922 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] max stream latency : %u (%3.2f ms)",
3923 (DWORD)latency, (double)(latency / 10000.0));
3925 // Get the length of the periodic interval separating successive processing passes by
3926 // the audio engine on the data in the endpoint buffer.
3928 REFERENCE_TIME devPeriod = 0;
3929 REFERENCE_TIME devPeriodMin = 0;
3930 _ptrClientIn->GetDevicePeriod(&devPeriod, &devPeriodMin);
3931 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] device period : %u (%3.2f ms)",
3932 (DWORD)devPeriod, (double)(devPeriod / 10000.0));
3934 double extraDelayMS = (double)((latency + devPeriod) / 10000.0);
3935 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] extraDelayMS : %3.2f", extraDelayMS);
3937 double endpointBufferSizeMS = 10.0 * ((double)bufferLength / (double)_recBlockSize);
3938 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "[CAPT] endpointBufferSizeMS : %3.2f", endpointBufferSizeMS);
3940 // Start up the capturing stream.
3942 hr = _ptrClientIn->Start();
3947 // Set event which will ensure that the calling thread modifies the recording state to true.
3949 SetEvent(_hCaptureStartedEvent);
3951 // >> ---------------------------- THREAD LOOP ----------------------------
3953 while (keepRecording)
3955 // Wait for a capture notification event or a shutdown event
3956 DWORD waitResult = WaitForMultipleObjects(2, waitArray, FALSE, 500);
3959 case WAIT_OBJECT_0 + 0: // _hShutdownCaptureEvent
3960 keepRecording = false;
3962 case WAIT_OBJECT_0 + 1: // _hCaptureSamplesReadyEvent
3964 case WAIT_TIMEOUT: // timeout notification
3965 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "capture event timed out after 0.5 seconds");
3967 default: // unexpected error
3968 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "unknown wait termination on capture side");
3972 while (keepRecording)
3975 UINT32 framesAvailable = 0;
3982 // Sanity check to ensure that essential states are not modified
3983 // during the unlocked period.
3984 if (_ptrCaptureClient == NULL || _ptrClientIn == NULL)
3987 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id,
3988 "input state has been modified during unlocked period");
3992 // Find out how much capture data is available
3994 hr = _ptrCaptureClient->GetBuffer(&pData, // packet which is ready to be read by used
3995 &framesAvailable, // #frames in the captured packet (can be zero)
3996 &flags, // support flags (check)
3997 &recPos, // device position of first audio frame in data packet
3998 &recTime); // value of performance counter at the time of recording the first audio frame
4002 if (AUDCLNT_S_BUFFER_EMPTY == hr)
4004 // Buffer was empty => start waiting for a new capture notification event
4009 if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
4011 // Treat all of the data in the packet as silence and ignore the actual data values.
4012 WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, _id, "AUDCLNT_BUFFERFLAGS_SILENT");
4016 assert(framesAvailable != 0);
4020 CopyMemory(&syncBuffer[syncBufIndex*_recAudioFrameSize], pData, framesAvailable*_recAudioFrameSize);
4024 ZeroMemory(&syncBuffer[syncBufIndex*_recAudioFrameSize], framesAvailable*_recAudioFrameSize);
4026 assert(syncBufferSize >= (syncBufIndex*_recAudioFrameSize)+framesAvailable*_recAudioFrameSize);
4028 // Release the capture buffer
4030 hr = _ptrCaptureClient->ReleaseBuffer(framesAvailable);
4033 _readSamples += framesAvailable;
4034 syncBufIndex += framesAvailable;
4036 QueryPerformanceCounter(&t1);
4038 // Get the current recording and playout delay.
4039 uint32_t sndCardRecDelay = (uint32_t)
4040 (((((UINT64)t1.QuadPart * _perfCounterFactor) - recTime)
4041 / 10000) + (10*syncBufIndex) / _recBlockSize - 10);
4042 uint32_t sndCardPlayDelay =
4043 static_cast<uint32_t>(_sndCardPlayDelay);
4045 _sndCardRecDelay = sndCardRecDelay;
4047 while (syncBufIndex >= _recBlockSize)
4049 if (_ptrAudioBuffer)
4051 _ptrAudioBuffer->SetRecordedBuffer((const int8_t*)syncBuffer, _recBlockSize);
4052 _ptrAudioBuffer->SetVQEData(sndCardPlayDelay,
4056 _ptrAudioBuffer->SetTypingStatus(KeyPressed());
4058 QueryPerformanceCounter(&t1); // measure time: START
4060 _UnLock(); // release lock while making the callback
4061 _ptrAudioBuffer->DeliverRecordedData();
4062 _Lock(); // restore the lock
4064 QueryPerformanceCounter(&t2); // measure time: STOP
4066 // Measure "average CPU load".
4067 // Basically what we do here is to measure how many percent of our 10ms period
4068 // is used for encoding and decoding. This value shuld be used as a warning indicator
4069 // only and not seen as an absolute value. Running at ~100% will lead to bad QoS.
4070 time = (int)(t2.QuadPart - t1.QuadPart);
4071 _avgCPULoad = (float)(_avgCPULoad*.99 + (time + _playAcc) / (double)(_perfCounterFreq.QuadPart));
4074 // Sanity check to ensure that essential states are not modified during the unlocked period
4075 if (_ptrCaptureClient == NULL || _ptrClientIn == NULL)
4078 WEBRTC_TRACE(kTraceCritical, kTraceAudioDevice, _id, "input state has been modified during unlocked period");
4083 // store remaining data which was not able to deliver as 10ms segment
4084 MoveMemory(&syncBuffer[0], &syncBuffer[_recBlockSize*_recAudioFrameSize], (syncBufIndex-_recBlockSize)*_recAudioFrameSize);
4085 syncBufIndex -= _recBlockSize;
4086 sndCardRecDelay -= 10;
4091 uint32_t newMicLevel = _ptrAudioBuffer->NewMicLevel();
4092 if (newMicLevel != 0)
4094 // The VQE will only deliver non-zero microphone levels when a change is needed.
4095 // Set this new mic level (received from the observer as return value in the callback).
4096 WEBRTC_TRACE(kTraceStream, kTraceAudioDevice, _id, "AGC change of volume: new=%u", newMicLevel);
4097 // We store this outside of the audio buffer to avoid
4098 // having it overwritten by the getter thread.
4099 _newMicLevel = newMicLevel;
4100 SetEvent(_hSetCaptureVolumeEvent);
4106 // If GetBuffer returns AUDCLNT_E_BUFFER_ERROR, the thread consuming the audio samples
4107 // must wait for the next processing pass. The client might benefit from keeping a count
4108 // of the failed GetBuffer calls. If GetBuffer returns this error repeatedly, the client
4109 // can start a new processing loop after shutting down the current client by calling
4110 // IAudioClient::Stop, IAudioClient::Reset, and releasing the audio client.
4111 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4112 "IAudioCaptureClient::GetBuffer returned AUDCLNT_E_BUFFER_ERROR, hr = 0x%08X", hr);
4120 // ---------------------------- THREAD LOOP ---------------------------- <<
4122 hr = _ptrClientIn->Stop();
4127 _ptrClientIn->Stop();
4132 RevertCaptureThreadPriority();
4138 if (_ptrClientIn != NULL)
4140 hr = _ptrClientIn->Stop();
4145 hr = _ptrClientIn->Reset();
4152 // Trigger callback from module process thread
4154 WEBRTC_TRACE(kTraceError, kTraceUtility, _id, "kRecordingError message posted: capturing thread has ended pre-maturely");
4158 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "_Capturing thread is now terminated properly");
4161 SAFE_RELEASE(_ptrClientIn);
4162 SAFE_RELEASE(_ptrCaptureClient);
4168 delete [] syncBuffer;
4174 int32_t AudioDeviceWindowsCore::EnableBuiltInAEC(bool enable)
4177 if (_recIsInitialized)
4179 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4180 "Attempt to set Windows AEC with recording already initialized");
4186 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4187 "Built-in AEC DMO was not initialized properly at create time");
4191 _builtInAecEnabled = enable;
4195 bool AudioDeviceWindowsCore::BuiltInAECIsEnabled() const
4197 return _builtInAecEnabled;
4200 int AudioDeviceWindowsCore::SetDMOProperties()
4203 assert(_dmo != NULL);
4205 scoped_refptr<IPropertyStore> ps;
4207 IPropertyStore* ptrPS = NULL;
4208 hr = _dmo->QueryInterface(IID_IPropertyStore,
4209 reinterpret_cast<void**>(&ptrPS));
4210 if (FAILED(hr) || ptrPS == NULL)
4216 SAFE_RELEASE(ptrPS);
4219 // Set the AEC system mode.
4220 // SINGLE_CHANNEL_AEC - AEC processing only.
4221 if (SetVtI4Property(ps,
4222 MFPKEY_WMAAECMA_SYSTEM_MODE,
4223 SINGLE_CHANNEL_AEC))
4228 // Set the AEC source mode.
4229 // VARIANT_TRUE - Source mode (we poll the AEC for captured data).
4230 if (SetBoolProperty(ps,
4231 MFPKEY_WMAAECMA_DMO_SOURCE_MODE,
4232 VARIANT_TRUE) == -1)
4237 // Enable the feature mode.
4238 // This lets us override all the default processing settings below.
4239 if (SetBoolProperty(ps,
4240 MFPKEY_WMAAECMA_FEATURE_MODE,
4241 VARIANT_TRUE) == -1)
4246 // Disable analog AGC (default enabled).
4247 if (SetBoolProperty(ps,
4248 MFPKEY_WMAAECMA_MIC_GAIN_BOUNDER,
4249 VARIANT_FALSE) == -1)
4254 // Disable noise suppression (default enabled).
4255 // 0 - Disabled, 1 - Enabled
4256 if (SetVtI4Property(ps,
4257 MFPKEY_WMAAECMA_FEATR_NS,
4263 // Relevant parameters to leave at default settings:
4264 // MFPKEY_WMAAECMA_FEATR_AGC - Digital AGC (disabled).
4265 // MFPKEY_WMAAECMA_FEATR_CENTER_CLIP - AEC center clipping (enabled).
4266 // MFPKEY_WMAAECMA_FEATR_ECHO_LENGTH - Filter length (256 ms).
4267 // TODO(andrew): investigate decresing the length to 128 ms.
4268 // MFPKEY_WMAAECMA_FEATR_FRAME_SIZE - Frame size (0).
4269 // 0 is automatic; defaults to 160 samples (or 10 ms frames at the
4270 // selected 16 kHz) as long as mic array processing is disabled.
4271 // MFPKEY_WMAAECMA_FEATR_NOISE_FILL - Comfort noise (enabled).
4272 // MFPKEY_WMAAECMA_FEATR_VAD - VAD (disabled).
4274 // Set the devices selected by VoE. If using a default device, we need to
4275 // search for the device index.
4276 int inDevIndex = _inputDeviceIndex;
4277 int outDevIndex = _outputDeviceIndex;
4278 if (!_usingInputDeviceIndex)
4280 ERole role = eCommunications;
4281 if (_inputDevice == AudioDeviceModule::kDefaultDevice)
4286 if (_GetDefaultDeviceIndex(eCapture, role, &inDevIndex) == -1)
4292 if (!_usingOutputDeviceIndex)
4294 ERole role = eCommunications;
4295 if (_outputDevice == AudioDeviceModule::kDefaultDevice)
4300 if (_GetDefaultDeviceIndex(eRender, role, &outDevIndex) == -1)
4306 DWORD devIndex = static_cast<uint32_t>(outDevIndex << 16) +
4307 static_cast<uint32_t>(0x0000ffff & inDevIndex);
4308 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
4309 "Capture device index: %d, render device index: %d",
4310 inDevIndex, outDevIndex);
4311 if (SetVtI4Property(ps,
4312 MFPKEY_WMAAECMA_DEVICE_INDEXES,
4321 int AudioDeviceWindowsCore::SetBoolProperty(IPropertyStore* ptrPS,
4326 PropVariantInit(&pv);
4329 HRESULT hr = ptrPS->SetValue(key, pv);
4330 PropVariantClear(&pv);
4339 int AudioDeviceWindowsCore::SetVtI4Property(IPropertyStore* ptrPS,
4344 PropVariantInit(&pv);
4347 HRESULT hr = ptrPS->SetValue(key, pv);
4348 PropVariantClear(&pv);
4357 // ----------------------------------------------------------------------------
4358 // _RefreshDeviceList
4360 // Creates a new list of endpoint rendering or capture devices after
4361 // deleting any previously created (and possibly out-of-date) list of
4363 // ----------------------------------------------------------------------------
4365 int32_t AudioDeviceWindowsCore::_RefreshDeviceList(EDataFlow dir)
4367 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4370 IMMDeviceCollection *pCollection = NULL;
4372 assert(dir == eRender || dir == eCapture);
4373 assert(_ptrEnumerator != NULL);
4375 // Create a fresh list of devices using the specified direction
4376 hr = _ptrEnumerator->EnumAudioEndpoints(
4378 DEVICE_STATE_ACTIVE,
4383 SAFE_RELEASE(pCollection);
4389 SAFE_RELEASE(_ptrRenderCollection);
4390 _ptrRenderCollection = pCollection;
4394 SAFE_RELEASE(_ptrCaptureCollection);
4395 _ptrCaptureCollection = pCollection;
4401 // ----------------------------------------------------------------------------
4404 // Gets a count of the endpoint rendering or capture devices in the
4405 // current list of such devices.
4406 // ----------------------------------------------------------------------------
4408 int16_t AudioDeviceWindowsCore::_DeviceListCount(EDataFlow dir)
4410 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4415 assert(eRender == dir || eCapture == dir);
4417 if (eRender == dir && NULL != _ptrRenderCollection)
4419 hr = _ptrRenderCollection->GetCount(&count);
4421 else if (NULL != _ptrCaptureCollection)
4423 hr = _ptrCaptureCollection->GetCount(&count);
4432 return static_cast<int16_t> (count);
4435 // ----------------------------------------------------------------------------
4436 // _GetListDeviceName
4438 // Gets the friendly name of an endpoint rendering or capture device
4439 // from the current list of such devices. The caller uses an index
4440 // into the list to identify the device.
4442 // Uses: _ptrRenderCollection or _ptrCaptureCollection which is updated
4443 // in _RefreshDeviceList().
4444 // ----------------------------------------------------------------------------
4446 int32_t AudioDeviceWindowsCore::_GetListDeviceName(EDataFlow dir, int index, LPWSTR szBuffer, int bufferLen)
4448 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4451 IMMDevice *pDevice = NULL;
4453 assert(dir == eRender || dir == eCapture);
4455 if (eRender == dir && NULL != _ptrRenderCollection)
4457 hr = _ptrRenderCollection->Item(index, &pDevice);
4459 else if (NULL != _ptrCaptureCollection)
4461 hr = _ptrCaptureCollection->Item(index, &pDevice);
4467 SAFE_RELEASE(pDevice);
4471 int32_t res = _GetDeviceName(pDevice, szBuffer, bufferLen);
4472 SAFE_RELEASE(pDevice);
4476 // ----------------------------------------------------------------------------
4477 // _GetDefaultDeviceName
4479 // Gets the friendly name of an endpoint rendering or capture device
4480 // given a specified device role.
4482 // Uses: _ptrEnumerator
4483 // ----------------------------------------------------------------------------
4485 int32_t AudioDeviceWindowsCore::_GetDefaultDeviceName(EDataFlow dir, ERole role, LPWSTR szBuffer, int bufferLen)
4487 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4490 IMMDevice *pDevice = NULL;
4492 assert(dir == eRender || dir == eCapture);
4493 assert(role == eConsole || role == eCommunications);
4494 assert(_ptrEnumerator != NULL);
4496 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
4504 SAFE_RELEASE(pDevice);
4508 int32_t res = _GetDeviceName(pDevice, szBuffer, bufferLen);
4509 SAFE_RELEASE(pDevice);
4513 // ----------------------------------------------------------------------------
4516 // Gets the unique ID string of an endpoint rendering or capture device
4517 // from the current list of such devices. The caller uses an index
4518 // into the list to identify the device.
4520 // Uses: _ptrRenderCollection or _ptrCaptureCollection which is updated
4521 // in _RefreshDeviceList().
4522 // ----------------------------------------------------------------------------
4524 int32_t AudioDeviceWindowsCore::_GetListDeviceID(EDataFlow dir, int index, LPWSTR szBuffer, int bufferLen)
4526 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4529 IMMDevice *pDevice = NULL;
4531 assert(dir == eRender || dir == eCapture);
4533 if (eRender == dir && NULL != _ptrRenderCollection)
4535 hr = _ptrRenderCollection->Item(index, &pDevice);
4537 else if (NULL != _ptrCaptureCollection)
4539 hr = _ptrCaptureCollection->Item(index, &pDevice);
4545 SAFE_RELEASE(pDevice);
4549 int32_t res = _GetDeviceID(pDevice, szBuffer, bufferLen);
4550 SAFE_RELEASE(pDevice);
4554 // ----------------------------------------------------------------------------
4555 // _GetDefaultDeviceID
4557 // Gets the uniqe device ID of an endpoint rendering or capture device
4558 // given a specified device role.
4560 // Uses: _ptrEnumerator
4561 // ----------------------------------------------------------------------------
4563 int32_t AudioDeviceWindowsCore::_GetDefaultDeviceID(EDataFlow dir, ERole role, LPWSTR szBuffer, int bufferLen)
4565 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4568 IMMDevice *pDevice = NULL;
4570 assert(dir == eRender || dir == eCapture);
4571 assert(role == eConsole || role == eCommunications);
4572 assert(_ptrEnumerator != NULL);
4574 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
4582 SAFE_RELEASE(pDevice);
4586 int32_t res = _GetDeviceID(pDevice, szBuffer, bufferLen);
4587 SAFE_RELEASE(pDevice);
4591 int32_t AudioDeviceWindowsCore::_GetDefaultDeviceIndex(EDataFlow dir,
4595 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4598 WCHAR szDefaultDeviceID[MAX_PATH] = {0};
4599 WCHAR szDeviceID[MAX_PATH] = {0};
4601 const size_t kDeviceIDLength = sizeof(szDeviceID)/sizeof(szDeviceID[0]);
4602 assert(kDeviceIDLength ==
4603 sizeof(szDefaultDeviceID) / sizeof(szDefaultDeviceID[0]));
4605 if (_GetDefaultDeviceID(dir,
4608 kDeviceIDLength) == -1)
4613 IMMDeviceCollection* collection = _ptrCaptureCollection;
4616 collection = _ptrRenderCollection;
4621 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4622 "Device collection not valid");
4627 hr = collection->GetCount(&count);
4635 for (UINT i = 0; i < count; i++)
4637 memset(szDeviceID, 0, sizeof(szDeviceID));
4638 scoped_refptr<IMMDevice> device;
4640 IMMDevice* ptrDevice = NULL;
4641 hr = collection->Item(i, &ptrDevice);
4642 if (FAILED(hr) || ptrDevice == NULL)
4648 SAFE_RELEASE(ptrDevice);
4651 if (_GetDeviceID(device, szDeviceID, kDeviceIDLength) == -1)
4656 if (wcsncmp(szDefaultDeviceID, szDeviceID, kDeviceIDLength) == 0)
4667 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4668 "Unable to find collection index for default device");
4675 // ----------------------------------------------------------------------------
4677 // ----------------------------------------------------------------------------
4679 int32_t AudioDeviceWindowsCore::_GetDeviceName(IMMDevice* pDevice,
4683 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4685 static const WCHAR szDefault[] = L"<Device not available>";
4687 HRESULT hr = E_FAIL;
4688 IPropertyStore *pProps = NULL;
4689 PROPVARIANT varName;
4691 assert(pszBuffer != NULL);
4692 assert(bufferLen > 0);
4694 if (pDevice != NULL)
4696 hr = pDevice->OpenPropertyStore(STGM_READ, &pProps);
4699 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4700 "IMMDevice::OpenPropertyStore failed, hr = 0x%08X", hr);
4704 // Initialize container for property value.
4705 PropVariantInit(&varName);
4709 // Get the endpoint device's friendly-name property.
4710 hr = pProps->GetValue(PKEY_Device_FriendlyName, &varName);
4713 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4714 "IPropertyStore::GetValue failed, hr = 0x%08X", hr);
4718 if ((SUCCEEDED(hr)) && (VT_EMPTY == varName.vt))
4721 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4722 "IPropertyStore::GetValue returned no value, hr = 0x%08X", hr);
4725 if ((SUCCEEDED(hr)) && (VT_LPWSTR != varName.vt))
4727 // The returned value is not a wide null terminated string.
4729 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
4730 "IPropertyStore::GetValue returned unexpected type, hr = 0x%08X", hr);
4733 if (SUCCEEDED(hr) && (varName.pwszVal != NULL))
4735 // Copy the valid device name to the provided ouput buffer.
4736 wcsncpy_s(pszBuffer, bufferLen, varName.pwszVal, _TRUNCATE);
4740 // Failed to find the device name.
4741 wcsncpy_s(pszBuffer, bufferLen, szDefault, _TRUNCATE);
4744 PropVariantClear(&varName);
4745 SAFE_RELEASE(pProps);
4750 // ----------------------------------------------------------------------------
4752 // ----------------------------------------------------------------------------
4754 int32_t AudioDeviceWindowsCore::_GetDeviceID(IMMDevice* pDevice, LPWSTR pszBuffer, int bufferLen)
4756 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4758 static const WCHAR szDefault[] = L"<Device not available>";
4760 HRESULT hr = E_FAIL;
4761 LPWSTR pwszID = NULL;
4763 assert(pszBuffer != NULL);
4764 assert(bufferLen > 0);
4766 if (pDevice != NULL)
4768 hr = pDevice->GetId(&pwszID);
4773 // Found the device ID.
4774 wcsncpy_s(pszBuffer, bufferLen, pwszID, _TRUNCATE);
4778 // Failed to find the device ID.
4779 wcsncpy_s(pszBuffer, bufferLen, szDefault, _TRUNCATE);
4782 CoTaskMemFree(pwszID);
4786 // ----------------------------------------------------------------------------
4787 // _GetDefaultDevice
4788 // ----------------------------------------------------------------------------
4790 int32_t AudioDeviceWindowsCore::_GetDefaultDevice(EDataFlow dir, ERole role, IMMDevice** ppDevice)
4792 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4796 assert(_ptrEnumerator != NULL);
4798 hr = _ptrEnumerator->GetDefaultAudioEndpoint(
4811 // ----------------------------------------------------------------------------
4813 // ----------------------------------------------------------------------------
4815 int32_t AudioDeviceWindowsCore::_GetListDevice(EDataFlow dir, int index, IMMDevice** ppDevice)
4819 assert(_ptrEnumerator != NULL);
4821 IMMDeviceCollection *pCollection = NULL;
4823 hr = _ptrEnumerator->EnumAudioEndpoints(
4825 DEVICE_STATE_ACTIVE, // only active endpoints are OK
4830 SAFE_RELEASE(pCollection);
4834 hr = pCollection->Item(
4840 SAFE_RELEASE(pCollection);
4847 // ----------------------------------------------------------------------------
4848 // _EnumerateEndpointDevicesAll
4849 // ----------------------------------------------------------------------------
4851 int32_t AudioDeviceWindowsCore::_EnumerateEndpointDevicesAll(EDataFlow dataFlow) const
4853 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "%s", __FUNCTION__);
4855 assert(_ptrEnumerator != NULL);
4858 IMMDeviceCollection *pCollection = NULL;
4859 IMMDevice *pEndpoint = NULL;
4860 IPropertyStore *pProps = NULL;
4861 IAudioEndpointVolume* pEndpointVolume = NULL;
4862 LPWSTR pwszID = NULL;
4864 // Generate a collection of audio endpoint devices in the system.
4865 // Get states for *all* endpoint devices.
4866 // Output: IMMDeviceCollection interface.
4867 hr = _ptrEnumerator->EnumAudioEndpoints(
4868 dataFlow, // data-flow direction (input parameter)
4869 DEVICE_STATE_ACTIVE | DEVICE_STATE_DISABLED | DEVICE_STATE_UNPLUGGED,
4870 &pCollection); // release interface when done
4874 // use the IMMDeviceCollection interface...
4878 // Retrieve a count of the devices in the device collection.
4879 hr = pCollection->GetCount(&count);
4881 if (dataFlow == eRender)
4882 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#rendering endpoint devices (counting all): %u", count);
4883 else if (dataFlow == eCapture)
4884 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#capturing endpoint devices (counting all): %u", count);
4891 // Each loop prints the name of an endpoint device.
4892 for (ULONG i = 0; i < count; i++)
4894 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "Endpoint %d:", i);
4896 // Get pointer to endpoint number i.
4897 // Output: IMMDevice interface.
4898 hr = pCollection->Item(
4901 CONTINUE_ON_ERROR(hr);
4903 // use the IMMDevice interface of the specified endpoint device...
4905 // Get the endpoint ID string (uniquely identifies the device among all audio endpoint devices)
4906 hr = pEndpoint->GetId(&pwszID);
4907 CONTINUE_ON_ERROR(hr);
4908 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "ID string : %S", pwszID);
4910 // Retrieve an interface to the device's property store.
4911 // Output: IPropertyStore interface.
4912 hr = pEndpoint->OpenPropertyStore(
4915 CONTINUE_ON_ERROR(hr);
4917 // use the IPropertyStore interface...
4919 PROPVARIANT varName;
4920 // Initialize container for property value.
4921 PropVariantInit(&varName);
4923 // Get the endpoint's friendly-name property.
4924 // Example: "Speakers (Realtek High Definition Audio)"
4925 hr = pProps->GetValue(
4926 PKEY_Device_FriendlyName,
4928 CONTINUE_ON_ERROR(hr);
4929 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "friendly name: \"%S\"", varName.pwszVal);
4931 // Get the endpoint's current device state
4933 hr = pEndpoint->GetState(&dwState);
4934 CONTINUE_ON_ERROR(hr);
4935 if (dwState & DEVICE_STATE_ACTIVE)
4936 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "state (0x%x) : *ACTIVE*", dwState);
4937 if (dwState & DEVICE_STATE_DISABLED)
4938 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "state (0x%x) : DISABLED", dwState);
4939 if (dwState & DEVICE_STATE_NOTPRESENT)
4940 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "state (0x%x) : NOTPRESENT", dwState);
4941 if (dwState & DEVICE_STATE_UNPLUGGED)
4942 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "state (0x%x) : UNPLUGGED", dwState);
4944 // Check the hardware volume capabilities.
4945 DWORD dwHwSupportMask = 0;
4946 hr = pEndpoint->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL,
4947 NULL, (void**)&pEndpointVolume);
4948 CONTINUE_ON_ERROR(hr);
4949 hr = pEndpointVolume->QueryHardwareSupport(&dwHwSupportMask);
4950 CONTINUE_ON_ERROR(hr);
4951 if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_VOLUME)
4952 // The audio endpoint device supports a hardware volume control
4953 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "hwmask (0x%x) : HARDWARE_SUPPORT_VOLUME", dwHwSupportMask);
4954 if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_MUTE)
4955 // The audio endpoint device supports a hardware mute control
4956 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "hwmask (0x%x) : HARDWARE_SUPPORT_MUTE", dwHwSupportMask);
4957 if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_METER)
4958 // The audio endpoint device supports a hardware peak meter
4959 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "hwmask (0x%x) : HARDWARE_SUPPORT_METER", dwHwSupportMask);
4961 // Check the channel count (#channels in the audio stream that enters or leaves the audio endpoint device)
4962 UINT nChannelCount(0);
4963 hr = pEndpointVolume->GetChannelCount(
4965 CONTINUE_ON_ERROR(hr);
4966 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#channels : %u", nChannelCount);
4968 if (dwHwSupportMask & ENDPOINT_HARDWARE_SUPPORT_VOLUME)
4970 // Get the volume range.
4971 float fLevelMinDB(0.0);
4972 float fLevelMaxDB(0.0);
4973 float fVolumeIncrementDB(0.0);
4974 hr = pEndpointVolume->GetVolumeRange(
4977 &fVolumeIncrementDB);
4978 CONTINUE_ON_ERROR(hr);
4979 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "volume range : %4.2f (min), %4.2f (max), %4.2f (inc) [dB]",
4980 fLevelMinDB, fLevelMaxDB, fVolumeIncrementDB);
4982 // The volume range from vmin = fLevelMinDB to vmax = fLevelMaxDB is divided
4983 // into n uniform intervals of size vinc = fVolumeIncrementDB, where
4984 // n = (vmax ?vmin) / vinc.
4985 // The values vmin, vmax, and vinc are measured in decibels. The client can set
4986 // the volume level to one of n + 1 discrete values in the range from vmin to vmax.
4987 int n = (int)((fLevelMaxDB-fLevelMinDB)/fVolumeIncrementDB);
4988 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "#intervals : %d", n);
4990 // Get information about the current step in the volume range.
4991 // This method represents the volume level of the audio stream that enters or leaves
4992 // the audio endpoint device as an index or "step" in a range of discrete volume levels.
4993 // Output value nStepCount is the number of steps in the range. Output value nStep
4994 // is the step index of the current volume level. If the number of steps is n = nStepCount,
4995 // then step index nStep can assume values from 0 (minimum volume) to n ?1 (maximum volume).
4998 hr = pEndpointVolume->GetVolumeStepInfo(
5001 CONTINUE_ON_ERROR(hr);
5002 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id, "volume steps : %d (nStep), %d (nStepCount)", nStep, nStepCount);
5006 WEBRTC_TRACE(kTraceInfo, kTraceAudioDevice, _id,
5007 "Error when logging device information");
5009 CoTaskMemFree(pwszID);
5011 PropVariantClear(&varName);
5012 SAFE_RELEASE(pProps);
5013 SAFE_RELEASE(pEndpoint);
5014 SAFE_RELEASE(pEndpointVolume);
5016 SAFE_RELEASE(pCollection);
5021 CoTaskMemFree(pwszID);
5023 SAFE_RELEASE(pCollection);
5024 SAFE_RELEASE(pEndpoint);
5025 SAFE_RELEASE(pEndpointVolume);
5026 SAFE_RELEASE(pProps);
5030 // ----------------------------------------------------------------------------
5032 // ----------------------------------------------------------------------------
5034 void AudioDeviceWindowsCore::_TraceCOMError(HRESULT hr) const
5036 TCHAR buf[MAXERRORLENGTH];
5037 TCHAR errorText[MAXERRORLENGTH];
5039 const DWORD dwFlags = FORMAT_MESSAGE_FROM_SYSTEM |
5040 FORMAT_MESSAGE_IGNORE_INSERTS;
5041 const DWORD dwLangID = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
5043 // Gets the system's human readable message string for this HRESULT.
5044 // All error message in English by default.
5045 DWORD messageLength = ::FormatMessageW(dwFlags,
5053 assert(messageLength <= MAXERRORLENGTH);
5055 // Trims tailing white space (FormatMessage() leaves a trailing cr-lf.).
5056 for (; messageLength && ::isspace(errorText[messageLength - 1]);
5059 errorText[messageLength - 1] = '\0';
5062 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id,
5063 "Core Audio method failed (hr=0x%x)", hr);
5064 StringCchPrintf(buf, MAXERRORLENGTH, TEXT("Error details: "));
5065 StringCchCat(buf, MAXERRORLENGTH, errorText);
5066 WEBRTC_TRACE(kTraceError, kTraceAudioDevice, _id, "%s", WideToUTF8(buf));
5069 // ----------------------------------------------------------------------------
5071 // ----------------------------------------------------------------------------
5073 void AudioDeviceWindowsCore::_SetThreadName(DWORD dwThreadID, LPCSTR szThreadName)
5075 // See http://msdn.microsoft.com/en-us/library/xcb2z8hs(VS.71).aspx for details on the code
5076 // in this function. Name of article is "Setting a Thread Name (Unmanaged)".
5078 THREADNAME_INFO info;
5079 info.dwType = 0x1000;
5080 info.szName = szThreadName;
5081 info.dwThreadID = dwThreadID;
5086 RaiseException( 0x406D1388, 0, sizeof(info)/sizeof(DWORD), (ULONG_PTR *)&info );
5088 __except (EXCEPTION_CONTINUE_EXECUTION)
5093 // ----------------------------------------------------------------------------
5095 // ----------------------------------------------------------------------------
5097 char* AudioDeviceWindowsCore::WideToUTF8(const TCHAR* src) const {
5099 const size_t kStrLen = sizeof(_str);
5100 memset(_str, 0, kStrLen);
5101 // Get required size (in bytes) to be able to complete the conversion.
5102 int required_size = WideCharToMultiByte(CP_UTF8, 0, src, -1, _str, 0, 0, 0);
5103 if (required_size <= kStrLen)
5105 // Process the entire input string, including the terminating null char.
5106 if (WideCharToMultiByte(CP_UTF8, 0, src, -1, _str, kStrLen, 0, 0) == 0)
5107 memset(_str, 0, kStrLen);
5111 return const_cast<char*>(src);
5116 bool AudioDeviceWindowsCore::KeyPressed() const{
5119 for (int key = VK_SPACE; key < VK_NUMLOCK; key++) {
5120 short res = GetAsyncKeyState(key);
5121 key_down |= res & 0x1; // Get the LSB
5123 return (key_down > 0);
5125 } // namespace webrtc
5127 #endif // WEBRTC_WINDOWS_CORE_AUDIO_BUILD