• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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>
5  *
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.
10  *
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.
15  *
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.
20  */
21 #ifdef HAVE_CONFIG_H
22 #  include <config.h>
23 #endif
24 
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.
29  */
30 #ifdef _MSC_VER
31 #include <initguid.h>
32 #endif
33 #include "gstwasapiutil.h"
34 #include "gstwasapidevice.h"
35 
36 GST_DEBUG_CATEGORY_EXTERN (gst_wasapi_debug);
37 #define GST_CAT_DEFAULT gst_wasapi_debug
38 
39 /* This was only added to MinGW in ~2015 and our Cerbero toolchain is too old */
40 #if defined(_MSC_VER)
41 #include <functiondiscoverykeys_devpkey.h>
42 #elif !defined(PKEY_Device_FriendlyName)
43 #include <initguid.h>
44 #include <propkey.h>
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);
49 #endif
50 
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}
55 };
56 
57 const IID IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,
58   {0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6}
59 };
60 
61 const IID IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089,
62   {0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5}
63 };
64 
65 const IID IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32,
66   {0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2}
67 };
68 
69 const IID IID_IAudioClient3 = { 0x7ed4ee07, 0x8e67, 0x4cd4,
70   {0x8c, 0x1a, 0x2b, 0x7a, 0x59, 0x87, 0xad, 0x42}
71 };
72 
73 const IID IID_IAudioClock = { 0xcd63314f, 0x3fba, 0x4a1b,
74   {0x81, 0x2c, 0xef, 0x96, 0x35, 0x87, 0x28, 0xe7}
75 };
76 
77 const IID IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0,
78   {0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17}
79 };
80 
81 const IID IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,
82   {0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2}
83 };
84 
85 /* *INDENT-OFF* */
86 static struct
87 {
88   guint64 wasapi_pos;
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}
112 };
113 /* *INDENT-ON* */
114 
115 static int windows_major_version = 0;
116 
117 gboolean
gst_wasapi_util_have_audioclient3(void)118 gst_wasapi_util_have_audioclient3 (void)
119 {
120   if (windows_major_version > 0)
121     return windows_major_version == 10;
122 
123   if (g_getenv ("GST_WASAPI_DISABLE_AUDIOCLIENT3") != NULL) {
124     windows_major_version = 6;
125     return FALSE;
126   }
127 
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;
132 
133   return windows_major_version == 10;
134 }
135 
136 GType
gst_wasapi_device_role_get_type(void)137 gst_wasapi_device_role_get_type (void)
138 {
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",
143         "multimedia"},
144     {GST_WASAPI_DEVICE_ROLE_COMMS, "Voice communications", "comms"},
145     {0, NULL, NULL}
146   };
147   static GType id = 0;
148 
149   if (g_once_init_enter ((gsize *) & id)) {
150     GType _id;
151 
152     _id = g_enum_register_static ("GstWasapiDeviceRole", values);
153 
154     g_once_init_leave ((gsize *) & id, _id);
155   }
156 
157   return id;
158 }
159 
160 gint
gst_wasapi_device_role_to_erole(gint role)161 gst_wasapi_device_role_to_erole (gint role)
162 {
163   switch (role) {
164     case GST_WASAPI_DEVICE_ROLE_CONSOLE:
165       return eConsole;
166     case GST_WASAPI_DEVICE_ROLE_MULTIMEDIA:
167       return eMultimedia;
168     case GST_WASAPI_DEVICE_ROLE_COMMS:
169       return eCommunications;
170     default:
171       g_assert_not_reached ();
172   }
173 
174   return -1;
175 }
176 
177 gint
gst_wasapi_erole_to_device_role(gint erole)178 gst_wasapi_erole_to_device_role (gint erole)
179 {
180   switch (erole) {
181     case eConsole:
182       return GST_WASAPI_DEVICE_ROLE_CONSOLE;
183     case eMultimedia:
184       return GST_WASAPI_DEVICE_ROLE_MULTIMEDIA;
185     case eCommunications:
186       return GST_WASAPI_DEVICE_ROLE_COMMS;
187     default:
188       g_assert_not_reached ();
189   }
190 
191   return -1;
192 }
193 
194 static const gchar *
hresult_to_string_fallback(HRESULT hr)195 hresult_to_string_fallback (HRESULT hr)
196 {
197   const gchar *s = "unknown error";
198 
199   switch (hr) {
200     case AUDCLNT_E_NOT_INITIALIZED:
201       s = "AUDCLNT_E_NOT_INITIALIZED";
202       break;
203     case AUDCLNT_E_ALREADY_INITIALIZED:
204       s = "AUDCLNT_E_ALREADY_INITIALIZED";
205       break;
206     case AUDCLNT_E_WRONG_ENDPOINT_TYPE:
207       s = "AUDCLNT_E_WRONG_ENDPOINT_TYPE";
208       break;
209     case AUDCLNT_E_DEVICE_INVALIDATED:
210       s = "AUDCLNT_E_DEVICE_INVALIDATED";
211       break;
212     case AUDCLNT_E_NOT_STOPPED:
213       s = "AUDCLNT_E_NOT_STOPPED";
214       break;
215     case AUDCLNT_E_BUFFER_TOO_LARGE:
216       s = "AUDCLNT_E_BUFFER_TOO_LARGE";
217       break;
218     case AUDCLNT_E_OUT_OF_ORDER:
219       s = "AUDCLNT_E_OUT_OF_ORDER";
220       break;
221     case AUDCLNT_E_UNSUPPORTED_FORMAT:
222       s = "AUDCLNT_E_UNSUPPORTED_FORMAT";
223       break;
224     case AUDCLNT_E_INVALID_DEVICE_PERIOD:
225       s = "AUDCLNT_E_INVALID_DEVICE_PERIOD";
226       break;
227     case AUDCLNT_E_INVALID_SIZE:
228       s = "AUDCLNT_E_INVALID_SIZE";
229       break;
230     case AUDCLNT_E_DEVICE_IN_USE:
231       s = "AUDCLNT_E_DEVICE_IN_USE";
232       break;
233     case AUDCLNT_E_BUFFER_OPERATION_PENDING:
234       s = "AUDCLNT_E_BUFFER_OPERATION_PENDING";
235       break;
236     case AUDCLNT_E_BUFFER_SIZE_ERROR:
237       s = "AUDCLNT_E_BUFFER_SIZE_ERROR";
238       break;
239     case AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED:
240       s = "AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED";
241       break;
242     case AUDCLNT_E_THREAD_NOT_REGISTERED:
243       s = "AUDCLNT_E_THREAD_NOT_REGISTERED";
244       break;
245     case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED:
246       s = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED";
247       break;
248     case AUDCLNT_E_ENDPOINT_CREATE_FAILED:
249       s = "AUDCLNT_E_ENDPOINT_CREATE_FAILED";
250       break;
251     case AUDCLNT_E_SERVICE_NOT_RUNNING:
252       s = "AUDCLNT_E_SERVICE_NOT_RUNNING";
253       break;
254     case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED:
255       s = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED";
256       break;
257     case AUDCLNT_E_EXCLUSIVE_MODE_ONLY:
258       s = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY";
259       break;
260     case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL:
261       s = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL";
262       break;
263     case AUDCLNT_E_EVENTHANDLE_NOT_SET:
264       s = "AUDCLNT_E_EVENTHANDLE_NOT_SET";
265       break;
266     case AUDCLNT_E_INCORRECT_BUFFER_SIZE:
267       s = "AUDCLNT_E_INCORRECT_BUFFER_SIZE";
268       break;
269     case AUDCLNT_E_CPUUSAGE_EXCEEDED:
270       s = "AUDCLNT_E_CPUUSAGE_EXCEEDED";
271       break;
272     case AUDCLNT_S_BUFFER_EMPTY:
273       s = "AUDCLNT_S_BUFFER_EMPTY";
274       break;
275     case AUDCLNT_S_THREAD_ALREADY_REGISTERED:
276       s = "AUDCLNT_S_THREAD_ALREADY_REGISTERED";
277       break;
278     case AUDCLNT_S_POSITION_STALLED:
279       s = "AUDCLNT_S_POSITION_STALLED";
280       break;
281     case E_POINTER:
282       s = "E_POINTER";
283       break;
284     case E_INVALIDARG:
285       s = "E_INVALIDARG";
286       break;
287   }
288 
289   return s;
290 }
291 
292 gchar *
gst_wasapi_util_hresult_to_string(HRESULT hr)293 gst_wasapi_util_hresult_to_string (HRESULT hr)
294 {
295   gchar *error_text = NULL;
296 
297   error_text = g_win32_error_message ((gint) hr);
298   /* g_win32_error_message() seems to be returning empty string for
299    * AUDCLNT_* cases */
300   if (!error_text || strlen (error_text) == 0) {
301     g_free (error_text);
302     error_text = g_strdup (hresult_to_string_fallback (hr));
303   }
304 
305   return error_text;
306 }
307 
308 gboolean
gst_wasapi_util_get_devices(GstMMDeviceEnumerator * self,gboolean active,GList ** devices)309 gst_wasapi_util_get_devices (GstMMDeviceEnumerator * self,
310     gboolean active, GList ** devices)
311 {
312   gboolean res = FALSE;
313   static GstStaticCaps scaps = GST_STATIC_CAPS (GST_WASAPI_STATIC_CAPS);
314   DWORD dwStateMask = active ? DEVICE_STATE_ACTIVE : DEVICE_STATEMASK_ALL;
315   IMMDeviceCollection *device_collection = NULL;
316   IMMDeviceEnumerator *enum_handle = NULL;
317   const gchar *device_class, *element_name;
318   guint ii, count;
319   HRESULT hr;
320 
321   *devices = NULL;
322 
323   if (!self)
324     return FALSE;
325 
326   enum_handle = gst_mm_device_enumerator_get_handle (self);
327   if (!enum_handle)
328     return FALSE;
329 
330   hr = IMMDeviceEnumerator_EnumAudioEndpoints (enum_handle, eAll, dwStateMask,
331       &device_collection);
332   HR_FAILED_GOTO (hr, IMMDeviceEnumerator::EnumAudioEndpoints, err);
333 
334   hr = IMMDeviceCollection_GetCount (device_collection, &count);
335   HR_FAILED_GOTO (hr, IMMDeviceCollection::GetCount, err);
336 
337   /* Create a GList of GstDevices* to return */
338   for (ii = 0; ii < count; ii++) {
339     IMMDevice *item = NULL;
340     IMMEndpoint *endpoint = NULL;
341     IAudioClient *client = NULL;
342     IPropertyStore *prop_store = NULL;
343     WAVEFORMATEX *format = NULL;
344     gchar *description = NULL;
345     gchar *strid = NULL;
346     EDataFlow dataflow;
347     PROPVARIANT var;
348     wchar_t *wstrid;
349     GstDevice *device;
350     GstStructure *props;
351     GstCaps *caps;
352 
353     hr = IMMDeviceCollection_Item (device_collection, ii, &item);
354     if (hr != S_OK)
355       continue;
356 
357     hr = IMMDevice_QueryInterface (item, &IID_IMMEndpoint, (void **) &endpoint);
358     if (hr != S_OK)
359       goto next;
360 
361     hr = IMMEndpoint_GetDataFlow (endpoint, &dataflow);
362     if (hr != S_OK)
363       goto next;
364 
365     if (dataflow == eRender) {
366       device_class = "Audio/Sink";
367       element_name = "wasapisink";
368     } else {
369       device_class = "Audio/Source";
370       element_name = "wasapisrc";
371     }
372 
373     PropVariantInit (&var);
374 
375     hr = IMMDevice_GetId (item, &wstrid);
376     if (hr != S_OK)
377       goto next;
378     strid = g_utf16_to_utf8 (wstrid, -1, NULL, NULL, NULL);
379     CoTaskMemFree (wstrid);
380 
381     hr = IMMDevice_OpenPropertyStore (item, STGM_READ, &prop_store);
382     if (hr != S_OK)
383       goto next;
384 
385     /* NOTE: More properties can be added as needed from here:
386      * https://msdn.microsoft.com/en-us/library/windows/desktop/dd370794(v=vs.85).aspx */
387     hr = IPropertyStore_GetValue (prop_store, &PKEY_Device_FriendlyName, &var);
388     if (hr != S_OK)
389       goto next;
390     description = g_utf16_to_utf8 (var.pwszVal, -1, NULL, NULL, NULL);
391     PropVariantClear (&var);
392 
393     /* Get the audio client so we can fetch the mix format for shared mode
394      * to get the device format for exclusive mode (or something close to that)
395      * fetch PKEY_AudioEngine_DeviceFormat from the property store. */
396     hr = IMMDevice_Activate (item, &IID_IAudioClient, CLSCTX_ALL, NULL,
397         (void **) &client);
398     if (hr != S_OK) {
399       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
400       GST_ERROR_OBJECT (self, "IMMDevice::Activate (IID_IAudioClient) failed"
401           "on %s: %s", strid, msg);
402       g_free (msg);
403       goto next;
404     }
405 
406     hr = IAudioClient_GetMixFormat (client, &format);
407     if (hr != S_OK || format == NULL) {
408       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
409       GST_ERROR_OBJECT (self, "GetMixFormat failed on %s: %s", strid, msg);
410       g_free (msg);
411       goto next;
412     }
413 
414     if (!gst_wasapi_util_parse_waveformatex ((WAVEFORMATEXTENSIBLE *) format,
415             gst_static_caps_get (&scaps), &caps, NULL))
416       goto next;
417 
418     /* Set some useful properties */
419     props = gst_structure_new ("wasapi-proplist",
420         "device.api", G_TYPE_STRING, "wasapi",
421         "device.strid", G_TYPE_STRING, GST_STR_NULL (strid),
422         "wasapi.device.description", G_TYPE_STRING, description, NULL);
423 
424     device = g_object_new (GST_TYPE_WASAPI_DEVICE, "device", strid,
425         "display-name", description, "caps", caps,
426         "device-class", device_class, "properties", props, NULL);
427     GST_WASAPI_DEVICE (device)->element = element_name;
428 
429     gst_structure_free (props);
430     gst_caps_unref (caps);
431     *devices = g_list_prepend (*devices, device);
432 
433   next:
434     PropVariantClear (&var);
435     if (prop_store)
436       IUnknown_Release (prop_store);
437     if (endpoint)
438       IUnknown_Release (endpoint);
439     if (client)
440       IUnknown_Release (client);
441     if (item)
442       IUnknown_Release (item);
443     if (description)
444       g_free (description);
445     if (strid)
446       g_free (strid);
447   }
448 
449   res = TRUE;
450 
451 err:
452   if (device_collection)
453     IUnknown_Release (device_collection);
454   return res;
455 }
456 
457 gboolean
gst_wasapi_util_get_device_format(GstElement * self,gint device_mode,IMMDevice * device,IAudioClient * client,WAVEFORMATEX ** ret_format)458 gst_wasapi_util_get_device_format (GstElement * self,
459     gint device_mode, IMMDevice * device, IAudioClient * client,
460     WAVEFORMATEX ** ret_format)
461 {
462   WAVEFORMATEX *format;
463   HRESULT hr;
464 
465   *ret_format = NULL;
466 
467   hr = IAudioClient_GetMixFormat (client, &format);
468   HR_FAILED_RET (hr, IAudioClient::GetMixFormat, FALSE);
469 
470   /* WASAPI always accepts the format returned by GetMixFormat in shared mode */
471   if (device_mode == AUDCLNT_SHAREMODE_SHARED)
472     goto out;
473 
474   /* WASAPI may or may not support this format in exclusive mode */
475   hr = IAudioClient_IsFormatSupported (client, AUDCLNT_SHAREMODE_EXCLUSIVE,
476       format, NULL);
477   if (hr == S_OK)
478     goto out;
479 
480   CoTaskMemFree (format);
481 
482   /* Open the device property store, and get the format that WASAPI has been
483    * using for sending data to the device */
484   {
485     PROPVARIANT var;
486     IPropertyStore *prop_store = NULL;
487 
488     hr = IMMDevice_OpenPropertyStore (device, STGM_READ, &prop_store);
489     HR_FAILED_RET (hr, IMMDevice::OpenPropertyStore, FALSE);
490 
491     hr = IPropertyStore_GetValue (prop_store, &PKEY_AudioEngine_DeviceFormat,
492         &var);
493     if (hr != S_OK) {
494       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
495       GST_ERROR_OBJECT (self, "GetValue failed: %s", msg);
496       g_free (msg);
497       IUnknown_Release (prop_store);
498       return FALSE;
499     }
500 
501     format = malloc (var.blob.cbSize);
502     memcpy (format, var.blob.pBlobData, var.blob.cbSize);
503 
504     PropVariantClear (&var);
505     IUnknown_Release (prop_store);
506   }
507 
508   /* WASAPI may or may not support this format in exclusive mode */
509   hr = IAudioClient_IsFormatSupported (client, AUDCLNT_SHAREMODE_EXCLUSIVE,
510       format, NULL);
511   if (hr == S_OK)
512     goto out;
513 
514   GST_ERROR_OBJECT (self, "AudioEngine DeviceFormat not supported");
515   free (format);
516   return FALSE;
517 
518 out:
519   *ret_format = format;
520   return TRUE;
521 }
522 
523 gboolean
gst_wasapi_util_get_device(GstMMDeviceEnumerator * self,gint data_flow,gint role,const wchar_t * device_strid,IMMDevice ** ret_device)524 gst_wasapi_util_get_device (GstMMDeviceEnumerator * self,
525     gint data_flow, gint role, const wchar_t * device_strid,
526     IMMDevice ** ret_device)
527 {
528   gboolean res = FALSE;
529   HRESULT hr;
530   IMMDeviceEnumerator *enum_handle = NULL;
531   IMMDevice *device = NULL;
532 
533   if (!self)
534     return FALSE;
535 
536   enum_handle = gst_mm_device_enumerator_get_handle (self);
537   if (!enum_handle)
538     return FALSE;
539 
540   if (!device_strid) {
541     hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint (enum_handle, data_flow,
542         role, &device);
543     HR_FAILED_GOTO (hr, IMMDeviceEnumerator::GetDefaultAudioEndpoint, beach);
544   } else {
545     hr = IMMDeviceEnumerator_GetDevice (enum_handle, device_strid, &device);
546     if (hr != S_OK) {
547       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
548       GST_ERROR_OBJECT (self, "IMMDeviceEnumerator::GetDevice (%S) failed"
549           ": %s", device_strid, msg);
550       g_free (msg);
551       goto beach;
552     }
553   }
554 
555   IUnknown_AddRef (device);
556   *ret_device = device;
557 
558   res = TRUE;
559 
560 beach:
561   if (device != NULL)
562     IUnknown_Release (device);
563 
564   return res;
565 }
566 
567 gboolean
gst_wasapi_util_get_audio_client(GstElement * self,IMMDevice * device,IAudioClient ** ret_client)568 gst_wasapi_util_get_audio_client (GstElement * self,
569     IMMDevice * device, IAudioClient ** ret_client)
570 {
571   IAudioClient *client = NULL;
572   gboolean res = FALSE;
573   HRESULT hr;
574 
575   if (gst_wasapi_util_have_audioclient3 ())
576     hr = IMMDevice_Activate (device, &IID_IAudioClient3, CLSCTX_ALL, NULL,
577         (void **) &client);
578   else
579     hr = IMMDevice_Activate (device, &IID_IAudioClient, CLSCTX_ALL, NULL,
580         (void **) &client);
581   HR_FAILED_GOTO (hr, IMMDevice::Activate (IID_IAudioClient), beach);
582 
583   IUnknown_AddRef (client);
584   *ret_client = client;
585 
586   res = TRUE;
587 
588 beach:
589   if (client != NULL)
590     IUnknown_Release (client);
591 
592   return res;
593 }
594 
595 gboolean
gst_wasapi_util_get_render_client(GstElement * self,IAudioClient * client,IAudioRenderClient ** ret_render_client)596 gst_wasapi_util_get_render_client (GstElement * self, IAudioClient * client,
597     IAudioRenderClient ** ret_render_client)
598 {
599   gboolean res = FALSE;
600   HRESULT hr;
601   IAudioRenderClient *render_client = NULL;
602 
603   hr = IAudioClient_GetService (client, &IID_IAudioRenderClient,
604       (void **) &render_client);
605   HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
606 
607   *ret_render_client = render_client;
608   res = TRUE;
609 
610 beach:
611   return res;
612 }
613 
614 gboolean
gst_wasapi_util_get_capture_client(GstElement * self,IAudioClient * client,IAudioCaptureClient ** ret_capture_client)615 gst_wasapi_util_get_capture_client (GstElement * self, IAudioClient * client,
616     IAudioCaptureClient ** ret_capture_client)
617 {
618   gboolean res = FALSE;
619   HRESULT hr;
620   IAudioCaptureClient *capture_client = NULL;
621 
622   hr = IAudioClient_GetService (client, &IID_IAudioCaptureClient,
623       (void **) &capture_client);
624   HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
625 
626   *ret_capture_client = capture_client;
627   res = TRUE;
628 
629 beach:
630   return res;
631 }
632 
633 gboolean
gst_wasapi_util_get_clock(GstElement * self,IAudioClient * client,IAudioClock ** ret_clock)634 gst_wasapi_util_get_clock (GstElement * self, IAudioClient * client,
635     IAudioClock ** ret_clock)
636 {
637   gboolean res = FALSE;
638   HRESULT hr;
639   IAudioClock *clock = NULL;
640 
641   hr = IAudioClient_GetService (client, &IID_IAudioClock, (void **) &clock);
642   HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
643 
644   *ret_clock = clock;
645   res = TRUE;
646 
647 beach:
648   return res;
649 }
650 
651 static const gchar *
gst_waveformatex_to_audio_format(WAVEFORMATEXTENSIBLE * format)652 gst_waveformatex_to_audio_format (WAVEFORMATEXTENSIBLE * format)
653 {
654   const gchar *fmt_str = NULL;
655   GstAudioFormat fmt = GST_AUDIO_FORMAT_UNKNOWN;
656 
657   if (format->Format.wFormatTag == WAVE_FORMAT_PCM) {
658     fmt = gst_audio_format_build_integer (TRUE, G_LITTLE_ENDIAN,
659         format->Format.wBitsPerSample, format->Format.wBitsPerSample);
660   } else if (format->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
661     if (format->Format.wBitsPerSample == 32)
662       fmt = GST_AUDIO_FORMAT_F32LE;
663     else if (format->Format.wBitsPerSample == 64)
664       fmt = GST_AUDIO_FORMAT_F64LE;
665   } else if (format->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
666     if (IsEqualGUID (&format->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
667       fmt = gst_audio_format_build_integer (TRUE, G_LITTLE_ENDIAN,
668           format->Format.wBitsPerSample, format->Samples.wValidBitsPerSample);
669     } else if (IsEqualGUID (&format->SubFormat,
670             &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
671       if (format->Format.wBitsPerSample == 32
672           && format->Samples.wValidBitsPerSample == 32)
673         fmt = GST_AUDIO_FORMAT_F32LE;
674       else if (format->Format.wBitsPerSample == 64 &&
675           format->Samples.wValidBitsPerSample == 64)
676         fmt = GST_AUDIO_FORMAT_F64LE;
677     }
678   }
679 
680   if (fmt != GST_AUDIO_FORMAT_UNKNOWN)
681     fmt_str = gst_audio_format_to_string (fmt);
682 
683   return fmt_str;
684 }
685 
686 static void
gst_wasapi_util_channel_position_all_none(guint channels,GstAudioChannelPosition * position)687 gst_wasapi_util_channel_position_all_none (guint channels,
688     GstAudioChannelPosition * position)
689 {
690   int ii;
691   for (ii = 0; ii < channels; ii++)
692     position[ii] = GST_AUDIO_CHANNEL_POSITION_NONE;
693 }
694 
695 /* Parse WAVEFORMATEX to get the gstreamer channel mask, and the wasapi channel
696  * positions so GstAudioRingbuffer can reorder the audio data to match the
697  * gstreamer channel order. */
698 static guint64
gst_wasapi_util_waveformatex_to_channel_mask(WAVEFORMATEXTENSIBLE * format,GstAudioChannelPosition ** out_position)699 gst_wasapi_util_waveformatex_to_channel_mask (WAVEFORMATEXTENSIBLE * format,
700     GstAudioChannelPosition ** out_position)
701 {
702   int ii, ch;
703   guint64 mask = 0;
704   WORD nChannels = format->Format.nChannels;
705   DWORD dwChannelMask = format->dwChannelMask;
706   GstAudioChannelPosition *pos = NULL;
707 
708   pos = g_new (GstAudioChannelPosition, nChannels);
709   gst_wasapi_util_channel_position_all_none (nChannels, pos);
710 
711   /* Too many channels, have to assume that they are all non-positional */
712   if (nChannels > G_N_ELEMENTS (wasapi_to_gst_pos)) {
713     GST_INFO ("Got too many (%i) channels, assuming non-positional", nChannels);
714     goto out;
715   }
716 
717   /* Too many bits in the channel mask, and the bits don't match nChannels */
718   if (dwChannelMask >> (G_N_ELEMENTS (wasapi_to_gst_pos) + 1) != 0) {
719     GST_WARNING ("Too many bits in channel mask (%lu), assuming "
720         "non-positional", dwChannelMask);
721     goto out;
722   }
723 
724   /* Map WASAPI's channel mask to Gstreamer's channel mask and positions.
725    * If the no. of bits in the mask > nChannels, we will ignore the extra. */
726   for (ii = 0, ch = 0; ii < G_N_ELEMENTS (wasapi_to_gst_pos) && ch < nChannels;
727       ii++) {
728     if (!(dwChannelMask & wasapi_to_gst_pos[ii].wasapi_pos))
729       /* no match, try next */
730       continue;
731     mask |= G_GUINT64_CONSTANT (1) << wasapi_to_gst_pos[ii].gst_pos;
732     pos[ch++] = wasapi_to_gst_pos[ii].gst_pos;
733   }
734 
735   /* XXX: Warn if some channel masks couldn't be mapped? */
736 
737   GST_DEBUG ("Converted WASAPI mask 0x%" G_GINT64_MODIFIER "x -> 0x%"
738       G_GINT64_MODIFIER "x", (guint64) dwChannelMask, (guint64) mask);
739 
740 out:
741   if (out_position)
742     *out_position = pos;
743   return mask;
744 }
745 
746 gboolean
gst_wasapi_util_parse_waveformatex(WAVEFORMATEXTENSIBLE * format,GstCaps * template_caps,GstCaps ** out_caps,GstAudioChannelPosition ** out_positions)747 gst_wasapi_util_parse_waveformatex (WAVEFORMATEXTENSIBLE * format,
748     GstCaps * template_caps, GstCaps ** out_caps,
749     GstAudioChannelPosition ** out_positions)
750 {
751   int ii;
752   const gchar *afmt;
753   guint64 channel_mask;
754 
755   *out_caps = NULL;
756 
757   /* TODO: handle SPDIF and other encoded formats */
758 
759   /* 1 or 2 channels <= 16 bits sample size OR
760    * 1 or 2 channels > 16 bits sample size or >2 channels */
761   if (format->Format.wFormatTag != WAVE_FORMAT_PCM &&
762       format->Format.wFormatTag != WAVE_FORMAT_IEEE_FLOAT &&
763       format->Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
764     /* Unhandled format tag */
765     return FALSE;
766 
767   /* WASAPI can only tell us one canonical mix format that it will accept. The
768    * alternative is calling IsFormatSupported on all combinations of formats.
769    * Instead, it's simpler and faster to require conversion inside gstreamer */
770   afmt = gst_waveformatex_to_audio_format (format);
771   if (afmt == NULL)
772     return FALSE;
773 
774   *out_caps = gst_caps_copy (template_caps);
775 
776   /* This will always return something that might be usable */
777   channel_mask =
778       gst_wasapi_util_waveformatex_to_channel_mask (format, out_positions);
779 
780   for (ii = 0; ii < gst_caps_get_size (*out_caps); ii++) {
781     GstStructure *s = gst_caps_get_structure (*out_caps, ii);
782 
783     gst_structure_set (s,
784         "format", G_TYPE_STRING, afmt,
785         "channels", G_TYPE_INT, format->Format.nChannels,
786         "rate", G_TYPE_INT, format->Format.nSamplesPerSec, NULL);
787 
788     if (channel_mask) {
789       gst_structure_set (s,
790           "channel-mask", GST_TYPE_BITMASK, channel_mask, NULL);
791     }
792   }
793 
794   return TRUE;
795 }
796 
797 void
gst_wasapi_util_get_best_buffer_sizes(GstAudioRingBufferSpec * spec,gboolean exclusive,REFERENCE_TIME default_period,REFERENCE_TIME min_period,REFERENCE_TIME * ret_period,REFERENCE_TIME * ret_buffer_duration)798 gst_wasapi_util_get_best_buffer_sizes (GstAudioRingBufferSpec * spec,
799     gboolean exclusive, REFERENCE_TIME default_period,
800     REFERENCE_TIME min_period, REFERENCE_TIME * ret_period,
801     REFERENCE_TIME * ret_buffer_duration)
802 {
803   REFERENCE_TIME use_period, use_buffer;
804 
805   /* Figure out what integral device period to use as the base */
806   if (exclusive) {
807     /* Exclusive mode can run at multiples of either the minimum period or the
808      * default period; these are on the hardware ringbuffer */
809     if (spec->latency_time * 10 > default_period)
810       use_period = default_period;
811     else
812       use_period = min_period;
813   } else {
814     /* Shared mode always runs at the default period, so if we want a larger
815      * period (for lower CPU usage), we do it as a multiple of that */
816     use_period = default_period;
817   }
818 
819   /* Ensure that the period (latency_time) used is an integral multiple of
820    * either the default period or the minimum period */
821   use_period = use_period * MAX ((spec->latency_time * 10) / use_period, 1);
822 
823   if (exclusive) {
824     /* Buffer duration is the same as the period in exclusive mode. The
825      * hardware is always writing out one buffer (of size *ret_period), and
826      * we're writing to the other one. */
827     use_buffer = use_period;
828   } else {
829     /* Ask WASAPI to create a software ringbuffer of at least this size; it may
830      * be larger so the actual buffer time may be different, which is why after
831      * initialization we read the buffer duration actually in-use and set
832      * segsize/segtotal from that. */
833     use_buffer = spec->buffer_time * 10;
834     /* Has to be at least twice the period */
835     if (use_buffer < 2 * use_period)
836       use_buffer = 2 * use_period;
837   }
838 
839   *ret_period = use_period;
840   *ret_buffer_duration = use_buffer;
841 }
842 
843 gboolean
gst_wasapi_util_initialize_audioclient(GstElement * self,GstAudioRingBufferSpec * spec,IAudioClient * client,WAVEFORMATEX * format,guint sharemode,gboolean low_latency,gboolean loopback,guint * ret_devicep_frames)844 gst_wasapi_util_initialize_audioclient (GstElement * self,
845     GstAudioRingBufferSpec * spec, IAudioClient * client,
846     WAVEFORMATEX * format, guint sharemode, gboolean low_latency,
847     gboolean loopback, guint * ret_devicep_frames)
848 {
849   REFERENCE_TIME default_period, min_period;
850   REFERENCE_TIME device_period, device_buffer_duration;
851   guint rate, stream_flags;
852   guint32 n_frames;
853   HRESULT hr;
854 
855   hr = IAudioClient_GetDevicePeriod (client, &default_period, &min_period);
856   HR_FAILED_RET (hr, IAudioClient::GetDevicePeriod, FALSE);
857 
858   GST_INFO_OBJECT (self, "wasapi default period: %" G_GINT64_FORMAT
859       ", min period: %" G_GINT64_FORMAT, default_period, min_period);
860 
861   rate = GST_AUDIO_INFO_RATE (&spec->info);
862 
863   if (low_latency) {
864     if (sharemode == AUDCLNT_SHAREMODE_SHARED) {
865       device_period = default_period;
866       device_buffer_duration = 0;
867     } else {
868       device_period = min_period;
869       device_buffer_duration = min_period;
870     }
871   } else {
872     /* Clamp values to integral multiples of an appropriate period */
873     gst_wasapi_util_get_best_buffer_sizes (spec,
874         sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE, default_period,
875         min_period, &device_period, &device_buffer_duration);
876   }
877 
878   stream_flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
879   if (loopback)
880     stream_flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
881 
882   hr = IAudioClient_Initialize (client, sharemode, stream_flags,
883       device_buffer_duration,
884       /* This must always be 0 in shared mode */
885       sharemode == AUDCLNT_SHAREMODE_SHARED ? 0 : device_period, format, NULL);
886 
887   if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED &&
888       sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE) {
889     GST_WARNING_OBJECT (self, "initialize failed due to unaligned period %i",
890         (int) device_period);
891 
892     /* Calculate a new aligned period. First get the aligned buffer size. */
893     hr = IAudioClient_GetBufferSize (client, &n_frames);
894     HR_FAILED_RET (hr, IAudioClient::GetBufferSize, FALSE);
895 
896     device_period = (GST_SECOND / 100) * n_frames / rate;
897 
898     GST_WARNING_OBJECT (self, "trying to re-initialize with period %i "
899         "(%i frames, %i rate)", (int) device_period, n_frames, rate);
900 
901     hr = IAudioClient_Initialize (client, sharemode, stream_flags,
902         device_period, device_period, format, NULL);
903   }
904   HR_FAILED_RET (hr, IAudioClient::Initialize, FALSE);
905 
906   if (sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE) {
907     /* We use the device period for the segment size and that needs to match
908      * the buffer size exactly when we write into it */
909     hr = IAudioClient_GetBufferSize (client, &n_frames);
910     HR_FAILED_RET (hr, IAudioClient::GetBufferSize, FALSE);
911 
912     *ret_devicep_frames = n_frames;
913   } else {
914     /* device_period can be a non-power-of-10 value so round while converting */
915     *ret_devicep_frames =
916         gst_util_uint64_scale_round (device_period, rate * 100, GST_SECOND);
917   }
918 
919   return TRUE;
920 }
921 
922 gboolean
gst_wasapi_util_initialize_audioclient3(GstElement * self,GstAudioRingBufferSpec * spec,IAudioClient3 * client,WAVEFORMATEX * format,gboolean low_latency,gboolean loopback,guint * ret_devicep_frames)923 gst_wasapi_util_initialize_audioclient3 (GstElement * self,
924     GstAudioRingBufferSpec * spec, IAudioClient3 * client,
925     WAVEFORMATEX * format, gboolean low_latency, gboolean loopback,
926     guint * ret_devicep_frames)
927 {
928   HRESULT hr;
929   gint stream_flags;
930   guint devicep_frames;
931   guint defaultp_frames, fundp_frames, minp_frames, maxp_frames;
932   WAVEFORMATEX *tmpf;
933 
934   hr = IAudioClient3_GetSharedModeEnginePeriod (client, format,
935       &defaultp_frames, &fundp_frames, &minp_frames, &maxp_frames);
936   HR_FAILED_RET (hr, IAudioClient3::GetSharedModeEnginePeriod, FALSE);
937 
938   GST_INFO_OBJECT (self, "Using IAudioClient3, default period %i frames, "
939       "fundamental period %i frames, minimum period %i frames, maximum period "
940       "%i frames", defaultp_frames, fundp_frames, minp_frames, maxp_frames);
941 
942   if (low_latency)
943     devicep_frames = minp_frames;
944   else
945     /* Just pick the max period, because lower values can cause glitches
946      * https://bugzilla.gnome.org/show_bug.cgi?id=794497 */
947     devicep_frames = maxp_frames;
948 
949   stream_flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
950   if (loopback)
951     stream_flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
952 
953   hr = IAudioClient3_InitializeSharedAudioStream (client, stream_flags,
954       devicep_frames, format, NULL);
955   HR_FAILED_RET (hr, IAudioClient3::InitializeSharedAudioStream, FALSE);
956 
957   hr = IAudioClient3_GetCurrentSharedModeEnginePeriod (client, &tmpf,
958       &devicep_frames);
959   CoTaskMemFree (tmpf);
960   HR_FAILED_RET (hr, IAudioClient3::GetCurrentSharedModeEnginePeriod, FALSE);
961 
962   *ret_devicep_frames = devicep_frames;
963   return TRUE;
964 }
965