wasapi: Set a default category for util functions
[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 #include "gstwasapiutil.h"
26 #include "gstwasapidevice.h"
27
28 GST_DEBUG_CATEGORY_EXTERN (gst_wasapi_debug);
29 #define GST_CAT_DEFAULT gst_wasapi_debug
30
31 /* This was only added to MinGW in ~2015 and our Cerbero toolchain is too old */
32 #if defined(_MSC_VER)
33 #include <functiondiscoverykeys_devpkey.h>
34 #elif !defined(PKEY_Device_FriendlyName)
35 #include <initguid.h>
36 #include <propkey.h>
37 DEFINE_PROPERTYKEY (PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,
38     0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14);
39 DEFINE_PROPERTYKEY (PKEY_AudioEngine_DeviceFormat, 0xf19f064d, 0x82c, 0x4e27,
40     0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c, 0);
41 #endif
42
43
44 #ifdef __uuidof
45 const CLSID CLSID_MMDeviceEnumerator = __uuidof (MMDeviceEnumerator);
46 const IID IID_IMMDeviceEnumerator = __uuidof (IMMDeviceEnumerator);
47 const IID IID_IMMEndpoint = __uuidof (IMMEndpoint);
48 const IID IID_IAudioClient = __uuidof (IAudioClient);
49 const IID IID_IAudioRenderClient = __uuidof (IAudioRenderClient);
50 const IID IID_IAudioCaptureClient = __uuidof (IAudioCaptureClient);
51 const IID IID_IAudioClock = __uuidof (IAudioClock);
52 #else
53 /* __uuidof is not implemented in our Cerbero's ancient MinGW toolchain so we
54  * hard-code the GUID values for all these. This is ok because these are ABI. */
55 const CLSID CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c,
56   {0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e}
57 };
58
59 const IID IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,
60   {0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6}
61 };
62
63 const IID IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089,
64   {0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5}
65 };
66
67 const IID IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32,
68   {0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2}
69 };
70
71 const IID IID_IAudioClock = { 0xcd63314f, 0x3fba, 0x4a1b,
72   {0x81, 0x2c, 0xef, 0x96, 0x35, 0x87, 0x28, 0xe7}
73 };
74
75 const IID IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0,
76   {0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17}
77 };
78
79 const IID IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,
80   {0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2}
81 };
82 #endif
83
84 static struct
85 {
86   guint64 wasapi_pos;
87   GstAudioChannelPosition gst_pos;
88 } wasapi_to_gst_pos[] = {
89   {SPEAKER_FRONT_LEFT, GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT},
90   {SPEAKER_FRONT_RIGHT, GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT},
91   {SPEAKER_FRONT_CENTER, GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER},
92   {SPEAKER_LOW_FREQUENCY, GST_AUDIO_CHANNEL_POSITION_LFE1},
93   {SPEAKER_BACK_LEFT, GST_AUDIO_CHANNEL_POSITION_REAR_LEFT},
94   {SPEAKER_BACK_RIGHT, GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT},
95   {SPEAKER_FRONT_LEFT_OF_CENTER,
96       GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER},
97   {SPEAKER_FRONT_RIGHT_OF_CENTER,
98       GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER},
99   {SPEAKER_BACK_CENTER, GST_AUDIO_CHANNEL_POSITION_REAR_CENTER},
100   /* Enum values diverge from this point onwards */
101   {SPEAKER_SIDE_LEFT, GST_AUDIO_CHANNEL_POSITION_SIDE_LEFT},
102   {SPEAKER_SIDE_RIGHT, GST_AUDIO_CHANNEL_POSITION_SIDE_RIGHT},
103   {SPEAKER_TOP_CENTER, GST_AUDIO_CHANNEL_POSITION_TOP_CENTER},
104   {SPEAKER_TOP_FRONT_LEFT, GST_AUDIO_CHANNEL_POSITION_TOP_FRONT_LEFT},
105   {SPEAKER_TOP_FRONT_CENTER, GST_AUDIO_CHANNEL_POSITION_TOP_FRONT_CENTER},
106   {SPEAKER_TOP_FRONT_RIGHT, GST_AUDIO_CHANNEL_POSITION_TOP_FRONT_RIGHT},
107   {SPEAKER_TOP_BACK_LEFT, GST_AUDIO_CHANNEL_POSITION_TOP_REAR_LEFT},
108   {SPEAKER_TOP_BACK_CENTER, GST_AUDIO_CHANNEL_POSITION_TOP_REAR_CENTER},
109   {SPEAKER_TOP_BACK_RIGHT, GST_AUDIO_CHANNEL_POSITION_TOP_REAR_RIGHT}
110 };
111
112 GType
113 gst_wasapi_device_role_get_type (void)
114 {
115   static const GEnumValue values[] = {
116     {GST_WASAPI_DEVICE_ROLE_CONSOLE,
117         "Games, system notifications, voice commands", "console"},
118     {GST_WASAPI_DEVICE_ROLE_MULTIMEDIA, "Music, movies, recorded media",
119         "multimedia"},
120     {GST_WASAPI_DEVICE_ROLE_COMMS, "Voice communications", "comms"},
121     {0, NULL, NULL}
122   };
123   static volatile GType id = 0;
124
125   if (g_once_init_enter ((gsize *) & id)) {
126     GType _id;
127
128     _id = g_enum_register_static ("GstWasapiDeviceRole", values);
129
130     g_once_init_leave ((gsize *) & id, _id);
131   }
132
133   return id;
134 }
135
136 gint
137 gst_wasapi_device_role_to_erole (gint role)
138 {
139   switch (role) {
140     case GST_WASAPI_DEVICE_ROLE_CONSOLE:
141       return eConsole;
142     case GST_WASAPI_DEVICE_ROLE_MULTIMEDIA:
143       return eMultimedia;
144     case GST_WASAPI_DEVICE_ROLE_COMMS:
145       return eCommunications;
146     default:
147       g_assert_not_reached ();
148   }
149 }
150
151 gint
152 gst_wasapi_erole_to_device_role (gint erole)
153 {
154   switch (erole) {
155     case eConsole:
156       return GST_WASAPI_DEVICE_ROLE_CONSOLE;
157     case eMultimedia:
158       return GST_WASAPI_DEVICE_ROLE_MULTIMEDIA;
159     case eCommunications:
160       return GST_WASAPI_DEVICE_ROLE_COMMS;
161     default:
162       g_assert_not_reached ();
163   }
164 }
165
166 static const gchar *
167 hresult_to_string_fallback (HRESULT hr)
168 {
169   const gchar *s = "unknown error";
170
171   switch (hr) {
172     case AUDCLNT_E_NOT_INITIALIZED:
173       s = "AUDCLNT_E_NOT_INITIALIZED";
174       break;
175     case AUDCLNT_E_ALREADY_INITIALIZED:
176       s = "AUDCLNT_E_ALREADY_INITIALIZED";
177       break;
178     case AUDCLNT_E_WRONG_ENDPOINT_TYPE:
179       s = "AUDCLNT_E_WRONG_ENDPOINT_TYPE";
180       break;
181     case AUDCLNT_E_DEVICE_INVALIDATED:
182       s = "AUDCLNT_E_DEVICE_INVALIDATED";
183       break;
184     case AUDCLNT_E_NOT_STOPPED:
185       s = "AUDCLNT_E_NOT_STOPPED";
186       break;
187     case AUDCLNT_E_BUFFER_TOO_LARGE:
188       s = "AUDCLNT_E_BUFFER_TOO_LARGE";
189       break;
190     case AUDCLNT_E_OUT_OF_ORDER:
191       s = "AUDCLNT_E_OUT_OF_ORDER";
192       break;
193     case AUDCLNT_E_UNSUPPORTED_FORMAT:
194       s = "AUDCLNT_E_UNSUPPORTED_FORMAT";
195       break;
196     case AUDCLNT_E_INVALID_DEVICE_PERIOD:
197       s = "AUDCLNT_E_INVALID_DEVICE_PERIOD";
198       break;
199     case AUDCLNT_E_INVALID_SIZE:
200       s = "AUDCLNT_E_INVALID_SIZE";
201       break;
202     case AUDCLNT_E_DEVICE_IN_USE:
203       s = "AUDCLNT_E_DEVICE_IN_USE";
204       break;
205     case AUDCLNT_E_BUFFER_OPERATION_PENDING:
206       s = "AUDCLNT_E_BUFFER_OPERATION_PENDING";
207       break;
208     case AUDCLNT_E_BUFFER_SIZE_ERROR:
209       s = "AUDCLNT_E_BUFFER_SIZE_ERROR";
210       break;
211     case AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED:
212       s = "AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED";
213       break;
214     case AUDCLNT_E_THREAD_NOT_REGISTERED:
215       s = "AUDCLNT_E_THREAD_NOT_REGISTERED";
216       break;
217     case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED:
218       s = "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED";
219       break;
220     case AUDCLNT_E_ENDPOINT_CREATE_FAILED:
221       s = "AUDCLNT_E_ENDPOINT_CREATE_FAILED";
222       break;
223     case AUDCLNT_E_SERVICE_NOT_RUNNING:
224       s = "AUDCLNT_E_SERVICE_NOT_RUNNING";
225       break;
226     case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED:
227       s = "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED";
228       break;
229     case AUDCLNT_E_EXCLUSIVE_MODE_ONLY:
230       s = "AUDCLNT_E_EXCLUSIVE_MODE_ONLY";
231       break;
232     case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL:
233       s = "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL";
234       break;
235     case AUDCLNT_E_EVENTHANDLE_NOT_SET:
236       s = "AUDCLNT_E_EVENTHANDLE_NOT_SET";
237       break;
238     case AUDCLNT_E_INCORRECT_BUFFER_SIZE:
239       s = "AUDCLNT_E_INCORRECT_BUFFER_SIZE";
240       break;
241     case AUDCLNT_E_CPUUSAGE_EXCEEDED:
242       s = "AUDCLNT_E_CPUUSAGE_EXCEEDED";
243       break;
244     case AUDCLNT_S_BUFFER_EMPTY:
245       s = "AUDCLNT_S_BUFFER_EMPTY";
246       break;
247     case AUDCLNT_S_THREAD_ALREADY_REGISTERED:
248       s = "AUDCLNT_S_THREAD_ALREADY_REGISTERED";
249       break;
250     case AUDCLNT_S_POSITION_STALLED:
251       s = "AUDCLNT_S_POSITION_STALLED";
252       break;
253     case E_POINTER:
254       s = "E_POINTER";
255       break;
256     case E_INVALIDARG:
257       s = "E_INVALIDARG";
258       break;
259   }
260
261   return s;
262 }
263
264 gchar *
265 gst_wasapi_util_hresult_to_string (HRESULT hr)
266 {
267   DWORD flags;
268   gchar *ret_text;
269   LPTSTR error_text = NULL;
270
271   flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER
272       | FORMAT_MESSAGE_IGNORE_INSERTS;
273   FormatMessage (flags, NULL, hr, MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
274       (LPTSTR) & error_text, 0, NULL);
275
276   /* If we couldn't get the error msg, try the fallback switch statement */
277   if (error_text == NULL)
278     return g_strdup (hresult_to_string_fallback (hr));
279
280 #ifdef UNICODE
281   /* If UNICODE is defined, LPTSTR is LPWSTR which is UTF-16 */
282   ret_text = g_utf16_to_utf8 (error_text, 0, NULL, NULL, NULL);
283 #else
284   ret_text = g_strdup (error_text);
285 #endif
286
287   LocalFree (error_text);
288   return ret_text;
289 }
290
291 static IMMDeviceEnumerator *
292 gst_wasapi_util_get_device_enumerator (GstElement * self)
293 {
294   HRESULT hr;
295   IMMDeviceEnumerator *enumerator = NULL;
296
297   hr = CoCreateInstance (&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL,
298       &IID_IMMDeviceEnumerator, (void **) &enumerator);
299   HR_FAILED_RET (hr, CoCreateInstance (MMDeviceEnumerator), NULL);
300
301   return enumerator;
302 }
303
304 gboolean
305 gst_wasapi_util_get_devices (GstElement * self, gboolean active,
306     GList ** devices)
307 {
308   gboolean res = FALSE;
309   static GstStaticCaps scaps = GST_STATIC_CAPS (GST_WASAPI_STATIC_CAPS);
310   DWORD dwStateMask = active ? DEVICE_STATE_ACTIVE : DEVICE_STATEMASK_ALL;
311   IMMDeviceCollection *device_collection = NULL;
312   IMMDeviceEnumerator *enumerator = NULL;
313   const gchar *device_class, *element_name;
314   guint ii, count;
315   HRESULT hr;
316
317   *devices = NULL;
318
319   enumerator = gst_wasapi_util_get_device_enumerator (self);
320   if (!enumerator)
321     return FALSE;
322
323   hr = IMMDeviceEnumerator_EnumAudioEndpoints (enumerator, eAll, dwStateMask,
324       &device_collection);
325   HR_FAILED_GOTO (hr, IMMDeviceEnumerator::EnumAudioEndpoints, err);
326
327   hr = IMMDeviceCollection_GetCount (device_collection, &count);
328   HR_FAILED_GOTO (hr, IMMDeviceCollection::GetCount, err);
329
330   /* Create a GList of GstDevices* to return */
331   for (ii = 0; ii < count; ii++) {
332     IMMDevice *item = NULL;
333     IMMEndpoint *endpoint = NULL;
334     IAudioClient *client = NULL;
335     IPropertyStore *prop_store = NULL;
336     WAVEFORMATEX *format = NULL;
337     gchar *description = NULL;
338     gchar *strid = NULL;
339     EDataFlow dataflow;
340     PROPVARIANT var;
341     wchar_t *wstrid;
342     GstDevice *device;
343     GstStructure *props;
344     GstCaps *caps;
345
346     hr = IMMDeviceCollection_Item (device_collection, ii, &item);
347     if (hr != S_OK)
348       continue;
349
350     hr = IMMDevice_QueryInterface (item, &IID_IMMEndpoint, (void **) &endpoint);
351     if (hr != S_OK)
352       goto next;
353
354     hr = IMMEndpoint_GetDataFlow (endpoint, &dataflow);
355     if (hr != S_OK)
356       goto next;
357
358     if (dataflow == eRender) {
359       device_class = "Audio/Sink";
360       element_name = "wasapisink";
361     } else {
362       device_class = "Audio/Source";
363       element_name = "wasapisrc";
364     }
365
366     PropVariantInit (&var);
367
368     hr = IMMDevice_GetId (item, &wstrid);
369     if (hr != S_OK)
370       goto next;
371     strid = g_utf16_to_utf8 (wstrid, -1, NULL, NULL, NULL);
372     CoTaskMemFree (wstrid);
373
374     hr = IMMDevice_OpenPropertyStore (item, STGM_READ, &prop_store);
375     if (hr != S_OK)
376       goto next;
377
378     /* NOTE: More properties can be added as needed from here:
379      * https://msdn.microsoft.com/en-us/library/windows/desktop/dd370794(v=vs.85).aspx */
380     hr = IPropertyStore_GetValue (prop_store, &PKEY_Device_FriendlyName, &var);
381     if (hr != S_OK)
382       goto next;
383     description = g_utf16_to_utf8 (var.pwszVal, -1, NULL, NULL, NULL);
384     PropVariantClear (&var);
385
386     /* Get the audio client so we can fetch the mix format for shared mode
387      * to get the device format for exclusive mode (or something close to that)
388      * fetch PKEY_AudioEngine_DeviceFormat from the property store. */
389     hr = IMMDevice_Activate (item, &IID_IAudioClient, CLSCTX_ALL, NULL,
390         (void **) &client);
391     if (hr != S_OK) {
392       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
393       GST_ERROR_OBJECT (self, "IMMDevice::Activate (IID_IAudioClient) failed"
394           "on %s: %s", strid, msg);
395       g_free (msg);
396       goto next;
397     }
398
399     hr = IAudioClient_GetMixFormat (client, &format);
400     if (hr != S_OK || format == NULL) {
401       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
402       GST_ERROR_OBJECT ("GetMixFormat failed on %s: %s", strid, msg);
403       g_free (msg);
404       goto next;
405     }
406
407     if (!gst_wasapi_util_parse_waveformatex ((WAVEFORMATEXTENSIBLE *) format,
408             gst_static_caps_get (&scaps), &caps, NULL))
409       goto next;
410
411     /* Set some useful properties */
412     props = gst_structure_new ("wasapi-proplist",
413         "device.api", G_TYPE_STRING, "wasapi",
414         "device.strid", G_TYPE_STRING, GST_STR_NULL (strid),
415         "wasapi.device.description", G_TYPE_STRING, description, NULL);
416
417     device = g_object_new (GST_TYPE_WASAPI_DEVICE, "device", strid,
418         "display-name", description, "caps", caps,
419         "device-class", device_class, "properties", props, NULL);
420     GST_WASAPI_DEVICE (device)->element = element_name;
421
422     gst_structure_free (props);
423     gst_caps_unref (caps);
424     *devices = g_list_prepend (*devices, device);
425
426   next:
427     PropVariantClear (&var);
428     if (prop_store)
429       IUnknown_Release (prop_store);
430     if (endpoint)
431       IUnknown_Release (endpoint);
432     if (client)
433       IUnknown_Release (client);
434     if (item)
435       IUnknown_Release (item);
436     if (description)
437       g_free (description);
438     if (strid)
439       g_free (strid);
440   }
441
442   res = TRUE;
443
444 err:
445   if (enumerator)
446     IUnknown_Release (enumerator);
447   if (device_collection)
448     IUnknown_Release (device_collection);
449   return res;
450 }
451
452 gboolean
453 gst_wasapi_util_get_device_format (GstElement * self,
454     gint device_mode, IMMDevice * device, IAudioClient * client,
455     WAVEFORMATEX ** ret_format)
456 {
457   WAVEFORMATEX *format;
458   HRESULT hr;
459
460   *ret_format = NULL;
461
462   hr = IAudioClient_GetMixFormat (client, &format);
463   HR_FAILED_RET (hr, IAudioClient::GetMixFormat, FALSE);
464
465   /* WASAPI always accepts the format returned by GetMixFormat in shared mode */
466   if (device_mode == AUDCLNT_SHAREMODE_SHARED)
467     goto out;
468
469   /* WASAPI may or may not support this format in exclusive mode */
470   hr = IAudioClient_IsFormatSupported (client, AUDCLNT_SHAREMODE_EXCLUSIVE,
471       format, NULL);
472   if (hr == S_OK)
473     goto out;
474
475   CoTaskMemFree (format);
476
477   /* Open the device property store, and get the format that WASAPI has been
478    * using for sending data to the device */
479   {
480     PROPVARIANT var;
481     IPropertyStore *prop_store = NULL;
482
483     hr = IMMDevice_OpenPropertyStore (device, STGM_READ, &prop_store);
484     HR_FAILED_RET (hr, IMMDevice::OpenPropertyStore, FALSE);
485
486     hr = IPropertyStore_GetValue (prop_store, &PKEY_AudioEngine_DeviceFormat,
487         &var);
488     if (hr != S_OK) {
489       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
490       GST_ERROR_OBJECT (self, "GetValue failed: %s", msg);
491       g_free (msg);
492       IUnknown_Release (prop_store);
493       return FALSE;
494     }
495
496     format = malloc (var.blob.cbSize);
497     memcpy (format, var.blob.pBlobData, var.blob.cbSize);
498
499     PropVariantClear (&var);
500     IUnknown_Release (prop_store);
501   }
502
503   /* WASAPI may or may not support this format in exclusive mode */
504   hr = IAudioClient_IsFormatSupported (client, AUDCLNT_SHAREMODE_EXCLUSIVE,
505       format, NULL);
506   if (hr == S_OK)
507     goto out;
508
509   GST_ERROR_OBJECT (self, "AudioEngine DeviceFormat not supported");
510   free (format);
511   return FALSE;
512
513 out:
514   *ret_format = format;
515   return TRUE;
516 }
517
518 gboolean
519 gst_wasapi_util_get_device_client (GstElement * self,
520     gboolean capture, gint role, const wchar_t * device_strid,
521     IMMDevice ** ret_device, IAudioClient ** ret_client)
522 {
523   gboolean res = FALSE;
524   HRESULT hr;
525   IMMDeviceEnumerator *enumerator = NULL;
526   IMMDevice *device = NULL;
527   IAudioClient *client = NULL;
528
529   if (!(enumerator = gst_wasapi_util_get_device_enumerator (self)))
530     goto beach;
531
532   if (!device_strid) {
533     hr = IMMDeviceEnumerator_GetDefaultAudioEndpoint (enumerator,
534         capture ? eCapture : eRender, role, &device);
535     HR_FAILED_GOTO (hr, IMMDeviceEnumerator::GetDefaultAudioEndpoint, beach);
536   } else {
537     hr = IMMDeviceEnumerator_GetDevice (enumerator, device_strid, &device);
538     if (hr != S_OK) {
539       gchar *msg = gst_wasapi_util_hresult_to_string (hr);
540       GST_ERROR_OBJECT (self, "IMMDeviceEnumerator::GetDevice (%S) failed"
541           ": %s", device_strid, msg);
542       g_free (msg);
543       goto beach;
544     }
545   }
546
547   hr = IMMDevice_Activate (device, &IID_IAudioClient, CLSCTX_ALL, NULL,
548       (void **) &client);
549   HR_FAILED_GOTO (hr, IMMDevice::Activate (IID_IAudioClient), beach);
550
551   IUnknown_AddRef (client);
552   IUnknown_AddRef (device);
553   *ret_client = client;
554   *ret_device = device;
555
556   res = TRUE;
557
558 beach:
559   if (client != NULL)
560     IUnknown_Release (client);
561
562   if (device != NULL)
563     IUnknown_Release (device);
564
565   if (enumerator != NULL)
566     IUnknown_Release (enumerator);
567
568   return res;
569 }
570
571 gboolean
572 gst_wasapi_util_get_render_client (GstElement * self, IAudioClient * client,
573     IAudioRenderClient ** ret_render_client)
574 {
575   gboolean res = FALSE;
576   HRESULT hr;
577   IAudioRenderClient *render_client = NULL;
578
579   hr = IAudioClient_GetService (client, &IID_IAudioRenderClient,
580       (void **) &render_client);
581   HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
582
583   *ret_render_client = render_client;
584   res = TRUE;
585
586 beach:
587   return res;
588 }
589
590 gboolean
591 gst_wasapi_util_get_capture_client (GstElement * self, IAudioClient * client,
592     IAudioCaptureClient ** ret_capture_client)
593 {
594   gboolean res = FALSE;
595   HRESULT hr;
596   IAudioCaptureClient *capture_client = NULL;
597
598   hr = IAudioClient_GetService (client, &IID_IAudioCaptureClient,
599       (void **) &capture_client);
600   HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
601
602   *ret_capture_client = capture_client;
603   res = TRUE;
604
605 beach:
606   return res;
607 }
608
609 gboolean
610 gst_wasapi_util_get_clock (GstElement * self, IAudioClient * client,
611     IAudioClock ** ret_clock)
612 {
613   gboolean res = FALSE;
614   HRESULT hr;
615   IAudioClock *clock = NULL;
616
617   hr = IAudioClient_GetService (client, &IID_IAudioClock, (void **) &clock);
618   HR_FAILED_GOTO (hr, IAudioClient::GetService, beach);
619
620   *ret_clock = clock;
621   res = TRUE;
622
623 beach:
624   return res;
625 }
626
627 static const gchar *
628 gst_waveformatex_to_audio_format (WAVEFORMATEXTENSIBLE * format)
629 {
630   const gchar *fmt_str = NULL;
631   GstAudioFormat fmt = GST_AUDIO_FORMAT_UNKNOWN;
632
633   if (format->Format.wFormatTag == WAVE_FORMAT_PCM) {
634     fmt = gst_audio_format_build_integer (TRUE, G_LITTLE_ENDIAN,
635         format->Format.wBitsPerSample, format->Format.wBitsPerSample);
636   } else if (format->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
637     if (format->Format.wBitsPerSample == 32)
638       fmt = GST_AUDIO_FORMAT_F32LE;
639     else if (format->Format.wBitsPerSample == 64)
640       fmt = GST_AUDIO_FORMAT_F64LE;
641   } else if (format->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
642     if (IsEqualGUID (&format->SubFormat, &KSDATAFORMAT_SUBTYPE_PCM)) {
643       fmt = gst_audio_format_build_integer (TRUE, G_LITTLE_ENDIAN,
644           format->Format.wBitsPerSample, format->Samples.wValidBitsPerSample);
645     } else if (IsEqualGUID (&format->SubFormat,
646             &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
647       if (format->Format.wBitsPerSample == 32
648           && format->Samples.wValidBitsPerSample == 32)
649         fmt = GST_AUDIO_FORMAT_F32LE;
650       else if (format->Format.wBitsPerSample == 64 &&
651           format->Samples.wValidBitsPerSample == 64)
652         fmt = GST_AUDIO_FORMAT_F64LE;
653     }
654   }
655
656   if (fmt != GST_AUDIO_FORMAT_UNKNOWN)
657     fmt_str = gst_audio_format_to_string (fmt);
658
659   return fmt_str;
660 }
661
662 static void
663 gst_wasapi_util_channel_position_all_none (guint channels,
664     GstAudioChannelPosition * position)
665 {
666   int ii;
667   for (ii = 0; ii < channels; ii++)
668     position[ii] = GST_AUDIO_CHANNEL_POSITION_NONE;
669 }
670
671 /* Parse WAVEFORMATEX to get the gstreamer channel mask, and the wasapi channel
672  * positions so GstAudioRingbuffer can reorder the audio data to match the
673  * gstreamer channel order. */
674 static guint64
675 gst_wasapi_util_waveformatex_to_channel_mask (WAVEFORMATEXTENSIBLE * format,
676     GstAudioChannelPosition ** out_position)
677 {
678   int ii;
679   guint64 mask = 0;
680   WORD nChannels = format->Format.nChannels;
681   DWORD dwChannelMask = format->dwChannelMask;
682   GstAudioChannelPosition *pos = NULL;
683
684   pos = g_new (GstAudioChannelPosition, nChannels);
685   gst_wasapi_util_channel_position_all_none (nChannels, pos);
686
687   /* Too many channels, have to assume that they are all non-positional */
688   if (nChannels > G_N_ELEMENTS (wasapi_to_gst_pos)) {
689     GST_INFO ("wasapi: got too many (%i) channels, assuming non-positional",
690         nChannels);
691     goto out;
692   }
693
694   /* Too many bits in the channel mask, and the bits don't match nChannels */
695   if (dwChannelMask >> (G_N_ELEMENTS (wasapi_to_gst_pos) + 1) != 0) {
696     GST_WARNING ("wasapi: too many bits in channel mask (%lu), assuming "
697         "non-positional", dwChannelMask);
698     goto out;
699   }
700
701   /* Map WASAPI's channel mask to Gstreamer's channel mask and positions.
702    * If the no. of bits in the mask > nChannels, we will ignore the extra. */
703   for (ii = 0; ii < nChannels; ii++) {
704     if (!(dwChannelMask & wasapi_to_gst_pos[ii].wasapi_pos))
705       /* Non-positional or unknown position, warn? */
706       continue;
707     mask |= G_GUINT64_CONSTANT (1) << wasapi_to_gst_pos[ii].gst_pos;
708     pos[ii] = wasapi_to_gst_pos[ii].gst_pos;
709   }
710
711 out:
712   if (out_position)
713     *out_position = pos;
714   return mask;
715 }
716
717 gboolean
718 gst_wasapi_util_parse_waveformatex (WAVEFORMATEXTENSIBLE * format,
719     GstCaps * template_caps, GstCaps ** out_caps,
720     GstAudioChannelPosition ** out_positions)
721 {
722   int ii;
723   const gchar *afmt;
724   guint64 channel_mask;
725
726   *out_caps = NULL;
727
728   /* TODO: handle SPDIF and other encoded formats */
729
730   /* 1 or 2 channels <= 16 bits sample size OR
731    * 1 or 2 channels > 16 bits sample size or >2 channels */
732   if (format->Format.wFormatTag != WAVE_FORMAT_PCM &&
733       format->Format.wFormatTag != WAVE_FORMAT_IEEE_FLOAT &&
734       format->Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
735     /* Unhandled format tag */
736     return FALSE;
737
738   /* WASAPI can only tell us one canonical mix format that it will accept. The
739    * alternative is calling IsFormatSupported on all combinations of formats.
740    * Instead, it's simpler and faster to require conversion inside gstreamer */
741   afmt = gst_waveformatex_to_audio_format (format);
742   if (afmt == NULL)
743     return FALSE;
744
745   *out_caps = gst_caps_copy (template_caps);
746
747   /* This will always return something that might be usable */
748   channel_mask =
749       gst_wasapi_util_waveformatex_to_channel_mask (format, out_positions);
750
751   for (ii = 0; ii < gst_caps_get_size (*out_caps); ii++) {
752     GstStructure *s = gst_caps_get_structure (*out_caps, ii);
753
754     gst_structure_set (s,
755         "format", G_TYPE_STRING, afmt,
756         "channels", G_TYPE_INT, format->Format.nChannels,
757         "rate", G_TYPE_INT, format->Format.nSamplesPerSec,
758         "channel-mask", GST_TYPE_BITMASK, channel_mask, NULL);
759   }
760
761   return TRUE;
762 }
763
764 void
765 gst_wasapi_util_get_best_buffer_sizes (GstAudioRingBufferSpec * spec,
766     gboolean exclusive, REFERENCE_TIME default_period,
767     REFERENCE_TIME min_period, REFERENCE_TIME * ret_period,
768     REFERENCE_TIME * ret_buffer_duration)
769 {
770   REFERENCE_TIME use_period, use_buffer;
771
772   /* Figure out what integral device period to use as the base */
773   if (exclusive) {
774     /* Exclusive mode can run at multiples of either the minimum period or the
775      * default period; these are on the hardware ringbuffer */
776     if (spec->latency_time * 10 > default_period)
777       use_period = default_period;
778     else
779       use_period = min_period;
780   } else {
781     /* Shared mode always runs at the default period, so if we want a larger
782      * period (for lower CPU usage), we do it as a multiple of that */
783     use_period = default_period;
784   }
785
786   /* Ensure that the period (latency_time) used is an integral multiple of
787    * either the default period or the minimum period */
788   use_period = use_period * MAX ((spec->latency_time * 10) / use_period, 1);
789
790   if (exclusive) {
791     /* Buffer duration is the same as the period in exclusive mode. The
792      * hardware is always writing out one buffer (of size *ret_period), and
793      * we're writing to the other one. */
794     use_buffer = use_period;
795   } else {
796     /* Ask WASAPI to create a software ringbuffer of at least this size; it may
797      * be larger so the actual buffer time may be different, which is why after
798      * initialization we read the buffer duration actually in-use and set
799      * segsize/segtotal from that. */
800     use_buffer = spec->buffer_time * 10;
801     /* Has to be at least twice the period */
802     if (use_buffer < 2 * use_period)
803       use_buffer = 2 * use_period;
804   }
805
806   *ret_period = use_period;
807   *ret_buffer_duration = use_buffer;
808 }