7ebf0106c9550c52a671c18c99e33f2f05d7e894
[platform/upstream/gstreamer.git] / sys / decklink / gstdecklinkaudiosrc.cpp
1 /* GStreamer
2  * Copyright (C) 2011 David Schleef <ds@entropywave.com>
3  * Copyright (C) 2014 Sebastian Dröge <sebastian@centricular.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 51 Franklin Street, Suite 500,
18  * Boston, MA 02110-1335, USA.
19  */
20 /**
21  * SECTION:element-decklinkaudiosrc
22  * @short_description: Inputs Audio from a BlackMagic DeckLink Device
23  * @see_also: decklinkvideosrc
24  *
25  * Capture Video and Audio from a BlackMagic DeckLink Device. Can only be used
26  * in conjunction with decklinkvideosink.
27  *
28  * ## Sample pipeline
29  * |[
30  * gst-launch-1.0 \
31  *   decklinkvideosrc device-number=0 mode=1080p25 ! autovideosink \
32  *   decklinkaudiosrc device-number=0 ! autoaudiosink
33  * ]|
34  * Capturing 1080p25 video and audio from the SDI-In of Card 0. Devices are numbered
35  * starting with 0.
36  */
37
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
41
42 #include "gstdecklinkaudiosrc.h"
43 #include "gstdecklinkvideosrc.h"
44 #include <string.h>
45
46 GST_DEBUG_CATEGORY_STATIC (gst_decklink_audio_src_debug);
47 #define GST_CAT_DEFAULT gst_decklink_audio_src_debug
48
49 #define DEFAULT_CONNECTION            (GST_DECKLINK_AUDIO_CONNECTION_AUTO)
50 #define DEFAULT_BUFFER_SIZE           (5)
51
52 #define DEFAULT_ALIGNMENT_THRESHOLD   (40 * GST_MSECOND)
53 #define DEFAULT_DISCONT_WAIT          (1 * GST_SECOND)
54 #define DEFAULT_CHANNELS              (GST_DECKLINK_AUDIO_CHANNELS_2)
55
56 #ifndef ABSDIFF
57 #define ABSDIFF(x, y) ( (x) > (y) ? ((x) - (y)) : ((y) - (x)) )
58 #endif
59
60 enum
61 {
62   PROP_0,
63   PROP_CONNECTION,
64   PROP_DEVICE_NUMBER,
65   PROP_ALIGNMENT_THRESHOLD,
66   PROP_DISCONT_WAIT,
67   PROP_BUFFER_SIZE,
68   PROP_CHANNELS,
69   PROP_HW_SERIAL_NUMBER
70 };
71
72 static GstStaticPadTemplate sink_template = GST_STATIC_PAD_TEMPLATE ("src",
73     GST_PAD_SRC,
74     GST_PAD_ALWAYS,
75     GST_STATIC_CAPS
76     ("audio/x-raw, format={S16LE,S32LE}, channels=2, rate=48000, "
77         "layout=interleaved;"
78         "audio/x-raw, format={S16LE,S32LE}, channels={8,16}, channel-mask=(bitmask)0, rate=48000, "
79         "layout=interleaved")
80     );
81
82 typedef struct
83 {
84   IDeckLinkAudioInputPacket *packet;
85   GstClockTime timestamp;
86   GstClockTime stream_timestamp;
87   GstClockTime stream_duration;
88   GstClockTime hardware_timestamp;
89   GstClockTime hardware_duration;
90   gboolean no_signal;
91 } CapturePacket;
92
93 static void
94 capture_packet_clear (CapturePacket * packet)
95 {
96   packet->packet->Release ();
97   memset (packet, 0, sizeof (*packet));
98 }
99
100 typedef struct
101 {
102   IDeckLinkAudioInputPacket *packet;
103   IDeckLinkInput *input;
104 } AudioPacket;
105
106 static void
107 audio_packet_free (void *data)
108 {
109   AudioPacket *packet = (AudioPacket *) data;
110
111   packet->packet->Release ();
112   packet->input->Release ();
113   g_free (packet);
114 }
115
116 static void gst_decklink_audio_src_set_property (GObject * object,
117     guint property_id, const GValue * value, GParamSpec * pspec);
118 static void gst_decklink_audio_src_get_property (GObject * object,
119     guint property_id, GValue * value, GParamSpec * pspec);
120 static void gst_decklink_audio_src_finalize (GObject * object);
121
122 static GstStateChangeReturn
123 gst_decklink_audio_src_change_state (GstElement * element,
124     GstStateChange transition);
125
126 static gboolean gst_decklink_audio_src_unlock (GstBaseSrc * bsrc);
127 static gboolean gst_decklink_audio_src_unlock_stop (GstBaseSrc * bsrc);
128 static GstCaps *gst_decklink_audio_src_get_caps (GstBaseSrc * bsrc,
129     GstCaps * filter);
130 static gboolean gst_decklink_audio_src_query (GstBaseSrc * bsrc,
131     GstQuery * query);
132
133 static GstFlowReturn gst_decklink_audio_src_create (GstPushSrc * psrc,
134     GstBuffer ** buffer);
135
136 static gboolean gst_decklink_audio_src_open (GstDecklinkAudioSrc * self);
137 static gboolean gst_decklink_audio_src_close (GstDecklinkAudioSrc * self);
138
139 static gboolean gst_decklink_audio_src_stop (GstDecklinkAudioSrc * self);
140
141 #define parent_class gst_decklink_audio_src_parent_class
142 G_DEFINE_TYPE (GstDecklinkAudioSrc, gst_decklink_audio_src, GST_TYPE_PUSH_SRC);
143
144 static void
145 gst_decklink_audio_src_class_init (GstDecklinkAudioSrcClass * klass)
146 {
147   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
148   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
149   GstBaseSrcClass *basesrc_class = GST_BASE_SRC_CLASS (klass);
150   GstPushSrcClass *pushsrc_class = GST_PUSH_SRC_CLASS (klass);
151
152   gobject_class->set_property = gst_decklink_audio_src_set_property;
153   gobject_class->get_property = gst_decklink_audio_src_get_property;
154   gobject_class->finalize = gst_decklink_audio_src_finalize;
155
156   element_class->change_state =
157       GST_DEBUG_FUNCPTR (gst_decklink_audio_src_change_state);
158
159   basesrc_class->query = GST_DEBUG_FUNCPTR (gst_decklink_audio_src_query);
160   basesrc_class->negotiate = NULL;
161   basesrc_class->get_caps = GST_DEBUG_FUNCPTR (gst_decklink_audio_src_get_caps);
162   basesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_decklink_audio_src_unlock);
163   basesrc_class->unlock_stop =
164       GST_DEBUG_FUNCPTR (gst_decklink_audio_src_unlock_stop);
165
166   pushsrc_class->create = GST_DEBUG_FUNCPTR (gst_decklink_audio_src_create);
167
168   g_object_class_install_property (gobject_class, PROP_CONNECTION,
169       g_param_spec_enum ("connection", "Connection",
170           "Audio input connection to use",
171           GST_TYPE_DECKLINK_AUDIO_CONNECTION, DEFAULT_CONNECTION,
172           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
173               G_PARAM_CONSTRUCT)));
174
175   g_object_class_install_property (gobject_class, PROP_DEVICE_NUMBER,
176       g_param_spec_int ("device-number", "Device number",
177           "Output device instance to use", 0, G_MAXINT, 0,
178           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
179               G_PARAM_CONSTRUCT)));
180
181   g_object_class_install_property (gobject_class, PROP_ALIGNMENT_THRESHOLD,
182       g_param_spec_uint64 ("alignment-threshold", "Alignment Threshold",
183           "Timestamp alignment threshold in nanoseconds", 0,
184           G_MAXUINT64 - 1, DEFAULT_ALIGNMENT_THRESHOLD,
185           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
186
187   g_object_class_install_property (gobject_class, PROP_DISCONT_WAIT,
188       g_param_spec_uint64 ("discont-wait", "Discont Wait",
189           "Window of time in nanoseconds to wait before "
190           "creating a discontinuity", 0,
191           G_MAXUINT64 - 1, DEFAULT_DISCONT_WAIT,
192           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
193
194   g_object_class_install_property (gobject_class, PROP_BUFFER_SIZE,
195       g_param_spec_uint ("buffer-size", "Buffer Size",
196           "Size of internal buffer in number of video frames", 1,
197           G_MAXINT, DEFAULT_BUFFER_SIZE,
198           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
199
200   g_object_class_install_property (gobject_class, PROP_CHANNELS,
201       g_param_spec_enum ("channels", "Channels",
202           "Audio channels",
203           GST_TYPE_DECKLINK_AUDIO_CHANNELS, DEFAULT_CHANNELS,
204           (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
205               G_PARAM_CONSTRUCT)));
206
207   g_object_class_install_property (gobject_class, PROP_HW_SERIAL_NUMBER,
208       g_param_spec_string ("hw-serial-number", "Hardware serial number",
209           "The serial number (hardware ID) of the Decklink card",
210           NULL, (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
211
212   gst_element_class_add_static_pad_template (element_class, &sink_template);
213
214   gst_element_class_set_static_metadata (element_class, "Decklink Audio Source",
215       "Audio/Source/Hardware", "Decklink Source",
216       "David Schleef <ds@entropywave.com>, "
217       "Sebastian Dröge <sebastian@centricular.com>");
218
219   GST_DEBUG_CATEGORY_INIT (gst_decklink_audio_src_debug, "decklinkaudiosrc",
220       0, "debug category for decklinkaudiosrc element");
221 }
222
223 static void
224 gst_decklink_audio_src_init (GstDecklinkAudioSrc * self)
225 {
226   self->device_number = 0;
227   self->alignment_threshold = DEFAULT_ALIGNMENT_THRESHOLD;
228   self->discont_wait = DEFAULT_DISCONT_WAIT;
229   self->buffer_size = DEFAULT_BUFFER_SIZE;
230   self->channels = DEFAULT_CHANNELS;
231
232   gst_base_src_set_live (GST_BASE_SRC (self), TRUE);
233   gst_base_src_set_format (GST_BASE_SRC (self), GST_FORMAT_TIME);
234
235   gst_pad_use_fixed_caps (GST_BASE_SRC_PAD (self));
236
237   g_mutex_init (&self->lock);
238   g_cond_init (&self->cond);
239
240   self->current_packets =
241       gst_queue_array_new_for_struct (sizeof (CapturePacket),
242       DEFAULT_BUFFER_SIZE);
243
244   self->skipped_last = 0;
245   self->skip_from_timestamp = GST_CLOCK_TIME_NONE;
246   self->skip_to_timestamp = GST_CLOCK_TIME_NONE;
247 }
248
249 void
250 gst_decklink_audio_src_set_property (GObject * object, guint property_id,
251     const GValue * value, GParamSpec * pspec)
252 {
253   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (object);
254
255   switch (property_id) {
256     case PROP_CONNECTION:
257       self->connection =
258           (GstDecklinkAudioConnectionEnum) g_value_get_enum (value);
259       break;
260     case PROP_DEVICE_NUMBER:
261       self->device_number = g_value_get_int (value);
262       break;
263     case PROP_ALIGNMENT_THRESHOLD:
264       self->alignment_threshold = g_value_get_uint64 (value);
265       break;
266     case PROP_DISCONT_WAIT:
267       self->discont_wait = g_value_get_uint64 (value);
268       break;
269     case PROP_BUFFER_SIZE:
270       self->buffer_size = g_value_get_uint (value);
271       break;
272     case PROP_CHANNELS:
273       self->channels = (GstDecklinkAudioChannelsEnum) g_value_get_enum (value);
274       break;
275     default:
276       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
277       break;
278   }
279 }
280
281 void
282 gst_decklink_audio_src_get_property (GObject * object, guint property_id,
283     GValue * value, GParamSpec * pspec)
284 {
285   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (object);
286
287   switch (property_id) {
288     case PROP_CONNECTION:
289       g_value_set_enum (value, self->connection);
290       break;
291     case PROP_DEVICE_NUMBER:
292       g_value_set_int (value, self->device_number);
293       break;
294     case PROP_ALIGNMENT_THRESHOLD:
295       g_value_set_uint64 (value, self->alignment_threshold);
296       break;
297     case PROP_DISCONT_WAIT:
298       g_value_set_uint64 (value, self->discont_wait);
299       break;
300     case PROP_BUFFER_SIZE:
301       g_value_set_uint (value, self->buffer_size);
302       break;
303     case PROP_CHANNELS:
304       g_value_set_enum (value, self->channels);
305       break;
306     case PROP_HW_SERIAL_NUMBER:
307       if (self->input)
308         g_value_set_string (value, self->input->hw_serial_number);
309       else
310         g_value_set_string (value, NULL);
311       break;
312     default:
313       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
314       break;
315   }
316 }
317
318 void
319 gst_decklink_audio_src_finalize (GObject * object)
320 {
321   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (object);
322
323   g_mutex_clear (&self->lock);
324   g_cond_clear (&self->cond);
325   if (self->current_packets) {
326     while (gst_queue_array_get_length (self->current_packets) > 0) {
327       CapturePacket *tmp = (CapturePacket *)
328           gst_queue_array_pop_head_struct (self->current_packets);
329       capture_packet_clear (tmp);
330     }
331     gst_queue_array_free (self->current_packets);
332     self->current_packets = NULL;
333   }
334
335   G_OBJECT_CLASS (parent_class)->finalize (object);
336 }
337
338 static gboolean
339 gst_decklink_audio_src_start (GstDecklinkAudioSrc * self)
340 {
341   BMDAudioSampleType sample_depth;
342   HRESULT ret;
343   BMDAudioConnection conn = (BMDAudioConnection) - 1;
344   GstCaps *allowed_caps, *caps;
345
346   g_mutex_lock (&self->input->lock);
347   if (self->input->audio_enabled) {
348     g_mutex_unlock (&self->input->lock);
349     return TRUE;
350   }
351   g_mutex_unlock (&self->input->lock);
352
353   /* Negotiate the format / sample depth with downstream */
354   allowed_caps = gst_pad_get_allowed_caps (GST_BASE_SRC_PAD (self));
355   if (!allowed_caps)
356     allowed_caps = gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD (self));
357
358   sample_depth = bmdAudioSampleType32bitInteger;
359   if (!gst_caps_is_empty (allowed_caps)) {
360     GstStructure *s;
361
362     allowed_caps = gst_caps_simplify (allowed_caps);
363
364     s = gst_caps_get_structure (allowed_caps, 0);
365
366     /* If it's not a string then both formats are supported */
367     if (gst_structure_has_field_typed (s, "format", G_TYPE_STRING)) {
368       const gchar *format = gst_structure_get_string (s, "format");
369       if (g_str_equal (format, "S16LE")) {
370         sample_depth = bmdAudioSampleType16bitInteger;
371       }
372     }
373   }
374   gst_caps_unref (allowed_caps);
375
376   switch (self->connection) {
377     case GST_DECKLINK_AUDIO_CONNECTION_AUTO:{
378       GstElement *videosrc = NULL;
379       GstDecklinkConnectionEnum vconn;
380
381       // Try to get the connection from the videosrc and try
382       // to select a sensible audio connection based on that
383       g_mutex_lock (&self->input->lock);
384       if (self->input->videosrc)
385         videosrc = GST_ELEMENT_CAST (gst_object_ref (self->input->videosrc));
386       g_mutex_unlock (&self->input->lock);
387
388       if (videosrc) {
389         g_object_get (videosrc, "connection", &vconn, NULL);
390         gst_object_unref (videosrc);
391
392         switch (vconn) {
393           case GST_DECKLINK_CONNECTION_SDI:
394             conn = bmdAudioConnectionEmbedded;
395             break;
396           case GST_DECKLINK_CONNECTION_HDMI:
397             conn = bmdAudioConnectionEmbedded;
398             break;
399           case GST_DECKLINK_CONNECTION_OPTICAL_SDI:
400             conn = bmdAudioConnectionEmbedded;
401             break;
402           case GST_DECKLINK_CONNECTION_COMPONENT:
403             conn = bmdAudioConnectionAnalog;
404             break;
405           case GST_DECKLINK_CONNECTION_COMPOSITE:
406             conn = bmdAudioConnectionAnalog;
407             break;
408           case GST_DECKLINK_CONNECTION_SVIDEO:
409             conn = bmdAudioConnectionAnalog;
410             break;
411           default:
412             // Use default
413             break;
414         }
415       }
416
417       break;
418     }
419     case GST_DECKLINK_AUDIO_CONNECTION_EMBEDDED:
420       conn = bmdAudioConnectionEmbedded;
421       break;
422     case GST_DECKLINK_AUDIO_CONNECTION_AES_EBU:
423       conn = bmdAudioConnectionAESEBU;
424       break;
425     case GST_DECKLINK_AUDIO_CONNECTION_ANALOG:
426       conn = bmdAudioConnectionAnalog;
427       break;
428     case GST_DECKLINK_AUDIO_CONNECTION_ANALOG_XLR:
429       conn = bmdAudioConnectionAnalogXLR;
430       break;
431     case GST_DECKLINK_AUDIO_CONNECTION_ANALOG_RCA:
432       conn = bmdAudioConnectionAnalogRCA;
433       break;
434     default:
435       g_assert_not_reached ();
436       break;
437   }
438
439   if (conn != (BMDAudioConnection) - 1) {
440     ret =
441         self->input->config->SetInt (bmdDeckLinkConfigAudioInputConnection,
442         conn);
443     if (ret != S_OK) {
444       GST_ERROR ("set configuration (audio input connection): 0x%08lx",
445           (unsigned long) ret);
446       return FALSE;
447     }
448   }
449
450   ret = self->input->input->EnableAudioInput (bmdAudioSampleRate48kHz,
451       sample_depth, self->channels_found);
452   if (ret != S_OK) {
453     GST_WARNING_OBJECT (self, "Failed to enable audio input: 0x%08lx",
454         (unsigned long) ret);
455     return FALSE;
456   }
457   gst_audio_info_set_format (&self->info,
458       sample_depth ==
459       bmdAudioSampleType16bitInteger ? GST_AUDIO_FORMAT_S16LE :
460       GST_AUDIO_FORMAT_S32LE, 48000, self->channels_found, NULL);
461
462   g_mutex_lock (&self->input->lock);
463   self->input->audio_enabled = TRUE;
464   if (self->input->start_streams && self->input->videosrc)
465     self->input->start_streams (self->input->videosrc);
466   g_mutex_unlock (&self->input->lock);
467
468   caps = gst_audio_info_to_caps (&self->info);
469   if (!gst_base_src_set_caps (GST_BASE_SRC (self), caps)) {
470     gst_caps_unref (caps);
471     GST_WARNING_OBJECT (self, "Failed to set caps");
472     return FALSE;
473   }
474   gst_caps_unref (caps);
475
476   self->skipped_last = 0;
477   self->skip_from_timestamp = GST_CLOCK_TIME_NONE;
478   self->skip_to_timestamp = GST_CLOCK_TIME_NONE;
479
480   return TRUE;
481 }
482
483 static void
484 gst_decklink_audio_src_got_packet (GstElement * element,
485     IDeckLinkAudioInputPacket * packet, GstClockTime capture_time,
486     GstClockTime stream_time, GstClockTime stream_duration,
487     GstClockTime hardware_time, GstClockTime hardware_duration,
488     gboolean no_signal)
489 {
490   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (element);
491   GstClockTime timestamp;
492
493   GST_LOG_OBJECT (self,
494       "Got audio packet at %" GST_TIME_FORMAT " / %" GST_TIME_FORMAT
495       ", no signal %d", GST_TIME_ARGS (capture_time),
496       GST_TIME_ARGS (stream_time), no_signal);
497
498   g_mutex_lock (&self->input->lock);
499   if (self->input->videosrc) {
500     GstDecklinkVideoSrc *videosrc =
501         GST_DECKLINK_VIDEO_SRC_CAST (gst_object_ref (self->input->videosrc));
502
503     if (videosrc->drop_no_signal_frames && no_signal) {
504       g_mutex_unlock (&self->input->lock);
505       return;
506     }
507
508     if (videosrc->first_time == GST_CLOCK_TIME_NONE)
509       videosrc->first_time = stream_time;
510
511     if (videosrc->skip_first_time > 0
512         && stream_time - videosrc->first_time < videosrc->skip_first_time) {
513       GST_DEBUG_OBJECT (self,
514           "Skipping frame as requested: %" GST_TIME_FORMAT " < %"
515           GST_TIME_FORMAT, GST_TIME_ARGS (stream_time),
516           GST_TIME_ARGS (videosrc->skip_first_time + videosrc->first_time));
517       g_mutex_unlock (&self->input->lock);
518       return;
519     }
520
521     if (videosrc->output_stream_time)
522       timestamp = stream_time;
523     else
524       timestamp = gst_clock_adjust_with_calibration (NULL, stream_time,
525           videosrc->current_time_mapping.xbase,
526           videosrc->current_time_mapping.b, videosrc->current_time_mapping.num,
527           videosrc->current_time_mapping.den);
528   } else {
529     timestamp = capture_time;
530   }
531   g_mutex_unlock (&self->input->lock);
532
533   GST_LOG_OBJECT (self, "Converted times to %" GST_TIME_FORMAT,
534       GST_TIME_ARGS (timestamp));
535
536   g_mutex_lock (&self->lock);
537   if (!self->flushing) {
538     CapturePacket p;
539     guint skipped_packets = 0;
540
541     while (gst_queue_array_get_length (self->current_packets) >=
542         self->buffer_size) {
543       CapturePacket *tmp = (CapturePacket *)
544           gst_queue_array_pop_head_struct (self->current_packets);
545       if (skipped_packets == 0 && self->skipped_last == 0)
546         self->skip_from_timestamp = tmp->timestamp;
547       skipped_packets++;
548       self->skip_to_timestamp = tmp->timestamp;
549       capture_packet_clear (tmp);
550     }
551
552     if (self->skipped_last == 0 && skipped_packets > 0) {
553       GST_WARNING_OBJECT (self, "Starting to drop audio packets");
554     }
555
556     if (skipped_packets == 0 && self->skipped_last > 0) {
557       GST_ELEMENT_WARNING_WITH_DETAILS (self,
558           STREAM, FAILED,
559           ("Dropped %u old packets from %" GST_TIME_FORMAT " to %"
560               GST_TIME_FORMAT, self->skipped_last,
561               GST_TIME_ARGS (self->skip_from_timestamp),
562               GST_TIME_ARGS (self->skip_to_timestamp)),
563           (NULL),
564           ("dropped", G_TYPE_UINT, self->skipped_last,
565               "from", G_TYPE_UINT64, self->skip_from_timestamp,
566               "to", G_TYPE_UINT64, self->skip_to_timestamp, NULL));
567       self->skipped_last = 0;
568     }
569     self->skipped_last += skipped_packets;
570
571     memset (&p, 0, sizeof (p));
572     p.packet = packet;
573     p.timestamp = timestamp;
574     p.stream_timestamp = stream_time;
575     p.stream_duration = stream_duration;
576     p.hardware_timestamp = hardware_time;
577     p.hardware_duration = hardware_duration;
578     p.no_signal = no_signal;
579     packet->AddRef ();
580     gst_queue_array_push_tail_struct (self->current_packets, &p);
581     g_cond_signal (&self->cond);
582   }
583   g_mutex_unlock (&self->lock);
584 }
585
586 static GstFlowReturn
587 gst_decklink_audio_src_create (GstPushSrc * bsrc, GstBuffer ** buffer)
588 {
589   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (bsrc);
590   GstFlowReturn flow_ret = GST_FLOW_OK;
591   const guint8 *data;
592   glong sample_count;
593   gsize data_size;
594   CapturePacket p;
595   AudioPacket *ap;
596   GstClockTime timestamp, duration;
597   GstClockTime start_time, end_time;
598   guint64 start_offset, end_offset;
599   gboolean discont = FALSE;
600   static GstStaticCaps stream_reference =
601       GST_STATIC_CAPS ("timestamp/x-decklink-stream");
602   static GstStaticCaps hardware_reference =
603       GST_STATIC_CAPS ("timestamp/x-decklink-hardware");
604
605   if (!gst_decklink_audio_src_start (self)) {
606     return GST_FLOW_NOT_NEGOTIATED;
607   }
608
609 retry:
610   g_mutex_lock (&self->lock);
611   while (gst_queue_array_is_empty (self->current_packets) && !self->flushing) {
612     g_cond_wait (&self->cond, &self->lock);
613   }
614
615   if (self->flushing) {
616     GST_DEBUG_OBJECT (self, "Flushing");
617     g_mutex_unlock (&self->lock);
618     return GST_FLOW_FLUSHING;
619   }
620
621   p = *(CapturePacket *)
622       gst_queue_array_pop_head_struct (self->current_packets);
623   g_mutex_unlock (&self->lock);
624
625   p.packet->GetBytes ((gpointer *) & data);
626   sample_count = p.packet->GetSampleFrameCount ();
627   data_size = self->info.bpf * sample_count;
628
629   if (p.timestamp == GST_CLOCK_TIME_NONE && self->next_offset == (guint64) - 1) {
630     GST_DEBUG_OBJECT (self,
631         "Got packet without timestamp before initial "
632         "timestamp after discont - dropping");
633     capture_packet_clear (&p);
634     goto retry;
635   }
636
637   ap = (AudioPacket *) g_malloc0 (sizeof (AudioPacket));
638
639   *buffer =
640       gst_buffer_new_wrapped_full ((GstMemoryFlags) GST_MEMORY_FLAG_READONLY,
641       (gpointer) data, data_size, 0, data_size, ap,
642       (GDestroyNotify) audio_packet_free);
643
644   ap->packet = p.packet;
645   p.packet->AddRef ();
646   ap->input = self->input->input;
647   ap->input->AddRef ();
648
649   timestamp = p.timestamp;
650
651   // Jitter and discontinuity handling, based on audiobasesrc
652   start_time = timestamp;
653
654   // Convert to the sample numbers
655   start_offset =
656       gst_util_uint64_scale (start_time, self->info.rate, GST_SECOND);
657   // Convert back to round down to a sample multiple and get rid of rounding errors
658   start_time = gst_util_uint64_scale (start_offset, GST_SECOND, self->info.rate);
659
660   end_offset = start_offset + sample_count;
661   end_time = gst_util_uint64_scale_int (end_offset, GST_SECOND,
662       self->info.rate);
663
664   duration = end_time - start_time;
665
666   if (self->next_offset == (guint64) - 1) {
667     discont = TRUE;
668   } else {
669     guint64 diff, max_sample_diff;
670
671     // Check discont
672     if (start_offset <= self->next_offset)
673       diff = self->next_offset - start_offset;
674     else
675       diff = start_offset - self->next_offset;
676
677     max_sample_diff =
678         gst_util_uint64_scale_int (self->alignment_threshold, self->info.rate,
679         GST_SECOND);
680
681     // Discont!
682     if (G_UNLIKELY (diff >= max_sample_diff)) {
683       if (self->discont_wait > 0) {
684         if (self->discont_time == GST_CLOCK_TIME_NONE) {
685           self->discont_time = start_time;
686         } else if (start_time - self->discont_time >= self->discont_wait) {
687           discont = TRUE;
688           self->discont_time = GST_CLOCK_TIME_NONE;
689         }
690       } else {
691         discont = TRUE;
692       }
693     } else if (G_UNLIKELY (self->discont_time != GST_CLOCK_TIME_NONE)) {
694       // we have had a discont, but are now back on track!
695       self->discont_time = GST_CLOCK_TIME_NONE;
696     }
697   }
698
699   if (discont) {
700     // Have discont, need resync and use the capture timestamps
701     if (self->next_offset != (guint64) - 1)
702       GST_INFO_OBJECT (self, "Have discont. Expected %"
703           G_GUINT64_FORMAT ", got %" G_GUINT64_FORMAT,
704           self->next_offset, start_offset);
705     GST_BUFFER_FLAG_SET (*buffer, GST_BUFFER_FLAG_DISCONT);
706     self->next_offset = end_offset;
707     // Got a discont and adjusted, reset the discont_time marker.
708     self->discont_time = GST_CLOCK_TIME_NONE;
709   } else {
710     // No discont, just keep counting
711     timestamp =
712         gst_util_uint64_scale (self->next_offset, GST_SECOND, self->info.rate);
713     self->next_offset += sample_count;
714     duration =
715         gst_util_uint64_scale (self->next_offset, GST_SECOND,
716         self->info.rate) - timestamp;
717   }
718
719   // Detect gaps in stream time
720   self->processed += sample_count;
721   if (self->expected_stream_time != GST_CLOCK_TIME_NONE
722       && p.stream_timestamp == GST_CLOCK_TIME_NONE) {
723     /* We missed a frame. Extrapolate the timestamps */
724     p.stream_timestamp = self->expected_stream_time;
725     p.stream_duration =
726         gst_util_uint64_scale_int (sample_count, GST_SECOND, self->info.rate);
727   }
728   if (self->last_hardware_time != GST_CLOCK_TIME_NONE
729       && p.hardware_timestamp == GST_CLOCK_TIME_NONE) {
730     /* This should always happen when the previous one also does, but let's
731      * have two separate checks just in case */
732     GstClockTime start_hw_offset, end_hw_offset;
733     start_hw_offset =
734         gst_util_uint64_scale (self->last_hardware_time, self->info.rate,
735         GST_SECOND);
736     end_hw_offset = start_hw_offset + sample_count;
737     p.hardware_timestamp =
738         gst_util_uint64_scale_int (end_hw_offset, GST_SECOND, self->info.rate);
739     /* Will be the same as the stream duration - reuse it */
740     p.hardware_duration = p.stream_duration;
741   }
742
743   if (p.stream_timestamp != GST_CLOCK_TIME_NONE) {
744     GstClockTime start_stream_time, end_stream_time;
745
746     start_stream_time = p.stream_timestamp;
747
748     start_offset =
749         gst_util_uint64_scale (start_stream_time, self->info.rate, GST_SECOND);
750
751     end_offset = start_offset + sample_count;
752     end_stream_time = gst_util_uint64_scale_int (end_offset, GST_SECOND,
753         self->info.rate);
754
755     /* With drop-frame we have gaps of 1 sample every now and then (rounding
756      * errors because of the samples-per-frame pattern which is not 100%
757      * accurate), and due to rounding errors in the calculations these can be
758      * 2>x>1 */
759     if (self->expected_stream_time != GST_CLOCK_TIME_NONE &&
760         ABSDIFF (self->expected_stream_time, p.stream_timestamp) >
761         gst_util_uint64_scale (2, GST_SECOND, self->info.rate)) {
762       GstMessage *msg;
763       GstClockTime running_time;
764
765       self->dropped +=
766           gst_util_uint64_scale (ABSDIFF (self->expected_stream_time,
767               p.stream_timestamp), self->info.rate, GST_SECOND);
768       running_time =
769           gst_segment_to_running_time (&GST_BASE_SRC (self)->segment,
770           GST_FORMAT_TIME, timestamp);
771
772       msg =
773           gst_message_new_qos (GST_OBJECT (self), TRUE, running_time,
774           p.stream_timestamp, timestamp, duration);
775       gst_message_set_qos_stats (msg, GST_FORMAT_DEFAULT, self->processed,
776           self->dropped);
777       gst_element_post_message (GST_ELEMENT (self), msg);
778     }
779     self->expected_stream_time = end_stream_time;
780   }
781   self->last_hardware_time = p.hardware_timestamp;
782
783   if (p.no_signal)
784     GST_BUFFER_FLAG_SET (*buffer, GST_BUFFER_FLAG_GAP);
785   GST_BUFFER_TIMESTAMP (*buffer) = timestamp;
786   GST_BUFFER_DURATION (*buffer) = duration;
787
788   gst_buffer_add_reference_timestamp_meta (*buffer,
789       gst_static_caps_get (&stream_reference), p.stream_timestamp,
790       p.stream_duration);
791   gst_buffer_add_reference_timestamp_meta (*buffer,
792       gst_static_caps_get (&hardware_reference), p.hardware_timestamp,
793       p.hardware_duration);
794
795   GST_DEBUG_OBJECT (self,
796       "Outputting buffer %p with timestamp %" GST_TIME_FORMAT " and duration %"
797       GST_TIME_FORMAT, *buffer, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (*buffer)),
798       GST_TIME_ARGS (GST_BUFFER_DURATION (*buffer)));
799
800   capture_packet_clear (&p);
801
802   return flow_ret;
803 }
804
805 static GstCaps *
806 gst_decklink_audio_src_get_caps (GstBaseSrc * bsrc, GstCaps * filter)
807 {
808   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (bsrc);
809   GstCaps *caps, *template_caps;
810   const GstStructure *s;
811   gint channels;
812
813   channels = self->channels;
814   if (channels == 0)
815     channels = self->channels_found;
816
817   template_caps = gst_pad_get_pad_template_caps (GST_BASE_SRC_PAD (bsrc));
818   if (channels == 0) {
819     caps = template_caps;
820   } else {
821     if (channels > 2)
822       s = gst_caps_get_structure (template_caps, 1);
823     else
824       s = gst_caps_get_structure (template_caps, 0);
825
826     caps = gst_caps_new_full (gst_structure_copy (s), NULL);
827     gst_caps_set_simple (caps, "channels", G_TYPE_INT, channels, NULL);
828     gst_caps_unref (template_caps);
829   }
830
831   if (filter) {
832     GstCaps *tmp =
833         gst_caps_intersect_full (filter, caps, GST_CAPS_INTERSECT_FIRST);
834     gst_caps_unref (caps);
835     caps = tmp;
836   }
837
838   return caps;
839 }
840
841 static gboolean
842 gst_decklink_audio_src_query (GstBaseSrc * bsrc, GstQuery * query)
843 {
844   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (bsrc);
845   gboolean ret = TRUE;
846
847   switch (GST_QUERY_TYPE (query)) {
848     case GST_QUERY_LATENCY:{
849       if (self->input) {
850         g_mutex_lock (&self->input->lock);
851         if (self->input->mode) {
852           GstClockTime min, max;
853
854           min =
855               gst_util_uint64_scale_ceil (GST_SECOND, self->input->mode->fps_d,
856               self->input->mode->fps_n);
857           max = self->buffer_size * min;
858
859           gst_query_set_latency (query, TRUE, min, max);
860           ret = TRUE;
861         } else {
862           ret = FALSE;
863         }
864         g_mutex_unlock (&self->input->lock);
865       } else {
866         ret = FALSE;
867       }
868
869       break;
870     }
871     default:
872       ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
873       break;
874   }
875
876   return ret;
877 }
878
879 static gboolean
880 gst_decklink_audio_src_unlock (GstBaseSrc * bsrc)
881 {
882   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (bsrc);
883
884   g_mutex_lock (&self->lock);
885   self->flushing = TRUE;
886   g_cond_signal (&self->cond);
887   g_mutex_unlock (&self->lock);
888
889   return TRUE;
890 }
891
892 static gboolean
893 gst_decklink_audio_src_unlock_stop (GstBaseSrc * bsrc)
894 {
895   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (bsrc);
896
897   g_mutex_lock (&self->lock);
898   self->flushing = FALSE;
899   while (gst_queue_array_get_length (self->current_packets) > 0) {
900     CapturePacket *tmp = (CapturePacket *)
901         gst_queue_array_pop_head_struct (self->current_packets);
902     capture_packet_clear (tmp);
903   }
904   g_mutex_unlock (&self->lock);
905
906   return TRUE;
907 }
908
909 static gboolean
910 gst_decklink_audio_src_open (GstDecklinkAudioSrc * self)
911 {
912   GST_DEBUG_OBJECT (self, "Opening");
913
914   self->input =
915       gst_decklink_acquire_nth_input (self->device_number,
916       GST_ELEMENT_CAST (self), TRUE);
917   if (!self->input) {
918     GST_ERROR_OBJECT (self, "Failed to acquire input");
919     return FALSE;
920   }
921
922   g_object_notify (G_OBJECT (self), "hw-serial-number");
923
924   g_mutex_lock (&self->input->lock);
925   if (self->channels > 0) {
926     self->channels_found = self->channels;
927   } else {
928     if (self->input->attributes) {
929       int64_t channels_found;
930
931       HRESULT ret = self->input->attributes->GetInt
932           (BMDDeckLinkMaximumAudioChannels, &channels_found);
933       self->channels_found = channels_found;
934
935       /* Sometimes the card may report an invalid number of channels. In
936        * that case, we should (empirically) use 8. */
937       if (ret != S_OK ||
938           self->channels_found == 0 || g_enum_get_value ((GEnumClass *)
939               g_type_class_peek (GST_TYPE_DECKLINK_AUDIO_CHANNELS),
940               self->channels_found)
941           == NULL) {
942         self->channels_found = GST_DECKLINK_AUDIO_CHANNELS_8;
943       }
944     }
945   }
946   self->input->got_audio_packet = gst_decklink_audio_src_got_packet;
947   g_mutex_unlock (&self->input->lock);
948
949   return TRUE;
950 }
951
952 static gboolean
953 gst_decklink_audio_src_close (GstDecklinkAudioSrc * self)
954 {
955   GST_DEBUG_OBJECT (self, "Closing");
956
957   if (self->input) {
958     g_mutex_lock (&self->input->lock);
959     self->input->got_audio_packet = NULL;
960     g_mutex_unlock (&self->input->lock);
961
962     gst_decklink_release_nth_input (self->device_number,
963         GST_ELEMENT_CAST (self), TRUE);
964     self->input = NULL;
965   }
966
967   return TRUE;
968 }
969
970 static gboolean
971 gst_decklink_audio_src_stop (GstDecklinkAudioSrc * self)
972 {
973   GST_DEBUG_OBJECT (self, "Stopping");
974
975   while (gst_queue_array_get_length (self->current_packets) > 0) {
976     CapturePacket *tmp = (CapturePacket *)
977         gst_queue_array_pop_head_struct (self->current_packets);
978     capture_packet_clear (tmp);
979   }
980
981   if (self->input && self->input->audio_enabled) {
982     g_mutex_lock (&self->input->lock);
983     self->input->audio_enabled = FALSE;
984     g_mutex_unlock (&self->input->lock);
985
986     self->input->input->DisableAudioInput ();
987   }
988
989   return TRUE;
990 }
991
992 #if 0
993 static gboolean
994 in_same_pipeline (GstElement * a, GstElement * b)
995 {
996   GstObject *root = NULL, *tmp;
997   gboolean ret = FALSE;
998
999   tmp = gst_object_get_parent (GST_OBJECT_CAST (a));
1000   while (tmp != NULL) {
1001     if (root)
1002       gst_object_unref (root);
1003     root = tmp;
1004     tmp = gst_object_get_parent (root);
1005   }
1006
1007   ret = root && gst_object_has_ancestor (GST_OBJECT_CAST (b), root);
1008
1009   if (root)
1010     gst_object_unref (root);
1011
1012   return ret;
1013 }
1014 #endif
1015
1016 static GstStateChangeReturn
1017 gst_decklink_audio_src_change_state (GstElement * element,
1018     GstStateChange transition)
1019 {
1020   GstDecklinkAudioSrc *self = GST_DECKLINK_AUDIO_SRC_CAST (element);
1021   GstStateChangeReturn ret;
1022
1023   switch (transition) {
1024     case GST_STATE_CHANGE_NULL_TO_READY:
1025       self->processed = 0;
1026       self->dropped = 0;
1027       self->expected_stream_time = GST_CLOCK_TIME_NONE;
1028       if (!gst_decklink_audio_src_open (self)) {
1029         ret = GST_STATE_CHANGE_FAILURE;
1030         goto out;
1031       }
1032       break;
1033     case GST_STATE_CHANGE_READY_TO_PAUSED:{
1034       GstElement *videosrc = NULL;
1035
1036       // Check if there is a video src for this input too and if it
1037       // is actually in the same pipeline
1038       g_mutex_lock (&self->input->lock);
1039       if (self->input->videosrc)
1040         videosrc = GST_ELEMENT_CAST (gst_object_ref (self->input->videosrc));
1041       g_mutex_unlock (&self->input->lock);
1042
1043       if (!videosrc) {
1044         GST_ELEMENT_ERROR (self, STREAM, FAILED,
1045             (NULL), ("Audio src needs a video src for its operation"));
1046         ret = GST_STATE_CHANGE_FAILURE;
1047         goto out;
1048       }
1049       // FIXME: This causes deadlocks sometimes
1050 #if 0
1051       else if (!in_same_pipeline (GST_ELEMENT_CAST (self), videosrc)) {
1052         GST_ELEMENT_ERROR (self, STREAM, FAILED,
1053             (NULL),
1054             ("Audio src and video src need to be in the same pipeline"));
1055         ret = GST_STATE_CHANGE_FAILURE;
1056         gst_object_unref (videosrc);
1057         goto out;
1058       }
1059 #endif
1060
1061       if (videosrc)
1062         gst_object_unref (videosrc);
1063
1064       self->flushing = FALSE;
1065       self->next_offset = -1;
1066       break;
1067     }
1068     default:
1069       break;
1070   }
1071
1072   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1073   if (ret == GST_STATE_CHANGE_FAILURE)
1074     return ret;
1075
1076   switch (transition) {
1077     case GST_STATE_CHANGE_PAUSED_TO_READY:
1078       gst_decklink_audio_src_stop (self);
1079       break;
1080     case GST_STATE_CHANGE_READY_TO_NULL:
1081       gst_decklink_audio_src_close (self);
1082       break;
1083     default:
1084       break;
1085   }
1086 out:
1087
1088   return ret;
1089 }