/
audio_device_core_win.cc
4403 lines (3650 loc) · 139 KB
/
audio_device_core_win.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#pragma warning(disable : 4995) // name was marked as #pragma deprecated
#if (_MSC_VER >= 1310) && (_MSC_VER < 1400)
// Reports the major and minor versions of the compiler.
// For example, 1310 for Microsoft Visual C++ .NET 2003. 1310 represents version
// 13 and a 1.0 point release. The Visual C++ 2005 compiler version is 1400.
// Type cl /? at the command line to see the major and minor versions of your
// compiler along with the build number.
#pragma message(">> INFO: Windows Core Audio is not supported in VS 2003")
#endif
#include "modules/audio_device/audio_device_config.h"
#ifdef WEBRTC_WINDOWS_CORE_AUDIO_BUILD
#include "modules/audio_device/win/audio_device_core_win.h"
#include <assert.h>
#include <string.h>
#include <comdef.h>
#include <dmo.h>
#include <functiondiscoverykeys_devpkey.h>
#include <mmsystem.h>
#include <strsafe.h>
#include <uuids.h>
#include <windows.h>
#include <iomanip>
#include "rtc_base/logging.h"
#include "rtc_base/platform_thread.h"
#include "rtc_base/string_utils.h"
#include "rtc_base/thread_annotations.h"
#include "system_wrappers/include/sleep.h"
// Macro that calls a COM method returning HRESULT value.
#define EXIT_ON_ERROR(hres) \
do { \
if (FAILED(hres)) \
goto Exit; \
} while (0)
// Macro that continues to a COM error.
#define CONTINUE_ON_ERROR(hres) \
do { \
if (FAILED(hres)) \
goto Next; \
} while (0)
// Macro that releases a COM object if not NULL.
#define SAFE_RELEASE(p) \
do { \
if ((p)) { \
(p)->Release(); \
(p) = NULL; \
} \
} while (0)
#define ROUND(x) ((x) >= 0 ? (int)((x) + 0.5) : (int)((x)-0.5))
// REFERENCE_TIME time units per millisecond
#define REFTIMES_PER_MILLISEC 10000
typedef struct tagTHREADNAME_INFO {
DWORD dwType; // must be 0x1000
LPCSTR szName; // pointer to name (in user addr space)
DWORD dwThreadID; // thread ID (-1=caller thread)
DWORD dwFlags; // reserved for future use, must be zero
} THREADNAME_INFO;
namespace webrtc {
namespace {
enum { COM_THREADING_MODEL = COINIT_MULTITHREADED };
enum { kAecCaptureStreamIndex = 0, kAecRenderStreamIndex = 1 };
// An implementation of IMediaBuffer, as required for
// IMediaObject::ProcessOutput(). After consuming data provided by
// ProcessOutput(), call SetLength() to update the buffer availability.
//
// Example implementation:
// http://msdn.microsoft.com/en-us/library/dd376684(v=vs.85).aspx
class MediaBufferImpl final : public IMediaBuffer {
public:
explicit MediaBufferImpl(DWORD maxLength)
: _data(new BYTE[maxLength]),
_length(0),
_maxLength(maxLength),
_refCount(0) {}
// IMediaBuffer methods.
STDMETHOD(GetBufferAndLength(BYTE** ppBuffer, DWORD* pcbLength)) {
if (!ppBuffer || !pcbLength) {
return E_POINTER;
}
*ppBuffer = _data;
*pcbLength = _length;
return S_OK;
}
STDMETHOD(GetMaxLength(DWORD* pcbMaxLength)) {
if (!pcbMaxLength) {
return E_POINTER;
}
*pcbMaxLength = _maxLength;
return S_OK;
}
STDMETHOD(SetLength(DWORD cbLength)) {
if (cbLength > _maxLength) {
return E_INVALIDARG;
}
_length = cbLength;
return S_OK;
}
// IUnknown methods.
STDMETHOD_(ULONG, AddRef()) { return InterlockedIncrement(&_refCount); }
STDMETHOD(QueryInterface(REFIID riid, void** ppv)) {
if (!ppv) {
return E_POINTER;
} else if (riid != IID_IMediaBuffer && riid != IID_IUnknown) {
return E_NOINTERFACE;
}
*ppv = static_cast<IMediaBuffer*>(this);
AddRef();
return S_OK;
}
STDMETHOD_(ULONG, Release()) {
LONG refCount = InterlockedDecrement(&_refCount);
if (refCount == 0) {
delete this;
}
return refCount;
}
private:
~MediaBufferImpl() { delete[] _data; }
BYTE* _data;
DWORD _length;
const DWORD _maxLength;
LONG _refCount;
};
} // namespace
// ============================================================================
// Static Methods
// ============================================================================
// ----------------------------------------------------------------------------
// CoreAudioIsSupported
// ----------------------------------------------------------------------------
bool AudioDeviceWindowsCore::CoreAudioIsSupported() {
RTC_LOG(LS_VERBOSE) << __FUNCTION__;
bool MMDeviceIsAvailable(false);
bool coreAudioIsSupported(false);
HRESULT hr(S_OK);
wchar_t buf[MAXERRORLENGTH];
wchar_t errorText[MAXERRORLENGTH];
// 1) Check if Windows version is Vista SP1 or later.
//
// CoreAudio is only available on Vista SP1 and later.
//
OSVERSIONINFOEX osvi;
DWORDLONG dwlConditionMask = 0;
int op = VER_LESS_EQUAL;
// Initialize the OSVERSIONINFOEX structure.
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion = 6;
osvi.dwMinorVersion = 0;
osvi.wServicePackMajor = 0;
osvi.wServicePackMinor = 0;
osvi.wProductType = VER_NT_WORKSTATION;
// Initialize the condition mask.
VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, op);
VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, op);
VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMAJOR, op);
VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMINOR, op);
VER_SET_CONDITION(dwlConditionMask, VER_PRODUCT_TYPE, VER_EQUAL);
DWORD dwTypeMask = VER_MAJORVERSION | VER_MINORVERSION |
VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR |
VER_PRODUCT_TYPE;
// Perform the test.
BOOL isVistaRTMorXP = VerifyVersionInfo(&osvi, dwTypeMask, dwlConditionMask);
if (isVistaRTMorXP != 0) {
RTC_LOG(LS_VERBOSE)
<< "*** Windows Core Audio is only supported on Vista SP1 or later"
<< " => will revert to the Wave API ***";
return false;
}
// 2) Initializes the COM library for use by the calling thread.
// The COM init wrapper sets the thread's concurrency model to MTA,
// and creates a new apartment for the thread if one is required. The
// wrapper also ensures that each call to CoInitializeEx is balanced
// by a corresponding call to CoUninitialize.
//
ScopedCOMInitializer comInit(ScopedCOMInitializer::kMTA);
if (!comInit.succeeded()) {
// Things will work even if an STA thread is calling this method but we
// want to ensure that MTA is used and therefore return false here.
return false;
}
// 3) Check if the MMDevice API is available.
//
// The Windows Multimedia Device (MMDevice) API enables audio clients to
// discover audio endpoint devices, determine their capabilities, and create
// driver instances for those devices.
// Header file Mmdeviceapi.h defines the interfaces in the MMDevice API.
// The MMDevice API consists of several interfaces. The first of these is the
// IMMDeviceEnumerator interface. To access the interfaces in the MMDevice
// API, a client obtains a reference to the IMMDeviceEnumerator interface of a
// device-enumerator object by calling the CoCreateInstance function.
//
// Through the IMMDeviceEnumerator interface, the client can obtain references
// to the other interfaces in the MMDevice API. The MMDevice API implements
// the following interfaces:
//
// IMMDevice Represents an audio device.
// IMMDeviceCollection Represents a collection of audio devices.
// IMMDeviceEnumerator Provides methods for enumerating audio devices.
// IMMEndpoint Represents an audio endpoint device.
//
IMMDeviceEnumerator* pIMMD(NULL);
const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
hr = CoCreateInstance(
CLSID_MMDeviceEnumerator, // GUID value of MMDeviceEnumerator coclass
NULL, CLSCTX_ALL,
IID_IMMDeviceEnumerator, // GUID value of the IMMDeviceEnumerator
// interface
(void**)&pIMMD);
if (FAILED(hr)) {
RTC_LOG(LS_ERROR) << "AudioDeviceWindowsCore::CoreAudioIsSupported()"
<< " Failed to create the required COM object (hr=" << hr
<< ")";
RTC_LOG(LS_VERBOSE) << "AudioDeviceWindowsCore::CoreAudioIsSupported()"
<< " CoCreateInstance(MMDeviceEnumerator) failed (hr="
<< hr << ")";
const DWORD dwFlags =
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
const DWORD dwLangID = MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US);
// Gets the system's human readable message string for this HRESULT.
// All error message in English by default.
DWORD messageLength = ::FormatMessageW(dwFlags, 0, hr, dwLangID, errorText,
MAXERRORLENGTH, NULL);
assert(messageLength <= MAXERRORLENGTH);
// Trims tailing white space (FormatMessage() leaves a trailing cr-lf.).
for (; messageLength && ::isspace(errorText[messageLength - 1]);
--messageLength) {
errorText[messageLength - 1] = '\0';
}
StringCchPrintfW(buf, MAXERRORLENGTH, L"Error details: ");
StringCchCatW(buf, MAXERRORLENGTH, errorText);
RTC_LOG(LS_VERBOSE) << buf;
} else {
MMDeviceIsAvailable = true;
RTC_LOG(LS_VERBOSE)
<< "AudioDeviceWindowsCore::CoreAudioIsSupported()"
<< " CoCreateInstance(MMDeviceEnumerator) succeeded (hr=" << hr << ")";
SAFE_RELEASE(pIMMD);
}
// 4) Verify that we can create and initialize our Core Audio class.
//
// Also, perform a limited "API test" to ensure that Core Audio is supported
// for all devices.
//
if (MMDeviceIsAvailable) {
coreAudioIsSupported = false;
AudioDeviceWindowsCore* p = new AudioDeviceWindowsCore();
if (p == NULL) {
return false;
}
int ok(0);
int temp_ok(0);
bool available(false);
if (p->Init() != InitStatus::OK) {
ok |= -1;
}
int16_t numDevsRec = p->RecordingDevices();
for (uint16_t i = 0; i < numDevsRec; i++) {
ok |= p->SetRecordingDevice(i);
temp_ok = p->RecordingIsAvailable(available);
ok |= temp_ok;
ok |= (available == false);
if (available) {
ok |= p->InitMicrophone();
}
if (ok) {
RTC_LOG(LS_WARNING)
<< "AudioDeviceWindowsCore::CoreAudioIsSupported()"
<< " Failed to use Core Audio Recording for device id=" << i;
}
}
int16_t numDevsPlay = p->PlayoutDevices();
for (uint16_t i = 0; i < numDevsPlay; i++) {
ok |= p->SetPlayoutDevice(i);
temp_ok = p->PlayoutIsAvailable(available);
ok |= temp_ok;
ok |= (available == false);
if (available) {
ok |= p->InitSpeaker();
}
if (ok) {
RTC_LOG(LS_WARNING)
<< "AudioDeviceWindowsCore::CoreAudioIsSupported()"
<< " Failed to use Core Audio Playout for device id=" << i;
}
}
ok |= p->Terminate();
if (ok == 0) {
coreAudioIsSupported = true;
}
delete p;
}
if (coreAudioIsSupported) {
RTC_LOG(LS_VERBOSE) << "*** Windows Core Audio is supported ***";
} else {
RTC_LOG(LS_VERBOSE) << "*** Windows Core Audio is NOT supported"
<< " => will revert to the Wave API ***";
}
return (coreAudioIsSupported);
}
// ============================================================================
// Construction & Destruction
// ============================================================================
// ----------------------------------------------------------------------------
// AudioDeviceWindowsCore() - ctor
// ----------------------------------------------------------------------------
AudioDeviceWindowsCore::AudioDeviceWindowsCore()
: _avrtLibrary(NULL),
_winSupportAvrt(false),
_comInit(ScopedCOMInitializer::kMTA),
_ptrAudioBuffer(NULL),
_ptrEnumerator(NULL),
_ptrRenderCollection(NULL),
_ptrCaptureCollection(NULL),
_ptrDeviceOut(NULL),
_ptrDeviceIn(NULL),
_ptrClientOut(NULL),
_ptrClientIn(NULL),
_ptrRenderClient(NULL),
_ptrCaptureClient(NULL),
_ptrCaptureVolume(NULL),
_ptrRenderSimpleVolume(NULL),
_dmo(NULL),
_mediaBuffer(NULL),
_builtInAecEnabled(false),
_hRenderSamplesReadyEvent(NULL),
_hPlayThread(NULL),
_hRenderStartedEvent(NULL),
_hShutdownRenderEvent(NULL),
_hCaptureSamplesReadyEvent(NULL),
_hRecThread(NULL),
_hCaptureStartedEvent(NULL),
_hShutdownCaptureEvent(NULL),
_hMmTask(NULL),
_playAudioFrameSize(0),
_playSampleRate(0),
_playBlockSize(0),
_playChannels(2),
_sndCardPlayDelay(0),
_sndCardRecDelay(0),
_writtenSamples(0),
_readSamples(0),
_recAudioFrameSize(0),
_recSampleRate(0),
_recBlockSize(0),
_recChannels(2),
_initialized(false),
_recording(false),
_playing(false),
_recIsInitialized(false),
_playIsInitialized(false),
_speakerIsInitialized(false),
_microphoneIsInitialized(false),
_usingInputDeviceIndex(false),
_usingOutputDeviceIndex(false),
_inputDevice(AudioDeviceModule::kDefaultCommunicationDevice),
_outputDevice(AudioDeviceModule::kDefaultCommunicationDevice),
_inputDeviceIndex(0),
_outputDeviceIndex(0) {
RTC_LOG(LS_INFO) << __FUNCTION__ << " created";
assert(_comInit.succeeded());
// Try to load the Avrt DLL
if (!_avrtLibrary) {
// Get handle to the Avrt DLL module.
_avrtLibrary = LoadLibrary(TEXT("Avrt.dll"));
if (_avrtLibrary) {
// Handle is valid (should only happen if OS larger than vista & win7).
// Try to get the function addresses.
RTC_LOG(LS_VERBOSE) << "AudioDeviceWindowsCore::AudioDeviceWindowsCore()"
<< " The Avrt DLL module is now loaded";
_PAvRevertMmThreadCharacteristics =
(PAvRevertMmThreadCharacteristics)GetProcAddress(
_avrtLibrary, "AvRevertMmThreadCharacteristics");
_PAvSetMmThreadCharacteristicsA =
(PAvSetMmThreadCharacteristicsA)GetProcAddress(
_avrtLibrary, "AvSetMmThreadCharacteristicsA");
_PAvSetMmThreadPriority = (PAvSetMmThreadPriority)GetProcAddress(
_avrtLibrary, "AvSetMmThreadPriority");
if (_PAvRevertMmThreadCharacteristics &&
_PAvSetMmThreadCharacteristicsA && _PAvSetMmThreadPriority) {
RTC_LOG(LS_VERBOSE)
<< "AudioDeviceWindowsCore::AudioDeviceWindowsCore()"
<< " AvRevertMmThreadCharacteristics() is OK";
RTC_LOG(LS_VERBOSE)
<< "AudioDeviceWindowsCore::AudioDeviceWindowsCore()"
<< " AvSetMmThreadCharacteristicsA() is OK";
RTC_LOG(LS_VERBOSE)
<< "AudioDeviceWindowsCore::AudioDeviceWindowsCore()"
<< " AvSetMmThreadPriority() is OK";
_winSupportAvrt = true;
}
}
}
// Create our samples ready events - we want auto reset events that start in
// the not-signaled state. The state of an auto-reset event object remains
// signaled until a single waiting thread is released, at which time the
// system automatically sets the state to nonsignaled. If no threads are
// waiting, the event object's state remains signaled. (Except for
// _hShutdownCaptureEvent, which is used to shutdown multiple threads).
_hRenderSamplesReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
_hCaptureSamplesReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
_hShutdownRenderEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
_hShutdownCaptureEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
_hRenderStartedEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
_hCaptureStartedEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
_perfCounterFreq.QuadPart = 1;
_perfCounterFactor = 0.0;
// list of number of channels to use on recording side
_recChannelsPrioList[0] = 2; // stereo is prio 1
_recChannelsPrioList[1] = 1; // mono is prio 2
_recChannelsPrioList[2] = 4; // quad is prio 3
// list of number of channels to use on playout side
_playChannelsPrioList[0] = 2; // stereo is prio 1
_playChannelsPrioList[1] = 1; // mono is prio 2
HRESULT hr;
// We know that this API will work since it has already been verified in
// CoreAudioIsSupported, hence no need to check for errors here as well.
// Retrive the IMMDeviceEnumerator API (should load the MMDevAPI.dll)
// TODO(henrika): we should probably move this allocation to Init() instead
// and deallocate in Terminate() to make the implementation more symmetric.
CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL,
__uuidof(IMMDeviceEnumerator),
reinterpret_cast<void**>(&_ptrEnumerator));
assert(NULL != _ptrEnumerator);
// DMO initialization for built-in WASAPI AEC.
{
IMediaObject* ptrDMO = NULL;
hr = CoCreateInstance(CLSID_CWMAudioAEC, NULL, CLSCTX_INPROC_SERVER,
IID_IMediaObject, reinterpret_cast<void**>(&ptrDMO));
if (FAILED(hr) || ptrDMO == NULL) {
// Since we check that _dmo is non-NULL in EnableBuiltInAEC(), the
// feature is prevented from being enabled.
_builtInAecEnabled = false;
_TraceCOMError(hr);
}
_dmo = ptrDMO;
SAFE_RELEASE(ptrDMO);
}
}
// ----------------------------------------------------------------------------
// AudioDeviceWindowsCore() - dtor
// ----------------------------------------------------------------------------
AudioDeviceWindowsCore::~AudioDeviceWindowsCore() {
RTC_LOG(LS_INFO) << __FUNCTION__ << " destroyed";
Terminate();
// The IMMDeviceEnumerator is created during construction. Must release
// it here and not in Terminate() since we don't recreate it in Init().
SAFE_RELEASE(_ptrEnumerator);
_ptrAudioBuffer = NULL;
if (NULL != _hRenderSamplesReadyEvent) {
CloseHandle(_hRenderSamplesReadyEvent);
_hRenderSamplesReadyEvent = NULL;
}
if (NULL != _hCaptureSamplesReadyEvent) {
CloseHandle(_hCaptureSamplesReadyEvent);
_hCaptureSamplesReadyEvent = NULL;
}
if (NULL != _hRenderStartedEvent) {
CloseHandle(_hRenderStartedEvent);
_hRenderStartedEvent = NULL;
}
if (NULL != _hCaptureStartedEvent) {
CloseHandle(_hCaptureStartedEvent);
_hCaptureStartedEvent = NULL;
}
if (NULL != _hShutdownRenderEvent) {
CloseHandle(_hShutdownRenderEvent);
_hShutdownRenderEvent = NULL;
}
if (NULL != _hShutdownCaptureEvent) {
CloseHandle(_hShutdownCaptureEvent);
_hShutdownCaptureEvent = NULL;
}
if (_avrtLibrary) {
BOOL freeOK = FreeLibrary(_avrtLibrary);
if (!freeOK) {
RTC_LOG(LS_WARNING)
<< "AudioDeviceWindowsCore::~AudioDeviceWindowsCore()"
<< " failed to free the loaded Avrt DLL module correctly";
} else {
RTC_LOG(LS_WARNING) << "AudioDeviceWindowsCore::~AudioDeviceWindowsCore()"
<< " the Avrt DLL module is now unloaded";
}
}
}
// ============================================================================
// API
// ============================================================================
// ----------------------------------------------------------------------------
// AttachAudioBuffer
// ----------------------------------------------------------------------------
void AudioDeviceWindowsCore::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) {
_ptrAudioBuffer = audioBuffer;
// Inform the AudioBuffer about default settings for this implementation.
// Set all values to zero here since the actual settings will be done by
// InitPlayout and InitRecording later.
_ptrAudioBuffer->SetRecordingSampleRate(0);
_ptrAudioBuffer->SetPlayoutSampleRate(0);
_ptrAudioBuffer->SetRecordingChannels(0);
_ptrAudioBuffer->SetPlayoutChannels(0);
}
// ----------------------------------------------------------------------------
// ActiveAudioLayer
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::ActiveAudioLayer(
AudioDeviceModule::AudioLayer& audioLayer) const {
audioLayer = AudioDeviceModule::kWindowsCoreAudio;
return 0;
}
// ----------------------------------------------------------------------------
// Init
// ----------------------------------------------------------------------------
AudioDeviceGeneric::InitStatus AudioDeviceWindowsCore::Init() {
rtc::CritScope lock(&_critSect);
if (_initialized) {
return InitStatus::OK;
}
// Enumerate all audio rendering and capturing endpoint devices.
// Note that, some of these will not be able to select by the user.
// The complete collection is for internal use only.
_EnumerateEndpointDevicesAll(eRender);
_EnumerateEndpointDevicesAll(eCapture);
_initialized = true;
return InitStatus::OK;
}
// ----------------------------------------------------------------------------
// Terminate
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::Terminate() {
rtc::CritScope lock(&_critSect);
if (!_initialized) {
return 0;
}
_initialized = false;
_speakerIsInitialized = false;
_microphoneIsInitialized = false;
_playing = false;
_recording = false;
SAFE_RELEASE(_ptrRenderCollection);
SAFE_RELEASE(_ptrCaptureCollection);
SAFE_RELEASE(_ptrDeviceOut);
SAFE_RELEASE(_ptrDeviceIn);
SAFE_RELEASE(_ptrClientOut);
SAFE_RELEASE(_ptrClientIn);
SAFE_RELEASE(_ptrRenderClient);
SAFE_RELEASE(_ptrCaptureClient);
SAFE_RELEASE(_ptrCaptureVolume);
SAFE_RELEASE(_ptrRenderSimpleVolume);
return 0;
}
// ----------------------------------------------------------------------------
// Initialized
// ----------------------------------------------------------------------------
bool AudioDeviceWindowsCore::Initialized() const {
return (_initialized);
}
// ----------------------------------------------------------------------------
// InitSpeaker
// 从新获取设备
//
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::InitSpeaker() {
rtc::CritScope lock(&_critSect);
if (_playing) {
return -1;
}
if (_ptrDeviceOut == NULL) {
return -1;
}
// TODO@chensong 20220718 设备是否使用索引号
if (_usingOutputDeviceIndex) {
int16_t nDevices = PlayoutDevices();
if (_outputDeviceIndex > (nDevices - 1)) {
RTC_LOG(LS_ERROR) << "current device selection is invalid => unable to"
<< " initialize";
return -1;
}
}
int32_t ret(0);
SAFE_RELEASE(_ptrDeviceOut);
if (_usingOutputDeviceIndex) {
// Refresh the selected rendering endpoint device using current index
ret = _GetListDevice(eRender, _outputDeviceIndex, &_ptrDeviceOut);
} else {
ERole role;
(_outputDevice == AudioDeviceModule::kDefaultDevice)
? role = eConsole
: role = eCommunications;
// Refresh the selected rendering endpoint device using role
// TODO@chensong 20220718 从新刷新设备 ---》 为什么刷新
ret = _GetDefaultDevice(eRender, role, &_ptrDeviceOut);
}
if (ret != 0 || (_ptrDeviceOut == NULL)) {
RTC_LOG(LS_ERROR) << "failed to initialize the rendering enpoint device";
SAFE_RELEASE(_ptrDeviceOut);
return -1;
}
IAudioSessionManager* pManager = NULL;
ret = _ptrDeviceOut->Activate(__uuidof(IAudioSessionManager), CLSCTX_ALL,
NULL, (void**)&pManager);
if (ret != 0 || pManager == NULL) {
RTC_LOG(LS_ERROR) << "failed to initialize the render manager";
SAFE_RELEASE(pManager);
return -1;
}
SAFE_RELEASE(_ptrRenderSimpleVolume);
// TODO@chensong 20220718 ===>GetSimpleAudioVolume
// 该方法属于IAudioSessionManager(WASAPI)
// 简单的音频音量控制, 只改变应用组件的音量
// 参数1: 指向会话GUID的指针,如果该参数为NULL, 该方法将音频流设置给默认Session
// 参数2: 指定该Session是否是一个跨进程的Session
// 参数3: 获得SimpleAudioVolume对象 调整扬声器得大小了
ret = pManager->GetSimpleAudioVolume(NULL, FALSE, &_ptrRenderSimpleVolume);
if (ret != 0 || _ptrRenderSimpleVolume == NULL) {
RTC_LOG(LS_ERROR) << "failed to initialize the render simple volume";
SAFE_RELEASE(pManager);
SAFE_RELEASE(_ptrRenderSimpleVolume);
return -1;
}
SAFE_RELEASE(pManager);
// 修改speaker状态
_speakerIsInitialized = true;
return 0;
}
// ----------------------------------------------------------------------------
// InitMicrophone
// 使用那个设备
// 设备音量控制
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::InitMicrophone() {
rtc::CritScope lock(&_critSect);
//有没有开启录制
if (_recording)
{
return -1;
}
// 采集设备是否获取到了
if (_ptrDeviceIn == NULL)
{
return -1;
}
if (_usingInputDeviceIndex)
{
int16_t nDevices = RecordingDevices();
if (_inputDeviceIndex > (nDevices - 1)) {
RTC_LOG(LS_ERROR) << "current device selection is invalid => unable to"
<< " initialize";
return -1;
}
}
int32_t ret(0);
SAFE_RELEASE(_ptrDeviceIn);
if (_usingInputDeviceIndex) {
// Refresh the selected capture endpoint device using current index
ret = _GetListDevice(eCapture, _inputDeviceIndex, &_ptrDeviceIn);
} else {
ERole role;
(_inputDevice == AudioDeviceModule::kDefaultDevice)
? role = eConsole
: role = eCommunications;
// Refresh the selected capture endpoint device using role
//从新获取采集设备
ret = _GetDefaultDevice(eCapture, role, &_ptrDeviceIn);
}
if (ret != 0 || (_ptrDeviceIn == NULL)) {
RTC_LOG(LS_ERROR) << "failed to initialize the capturing enpoint device";
SAFE_RELEASE(_ptrDeviceIn);
return -1;
}
SAFE_RELEASE(_ptrCaptureVolume);
ret = _ptrDeviceIn->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL,
reinterpret_cast<void**>(&_ptrCaptureVolume));
if (ret != 0 || _ptrCaptureVolume == NULL)
{
RTC_LOG(LS_ERROR) << "failed to initialize the capture volume";
SAFE_RELEASE(_ptrCaptureVolume);
return -1;
}
_microphoneIsInitialized = true;
return 0;
}
// ----------------------------------------------------------------------------
// SpeakerIsInitialized
// ----------------------------------------------------------------------------
bool AudioDeviceWindowsCore::SpeakerIsInitialized() const {
return (_speakerIsInitialized);
}
// ----------------------------------------------------------------------------
// MicrophoneIsInitialized
// ----------------------------------------------------------------------------
bool AudioDeviceWindowsCore::MicrophoneIsInitialized() const {
return (_microphoneIsInitialized);
}
// ----------------------------------------------------------------------------
// SpeakerVolumeIsAvailable
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::SpeakerVolumeIsAvailable(bool& available) {
rtc::CritScope lock(&_critSect);
if (_ptrDeviceOut == NULL) {
return -1;
}
HRESULT hr = S_OK;
IAudioSessionManager* pManager = NULL;
ISimpleAudioVolume* pVolume = NULL;
hr = _ptrDeviceOut->Activate(__uuidof(IAudioSessionManager), CLSCTX_ALL, NULL,
(void**)&pManager);
EXIT_ON_ERROR(hr);
hr = pManager->GetSimpleAudioVolume(NULL, FALSE, &pVolume);
EXIT_ON_ERROR(hr);
float volume(0.0f);
hr = pVolume->GetMasterVolume(&volume);
if (FAILED(hr)) {
available = false;
}
available = true;
SAFE_RELEASE(pManager);
SAFE_RELEASE(pVolume);
return 0;
Exit:
_TraceCOMError(hr);
SAFE_RELEASE(pManager);
SAFE_RELEASE(pVolume);
return -1;
}
// ----------------------------------------------------------------------------
// SetSpeakerVolume
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::SetSpeakerVolume(uint32_t volume) {
{
rtc::CritScope lock(&_critSect);
if (!_speakerIsInitialized) {
return -1;
}
if (_ptrDeviceOut == NULL) {
return -1;
}
}
if (volume < (uint32_t)MIN_CORE_SPEAKER_VOLUME ||
volume > (uint32_t)MAX_CORE_SPEAKER_VOLUME) {
return -1;
}
HRESULT hr = S_OK;
// scale input volume to valid range (0.0 to 1.0)
const float fLevel = (float)volume / MAX_CORE_SPEAKER_VOLUME;
_volumeMutex.Enter();
hr = _ptrRenderSimpleVolume->SetMasterVolume(fLevel, NULL);
_volumeMutex.Leave();
EXIT_ON_ERROR(hr);
return 0;
Exit:
_TraceCOMError(hr);
return -1;
}
// ----------------------------------------------------------------------------
// SpeakerVolume
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::SpeakerVolume(uint32_t& volume) const {
{
rtc::CritScope lock(&_critSect);
if (!_speakerIsInitialized) {
return -1;
}
if (_ptrDeviceOut == NULL) {
return -1;
}
}
HRESULT hr = S_OK;
float fLevel(0.0f);
_volumeMutex.Enter();
hr = _ptrRenderSimpleVolume->GetMasterVolume(&fLevel);
_volumeMutex.Leave();
EXIT_ON_ERROR(hr);
// scale input volume range [0.0,1.0] to valid output range
volume = static_cast<uint32_t>(fLevel * MAX_CORE_SPEAKER_VOLUME);
return 0;
Exit:
_TraceCOMError(hr);
return -1;
}
// ----------------------------------------------------------------------------
// MaxSpeakerVolume
//
// The internal range for Core Audio is 0.0 to 1.0, where 0.0 indicates
// silence and 1.0 indicates full volume (no attenuation).
// We add our (webrtc-internal) own max level to match the Wave API and
// how it is used today in VoE.
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::MaxSpeakerVolume(uint32_t& maxVolume) const {
if (!_speakerIsInitialized) {
return -1;
}
maxVolume = static_cast<uint32_t>(MAX_CORE_SPEAKER_VOLUME);
return 0;
}
// ----------------------------------------------------------------------------
// MinSpeakerVolume
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::MinSpeakerVolume(uint32_t& minVolume) const {
if (!_speakerIsInitialized) {
return -1;
}
minVolume = static_cast<uint32_t>(MIN_CORE_SPEAKER_VOLUME);
return 0;
}
// ----------------------------------------------------------------------------
// SpeakerMuteIsAvailable
// ----------------------------------------------------------------------------
int32_t AudioDeviceWindowsCore::SpeakerMuteIsAvailable(bool& available) {
rtc::CritScope lock(&_critSect);
if (_ptrDeviceOut == NULL) {
return -1;
}
HRESULT hr = S_OK;
IAudioEndpointVolume* pVolume = NULL;
// Query the speaker system mute state.
hr = _ptrDeviceOut->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, NULL,
reinterpret_cast<void**>(&pVolume));