gst: don't use volatile to mean atomic
[platform/upstream/gstreamer.git] / sys / wasapi / gstwasapiutil.c
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
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
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
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
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 *
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 *
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 static IMMDeviceEnumerator *
309 gst_wasapi_util_get_device_enumerator (GstObject * self)
310 {
311   HRESULT hr;
312   IMMDeviceEnumerator *enumerator = NULL;
313
314   hr = CoCreateInstance (&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL,
315       &IID_IMMDeviceEnumerator, (void **) &enumerator);
316   HR_FAILED_RET (hr, CoCreateInstance (MMDeviceEnumerator), NULL);
317
318   return enumerator;
319 }
320
321 gboolean
322 gst_wasapi_util_get_devices (GstObject * self, gboolean active,
323     GList ** devices)
324 {
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;
331   guint ii, count;
332   HRESULT hr;
333
334   *devices = NULL;
335
336   enumerator = gst_wasapi_util_get_device_enumerator (self);
337   if (!enumerator)
338     return FALSE;
339
340   hr = IMMDeviceEnumerator_EnumAudioEndpoints (enumerator, eAll, dwStateMask,
341       &device_collection);
342   HR_FAILED_GOTO (hr, IMMDeviceEnumerator::EnumAudioEndpoints, err);
343
344   hr = IMMDeviceCollection_GetCount (device_collection, &count);
345   HR_FAILED_GOTO (hr, IMMDeviceCollection::GetCount, err);
346
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;
355     gchar *strid = NULL;
356     EDataFlow dataflow;
357     PROPVARIANT var;
358     wchar_t *wstrid;
359     GstDevice *device;
360     GstStructure *props;
361     GstCaps *caps;
362
363     hr = IMMDeviceCollection_Item (device_collection, ii, &item);
364     if (hr != S_OK)
365       continue;
366
367     hr = IMMDevice_QueryInterface (item, &IID_IMMEndpoint, (void **) &endpoint);
368     if (hr != S_OK)
369       goto next;
370
371     hr = IMMEndpoint_GetDataFlow (endpoint, &dataflow);
372     if (hr != S_OK)
373       goto next;
374
375     if (dataflow == eRender) {
376       device_class = "Audio/Sink";
377       element_name = "wasapisink";
378     } else {
379       device_class = "Audio/Source";
380       element_name = "wasapisrc";
381     }
382
383     PropVariantInit (&var);
384
385     hr = IMMDevice_GetId (item, &wstrid);
386     if (hr != S_OK)
387       goto next;
388     strid = g_utf16_to_utf8 (wstrid, -1, NULL, NULL, NULL);
389     CoTaskMemFree (wstrid);
390
391     hr = IMMDevice_OpenPropertyStore (item, STGM_READ, &prop_store);
392     if (hr != S_OK)
393       goto next;
394
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);
398     if (hr != S_OK)
399       goto next;
400     description = g_utf16_to_utf8 (var.pwszVal, -1, NULL, NULL, NULL);
401     PropVariantClear (&var);
402
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,
407         (void **) &client);
408     if (hr != S_OK) {
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);
412       g_free (msg);
413       goto next;
414     }
415
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);
420       g_free (msg);
421       goto next;
422     }
423
424     if (!gst_wasapi_util_parse_waveformatex ((WAVEFORMATEXTENSIBLE *) format,
425             gst_static_caps_get (&scaps), &caps, NULL))
426       goto next;
427
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);
433
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;
438
439     gst_structure_free (props);
440     gst_caps_unref (caps);
441     *devices = g_list_prepend (*devices, device);
442
443   next:
444     PropVariantClear (&var);
445     if (prop_store)
446       IUnknown_Release (prop_store);
447     if (endpoint)
448       IUnknown_Release (endpoint);
449     if (client)
450       IUnknown_Release (client);
451     if (item)
452       IUnknown_Release (item);
453     if (description)
454       g_free (description);
455     if (strid)
456       g_free (strid);
457   }
458
459   res = TRUE;
460
461 err:
462   if (enumerator)
463     IUnknown_Release (enumerator);
464   if (device_collection)
465     IUnknown_Release (device_collection);
466   return res;
467 }
468
469 gboolean
470 gst_wasapi_util_get_device_format (GstElement * self,
471     gint device_mode, IMMDevice * device, IAudioClient * client,
472     WAVEFORMATEX ** ret_format)
473 {
474   WAVEFORMATEX *format;
475   HRESULT hr;
476
477   *ret_format = NULL;
478
479   hr = IAudioClient_GetMixFormat (client, &format);
480   HR_FAILED_RET (hr, IAudioClient::GetMixFormat, FALSE);
481
482   /* WASAPI always accepts the format returned by GetMixFormat in shared mode */
483   if (device_mode == AUDCLNT_SHAREMODE_SHARED)
484     goto out;
485
486   /* WASAPI may or may not support this format in exclusive mode */
487   hr = IAudioClient_IsFormatSupported (client, AUDCLNT_SHAREMODE_EXCLUSIVE,
488       format, NULL);
489   if (hr == S_OK)
490     goto out;
491
492   CoTaskMemFree (format);
493
494   /* Open the device property store, and get the format that WASAPI has been
495    * using for sending data to the device */
496   {
497     PROPVARIANT var;
498     IPropertyStore *prop_store = NULL;
499
500     hr = IMMDevice_OpenPropertyStore (device, STGM_READ, &prop_store);
501     HR_FAILED_RET (hr, IMMDevice::OpenPropertyStore, FALSE);
502
503     hr = IPropertyStore_GetValue (prop_store, &PKEY_AudioEngine_DeviceFormat,
504         &var);
505     if (hr != S_OK) {
506       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
507       GST_ERROR_OBJECT (self, "GetValue failed: %s", msg);
508       g_free (msg);
509       IUnknown_Release (prop_store);
510       return FALSE;
511     }
512
513     format = malloc (var.blob.cbSize);
514     memcpy (format, var.blob.pBlobData, var.blob.cbSize);
515
516     PropVariantClear (&var);
517     IUnknown_Release (prop_store);
518   }
519
520   /* WASAPI may or may not support this format in exclusive mode */
521   hr = IAudioClient_IsFormatSupported (client, AUDCLNT_SHAREMODE_EXCLUSIVE,
522       format, NULL);
523   if (hr == S_OK)
524     goto out;
525
526   GST_ERROR_OBJECT (self, "AudioEngine DeviceFormat not supported");
527   free (format);
528   return FALSE;
529
530 out:
531   *ret_format = format;
532   return TRUE;
533 }
534
535 gboolean
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)
539 {
540   gboolean res = FALSE;
541   HRESULT hr;
542   IMMDeviceEnumerator *enumerator = NULL;
543   IMMDevice *device = NULL;
544   IAudioClient *client = NULL;
545
546   if (!(enumerator = gst_wasapi_util_get_device_enumerator (GST_OBJECT (self))))
547     goto beach;
548
549   if (!device_strid) {
550     hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint (enumerator, data_flow,
551         role, &device);
552     HR_FAILED_GOTO (hr, IMMDeviceEnumerator::GetDefaultAudioEndpoint, beach);
553   } else {
554     hr = IMMDeviceEnumerator_GetDevice (enumerator, device_strid, &device);
555     if (hr != S_OK) {
556       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
557       GST_ERROR_OBJECT (self, "IMMDeviceEnumerator::GetDevice (%S) failed"
558           ": %s", device_strid, msg);
559       g_free (msg);
560       goto beach;
561     }
562   }
563
564   if (gst_wasapi_util_have_audioclient3 ())
565     hr = IMMDevice_Activate (device, &IID_IAudioClient3, CLSCTX_ALL, NULL,
566         (void **) &client);
567   else
568     hr = IMMDevice_Activate (device, &IID_IAudioClient, CLSCTX_ALL, NULL,
569         (void **) &client);
570   HR_FAILED_GOTO (hr, IMMDevice::Activate (IID_IAudioClient), beach);
571
572   IUnknown_AddRef (client);
573   IUnknown_AddRef (device);
574   *ret_client = client;
575   *ret_device = device;
576
577   res = TRUE;
578
579 beach:
580   if (client != NULL)
581     IUnknown_Release (client);
582
583   if (device != NULL)
584     IUnknown_Release (device);
585
586   if (enumerator != NULL)
587     IUnknown_Release (enumerator);
588
589   return res;
590 }
591
592 gboolean
593 gst_wasapi_util_get_render_client (GstElement * self, IAudioClient * client,
594     IAudioRenderClient ** ret_render_client)
595 {
596   gboolean res = FALSE;
597   HRESULT hr;
598   IAudioRenderClient *render_client = NULL;
599
600   hr = IAudioClient_GetService (client, &IID_IAudioRenderClient,
601       (void **) &render_client);
602   HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
603
604   *ret_render_client = render_client;
605   res = TRUE;
606
607 beach:
608   return res;
609 }
610
611 gboolean
612 gst_wasapi_util_get_capture_client (GstElement * self, IAudioClient * client,
613     IAudioCaptureClient ** ret_capture_client)
614 {
615   gboolean res = FALSE;
616   HRESULT hr;
617   IAudioCaptureClient *capture_client = NULL;
618
619   hr = IAudioClient_GetService (client, &IID_IAudioCaptureClient,
620       (void **) &capture_client);
621   HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
622
623   *ret_capture_client = capture_client;
624   res = TRUE;
625
626 beach:
627   return res;
628 }
629
630 gboolean
631 gst_wasapi_util_get_clock (GstElement * self, IAudioClient * client,
632     IAudioClock ** ret_clock)
633 {
634   gboolean res = FALSE;
635   HRESULT hr;
636   IAudioClock *clock = NULL;
637
638   hr = IAudioClient_GetService (client, &IID_IAudioClock, (void **) &clock);
639   HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
640
641   *ret_clock = clock;
642   res = TRUE;
643
644 beach:
645   return res;
646 }
647
648 static const gchar *
649 gst_waveformatex_to_audio_format (WAVEFORMATEXTENSIBLE * format)
650 {
651   const gchar *fmt_str = NULL;
652   GstAudioFormat fmt = GST_AUDIO_FORMAT_UNKNOWN;
653
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;
674     }
675   }
676
677   if (fmt != GST_AUDIO_FORMAT_UNKNOWN)
678     fmt_str = gst_audio_format_to_string (fmt);
679
680   return fmt_str;
681 }
682
683 static void
684 gst_wasapi_util_channel_position_all_none (guint channels,
685     GstAudioChannelPosition * position)
686 {
687   int ii;
688   for (ii = 0; ii < channels; ii++)
689     position[ii] = GST_AUDIO_CHANNEL_POSITION_NONE;
690 }
691
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. */
695 static guint64
696 gst_wasapi_util_waveformatex_to_channel_mask (WAVEFORMATEXTENSIBLE * format,
697     GstAudioChannelPosition ** out_position)
698 {
699   int ii, ch;
700   guint64 mask = 0;
701   WORD nChannels = format->Format.nChannels;
702   DWORD dwChannelMask = format->dwChannelMask;
703   GstAudioChannelPosition *pos = NULL;
704
705   pos = g_new (GstAudioChannelPosition, nChannels);
706   gst_wasapi_util_channel_position_all_none (nChannels, pos);
707
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);
711     goto out;
712   }
713
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);
718     goto out;
719   }
720
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;
724       ii++) {
725     if (!(dwChannelMask & wasapi_to_gst_pos[ii].wasapi_pos))
726       /* no match, try next */
727       continue;
728     mask |= G_GUINT64_CONSTANT (1) << wasapi_to_gst_pos[ii].gst_pos;
729     pos[ch++] = wasapi_to_gst_pos[ii].gst_pos;
730   }
731
732   /* XXX: Warn if some channel masks couldn't be mapped? */
733
734   GST_DEBUG ("Converted WASAPI mask 0x%" G_GINT64_MODIFIER "x -> 0x%"
735       G_GINT64_MODIFIER "x", (guint64) dwChannelMask, (guint64) mask);
736
737 out:
738   if (out_position)
739     *out_position = pos;
740   return mask;
741 }
742
743 gboolean
744 gst_wasapi_util_parse_waveformatex (WAVEFORMATEXTENSIBLE * format,
745     GstCaps * template_caps, GstCaps ** out_caps,
746     GstAudioChannelPosition ** out_positions)
747 {
748   int ii;
749   const gchar *afmt;
750   guint64 channel_mask;
751
752   *out_caps = NULL;
753
754   /* TODO: handle SPDIF and other encoded formats */
755
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 */
762     return FALSE;
763
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);
768   if (afmt == NULL)
769     return FALSE;
770
771   *out_caps = gst_caps_copy (template_caps);
772
773   /* This will always return something that might be usable */
774   channel_mask =
775       gst_wasapi_util_waveformatex_to_channel_mask (format, out_positions);
776
777   for (ii = 0; ii < gst_caps_get_size (*out_caps); ii++) {
778     GstStructure *s = gst_caps_get_structure (*out_caps, ii);
779
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);
784
785     if (channel_mask) {
786       gst_structure_set (s,
787           "channel-mask", GST_TYPE_BITMASK, channel_mask, NULL);
788     }
789   }
790
791   return TRUE;
792 }
793
794 void
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)
799 {
800   REFERENCE_TIME use_period, use_buffer;
801
802   /* Figure out what integral device period to use as the base */
803   if (exclusive) {
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;
808     else
809       use_period = min_period;
810   } else {
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;
814   }
815
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);
819
820   if (exclusive) {
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;
825   } else {
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;
834   }
835
836   *ret_period = use_period;
837   *ret_buffer_duration = use_buffer;
838 }
839
840 gboolean
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)
845 {
846   REFERENCE_TIME default_period, min_period;
847   REFERENCE_TIME device_period, device_buffer_duration;
848   guint rate, stream_flags;
849   guint32 n_frames;
850   HRESULT hr;
851
852   hr = IAudioClient_GetDevicePeriod (client, &default_period, &min_period);
853   HR_FAILED_RET (hr, IAudioClient::GetDevicePeriod, FALSE);
854
855   GST_INFO_OBJECT (self, "wasapi default period: %" G_GINT64_FORMAT
856       ", min period: %" G_GINT64_FORMAT, default_period, min_period);
857
858   rate = GST_AUDIO_INFO_RATE (&spec->info);
859
860   if (low_latency) {
861     if (sharemode == AUDCLNT_SHAREMODE_SHARED) {
862       device_period = default_period;
863       device_buffer_duration = 0;
864     } else {
865       device_period = min_period;
866       device_buffer_duration = min_period;
867     }
868   } else {
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);
873   }
874
875   stream_flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
876   if (loopback)
877     stream_flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
878
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);
883
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);
888
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);
892
893     device_period = (GST_SECOND / 100) * n_frames / rate;
894
895     GST_WARNING_OBJECT (self, "trying to re-initialize with period %i "
896         "(%i frames, %i rate)", (int) device_period, n_frames, rate);
897
898     hr = IAudioClient_Initialize (client, sharemode, stream_flags,
899         device_period, device_period, format, NULL);
900   }
901   HR_FAILED_RET (hr, IAudioClient::Initialize, FALSE);
902
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);
908
909     *ret_devicep_frames = n_frames;
910   } else {
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);
914   }
915
916   return TRUE;
917 }
918
919 gboolean
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)
924 {
925   HRESULT hr;
926   gint stream_flags;
927   guint devicep_frames;
928   guint defaultp_frames, fundp_frames, minp_frames, maxp_frames;
929   WAVEFORMATEX *tmpf;
930
931   hr = IAudioClient3_GetSharedModeEnginePeriod (client, format,
932       &defaultp_frames, &fundp_frames, &minp_frames, &maxp_frames);
933   HR_FAILED_RET (hr, IAudioClient3::GetSharedModeEnginePeriod, FALSE);
934
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);
938
939   if (low_latency)
940     devicep_frames = minp_frames;
941   else
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;
945
946   stream_flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
947   if (loopback)
948     stream_flags |= AUDCLNT_STREAMFLAGS_LOOPBACK;
949
950   hr = IAudioClient3_InitializeSharedAudioStream (client, stream_flags,
951       devicep_frames, format, NULL);
952   HR_FAILED_RET (hr, IAudioClient3::InitializeSharedAudioStream, FALSE);
953
954   hr = IAudioClient3_GetCurrentSharedModeEnginePeriod (client, &tmpf,
955       &devicep_frames);
956   CoTaskMemFree (tmpf);
957   HR_FAILED_RET (hr, IAudioClient3::GetCurrentSharedModeEnginePeriod, FALSE);
958
959   *ret_devicep_frames = devicep_frames;
960   return TRUE;
961 }