-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathcubeb_wasapi.cpp
More file actions
2472 lines (2113 loc) · 77.6 KB
/
cubeb_wasapi.cpp
File metadata and controls
2472 lines (2113 loc) · 77.6 KB
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 © 2013 Mozilla Foundation
*
* This program is made available under an ISC-style license. See the
* accompanying file LICENSE for details.
*/
#define _WIN32_WINNT 0x0600
#define NOMINMAX
#include <initguid.h>
#include <windows.h>
#include <mmdeviceapi.h>
#include <windef.h>
#include <audioclient.h>
#include <devicetopology.h>
#include <process.h>
#include <avrt.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <cmath>
#include <algorithm>
#include <memory>
#include <limits>
#include <atomic>
#include <vector>
#include "cubeb/cubeb.h"
#include "cubeb-internal.h"
#include "cubeb_mixer.h"
#include "cubeb_resampler.h"
#include "cubeb_strings.h"
#include "cubeb_utils.h"
#ifndef PKEY_Device_FriendlyName
DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14); // DEVPROP_TYPE_STRING
#endif
#ifndef PKEY_Device_InstanceId
DEFINE_PROPERTYKEY(PKEY_Device_InstanceId, 0x78c34fc8, 0x104a, 0x4aca, 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57, 0x00000100); // VT_LPWSTR
#endif
namespace {
struct com_heap_ptr_deleter {
void operator()(void * ptr) const noexcept {
CoTaskMemFree(ptr);
}
};
template <typename T>
using com_heap_ptr = std::unique_ptr<T, com_heap_ptr_deleter>;
template<typename T, size_t N>
constexpr size_t
ARRAY_LENGTH(T(&)[N])
{
return N;
}
template <typename T>
class no_addref_release : public T {
ULONG STDMETHODCALLTYPE AddRef() = 0;
ULONG STDMETHODCALLTYPE Release() = 0;
};
template <typename T>
class com_ptr {
public:
com_ptr() noexcept = default;
com_ptr(com_ptr const & other) noexcept = delete;
com_ptr & operator=(com_ptr const & other) noexcept = delete;
T ** operator&() const noexcept = delete;
~com_ptr() noexcept {
release();
}
com_ptr(com_ptr && other) noexcept
: ptr(other.ptr)
{
other.ptr = nullptr;
}
com_ptr & operator=(com_ptr && other) noexcept {
if (ptr != other.ptr) {
release();
ptr = other.ptr;
other.ptr = nullptr;
}
return *this;
}
explicit operator bool() const noexcept {
return nullptr != ptr;
}
no_addref_release<T> * operator->() const noexcept {
return static_cast<no_addref_release<T> *>(ptr);
}
T * get() const noexcept {
return ptr;
}
T ** receive() noexcept {
XASSERT(ptr == nullptr);
return &ptr;
}
void ** receive_vpp() noexcept {
return reinterpret_cast<void **>(receive());
}
com_ptr & operator=(std::nullptr_t) noexcept {
release();
return *this;
}
void reset(T * p = nullptr) noexcept {
release();
ptr = p;
}
private:
void release() noexcept {
T * temp = ptr;
if (temp) {
ptr = nullptr;
temp->Release();
}
}
T * ptr = nullptr;
};
extern cubeb_ops const wasapi_ops;
int wasapi_stream_stop(cubeb_stream * stm);
int wasapi_stream_start(cubeb_stream * stm);
void close_wasapi_stream(cubeb_stream * stm);
int setup_wasapi_stream(cubeb_stream * stm);
static char const * wstr_to_utf8(wchar_t const * str);
static std::unique_ptr<wchar_t const []> utf8_to_wstr(char const * str);
}
struct cubeb {
cubeb_ops const * ops = &wasapi_ops;
cubeb_strings * device_ids;
};
class wasapi_endpoint_notification_client;
/* We have three possible callbacks we can use with a stream:
* - input only
* - output only
* - synchronized input and output
*
* Returns true when we should continue to play, false otherwise.
*/
typedef bool (*wasapi_refill_callback)(cubeb_stream * stm);
struct cubeb_stream {
/* Note: Must match cubeb_stream layout in cubeb.c. */
cubeb * context = nullptr;
void * user_ptr = nullptr;
/**/
/* Mixer pameters. We need to convert the input stream to this
samplerate/channel layout, as WASAPI does not resample nor upmix
itself. */
cubeb_stream_params input_mix_params = { CUBEB_SAMPLE_FLOAT32NE, 0, 0, CUBEB_LAYOUT_UNDEFINED, CUBEB_STREAM_PREF_NONE };
cubeb_stream_params output_mix_params = { CUBEB_SAMPLE_FLOAT32NE, 0, 0, CUBEB_LAYOUT_UNDEFINED, CUBEB_STREAM_PREF_NONE };
/* Stream parameters. This is what the client requested,
* and what will be presented in the callback. */
cubeb_stream_params input_stream_params = { CUBEB_SAMPLE_FLOAT32NE, 0, 0, CUBEB_LAYOUT_UNDEFINED, CUBEB_STREAM_PREF_NONE };
cubeb_stream_params output_stream_params = { CUBEB_SAMPLE_FLOAT32NE, 0, 0, CUBEB_LAYOUT_UNDEFINED, CUBEB_STREAM_PREF_NONE };
/* The input and output device, or NULL for default. */
std::unique_ptr<const wchar_t[]> input_device;
std::unique_ptr<const wchar_t[]> output_device;
/* The latency initially requested for this stream, in frames. */
unsigned latency = 0;
cubeb_state_callback state_callback = nullptr;
cubeb_data_callback data_callback = nullptr;
wasapi_refill_callback refill_callback = nullptr;
/* True when a loopback device is requested with no output device. In this
case a dummy output device is opened to drive the loopback, but should not
be exposed. */
bool has_dummy_output = false;
/* Lifetime considerations:
- client, render_client, audio_clock and audio_stream_volume are interface
pointer to the IAudioClient.
- The lifetime for device_enumerator and notification_client, resampler,
mix_buffer are the same as the cubeb_stream instance. */
/* Main handle on the WASAPI stream. */
com_ptr<IAudioClient> output_client;
/* Interface pointer to use the event-driven interface. */
com_ptr<IAudioRenderClient> render_client;
/* Interface pointer to use the volume facilities. */
com_ptr<IAudioStreamVolume> audio_stream_volume;
/* Interface pointer to use the stream audio clock. */
com_ptr<IAudioClock> audio_clock;
/* Frames written to the stream since it was opened. Reset on device
change. Uses mix_params.rate. */
UINT64 frames_written = 0;
/* Frames written to the (logical) stream since it was first
created. Updated on device change. Uses stream_params.rate. */
UINT64 total_frames_written = 0;
/* Last valid reported stream position. Used to ensure the position
reported by stream_get_position increases monotonically. */
UINT64 prev_position = 0;
/* Device enumerator to be able to be notified when the default
device change. */
com_ptr<IMMDeviceEnumerator> device_enumerator;
/* Device notification client, to be able to be notified when the default
audio device changes and route the audio to the new default audio output
device */
com_ptr<wasapi_endpoint_notification_client> notification_client;
/* Main andle to the WASAPI capture stream. */
com_ptr<IAudioClient> input_client;
/* Interface to use the event driven capture interface */
com_ptr<IAudioCaptureClient> capture_client;
/* This event is set by the stream_stop and stream_destroy
function, so the render loop can exit properly. */
HANDLE shutdown_event = 0;
/* Set by OnDefaultDeviceChanged when a stream reconfiguration is required.
The reconfiguration is handled by the render loop thread. */
HANDLE reconfigure_event = 0;
/* This is set by WASAPI when we should refill the stream. */
HANDLE refill_event = 0;
/* This is set by WASAPI when we should read from the input stream. In
* practice, we read from the input stream in the output callback, so
* this is not used, but it is necessary to start getting input data. */
HANDLE input_available_event = 0;
/* Each cubeb_stream has its own thread. */
HANDLE thread = 0;
/* The lock protects all members that are touched by the render thread or
change during a device reset, including: audio_clock, audio_stream_volume,
client, frames_written, mix_params, total_frames_written, prev_position. */
owned_critical_section stream_reset_lock;
/* Maximum number of frames that can be passed down in a callback. */
uint32_t input_buffer_frame_count = 0;
/* Maximum number of frames that can be requested in a callback. */
uint32_t output_buffer_frame_count = 0;
/* Resampler instance. Resampling will only happen if necessary. */
std::unique_ptr<cubeb_resampler, decltype(&cubeb_resampler_destroy)> resampler = { nullptr, cubeb_resampler_destroy };
/* Mixer interfaces */
std::unique_ptr<cubeb_mixer, decltype(&cubeb_mixer_destroy)> output_mixer = { nullptr, cubeb_mixer_destroy };
std::unique_ptr<cubeb_mixer, decltype(&cubeb_mixer_destroy)> input_mixer = { nullptr, cubeb_mixer_destroy };
/* A buffer for up/down mixing multi-channel audio output. */
std::vector<BYTE> mix_buffer;
/* WASAPI input works in "packets". We re-linearize the audio packets
* into this buffer before handing it to the resampler. */
std::unique_ptr<auto_array_wrapper> linear_input_buffer;
/* Bytes per sample. This multiplied by the number of channels is the number
* of bytes per frame. */
size_t bytes_per_sample = 0;
/* WAVEFORMATEXTENSIBLE sub-format: either PCM or float. */
GUID waveformatextensible_sub_format = GUID_NULL;
/* Stream volume. Set via stream_set_volume and used to reset volume on
device changes. */
float volume = 1.0;
/* True if the stream is draining. */
bool draining = false;
/* True when we've destroyed the stream. This pointer is leaked on stream
* destruction if we could not join the thread. */
std::atomic<std::atomic<bool>*> emergency_bailout;
};
class wasapi_endpoint_notification_client : public IMMNotificationClient
{
public:
/* The implementation of MSCOM was copied from MSDN. */
ULONG STDMETHODCALLTYPE
AddRef()
{
return InterlockedIncrement(&ref_count);
}
ULONG STDMETHODCALLTYPE
Release()
{
ULONG ulRef = InterlockedDecrement(&ref_count);
if (0 == ulRef) {
delete this;
}
return ulRef;
}
HRESULT STDMETHODCALLTYPE
QueryInterface(REFIID riid, VOID **ppvInterface)
{
if (__uuidof(IUnknown) == riid) {
AddRef();
*ppvInterface = (IUnknown*)this;
} else if (__uuidof(IMMNotificationClient) == riid) {
AddRef();
*ppvInterface = (IMMNotificationClient*)this;
} else {
*ppvInterface = NULL;
return E_NOINTERFACE;
}
return S_OK;
}
wasapi_endpoint_notification_client(HANDLE event)
: ref_count(1)
, reconfigure_event(event)
{ }
virtual ~wasapi_endpoint_notification_client()
{ }
HRESULT STDMETHODCALLTYPE
OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR device_id)
{
LOG("Audio device default changed.");
/* we only support a single stream type for now. */
if (flow != eRender && role != eConsole) {
return S_OK;
}
BOOL ok = SetEvent(reconfigure_event);
if (!ok) {
LOG("SetEvent on reconfigure_event failed: %lx", GetLastError());
}
return S_OK;
}
/* The remaining methods are not implemented, they simply log when called (if
log is enabled), for debugging. */
HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR device_id)
{
LOG("Audio device added.");
return S_OK;
};
HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR device_id)
{
LOG("Audio device removed.");
return S_OK;
}
HRESULT STDMETHODCALLTYPE
OnDeviceStateChanged(LPCWSTR device_id, DWORD new_state)
{
LOG("Audio device state changed.");
return S_OK;
}
HRESULT STDMETHODCALLTYPE
OnPropertyValueChanged(LPCWSTR device_id, const PROPERTYKEY key)
{
LOG("Audio device property value changed.");
return S_OK;
}
private:
/* refcount for this instance, necessary to implement MSCOM semantics. */
LONG ref_count;
HANDLE reconfigure_event;
};
namespace {
char const *
intern_device_id(cubeb * ctx, wchar_t const * id)
{
XASSERT(id);
char const * tmp = wstr_to_utf8(id);
if (!tmp)
return nullptr;
char const * interned = cubeb_strings_intern(ctx->device_ids, tmp);
free((void *) tmp);
return interned;
}
bool has_input(cubeb_stream * stm)
{
return stm->input_stream_params.rate != 0;
}
bool has_output(cubeb_stream * stm)
{
return stm->output_stream_params.rate != 0;
}
double stream_to_mix_samplerate_ratio(cubeb_stream_params & stream, cubeb_stream_params & mixer)
{
return double(stream.rate) / mixer.rate;
}
/* Convert the channel layout into the corresponding KSAUDIO_CHANNEL_CONFIG.
See more: https://msdn.microsoft.com/en-us/library/windows/hardware/ff537083(v=vs.85).aspx */
cubeb_channel_layout
mask_to_channel_layout(WAVEFORMATEX const * fmt)
{
cubeb_channel_layout mask = 0;
if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
WAVEFORMATEXTENSIBLE const * ext = reinterpret_cast<WAVEFORMATEXTENSIBLE const *>(fmt);
mask = ext->dwChannelMask;
} else if (fmt->wFormatTag == WAVE_FORMAT_PCM ||
fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
if (fmt->nChannels == 1) {
mask = CHANNEL_FRONT_CENTER;
} else if (fmt->nChannels == 2) {
mask = CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT;
}
}
return mask;
}
uint32_t
get_rate(cubeb_stream * stm)
{
return has_input(stm) ? stm->input_stream_params.rate
: stm->output_stream_params.rate;
}
uint32_t
hns_to_frames(uint32_t rate, REFERENCE_TIME hns)
{
return std::ceil(hns / 10000000.0 * rate);
}
uint32_t
hns_to_frames(cubeb_stream * stm, REFERENCE_TIME hns)
{
return hns_to_frames(get_rate(stm), hns);
}
REFERENCE_TIME
frames_to_hns(cubeb_stream * stm, uint32_t frames)
{
return std::ceil(frames * 10000000.0 / get_rate(stm));
}
/* This returns the size of a frame in the stream, before the eventual upmix
occurs. */
static size_t
frames_to_bytes_before_mix(cubeb_stream * stm, size_t frames)
{
// This is called only when we has a output client.
XASSERT(has_output(stm));
return stm->output_stream_params.channels * stm->bytes_per_sample * frames;
}
/* This function handles the processing of the input and output audio,
* converting it to rate and channel layout specified at initialization.
* It then calls the data callback, via the resampler. */
long
refill(cubeb_stream * stm, void * input_buffer, long input_frames_count,
void * output_buffer, long output_frames_needed)
{
XASSERT(!stm->draining);
/* If we need to upmix after resampling, resample into the mix buffer to
avoid a copy. Avoid exposing output if it is a dummy stream. */
void * dest = nullptr;
if (has_output(stm) && !stm->has_dummy_output) {
if (stm->output_mixer) {
dest = stm->mix_buffer.data();
} else {
dest = output_buffer;
}
}
long out_frames = cubeb_resampler_fill(stm->resampler.get(),
input_buffer,
&input_frames_count,
dest,
output_frames_needed);
/* TODO: Report out_frames < 0 as an error via the API. */
XASSERT(out_frames >= 0);
{
auto_lock lock(stm->stream_reset_lock);
stm->frames_written += out_frames;
}
/* Go in draining mode if we got fewer frames than requested. If the stream
has no output we still expect the callback to return number of frames read
from input, otherwise we stop. */
if ((out_frames < output_frames_needed) ||
(!has_output(stm) && out_frames < input_frames_count)) {
LOG("start draining.");
stm->draining = true;
}
/* If this is not true, there will be glitches.
It is alright to have produced less frames if we are draining, though. */
XASSERT(out_frames == output_frames_needed || stm->draining || !has_output(stm) || stm->has_dummy_output);
// We don't bother mixing dummy output as it will be silenced, otherwise mix output if needed
if (!stm->has_dummy_output && has_output(stm) && stm->output_mixer) {
XASSERT(dest == stm->mix_buffer.data());
size_t dest_size =
out_frames * stm->output_stream_params.channels * stm->bytes_per_sample;
XASSERT(dest_size <= stm->mix_buffer.size());
size_t output_buffer_size =
out_frames * stm->output_mix_params.channels * stm->bytes_per_sample;
int ret = cubeb_mixer_mix(stm->output_mixer.get(),
out_frames,
dest,
dest_size,
output_buffer,
output_buffer_size);
if (ret < 0) {
LOG("Error remixing content (%d)", ret);
}
}
return out_frames;
}
int wasapi_stream_reset_default_device(cubeb_stream * stm);
/* Helper for making get_input_buffer work in exclusive mode */
HRESULT get_next_packet_size(cubeb_stream * stm, PUINT32 next)
{
if (stm->input_stream_params.prefs & CUBEB_STREAM_PREF_EXCLUSIVE) {
*next = stm->input_buffer_frame_count;
return S_OK;
} else {
return stm->capture_client->GetNextPacketSize(next);
}
}
/* This helper grabs all the frames available from a capture client, put them in
* linear_input_buffer. linear_input_buffer should be cleared before the
* callback exits. */
bool get_input_buffer(cubeb_stream * stm)
{
XASSERT(has_input(stm));
HRESULT hr;
BYTE * input_packet = NULL;
DWORD flags;
UINT64 dev_pos;
UINT32 next;
/* Get input packets until we have captured enough frames, and put them in a
* contiguous buffer. */
uint32_t offset = 0;
// If the input stream is event driven we should only ever expect to read a
// single packet each time. However, if we're pulling from the stream we may
// need to grab multiple packets worth of frames that have accumulated (so
// need a loop).
for (hr = get_next_packet_size(stm, &next);
next > 0;
hr = get_next_packet_size(stm, &next)) {
if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
// Application can recover from this error. More info
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd316605(v=vs.85).aspx
LOG("Device invalidated error, reset default device");
wasapi_stream_reset_default_device(stm);
return true;
}
if (FAILED(hr)) {
LOG("cannot get next packet size: %lx", hr);
return false;
}
UINT32 frames;
hr = stm->capture_client->GetBuffer(&input_packet,
&frames,
&flags,
&dev_pos,
NULL);
if (FAILED(hr)) {
LOG("GetBuffer failed for capture: %lx", hr);
return false;
}
XASSERT(frames == next);
UINT32 input_stream_samples = frames * stm->input_stream_params.channels;
// We do not explicitly handle the AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY
// flag. There a two primary (non exhaustive) scenarios we anticipate this
// flag being set in:
// - The first GetBuffer after Start has this flag undefined. In this
// case the flag may be set but is meaningless and can be ignored.
// - If a glitch is introduced into the input. This should not happen
// for event based inputs, and should be mitigated by using a dummy
// stream to drive input in the case of input only loopback. Without
// a dummy output, input only loopback would glitch on silence. However,
// the dummy input should push silence to the loopback and prevent
// discontinuities. See https://blogs.msdn.microsoft.com/matthew_van_eerde/2008/12/16/sample-wasapi-loopback-capture-record-what-you-hear/
// As the first scenario can be ignored, and we anticipate the second
// scenario is mitigated, we ignore the flag.
// For more info: https://msdn.microsoft.com/en-us/library/windows/desktop/dd370859(v=vs.85).aspx,
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd371458(v=vs.85).aspx
if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
LOG("insert silence: ps=%u", frames);
stm->linear_input_buffer->push_silence(input_stream_samples);
} else {
if (stm->input_mixer) {
bool ok = stm->linear_input_buffer->reserve(
stm->linear_input_buffer->length() + input_stream_samples);
XASSERT(ok);
size_t input_packet_size =
frames * stm->input_mix_params.channels *
cubeb_sample_size(stm->input_mix_params.format);
size_t linear_input_buffer_size =
input_stream_samples *
cubeb_sample_size(stm->input_stream_params.format);
cubeb_mixer_mix(stm->input_mixer.get(),
frames,
input_packet,
input_packet_size,
stm->linear_input_buffer->end(),
linear_input_buffer_size);
stm->linear_input_buffer->set_length(
stm->linear_input_buffer->length() + input_stream_samples);
} else {
stm->linear_input_buffer->push(
input_packet, input_stream_samples);
}
}
hr = stm->capture_client->ReleaseBuffer(frames);
if (FAILED(hr)) {
LOG("FAILED to release intput buffer");
return false;
}
offset += input_stream_samples;
if (stm->input_stream_params.prefs & CUBEB_STREAM_PREF_EXCLUSIVE)
break;
}
XASSERT(stm->linear_input_buffer->length() >= offset);
return true;
}
/* Get an output buffer from the render_client. It has to be released before
* exiting the callback. */
bool get_output_buffer(cubeb_stream * stm, void *& buffer, size_t & frame_count)
{
UINT32 padding_out;
HRESULT hr;
XASSERT(has_output(stm));
hr = stm->output_client->GetCurrentPadding(&padding_out);
if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
// Application can recover from this error. More info
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd316605(v=vs.85).aspx
LOG("Device invalidated error, reset default device");
wasapi_stream_reset_default_device(stm);
return true;
}
if (FAILED(hr)) {
LOG("Failed to get padding: %lx", hr);
return false;
}
XASSERT(padding_out <= stm->output_buffer_frame_count);
if (stm->draining) {
if (padding_out == 0) {
LOG("Draining finished.");
stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_DRAINED);
return false;
}
LOG("Draining.");
return true;
}
frame_count = stm->output_buffer_frame_count - padding_out;
BYTE * output_buffer;
hr = stm->render_client->GetBuffer(frame_count, &output_buffer);
if (FAILED(hr)) {
LOG("cannot get render buffer");
return false;
}
buffer = output_buffer;
return true;
}
/**
* This function gets input data from a input device, and pass it along with an
* output buffer to the resamplers. */
bool
refill_callback_duplex(cubeb_stream * stm)
{
HRESULT hr;
void * output_buffer = nullptr;
size_t output_frames = 0;
size_t input_frames;
bool rv;
XASSERT(has_input(stm) && has_output(stm));
rv = get_input_buffer(stm);
if (!rv) {
return rv;
}
input_frames = stm->linear_input_buffer->length() / stm->input_stream_params.channels;
if (!input_frames) {
return true;
}
rv = get_output_buffer(stm, output_buffer, output_frames);
if (!rv) {
hr = stm->render_client->ReleaseBuffer(output_frames, 0);
return rv;
}
/* This can only happen when debugging, and having breakpoints set in the
* callback in a way that it makes the stream underrun. */
if (output_frames == 0) {
return true;
}
/* Wait for draining is not important on duplex. */
if (stm->draining) {
return false;
}
if (stm->has_dummy_output) {
ALOGV("Duplex callback (dummy output): input frames: %Iu, output frames: %Iu",
input_frames, output_frames);
// We don't want to expose the dummy output to the callback so don't pass
// the output buffer (it will be released later with silence in it)
refill(stm,
stm->linear_input_buffer->data(),
input_frames,
nullptr,
0);
} else {
ALOGV("Duplex callback: input frames: %Iu, output frames: %Iu",
input_frames, output_frames);
refill(stm,
stm->linear_input_buffer->data(),
input_frames,
output_buffer,
output_frames);
}
stm->linear_input_buffer->clear();
if (stm->has_dummy_output) {
// If output is a dummy output, make sure it's silent
hr = stm->render_client->ReleaseBuffer(output_frames, AUDCLNT_BUFFERFLAGS_SILENT);
} else {
hr = stm->render_client->ReleaseBuffer(output_frames, 0);
}
if (FAILED(hr)) {
LOG("failed to release buffer: %lx", hr);
return false;
}
return true;
}
bool
refill_callback_input(cubeb_stream * stm)
{
bool rv;
size_t input_frames;
XASSERT(has_input(stm) && !has_output(stm));
rv = get_input_buffer(stm);
if (!rv) {
return rv;
}
input_frames = stm->linear_input_buffer->length() / stm->input_stream_params.channels;
if (!input_frames) {
return true;
}
ALOGV("Input callback: input frames: %Iu", input_frames);
long read = refill(stm,
stm->linear_input_buffer->data(),
input_frames,
nullptr,
0);
XASSERT(read >= 0);
stm->linear_input_buffer->clear();
return !stm->draining;
}
bool
refill_callback_output(cubeb_stream * stm)
{
bool rv;
HRESULT hr;
void * output_buffer = nullptr;
size_t output_frames = 0;
XASSERT(!has_input(stm) && has_output(stm));
rv = get_output_buffer(stm, output_buffer, output_frames);
if (!rv) {
return rv;
}
if (stm->draining || output_frames == 0) {
return true;
}
long got = refill(stm,
nullptr,
0,
output_buffer,
output_frames);
ALOGV("Output callback: output frames requested: %Iu, got %ld",
output_frames, got);
XASSERT(got >= 0);
XASSERT(size_t(got) == output_frames || stm->draining);
hr = stm->render_client->ReleaseBuffer(got, 0);
if (FAILED(hr)) {
LOG("failed to release buffer: %lx", hr);
return false;
}
return size_t(got) == output_frames || stm->draining;
}
static unsigned int __stdcall
wasapi_stream_render_loop(LPVOID stream)
{
cubeb_stream * stm = static_cast<cubeb_stream *>(stream);
std::atomic<bool> * emergency_bailout = stm->emergency_bailout;
bool is_playing = true;
HANDLE wait_array[4] = {
stm->shutdown_event,
stm->reconfigure_event,
stm->refill_event,
stm->input_available_event
};
HANDLE mmcss_handle = NULL;
HRESULT hr = 0;
DWORD mmcss_task_index = 0;
struct auto_com {
auto_com() {
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
XASSERT(SUCCEEDED(hr));
}
~auto_com() {
CoUninitialize();
}
} com;
/* We could consider using "Pro Audio" here for WebAudio and
maybe WebRTC. */
mmcss_handle = AvSetMmThreadCharacteristicsA("Audio", &mmcss_task_index);
if (!mmcss_handle) {
/* This is not fatal, but we might glitch under heavy load. */
LOG("Unable to use mmcss to bump the render thread priority: %lx", GetLastError());
}
// This has already been nulled out, simply exit.
if (!emergency_bailout) {
is_playing = false;
}
/* WaitForMultipleObjects timeout can trigger in cases where we don't want to
treat it as a timeout, such as across a system sleep/wake cycle. Trigger
the timeout error handling only when the timeout_limit is reached, which is
reset on each successful loop. */
unsigned timeout_count = 0;
const unsigned timeout_limit = 5;
while (is_playing) {
// We want to check the emergency bailout variable before a
// and after the WaitForMultipleObject, because the handles WaitForMultipleObjects
// is going to wait on might have been closed already.
if (*emergency_bailout) {
delete emergency_bailout;
return 0;
}
DWORD waitResult = WaitForMultipleObjects(ARRAY_LENGTH(wait_array),
wait_array,
FALSE,
1000);
if (*emergency_bailout) {
delete emergency_bailout;
return 0;
}
if (waitResult != WAIT_TIMEOUT) {
timeout_count = 0;
}
switch (waitResult) {
case WAIT_OBJECT_0: { /* shutdown */
is_playing = false;
/* We don't check if the drain is actually finished here, we just want to
shutdown. */
if (stm->draining) {
stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_DRAINED);
}
continue;
}
case WAIT_OBJECT_0 + 1: { /* reconfigure */
XASSERT(stm->output_client || stm->input_client);
LOG("Reconfiguring the stream");
/* Close the stream */
if (stm->output_client) {
stm->output_client->Stop();
LOG("Output stopped.");
}
if (stm->input_client) {
stm->input_client->Stop();
LOG("Input stopped.");
}
{
auto_lock lock(stm->stream_reset_lock);
close_wasapi_stream(stm);
LOG("Stream closed.");
/* Reopen a stream and start it immediately. This will automatically pick the
new default device for this role. */
int r = setup_wasapi_stream(stm);
if (r != CUBEB_OK) {
LOG("Error setting up the stream during reconfigure.");
/* Don't destroy the stream here, since we expect the caller to do
so after the error has propagated via the state callback. */
is_playing = false;
hr = E_FAIL;
continue;
}
LOG("Stream setup successfuly.");
}
XASSERT(stm->output_client || stm->input_client);
if (stm->output_client) {
hr = stm->output_client->Start();
if (FAILED(hr)) {
LOG("Error starting output after reconfigure, error: %lx", hr);
is_playing = false;
continue;
}
LOG("Output started after reconfigure.");
}
if (stm->input_client) {
hr = stm->input_client->Start();
if (FAILED(hr)) {
LOG("Error starting input after reconfiguring, error: %lx", hr);
is_playing = false;
continue;
}
LOG("Input started after reconfigure.");
}
break;
}
case WAIT_OBJECT_0 + 2: /* refill */
XASSERT((has_input(stm) && has_output(stm)) ||
(!has_input(stm) && has_output(stm)));
is_playing = stm->refill_callback(stm);
break;
case WAIT_OBJECT_0 + 3: /* input available */
if (has_input(stm) && has_output(stm)) { continue; }
is_playing = stm->refill_callback(stm);
break;
case WAIT_TIMEOUT:
XASSERT(stm->shutdown_event == wait_array[0]);
if (++timeout_count >= timeout_limit) {
LOG("Render loop reached the timeout limit.");
is_playing = false;
hr = E_FAIL;
}
break;
default:
LOG("case %lu not handled in render loop.", waitResult);
abort();
}
}
if (FAILED(hr)) {
stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
}
if (mmcss_handle) {
AvRevertMmThreadCharacteristics(mmcss_handle);
}
return 0;