2 * Copyright (C) 2008 Ole André Vadla Ravnås <ole.andre.ravnas@tandberg.com>
3 * Copyright (C) 2018 Centricular Ltd.
4 * Author: Nirbheek Chauhan <nirbheek@centricular.com>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public
17 * License along with this library; if not, write to the
18 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
23 * SECTION:element-wasapisrc
26 * Provides audio capture from the Windows Audio Session API available with
29 * ## Example pipelines
31 * gst-launch-1.0 -v wasapisrc ! fakesink
32 * ]| Capture from the default audio device and render to fakesink.
35 * gst-launch-1.0 -v wasapisrc low-latency=true ! fakesink
36 * ]| Capture from the default audio device with the minimum possible latency and render to fakesink.
43 #include "gstwasapisrc.h"
47 GST_DEBUG_CATEGORY_STATIC (gst_wasapi_src_debug);
48 #define GST_CAT_DEFAULT gst_wasapi_src_debug
50 static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
53 GST_STATIC_CAPS (GST_WASAPI_STATIC_CAPS));
55 #define DEFAULT_ROLE GST_WASAPI_DEVICE_ROLE_CONSOLE
56 #define DEFAULT_LOOPBACK FALSE
57 #define DEFAULT_EXCLUSIVE FALSE
58 #define DEFAULT_LOW_LATENCY FALSE
59 #define DEFAULT_AUDIOCLIENT3 FALSE
72 static void gst_wasapi_src_dispose (GObject * object);
73 static void gst_wasapi_src_finalize (GObject * object);
74 static void gst_wasapi_src_set_property (GObject * object, guint prop_id,
75 const GValue * value, GParamSpec * pspec);
76 static void gst_wasapi_src_get_property (GObject * object, guint prop_id,
77 GValue * value, GParamSpec * pspec);
79 static GstCaps *gst_wasapi_src_get_caps (GstBaseSrc * bsrc, GstCaps * filter);
81 static gboolean gst_wasapi_src_open (GstAudioSrc * asrc);
82 static gboolean gst_wasapi_src_close (GstAudioSrc * asrc);
83 static gboolean gst_wasapi_src_prepare (GstAudioSrc * asrc,
84 GstAudioRingBufferSpec * spec);
85 static gboolean gst_wasapi_src_unprepare (GstAudioSrc * asrc);
86 static guint gst_wasapi_src_read (GstAudioSrc * asrc, gpointer data,
87 guint length, GstClockTime * timestamp);
88 static guint gst_wasapi_src_delay (GstAudioSrc * asrc);
89 static void gst_wasapi_src_reset (GstAudioSrc * asrc);
91 static GstClockTime gst_wasapi_src_get_time (GstClock * clock,
94 #define gst_wasapi_src_parent_class parent_class
95 G_DEFINE_TYPE (GstWasapiSrc, gst_wasapi_src, GST_TYPE_AUDIO_SRC);
98 gst_wasapi_src_class_init (GstWasapiSrcClass * klass)
100 GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
101 GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
102 GstBaseSrcClass *gstbasesrc_class = GST_BASE_SRC_CLASS (klass);
103 GstAudioSrcClass *gstaudiosrc_class = GST_AUDIO_SRC_CLASS (klass);
105 gobject_class->dispose = gst_wasapi_src_dispose;
106 gobject_class->finalize = gst_wasapi_src_finalize;
107 gobject_class->set_property = gst_wasapi_src_set_property;
108 gobject_class->get_property = gst_wasapi_src_get_property;
110 g_object_class_install_property (gobject_class,
112 g_param_spec_enum ("role", "Role",
113 "Role of the device: communications, multimedia, etc",
114 GST_WASAPI_DEVICE_TYPE_ROLE, DEFAULT_ROLE, G_PARAM_READWRITE |
115 G_PARAM_STATIC_STRINGS | GST_PARAM_MUTABLE_READY));
117 g_object_class_install_property (gobject_class,
119 g_param_spec_string ("device", "Device",
120 "WASAPI playback device as a GUID string",
121 NULL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
123 g_object_class_install_property (gobject_class,
125 g_param_spec_boolean ("loopback", "Loopback recording",
126 "Open the sink device for loopback recording",
127 DEFAULT_LOOPBACK, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
129 g_object_class_install_property (gobject_class,
131 g_param_spec_boolean ("exclusive", "Exclusive mode",
132 "Open the device in exclusive mode",
133 DEFAULT_EXCLUSIVE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
135 g_object_class_install_property (gobject_class,
137 g_param_spec_boolean ("low-latency", "Low latency",
138 "Optimize all settings for lowest latency. Always safe to enable.",
139 DEFAULT_LOW_LATENCY, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
141 g_object_class_install_property (gobject_class,
143 g_param_spec_boolean ("use-audioclient3", "Use the AudioClient3 API",
144 "Whether to use the Windows 10 AudioClient3 API when available",
145 DEFAULT_AUDIOCLIENT3, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
147 gst_element_class_add_static_pad_template (gstelement_class, &src_template);
148 gst_element_class_set_static_metadata (gstelement_class, "WasapiSrc",
150 "Stream audio from an audio capture device through WASAPI",
151 "Nirbheek Chauhan <nirbheek@centricular.com>, "
152 "Ole André Vadla Ravnås <ole.andre.ravnas@tandberg.com>");
154 gstbasesrc_class->get_caps = GST_DEBUG_FUNCPTR (gst_wasapi_src_get_caps);
156 gstaudiosrc_class->open = GST_DEBUG_FUNCPTR (gst_wasapi_src_open);
157 gstaudiosrc_class->close = GST_DEBUG_FUNCPTR (gst_wasapi_src_close);
158 gstaudiosrc_class->read = GST_DEBUG_FUNCPTR (gst_wasapi_src_read);
159 gstaudiosrc_class->prepare = GST_DEBUG_FUNCPTR (gst_wasapi_src_prepare);
160 gstaudiosrc_class->unprepare = GST_DEBUG_FUNCPTR (gst_wasapi_src_unprepare);
161 gstaudiosrc_class->delay = GST_DEBUG_FUNCPTR (gst_wasapi_src_delay);
162 gstaudiosrc_class->reset = GST_DEBUG_FUNCPTR (gst_wasapi_src_reset);
164 GST_DEBUG_CATEGORY_INIT (gst_wasapi_src_debug, "wasapisrc",
165 0, "Windows audio session API source");
169 gst_wasapi_src_init (GstWasapiSrc * self)
171 /* override with a custom clock */
172 if (GST_AUDIO_BASE_SRC (self)->clock)
173 gst_object_unref (GST_AUDIO_BASE_SRC (self)->clock);
175 GST_AUDIO_BASE_SRC (self)->clock = gst_audio_clock_new ("GstWasapiSrcClock",
176 gst_wasapi_src_get_time, gst_object_ref (self),
177 (GDestroyNotify) gst_object_unref);
179 self->role = DEFAULT_ROLE;
180 self->sharemode = AUDCLNT_SHAREMODE_SHARED;
181 self->loopback = DEFAULT_LOOPBACK;
182 self->low_latency = DEFAULT_LOW_LATENCY;
183 self->try_audioclient3 = DEFAULT_AUDIOCLIENT3;
184 self->event_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
185 self->client_needs_restart = FALSE;
191 gst_wasapi_src_dispose (GObject * object)
193 GstWasapiSrc *self = GST_WASAPI_SRC (object);
195 if (self->event_handle != NULL) {
196 CloseHandle (self->event_handle);
197 self->event_handle = NULL;
200 if (self->client_clock != NULL) {
201 IUnknown_Release (self->client_clock);
202 self->client_clock = NULL;
205 if (self->client != NULL) {
206 IUnknown_Release (self->client);
210 if (self->capture_client != NULL) {
211 IUnknown_Release (self->capture_client);
212 self->capture_client = NULL;
215 G_OBJECT_CLASS (parent_class)->dispose (object);
219 gst_wasapi_src_finalize (GObject * object)
221 GstWasapiSrc *self = GST_WASAPI_SRC (object);
223 g_clear_pointer (&self->mix_format, CoTaskMemFree);
227 g_clear_pointer (&self->cached_caps, gst_caps_unref);
228 g_clear_pointer (&self->positions, g_free);
229 g_clear_pointer (&self->device_strid, g_free);
231 G_OBJECT_CLASS (parent_class)->finalize (object);
235 gst_wasapi_src_set_property (GObject * object, guint prop_id,
236 const GValue * value, GParamSpec * pspec)
238 GstWasapiSrc *self = GST_WASAPI_SRC (object);
242 self->role = gst_wasapi_device_role_to_erole (g_value_get_enum (value));
246 const gchar *device = g_value_get_string (value);
247 g_free (self->device_strid);
249 device ? g_utf8_to_utf16 (device, -1, NULL, NULL, NULL) : NULL;
253 self->loopback = g_value_get_boolean (value);
256 self->sharemode = g_value_get_boolean (value)
257 ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED;
259 case PROP_LOW_LATENCY:
260 self->low_latency = g_value_get_boolean (value);
262 case PROP_AUDIOCLIENT3:
263 self->try_audioclient3 = g_value_get_boolean (value);
266 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
272 gst_wasapi_src_get_property (GObject * object, guint prop_id,
273 GValue * value, GParamSpec * pspec)
275 GstWasapiSrc *self = GST_WASAPI_SRC (object);
279 g_value_set_enum (value, gst_wasapi_erole_to_device_role (self->role));
282 g_value_take_string (value, self->device_strid ?
283 g_utf16_to_utf8 (self->device_strid, -1, NULL, NULL, NULL) : NULL);
286 g_value_set_boolean (value, self->loopback);
289 g_value_set_boolean (value,
290 self->sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE);
292 case PROP_LOW_LATENCY:
293 g_value_set_boolean (value, self->low_latency);
295 case PROP_AUDIOCLIENT3:
296 g_value_set_boolean (value, self->try_audioclient3);
299 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
305 gst_wasapi_src_can_audioclient3 (GstWasapiSrc * self)
307 if (self->sharemode == AUDCLNT_SHAREMODE_SHARED &&
308 self->try_audioclient3 && gst_wasapi_util_have_audioclient3 ())
314 gst_wasapi_src_get_caps (GstBaseSrc * bsrc, GstCaps * filter)
316 GstWasapiSrc *self = GST_WASAPI_SRC (bsrc);
317 WAVEFORMATEX *format = NULL;
318 GstCaps *caps = NULL;
320 GST_DEBUG_OBJECT (self, "entering get caps");
322 if (self->cached_caps) {
323 caps = gst_caps_ref (self->cached_caps);
325 GstCaps *template_caps;
328 template_caps = gst_pad_get_pad_template_caps (bsrc->srcpad);
331 caps = template_caps;
335 ret = gst_wasapi_util_get_device_format (GST_ELEMENT (self),
336 self->sharemode, self->device, self->client, &format);
338 GST_ELEMENT_ERROR (self, STREAM, FORMAT, (NULL),
339 ("failed to detect format"));
340 gst_caps_unref (template_caps);
344 gst_wasapi_util_parse_waveformatex ((WAVEFORMATEXTENSIBLE *) format,
345 template_caps, &caps, &self->positions);
347 GST_ELEMENT_ERROR (self, STREAM, FORMAT, (NULL), ("unknown format"));
348 gst_caps_unref (template_caps);
353 gchar *pos_str = gst_audio_channel_positions_to_string (self->positions,
355 GST_INFO_OBJECT (self, "positions are: %s", pos_str);
359 self->mix_format = format;
360 gst_caps_replace (&self->cached_caps, caps);
361 gst_caps_unref (template_caps);
366 gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
367 gst_caps_unref (caps);
372 GST_DEBUG_OBJECT (self, "returning caps %" GST_PTR_FORMAT, caps);
377 gst_wasapi_src_open (GstAudioSrc * asrc)
379 GstWasapiSrc *self = GST_WASAPI_SRC (asrc);
380 gboolean res = FALSE;
381 IAudioClient *client = NULL;
382 IMMDevice *device = NULL;
387 /* FIXME: Switching the default device does not switch the stream to it,
388 * even if the old device was unplugged. We need to handle this somehow.
389 * For example, perhaps we should automatically switch to the new device if
390 * the default device is changed and a device isn't explicitly selected. */
391 if (!gst_wasapi_util_get_device_client (GST_ELEMENT (self),
392 self->loopback ? eRender : eCapture, self->role, self->device_strid,
394 if (!self->device_strid)
395 GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ, (NULL),
396 ("Failed to get default device"));
398 GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ, (NULL),
399 ("Failed to open device %S", self->device_strid));
403 self->client = client;
404 self->device = device;
413 gst_wasapi_src_close (GstAudioSrc * asrc)
415 GstWasapiSrc *self = GST_WASAPI_SRC (asrc);
417 if (self->device != NULL) {
418 IUnknown_Release (self->device);
422 if (self->client != NULL) {
423 IUnknown_Release (self->client);
431 gst_wasapi_src_prepare (GstAudioSrc * asrc, GstAudioRingBufferSpec * spec)
433 GstWasapiSrc *self = GST_WASAPI_SRC (asrc);
434 gboolean res = FALSE;
435 REFERENCE_TIME latency_rt;
436 guint bpf, rate, devicep_frames, buffer_frames;
441 if (gst_wasapi_src_can_audioclient3 (self)) {
442 if (!gst_wasapi_util_initialize_audioclient3 (GST_ELEMENT (self), spec,
443 (IAudioClient3 *) self->client, self->mix_format, self->low_latency,
444 self->loopback, &devicep_frames))
447 if (!gst_wasapi_util_initialize_audioclient (GST_ELEMENT (self), spec,
448 self->client, self->mix_format, self->sharemode, self->low_latency,
449 self->loopback, &devicep_frames))
453 bpf = GST_AUDIO_INFO_BPF (&spec->info);
454 rate = GST_AUDIO_INFO_RATE (&spec->info);
456 /* Total size in frames of the allocated buffer that we will read from */
457 hr = IAudioClient_GetBufferSize (self->client, &buffer_frames);
458 HR_FAILED_GOTO (hr, IAudioClient::GetBufferSize, beach);
460 GST_INFO_OBJECT (self, "buffer size is %i frames, device period is %i "
461 "frames, bpf is %i bytes, rate is %i Hz", buffer_frames,
462 devicep_frames, bpf, rate);
464 /* Actual latency-time/buffer-time will be different now */
465 spec->segsize = devicep_frames * bpf;
467 /* We need a minimum of 2 segments to ensure glitch-free playback */
468 spec->segtotal = MAX (self->buffer_frame_count * bpf / spec->segsize, 2);
470 GST_INFO_OBJECT (self, "segsize is %i, segtotal is %i", spec->segsize,
473 /* Get WASAPI latency for logging */
474 hr = IAudioClient_GetStreamLatency (self->client, &latency_rt);
475 HR_FAILED_GOTO (hr, IAudioClient::GetStreamLatency, beach);
477 GST_INFO_OBJECT (self, "wasapi stream latency: %" G_GINT64_FORMAT " (%"
478 G_GINT64_FORMAT " ms)", latency_rt, latency_rt / 10000);
480 /* Set the event handler which will trigger reads */
481 hr = IAudioClient_SetEventHandle (self->client, self->event_handle);
482 HR_FAILED_GOTO (hr, IAudioClient::SetEventHandle, beach);
484 /* Get the clock and the clock freq */
485 if (!gst_wasapi_util_get_clock (GST_ELEMENT (self), self->client,
486 &self->client_clock))
489 hr = IAudioClock_GetFrequency (self->client_clock, &self->client_clock_freq);
490 HR_FAILED_GOTO (hr, IAudioClock::GetFrequency, beach);
492 /* Get capture source client and start it up */
493 if (!gst_wasapi_util_get_capture_client (GST_ELEMENT (self), self->client,
494 &self->capture_client)) {
498 hr = IAudioClient_Start (self->client);
499 HR_FAILED_GOTO (hr, IAudioClock::Start, beach);
501 gst_audio_ring_buffer_set_channel_positions (GST_AUDIO_BASE_SRC
502 (self)->ringbuffer, self->positions);
504 /* Increase the thread priority to reduce glitches */
505 self->thread_priority_handle = gst_wasapi_util_set_thread_characteristics ();
509 /* unprepare() is not called if prepare() fails, but we want it to be, so call
510 * it manually when needed */
512 gst_wasapi_src_unprepare (asrc);
518 gst_wasapi_src_unprepare (GstAudioSrc * asrc)
520 GstWasapiSrc *self = GST_WASAPI_SRC (asrc);
522 if (self->thread_priority_handle != NULL) {
523 gst_wasapi_util_revert_thread_characteristics
524 (self->thread_priority_handle);
525 self->thread_priority_handle = NULL;
528 if (self->client != NULL) {
529 IAudioClient_Stop (self->client);
532 if (self->capture_client != NULL) {
533 IUnknown_Release (self->capture_client);
534 self->capture_client = NULL;
537 if (self->client_clock != NULL) {
538 IUnknown_Release (self->client_clock);
539 self->client_clock = NULL;
542 self->client_clock_freq = 0;
550 gst_wasapi_src_read (GstAudioSrc * asrc, gpointer data, guint length,
551 GstClockTime * timestamp)
553 GstWasapiSrc *self = GST_WASAPI_SRC (asrc);
556 guint wanted = length;
559 GST_OBJECT_LOCK (self);
560 if (self->client_needs_restart) {
561 hr = IAudioClient_Start (self->client);
562 HR_FAILED_AND (hr, IAudioClient::Start, length = 0; goto beach);
563 self->client_needs_restart = FALSE;
565 GST_OBJECT_UNLOCK (self);
569 guint have_frames, n_frames, want_frames, read_len;
571 /* Wait for data to become available */
572 dwWaitResult = WaitForSingleObject (self->event_handle, INFINITE);
573 if (dwWaitResult != WAIT_OBJECT_0) {
574 GST_ERROR_OBJECT (self, "Error waiting for event handle: %x",
575 (guint) dwWaitResult);
580 hr = IAudioCaptureClient_GetBuffer (self->capture_client,
581 (BYTE **) & from, &have_frames, &flags, NULL, NULL);
583 gchar *msg = gst_wasapi_util_hresult_to_string (hr);
584 if (hr == AUDCLNT_S_BUFFER_EMPTY)
585 GST_WARNING_OBJECT (self, "IAudioCaptureClient::GetBuffer failed: %s"
588 GST_ERROR_OBJECT (self, "IAudioCaptureClient::GetBuffer failed: %s",
596 GST_INFO_OBJECT (self, "buffer flags=%#08x", (guint) flags);
598 /* XXX: How do we handle AUDCLNT_BUFFERFLAGS_SILENT? We're supposed to write
599 * out silence when that flag is set? See:
600 * https://msdn.microsoft.com/en-us/library/windows/desktop/dd370800(v=vs.85).aspx */
602 if (flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY)
603 GST_WARNING_OBJECT (self, "WASAPI reported glitch in buffer");
605 want_frames = wanted / self->mix_format->nBlockAlign;
607 /* If GetBuffer is returning more frames than we can handle, all we can do is
608 * hope that this is temporary and that things will settle down later. */
609 if (G_UNLIKELY (have_frames > want_frames))
610 GST_WARNING_OBJECT (self, "captured too many frames: have %i, want %i",
611 have_frames, want_frames);
613 /* Only copy data that will fit into the allocated buffer of size @length */
614 n_frames = MIN (have_frames, want_frames);
615 read_len = n_frames * self->mix_format->nBlockAlign;
618 guint bpf = self->mix_format->nBlockAlign;
619 GST_DEBUG_OBJECT (self, "have: %i (%i bytes), can read: %i (%i bytes), "
620 "will read: %i (%i bytes)", have_frames, have_frames * bpf,
621 want_frames, wanted, n_frames, read_len);
624 memcpy (data, from, read_len);
627 /* Always release all captured buffers if we've captured any at all */
628 hr = IAudioCaptureClient_ReleaseBuffer (self->capture_client, have_frames);
629 HR_FAILED_AND (hr, IAudioClock::ReleaseBuffer, goto beach);
639 gst_wasapi_src_delay (GstAudioSrc * asrc)
641 GstWasapiSrc *self = GST_WASAPI_SRC (asrc);
645 hr = IAudioClient_GetCurrentPadding (self->client, &delay);
646 HR_FAILED_RET (hr, IAudioClock::GetCurrentPadding, 0);
652 gst_wasapi_src_reset (GstAudioSrc * asrc)
654 GstWasapiSrc *self = GST_WASAPI_SRC (asrc);
660 GST_OBJECT_LOCK (self);
661 hr = IAudioClient_Stop (self->client);
662 HR_FAILED_RET (hr, IAudioClock::Stop,);
664 hr = IAudioClient_Reset (self->client);
665 HR_FAILED_RET (hr, IAudioClock::Reset,);
667 self->client_needs_restart = TRUE;
668 GST_OBJECT_UNLOCK (self);
672 gst_wasapi_src_get_time (GstClock * clock, gpointer user_data)
674 GstWasapiSrc *self = GST_WASAPI_SRC (user_data);
679 if (G_UNLIKELY (self->client_clock == NULL))
680 return GST_CLOCK_TIME_NONE;
682 hr = IAudioClock_GetPosition (self->client_clock, &devpos, NULL);
683 HR_FAILED_RET (hr, IAudioClock::GetPosition, GST_CLOCK_TIME_NONE);
685 result = gst_util_uint64_scale_int (devpos, GST_SECOND,
686 self->client_clock_freq);
689 GST_DEBUG_OBJECT (self, "devpos = %" G_GUINT64_FORMAT
690 " frequency = %" G_GUINT64_FORMAT
691 " result = %" G_GUINT64_FORMAT " ms",
692 devpos, self->client_clock_freq, GST_TIME_AS_MSECONDS (result));