wasapisrc: Correctly handle BUFFERFLAGS_SILENT
[platform/upstream/gstreamer.git] / sys / wasapi / gstwasapisrc.c
index da1e097..2286b0d 100644 (file)
@@ -57,6 +57,9 @@ static GstStaticPadTemplate src_template = GST_STATIC_PAD_TEMPLATE ("src",
 #define DEFAULT_EXCLUSIVE     FALSE
 #define DEFAULT_LOW_LATENCY   FALSE
 #define DEFAULT_AUDIOCLIENT3  FALSE
+/* The clock provided by WASAPI is always off and causes buffers to be late
+ * very quickly on the sink. Disable pending further investigation. */
+#define DEFAULT_PROVIDE_CLOCK FALSE
 
 enum
 {
@@ -88,8 +91,10 @@ static guint gst_wasapi_src_read (GstAudioSrc * asrc, gpointer data,
 static guint gst_wasapi_src_delay (GstAudioSrc * asrc);
 static void gst_wasapi_src_reset (GstAudioSrc * asrc);
 
+#if DEFAULT_PROVIDE_CLOCK
 static GstClockTime gst_wasapi_src_get_time (GstClock * clock,
     gpointer user_data);
+#endif
 
 #define gst_wasapi_src_parent_class parent_class
 G_DEFINE_TYPE (GstWasapiSrc, gst_wasapi_src, GST_TYPE_AUDIO_SRC);
@@ -146,7 +151,7 @@ gst_wasapi_src_class_init (GstWasapiSrcClass * klass)
 
   gst_element_class_add_static_pad_template (gstelement_class, &src_template);
   gst_element_class_set_static_metadata (gstelement_class, "WasapiSrc",
-      "Source/Audio",
+      "Source/Audio/Hardware",
       "Stream audio from an audio capture device through WASAPI",
       "Nirbheek Chauhan <nirbheek@centricular.com>, "
       "Ole André Vadla Ravnås <ole.andre.ravnas@tandberg.com>");
@@ -168,6 +173,7 @@ gst_wasapi_src_class_init (GstWasapiSrcClass * klass)
 static void
 gst_wasapi_src_init (GstWasapiSrc * self)
 {
+#if DEFAULT_PROVIDE_CLOCK
   /* override with a custom clock */
   if (GST_AUDIO_BASE_SRC (self)->clock)
     gst_object_unref (GST_AUDIO_BASE_SRC (self)->clock);
@@ -175,6 +181,7 @@ gst_wasapi_src_init (GstWasapiSrc * self)
   GST_AUDIO_BASE_SRC (self)->clock = gst_audio_clock_new ("GstWasapiSrcClock",
       gst_wasapi_src_get_time, gst_object_ref (self),
       (GDestroyNotify) gst_object_unref);
+#endif
 
   self->role = DEFAULT_ROLE;
   self->sharemode = AUDCLNT_SHAREMODE_SHARED;
@@ -183,8 +190,9 @@ gst_wasapi_src_init (GstWasapiSrc * self)
   self->try_audioclient3 = DEFAULT_AUDIOCLIENT3;
   self->event_handle = CreateEvent (NULL, FALSE, FALSE, NULL);
   self->client_needs_restart = FALSE;
+  self->adapter = gst_adapter_new ();
 
-  CoInitialize (NULL);
+  CoInitializeEx (NULL, COINIT_MULTITHREADED);
 }
 
 static void
@@ -220,7 +228,8 @@ gst_wasapi_src_finalize (GObject * object)
 {
   GstWasapiSrc *self = GST_WASAPI_SRC (object);
 
-  g_clear_pointer (&self->mix_format, CoTaskMemFree);
+  CoTaskMemFree (self->mix_format);
+  self->mix_format = NULL;
 
   CoUninitialize ();
 
@@ -228,6 +237,9 @@ gst_wasapi_src_finalize (GObject * object)
   g_clear_pointer (&self->positions, g_free);
   g_clear_pointer (&self->device_strid, g_free);
 
+  g_object_unref (self->adapter);
+  self->adapter = NULL;
+
   G_OBJECT_CLASS (parent_class)->finalize (object);
 }
 
@@ -436,6 +448,8 @@ gst_wasapi_src_prepare (GstAudioSrc * asrc, GstAudioRingBufferSpec * spec)
   guint bpf, rate, devicep_frames, buffer_frames;
   HRESULT hr;
 
+  CoInitializeEx (NULL, COINIT_MULTITHREADED);
+
   if (gst_wasapi_src_can_audioclient3 (self)) {
     if (!gst_wasapi_util_initialize_audioclient3 (GST_ELEMENT (self), spec,
             (IAudioClient3 *) self->client, self->mix_format, self->low_latency,
@@ -463,7 +477,7 @@ gst_wasapi_src_prepare (GstAudioSrc * asrc, GstAudioRingBufferSpec * spec)
   spec->segsize = devicep_frames * bpf;
 
   /* We need a minimum of 2 segments to ensure glitch-free playback */
-  spec->segtotal = MAX (self->buffer_frame_count * bpf / spec->segsize, 2);
+  spec->segtotal = MAX (buffer_frames * bpf / spec->segsize, 2);
 
   GST_INFO_OBJECT (self, "segsize is %i, segtotal is %i", spec->segsize,
       spec->segtotal);
@@ -487,6 +501,9 @@ gst_wasapi_src_prepare (GstAudioSrc * asrc, GstAudioRingBufferSpec * spec)
   hr = IAudioClock_GetFrequency (self->client_clock, &self->client_clock_freq);
   HR_FAILED_GOTO (hr, IAudioClock::GetFrequency, beach);
 
+  GST_INFO_OBJECT (self, "wasapi clock freq is %" G_GUINT64_FORMAT,
+      self->client_clock_freq);
+
   /* Get capture source client and start it up */
   if (!gst_wasapi_util_get_capture_client (GST_ELEMENT (self), self->client,
           &self->capture_client)) {
@@ -495,13 +512,11 @@ gst_wasapi_src_prepare (GstAudioSrc * asrc, GstAudioRingBufferSpec * spec)
 
   hr = IAudioClient_Start (self->client);
   HR_FAILED_GOTO (hr, IAudioClock::Start, beach);
+  self->client_needs_restart = FALSE;
 
   gst_audio_ring_buffer_set_channel_positions (GST_AUDIO_BASE_SRC
       (self)->ringbuffer, self->positions);
 
-  /* Increase the thread priority to reduce glitches */
-  self->thread_priority_handle = gst_wasapi_util_set_thread_characteristics ();
-
   res = TRUE;
 beach:
   /* unprepare() is not called if prepare() fails, but we want it to be, so call
@@ -517,16 +532,6 @@ gst_wasapi_src_unprepare (GstAudioSrc * asrc)
 {
   GstWasapiSrc *self = GST_WASAPI_SRC (asrc);
 
-  if (self->sharemode == AUDCLNT_SHAREMODE_EXCLUSIVE &&
-      !gst_wasapi_src_can_audioclient3 (self))
-    CoUninitialize ();
-
-  if (self->thread_priority_handle != NULL) {
-    gst_wasapi_util_revert_thread_characteristics
-        (self->thread_priority_handle);
-    self->thread_priority_handle = NULL;
-  }
-
   if (self->client != NULL) {
     IAudioClient_Stop (self->client);
   }
@@ -543,6 +548,8 @@ gst_wasapi_src_unprepare (GstAudioSrc * asrc)
 
   self->client_clock_freq = 0;
 
+  CoUninitialize ();
+
   return TRUE;
 }
 
@@ -554,78 +561,108 @@ gst_wasapi_src_read (GstAudioSrc * asrc, gpointer data, guint length,
   HRESULT hr;
   gint16 *from = NULL;
   guint wanted = length;
+  guint bpf;
   DWORD flags;
 
   GST_OBJECT_LOCK (self);
   if (self->client_needs_restart) {
     hr = IAudioClient_Start (self->client);
-    HR_FAILED_AND (hr, IAudioClient::Start, length = 0; goto beach);
+    HR_FAILED_ELEMENT_ERROR_AND (hr, IAudioClient::Start, self,
+        GST_OBJECT_UNLOCK (self); goto err);
     self->client_needs_restart = FALSE;
+    gst_adapter_clear (self->adapter);
   }
+
+  bpf = self->mix_format->nBlockAlign;
   GST_OBJECT_UNLOCK (self);
 
+  /* If we've accumulated enough data, return it immediately */
+  if (gst_adapter_available (self->adapter) >= wanted) {
+    memcpy (data, gst_adapter_map (self->adapter, wanted), wanted);
+    gst_adapter_flush (self->adapter, wanted);
+    GST_DEBUG_OBJECT (self, "Adapter has enough data, returning %i", wanted);
+    goto out;
+  }
+
   while (wanted > 0) {
-    guint have_frames, n_frames, want_frames, read_len;
+    DWORD dwWaitResult;
+    guint got_frames, avail_frames, n_frames, want_frames, read_len;
 
     /* Wait for data to become available */
-    WaitForSingleObject (self->event_handle, INFINITE);
+    dwWaitResult = WaitForSingleObject (self->event_handle, INFINITE);
+    if (dwWaitResult != WAIT_OBJECT_0) {
+      GST_ERROR_OBJECT (self, "Error waiting for event handle: %x",
+          (guint) dwWaitResult);
+      goto err;
+    }
 
     hr = IAudioCaptureClient_GetBuffer (self->capture_client,
-        (BYTE **) & from, &have_frames, &flags, NULL, NULL);
+        (BYTE **) & from, &got_frames, &flags, NULL, NULL);
     if (hr != S_OK) {
-      gchar *msg = gst_wasapi_util_hresult_to_string (hr);
-      if (hr == AUDCLNT_S_BUFFER_EMPTY)
+      if (hr == AUDCLNT_S_BUFFER_EMPTY) {
+        gchar *msg = gst_wasapi_util_hresult_to_string (hr);
         GST_WARNING_OBJECT (self, "IAudioCaptureClient::GetBuffer failed: %s"
             ", retrying", msg);
-      else
-        GST_ERROR_OBJECT (self, "IAudioCaptureClient::GetBuffer failed: %s",
-            msg);
-      g_free (msg);
-      length = 0;
-      goto beach;
+        g_free (msg);
+        length = 0;
+        goto out;
+      }
+      HR_FAILED_ELEMENT_ERROR_AND (hr, IAudioCaptureClient::GetBuffer, self,
+          goto err);
     }
 
-    if (flags != 0)
-      GST_INFO_OBJECT (self, "buffer flags=%#08x", (guint) flags);
-
-    /* XXX: How do we handle AUDCLNT_BUFFERFLAGS_SILENT? We're supposed to write
-     * out silence when that flag is set? See:
-     * https://msdn.microsoft.com/en-us/library/windows/desktop/dd370800(v=vs.85).aspx */
+    if (G_UNLIKELY (flags != 0)) {
+      /* https://docs.microsoft.com/en-us/windows/win32/api/audioclient/ne-audioclient-_audclnt_bufferflags */
+      if (flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY)
+        GST_DEBUG_OBJECT (self, "WASAPI reported discontinuity (glitch?)");
+      if (flags & AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR)
+        GST_DEBUG_OBJECT (self, "WASAPI reported a timestamp error");
+    }
 
-    if (flags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY)
-      GST_WARNING_OBJECT (self, "WASAPI reported glitch in buffer");
+    /* Copy all the frames we got into the adapter, and then extract at most
+     * @wanted size of frames from it. This helps when ::GetBuffer returns more
+     * data than we can handle right now. */
+    {
+      GstBuffer *tmp = gst_buffer_new_allocate (NULL, got_frames * bpf, NULL);
+      /* If flags has AUDCLNT_BUFFERFLAGS_SILENT, we will ignore the actual
+       * data and write out silence, see:
+       * https://docs.microsoft.com/en-us/windows/win32/api/audioclient/ne-audioclient-_audclnt_bufferflags */
+      if (flags & AUDCLNT_BUFFERFLAGS_SILENT)
+        memset (from, 0, got_frames * bpf);
+      gst_buffer_fill (tmp, 0, from, got_frames * bpf);
+      gst_adapter_push (self->adapter, tmp);
+    }
 
-    want_frames = wanted / self->mix_format->nBlockAlign;
+    /* Release all captured buffers; we copied them above */
+    hr = IAudioCaptureClient_ReleaseBuffer (self->capture_client, got_frames);
+    from = NULL;
+    HR_FAILED_ELEMENT_ERROR_AND (hr, IAudioCaptureClient::ReleaseBuffer, self,
+        goto err);
 
-    /* If GetBuffer is returning more frames than we can handle, all we can do is
-     * hope that this is temporary and that things will settle down later. */
-    if (G_UNLIKELY (have_frames > want_frames))
-      GST_WARNING_OBJECT (self, "captured too many frames: have %i, want %i",
-          have_frames, want_frames);
+    want_frames = wanted / bpf;
+    avail_frames = gst_adapter_available (self->adapter) / bpf;
 
     /* Only copy data that will fit into the allocated buffer of size @length */
-    n_frames = MIN (have_frames, want_frames);
-    read_len = n_frames * self->mix_format->nBlockAlign;
+    n_frames = MIN (avail_frames, want_frames);
+    read_len = n_frames * bpf;
 
-    {
-      guint bpf = self->mix_format->nBlockAlign;
-      GST_DEBUG_OBJECT (self, "have: %i (%i bytes), can read: %i (%i bytes), "
-          "will read: %i (%i bytes)", have_frames, have_frames * bpf,
-          want_frames, wanted, n_frames, read_len);
-    }
+    GST_DEBUG_OBJECT (self, "frames captured: %i (%i bytes), "
+        "can read: %i (%i bytes), will read: %i (%i bytes), "
+        "adapter has: %i (%i bytes)", got_frames, got_frames * bpf, want_frames,
+        wanted, n_frames, read_len, avail_frames, avail_frames * bpf);
 
-    memcpy (data, from, read_len);
+    memcpy (data, gst_adapter_map (self->adapter, read_len), read_len);
+    gst_adapter_flush (self->adapter, read_len);
     wanted -= read_len;
-
-    /* Always release all captured buffers if we've captured any at all */
-    hr = IAudioCaptureClient_ReleaseBuffer (self->capture_client, have_frames);
-    HR_FAILED_AND (hr, IAudioClock::ReleaseBuffer, goto beach);
   }
 
 
-beach:
-
+out:
   return length;
+
+err:
+  length = -1;
+  goto out;
 }
 
 static guint
@@ -661,6 +698,7 @@ gst_wasapi_src_reset (GstAudioSrc * asrc)
   GST_OBJECT_UNLOCK (self);
 }
 
+#if DEFAULT_PROVIDE_CLOCK
 static GstClockTime
 gst_wasapi_src_get_time (GstClock * clock, gpointer user_data)
 {
@@ -687,3 +725,4 @@ gst_wasapi_src_get_time (GstClock * clock, gpointer user_data)
 
   return result;
 }
+#endif