Debian Codegraph @

third_party/rust/cubeb-sys/libcubeb/src/cubeb_wasapi.cpp

raw
1 /*
2 * Copyright © 2013 Mozilla Foundation
3 *
4 * This program is made available under an ISC-style license. See the
5 * accompanying file LICENSE for details.
6 */
7 #define _WIN32_WINNT 0x0603
8 #define NOMINMAX
9
10 #include <algorithm>
11 #include <atomic>
12 #include <audioclient.h>
13 #include <avrt.h>
14 #include <cmath>
15 #include <devicetopology.h>
16 #include <initguid.h>
17 #include <limits>
18 #include <memory>
19 #include <mmdeviceapi.h>
20 #include <process.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <vector>
25 #include <windef.h>
26 #include <windows.h>
27 /* clang-format off */
28 /* These need to be included after windows.h */
29 #include <mmsystem.h>
30 /* clang-format on */
31
32 #include "cubeb-internal.h"
33 #include "cubeb/cubeb.h"
34 #include "cubeb_mixer.h"
35 #include "cubeb_resampler.h"
36 #include "cubeb_strings.h"
37 #include "cubeb_tracing.h"
38 #include "cubeb_utils.h"
39
40 // Windows 10 exposes the IAudioClient3 interface to create low-latency streams.
41 // Copy the interface definition from audioclient.h here to make the code
42 // simpler and so that we can still access IAudioClient3 via COM if cubeb was
43 // compiled against an older SDK.
44 #ifndef __IAudioClient3_INTERFACE_DEFINED__
45 #define __IAudioClient3_INTERFACE_DEFINED__
46 MIDL_INTERFACE("7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42")
47 IAudioClient3 : public IAudioClient
48 {
49 public:
50 virtual HRESULT STDMETHODCALLTYPE GetSharedModeEnginePeriod(
51 /* [annotation][in] */
52 _In_ const WAVEFORMATEX * pFormat,
53 /* [annotation][out] */
54 _Out_ UINT32 * pDefaultPeriodInFrames,
55 /* [annotation][out] */
56 _Out_ UINT32 * pFundamentalPeriodInFrames,
57 /* [annotation][out] */
58 _Out_ UINT32 * pMinPeriodInFrames,
59 /* [annotation][out] */
60 _Out_ UINT32 * pMaxPeriodInFrames) = 0;
61
62 virtual HRESULT STDMETHODCALLTYPE GetCurrentSharedModeEnginePeriod(
63 /* [unique][annotation][out] */
64 _Out_ WAVEFORMATEX * *ppFormat,
65 /* [annotation][out] */
66 _Out_ UINT32 * pCurrentPeriodInFrames) = 0;
67
68 virtual HRESULT STDMETHODCALLTYPE InitializeSharedAudioStream(
69 /* [annotation][in] */
70 _In_ DWORD StreamFlags,
71 /* [annotation][in] */
72 _In_ UINT32 PeriodInFrames,
73 /* [annotation][in] */
74 _In_ const WAVEFORMATEX * pFormat,
75 /* [annotation][in] */
76 _In_opt_ LPCGUID AudioSessionGuid) = 0;
77 };
78 #ifdef __CRT_UUID_DECL
79 // Required for MinGW
80 __CRT_UUID_DECL(IAudioClient3, 0x7ED4EE07, 0x8E67, 0x4CD4, 0x8C, 0x1A, 0x2B,
81 0x7A, 0x59, 0x87, 0xAD, 0x42)
82 #endif
83 #endif
84 // Copied from audioclient.h in the Windows 10 SDK
85 #ifndef AUDCLNT_E_ENGINE_PERIODICITY_LOCKED
86 #define AUDCLNT_E_ENGINE_PERIODICITY_LOCKED AUDCLNT_ERR(0x028)
87 #endif
88
89 #ifndef PKEY_Device_FriendlyName
90 DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,
91 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0,
92 14); // DEVPROP_TYPE_STRING
93 #endif
94 #ifndef PKEY_Device_InstanceId
95 DEFINE_PROPERTYKEY(PKEY_Device_InstanceId, 0x78c34fc8, 0x104a, 0x4aca, 0x9e,
96 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57,
97 0x00000100); // VT_LPWSTR
98 #endif
99
100 namespace {
101
102 const int64_t LATENCY_NOT_AVAILABLE_YET = -1;
103
104 const DWORD DEVICE_CHANGE_DEBOUNCE_MS = 250;
105
106 struct com_heap_ptr_deleter {
107 void operator()(void * ptr) const noexcept { CoTaskMemFree(ptr); }
108 };
109
110 template <typename T>
111 using com_heap_ptr = std::unique_ptr<T, com_heap_ptr_deleter>;
112
113 template <typename T, size_t N>
114 constexpr size_t
115 ARRAY_LENGTH(T (&)[N])
116 {
117 return N;
118 }
119
120 template <typename T> class no_addref_release : public T {
121 ULONG STDMETHODCALLTYPE AddRef() = 0;
122 ULONG STDMETHODCALLTYPE Release() = 0;
123 };
124
125 template <typename T> class com_ptr {
126 public:
127 com_ptr() noexcept = default;
128
129 com_ptr(com_ptr const & other) noexcept = delete;
130 com_ptr & operator=(com_ptr const & other) noexcept = delete;
131 T ** operator&() const noexcept = delete;
132
133 ~com_ptr() noexcept { release(); }
134
135 com_ptr(com_ptr && other) noexcept : ptr(other.ptr) { other.ptr = nullptr; }
136
137 com_ptr & operator=(com_ptr && other) noexcept
138 {
139 if (ptr != other.ptr) {
140 release();
141 ptr = other.ptr;
142 other.ptr = nullptr;
143 }
144 return *this;
145 }
146
147 explicit operator bool() const noexcept { return nullptr != ptr; }
148
149 no_addref_release<T> * operator->() const noexcept
150 {
151 return static_cast<no_addref_release<T> *>(ptr);
152 }
153
154 T * get() const noexcept { return ptr; }
155
156 T ** receive() noexcept
157 {
158 XASSERT(ptr == nullptr);
159 return &ptr;
160 }
161
162 void ** receive_vpp() noexcept
163 {
164 return reinterpret_cast<void **>(receive());
165 }
166
167 com_ptr & operator=(std::nullptr_t) noexcept
168 {
169 release();
170 return *this;
171 }
172
173 void reset(T * p = nullptr) noexcept
174 {
175 release();
176 ptr = p;
177 }
178
179 private:
180 void release() noexcept
181 {
182 T * temp = ptr;
183
184 if (temp) {
185 ptr = nullptr;
186 temp->Release();
187 }
188 }
189
190 T * ptr = nullptr;
191 };
192
193 LONG
194 wasapi_stream_add_ref(cubeb_stream * stm);
195 LONG
196 wasapi_stream_release(cubeb_stream * stm);
197
198 struct auto_stream_ref {
199 auto_stream_ref(cubeb_stream * stm_) : stm(stm_)
200 {
201 wasapi_stream_add_ref(stm);
202 }
203 ~auto_stream_ref() { wasapi_stream_release(stm); }
204 cubeb_stream * stm;
205 };
206
207 using set_mm_thread_characteristics_function =
208 decltype(&AvSetMmThreadCharacteristicsW);
209 using revert_mm_thread_characteristics_function =
210 decltype(&AvRevertMmThreadCharacteristics);
211
212 extern cubeb_ops const wasapi_ops;
213
214 static com_heap_ptr<wchar_t>
215 wasapi_get_default_device_id(EDataFlow flow, ERole role,
216 IMMDeviceEnumerator * enumerator);
217
218 struct wasapi_default_devices {
219 wasapi_default_devices(IMMDeviceEnumerator * enumerator)
220 : render_console_id(
221 wasapi_get_default_device_id(eRender, eConsole, enumerator)),
222 render_comms_id(
223 wasapi_get_default_device_id(eRender, eCommunications, enumerator)),
224 capture_console_id(
225 wasapi_get_default_device_id(eCapture, eConsole, enumerator)),
226 capture_comms_id(
227 wasapi_get_default_device_id(eCapture, eCommunications, enumerator))
228 {
229 }
230
231 bool is_default(EDataFlow flow, ERole role, wchar_t const * id)
232 {
233 wchar_t const * default_id = nullptr;
234 if (flow == eRender && role == eConsole) {
235 default_id = this->render_console_id.get();
236 } else if (flow == eRender && role == eCommunications) {
237 default_id = this->render_comms_id.get();
238 } else if (flow == eCapture && role == eConsole) {
239 default_id = this->capture_console_id.get();
240 } else if (flow == eCapture && role == eCommunications) {
241 default_id = this->capture_comms_id.get();
242 }
243
244 return default_id && wcscmp(id, default_id) == 0;
245 }
246
247 private:
248 com_heap_ptr<wchar_t> render_console_id;
249 com_heap_ptr<wchar_t> render_comms_id;
250 com_heap_ptr<wchar_t> capture_console_id;
251 com_heap_ptr<wchar_t> capture_comms_id;
252 };
253
254 struct AutoRegisterThread {
255 AutoRegisterThread(const char * name) { CUBEB_REGISTER_THREAD(name); }
256 ~AutoRegisterThread() { CUBEB_UNREGISTER_THREAD(); }
257 };
258
259 int
260 wasapi_stream_stop(cubeb_stream * stm);
261 int
262 wasapi_stream_start(cubeb_stream * stm);
263 void
264 close_wasapi_stream(cubeb_stream * stm);
265 int
266 setup_wasapi_stream(cubeb_stream * stm);
267 ERole
268 pref_to_role(cubeb_stream_prefs param);
269 int
270 wasapi_create_device(cubeb * ctx, cubeb_device_info & ret,
271 IMMDeviceEnumerator * enumerator, IMMDevice * dev,
272 wasapi_default_devices * defaults);
273 void
274 wasapi_destroy_device(cubeb_device_info * device_info);
275 static int
276 wasapi_enumerate_devices_internal(cubeb * context, cubeb_device_type type,
277 cubeb_device_collection * out,
278 DWORD state_mask);
279 static int
280 wasapi_device_collection_destroy(cubeb * ctx,
281 cubeb_device_collection * collection);
282 static char const *
283 wstr_to_utf8(wchar_t const * str);
284 static std::unique_ptr<wchar_t const[]>
285 utf8_to_wstr(char const * str);
286
287 } // namespace
288
289 class wasapi_collection_notification_client;
290 class monitor_device_notifications;
291
292 struct cubeb {
293 cubeb_ops const * ops = &wasapi_ops;
294 owned_critical_section lock;
295 cubeb_strings * device_ids;
296 /* Device enumerator to get notifications when the
297 device collection change. */
298 com_ptr<IMMDeviceEnumerator> device_collection_enumerator;
299 com_ptr<wasapi_collection_notification_client> collection_notification_client;
300 /* Collection changed for input (capture) devices. */
301 cubeb_device_collection_changed_callback input_collection_changed_callback =
302 nullptr;
303 void * input_collection_changed_user_ptr = nullptr;
304 /* Collection changed for output (render) devices. */
305 cubeb_device_collection_changed_callback output_collection_changed_callback =
306 nullptr;
307 void * output_collection_changed_user_ptr = nullptr;
308 UINT64 performance_counter_frequency;
309 /* Library dynamically opened to increase the render thread priority, and
310 the two function pointers we need. */
311 HMODULE mmcss_module = nullptr;
312 set_mm_thread_characteristics_function set_mm_thread_characteristics =
313 nullptr;
314 revert_mm_thread_characteristics_function revert_mm_thread_characteristics =
315 nullptr;
316 };
317
318 class wasapi_endpoint_notification_client;
319
320 /* We have three possible callbacks we can use with a stream:
321 * - input only
322 * - output only
323 * - synchronized input and output
324 *
325 * Returns true when we should continue to play, false otherwise.
326 */
327 typedef bool (*wasapi_refill_callback)(cubeb_stream * stm);
328
329 struct cubeb_stream {
330 /* Note: Must match cubeb_stream layout in cubeb.c. */
331 cubeb * context = nullptr;
332 void * user_ptr = nullptr;
333 /**/
334
335 /* Mixer pameters. We need to convert the input stream to this
336 samplerate/channel layout, as WASAPI does not resample nor upmix
337 itself. */
338 cubeb_stream_params input_mix_params = {CUBEB_SAMPLE_FLOAT32NE, 0, 0,
339 CUBEB_LAYOUT_UNDEFINED,
340 CUBEB_STREAM_PREF_NONE};
341 cubeb_stream_params output_mix_params = {CUBEB_SAMPLE_FLOAT32NE, 0, 0,
342 CUBEB_LAYOUT_UNDEFINED,
343 CUBEB_STREAM_PREF_NONE};
344 /* Stream parameters. This is what the client requested,
345 * and what will be presented in the callback. */
346 cubeb_stream_params input_stream_params = {CUBEB_SAMPLE_FLOAT32NE, 0, 0,
347 CUBEB_LAYOUT_UNDEFINED,
348 CUBEB_STREAM_PREF_NONE};
349 cubeb_stream_params output_stream_params = {CUBEB_SAMPLE_FLOAT32NE, 0, 0,
350 CUBEB_LAYOUT_UNDEFINED,
351 CUBEB_STREAM_PREF_NONE};
352 /* A MMDevice role for this stream: either communication or console here. */
353 ERole role;
354 /* True if this stream will transport voice-data. */
355 bool voice;
356 /* True if the input device of this stream is using bluetooth handsfree. */
357 bool input_bluetooth_handsfree;
358 /* The input and output device, or NULL for default. */
359 std::unique_ptr<const wchar_t[]> input_device_id;
360 std::unique_ptr<const wchar_t[]> output_device_id;
361 com_ptr<IMMDevice> input_device;
362 com_ptr<IMMDevice> output_device;
363 /* The latency initially requested for this stream, in frames. */
364 unsigned latency = 0;
365 cubeb_state_callback state_callback = nullptr;
366 cubeb_data_callback data_callback = nullptr;
367 wasapi_refill_callback refill_callback = nullptr;
368 /* True when a loopback device is requested with no output device. In this
369 case a dummy output device is opened to drive the loopback, but should not
370 be exposed. */
371 bool has_dummy_output = false;
372 /* Lifetime considerations:
373 - client, render_client, audio_clock and audio_stream_volume are interface
374 pointer to the IAudioClient.
375 - The lifetime for device_enumerator and notification_client, resampler,
376 mix_buffer are the same as the cubeb_stream instance. */
377
378 /* Main handle on the WASAPI stream. */
379 com_ptr<IAudioClient> output_client;
380 /* Interface pointer to use the event-driven interface. */
381 com_ptr<IAudioRenderClient> render_client;
382 #ifdef CUBEB_WASAPI_USE_IAUDIOSTREAMVOLUME
383 /* Interface pointer to use the volume facilities. */
384 com_ptr<IAudioStreamVolume> audio_stream_volume;
385 #endif
386 /* Interface pointer to use the stream audio clock. */
387 com_ptr<IAudioClock> audio_clock;
388 /* Frames written to the stream since it was opened. Reset on device
389 change. Uses mix_params.rate. */
390 UINT64 frames_written = 0;
391 /* Frames written to the (logical) stream since it was first
392 created. Updated on device change. Uses stream_params.rate. */
393 UINT64 total_frames_written = 0;
394 /* Last valid reported stream position. Used to ensure the position
395 reported by stream_get_position increases monotonically. */
396 UINT64 prev_position = 0;
397 /* Device enumerator to be able to be notified when the default
398 device change. */
399 com_ptr<IMMDeviceEnumerator> device_enumerator;
400 /* Device notification client, to be able to be notified when the default
401 audio device changes and route the audio to the new default audio output
402 device */
403 com_ptr<wasapi_endpoint_notification_client> notification_client;
404 /* Main andle to the WASAPI capture stream. */
405 com_ptr<IAudioClient> input_client;
406 /* Interface to use the event driven capture interface */
407 com_ptr<IAudioCaptureClient> capture_client;
408 /* This event is set by the stream_destroy function, so the render loop can
409 exit properly. */
410 HANDLE shutdown_event = 0;
411 /* Set by OnDefaultDeviceChanged when a stream reconfiguration is required.
412 The reconfiguration is handled by the render loop thread. */
413 HANDLE reconfigure_event = 0;
414 /* This is set by WASAPI when we should refill the stream. */
415 HANDLE refill_event = 0;
416 /* This is set by WASAPI when we should read from the input stream. In
417 * practice, we read from the input stream in the output callback, so
418 * this is not used, but it is necessary to start getting input data. */
419 HANDLE input_available_event = 0;
420 /* Each cubeb_stream has its own thread. */
421 HANDLE thread = 0;
422 /* The lock protects all members that are touched by the render thread or
423 change during a device reset, including: audio_clock, audio_stream_volume,
424 client, frames_written, mix_params, total_frames_written, prev_position. */
425 owned_critical_section stream_reset_lock;
426 /* Maximum number of frames that can be passed down in a callback. */
427 uint32_t input_buffer_frame_count = 0;
428 /* Maximum number of frames that can be requested in a callback. */
429 uint32_t output_buffer_frame_count = 0;
430 /* Resampler instance. Resampling will only happen if necessary. */
431 std::unique_ptr<cubeb_resampler, decltype(&cubeb_resampler_destroy)>
432 resampler = {nullptr, cubeb_resampler_destroy};
433 /* Mixer interfaces */
434 std::unique_ptr<cubeb_mixer, decltype(&cubeb_mixer_destroy)> output_mixer = {
435 nullptr, cubeb_mixer_destroy};
436 std::unique_ptr<cubeb_mixer, decltype(&cubeb_mixer_destroy)> input_mixer = {
437 nullptr, cubeb_mixer_destroy};
438 /* A buffer for up/down mixing multi-channel audio output. */
439 std::vector<BYTE> mix_buffer;
440 /* WASAPI input works in "packets". We re-linearize the audio packets
441 * into this buffer before handing it to the resampler. */
442 std::unique_ptr<auto_array_wrapper> linear_input_buffer;
443 /* Bytes per sample. This multiplied by the number of channels is the number
444 * of bytes per frame. */
445 size_t bytes_per_sample = 0;
446 /* WAVEFORMATEXTENSIBLE sub-format: either PCM or float. */
447 GUID waveformatextensible_sub_format = GUID_NULL;
448 /* Stream volume. Set via stream_set_volume and used to reset volume on
449 device changes. */
450 float volume = 1.0;
451 /* True if the stream is draining. */
452 bool draining = false;
453 /* This needs an active audio input stream to be known, and is updated in the
454 * first audio input callback. */
455 std::atomic<int64_t> input_latency_hns{LATENCY_NOT_AVAILABLE_YET};
456 /* Those attributes count the number of frames requested (resp. received) by
457 the OS, to be able to detect drifts. This is only used for logging for now. */
458 size_t total_input_frames = 0;
459 size_t total_output_frames = 0;
460 /* This is set by the render loop thread once it has obtained a reference to
461 * COM and this stream object. */
462 HANDLE thread_ready_event = 0;
463 /* Keep a ref count on this stream object. After both stream_destroy has been
464 * called and the render loop thread has exited, destroy this stream object.
465 */
466 LONG ref_count = 0;
467
468 /* True if the stream is active, false if inactive. */
469 bool active = false;
470 };
471
472 class monitor_device_notifications {
473 public:
474 monitor_device_notifications(cubeb * context) : cubeb_context(context)
475 {
476 create_thread();
477 }
478
479 ~monitor_device_notifications()
480 {
481 SetEvent(begin_shutdown);
482 WaitForSingleObject(shutdown_complete, INFINITE);
483 CloseHandle(thread);
484
485 CloseHandle(input_changed);
486 CloseHandle(output_changed);
487 CloseHandle(begin_shutdown);
488 CloseHandle(shutdown_complete);
489 }
490
491 void notify(EDataFlow flow)
492 {
493 XASSERT(cubeb_context);
494 if (flow == eCapture && cubeb_context->input_collection_changed_callback) {
495 bool res = SetEvent(input_changed);
496 if (!res) {
497 LOG("Failed to set input changed event");
498 }
499 return;
500 }
501 if (flow == eRender && cubeb_context->output_collection_changed_callback) {
502 bool res = SetEvent(output_changed);
503 if (!res) {
504 LOG("Failed to set output changed event");
505 }
506 }
507 }
508
509 private:
510 static unsigned int __stdcall thread_proc(LPVOID args)
511 {
512 AutoRegisterThread raii("WASAPI device notification thread");
513 XASSERT(args);
514 auto mdn = static_cast<monitor_device_notifications *>(args);
515 mdn->notification_thread_loop();
516 SetEvent(mdn->shutdown_complete);
517 return 0;
518 }
519
520 void notification_thread_loop()
521 {
522 struct auto_com {
523 auto_com()
524 {
525 HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
526 XASSERT(SUCCEEDED(hr));
527 }
528 ~auto_com() { CoUninitialize(); }
529 } com;
530
531 HANDLE wait_array[3] = {
532 input_changed,
533 output_changed,
534 begin_shutdown,
535 };
536
537 while (true) {
538 Sleep(200);
539
540 DWORD wait_result = WaitForMultipleObjects(ARRAY_LENGTH(wait_array),
541 wait_array, FALSE, INFINITE);
542 if (wait_result == WAIT_OBJECT_0) { // input changed
543 cubeb_context->input_collection_changed_callback(
544 cubeb_context, cubeb_context->input_collection_changed_user_ptr);
545 } else if (wait_result == WAIT_OBJECT_0 + 1) { // output changed
546 cubeb_context->output_collection_changed_callback(
547 cubeb_context, cubeb_context->output_collection_changed_user_ptr);
548 } else if (wait_result == WAIT_OBJECT_0 + 2) { // shutdown
549 break;
550 } else {
551 LOG("Unexpected result %lu", wait_result);
552 }
553 } // loop
554 }
555
556 void create_thread()
557 {
558 output_changed = CreateEvent(nullptr, 0, 0, nullptr);
559 if (!output_changed) {
560 LOG("Failed to create output changed event.");
561 return;
562 }
563
564 input_changed = CreateEvent(nullptr, 0, 0, nullptr);
565 if (!input_changed) {
566 LOG("Failed to create input changed event.");
567 return;
568 }
569
570 begin_shutdown = CreateEvent(nullptr, 0, 0, nullptr);
571 if (!begin_shutdown) {
572 LOG("Failed to create begin_shutdown event.");
573 return;
574 }
575
576 shutdown_complete = CreateEvent(nullptr, 0, 0, nullptr);
577 if (!shutdown_complete) {
578 LOG("Failed to create shutdown_complete event.");
579 return;
580 }
581
582 thread = (HANDLE)_beginthreadex(nullptr, 256 * 1024, thread_proc, this,
583 STACK_SIZE_PARAM_IS_A_RESERVATION, nullptr);
584 if (!thread) {
585 LOG("Failed to create thread.");
586 return;
587 }
588 }
589
590 HANDLE thread = INVALID_HANDLE_VALUE;
591 HANDLE output_changed = INVALID_HANDLE_VALUE;
592 HANDLE input_changed = INVALID_HANDLE_VALUE;
593 HANDLE begin_shutdown = INVALID_HANDLE_VALUE;
594 HANDLE shutdown_complete = INVALID_HANDLE_VALUE;
595
596 cubeb * cubeb_context = nullptr;
597 };
598
599 class wasapi_collection_notification_client : public IMMNotificationClient {
600 public:
601 /* The implementation of MSCOM was copied from MSDN. */
602 ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&ref_count); }
603
604 ULONG STDMETHODCALLTYPE Release()
605 {
606 ULONG ulRef = InterlockedDecrement(&ref_count);
607 if (0 == ulRef) {
608 delete this;
609 }
610 return ulRef;
611 }
612
613 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID ** ppvInterface)
614 {
615 if (__uuidof(IUnknown) == riid) {
616 AddRef();
617 *ppvInterface = (IUnknown *)this;
618 } else if (__uuidof(IMMNotificationClient) == riid) {
619 AddRef();
620 *ppvInterface = (IMMNotificationClient *)this;
621 } else {
622 *ppvInterface = NULL;
623 return E_NOINTERFACE;
624 }
625 return S_OK;
626 }
627
628 wasapi_collection_notification_client(cubeb * context)
629 : ref_count(1), cubeb_context(context), monitor_notifications(context)
630 {
631 XASSERT(cubeb_context);
632 }
633
634 virtual ~wasapi_collection_notification_client() {}
635
636 HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role,
637 LPCWSTR device_id)
638 {
639 LOG("collection: Audio device default changed, id = %S.", device_id);
640 return S_OK;
641 }
642
643 /* The remaining methods are not implemented, they simply log when called (if
644 log is enabled), for debugging. */
645 HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR device_id)
646 {
647 LOG("collection: Audio device added.");
648 return S_OK;
649 };
650
651 HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR device_id)
652 {
653 LOG("collection: Audio device removed.");
654 return S_OK;
655 }
656
657 HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR device_id,
658 DWORD new_state)
659 {
660 XASSERT(cubeb_context->output_collection_changed_callback ||
661 cubeb_context->input_collection_changed_callback);
662 LOG("collection: Audio device state changed, id = %S, state = %lu.",
663 device_id, new_state);
664 EDataFlow flow;
665 HRESULT hr = GetDataFlow(device_id, &flow);
666 if (FAILED(hr)) {
667 return hr;
668 }
669 monitor_notifications.notify(flow);
670 return S_OK;
671 }
672
673 HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR device_id,
674 const PROPERTYKEY key)
675 {
676 // Audio device property value changed.
677 return S_OK;
678 }
679
680 private:
681 HRESULT GetDataFlow(LPCWSTR device_id, EDataFlow * flow)
682 {
683 com_ptr<IMMDevice> device;
684 com_ptr<IMMEndpoint> endpoint;
685
686 HRESULT hr = cubeb_context->device_collection_enumerator->GetDevice(
687 device_id, device.receive());
688 if (FAILED(hr)) {
689 LOG("collection: Could not get device: %lx", hr);
690 return hr;
691 }
692
693 hr = device->QueryInterface(IID_PPV_ARGS(endpoint.receive()));
694 if (FAILED(hr)) {
695 LOG("collection: Could not get endpoint: %lx", hr);
696 return hr;
697 }
698
699 return endpoint->GetDataFlow(flow);
700 }
701
702 /* refcount for this instance, necessary to implement MSCOM semantics. */
703 LONG ref_count;
704
705 cubeb * cubeb_context = nullptr;
706 monitor_device_notifications monitor_notifications;
707 };
708
709 class wasapi_endpoint_notification_client : public IMMNotificationClient {
710 public:
711 /* The implementation of MSCOM was copied from MSDN. */
712 ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&ref_count); }
713
714 ULONG STDMETHODCALLTYPE Release()
715 {
716 ULONG ulRef = InterlockedDecrement(&ref_count);
717 if (0 == ulRef) {
718 delete this;
719 }
720 return ulRef;
721 }
722
723 HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID ** ppvInterface)
724 {
725 if (__uuidof(IUnknown) == riid) {
726 AddRef();
727 *ppvInterface = (IUnknown *)this;
728 } else if (__uuidof(IMMNotificationClient) == riid) {
729 AddRef();
730 *ppvInterface = (IMMNotificationClient *)this;
731 } else {
732 *ppvInterface = NULL;
733 return E_NOINTERFACE;
734 }
735 return S_OK;
736 }
737
738 wasapi_endpoint_notification_client(HANDLE event, ERole role)
739 : ref_count(1), reconfigure_event(event), role(role),
740 last_device_change(timeGetTime())
741 {
742 }
743
744 virtual ~wasapi_endpoint_notification_client() {}
745
746 HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role,
747 LPCWSTR device_id)
748 {
749 LOG("endpoint: Audio device default changed flow=%d role=%d "
750 "new_device_id=%ws.",
751 flow, role, device_id);
752
753 /* we only support a single stream type for now. */
754 if (flow != eRender || role != this->role) {
755 return S_OK;
756 }
757
758 DWORD last_change_ms = timeGetTime() - last_device_change;
759 bool same_device = default_device_id && device_id &&
760 wcscmp(default_device_id.get(), device_id) == 0;
761 LOG("endpoint: Audio device default changed last_change=%u same_device=%d",
762 last_change_ms, same_device);
763 if (last_change_ms > DEVICE_CHANGE_DEBOUNCE_MS || !same_device) {
764 if (device_id) {
765 default_device_id.reset(_wcsdup(device_id));
766 } else {
767 default_device_id.reset();
768 }
769 BOOL ok = SetEvent(reconfigure_event);
770 LOG("endpoint: Audio device default changed: trigger reconfig");
771 if (!ok) {
772 LOG("endpoint: SetEvent on reconfigure_event failed: %lx",
773 GetLastError());
774 }
775 }
776
777 return S_OK;
778 }
779
780 /* The remaining methods are not implemented, they simply log when called (if
781 log is enabled), for debugging. */
782 HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR device_id)
783 {
784 LOG("endpoint: Audio device added.");
785 return S_OK;
786 };
787
788 HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR device_id)
789 {
790 LOG("endpoint: Audio device removed.");
791 return S_OK;
792 }
793
794 HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR device_id,
795 DWORD new_state)
796 {
797 LOG("endpoint: Audio device state changed.");
798 return S_OK;
799 }
800
801 HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR device_id,
802 const PROPERTYKEY key)
803 {
804 // Audio device property value changed.
805 return S_OK;
806 }
807
808 private:
809 /* refcount for this instance, necessary to implement MSCOM semantics. */
810 LONG ref_count;
811 HANDLE reconfigure_event;
812 ERole role;
813 std::unique_ptr<const wchar_t[]> default_device_id;
814 DWORD last_device_change;
815 };
816
817 namespace {
818
819 long
820 wasapi_data_callback(cubeb_stream * stm, void * user_ptr,
821 void const * input_buffer, void * output_buffer,
822 long nframes)
823 {
824 return stm->data_callback(stm, user_ptr, input_buffer, output_buffer,
825 nframes);
826 }
827
828 void
829 wasapi_state_callback(cubeb_stream * stm, void * user_ptr, cubeb_state state)
830 {
831 return stm->state_callback(stm, user_ptr, state);
832 }
833
834 char const *
835 intern_device_id(cubeb * ctx, wchar_t const * id)
836 {
837 XASSERT(id);
838
839 auto_lock lock(ctx->lock);
840
841 char const * tmp = wstr_to_utf8(id);
842 if (!tmp) {
843 return nullptr;
844 }
845
846 char const * interned = cubeb_strings_intern(ctx->device_ids, tmp);
847
848 free((void *)tmp);
849
850 return interned;
851 }
852
853 bool
854 has_input(cubeb_stream * stm)
855 {
856 return stm->input_stream_params.rate != 0;
857 }
858
859 bool
860 has_output(cubeb_stream * stm)
861 {
862 return stm->output_stream_params.rate != 0;
863 }
864
865 double
866 stream_to_mix_samplerate_ratio(cubeb_stream_params & stream,
867 cubeb_stream_params & mixer)
868 {
869 return double(stream.rate) / mixer.rate;
870 }
871
872 /* Convert the channel layout into the corresponding KSAUDIO_CHANNEL_CONFIG.
873 See more:
874 https://msdn.microsoft.com/en-us/library/windows/hardware/ff537083(v=vs.85).aspx
875 */
876
877 cubeb_channel_layout
878 mask_to_channel_layout(WAVEFORMATEX const * fmt)
879 {
880 cubeb_channel_layout mask = 0;
881
882 if (fmt->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
883 WAVEFORMATEXTENSIBLE const * ext =
884 reinterpret_cast<WAVEFORMATEXTENSIBLE const *>(fmt);
885 mask = ext->dwChannelMask;
886 } else if (fmt->wFormatTag == WAVE_FORMAT_PCM ||
887 fmt->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
888 if (fmt->nChannels == 1) {
889 mask = CHANNEL_FRONT_CENTER;
890 } else if (fmt->nChannels == 2) {
891 mask = CHANNEL_FRONT_LEFT | CHANNEL_FRONT_RIGHT;
892 }
893 }
894 return mask;
895 }
896
897 uint32_t
898 get_rate(cubeb_stream * stm)
899 {
900 return has_input(stm) ? stm->input_stream_params.rate
901 : stm->output_stream_params.rate;
902 }
903
904 uint32_t
905 hns_to_frames(uint32_t rate, REFERENCE_TIME hns)
906 {
907 return std::ceil((hns - 1) / 10000000.0 * rate);
908 }
909
910 uint32_t
911 hns_to_frames(cubeb_stream * stm, REFERENCE_TIME hns)
912 {
913 return hns_to_frames(get_rate(stm), hns);
914 }
915
916 REFERENCE_TIME
917 frames_to_hns(uint32_t rate, uint32_t frames)
918 {
919 return std::ceil(frames * 10000000.0 / rate);
920 }
921
922 /* This returns the size of a frame in the stream, before the eventual upmix
923 occurs. */
924 static size_t
925 frames_to_bytes_before_mix(cubeb_stream * stm, size_t frames)
926 {
927 // This is called only when we has a output client.
928 XASSERT(has_output(stm));
929 return stm->output_stream_params.channels * stm->bytes_per_sample * frames;
930 }
931
932 /* This function handles the processing of the input and output audio,
933 * converting it to rate and channel layout specified at initialization.
934 * It then calls the data callback, via the resampler. */
935 long
936 refill(cubeb_stream * stm, void * input_buffer, long input_frames_count,
937 void * output_buffer, long output_frames_needed)
938 {
939 XASSERT(!stm->draining);
940 /* If we need to upmix after resampling, resample into the mix buffer to
941 avoid a copy. Avoid exposing output if it is a dummy stream. */
942 void * dest = nullptr;
943 if (has_output(stm) && !stm->has_dummy_output) {
944 if (stm->output_mixer) {
945 dest = stm->mix_buffer.data();
946 } else {
947 dest = output_buffer;
948 }
949 }
950
951 long out_frames =
952 cubeb_resampler_fill(stm->resampler.get(), input_buffer,
953 &input_frames_count, dest, output_frames_needed);
954 if (out_frames < 0) {
955 ALOGV("Callback refill error: %d", out_frames);
956 wasapi_state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
957 return out_frames;
958 }
959
960 float volume = 1.0;
961 {
962 auto_lock lock(stm->stream_reset_lock);
963 stm->frames_written += out_frames;
964 volume = stm->volume;
965 }
966
967 /* Go in draining mode if we got fewer frames than requested. If the stream
968 has no output we still expect the callback to return number of frames read
969 from input, otherwise we stop. */
970 if ((out_frames < output_frames_needed) ||
971 (!has_output(stm) && out_frames < input_frames_count)) {
972 LOG("start draining.");
973 stm->draining = true;
974 }
975
976 /* If this is not true, there will be glitches.
977 It is alright to have produced less frames if we are draining, though. */
978 XASSERT(out_frames == output_frames_needed || stm->draining ||
979 !has_output(stm) || stm->has_dummy_output);
980
981 #ifndef CUBEB_WASAPI_USE_IAUDIOSTREAMVOLUME
982 if (has_output(stm) && !stm->has_dummy_output && volume != 1.0) {
983 // Adjust the output volume.
984 // Note: This could be integrated with the remixing below.
985 long out_samples = out_frames * stm->output_stream_params.channels;
986 if (volume == 0.0) {
987 memset(dest, 0, out_samples * stm->bytes_per_sample);
988 } else {
989 switch (stm->output_stream_params.format) {
990 case CUBEB_SAMPLE_FLOAT32NE: {
991 float * buf = static_cast<float *>(dest);
992 for (long i = 0; i < out_samples; ++i) {
993 buf[i] *= volume;
994 }
995 break;
996 }
997 case CUBEB_SAMPLE_S16NE: {
998 short * buf = static_cast<short *>(dest);
999 for (long i = 0; i < out_samples; ++i) {
1000 buf[i] = static_cast<short>(static_cast<float>(buf[i]) * volume);
1001 }
1002 break;
1003 }
1004 default:
1005 XASSERT(false);
1006 }
1007 }
1008 }
1009 #endif
1010
1011 // We don't bother mixing dummy output as it will be silenced, otherwise mix
1012 // output if needed
1013 if (!stm->has_dummy_output && has_output(stm) && stm->output_mixer) {
1014 XASSERT(dest == stm->mix_buffer.data());
1015 size_t dest_size =
1016 out_frames * stm->output_stream_params.channels * stm->bytes_per_sample;
1017 XASSERT(dest_size <= stm->mix_buffer.size());
1018 size_t output_buffer_size =
1019 out_frames * stm->output_mix_params.channels * stm->bytes_per_sample;
1020 int ret = cubeb_mixer_mix(stm->output_mixer.get(), out_frames, dest,
1021 dest_size, output_buffer, output_buffer_size);
1022 if (ret < 0) {
1023 LOG("Error remixing content (%d)", ret);
1024 }
1025 }
1026
1027 return out_frames;
1028 }
1029
1030 bool
1031 trigger_async_reconfigure(cubeb_stream * stm)
1032 {
1033 XASSERT(stm && stm->reconfigure_event);
1034 LOG("Try reconfiguring the stream");
1035 BOOL ok = SetEvent(stm->reconfigure_event);
1036 if (!ok) {
1037 LOG("SetEvent on reconfigure_event failed: %lx", GetLastError());
1038 }
1039 return static_cast<bool>(ok);
1040 }
1041
1042 /* This helper grabs all the frames available from a capture client, put them in
1043 * the linear_input_buffer. This helper does not work with exclusive mode
1044 * streams. */
1045 bool
1046 get_input_buffer(cubeb_stream * stm)
1047 {
1048 XASSERT(has_input(stm));
1049
1050 HRESULT hr;
1051 BYTE * input_packet = NULL;
1052 DWORD flags;
1053 UINT64 dev_pos;
1054 UINT64 pc_position;
1055 UINT32 next;
1056 /* Get input packets until we have captured enough frames, and put them in a
1057 * contiguous buffer. */
1058 uint32_t offset = 0;
1059 // If the input stream is event driven we should only ever expect to read a
1060 // single packet each time. However, if we're pulling from the stream we may
1061 // need to grab multiple packets worth of frames that have accumulated (so
1062 // need a loop).
1063 for (hr = stm->capture_client->GetNextPacketSize(&next); next > 0;
1064 hr = stm->capture_client->GetNextPacketSize(&next)) {
1065 if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
1066 // Application can recover from this error. More info
1067 // https://msdn.microsoft.com/en-us/library/windows/desktop/dd316605(v=vs.85).aspx
1068 LOG("Input device invalidated error");
1069 // No need to reset device if user asks to use particular device, or
1070 // switching is disabled.
1071 if (stm->input_device_id ||
1072 (stm->input_stream_params.prefs &
1073 CUBEB_STREAM_PREF_DISABLE_DEVICE_SWITCHING) ||
1074 !trigger_async_reconfigure(stm)) {
1075 wasapi_state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
1076 return false;
1077 }
1078 return true;
1079 }
1080
1081 if (FAILED(hr)) {
1082 LOG("cannot get next packet size: %lx", hr);
1083 return false;
1084 }
1085
1086 UINT32 frames;
1087 hr = stm->capture_client->GetBuffer(&input_packet, &frames, &flags,
1088 &dev_pos, &pc_position);
1089
1090 if (FAILED(hr)) {
1091 LOG("GetBuffer failed for capture: %lx", hr);
1092 return false;
1093 }
1094 XASSERT(frames == next);
1095
1096 if (stm->context->performance_counter_frequency) {
1097 LARGE_INTEGER now;
1098 UINT64 now_hns;
1099 // See
1100 // https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudiocaptureclient-getbuffer,
1101 // section "Remarks".
1102 QueryPerformanceCounter(&now);
1103 now_hns =
1104 10000000 * now.QuadPart / stm->context->performance_counter_frequency;
1105 if (now_hns >= pc_position) {
1106 stm->input_latency_hns = now_hns - pc_position;
1107 }
1108 }
1109
1110 stm->total_input_frames += frames;
1111
1112 UINT32 input_stream_samples = frames * stm->input_stream_params.channels;
1113 // We do not explicitly handle the AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY
1114 // flag. There a two primary (non exhaustive) scenarios we anticipate this
1115 // flag being set in:
1116 // - The first GetBuffer after Start has this flag undefined. In this
1117 // case the flag may be set but is meaningless and can be ignored.
1118 // - If a glitch is introduced into the input. This should not happen
1119 // for event based inputs, and should be mitigated by using a dummy
1120 // stream to drive input in the case of input only loopback. Without
1121 // a dummy output, input only loopback would glitch on silence. However,
1122 // the dummy input should push silence to the loopback and prevent
1123 // discontinuities. See
1124 // https://blogs.msdn.microsoft.com/matthew_van_eerde/2008/12/16/sample-wasapi-loopback-capture-record-what-you-hear/
1125 // As the first scenario can be ignored, and we anticipate the second
1126 // scenario is mitigated, we ignore the flag.
1127 // For more info:
1128 // https://msdn.microsoft.com/en-us/library/windows/desktop/dd370859(v=vs.85).aspx,
1129 // https://msdn.microsoft.com/en-us/library/windows/desktop/dd371458(v=vs.85).aspx
1130 if (flags & AUDCLNT_BUFFERFLAGS_SILENT) {
1131 LOG("insert silence: ps=%u", frames);
1132 stm->linear_input_buffer->push_silence(input_stream_samples);
1133 } else {
1134 if (stm->input_mixer) {
1135 bool ok = stm->linear_input_buffer->reserve(
1136 stm->linear_input_buffer->length() + input_stream_samples);
1137 XASSERT(ok);
1138 size_t input_packet_size =
1139 frames * stm->input_mix_params.channels *
1140 cubeb_sample_size(stm->input_mix_params.format);
1141 size_t linear_input_buffer_size =
1142 input_stream_samples *
1143 cubeb_sample_size(stm->input_stream_params.format);
1144 cubeb_mixer_mix(stm->input_mixer.get(), frames, input_packet,
1145 input_packet_size, stm->linear_input_buffer->end(),
1146 linear_input_buffer_size);
1147 stm->linear_input_buffer->set_length(
1148 stm->linear_input_buffer->length() + input_stream_samples);
1149 } else {
1150 stm->linear_input_buffer->push(input_packet, input_stream_samples);
1151 }
1152 }
1153 hr = stm->capture_client->ReleaseBuffer(frames);
1154 if (FAILED(hr)) {
1155 LOG("FAILED to release intput buffer");
1156 return false;
1157 }
1158 offset += input_stream_samples;
1159 }
1160
1161 ALOGV("get_input_buffer: got %d frames", offset);
1162
1163 XASSERT(stm->linear_input_buffer->length() >= offset);
1164
1165 return true;
1166 }
1167
1168 /* Get an output buffer from the render_client. It has to be released before
1169 * exiting the callback. */
1170 bool
1171 get_output_buffer(cubeb_stream * stm, void *& buffer, size_t & frame_count)
1172 {
1173 UINT32 padding_out;
1174 HRESULT hr;
1175
1176 XASSERT(has_output(stm));
1177
1178 hr = stm->output_client->GetCurrentPadding(&padding_out);
1179 if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
1180 // Application can recover from this error. More info
1181 // https://msdn.microsoft.com/en-us/library/windows/desktop/dd316605(v=vs.85).aspx
1182 LOG("Output device invalidated error");
1183 // No need to reset device if user asks to use particular device, or
1184 // switching is disabled.
1185 if (stm->output_device_id ||
1186 (stm->output_stream_params.prefs &
1187 CUBEB_STREAM_PREF_DISABLE_DEVICE_SWITCHING) ||
1188 !trigger_async_reconfigure(stm)) {
1189 wasapi_state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
1190 return false;
1191 }
1192 return true;
1193 }
1194
1195 if (FAILED(hr)) {
1196 LOG("Failed to get padding: %lx", hr);
1197 return false;
1198 }
1199
1200 XASSERT(padding_out <= stm->output_buffer_frame_count);
1201
1202 if (stm->draining) {
1203 if (padding_out == 0) {
1204 LOG("Draining finished.");
1205 wasapi_state_callback(stm, stm->user_ptr, CUBEB_STATE_DRAINED);
1206 return false;
1207 }
1208 LOG("Draining.");
1209 return true;
1210 }
1211
1212 frame_count = stm->output_buffer_frame_count - padding_out;
1213 BYTE * output_buffer;
1214
1215 hr = stm->render_client->GetBuffer(frame_count, &output_buffer);
1216 if (FAILED(hr)) {
1217 LOG("cannot get render buffer");
1218 return false;
1219 }
1220
1221 buffer = output_buffer;
1222
1223 return true;
1224 }
1225
1226 /**
1227 * This function gets input data from a input device, and pass it along with an
1228 * output buffer to the resamplers. */
1229 bool
1230 refill_callback_duplex(cubeb_stream * stm)
1231 {
1232 HRESULT hr;
1233 void * output_buffer = nullptr;
1234 size_t output_frames = 0;
1235 size_t input_frames;
1236 bool rv;
1237
1238 XASSERT(has_input(stm) && has_output(stm));
1239
1240 if (stm->input_stream_params.prefs & CUBEB_STREAM_PREF_LOOPBACK) {
1241 HRESULT rv = get_input_buffer(stm);
1242 if (FAILED(rv)) {
1243 return rv;
1244 }
1245 }
1246
1247 input_frames =
1248 stm->linear_input_buffer->length() / stm->input_stream_params.channels;
1249
1250 rv = get_output_buffer(stm, output_buffer, output_frames);
1251 if (!rv) {
1252 hr = stm->render_client->ReleaseBuffer(output_frames, 0);
1253 return rv;
1254 }
1255
1256 /* This can only happen when debugging, and having breakpoints set in the
1257 * callback in a way that it makes the stream underrun. */
1258 if (output_frames == 0) {
1259 return true;
1260 }
1261
1262 /* Wait for draining is not important on duplex. */
1263 if (stm->draining) {
1264 return false;
1265 }
1266
1267 stm->total_output_frames += output_frames;
1268
1269 ALOGV("in: %zu, out: %zu, missing: %ld, ratio: %f", stm->total_input_frames,
1270 stm->total_output_frames,
1271 static_cast<long>(stm->total_output_frames) - stm->total_input_frames,
1272 static_cast<float>(stm->total_output_frames) / stm->total_input_frames);
1273
1274 long got;
1275 if (stm->has_dummy_output) {
1276 ALOGV(
1277 "Duplex callback (dummy output): input frames: %Iu, output frames: %Iu",
1278 input_frames, output_frames);
1279
1280 // We don't want to expose the dummy output to the callback so don't pass
1281 // the output buffer (it will be released later with silence in it)
1282 got =
1283 refill(stm, stm->linear_input_buffer->data(), input_frames, nullptr, 0);
1284
1285 } else {
1286 ALOGV("Duplex callback: input frames: %Iu, output frames: %Iu",
1287 input_frames, output_frames);
1288
1289 got = refill(stm, stm->linear_input_buffer->data(), input_frames,
1290 output_buffer, output_frames);
1291 }
1292
1293 stm->linear_input_buffer->clear();
1294
1295 if (stm->has_dummy_output) {
1296 // If output is a dummy output, make sure it's silent
1297 hr = stm->render_client->ReleaseBuffer(output_frames,
1298 AUDCLNT_BUFFERFLAGS_SILENT);
1299 } else {
1300 hr = stm->render_client->ReleaseBuffer(output_frames, 0);
1301 }
1302 if (FAILED(hr)) {
1303 LOG("failed to release buffer: %lx", hr);
1304 return false;
1305 }
1306 if (got < 0) {
1307 return false;
1308 }
1309 return true;
1310 }
1311
1312 bool
1313 refill_callback_input(cubeb_stream * stm)
1314 {
1315 bool rv;
1316 size_t input_frames;
1317
1318 XASSERT(has_input(stm) && !has_output(stm));
1319
1320 rv = get_input_buffer(stm);
1321 if (!rv) {
1322 return rv;
1323 }
1324
1325 input_frames =
1326 stm->linear_input_buffer->length() / stm->input_stream_params.channels;
1327 if (!input_frames) {
1328 return true;
1329 }
1330
1331 ALOGV("Input callback: input frames: %Iu", input_frames);
1332
1333 long read =
1334 refill(stm, stm->linear_input_buffer->data(), input_frames, nullptr, 0);
1335 if (read < 0) {
1336 return false;
1337 }
1338
1339 stm->linear_input_buffer->clear();
1340
1341 return !stm->draining;
1342 }
1343
1344 bool
1345 refill_callback_output(cubeb_stream * stm)
1346 {
1347 bool rv;
1348 HRESULT hr;
1349 void * output_buffer = nullptr;
1350 size_t output_frames = 0;
1351
1352 XASSERT(!has_input(stm) && has_output(stm));
1353
1354 rv = get_output_buffer(stm, output_buffer, output_frames);
1355 if (!rv) {
1356 return rv;
1357 }
1358
1359 if (stm->draining || output_frames == 0) {
1360 return true;
1361 }
1362
1363 long got = refill(stm, nullptr, 0, output_buffer, output_frames);
1364
1365 ALOGV("Output callback: output frames requested: %Iu, got %ld", output_frames,
1366 got);
1367 if (got < 0) {
1368 return false;
1369 }
1370 XASSERT(size_t(got) == output_frames || stm->draining);
1371
1372 hr = stm->render_client->ReleaseBuffer(got, 0);
1373 if (FAILED(hr)) {
1374 LOG("failed to release buffer: %lx", hr);
1375 return false;
1376 }
1377
1378 return size_t(got) == output_frames || stm->draining;
1379 }
1380
1381 void
1382 wasapi_stream_destroy(cubeb_stream * stm);
1383
1384 static unsigned int __stdcall wasapi_stream_render_loop(LPVOID stream)
1385 {
1386 AutoRegisterThread raii("cubeb rendering thread");
1387 cubeb_stream * stm = static_cast<cubeb_stream *>(stream);
1388
1389 auto_stream_ref stream_ref(stm);
1390 struct auto_com {
1391 auto_com()
1392 {
1393 HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
1394 XASSERT(SUCCEEDED(hr));
1395 }
1396 ~auto_com() { CoUninitialize(); }
1397 } com;
1398
1399 bool is_playing = true;
1400 HANDLE wait_array[4] = {stm->shutdown_event, stm->reconfigure_event,
1401 stm->refill_event, stm->input_available_event};
1402 HANDLE mmcss_handle = NULL;
1403 HRESULT hr = 0;
1404 DWORD mmcss_task_index = 0;
1405
1406 // Signal wasapi_stream_start that we've initialized COM and incremented
1407 // the stream's ref_count.
1408 BOOL ok = SetEvent(stm->thread_ready_event);
1409 if (!ok) {
1410 LOG("thread_ready SetEvent failed: %lx", GetLastError());
1411 return 0;
1412 }
1413
1414 /* We could consider using "Pro Audio" here for WebAudio and
1415 maybe WebRTC. */
1416 mmcss_handle =
1417 stm->context->set_mm_thread_characteristics(L"Audio", &mmcss_task_index);
1418 if (!mmcss_handle) {
1419 /* This is not fatal, but we might glitch under heavy load. */
1420 LOG("Unable to use mmcss to bump the render thread priority: %lx",
1421 GetLastError());
1422 }
1423
1424 while (is_playing) {
1425 DWORD waitResult = WaitForMultipleObjects(ARRAY_LENGTH(wait_array),
1426 wait_array, FALSE, INFINITE);
1427 switch (waitResult) {
1428 case WAIT_OBJECT_0: { /* shutdown */
1429 is_playing = false;
1430 /* We don't check if the drain is actually finished here, we just want to
1431 shutdown. */
1432 if (stm->draining) {
1433 wasapi_state_callback(stm, stm->user_ptr, CUBEB_STATE_DRAINED);
1434 }
1435 continue;
1436 }
1437 case WAIT_OBJECT_0 + 1: { /* reconfigure */
1438 auto_lock lock(stm->stream_reset_lock);
1439 if (!stm->active) {
1440 /* Avoid reconfiguring, stream start will handle it. */
1441 LOG("Stream is not active, ignoring reconfigure.");
1442 continue;
1443 }
1444 XASSERT(stm->output_client || stm->input_client);
1445 LOG("Reconfiguring the stream");
1446 /* Close the stream */
1447 bool was_running = false;
1448 if (stm->output_client) {
1449 was_running = stm->output_client->Stop() == S_OK;
1450 LOG("Output stopped.");
1451 }
1452 if (stm->input_client) {
1453 was_running = stm->input_client->Stop() == S_OK;
1454 LOG("Input stopped.");
1455 }
1456 close_wasapi_stream(stm);
1457 LOG("Stream closed.");
1458 /* Reopen a stream and start it immediately. This will automatically
1459 pick the new default device for this role. */
1460 int r = setup_wasapi_stream(stm);
1461 if (r != CUBEB_OK) {
1462 LOG("Error setting up the stream during reconfigure.");
1463 /* Don't destroy the stream here, since we expect the caller to do
1464 so after the error has propagated via the state callback. */
1465 is_playing = false;
1466 hr = E_FAIL;
1467 continue;
1468 }
1469 LOG("Stream setup successfuly.");
1470 XASSERT(stm->output_client || stm->input_client);
1471 if (was_running && stm->output_client) {
1472 hr = stm->output_client->Start();
1473 if (FAILED(hr)) {
1474 LOG("Error starting output after reconfigure, error: %lx", hr);
1475 is_playing = false;
1476 continue;
1477 }
1478 LOG("Output started after reconfigure.");
1479 }
1480 if (was_running && stm->input_client) {
1481 hr = stm->input_client->Start();
1482 if (FAILED(hr)) {
1483 LOG("Error starting input after reconfiguring, error: %lx", hr);
1484 is_playing = false;
1485 continue;
1486 }
1487 LOG("Input started after reconfigure.");
1488 }
1489 break;
1490 }
1491 case WAIT_OBJECT_0 + 2: /* refill */
1492 XASSERT((has_input(stm) && has_output(stm)) ||
1493 (!has_input(stm) && has_output(stm)));
1494 is_playing = stm->refill_callback(stm);
1495 break;
1496 case WAIT_OBJECT_0 + 3: { /* input available */
1497 HRESULT rv = get_input_buffer(stm);
1498 if (FAILED(rv)) {
1499 is_playing = false;
1500 continue;
1501 }
1502
1503 if (!has_output(stm)) {
1504 is_playing = stm->refill_callback(stm);
1505 }
1506
1507 break;
1508 }
1509 default:
1510 LOG("case %lu not handled in render loop.", waitResult);
1511 XASSERT(false);
1512 }
1513 }
1514
1515 // Stop audio clients since this thread will no longer service
1516 // the events.
1517 if (stm->output_client) {
1518 stm->output_client->Stop();
1519 }
1520 if (stm->input_client) {
1521 stm->input_client->Stop();
1522 }
1523
1524 if (mmcss_handle) {
1525 stm->context->revert_mm_thread_characteristics(mmcss_handle);
1526 }
1527
1528 if (FAILED(hr)) {
1529 wasapi_state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
1530 }
1531
1532 return 0;
1533 }
1534
1535 void
1536 wasapi_destroy(cubeb * context);
1537
1538 HANDLE WINAPI
1539 set_mm_thread_characteristics_noop(LPCWSTR, LPDWORD mmcss_task_index)
1540 {
1541 return (HANDLE)1;
1542 }
1543
1544 BOOL WINAPI
1545 revert_mm_thread_characteristics_noop(HANDLE mmcss_handle)
1546 {
1547 return true;
1548 }
1549
1550 HRESULT
1551 register_notification_client(cubeb_stream * stm)
1552 {
1553 XASSERT(stm->device_enumerator && !stm->notification_client);
1554
1555 stm->notification_client.reset(new wasapi_endpoint_notification_client(
1556 stm->reconfigure_event, stm->role));
1557
1558 HRESULT hr = stm->device_enumerator->RegisterEndpointNotificationCallback(
1559 stm->notification_client.get());
1560 if (FAILED(hr)) {
1561 LOG("Could not register endpoint notification callback: %lx", hr);
1562 stm->notification_client = nullptr;
1563 }
1564
1565 return hr;
1566 }
1567
1568 HRESULT
1569 unregister_notification_client(cubeb_stream * stm)
1570 {
1571 XASSERT(stm->device_enumerator && stm->notification_client);
1572
1573 HRESULT hr = stm->device_enumerator->UnregisterEndpointNotificationCallback(
1574 stm->notification_client.get());
1575 if (FAILED(hr)) {
1576 // We can't really do anything here, we'll probably leak the
1577 // notification client.
1578 return S_OK;
1579 }
1580
1581 stm->notification_client = nullptr;
1582
1583 return S_OK;
1584 }
1585
1586 HRESULT
1587 get_endpoint(com_ptr<IMMDevice> & device, LPCWSTR devid)
1588 {
1589 com_ptr<IMMDeviceEnumerator> enumerator;
1590 HRESULT hr =
1591 CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER,
1592 IID_PPV_ARGS(enumerator.receive()));
1593 if (FAILED(hr)) {
1594 LOG("Could not get device enumerator: %lx", hr);
1595 return hr;
1596 }
1597
1598 hr = enumerator->GetDevice(devid, device.receive());
1599 if (FAILED(hr)) {
1600 LOG("Could not get device: %lx", hr);
1601 return hr;
1602 }
1603
1604 return S_OK;
1605 }
1606
1607 HRESULT
1608 register_collection_notification_client(cubeb * context)
1609 {
1610 context->lock.assert_current_thread_owns();
1611 XASSERT(!context->device_collection_enumerator &&
1612 !context->collection_notification_client);
1613 HRESULT hr = CoCreateInstance(
1614 __uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER,
1615 IID_PPV_ARGS(context->device_collection_enumerator.receive()));
1616 if (FAILED(hr)) {
1617 LOG("Could not get device enumerator: %lx", hr);
1618 return hr;
1619 }
1620
1621 context->collection_notification_client.reset(
1622 new wasapi_collection_notification_client(context));
1623
1624 hr = context->device_collection_enumerator
1625 ->RegisterEndpointNotificationCallback(
1626 context->collection_notification_client.get());
1627 if (FAILED(hr)) {
1628 LOG("Could not register endpoint notification callback: %lx", hr);
1629 context->collection_notification_client.reset();
1630 context->device_collection_enumerator.reset();
1631 }
1632
1633 return hr;
1634 }
1635
1636 HRESULT
1637 unregister_collection_notification_client(cubeb * context)
1638 {
1639 context->lock.assert_current_thread_owns();
1640 XASSERT(context->device_collection_enumerator &&
1641 context->collection_notification_client);
1642 HRESULT hr = context->device_collection_enumerator
1643 ->UnregisterEndpointNotificationCallback(
1644 context->collection_notification_client.get());
1645 if (FAILED(hr)) {
1646 return hr;
1647 }
1648
1649 context->collection_notification_client = nullptr;
1650 context->device_collection_enumerator = nullptr;
1651
1652 return hr;
1653 }
1654
1655 HRESULT
1656 get_default_endpoint(com_ptr<IMMDevice> & device, EDataFlow direction,
1657 ERole role)
1658 {
1659 com_ptr<IMMDeviceEnumerator> enumerator;
1660 HRESULT hr =
1661 CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER,
1662 IID_PPV_ARGS(enumerator.receive()));
1663 if (FAILED(hr)) {
1664 LOG("Could not get device enumerator: %lx", hr);
1665 return hr;
1666 }
1667 hr = enumerator->GetDefaultAudioEndpoint(direction, role, device.receive());
1668 if (FAILED(hr)) {
1669 LOG("Could not get default audio endpoint: %lx", hr);
1670 return hr;
1671 }
1672
1673 return ERROR_SUCCESS;
1674 }
1675
1676 double
1677 current_stream_delay(cubeb_stream * stm)
1678 {
1679 stm->stream_reset_lock.assert_current_thread_owns();
1680
1681 /* If the default audio endpoint went away during playback and we weren't
1682 able to configure a new one, it's possible the caller may call this
1683 before the error callback has propogated back. */
1684 if (!stm->audio_clock) {
1685 return 0;
1686 }
1687
1688 UINT64 freq;
1689 HRESULT hr = stm->audio_clock->GetFrequency(&freq);
1690 if (FAILED(hr)) {
1691 LOG("GetFrequency failed: %lx", hr);
1692 return 0;
1693 }
1694
1695 UINT64 pos;
1696 hr = stm->audio_clock->GetPosition(&pos, NULL);
1697 if (FAILED(hr)) {
1698 LOG("GetPosition failed: %lx", hr);
1699 return 0;
1700 }
1701
1702 double cur_pos = static_cast<double>(pos) / freq;
1703 double max_pos =
1704 static_cast<double>(stm->frames_written) / stm->output_mix_params.rate;
1705 double delay = std::max(max_pos - cur_pos, 0.0);
1706
1707 return delay;
1708 }
1709
1710 #ifdef CUBEB_WASAPI_USE_IAUDIOSTREAMVOLUME
1711 int
1712 stream_set_volume(cubeb_stream * stm, float volume)
1713 {
1714 stm->stream_reset_lock.assert_current_thread_owns();
1715
1716 if (!stm->audio_stream_volume) {
1717 return CUBEB_ERROR;
1718 }
1719
1720 uint32_t channels;
1721 HRESULT hr = stm->audio_stream_volume->GetChannelCount(&channels);
1722 if (FAILED(hr)) {
1723 LOG("could not get the channel count: %lx", hr);
1724 return CUBEB_ERROR;
1725 }
1726
1727 /* up to 9.1 for now */
1728 if (channels > 10) {
1729 return CUBEB_ERROR_NOT_SUPPORTED;
1730 }
1731
1732 float volumes[10];
1733 for (uint32_t i = 0; i < channels; i++) {
1734 volumes[i] = volume;
1735 }
1736
1737 hr = stm->audio_stream_volume->SetAllVolumes(channels, volumes);
1738 if (FAILED(hr)) {
1739 LOG("could not set the channels volume: %lx", hr);
1740 return CUBEB_ERROR;
1741 }
1742
1743 return CUBEB_OK;
1744 }
1745 #endif
1746 } // namespace
1747
1748 extern "C" {
1749 int
1750 wasapi_init(cubeb ** context, char const * context_name)
1751 {
1752 /* We don't use the device yet, but need to make sure we can initialize one
1753 so that this backend is not incorrectly enabled on platforms that don't
1754 support WASAPI. */
1755 com_ptr<IMMDevice> device;
1756 HRESULT hr = get_default_endpoint(device, eRender, eConsole);
1757 if (FAILED(hr)) {
1758 XASSERT(hr != CO_E_NOTINITIALIZED);
1759 LOG("It wasn't able to find a default rendering device: %lx", hr);
1760 hr = get_default_endpoint(device, eCapture, eConsole);
1761 if (FAILED(hr)) {
1762 LOG("It wasn't able to find a default capture device: %lx", hr);
1763 return CUBEB_ERROR;
1764 }
1765 }
1766
1767 cubeb * ctx = new cubeb();
1768
1769 ctx->ops = &wasapi_ops;
1770 auto_lock lock(ctx->lock);
1771 if (cubeb_strings_init(&ctx->device_ids) != CUBEB_OK) {
1772 delete ctx;
1773 return CUBEB_ERROR;
1774 }
1775
1776 LARGE_INTEGER frequency;
1777 if (QueryPerformanceFrequency(&frequency)) {
1778 ctx->performance_counter_frequency = frequency.QuadPart;
1779 } else {
1780 LOG("Failed getting performance counter frequency, latency reporting will "
1781 "be inacurate");
1782 ctx->performance_counter_frequency = 0;
1783 }
1784
1785 ctx->mmcss_module = LoadLibraryW(L"Avrt.dll");
1786
1787 bool success = false;
1788 if (ctx->mmcss_module) {
1789 ctx->set_mm_thread_characteristics =
1790 reinterpret_cast<set_mm_thread_characteristics_function>(
1791 GetProcAddress(ctx->mmcss_module, "AvSetMmThreadCharacteristicsW"));
1792 ctx->revert_mm_thread_characteristics =
1793 reinterpret_cast<revert_mm_thread_characteristics_function>(
1794 GetProcAddress(ctx->mmcss_module,
1795 "AvRevertMmThreadCharacteristics"));
1796 success = ctx->set_mm_thread_characteristics &&
1797 ctx->revert_mm_thread_characteristics;
1798 }
1799 if (!success) {
1800 // This is not a fatal error, but we might end up glitching when
1801 // the system is under high load.
1802 LOG("Could not load avrt.dll or fetch AvSetMmThreadCharacteristicsW "
1803 "AvRevertMmThreadCharacteristics: %lx",
1804 GetLastError());
1805 ctx->set_mm_thread_characteristics = &set_mm_thread_characteristics_noop;
1806 ctx->revert_mm_thread_characteristics =
1807 &revert_mm_thread_characteristics_noop;
1808 }
1809
1810 *context = ctx;
1811
1812 return CUBEB_OK;
1813 }
1814 }
1815
1816 namespace {
1817 enum ShutdownPhase { OnStop, OnDestroy };
1818
1819 bool
1820 stop_and_join_render_thread(cubeb_stream * stm)
1821 {
1822 LOG("%p: Stop and join render thread: %p", stm, stm->thread);
1823 if (!stm->thread) {
1824 return true;
1825 }
1826
1827 BOOL ok = SetEvent(stm->shutdown_event);
1828 if (!ok) {
1829 LOG("stop_and_join_render_thread: SetEvent failed: %lx", GetLastError());
1830 return false;
1831 }
1832
1833 /* Wait five seconds for the rendering thread to return. It's supposed to
1834 * check its event loop very often, five seconds is rather conservative.
1835 * Note: 5*1s loop to work around timer sleep issues on pre-Windows 8. */
1836 DWORD r;
1837 for (int i = 0; i < 5; ++i) {
1838 r = WaitForSingleObject(stm->thread, 1000);
1839 if (r == WAIT_OBJECT_0) {
1840 break;
1841 }
1842 }
1843 if (r != WAIT_OBJECT_0) {
1844 LOG("stop_and_join_render_thread: WaitForSingleObject on thread failed: "
1845 "%lx, %lx",
1846 r, GetLastError());
1847 return false;
1848 }
1849
1850 return true;
1851 }
1852
1853 void
1854 wasapi_destroy(cubeb * context)
1855 {
1856 {
1857 auto_lock lock(context->lock);
1858 XASSERT(!context->device_collection_enumerator &&
1859 !context->collection_notification_client);
1860
1861 if (context->device_ids) {
1862 cubeb_strings_destroy(context->device_ids);
1863 }
1864 }
1865
1866 if (context->mmcss_module) {
1867 FreeLibrary(context->mmcss_module);
1868 }
1869
1870 delete context;
1871 }
1872
1873 char const *
1874 wasapi_get_backend_id(cubeb * context)
1875 {
1876 return "wasapi";
1877 }
1878
1879 int
1880 wasapi_get_max_channel_count(cubeb * ctx, uint32_t * max_channels)
1881 {
1882 XASSERT(ctx && max_channels);
1883
1884 com_ptr<IMMDevice> device;
1885 HRESULT hr = get_default_endpoint(device, eRender, eConsole);
1886 if (FAILED(hr)) {
1887 return CUBEB_ERROR;
1888 }
1889
1890 com_ptr<IAudioClient> client;
1891 hr = device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL,
1892 client.receive_vpp());
1893 if (FAILED(hr)) {
1894 return CUBEB_ERROR;
1895 }
1896
1897 WAVEFORMATEX * tmp = nullptr;
1898 hr = client->GetMixFormat(&tmp);
1899 if (FAILED(hr)) {
1900 return CUBEB_ERROR;
1901 }
1902 com_heap_ptr<WAVEFORMATEX> mix_format(tmp);
1903
1904 *max_channels = mix_format->nChannels;
1905
1906 return CUBEB_OK;
1907 }
1908
1909 int
1910 wasapi_get_min_latency(cubeb * ctx, cubeb_stream_params params,
1911 uint32_t * latency_frames)
1912 {
1913 if (params.format != CUBEB_SAMPLE_FLOAT32NE &&
1914 params.format != CUBEB_SAMPLE_S16NE) {
1915 return CUBEB_ERROR_INVALID_FORMAT;
1916 }
1917
1918 ERole role = pref_to_role(params.prefs);
1919
1920 com_ptr<IMMDevice> device;
1921 HRESULT hr = get_default_endpoint(device, eRender, role);
1922 if (FAILED(hr)) {
1923 LOG("Could not get default endpoint: %lx", hr);
1924 return CUBEB_ERROR;
1925 }
1926
1927 com_ptr<IAudioClient> client;
1928 hr = device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL,
1929 client.receive_vpp());
1930 if (FAILED(hr)) {
1931 LOG("Could not activate device for latency: %lx", hr);
1932 return CUBEB_ERROR;
1933 }
1934
1935 REFERENCE_TIME minimum_period;
1936 REFERENCE_TIME default_period;
1937 hr = client->GetDevicePeriod(&default_period, &minimum_period);
1938 if (FAILED(hr)) {
1939 LOG("Could not get device period: %lx", hr);
1940 return CUBEB_ERROR;
1941 }
1942
1943 LOG("default device period: %I64d, minimum device period: %I64d",
1944 default_period, minimum_period);
1945
1946 /* If we're on Windows 10, we can use IAudioClient3 to get minimal latency.
1947 Otherwise, according to the docs, the best latency we can achieve is by
1948 synchronizing the stream and the engine.
1949 http://msdn.microsoft.com/en-us/library/windows/desktop/dd370871%28v=vs.85%29.aspx
1950 */
1951
1952 // #ifdef _WIN32_WINNT_WIN10
1953 #if 0
1954 *latency_frames = hns_to_frames(params.rate, minimum_period);
1955 #else
1956 *latency_frames = hns_to_frames(params.rate, default_period);
1957 #endif
1958
1959 LOG("Minimum latency in frames: %u", *latency_frames);
1960
1961 return CUBEB_OK;
1962 }
1963
1964 int
1965 wasapi_get_preferred_sample_rate(cubeb * ctx, uint32_t * rate)
1966 {
1967 com_ptr<IMMDevice> device;
1968 HRESULT hr = get_default_endpoint(device, eRender, eConsole);
1969 if (FAILED(hr)) {
1970 return CUBEB_ERROR;
1971 }
1972
1973 com_ptr<IAudioClient> client;
1974 hr = device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL,
1975 client.receive_vpp());
1976 if (FAILED(hr)) {
1977 return CUBEB_ERROR;
1978 }
1979
1980 WAVEFORMATEX * tmp = nullptr;
1981 hr = client->GetMixFormat(&tmp);
1982 if (FAILED(hr)) {
1983 return CUBEB_ERROR;
1984 }
1985 com_heap_ptr<WAVEFORMATEX> mix_format(tmp);
1986
1987 *rate = mix_format->nSamplesPerSec;
1988
1989 LOG("Preferred sample rate for output: %u", *rate);
1990
1991 return CUBEB_OK;
1992 }
1993
1994 static void
1995 waveformatex_update_derived_properties(WAVEFORMATEX * format)
1996 {
1997 format->nBlockAlign = format->wBitsPerSample * format->nChannels / 8;
1998 format->nAvgBytesPerSec = format->nSamplesPerSec * format->nBlockAlign;
1999 if (format->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
2000 WAVEFORMATEXTENSIBLE * format_pcm =
2001 reinterpret_cast<WAVEFORMATEXTENSIBLE *>(format);
2002 format_pcm->Samples.wValidBitsPerSample = format->wBitsPerSample;
2003 }
2004 }
2005
2006 /* Based on the mix format and the stream format, try to find a way to play
2007 what the user requested. */
2008 static void
2009 handle_channel_layout(cubeb_stream * stm, EDataFlow direction,
2010 com_heap_ptr<WAVEFORMATEX> & mix_format,
2011 const cubeb_stream_params * stream_params)
2012 {
2013 com_ptr<IAudioClient> & audio_client =
2014 (direction == eRender) ? stm->output_client : stm->input_client;
2015 XASSERT(audio_client);
2016 /* The docs say that GetMixFormat is always of type WAVEFORMATEXTENSIBLE [1],
2017 so the reinterpret_cast below should be safe. In practice, this is not
2018 true, and we just want to bail out and let the rest of the code find a good
2019 conversion path instead of trying to make WASAPI do it by itself.
2020 [1]:
2021 http://msdn.microsoft.com/en-us/library/windows/desktop/dd370811%28v=vs.85%29.aspx*/
2022 if (mix_format->wFormatTag != WAVE_FORMAT_EXTENSIBLE) {
2023 return;
2024 }
2025
2026 WAVEFORMATEXTENSIBLE * format_pcm =
2027 reinterpret_cast<WAVEFORMATEXTENSIBLE *>(mix_format.get());
2028
2029 /* Stash a copy of the original mix format in case we need to restore it
2030 * later. */
2031 WAVEFORMATEXTENSIBLE hw_mix_format = *format_pcm;
2032
2033 /* Get the channel mask by the channel layout.
2034 If the layout is not supported, we will get a closest settings below. */
2035 format_pcm->dwChannelMask = stream_params->layout;
2036 mix_format->nChannels = stream_params->channels;
2037 waveformatex_update_derived_properties(mix_format.get());
2038
2039 /* Check if wasapi will accept our channel layout request. */
2040 WAVEFORMATEX * tmp = nullptr;
2041 HRESULT hr = audio_client->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED,
2042 mix_format.get(), &tmp);
2043 com_heap_ptr<WAVEFORMATEX> closest(tmp);
2044 if (hr == S_FALSE) {
2045 /* Channel layout not supported, but WASAPI gives us a suggestion. Use it,
2046 and handle the eventual upmix/downmix ourselves. Ignore the subformat of
2047 the suggestion, since it seems to always be IEEE_FLOAT. */
2048 LOG("Using WASAPI suggested format: channels: %d", closest->nChannels);
2049 XASSERT(closest->wFormatTag == WAVE_FORMAT_EXTENSIBLE);
2050 WAVEFORMATEXTENSIBLE * closest_pcm =
2051 reinterpret_cast<WAVEFORMATEXTENSIBLE *>(closest.get());
2052 format_pcm->dwChannelMask = closest_pcm->dwChannelMask;
2053 mix_format->nChannels = closest->nChannels;
2054 waveformatex_update_derived_properties(mix_format.get());
2055 } else if (hr == AUDCLNT_E_UNSUPPORTED_FORMAT) {
2056 /* Not supported, no suggestion. This should not happen, but it does in the
2057 field with some sound cards. We restore the mix format, and let the rest
2058 of the code figure out the right conversion path. */
2059 XASSERT(mix_format->wFormatTag == WAVE_FORMAT_EXTENSIBLE);
2060 *reinterpret_cast<WAVEFORMATEXTENSIBLE *>(mix_format.get()) = hw_mix_format;
2061 } else if (hr == S_OK) {
2062 LOG("Requested format accepted by WASAPI.");
2063 } else {
2064 LOG("IsFormatSupported unhandled error: %lx", hr);
2065 }
2066 }
2067
2068 static int
2069 initialize_iaudioclient2(com_ptr<IAudioClient> & audio_client)
2070 {
2071 com_ptr<IAudioClient2> audio_client2;
2072 audio_client->QueryInterface<IAudioClient2>(audio_client2.receive());
2073 if (!audio_client2) {
2074 LOG("Could not get IAudioClient2 interface, not setting "
2075 "AUDCLNT_STREAMOPTIONS_RAW.");
2076 return CUBEB_OK;
2077 }
2078 AudioClientProperties properties = {0};
2079 properties.cbSize = sizeof(AudioClientProperties);
2080 #ifndef __MINGW32__
2081 properties.Options |= AUDCLNT_STREAMOPTIONS_RAW;
2082 #endif
2083 HRESULT hr = audio_client2->SetClientProperties(&properties);
2084 if (FAILED(hr)) {
2085 LOG("IAudioClient2::SetClientProperties error: %lx", GetLastError());
2086 return CUBEB_ERROR;
2087 }
2088 return CUBEB_OK;
2089 }
2090
2091 #if 0
2092 bool
2093 initialize_iaudioclient3(com_ptr<IAudioClient> & audio_client,
2094 cubeb_stream * stm,
2095 const com_heap_ptr<WAVEFORMATEX> & mix_format,
2096 DWORD flags, EDataFlow direction)
2097 {
2098 com_ptr<IAudioClient3> audio_client3;
2099 audio_client->QueryInterface<IAudioClient3>(audio_client3.receive());
2100 if (!audio_client3) {
2101 LOG("Could not get IAudioClient3 interface");
2102 return false;
2103 }
2104
2105 if (flags & AUDCLNT_STREAMFLAGS_LOOPBACK) {
2106 // IAudioClient3 doesn't work with loopback streams, and will return error
2107 // 88890021: AUDCLNT_E_INVALID_STREAM_FLAG
2108 LOG("Audio stream is loopback, not using IAudioClient3");
2109 return false;
2110 }
2111
2112 // Some people have reported glitches with capture streams:
2113 // http://blog.nirbheek.in/2018/03/low-latency-audio-on-windows-with.html
2114 if (direction == eCapture) {
2115 LOG("Audio stream is capture, not using IAudioClient3");
2116 return false;
2117 }
2118
2119 // Possibly initialize a shared-mode stream using IAudioClient3. Initializing
2120 // a stream this way lets you request lower latencies, but also locks the
2121 // global WASAPI engine at that latency.
2122 // - If we request a shared-mode stream, streams created with IAudioClient
2123 // will
2124 // have their latency adjusted to match. When the shared-mode stream is
2125 // closed, they'll go back to normal.
2126 // - If there's already a shared-mode stream running, then we cannot request
2127 // the engine change to a different latency - we have to match it.
2128 // - It's antisocial to lock the WASAPI engine at its default latency. If we
2129 // would do this, then stop and use IAudioClient instead.
2130
2131 HRESULT hr;
2132 uint32_t default_period = 0, fundamental_period = 0, min_period = 0,
2133 max_period = 0;
2134 hr = audio_client3->GetSharedModeEnginePeriod(
2135 mix_format.get(), &default_period, &fundamental_period, &min_period,
2136 &max_period);
2137 if (FAILED(hr)) {
2138 LOG("Could not get shared mode engine period: error: %lx", hr);
2139 return false;
2140 }
2141 uint32_t requested_latency = stm->latency;
2142 if (requested_latency >= default_period) {
2143 LOG("Requested latency %i greater than default latency %i, not using "
2144 "IAudioClient3",
2145 requested_latency, default_period);
2146 return false;
2147 }
2148 LOG("Got shared mode engine period: default=%i fundamental=%i min=%i max=%i",
2149 default_period, fundamental_period, min_period, max_period);
2150 // Snap requested latency to a valid value
2151 uint32_t old_requested_latency = requested_latency;
2152 if (requested_latency < min_period) {
2153 requested_latency = min_period;
2154 }
2155 requested_latency -= (requested_latency - min_period) % fundamental_period;
2156 if (requested_latency != old_requested_latency) {
2157 LOG("Requested latency %i was adjusted to %i", old_requested_latency,
2158 requested_latency);
2159 }
2160
2161 hr = audio_client3->InitializeSharedAudioStream(flags, requested_latency,
2162 mix_format.get(), NULL);
2163 if (SUCCEEDED(hr)) {
2164 return true;
2165 } else if (hr == AUDCLNT_E_ENGINE_PERIODICITY_LOCKED) {
2166 LOG("Got AUDCLNT_E_ENGINE_PERIODICITY_LOCKED, adjusting latency request");
2167 } else {
2168 LOG("Could not initialize shared stream with IAudioClient3: error: %lx",
2169 hr);
2170 return false;
2171 }
2172
2173 uint32_t current_period = 0;
2174 WAVEFORMATEX * current_format = nullptr;
2175 // We have to pass a valid WAVEFORMATEX** and not nullptr, otherwise
2176 // GetCurrentSharedModeEnginePeriod will return E_POINTER
2177 hr = audio_client3->GetCurrentSharedModeEnginePeriod(&current_format,
2178 &current_period);
2179 CoTaskMemFree(current_format);
2180 if (FAILED(hr)) {
2181 LOG("Could not get current shared mode engine period: error: %lx", hr);
2182 return false;
2183 }
2184
2185 if (current_period >= default_period) {
2186 LOG("Current shared mode engine period %i too high, not using IAudioClient",
2187 current_period);
2188 return false;
2189 }
2190
2191 hr = audio_client3->InitializeSharedAudioStream(flags, current_period,
2192 mix_format.get(), NULL);
2193 if (SUCCEEDED(hr)) {
2194 LOG("Current shared mode engine period is %i instead of requested %i",
2195 current_period, requested_latency);
2196 return true;
2197 }
2198
2199 LOG("Could not initialize shared stream with IAudioClient3: error: %lx", hr);
2200 return false;
2201 }
2202 #endif
2203
2204 #define DIRECTION_NAME (direction == eCapture ? "capture" : "render")
2205
2206 template <typename T>
2207 int
2208 setup_wasapi_stream_one_side(cubeb_stream * stm,
2209 cubeb_stream_params * stream_params,
2210 wchar_t const * devid, EDataFlow direction,
2211 REFIID riid, com_ptr<IAudioClient> & audio_client,
2212 uint32_t * buffer_frame_count, HANDLE & event,
2213 T & render_or_capture_client,
2214 cubeb_stream_params * mix_params,
2215 com_ptr<IMMDevice> & device)
2216 {
2217 XASSERT(direction == eCapture || direction == eRender);
2218
2219 HRESULT hr;
2220 bool is_loopback = stream_params->prefs & CUBEB_STREAM_PREF_LOOPBACK;
2221 if (is_loopback && direction != eCapture) {
2222 LOG("Loopback pref can only be used with capture streams!\n");
2223 return CUBEB_ERROR;
2224 }
2225
2226 stm->stream_reset_lock.assert_current_thread_owns();
2227 // If user doesn't specify a particular device, we can choose another one when
2228 // the given devid is unavailable.
2229 bool allow_fallback =
2230 direction == eCapture ? !stm->input_device_id : !stm->output_device_id;
2231 bool try_again = false;
2232 // This loops until we find a device that works, or we've exhausted all
2233 // possibilities.
2234 do {
2235 if (devid) {
2236 hr = get_endpoint(device, devid);
2237 if (FAILED(hr)) {
2238 LOG("Could not get %s endpoint, error: %lx\n", DIRECTION_NAME, hr);
2239 return CUBEB_ERROR;
2240 }
2241 } else {
2242 // If caller has requested loopback but not specified a device, look for
2243 // the default render device. Otherwise look for the default device
2244 // appropriate to the direction.
2245 hr = get_default_endpoint(device, is_loopback ? eRender : direction,
2246 pref_to_role(stream_params->prefs));
2247 if (FAILED(hr)) {
2248 if (is_loopback) {
2249 LOG("Could not get default render endpoint for loopback, error: "
2250 "%lx\n",
2251 hr);
2252 } else {
2253 LOG("Could not get default %s endpoint, error: %lx\n", DIRECTION_NAME,
2254 hr);
2255 }
2256 return CUBEB_ERROR;
2257 }
2258 }
2259
2260 /* Get a client. We will get all other interfaces we need from
2261 * this pointer. */
2262 #if 0 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1590902
2263 hr = device->Activate(__uuidof(IAudioClient3),
2264 CLSCTX_INPROC_SERVER,
2265 NULL, audio_client.receive_vpp());
2266 if (hr == E_NOINTERFACE) {
2267 #endif
2268 hr = device->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER, NULL,
2269 audio_client.receive_vpp());
2270 #if 0
2271 }
2272 #endif
2273
2274 if (FAILED(hr)) {
2275 LOG("Could not activate the device to get an audio"
2276 " client for %s: error: %lx\n",
2277 DIRECTION_NAME, hr);
2278 // A particular device can't be activated because it has been
2279 // unplugged, try fall back to the default audio device.
2280 if (devid && hr == AUDCLNT_E_DEVICE_INVALIDATED && allow_fallback) {
2281 LOG("Trying again with the default %s audio device.", DIRECTION_NAME);
2282 devid = nullptr;
2283 device = nullptr;
2284 try_again = true;
2285 } else {
2286 return CUBEB_ERROR;
2287 }
2288 } else {
2289 try_again = false;
2290 }
2291 } while (try_again);
2292
2293 /* We have to distinguish between the format the mixer uses,
2294 * and the format the stream we want to play uses. */
2295 WAVEFORMATEX * tmp = nullptr;
2296 hr = audio_client->GetMixFormat(&tmp);
2297 if (FAILED(hr)) {
2298 LOG("Could not fetch current mix format from the audio"
2299 " client for %s: error: %lx",
2300 DIRECTION_NAME, hr);
2301 return CUBEB_ERROR;
2302 }
2303 com_heap_ptr<WAVEFORMATEX> mix_format(tmp);
2304
2305 mix_format->wBitsPerSample = stm->bytes_per_sample * 8;
2306 if (mix_format->wFormatTag == WAVE_FORMAT_PCM ||
2307 mix_format->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
2308 switch (mix_format->wBitsPerSample) {
2309 case 8:
2310 case 16:
2311 mix_format->wFormatTag = WAVE_FORMAT_PCM;
2312 break;
2313 case 32:
2314 mix_format->wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
2315 break;
2316 default:
2317 LOG("%u bits per sample is incompatible with PCM wave formats",
2318 mix_format->wBitsPerSample);
2319 return CUBEB_ERROR;
2320 }
2321 }
2322
2323 if (mix_format->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
2324 WAVEFORMATEXTENSIBLE * format_pcm =
2325 reinterpret_cast<WAVEFORMATEXTENSIBLE *>(mix_format.get());
2326 format_pcm->SubFormat = stm->waveformatextensible_sub_format;
2327 }
2328 waveformatex_update_derived_properties(mix_format.get());
2329
2330 /* Set channel layout only when there're more than two channels. Otherwise,
2331 * use the default setting retrieved from the stream format of the audio
2332 * engine's internal processing by GetMixFormat. */
2333 if (mix_format->nChannels > 2) {
2334 handle_channel_layout(stm, direction, mix_format, stream_params);
2335 }
2336
2337 mix_params->format = stream_params->format;
2338 mix_params->rate = mix_format->nSamplesPerSec;
2339 mix_params->channels = mix_format->nChannels;
2340 mix_params->layout = mask_to_channel_layout(mix_format.get());
2341
2342 LOG("Setup requested=[f=%d r=%u c=%u l=%u] mix=[f=%d r=%u c=%u l=%u]",
2343 stream_params->format, stream_params->rate, stream_params->channels,
2344 stream_params->layout, mix_params->format, mix_params->rate,
2345 mix_params->channels, mix_params->layout);
2346
2347 DWORD flags = 0;
2348
2349 // Check if a loopback device should be requested. Note that event callbacks
2350 // do not work with loopback devices, so only request these if not looping.
2351 if (is_loopback) {
2352 flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
2353 } else {
2354 flags |= AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
2355 }
2356
2357 REFERENCE_TIME latency_hns = frames_to_hns(stream_params->rate, stm->latency);
2358
2359 // Adjust input latency and check if input is using bluetooth handsfree
2360 // protocol.
2361 if (direction == eCapture) {
2362 stm->input_bluetooth_handsfree = false;
2363
2364 wasapi_default_devices default_devices(stm->device_enumerator.get());
2365 cubeb_device_info device_info;
2366 if (wasapi_create_device(stm->context, device_info,
2367 stm->device_enumerator.get(), device.get(),
2368 &default_devices) == CUBEB_OK) {
2369 if (device_info.latency_hi == 0) {
2370 LOG("Input: could not query latency_hi to guess safe latency");
2371 wasapi_destroy_device(&device_info);
2372 return CUBEB_ERROR;
2373 }
2374 // This multiplicator has been found empirically.
2375 uint32_t latency_frames = device_info.latency_hi * 8;
2376 LOG("Input: latency increased to %u frames from a default of %u",
2377 latency_frames, device_info.latency_hi);
2378 latency_hns = frames_to_hns(device_info.default_rate, latency_frames);
2379
2380 const char * HANDSFREE_TAG = "BTHHFENUM";
2381 size_t len = sizeof(HANDSFREE_TAG);
2382 if (strlen(device_info.group_id) >= len &&
2383 strncmp(device_info.group_id, HANDSFREE_TAG, len) == 0) {
2384 LOG("Input device is using bluetooth handsfree protocol");
2385 stm->input_bluetooth_handsfree = true;
2386 }
2387
2388 wasapi_destroy_device(&device_info);
2389 } else {
2390 LOG("Could not get cubeb_device_info. Skip customizing input settings");
2391 }
2392 }
2393
2394 if (stream_params->prefs & CUBEB_STREAM_PREF_RAW) {
2395 if (initialize_iaudioclient2(audio_client) != CUBEB_OK) {
2396 LOG("Can't initialize an IAudioClient2, error: %lx", GetLastError());
2397 // This is not fatal.
2398 }
2399 }
2400
2401 #if 0 // See https://bugzilla.mozilla.org/show_bug.cgi?id=1590902
2402 if (initialize_iaudioclient3(audio_client, stm, mix_format, flags, direction)) {
2403 LOG("Initialized with IAudioClient3");
2404 } else {
2405 #endif
2406 hr = audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags, latency_hns, 0,
2407 mix_format.get(), NULL);
2408 #if 0
2409 }
2410 #endif
2411 if (FAILED(hr)) {
2412 LOG("Unable to initialize audio client for %s: %lx.", DIRECTION_NAME, hr);
2413 return CUBEB_ERROR;
2414 }
2415
2416 hr = audio_client->GetBufferSize(buffer_frame_count);
2417 if (FAILED(hr)) {
2418 LOG("Could not get the buffer size from the client"
2419 " for %s %lx.",
2420 DIRECTION_NAME, hr);
2421 return CUBEB_ERROR;
2422 }
2423
2424 LOG("Buffer size is: %d for %s\n", *buffer_frame_count, DIRECTION_NAME);
2425
2426 // Events are used if not looping back
2427 if (!is_loopback) {
2428 hr = audio_client->SetEventHandle(event);
2429 if (FAILED(hr)) {
2430 LOG("Could set the event handle for the %s client %lx.", DIRECTION_NAME,
2431 hr);
2432 return CUBEB_ERROR;
2433 }
2434 }
2435
2436 hr = audio_client->GetService(riid, render_or_capture_client.receive_vpp());
2437 if (FAILED(hr)) {
2438 LOG("Could not get the %s client %lx.", DIRECTION_NAME, hr);
2439 return CUBEB_ERROR;
2440 }
2441
2442 return CUBEB_OK;
2443 }
2444
2445 #undef DIRECTION_NAME
2446
2447 // Returns a non-null cubeb_devid if we find a matched device, or nullptr
2448 // otherwise.
2449 cubeb_devid
2450 wasapi_find_bt_handsfree_output_device(cubeb_stream * stm)
2451 {
2452 HRESULT hr;
2453 cubeb_device_info * input_device = nullptr;
2454 cubeb_device_collection collection;
2455
2456 // Only try to match to an output device if the input device is a bluetooth
2457 // device that is using the handsfree protocol
2458 if (!stm->input_bluetooth_handsfree) {
2459 return nullptr;
2460 }
2461
2462 wchar_t * tmp = nullptr;
2463 hr = stm->input_device->GetId(&tmp);
2464 if (FAILED(hr)) {
2465 LOG("Couldn't get input device id in "
2466 "wasapi_find_bt_handsfree_output_device");
2467 return nullptr;
2468 }
2469 com_heap_ptr<wchar_t> device_id(tmp);
2470 cubeb_devid input_device_id = reinterpret_cast<cubeb_devid>(
2471 intern_device_id(stm->context, device_id.get()));
2472 if (!input_device_id) {
2473 return nullptr;
2474 }
2475
2476 int rv = wasapi_enumerate_devices_internal(
2477 stm->context,
2478 (cubeb_device_type)(CUBEB_DEVICE_TYPE_INPUT | CUBEB_DEVICE_TYPE_OUTPUT),
2479 &collection, DEVICE_STATE_ACTIVE);
2480 if (rv != CUBEB_OK) {
2481 return nullptr;
2482 }
2483
2484 // Find the input device, and then find the output device with the same group
2485 // id and the same rate.
2486 for (uint32_t i = 0; i < collection.count; i++) {
2487 if (collection.device[i].devid == input_device_id) {
2488 input_device = &collection.device[i];
2489 break;
2490 }
2491 }
2492
2493 cubeb_devid matched_output = nullptr;
2494
2495 if (input_device) {
2496 for (uint32_t i = 0; i < collection.count; i++) {
2497 cubeb_device_info & dev = collection.device[i];
2498 if (dev.type == CUBEB_DEVICE_TYPE_OUTPUT && dev.group_id &&
2499 !strcmp(dev.group_id, input_device->group_id) &&
2500 dev.default_rate == input_device->default_rate) {
2501 LOG("Found matching device for %s: %s", input_device->friendly_name,
2502 dev.friendly_name);
2503 matched_output = dev.devid;
2504 break;
2505 }
2506 }
2507 }
2508
2509 wasapi_device_collection_destroy(stm->context, &collection);
2510 return matched_output;
2511 }
2512
2513 std::unique_ptr<wchar_t[]>
2514 copy_wide_string(const wchar_t * src)
2515 {
2516 XASSERT(src);
2517 size_t len = wcslen(src);
2518 std::unique_ptr<wchar_t[]> copy(new wchar_t[len + 1]);
2519 if (wcsncpy_s(copy.get(), len + 1, src, len) != 0) {
2520 return nullptr;
2521 }
2522 return copy;
2523 }
2524
2525 int
2526 setup_wasapi_stream(cubeb_stream * stm)
2527 {
2528 int rv;
2529
2530 stm->stream_reset_lock.assert_current_thread_owns();
2531
2532 XASSERT((!stm->output_client || !stm->input_client) &&
2533 "WASAPI stream already setup, close it first.");
2534
2535 std::unique_ptr<const wchar_t[]> selected_output_device_id;
2536 if (stm->output_device_id) {
2537 if (std::unique_ptr<wchar_t[]> tmp =
2538 copy_wide_string(stm->output_device_id.get())) {
2539 selected_output_device_id = std::move(tmp);
2540 } else {
2541 LOG("Failed to copy output device identifier.");
2542 return CUBEB_ERROR;
2543 }
2544 }
2545
2546 if (has_input(stm)) {
2547 LOG("(%p) Setup capture: device=%p", stm, stm->input_device_id.get());
2548 rv = setup_wasapi_stream_one_side(
2549 stm, &stm->input_stream_params, stm->input_device_id.get(), eCapture,
2550 __uuidof(IAudioCaptureClient), stm->input_client,
2551 &stm->input_buffer_frame_count, stm->input_available_event,
2552 stm->capture_client, &stm->input_mix_params, stm->input_device);
2553 if (rv != CUBEB_OK) {
2554 LOG("Failure to open the input side.");
2555 return rv;
2556 }
2557
2558 // We initializing an input stream, buffer ahead two buffers worth of
2559 // silence. This delays the input side slightly, but allow to not glitch
2560 // when no input is available when calling into the resampler to call the
2561 // callback: the input refill event will be set shortly after to compensate
2562 // for this lack of data. In debug, four buffers are used, to avoid tripping
2563 // up assertions down the line.
2564 #if !defined(DEBUG)
2565 const int silent_buffer_count = 2;
2566 #else
2567 const int silent_buffer_count = 6;
2568 #endif
2569 stm->linear_input_buffer->push_silence(stm->input_buffer_frame_count *
2570 stm->input_stream_params.channels *
2571 silent_buffer_count);
2572
2573 // If this is a bluetooth device, and the output device is the default
2574 // device, and the default device is the same bluetooth device, pick the
2575 // right output device, running at the same rate and with the same protocol
2576 // as the input.
2577 if (!selected_output_device_id) {
2578 cubeb_devid matched = wasapi_find_bt_handsfree_output_device(stm);
2579 if (matched) {
2580 selected_output_device_id =
2581 utf8_to_wstr(reinterpret_cast<char const *>(matched));
2582 }
2583 }
2584 }
2585
2586 // If we don't have an output device but are requesting a loopback device,
2587 // we attempt to open that same device in output mode in order to drive the
2588 // loopback via the output events.
2589 stm->has_dummy_output = false;
2590 if (!has_output(stm) &&
2591 stm->input_stream_params.prefs & CUBEB_STREAM_PREF_LOOPBACK) {
2592 stm->output_stream_params.rate = stm->input_stream_params.rate;
2593 stm->output_stream_params.channels = stm->input_stream_params.channels;
2594 stm->output_stream_params.layout = stm->input_stream_params.layout;
2595 if (stm->input_device_id) {
2596 if (std::unique_ptr<wchar_t[]> tmp =
2597 copy_wide_string(stm->input_device_id.get())) {
2598 XASSERT(!selected_output_device_id);
2599 selected_output_device_id = std::move(tmp);
2600 } else {
2601 LOG("Failed to copy device identifier while copying input stream "
2602 "configuration to output stream configuration to drive loopback.");
2603 return CUBEB_ERROR;
2604 }
2605 }
2606 stm->has_dummy_output = true;
2607 }
2608
2609 if (has_output(stm)) {
2610 LOG("(%p) Setup render: device=%p", stm, selected_output_device_id.get());
2611 rv = setup_wasapi_stream_one_side(
2612 stm, &stm->output_stream_params, selected_output_device_id.get(),
2613 eRender, __uuidof(IAudioRenderClient), stm->output_client,
2614 &stm->output_buffer_frame_count, stm->refill_event, stm->render_client,
2615 &stm->output_mix_params, stm->output_device);
2616 if (rv != CUBEB_OK) {
2617 LOG("Failure to open the output side.");
2618 return rv;
2619 }
2620
2621 HRESULT hr = 0;
2622 #ifdef CUBEB_WASAPI_USE_IAUDIOSTREAMVOLUME
2623 hr = stm->output_client->GetService(__uuidof(IAudioStreamVolume),
2624 stm->audio_stream_volume.receive_vpp());
2625 if (FAILED(hr)) {
2626 LOG("Could not get the IAudioStreamVolume: %lx", hr);
2627 return CUBEB_ERROR;
2628 }
2629 #endif
2630
2631 XASSERT(stm->frames_written == 0);
2632 hr = stm->output_client->GetService(__uuidof(IAudioClock),
2633 stm->audio_clock.receive_vpp());
2634 if (FAILED(hr)) {
2635 LOG("Could not get the IAudioClock: %lx", hr);
2636 return CUBEB_ERROR;
2637 }
2638
2639 #ifdef CUBEB_WASAPI_USE_IAUDIOSTREAMVOLUME
2640 /* Restore the stream volume over a device change. */
2641 if (stream_set_volume(stm, stm->volume) != CUBEB_OK) {
2642 LOG("Could not set the volume.");
2643 return CUBEB_ERROR;
2644 }
2645 #endif
2646 }
2647
2648 /* If we have both input and output, we resample to
2649 * the highest sample rate available. */
2650 int32_t target_sample_rate;
2651 if (has_input(stm) && has_output(stm)) {
2652 XASSERT(stm->input_stream_params.rate == stm->output_stream_params.rate);
2653 target_sample_rate = stm->input_stream_params.rate;
2654 } else if (has_input(stm)) {
2655 target_sample_rate = stm->input_stream_params.rate;
2656 } else {
2657 XASSERT(has_output(stm));
2658 target_sample_rate = stm->output_stream_params.rate;
2659 }
2660
2661 LOG("Target sample rate: %d", target_sample_rate);
2662
2663 /* If we are playing/capturing a mono stream, we only resample one channel,
2664 and copy it over, so we are always resampling the number
2665 of channels of the stream, not the number of channels
2666 that WASAPI wants. */
2667 cubeb_stream_params input_params = stm->input_mix_params;
2668 input_params.channels = stm->input_stream_params.channels;
2669 cubeb_stream_params output_params = stm->output_mix_params;
2670 output_params.channels = stm->output_stream_params.channels;
2671
2672 stm->resampler.reset(cubeb_resampler_create(
2673 stm, has_input(stm) ? &input_params : nullptr,
2674 has_output(stm) && !stm->has_dummy_output ? &output_params : nullptr,
2675 target_sample_rate, wasapi_data_callback, stm->user_ptr,
2676 stm->voice ? CUBEB_RESAMPLER_QUALITY_VOIP
2677 : CUBEB_RESAMPLER_QUALITY_DESKTOP,
2678 CUBEB_RESAMPLER_RECLOCK_NONE));
2679 if (!stm->resampler) {
2680 LOG("Could not get a resampler");
2681 return CUBEB_ERROR;
2682 }
2683
2684 XASSERT(has_input(stm) || has_output(stm));
2685
2686 if (has_input(stm) && has_output(stm)) {
2687 stm->refill_callback = refill_callback_duplex;
2688 } else if (has_input(stm)) {
2689 stm->refill_callback = refill_callback_input;
2690 } else if (has_output(stm)) {
2691 stm->refill_callback = refill_callback_output;
2692 }
2693
2694 // Create input mixer.
2695 if (has_input(stm) &&
2696 ((stm->input_mix_params.layout != CUBEB_LAYOUT_UNDEFINED &&
2697 stm->input_mix_params.layout != stm->input_stream_params.layout) ||
2698 (stm->input_mix_params.channels != stm->input_stream_params.channels))) {
2699 if (stm->input_mix_params.layout == CUBEB_LAYOUT_UNDEFINED) {
2700 LOG("Input stream using undefined layout! Any mixing may be "
2701 "unpredictable!\n");
2702 }
2703 stm->input_mixer.reset(cubeb_mixer_create(
2704 stm->input_stream_params.format, stm->input_mix_params.channels,
2705 stm->input_mix_params.layout, stm->input_stream_params.channels,
2706 stm->input_stream_params.layout));
2707 assert(stm->input_mixer);
2708 }
2709
2710 // Create output mixer.
2711 if (has_output(stm) &&
2712 stm->output_mix_params.layout != stm->output_stream_params.layout) {
2713 if (stm->output_mix_params.layout == CUBEB_LAYOUT_UNDEFINED) {
2714 LOG("Output stream using undefined layout! Any mixing may be "
2715 "unpredictable!\n");
2716 }
2717 stm->output_mixer.reset(cubeb_mixer_create(
2718 stm->output_stream_params.format, stm->output_stream_params.channels,
2719 stm->output_stream_params.layout, stm->output_mix_params.channels,
2720 stm->output_mix_params.layout));
2721 assert(stm->output_mixer);
2722 // Input is up/down mixed when depacketized in get_input_buffer.
2723 stm->mix_buffer.resize(
2724 frames_to_bytes_before_mix(stm, stm->output_buffer_frame_count));
2725 }
2726
2727 return CUBEB_OK;
2728 }
2729
2730 ERole
2731 pref_to_role(cubeb_stream_prefs prefs)
2732 {
2733 if (prefs & CUBEB_STREAM_PREF_VOICE) {
2734 return eCommunications;
2735 }
2736
2737 return eConsole;
2738 }
2739
2740 int
2741 wasapi_stream_init(cubeb * context, cubeb_stream ** stream,
2742 char const * stream_name, cubeb_devid input_device,
2743 cubeb_stream_params * input_stream_params,
2744 cubeb_devid output_device,
2745 cubeb_stream_params * output_stream_params,
2746 unsigned int latency_frames,
2747 cubeb_data_callback data_callback,
2748 cubeb_state_callback state_callback, void * user_ptr)
2749 {
2750 int rv;
2751
2752 XASSERT(context && stream && (input_stream_params || output_stream_params));
2753
2754 if (output_stream_params && input_stream_params &&
2755 output_stream_params->format != input_stream_params->format) {
2756 return CUBEB_ERROR_INVALID_FORMAT;
2757 }
2758
2759 cubeb_stream * stm = new cubeb_stream();
2760 auto_stream_ref stream_ref(stm);
2761
2762 stm->context = context;
2763 stm->data_callback = data_callback;
2764 stm->state_callback = state_callback;
2765 stm->user_ptr = user_ptr;
2766 stm->role = eConsole;
2767 stm->input_bluetooth_handsfree = false;
2768
2769 HRESULT hr =
2770 CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER,
2771 IID_PPV_ARGS(stm->device_enumerator.receive()));
2772 if (FAILED(hr)) {
2773 LOG("Could not get device enumerator: %lx", hr);
2774 return hr;
2775 }
2776
2777 if (input_stream_params) {
2778 stm->input_stream_params = *input_stream_params;
2779 stm->input_device_id =
2780 utf8_to_wstr(reinterpret_cast<char const *>(input_device));
2781 }
2782 if (output_stream_params) {
2783 stm->output_stream_params = *output_stream_params;
2784 stm->output_device_id =
2785 utf8_to_wstr(reinterpret_cast<char const *>(output_device));
2786 }
2787
2788 if (stm->output_stream_params.prefs & CUBEB_STREAM_PREF_VOICE ||
2789 stm->input_stream_params.prefs & CUBEB_STREAM_PREF_VOICE) {
2790 stm->voice = true;
2791 } else {
2792 stm->voice = false;
2793 }
2794
2795 switch (output_stream_params ? output_stream_params->format
2796 : input_stream_params->format) {
2797 case CUBEB_SAMPLE_S16NE:
2798 stm->bytes_per_sample = sizeof(short);
2799 stm->waveformatextensible_sub_format = KSDATAFORMAT_SUBTYPE_PCM;
2800 stm->linear_input_buffer.reset(new auto_array_wrapper_impl<short>);
2801 break;
2802 case CUBEB_SAMPLE_FLOAT32NE:
2803 stm->bytes_per_sample = sizeof(float);
2804 stm->waveformatextensible_sub_format = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
2805 stm->linear_input_buffer.reset(new auto_array_wrapper_impl<float>);
2806 break;
2807 default:
2808 return CUBEB_ERROR_INVALID_FORMAT;
2809 }
2810
2811 stm->latency = latency_frames;
2812
2813 stm->reconfigure_event = CreateEvent(NULL, 0, 0, NULL);
2814 if (!stm->reconfigure_event) {
2815 LOG("Can't create the reconfigure event, error: %lx", GetLastError());
2816 return CUBEB_ERROR;
2817 }
2818
2819 /* Unconditionally create the two events so that the wait logic is simpler. */
2820 stm->refill_event = CreateEvent(NULL, 0, 0, NULL);
2821 if (!stm->refill_event) {
2822 LOG("Can't create the refill event, error: %lx", GetLastError());
2823 return CUBEB_ERROR;
2824 }
2825
2826 stm->input_available_event = CreateEvent(NULL, 0, 0, NULL);
2827 if (!stm->input_available_event) {
2828 LOG("Can't create the input available event , error: %lx", GetLastError());
2829 return CUBEB_ERROR;
2830 }
2831
2832 stm->shutdown_event = CreateEvent(NULL, 0, 0, NULL);
2833 if (!stm->shutdown_event) {
2834 LOG("Can't create the shutdown event, error: %lx", GetLastError());
2835 return CUBEB_ERROR;
2836 }
2837
2838 stm->thread_ready_event = CreateEvent(NULL, 0, 0, NULL);
2839 if (!stm->thread_ready_event) {
2840 LOG("Can't create the thread ready event, error: %lx", GetLastError());
2841 return CUBEB_ERROR;
2842 }
2843
2844 {
2845 /* Locking here is not strictly necessary, because we don't have a
2846 notification client that can reset the stream yet, but it lets us
2847 assert that the lock is held in the function. */
2848 auto_lock lock(stm->stream_reset_lock);
2849 rv = setup_wasapi_stream(stm);
2850 }
2851 if (rv != CUBEB_OK) {
2852 return rv;
2853 }
2854
2855 // Follow the system default devices when not specifying devices explicitly
2856 // and CUBEB_STREAM_PREF_DISABLE_DEVICE_SWITCHING is not set.
2857 if ((!input_device && input_stream_params &&
2858 !(input_stream_params->prefs &
2859 CUBEB_STREAM_PREF_DISABLE_DEVICE_SWITCHING)) ||
2860 (!output_device && output_stream_params &&
2861 !(output_stream_params->prefs &
2862 CUBEB_STREAM_PREF_DISABLE_DEVICE_SWITCHING))) {
2863 LOG("Follow the system default input or/and output devices");
2864 HRESULT hr = register_notification_client(stm);
2865 if (FAILED(hr)) {
2866 /* this is not fatal, we can still play audio, but we won't be able
2867 to keep using the default audio endpoint if it changes. */
2868 LOG("failed to register notification client, %lx", hr);
2869 }
2870 }
2871
2872 cubeb_async_log_reset_threads();
2873 stm->thread =
2874 (HANDLE)_beginthreadex(NULL, 512 * 1024, wasapi_stream_render_loop, stm,
2875 STACK_SIZE_PARAM_IS_A_RESERVATION, NULL);
2876 if (stm->thread == NULL) {
2877 LOG("could not create WASAPI render thread.");
2878 return CUBEB_ERROR;
2879 }
2880
2881 // Wait for the wasapi_stream_render_loop thread to signal that COM has been
2882 // initialized and the stream's ref_count has been incremented.
2883 hr = WaitForSingleObject(stm->thread_ready_event, INFINITE);
2884 XASSERT(hr == WAIT_OBJECT_0);
2885 CloseHandle(stm->thread_ready_event);
2886 stm->thread_ready_event = 0;
2887
2888 wasapi_stream_add_ref(stm);
2889 *stream = stm;
2890
2891 LOG("Stream init successful (%p)", *stream);
2892 return CUBEB_OK;
2893 }
2894
2895 void
2896 close_wasapi_stream(cubeb_stream * stm)
2897 {
2898 XASSERT(stm);
2899
2900 stm->stream_reset_lock.assert_current_thread_owns();
2901
2902 #ifdef CUBEB_WASAPI_USE_IAUDIOSTREAMVOLUME
2903 stm->audio_stream_volume = nullptr;
2904 #endif
2905 stm->audio_clock = nullptr;
2906 stm->render_client = nullptr;
2907 stm->output_client = nullptr;
2908 stm->output_device = nullptr;
2909
2910 stm->capture_client = nullptr;
2911 stm->input_client = nullptr;
2912 stm->input_device = nullptr;
2913
2914 stm->total_frames_written += static_cast<UINT64>(
2915 round(stm->frames_written *
2916 stream_to_mix_samplerate_ratio(stm->output_stream_params,
2917 stm->output_mix_params)));
2918 stm->frames_written = 0;
2919
2920 stm->resampler.reset();
2921 stm->output_mixer.reset();
2922 stm->input_mixer.reset();
2923 stm->mix_buffer.clear();
2924 if (stm->linear_input_buffer) {
2925 stm->linear_input_buffer->clear();
2926 }
2927 }
2928
2929 LONG
2930 wasapi_stream_add_ref(cubeb_stream * stm)
2931 {
2932 XASSERT(stm);
2933 LONG result = InterlockedIncrement(&stm->ref_count);
2934 LOGV("Stream ref count incremented = %i (%p)", result, stm);
2935 return result;
2936 }
2937
2938 LONG
2939 wasapi_stream_release(cubeb_stream * stm)
2940 {
2941 XASSERT(stm);
2942
2943 LONG result = InterlockedDecrement(&stm->ref_count);
2944 LOGV("Stream ref count decremented = %i (%p)", result, stm);
2945 if (result == 0) {
2946 LOG("Stream ref count hit zero, destroying (%p)", stm);
2947
2948 if (stm->notification_client) {
2949 unregister_notification_client(stm);
2950 }
2951
2952 CloseHandle(stm->shutdown_event);
2953 CloseHandle(stm->reconfigure_event);
2954 CloseHandle(stm->refill_event);
2955 CloseHandle(stm->input_available_event);
2956
2957 CloseHandle(stm->thread);
2958
2959 // The variables intialized in wasapi_stream_init,
2960 // must be destroyed in wasapi_stream_release.
2961 stm->linear_input_buffer.reset();
2962
2963 {
2964 auto_lock lock(stm->stream_reset_lock);
2965 close_wasapi_stream(stm);
2966 }
2967
2968 delete stm;
2969 }
2970
2971 return result;
2972 }
2973
2974 void
2975 wasapi_stream_destroy(cubeb_stream * stm)
2976 {
2977 XASSERT(stm);
2978 LOG("Stream destroy called, decrementing ref count (%p)", stm);
2979
2980 stop_and_join_render_thread(stm);
2981 wasapi_stream_release(stm);
2982 }
2983
2984 enum StreamDirection { OUTPUT, INPUT };
2985
2986 int
2987 stream_start_one_side(cubeb_stream * stm, StreamDirection dir)
2988 {
2989 XASSERT(stm);
2990 XASSERT((dir == OUTPUT && stm->output_client) ||
2991 (dir == INPUT && stm->input_client));
2992
2993 HRESULT hr =
2994 dir == OUTPUT ? stm->output_client->Start() : stm->input_client->Start();
2995 if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
2996 LOG("audioclient invalidated for %s device, reconfiguring",
2997 dir == OUTPUT ? "output" : "input");
2998
2999 BOOL ok = ResetEvent(stm->reconfigure_event);
3000 if (!ok) {
3001 LOG("resetting reconfig event failed for %s stream: %lx",
3002 dir == OUTPUT ? "output" : "input", GetLastError());
3003 }
3004
3005 close_wasapi_stream(stm);
3006 int r = setup_wasapi_stream(stm);
3007 if (r != CUBEB_OK) {
3008 LOG("reconfigure failed");
3009 return r;
3010 }
3011
3012 HRESULT hr2 = dir == OUTPUT ? stm->output_client->Start()
3013 : stm->input_client->Start();
3014 if (FAILED(hr2)) {
3015 LOG("could not start the %s stream after reconfig: %lx",
3016 dir == OUTPUT ? "output" : "input", hr);
3017 return CUBEB_ERROR;
3018 }
3019 } else if (FAILED(hr)) {
3020 LOG("could not start the %s stream: %lx.",
3021 dir == OUTPUT ? "output" : "input", hr);
3022 return CUBEB_ERROR;
3023 }
3024
3025 return CUBEB_OK;
3026 }
3027
3028 int
3029 wasapi_stream_start(cubeb_stream * stm)
3030 {
3031 auto_lock lock(stm->stream_reset_lock);
3032
3033 XASSERT(stm);
3034 XASSERT(stm->output_client || stm->input_client);
3035
3036 if (stm->output_client) {
3037 int rv = stream_start_one_side(stm, OUTPUT);
3038 if (rv != CUBEB_OK) {
3039 return rv;
3040 }
3041 }
3042
3043 if (stm->input_client) {
3044 int rv = stream_start_one_side(stm, INPUT);
3045 if (rv != CUBEB_OK) {
3046 return rv;
3047 }
3048 }
3049
3050 stm->active = true;
3051
3052 stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_STARTED);
3053
3054 return CUBEB_OK;
3055 }
3056
3057 int
3058 wasapi_stream_stop(cubeb_stream * stm)
3059 {
3060 XASSERT(stm);
3061 HRESULT hr;
3062
3063 {
3064 auto_lock lock(stm->stream_reset_lock);
3065
3066 if (stm->output_client) {
3067 hr = stm->output_client->Stop();
3068 if (FAILED(hr)) {
3069 LOG("could not stop AudioClient (output)");
3070 return CUBEB_ERROR;
3071 }
3072 }
3073
3074 if (stm->input_client) {
3075 hr = stm->input_client->Stop();
3076 if (FAILED(hr)) {
3077 LOG("could not stop AudioClient (input)");
3078 return CUBEB_ERROR;
3079 }
3080 }
3081
3082 stm->active = false;
3083
3084 wasapi_state_callback(stm, stm->user_ptr, CUBEB_STATE_STOPPED);
3085 }
3086
3087 return CUBEB_OK;
3088 }
3089
3090 int
3091 wasapi_stream_get_position(cubeb_stream * stm, uint64_t * position)
3092 {
3093 XASSERT(stm && position);
3094 auto_lock lock(stm->stream_reset_lock);
3095
3096 if (!has_output(stm)) {
3097 return CUBEB_ERROR;
3098 }
3099
3100 /* Calculate how far behind the current stream head the playback cursor is. */
3101 uint64_t stream_delay = static_cast<uint64_t>(current_stream_delay(stm) *
3102 stm->output_stream_params.rate);
3103
3104 /* Calculate the logical stream head in frames at the stream sample rate. */
3105 uint64_t max_pos =
3106 stm->total_frames_written +
3107 static_cast<uint64_t>(
3108 round(stm->frames_written *
3109 stream_to_mix_samplerate_ratio(stm->output_stream_params,
3110 stm->output_mix_params)));
3111
3112 *position = max_pos;
3113 if (stream_delay <= *position) {
3114 *position -= stream_delay;
3115 }
3116
3117 if (*position < stm->prev_position) {
3118 *position = stm->prev_position;
3119 }
3120 stm->prev_position = *position;
3121
3122 return CUBEB_OK;
3123 }
3124
3125 int
3126 wasapi_stream_get_latency(cubeb_stream * stm, uint32_t * latency)
3127 {
3128 XASSERT(stm && latency);
3129
3130 if (!has_output(stm)) {
3131 return CUBEB_ERROR;
3132 }
3133
3134 auto_lock lock(stm->stream_reset_lock);
3135
3136 /* The GetStreamLatency method only works if the
3137 AudioClient has been initialized. */
3138 if (!stm->output_client) {
3139 LOG("get_latency: No output_client.");
3140 return CUBEB_ERROR;
3141 }
3142
3143 REFERENCE_TIME latency_hns;
3144 HRESULT hr = stm->output_client->GetStreamLatency(&latency_hns);
3145 if (FAILED(hr)) {
3146 LOG("GetStreamLatency failed %lx.", hr);
3147 return CUBEB_ERROR;
3148 }
3149 // This happens on windows 10: no error, but always 0 for latency.
3150 if (latency_hns == 0) {
3151 LOG("GetStreamLatency returned 0, using workaround.");
3152 double delay_s = current_stream_delay(stm);
3153 // convert to sample-frames
3154 *latency = delay_s * stm->output_stream_params.rate;
3155 } else {
3156 *latency = hns_to_frames(stm, latency_hns);
3157 }
3158
3159 LOG("Output latency %u frames.", *latency);
3160
3161 return CUBEB_OK;
3162 }
3163
3164 int
3165 wasapi_stream_get_input_latency(cubeb_stream * stm, uint32_t * latency)
3166 {
3167 XASSERT(stm && latency);
3168
3169 if (!has_input(stm)) {
3170 LOG("Input latency queried on an output-only stream.");
3171 return CUBEB_ERROR;
3172 }
3173
3174 auto_lock lock(stm->stream_reset_lock);
3175
3176 if (stm->input_latency_hns == LATENCY_NOT_AVAILABLE_YET) {
3177 LOG("Input latency not available yet.");
3178 return CUBEB_ERROR;
3179 }
3180
3181 *latency = hns_to_frames(stm, stm->input_latency_hns);
3182
3183 return CUBEB_OK;
3184 }
3185
3186 int
3187 wasapi_stream_set_volume(cubeb_stream * stm, float volume)
3188 {
3189 auto_lock lock(stm->stream_reset_lock);
3190
3191 if (!has_output(stm)) {
3192 return CUBEB_ERROR;
3193 }
3194
3195 #ifdef CUBEB_WASAPI_USE_IAUDIOSTREAMVOLUME
3196 if (stream_set_volume(stm, volume) != CUBEB_OK) {
3197 return CUBEB_ERROR;
3198 }
3199 #endif
3200
3201 stm->volume = volume;
3202
3203 return CUBEB_OK;
3204 }
3205
3206 static char const *
3207 wstr_to_utf8(LPCWSTR str)
3208 {
3209 int size = ::WideCharToMultiByte(CP_UTF8, 0, str, -1, nullptr, 0, NULL, NULL);
3210 if (size <= 0) {
3211 return nullptr;
3212 }
3213
3214 char * ret = static_cast<char *>(malloc(size));
3215 ::WideCharToMultiByte(CP_UTF8, 0, str, -1, ret, size, NULL, NULL);
3216 return ret;
3217 }
3218
3219 static std::unique_ptr<wchar_t const[]>
3220 utf8_to_wstr(char const * str)
3221 {
3222 int size = ::MultiByteToWideChar(CP_UTF8, 0, str, -1, nullptr, 0);
3223 if (size <= 0) {
3224 return nullptr;
3225 }
3226
3227 std::unique_ptr<wchar_t[]> ret(new wchar_t[size]);
3228 ::MultiByteToWideChar(CP_UTF8, 0, str, -1, ret.get(), size);
3229 return ret;
3230 }
3231
3232 static com_ptr<IMMDevice>
3233 wasapi_get_device_node(IMMDeviceEnumerator * enumerator, IMMDevice * dev)
3234 {
3235 com_ptr<IMMDevice> ret;
3236 com_ptr<IDeviceTopology> devtopo;
3237 com_ptr<IConnector> connector;
3238
3239 if (SUCCEEDED(dev->Activate(__uuidof(IDeviceTopology), CLSCTX_ALL, NULL,
3240 devtopo.receive_vpp())) &&
3241 SUCCEEDED(devtopo->GetConnector(0, connector.receive()))) {
3242 wchar_t * tmp = nullptr;
3243 if (SUCCEEDED(connector->GetDeviceIdConnectedTo(&tmp))) {
3244 com_heap_ptr<wchar_t> filterid(tmp);
3245 if (FAILED(enumerator->GetDevice(filterid.get(), ret.receive())))
3246 ret = NULL;
3247 }
3248 }
3249
3250 return ret;
3251 }
3252
3253 static com_heap_ptr<wchar_t>
3254 wasapi_get_default_device_id(EDataFlow flow, ERole role,
3255 IMMDeviceEnumerator * enumerator)
3256 {
3257 com_ptr<IMMDevice> dev;
3258
3259 HRESULT hr = enumerator->GetDefaultAudioEndpoint(flow, role, dev.receive());
3260 if (SUCCEEDED(hr)) {
3261 wchar_t * tmp = nullptr;
3262 if (SUCCEEDED(dev->GetId(&tmp))) {
3263 com_heap_ptr<wchar_t> devid(tmp);
3264 return devid;
3265 }
3266 }
3267
3268 return nullptr;
3269 }
3270
3271 /* `ret` must be deallocated with `wasapi_destroy_device`, iff the return value
3272 * of this function is `CUBEB_OK`. */
3273 int
3274 wasapi_create_device(cubeb * ctx, cubeb_device_info & ret,
3275 IMMDeviceEnumerator * enumerator, IMMDevice * dev,
3276 wasapi_default_devices * defaults)
3277 {
3278 com_ptr<IMMEndpoint> endpoint;
3279 com_ptr<IMMDevice> devnode;
3280 com_ptr<IAudioClient> client;
3281 EDataFlow flow;
3282 DWORD state = DEVICE_STATE_NOTPRESENT;
3283 com_ptr<IPropertyStore> propstore;
3284 REFERENCE_TIME def_period, min_period;
3285 HRESULT hr;
3286
3287 XASSERT(enumerator && dev && defaults);
3288
3289 // zero-out to be able to safely delete the pointers to friendly_name and
3290 // group_id at all time in this function.
3291 PodZero(&ret, 1);
3292
3293 struct prop_variant : public PROPVARIANT {
3294 prop_variant() { PropVariantInit(this); }
3295 ~prop_variant() { PropVariantClear(this); }
3296 prop_variant(prop_variant const &) = delete;
3297 prop_variant & operator=(prop_variant const &) = delete;
3298 };
3299
3300 hr = dev->QueryInterface(IID_PPV_ARGS(endpoint.receive()));
3301 if (FAILED(hr)) {
3302 wasapi_destroy_device(&ret);
3303 return CUBEB_ERROR;
3304 }
3305
3306 hr = endpoint->GetDataFlow(&flow);
3307 if (FAILED(hr)) {
3308 wasapi_destroy_device(&ret);
3309 return CUBEB_ERROR;
3310 }
3311
3312 wchar_t * tmp = nullptr;
3313 hr = dev->GetId(&tmp);
3314 if (FAILED(hr)) {
3315 wasapi_destroy_device(&ret);
3316 return CUBEB_ERROR;
3317 }
3318 com_heap_ptr<wchar_t> device_id(tmp);
3319
3320 char const * device_id_intern = intern_device_id(ctx, device_id.get());
3321 if (!device_id_intern) {
3322 wasapi_destroy_device(&ret);
3323 return CUBEB_ERROR;
3324 }
3325
3326 hr = dev->OpenPropertyStore(STGM_READ, propstore.receive());
3327 if (FAILED(hr)) {
3328 wasapi_destroy_device(&ret);
3329 return CUBEB_ERROR;
3330 }
3331
3332 hr = dev->GetState(&state);
3333 if (FAILED(hr)) {
3334 wasapi_destroy_device(&ret);
3335 return CUBEB_ERROR;
3336 }
3337
3338 ret.device_id = device_id_intern;
3339 ret.devid = reinterpret_cast<cubeb_devid>(ret.device_id);
3340 prop_variant namevar;
3341 hr = propstore->GetValue(PKEY_Device_FriendlyName, &namevar);
3342 if (SUCCEEDED(hr) && namevar.vt == VT_LPWSTR) {
3343 ret.friendly_name = wstr_to_utf8(namevar.pwszVal);
3344 }
3345 if (!ret.friendly_name) {
3346 // This is not fatal, but a valid string is expected in all cases.
3347 char * empty = new char[1];
3348 empty[0] = '\0';
3349 ret.friendly_name = empty;
3350 }
3351
3352 devnode = wasapi_get_device_node(enumerator, dev);
3353 if (devnode) {
3354 com_ptr<IPropertyStore> ps;
3355 hr = devnode->OpenPropertyStore(STGM_READ, ps.receive());
3356 if (FAILED(hr)) {
3357 wasapi_destroy_device(&ret);
3358 return CUBEB_ERROR;
3359 }
3360
3361 prop_variant instancevar;
3362 hr = ps->GetValue(PKEY_Device_InstanceId, &instancevar);
3363 if (SUCCEEDED(hr) && instancevar.vt == VT_LPWSTR) {
3364 ret.group_id = wstr_to_utf8(instancevar.pwszVal);
3365 }
3366 }
3367
3368 if (!ret.group_id) {
3369 // This is not fatal, but a valid string is expected in all cases.
3370 char * empty = new char[1];
3371 empty[0] = '\0';
3372 ret.group_id = empty;
3373 }
3374
3375 ret.preferred = CUBEB_DEVICE_PREF_NONE;
3376 if (defaults->is_default(flow, eConsole, device_id.get())) {
3377 ret.preferred =
3378 (cubeb_device_pref)(ret.preferred | CUBEB_DEVICE_PREF_MULTIMEDIA |
3379 CUBEB_DEVICE_PREF_NOTIFICATION);
3380 } else if (defaults->is_default(flow, eCommunications, device_id.get())) {
3381 ret.preferred =
3382 (cubeb_device_pref)(ret.preferred | CUBEB_DEVICE_PREF_VOICE);
3383 }
3384
3385 if (flow == eRender) {
3386 ret.type = CUBEB_DEVICE_TYPE_OUTPUT;
3387 } else if (flow == eCapture) {
3388 ret.type = CUBEB_DEVICE_TYPE_INPUT;
3389 }
3390
3391 switch (state) {
3392 case DEVICE_STATE_ACTIVE:
3393 ret.state = CUBEB_DEVICE_STATE_ENABLED;
3394 break;
3395 case DEVICE_STATE_UNPLUGGED:
3396 ret.state = CUBEB_DEVICE_STATE_UNPLUGGED;
3397 break;
3398 default:
3399 ret.state = CUBEB_DEVICE_STATE_DISABLED;
3400 break;
3401 };
3402
3403 ret.format = static_cast<cubeb_device_fmt>(CUBEB_DEVICE_FMT_F32NE |
3404 CUBEB_DEVICE_FMT_S16NE);
3405 ret.default_format = CUBEB_DEVICE_FMT_F32NE;
3406 prop_variant fmtvar;
3407 hr = propstore->GetValue(PKEY_AudioEngine_DeviceFormat, &fmtvar);
3408 if (SUCCEEDED(hr) && fmtvar.vt == VT_BLOB) {
3409 if (fmtvar.blob.cbSize == sizeof(PCMWAVEFORMAT)) {
3410 const PCMWAVEFORMAT * pcm =
3411 reinterpret_cast<const PCMWAVEFORMAT *>(fmtvar.blob.pBlobData);
3412
3413 ret.max_rate = ret.min_rate = ret.default_rate = pcm->wf.nSamplesPerSec;
3414 ret.max_channels = pcm->wf.nChannels;
3415 } else if (fmtvar.blob.cbSize >= sizeof(WAVEFORMATEX)) {
3416 WAVEFORMATEX * wfx =
3417 reinterpret_cast<WAVEFORMATEX *>(fmtvar.blob.pBlobData);
3418
3419 if (fmtvar.blob.cbSize >= sizeof(WAVEFORMATEX) + wfx->cbSize ||
3420 wfx->wFormatTag == WAVE_FORMAT_PCM) {
3421 ret.max_rate = ret.min_rate = ret.default_rate = wfx->nSamplesPerSec;
3422 ret.max_channels = wfx->nChannels;
3423 }
3424 }
3425 }
3426
3427 if (SUCCEEDED(dev->Activate(__uuidof(IAudioClient), CLSCTX_INPROC_SERVER,
3428 NULL, client.receive_vpp())) &&
3429 SUCCEEDED(client->GetDevicePeriod(&def_period, &min_period))) {
3430 ret.latency_lo = hns_to_frames(ret.default_rate, min_period);
3431 ret.latency_hi = hns_to_frames(ret.default_rate, def_period);
3432 } else {
3433 ret.latency_lo = 0;
3434 ret.latency_hi = 0;
3435 }
3436
3437 XASSERT(ret.friendly_name && ret.group_id);
3438
3439 return CUBEB_OK;
3440 }
3441
3442 void
3443 wasapi_destroy_device(cubeb_device_info * device)
3444 {
3445 delete[] device->friendly_name;
3446 delete[] device->group_id;
3447 }
3448
3449 static int
3450 wasapi_enumerate_devices_internal(cubeb * context, cubeb_device_type type,
3451 cubeb_device_collection * out,
3452 DWORD state_mask)
3453 {
3454 com_ptr<IMMDeviceEnumerator> enumerator;
3455 com_ptr<IMMDeviceCollection> collection;
3456 HRESULT hr;
3457 UINT cc, i;
3458 EDataFlow flow;
3459
3460 hr =
3461 CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER,
3462 IID_PPV_ARGS(enumerator.receive()));
3463 if (FAILED(hr)) {
3464 LOG("Could not get device enumerator: %lx", hr);
3465 return CUBEB_ERROR;
3466 }
3467
3468 wasapi_default_devices default_devices(enumerator.get());
3469
3470 if (type == CUBEB_DEVICE_TYPE_OUTPUT) {
3471 flow = eRender;
3472 } else if (type == CUBEB_DEVICE_TYPE_INPUT) {
3473 flow = eCapture;
3474 } else if (type & (CUBEB_DEVICE_TYPE_INPUT | CUBEB_DEVICE_TYPE_OUTPUT)) {
3475 flow = eAll;
3476 } else {
3477 return CUBEB_ERROR;
3478 }
3479
3480 hr = enumerator->EnumAudioEndpoints(flow, state_mask, collection.receive());
3481 if (FAILED(hr)) {
3482 LOG("Could not enumerate audio endpoints: %lx", hr);
3483 return CUBEB_ERROR;
3484 }
3485
3486 hr = collection->GetCount(&cc);
3487 if (FAILED(hr)) {
3488 LOG("IMMDeviceCollection::GetCount() failed: %lx", hr);
3489 return CUBEB_ERROR;
3490 }
3491 cubeb_device_info * devices = new cubeb_device_info[cc];
3492 if (!devices)
3493 return CUBEB_ERROR;
3494
3495 PodZero(devices, cc);
3496 out->count = 0;
3497 for (i = 0; i < cc; i++) {
3498 com_ptr<IMMDevice> dev;
3499 hr = collection->Item(i, dev.receive());
3500 if (FAILED(hr)) {
3501 LOG("IMMDeviceCollection::Item(%u) failed: %lx", i - 1, hr);
3502 continue;
3503 }
3504 if (wasapi_create_device(context, devices[out->count], enumerator.get(),
3505 dev.get(), &default_devices) == CUBEB_OK) {
3506 out->count += 1;
3507 }
3508 }
3509
3510 out->device = devices;
3511 return CUBEB_OK;
3512 }
3513
3514 static int
3515 wasapi_enumerate_devices(cubeb * context, cubeb_device_type type,
3516 cubeb_device_collection * out)
3517 {
3518 return wasapi_enumerate_devices_internal(
3519 context, type, out,
3520 DEVICE_STATE_ACTIVE | DEVICE_STATE_DISABLED | DEVICE_STATE_UNPLUGGED);
3521 }
3522
3523 static int
3524 wasapi_device_collection_destroy(cubeb * /*ctx*/,
3525 cubeb_device_collection * collection)
3526 {
3527 XASSERT(collection);
3528
3529 for (size_t n = 0; n < collection->count; n++) {
3530 cubeb_device_info & dev = collection->device[n];
3531 wasapi_destroy_device(&dev);
3532 }
3533
3534 delete[] collection->device;
3535 return CUBEB_OK;
3536 }
3537
3538 static int
3539 wasapi_register_device_collection_changed(
3540 cubeb * context, cubeb_device_type devtype,
3541 cubeb_device_collection_changed_callback collection_changed_callback,
3542 void * user_ptr)
3543 {
3544 auto_lock lock(context->lock);
3545 if (devtype == CUBEB_DEVICE_TYPE_UNKNOWN) {
3546 return CUBEB_ERROR_INVALID_PARAMETER;
3547 }
3548
3549 if (collection_changed_callback) {
3550 // Make sure it has been unregistered first.
3551 XASSERT(((devtype & CUBEB_DEVICE_TYPE_INPUT) &&
3552 !context->input_collection_changed_callback) ||
3553 ((devtype & CUBEB_DEVICE_TYPE_OUTPUT) &&
3554 !context->output_collection_changed_callback));
3555
3556 // Stop the notification client. Notifications arrive on
3557 // a separate thread. We stop them here to avoid
3558 // synchronization issues during the update.
3559 if (context->device_collection_enumerator.get()) {
3560 HRESULT hr = unregister_collection_notification_client(context);
3561 if (FAILED(hr)) {
3562 return CUBEB_ERROR;
3563 }
3564 }
3565
3566 if (devtype & CUBEB_DEVICE_TYPE_INPUT) {
3567 context->input_collection_changed_callback = collection_changed_callback;
3568 context->input_collection_changed_user_ptr = user_ptr;
3569 }
3570 if (devtype & CUBEB_DEVICE_TYPE_OUTPUT) {
3571 context->output_collection_changed_callback = collection_changed_callback;
3572 context->output_collection_changed_user_ptr = user_ptr;
3573 }
3574
3575 HRESULT hr = register_collection_notification_client(context);
3576 if (FAILED(hr)) {
3577 return CUBEB_ERROR;
3578 }
3579 } else {
3580 if (!context->device_collection_enumerator.get()) {
3581 // Already unregistered, ignore it.
3582 return CUBEB_OK;
3583 }
3584
3585 HRESULT hr = unregister_collection_notification_client(context);
3586 if (FAILED(hr)) {
3587 return CUBEB_ERROR;
3588 }
3589 if (devtype & CUBEB_DEVICE_TYPE_INPUT) {
3590 context->input_collection_changed_callback = nullptr;
3591 context->input_collection_changed_user_ptr = nullptr;
3592 }
3593 if (devtype & CUBEB_DEVICE_TYPE_OUTPUT) {
3594 context->output_collection_changed_callback = nullptr;
3595 context->output_collection_changed_user_ptr = nullptr;
3596 }
3597
3598 // If after the updates we still have registered
3599 // callbacks restart the notification client.
3600 if (context->input_collection_changed_callback ||
3601 context->output_collection_changed_callback) {
3602 hr = register_collection_notification_client(context);
3603 if (FAILED(hr)) {
3604 return CUBEB_ERROR;
3605 }
3606 }
3607 }
3608
3609 return CUBEB_OK;
3610 }
3611
3612 cubeb_ops const wasapi_ops = {
3613 /*.init =*/wasapi_init,
3614 /*.get_backend_id =*/wasapi_get_backend_id,
3615 /*.get_max_channel_count =*/wasapi_get_max_channel_count,
3616 /*.get_min_latency =*/wasapi_get_min_latency,
3617 /*.get_preferred_sample_rate =*/wasapi_get_preferred_sample_rate,
3618 /*.get_supported_input_processing_params =*/NULL,
3619 /*.enumerate_devices =*/wasapi_enumerate_devices,
3620 /*.device_collection_destroy =*/wasapi_device_collection_destroy,
3621 /*.destroy =*/wasapi_destroy,
3622 /*.stream_init =*/wasapi_stream_init,
3623 /*.stream_destroy =*/wasapi_stream_destroy,
3624 /*.stream_start =*/wasapi_stream_start,
3625 /*.stream_stop =*/wasapi_stream_stop,
3626 /*.stream_get_position =*/wasapi_stream_get_position,
3627 /*.stream_get_latency =*/wasapi_stream_get_latency,
3628 /*.stream_get_input_latency =*/wasapi_stream_get_input_latency,
3629 /*.stream_set_volume =*/wasapi_stream_set_volume,
3630 /*.stream_set_name =*/NULL,
3631 /*.stream_get_current_device =*/NULL,
3632 /*.stream_set_input_mute =*/NULL,
3633 /*.stream_set_input_processing_params =*/NULL,
3634 /*.stream_device_destroy =*/NULL,
3635 /*.stream_register_device_changed_callback =*/NULL,
3636 /*.register_device_collection_changed =*/
3637 wasapi_register_device_collection_changed,
3638 };
3639 } // namespace