2 * Copyright (C) 2008 Ole André Vadla Ravnås <ole.andre.ravnas@tandberg.com>
3 * Copyright (C) 2018 Centricular Ltd.
4 * Author: Nirbheek Chauhan <nirbheek@centricular.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public
17 * License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
25 /* Note: initguid.h can not be included in gstwasapiutil.h, otherwise a
26 * symbol redefinition error will be raised.
27 * initguid.h must be included in the C file before mmdeviceapi.h
28 * which is included in gstwasapiutil.h.
33 #include "gstwasapiutil.h"
34 #include "gstwasapidevice.h"
36 GST_DEBUG_CATEGORY_EXTERN (gst_wasapi_debug);
37 #define GST_CAT_DEFAULT gst_wasapi_debug
39 /* This was only added to MinGW in ~2015 and our Cerbero toolchain is too old */
41 #include <functiondiscoverykeys_devpkey.h>
42 #elif !defined(PKEY_Device_FriendlyName)
45 DEFINE_PROPERTYKEY (PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,
46 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14);
47 DEFINE_PROPERTYKEY (PKEY_AudioEngine_DeviceFormat, 0xf19f064d, 0x82c, 0x4e27,
48 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c, 0);
51 /* __uuidof is only available in C++, so we hard-code the GUID values for all
52 * these. This is ok because these are ABI. */
53 const CLSID CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c,
54 {0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e}
57 const IID IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,
58 {0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6}
61 const IID IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089,
62 {0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5}
65 const IID IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32,
66 {0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2}
69 const IID IID_IAudioClient3 = { 0x7ed4ee07, 0x8e67, 0x4cd4,
70 {0x8c, 0x1a, 0x2b, 0x7a, 0x59, 0x87, 0xad, 0x42}
73 const IID IID_IAudioClock = { 0xcd63314f, 0x3fba, 0x4a1b,
74 {0x81, 0x2c, 0xef, 0x96, 0x35, 0x87, 0x28, 0xe7}
77 const IID IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0,
78 {0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17}
81 const IID IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,
82 {0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2}
89 GstAudioChannelPosition gst_pos;
90 } wasapi_to_gst_pos[] = {
91 {SPEAKER_FRONT_LEFT, GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT},
92 {SPEAKER_FRONT_RIGHT, GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT},
93 {SPEAKER_FRONT_CENTER, GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER},
94 {SPEAKER_LOW_FREQUENCY, GST_AUDIO_CHANNEL_POSITION_LFE1},
95 {SPEAKER_BACK_LEFT, GST_AUDIO_CHANNEL_POSITION_REAR_LEFT},
96 {SPEAKER_BACK_RIGHT, GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT},
97 {SPEAKER_FRONT_LEFT_OF_CENTER,
98 GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER},
99 {SPEAKER_FRONT_RIGHT_OF_CENTER,
100 GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER},
101 {SPEAKER_BACK_CENTER, GST_AUDIO_CHANNEL_POSITION_REAR_CENTER},
102 /* Enum values diverge from this point onwards */
103 {SPEAKER_SIDE_LEFT, GST_AUDIO_CHANNEL_POSITION_SIDE_LEFT},
104 {SPEAKER_SIDE_RIGHT, GST_AUDIO_CHANNEL_POSITION_SIDE_RIGHT},
105 {SPEAKER_TOP_CENTER, GST_AUDIO_CHANNEL_POSITION_TOP_CENTER},
106 {SPEAKER_TOP_FRONT_LEFT, GST_AUDIO_CHANNEL_POSITION_TOP_FRONT_LEFT},
107 {SPEAKER_TOP_FRONT_CENTER, GST_AUDIO_CHANNEL_POSITION_TOP_FRONT_CENTER},
108 {SPEAKER_TOP_FRONT_RIGHT, GST_AUDIO_CHANNEL_POSITION_TOP_FRONT_RIGHT},
109 {SPEAKER_TOP_BACK_LEFT, GST_AUDIO_CHANNEL_POSITION_TOP_REAR_LEFT},
110 {SPEAKER_TOP_BACK_CENTER, GST_AUDIO_CHANNEL_POSITION_TOP_REAR_CENTER},
111 {SPEAKER_TOP_BACK_RIGHT, GST_AUDIO_CHANNEL_POSITION_TOP_REAR_RIGHT}
115 static int windows_major_version = 0;
118 gst_wasapi_util_have_audioclient3 (void)
120 if (windows_major_version > 0)
121 return windows_major_version == 10;
123 if (g_getenv ("GST_WASAPI_DISABLE_AUDIOCLIENT3") != NULL) {
124 windows_major_version = 6;
128 /* https://msdn.microsoft.com/en-us/library/windows/desktop/ms724834(v=vs.85).aspx */
129 windows_major_version = 6;
130 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
131 windows_major_version = 10;
133 return windows_major_version == 10;
137 gst_wasapi_device_role_get_type (void)
139 static const GEnumValue values[] = {
140 {GST_WASAPI_DEVICE_ROLE_CONSOLE,
141 "Games, system notifications, voice commands", "console"},
142 {GST_WASAPI_DEVICE_ROLE_MULTIMEDIA, "Music, movies, recorded media",
144 {GST_WASAPI_DEVICE_ROLE_COMMS, "Voice communications", "comms"},
149 if (g_once_init_enter ((gsize *) & id)) {
152 _id = g_enum_register_static ("GstWasapiDeviceRole", values);
154 g_once_init_leave ((gsize *) & id, _id);
161 gst_wasapi_device_role_to_erole (gint role)
164 case GST_WASAPI_DEVICE_ROLE_CONSOLE:
166 case GST_WASAPI_DEVICE_ROLE_MULTIMEDIA:
168 case GST_WASAPI_DEVICE_ROLE_COMMS:
169 return eCommunications;
171 g_assert_not_reached ();
178 gst_wasapi_erole_to_device_role (gint erole)
182 return GST_WASAPI_DEVICE_ROLE_CONSOLE;
184 return GST_WASAPI_DEVICE_ROLE_MULTIMEDIA;
185 case eCommunications:
186 return GST_WASAPI_DEVICE_ROLE_COMMS;
188 g_assert_not_reached ();
195 hresult_to_string_fallback (HRESULT hr)
197 const gchar *s = "unknown error";
200 case AUDCLNT_E_NOT_INITIALIZED:
201 s = "AUDCLNT_E_NOT_INITIALIZED";
203 case AUDCLNT_E_ALREADY_INITIALIZED:
204 s = "AUDCLNT_E_ALREADY_INITIALIZED";
206 case AUDCLNT_E_WRONG_ENDPOINT_TYPE:
207 s = "AUDCLNT_E_WRONG_ENDPOINT_TYPE";
209 case AUDCLNT_E_DEVICE_INVALIDATED:
210 s = "AUDCLNT_E_DEVICE_INVALIDATED";
212 case AUDCLNT_E_NOT_STOPPED:
213 s = "AUDCLNT_E_NOT_STOPPED";
215 case AUDCLNT_E_BUFFER_TOO_LARGE:
216 s = "AUDCLNT_E_BUFFER_TOO_LARGE";
218 case AUDCLNT_E_OUT_OF_ORDER:
219 s = "AUDCLNT_E_OUT_OF_ORDER";
221 case AUDCLNT_E_UNSUPPORTED_FORMAT:
222 s = "AUDCLNT_E_UNSUPPORTED_FORMAT";
224 case AUDCLNT_E_INVALID_DEVICE_PERIOD:
225 s = "AUDCLNT_E_INVALID_DEVICE_PERIOD";
227 case AUDCLNT_E_INVALID_SIZE:
228 s = "AUDCLNT_E_INVALID_SIZE";
230 case AUDCLNT_E_DEVICE_IN_USE:
231 s = "AUDCLNT_E_DEVICE_IN_USE";
233 case AUDCLNT_E_BUFFER_OPERATION_PENDING:
234 s = "AUDCLNT_E_BUFFER_OPERATION_PENDING";
236 case AUDCLNT_E_BUFFER_SIZE_ERROR:
237 s = "AUDCLNT_E_BUFFER_SIZE_ERROR";
239 case AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED:
240 s = "AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED";
242 case AUDCLNT_E_THREAD_NOT_REGISTERED:
243 s = "AUDCLNT_E_THREAD_NOT_REGISTERED";
245 case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED:
246 s = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED";
248 case AUDCLNT_E_ENDPOINT_CREATE_FAILED:
249 s = "AUDCLNT_E_ENDPOINT_CREATE_FAILED";
251 case AUDCLNT_E_SERVICE_NOT_RUNNING:
252 s = "AUDCLNT_E_SERVICE_NOT_RUNNING";
254 case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED:
255 s = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED";
257 case AUDCLNT_E_EXCLUSIVE_MODE_ONLY:
258 s = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY";
260 case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL:
261 s = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL";
263 case AUDCLNT_E_EVENTHANDLE_NOT_SET:
264 s = "AUDCLNT_E_EVENTHANDLE_NOT_SET";
266 case AUDCLNT_E_INCORRECT_BUFFER_SIZE:
267 s = "AUDCLNT_E_INCORRECT_BUFFER_SIZE";
269 case AUDCLNT_E_CPUUSAGE_EXCEEDED:
270 s = "AUDCLNT_E_CPUUSAGE_EXCEEDED";
272 case AUDCLNT_S_BUFFER_EMPTY:
273 s = "AUDCLNT_S_BUFFER_EMPTY";
275 case AUDCLNT_S_THREAD_ALREADY_REGISTERED:
276 s = "AUDCLNT_S_THREAD_ALREADY_REGISTERED";
278 case AUDCLNT_S_POSITION_STALLED:
279 s = "AUDCLNT_S_POSITION_STALLED";
293 gst_wasapi_util_hresult_to_string (HRESULT hr)
295 gchar *error_text = NULL;
297 error_text = g_win32_error_message ((gint) hr);
298 /* g_win32_error_message() seems to be returning empty string for
300 if (!error_text || strlen (error_text) == 0) {
302 error_text = g_strdup (hresult_to_string_fallback (hr));
308 static IMMDeviceEnumerator *
309 gst_wasapi_util_get_device_enumerator (GstObject * self)
312 IMMDeviceEnumerator *enumerator = NULL;
314 hr = CoCreateInstance (&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL,
315 &IID_IMMDeviceEnumerator, (void **) &enumerator);
316 HR_FAILED_RET (hr, CoCreateInstance (MMDeviceEnumerator), NULL);
322 gst_wasapi_util_get_devices (GstObject * self, gboolean active,
325 gboolean res = FALSE;
326 static GstStaticCaps scaps = GST_STATIC_CAPS (GST_WASAPI_STATIC_CAPS);
327 DWORD dwStateMask = active ? DEVICE_STATE_ACTIVE : DEVICE_STATEMASK_ALL;
328 IMMDeviceCollection *device_collection = NULL;
329 IMMDeviceEnumerator *enumerator = NULL;
330 const gchar *device_class, *element_name;
336 enumerator = gst_wasapi_util_get_device_enumerator (self);
340 hr = IMMDeviceEnumerator_EnumAudioEndpoints (enumerator, eAll, dwStateMask,
342 HR_FAILED_GOTO (hr, IMMDeviceEnumerator::EnumAudioEndpoints, err);
344 hr = IMMDeviceCollection_GetCount (device_collection, &count);
345 HR_FAILED_GOTO (hr, IMMDeviceCollection::GetCount, err);
347 /* Create a GList of GstDevices* to return */
348 for (ii = 0; ii < count; ii++) {
349 IMMDevice *item = NULL;
350 IMMEndpoint *endpoint = NULL;
351 IAudioClient *client = NULL;
352 IPropertyStore *prop_store = NULL;
353 WAVEFORMATEX *format = NULL;
354 gchar *description = NULL;
363 hr = IMMDeviceCollection_Item (device_collection, ii, &item);
367 hr = IMMDevice_QueryInterface (item, &IID_IMMEndpoint, (void **) &endpoint);
371 hr = IMMEndpoint_GetDataFlow (endpoint, &dataflow);
375 if (dataflow == eRender) {
376 device_class = "Audio/Sink";
377 element_name = "wasapisink";
379 device_class = "Audio/Source";
380 element_name = "wasapisrc";
383 PropVariantInit (&var);
385 hr = IMMDevice_GetId (item, &wstrid);
388 strid = g_utf16_to_utf8 (wstrid, -1, NULL, NULL, NULL);
389 CoTaskMemFree (wstrid);
391 hr = IMMDevice_OpenPropertyStore (item, STGM_READ, &prop_store);
395 /* NOTE: More properties can be added as needed from here:
396 * https://msdn.microsoft.com/en-us/library/windows/desktop/dd370794(v=vs.85).aspx */
397 hr = IPropertyStore_GetValue (prop_store, &PKEY_Device_FriendlyName, &var);
400 description = g_utf16_to_utf8 (var.pwszVal, -1, NULL, NULL, NULL);
401 PropVariantClear (&var);
403 /* Get the audio client so we can fetch the mix format for shared mode
404 * to get the device format for exclusive mode (or something close to that)
405 * fetch PKEY_AudioEngine_DeviceFormat from the property store. */
406 hr = IMMDevice_Activate (item, &IID_IAudioClient, CLSCTX_ALL, NULL,
409 gchar *msg = gst_wasapi_util_hresult_to_string (hr);
410 GST_ERROR_OBJECT (self, "IMMDevice::Activate (IID_IAudioClient) failed"
411 "on %s: %s", strid, msg);
416 hr = IAudioClient_GetMixFormat (client, &format);
417 if (hr != S_OK || format == NULL) {
418 gchar *msg = gst_wasapi_util_hresult_to_string (hr);
419 GST_ERROR_OBJECT (self, "GetMixFormat failed on %s: %s", strid, msg);
424 if (!gst_wasapi_util_parse_waveformatex ((WAVEFORMATEXTENSIBLE *) format,
425 gst_static_caps_get (&scaps), &caps, NULL))
428 /* Set some useful properties */
429 props = gst_structure_new ("wasapi-proplist",
430 "device.api", G_TYPE_STRING, "wasapi",
431 "device.strid", G_TYPE_STRING, GST_STR_NULL (strid),
432 "wasapi.device.description", G_TYPE_STRING, description, NULL);
434 device = g_object_new (GST_TYPE_WASAPI_DEVICE, "device", strid,
435 "display-name", description, "caps", caps,
436 "device-class", device_class, "properties", props, NULL);
437 GST_WASAPI_DEVICE (device)->element = element_name;
439 gst_structure_free (props);
440 gst_caps_unref (caps);
441 *devices = g_list_prepend (*devices, device);
444 PropVariantClear (&var);
446 IUnknown_Release (prop_store);
448 IUnknown_Release (endpoint);
450 IUnknown_Release (client);
452 IUnknown_Release (item);
454 g_free (description);
463 IUnknown_Release (enumerator);
464 if (device_collection)
465 IUnknown_Release (device_collection);
470 gst_wasapi_util_get_device_format (GstElement * self,
471 gint device_mode, IMMDevice * device, IAudioClient * client,
472 WAVEFORMATEX ** ret_format)
474 WAVEFORMATEX *format;
479 hr = IAudioClient_GetMixFormat (client, &format);
480 HR_FAILED_RET (hr, IAudioClient::GetMixFormat, FALSE);
482 /* WASAPI always accepts the format returned by GetMixFormat in shared mode */
483 if (device_mode == AUDCLNT_SHAREMODE_SHARED)
486 /* WASAPI may or may not support this format in exclusive mode */
487 hr = IAudioClient_IsFormatSupported (client, AUDCLNT_SHAREMODE_EXCLUSIVE,
492 CoTaskMemFree (format);
494 /* Open the device property store, and get the format that WASAPI has been
495 * using for sending data to the device */
498 IPropertyStore *prop_store = NULL;
500 hr = IMMDevice_OpenPropertyStore (device, STGM_READ, &prop_store);
501 HR_FAILED_RET (hr, IMMDevice::OpenPropertyStore, FALSE);
503 hr = IPropertyStore_GetValue (prop_store, &PKEY_AudioEngine_DeviceFormat,
506 gchar *msg = gst_wasapi_util_hresult_to_string (hr);
507 GST_ERROR_OBJECT (self, "GetValue failed: %s", msg);
509 IUnknown_Release (prop_store);
513 format = malloc (var.blob.cbSize);
514 memcpy (format, var.blob.pBlobData, var.blob.cbSize);
516 PropVariantClear (&var);
517 IUnknown_Release (prop_store);
520 /* WASAPI may or may not support this format in exclusive mode */
521 hr = IAudioClient_IsFormatSupported (client, AUDCLNT_SHAREMODE_EXCLUSIVE,
526 GST_ERROR_OBJECT (self, "AudioEngine DeviceFormat not supported");
531 *ret_format = format;
536 gst_wasapi_util_get_device_client (GstElement * self,
537 gint data_flow, gint role, const wchar_t * device_strid,
538 IMMDevice ** ret_device, IAudioClient ** ret_client)
540 gboolean res = FALSE;
542 IMMDeviceEnumerator *enumerator = NULL;
543 IMMDevice *device = NULL;
544 IAudioClient *client = NULL;
546 if (!(enumerator = gst_wasapi_util_get_device_enumerator (GST_OBJECT (self))))
550 hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint (enumerator, data_flow,
552 HR_FAILED_GOTO (hr, IMMDeviceEnumerator::GetDefaultAudioEndpoint, beach);
554 hr = IMMDeviceEnumerator_GetDevice (enumerator, device_strid, &device);
556 gchar *msg = gst_wasapi_util_hresult_to_string (hr);
557 GST_ERROR_OBJECT (self, "IMMDeviceEnumerator::GetDevice (%S) failed"
558 ": %s", device_strid, msg);
564 if (gst_wasapi_util_have_audioclient3 ())
565 hr = IMMDevice_Activate (device, &IID_IAudioClient3, CLSCTX_ALL, NULL,
568 hr = IMMDevice_Activate (device, &IID_IAudioClient, CLSCTX_ALL, NULL,
570 HR_FAILED_GOTO (hr, IMMDevice::Activate (IID_IAudioClient), beach);
572 IUnknown_AddRef (client);
573 IUnknown_AddRef (device);
574 *ret_client = client;
575 *ret_device = device;
581 IUnknown_Release (client);
584 IUnknown_Release (device);
586 if (enumerator != NULL)
587 IUnknown_Release (enumerator);
593 gst_wasapi_util_get_render_client (GstElement * self, IAudioClient * client,
594 IAudioRenderClient ** ret_render_client)
596 gboolean res = FALSE;
598 IAudioRenderClient *render_client = NULL;
600 hr = IAudioClient_GetService (client, &IID_IAudioRenderClient,
601 (void **) &render_client);
602 HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
604 *ret_render_client = render_client;
612 gst_wasapi_util_get_capture_client (GstElement * self, IAudioClient * client,
613 IAudioCaptureClient ** ret_capture_client)
615 gboolean res = FALSE;
617 IAudioCaptureClient *capture_client = NULL;
619 hr = IAudioClient_GetService (client, &IID_IAudioCaptureClient,
620 (void **) &capture_client);
621 HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
623 *ret_capture_client = capture_client;
631 gst_wasapi_util_get_clock (GstElement * self, IAudioClient * client,
632 IAudioClock ** ret_clock)
634 gboolean res = FALSE;
636 IAudioClock *clock = NULL;
638 hr = IAudioClient_GetService (client, &IID_IAudioClock, (void **) &clock);
639 HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
649 gst_waveformatex_to_audio_format (WAVEFORMATEXTENSIBLE * format)
651 const gchar *fmt_str = NULL;
652 GstAudioFormat fmt = GST_AUDIO_FORMAT_UNKNOWN;
654 if (format->Format.wFormatTag == WAVE_FORMAT_PCM) {
655 fmt = gst_audio_format_build_integer (TRUE, G_LITTLE_ENDIAN,
656 format->Format.wBitsPerSample, format->Format.wBitsPerSample);
657 } else if (format->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
658 if (format->Format.wBitsPerSample == 32)
659 fmt = GST_AUDIO_FORMAT_F32LE;
660 else if (format->Format.wBitsPerSample == 64)
661 fmt = GST_AUDIO_FORMAT_F64LE;
662 } else if (format->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
663 if (IsEqualGUID (&format->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
664 fmt = gst_audio_format_build_integer (TRUE, G_LITTLE_ENDIAN,
665 format->Format.wBitsPerSample, format->Samples.wValidBitsPerSample);
666 } else if (IsEqualGUID (&format->SubFormat,
667 &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
668 if (format->Format.wBitsPerSample == 32
669 && format->Samples.wValidBitsPerSample == 32)
670 fmt = GST_AUDIO_FORMAT_F32LE;
671 else if (format->Format.wBitsPerSample == 64 &&
672 format->Samples.wValidBitsPerSample == 64)
673 fmt = GST_AUDIO_FORMAT_F64LE;
677 if (fmt != GST_AUDIO_FORMAT_UNKNOWN)
678 fmt_str = gst_audio_format_to_string (fmt);
684 gst_wasapi_util_channel_position_all_none (guint channels,
685 GstAudioChannelPosition * position)
688 for (ii = 0; ii < channels; ii++)
689 position[ii] = GST_AUDIO_CHANNEL_POSITION_NONE;
692 /* Parse WAVEFORMATEX to get the gstreamer channel mask, and the wasapi channel
693 * positions so GstAudioRingbuffer can reorder the audio data to match the
694 * gstreamer channel order. */
696 gst_wasapi_util_waveformatex_to_channel_mask (WAVEFORMATEXTENSIBLE * format,
697 GstAudioChannelPosition ** out_position)
701 WORD nChannels = format->Format.nChannels;
702 DWORD dwChannelMask = format->dwChannelMask;
703 GstAudioChannelPosition *pos = NULL;
705 pos = g_new (GstAudioChannelPosition, nChannels);
706 gst_wasapi_util_channel_position_all_none (nChannels, pos);
708 /* Too many channels, have to assume that they are all non-positional */
709 if (nChannels > G_N_ELEMENTS (wasapi_to_gst_pos)) {
710 GST_INFO ("Got too many (%i) channels, assuming non-positional", nChannels);
714 /* Too many bits in the channel mask, and the bits don't match nChannels */
715 if (dwChannelMask >> (G_N_ELEMENTS (wasapi_to_gst_pos) + 1) != 0) {
716 GST_WARNING ("Too many bits in channel mask (%lu), assuming "
717 "non-positional", dwChannelMask);
721 /* Map WASAPI's channel mask to Gstreamer's channel mask and positions.
722 * If the no. of bits in the mask > nChannels, we will ignore the extra. */
723 for (ii = 0, ch = 0; ii < G_N_ELEMENTS (wasapi_to_gst_pos) && ch < nChannels;
725 if (!(dwChannelMask & wasapi_to_gst_pos[ii].wasapi_pos))
726 /* no match, try next */
728 mask |= G_GUINT64_CONSTANT (1) << wasapi_to_gst_pos[ii].gst_pos;
729 pos[ch++] = wasapi_to_gst_pos[ii].gst_pos;
732 /* XXX: Warn if some channel masks couldn't be mapped? */
734 GST_DEBUG ("Converted WASAPI mask 0x%" G_GINT64_MODIFIER "x -> 0x%"
735 G_GINT64_MODIFIER "x", (guint64) dwChannelMask, (guint64) mask);
744 gst_wasapi_util_parse_waveformatex (WAVEFORMATEXTENSIBLE * format,
745 GstCaps * template_caps, GstCaps ** out_caps,
746 GstAudioChannelPosition ** out_positions)
750 guint64 channel_mask;
754 /* TODO: handle SPDIF and other encoded formats */
756 /* 1 or 2 channels <= 16 bits sample size OR
757 * 1 or 2 channels > 16 bits sample size or >2 channels */
758 if (format->Format.wFormatTag != WAVE_FORMAT_PCM &&
759 format->Format.wFormatTag != WAVE_FORMAT_IEEE_FLOAT &&
760 format->Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
761 /* Unhandled format tag */
764 /* WASAPI can only tell us one canonical mix format that it will accept. The
765 * alternative is calling IsFormatSupported on all combinations of formats.
766 * Instead, it's simpler and faster to require conversion inside gstreamer */
767 afmt = gst_waveformatex_to_audio_format (format);
771 *out_caps = gst_caps_copy (template_caps);
773 /* This will always return something that might be usable */
775 gst_wasapi_util_waveformatex_to_channel_mask (format, out_positions);
777 for (ii = 0; ii < gst_caps_get_size (*out_caps); ii++) {
778 GstStructure *s = gst_caps_get_structure (*out_caps, ii);
780 gst_structure_set (s,
781 "format", G_TYPE_STRING, afmt,
782 "channels", G_TYPE_INT, format->Format.nChannels,
783 "rate", G_TYPE_INT, format->Format.nSamplesPerSec, NULL);
786 gst_structure_set (s,
787 "channel-mask", GST_TYPE_BITMASK, channel_mask, NULL);
795 gst_wasapi_util_get_best_buffer_sizes (GstAudioRingBufferSpec * spec,
796 gboolean exclusive, REFERENCE_TIME default_period,
797 REFERENCE_TIME min_period, REFERENCE_TIME * ret_period,
798 REFERENCE_TIME * ret_buffer_duration)
800 REFERENCE_TIME use_period, use_buffer;
802 /* Figure out what integral device period to use as the base */
804 /* Exclusive mode can run at multiples of either the minimum period or the
805 * default period; these are on the hardware ringbuffer */
806 if (spec->latency_time * 10 > default_period)
807 use_period = default_period;
809 use_period = min_period;
811 /* Shared mode always runs at the default period, so if we want a larger
812 * period (for lower CPU usage), we do it as a multiple of that */
813 use_period = default_period;
816 /* Ensure that the period (latency_time) used is an integral multiple of
817 * either the default period or the minimum period */
818 use_period = use_period * MAX ((spec->latency_time * 10) / use_period, 1);
821 /* Buffer duration is the same as the period in exclusive mode. The
822 * hardware is always writing out one buffer (of size *ret_period), and
823 * we're writing to the other one. */
824 use_buffer = use_period;
826 /* Ask WASAPI to create a software ringbuffer of at least this size; it may
827 * be larger so the actual buffer time may be different, which is why after
828 * initialization we read the buffer duration actually in-use and set
829 * segsize/segtotal from that. */
830 use_buffer = spec->buffer_time * 10;
831 /* Has to be at least twice the period */
832 if (use_buffer < 2 * use_period)
833 use_buffer = 2 * use_period;
836 *ret_period = use_period;
837 *ret_buffer_duration = use_buffer;
841 gst_wasapi_util_initialize_audioclient (GstElement * self,
842 GstAudioRingBufferSpec * spec, IAudioClient * client,
843 WAVEFORMATEX * format, guint sharemode, gboolean low_latency,
844 gboolean loopback, guint * ret_devicep_frames)
846 REFERENCE_TIME default_period, min_period;
847 REFERENCE_TIME device_period, device_buffer_duration;
848 guint rate, stream_flags;
852 hr = IAudioClient_GetDevicePeriod (client, &default_period, &min_period);
853 HR_FAILED_RET (hr, IAudioClient::GetDevicePeriod, FALSE);
855 GST_INFO_OBJECT (self, "wasapi default period: %" G_GINT64_FORMAT
856 ", min period: %" G_GINT64_FORMAT, default_period, min_period);
858 rate = GST_AUDIO_INFO_RATE (&spec->info);
861 if (sharemode == AUDCLNT_SHAREMODE_SHARED) {
862 device_period = default_period;
863 device_buffer_duration = 0;
865 device_period = min_period;
866 device_buffer_duration = min_period;
869 /* Clamp values to integral multiples of an appropriate period */
870 gst_wasapi_util_get_best_buffer_sizes (spec,
871 sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE, default_period,
872 min_period, &device_period, &device_buffer_duration);
875 stream_flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
877 stream_flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
879 hr = IAudioClient_Initialize (client, sharemode, stream_flags,
880 device_buffer_duration,
881 /* This must always be 0 in shared mode */
882 sharemode == AUDCLNT_SHAREMODE_SHARED ? 0 : device_period, format, NULL);
884 if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED &&
885 sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE) {
886 GST_WARNING_OBJECT (self, "initialize failed due to unaligned period %i",
887 (int) device_period);
889 /* Calculate a new aligned period. First get the aligned buffer size. */
890 hr = IAudioClient_GetBufferSize (client, &n_frames);
891 HR_FAILED_RET (hr, IAudioClient::GetBufferSize, FALSE);
893 device_period = (GST_SECOND / 100) * n_frames / rate;
895 GST_WARNING_OBJECT (self, "trying to re-initialize with period %i "
896 "(%i frames, %i rate)", (int) device_period, n_frames, rate);
898 hr = IAudioClient_Initialize (client, sharemode, stream_flags,
899 device_period, device_period, format, NULL);
901 HR_FAILED_RET (hr, IAudioClient::Initialize, FALSE);
903 if (sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE) {
904 /* We use the device period for the segment size and that needs to match
905 * the buffer size exactly when we write into it */
906 hr = IAudioClient_GetBufferSize (client, &n_frames);
907 HR_FAILED_RET (hr, IAudioClient::GetBufferSize, FALSE);
909 *ret_devicep_frames = n_frames;
911 /* device_period can be a non-power-of-10 value so round while converting */
912 *ret_devicep_frames =
913 gst_util_uint64_scale_round (device_period, rate * 100, GST_SECOND);
920 gst_wasapi_util_initialize_audioclient3 (GstElement * self,
921 GstAudioRingBufferSpec * spec, IAudioClient3 * client,
922 WAVEFORMATEX * format, gboolean low_latency, gboolean loopback,
923 guint * ret_devicep_frames)
927 guint devicep_frames;
928 guint defaultp_frames, fundp_frames, minp_frames, maxp_frames;
931 hr = IAudioClient3_GetSharedModeEnginePeriod (client, format,
932 &defaultp_frames, &fundp_frames, &minp_frames, &maxp_frames);
933 HR_FAILED_RET (hr, IAudioClient3::GetSharedModeEnginePeriod, FALSE);
935 GST_INFO_OBJECT (self, "Using IAudioClient3, default period %i frames, "
936 "fundamental period %i frames, minimum period %i frames, maximum period "
937 "%i frames", defaultp_frames, fundp_frames, minp_frames, maxp_frames);
940 devicep_frames = minp_frames;
942 /* Just pick the max period, because lower values can cause glitches
943 * https://bugzilla.gnome.org/show_bug.cgi?id=794497 */
944 devicep_frames = maxp_frames;
946 stream_flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
948 stream_flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
950 hr = IAudioClient3_InitializeSharedAudioStream (client, stream_flags,
951 devicep_frames, format, NULL);
952 HR_FAILED_RET (hr, IAudioClient3::InitializeSharedAudioStream, FALSE);
954 hr = IAudioClient3_GetCurrentSharedModeEnginePeriod (client, &tmpf,
956 CoTaskMemFree (tmpf);
957 HR_FAILED_RET (hr, IAudioClient3::GetCurrentSharedModeEnginePeriod, FALSE);
959 *ret_devicep_frames = devicep_frames;