• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2001 Thomas <thomas@apestaart.org>
4  *               2005,2006 Wim Taymans <wim@fluendo.com>
5  *
6  * adder.c: Adder element, N in, one out, samples are added
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23 /**
24  * SECTION:element-adder
25  * @title: adder
26  *
27  * The adder allows to mix several streams into one by adding the data.
28  * Mixed data is clamped to the min/max values of the data format.
29  *
30  * The adder currently mixes all data received on the sinkpads as soon as
31  * possible without trying to synchronize the streams.
32  *
33  * Check out the audiomixer element in gst-plugins-bad for a better-behaving
34  * audio mixing element: It will sync input streams correctly and also handle
35  * live inputs properly.
36  *
37  * Caps negotiation is inherently racy with the adder element. You can set
38  * the "caps" property to force adder to operate in a specific audio
39  * format, sample rate and channel count. In this case you may also need
40  * audioconvert and/or audioresample elements for each input stream before the
41  * adder element to make sure the input branch can produce the forced format.
42  *
43  * ## Example launch line
44  * |[
45  * gst-launch-1.0 audiotestsrc freq=100 ! adder name=mix ! audioconvert ! autoaudiosink audiotestsrc freq=500 ! mix.
46  * ]|
47  *  This pipeline produces two sine waves mixed together.
48  *
49  */
50 /* Element-Checklist-Version: 5 */
51 
52 #ifdef HAVE_CONFIG_H
53 #include "config.h"
54 #endif
55 
56 #include "gstadder.h"
57 #include <gst/audio/audio.h>
58 #include <string.h>             /* strcmp */
59 #include "gstadderorc.h"
60 
61 #define GST_CAT_DEFAULT gst_adder_debug
62 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
63 
64 #define DEFAULT_PAD_VOLUME (1.0)
65 #define DEFAULT_PAD_MUTE (FALSE)
66 
67 /* some defines for audio processing */
68 /* the volume factor is a range from 0.0 to (arbitrary) VOLUME_MAX_DOUBLE = 10.0
69  * we map 1.0 to VOLUME_UNITY_INT*
70  */
71 #define VOLUME_UNITY_INT8            8  /* internal int for unity 2^(8-5) */
72 #define VOLUME_UNITY_INT8_BIT_SHIFT  3  /* number of bits to shift for unity */
73 #define VOLUME_UNITY_INT16           2048       /* internal int for unity 2^(16-5) */
74 #define VOLUME_UNITY_INT16_BIT_SHIFT 11 /* number of bits to shift for unity */
75 #define VOLUME_UNITY_INT24           524288     /* internal int for unity 2^(24-5) */
76 #define VOLUME_UNITY_INT24_BIT_SHIFT 19 /* number of bits to shift for unity */
77 #define VOLUME_UNITY_INT32           134217728  /* internal int for unity 2^(32-5) */
78 #define VOLUME_UNITY_INT32_BIT_SHIFT 27
79 
80 enum
81 {
82   PROP_PAD_0,
83   PROP_PAD_VOLUME,
84   PROP_PAD_MUTE
85 };
86 
87 G_DEFINE_TYPE (GstAdderPad, gst_adder_pad, GST_TYPE_PAD);
88 
89 static void
gst_adder_pad_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)90 gst_adder_pad_get_property (GObject * object, guint prop_id,
91     GValue * value, GParamSpec * pspec)
92 {
93   GstAdderPad *pad = GST_ADDER_PAD (object);
94 
95   switch (prop_id) {
96     case PROP_PAD_VOLUME:
97       g_value_set_double (value, pad->volume);
98       break;
99     case PROP_PAD_MUTE:
100       g_value_set_boolean (value, pad->mute);
101       break;
102     default:
103       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
104       break;
105   }
106 }
107 
108 static void
gst_adder_pad_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)109 gst_adder_pad_set_property (GObject * object, guint prop_id,
110     const GValue * value, GParamSpec * pspec)
111 {
112   GstAdderPad *pad = GST_ADDER_PAD (object);
113 
114   switch (prop_id) {
115     case PROP_PAD_VOLUME:
116       GST_OBJECT_LOCK (pad);
117       pad->volume = g_value_get_double (value);
118       pad->volume_i8 = pad->volume * VOLUME_UNITY_INT8;
119       pad->volume_i16 = pad->volume * VOLUME_UNITY_INT16;
120       pad->volume_i32 = pad->volume * VOLUME_UNITY_INT32;
121       GST_OBJECT_UNLOCK (pad);
122       break;
123     case PROP_PAD_MUTE:
124       GST_OBJECT_LOCK (pad);
125       pad->mute = g_value_get_boolean (value);
126       GST_OBJECT_UNLOCK (pad);
127       break;
128     default:
129       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
130       break;
131   }
132 }
133 
134 static void
gst_adder_pad_class_init(GstAdderPadClass * klass)135 gst_adder_pad_class_init (GstAdderPadClass * klass)
136 {
137   GObjectClass *gobject_class = (GObjectClass *) klass;
138 
139   gobject_class->set_property = gst_adder_pad_set_property;
140   gobject_class->get_property = gst_adder_pad_get_property;
141 
142   g_object_class_install_property (gobject_class, PROP_PAD_VOLUME,
143       g_param_spec_double ("volume", "Volume", "Volume of this pad",
144           0.0, 10.0, DEFAULT_PAD_VOLUME,
145           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
146   g_object_class_install_property (gobject_class, PROP_PAD_MUTE,
147       g_param_spec_boolean ("mute", "Mute", "Mute this pad",
148           DEFAULT_PAD_MUTE,
149           G_PARAM_READWRITE | GST_PARAM_CONTROLLABLE | G_PARAM_STATIC_STRINGS));
150 }
151 
152 static void
gst_adder_pad_init(GstAdderPad * pad)153 gst_adder_pad_init (GstAdderPad * pad)
154 {
155   pad->volume = DEFAULT_PAD_VOLUME;
156   pad->mute = DEFAULT_PAD_MUTE;
157 }
158 
159 enum
160 {
161   PROP_0,
162   PROP_FILTER_CAPS
163 };
164 
165 /* elementfactory information */
166 
167 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
168 #define CAPS \
169   GST_AUDIO_CAPS_MAKE ("{ S32LE, U32LE, S16LE, U16LE, S8, U8, F32LE, F64LE }") \
170   ", layout = (string) { interleaved }"
171 #else
172 #define CAPS \
173   GST_AUDIO_CAPS_MAKE ("{ S32BE, U32BE, S16BE, U16BE, S8, U8, F32BE, F64BE }") \
174   ", layout = (string) { interleaved }"
175 #endif
176 
177 static GstStaticPadTemplate gst_adder_src_template =
178 GST_STATIC_PAD_TEMPLATE ("src",
179     GST_PAD_SRC,
180     GST_PAD_ALWAYS,
181     GST_STATIC_CAPS (CAPS)
182     );
183 
184 static GstStaticPadTemplate gst_adder_sink_template =
185 GST_STATIC_PAD_TEMPLATE ("sink_%u",
186     GST_PAD_SINK,
187     GST_PAD_REQUEST,
188     GST_STATIC_CAPS (CAPS)
189     );
190 
191 static void gst_adder_child_proxy_init (gpointer g_iface, gpointer iface_data);
192 
193 #define gst_adder_parent_class parent_class
194 G_DEFINE_TYPE_WITH_CODE (GstAdder, gst_adder, GST_TYPE_ELEMENT,
195     G_IMPLEMENT_INTERFACE (GST_TYPE_CHILD_PROXY, gst_adder_child_proxy_init));
196 GST_ELEMENT_REGISTER_DEFINE (adder, "adder", GST_RANK_NONE, GST_TYPE_ADDER);
197 
198 static void gst_adder_dispose (GObject * object);
199 static void gst_adder_set_property (GObject * object, guint prop_id,
200     const GValue * value, GParamSpec * pspec);
201 static void gst_adder_get_property (GObject * object, guint prop_id,
202     GValue * value, GParamSpec * pspec);
203 
204 static gboolean gst_adder_setcaps (GstAdder * adder, GstPad * pad,
205     GstCaps * caps);
206 static gboolean gst_adder_src_query (GstPad * pad, GstObject * parent,
207     GstQuery * query);
208 static gboolean gst_adder_sink_query (GstCollectPads * pads,
209     GstCollectData * pad, GstQuery * query, gpointer user_data);
210 static gboolean gst_adder_src_event (GstPad * pad, GstObject * parent,
211     GstEvent * event);
212 static gboolean gst_adder_sink_event (GstCollectPads * pads,
213     GstCollectData * pad, GstEvent * event, gpointer user_data);
214 
215 static GstPad *gst_adder_request_new_pad (GstElement * element,
216     GstPadTemplate * temp, const gchar * unused, const GstCaps * caps);
217 static void gst_adder_release_pad (GstElement * element, GstPad * pad);
218 
219 static GstStateChangeReturn gst_adder_change_state (GstElement * element,
220     GstStateChange transition);
221 
222 static GstFlowReturn gst_adder_do_clip (GstCollectPads * pads,
223     GstCollectData * data, GstBuffer * buffer, GstBuffer ** out,
224     gpointer user_data);
225 static GstFlowReturn gst_adder_collected (GstCollectPads * pads,
226     gpointer user_data);
227 
228 /* we can only accept caps that we and downstream can handle.
229  * if we have filtercaps set, use those to constrain the target caps.
230  */
231 static GstCaps *
gst_adder_sink_getcaps(GstPad * pad,GstCaps * filter)232 gst_adder_sink_getcaps (GstPad * pad, GstCaps * filter)
233 {
234   GstAdder *adder;
235   GstCaps *result, *peercaps, *current_caps, *filter_caps;
236   GstStructure *s;
237   gint i, n;
238 
239   adder = GST_ADDER (GST_PAD_PARENT (pad));
240 
241   GST_OBJECT_LOCK (adder);
242   /* take filter */
243   if ((filter_caps = adder->filter_caps)) {
244     if (filter)
245       filter_caps =
246           gst_caps_intersect_full (filter, filter_caps,
247           GST_CAPS_INTERSECT_FIRST);
248     else
249       gst_caps_ref (filter_caps);
250   } else {
251     filter_caps = filter ? gst_caps_ref (filter) : NULL;
252   }
253   GST_OBJECT_UNLOCK (adder);
254 
255   if (filter_caps && gst_caps_is_empty (filter_caps)) {
256     GST_WARNING_OBJECT (pad, "Empty filter caps");
257     return filter_caps;
258   }
259 
260   /* get the downstream possible caps */
261   peercaps = gst_pad_peer_query_caps (adder->srcpad, filter_caps);
262 
263   /* get the allowed caps on this sinkpad */
264   GST_OBJECT_LOCK (adder);
265   current_caps =
266       adder->current_caps ? gst_caps_ref (adder->current_caps) : NULL;
267   if (current_caps == NULL) {
268     current_caps = gst_pad_get_pad_template_caps (pad);
269     if (!current_caps)
270       current_caps = gst_caps_new_any ();
271   }
272   GST_OBJECT_UNLOCK (adder);
273 
274   if (peercaps) {
275     /* if the peer has caps, intersect */
276     GST_DEBUG_OBJECT (adder, "intersecting peer and our caps");
277     result =
278         gst_caps_intersect_full (peercaps, current_caps,
279         GST_CAPS_INTERSECT_FIRST);
280     gst_caps_unref (peercaps);
281     gst_caps_unref (current_caps);
282   } else {
283     /* the peer has no caps (or there is no peer), just use the allowed caps
284      * of this sinkpad. */
285     /* restrict with filter-caps if any */
286     if (filter_caps) {
287       GST_DEBUG_OBJECT (adder, "no peer caps, using filtered caps");
288       result =
289           gst_caps_intersect_full (filter_caps, current_caps,
290           GST_CAPS_INTERSECT_FIRST);
291       gst_caps_unref (current_caps);
292     } else {
293       GST_DEBUG_OBJECT (adder, "no peer caps, using our caps");
294       result = current_caps;
295     }
296   }
297 
298   result = gst_caps_make_writable (result);
299 
300   n = gst_caps_get_size (result);
301   for (i = 0; i < n; i++) {
302     GstStructure *sref;
303 
304     s = gst_caps_get_structure (result, i);
305     sref = gst_structure_copy (s);
306     gst_structure_set (sref, "channels", GST_TYPE_INT_RANGE, 0, 2, NULL);
307     if (gst_structure_is_subset (s, sref)) {
308       /* This field is irrelevant when in mono or stereo */
309       gst_structure_remove_field (s, "channel-mask");
310     }
311     gst_structure_free (sref);
312   }
313 
314   if (filter_caps)
315     gst_caps_unref (filter_caps);
316 
317   GST_LOG_OBJECT (adder, "getting caps on pad %p,%s to %" GST_PTR_FORMAT, pad,
318       GST_PAD_NAME (pad), result);
319 
320   return result;
321 }
322 
323 static gboolean
gst_adder_sink_query(GstCollectPads * pads,GstCollectData * pad,GstQuery * query,gpointer user_data)324 gst_adder_sink_query (GstCollectPads * pads, GstCollectData * pad,
325     GstQuery * query, gpointer user_data)
326 {
327   gboolean res = FALSE;
328 
329   switch (GST_QUERY_TYPE (query)) {
330     case GST_QUERY_CAPS:
331     {
332       GstCaps *filter, *caps;
333 
334       gst_query_parse_caps (query, &filter);
335       caps = gst_adder_sink_getcaps (pad->pad, filter);
336       gst_query_set_caps_result (query, caps);
337       gst_caps_unref (caps);
338       res = TRUE;
339       break;
340     }
341     default:
342       res = gst_collect_pads_query_default (pads, pad, query, FALSE);
343       break;
344   }
345 
346   return res;
347 }
348 
349 /* the first caps we receive on any of the sinkpads will define the caps for all
350  * the other sinkpads because we can only mix streams with the same caps.
351  */
352 static gboolean
gst_adder_setcaps(GstAdder * adder,GstPad * pad,GstCaps * orig_caps)353 gst_adder_setcaps (GstAdder * adder, GstPad * pad, GstCaps * orig_caps)
354 {
355   GstCaps *caps;
356   GstAudioInfo info;
357   GstStructure *s;
358   gint channels;
359 
360   caps = gst_caps_copy (orig_caps);
361 
362   s = gst_caps_get_structure (caps, 0);
363   if (gst_structure_get_int (s, "channels", &channels))
364     if (channels <= 2)
365       gst_structure_remove_field (s, "channel-mask");
366 
367   if (!gst_audio_info_from_caps (&info, caps))
368     goto invalid_format;
369 
370   GST_OBJECT_LOCK (adder);
371   /* don't allow reconfiguration for now; there's still a race between the
372    * different upstream threads doing query_caps + accept_caps + sending
373    * (possibly different) CAPS events, but there's not much we can do about
374    * that, upstream needs to deal with it. */
375   if (adder->current_caps != NULL) {
376     if (gst_audio_info_is_equal (&info, &adder->info)) {
377       GST_OBJECT_UNLOCK (adder);
378       gst_caps_unref (caps);
379       return TRUE;
380     } else {
381       GST_DEBUG_OBJECT (pad, "got input caps %" GST_PTR_FORMAT ", but "
382           "current caps are %" GST_PTR_FORMAT, caps, adder->current_caps);
383       GST_OBJECT_UNLOCK (adder);
384       gst_pad_push_event (pad, gst_event_new_reconfigure ());
385       gst_caps_unref (caps);
386       return FALSE;
387     }
388   }
389 
390   GST_INFO_OBJECT (pad, "setting caps to %" GST_PTR_FORMAT, caps);
391   adder->current_caps = gst_caps_ref (caps);
392 
393   memcpy (&adder->info, &info, sizeof (info));
394   GST_OBJECT_UNLOCK (adder);
395   /* send caps event later, after stream-start event */
396 
397   GST_INFO_OBJECT (pad, "handle caps change to %" GST_PTR_FORMAT, caps);
398 
399   gst_caps_unref (caps);
400 
401   return TRUE;
402 
403   /* ERRORS */
404 invalid_format:
405   {
406     gst_caps_unref (caps);
407     GST_WARNING_OBJECT (adder, "invalid format set as caps");
408     return FALSE;
409   }
410 }
411 
412 /* FIXME, the duration query should reflect how long you will produce
413  * data, that is the amount of stream time until you will emit EOS.
414  *
415  * For synchronized mixing this is always the max of all the durations
416  * of upstream since we emit EOS when all of them finished.
417  *
418  * We don't do synchronized mixing so this really depends on where the
419  * streams where punched in and what their relative offsets are against
420  * each other which we can get from the first timestamps we see.
421  *
422  * When we add a new stream (or remove a stream) the duration might
423  * also become invalid again and we need to post a new DURATION
424  * message to notify this fact to the parent.
425  * For now we take the max of all the upstream elements so the simple
426  * cases work at least somewhat.
427  */
428 static gboolean
gst_adder_query_duration(GstAdder * adder,GstQuery * query)429 gst_adder_query_duration (GstAdder * adder, GstQuery * query)
430 {
431   gint64 max;
432   gboolean res;
433   GstFormat format;
434   GstIterator *it;
435   gboolean done;
436   GValue item = { 0, };
437 
438   /* parse format */
439   gst_query_parse_duration (query, &format, NULL);
440 
441   max = -1;
442   res = TRUE;
443   done = FALSE;
444 
445   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
446   while (!done) {
447     GstIteratorResult ires;
448 
449     ires = gst_iterator_next (it, &item);
450     switch (ires) {
451       case GST_ITERATOR_DONE:
452         done = TRUE;
453         break;
454       case GST_ITERATOR_OK:
455       {
456         GstPad *pad = g_value_get_object (&item);
457         gint64 duration;
458 
459         /* ask sink peer for duration */
460         res &= gst_pad_peer_query_duration (pad, format, &duration);
461         /* take max from all valid return values */
462         if (res) {
463           /* valid unknown length, stop searching */
464           if (duration == -1) {
465             max = duration;
466             done = TRUE;
467           }
468           /* else see if bigger than current max */
469           else if (duration > max)
470             max = duration;
471         }
472         g_value_reset (&item);
473         break;
474       }
475       case GST_ITERATOR_RESYNC:
476         max = -1;
477         res = TRUE;
478         gst_iterator_resync (it);
479         break;
480       default:
481         res = FALSE;
482         done = TRUE;
483         break;
484     }
485   }
486   g_value_unset (&item);
487   gst_iterator_free (it);
488 
489   if (res) {
490     /* and store the max */
491     GST_DEBUG_OBJECT (adder, "Total duration in format %s: %"
492         GST_TIME_FORMAT, gst_format_get_name (format), GST_TIME_ARGS (max));
493     gst_query_set_duration (query, format, max);
494   }
495 
496   return res;
497 }
498 
499 static gboolean
gst_adder_src_query(GstPad * pad,GstObject * parent,GstQuery * query)500 gst_adder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
501 {
502   GstAdder *adder = GST_ADDER (parent);
503   gboolean res = FALSE;
504 
505   switch (GST_QUERY_TYPE (query)) {
506     case GST_QUERY_POSITION:
507     {
508       GstFormat format;
509 
510       gst_query_parse_position (query, &format, NULL);
511 
512       switch (format) {
513         case GST_FORMAT_TIME:
514           /* FIXME, bring to stream time, might be tricky */
515           gst_query_set_position (query, format, adder->segment.position);
516           res = TRUE;
517           break;
518         case GST_FORMAT_DEFAULT:
519           gst_query_set_position (query, format, adder->offset);
520           res = TRUE;
521           break;
522         default:
523           break;
524       }
525       break;
526     }
527     case GST_QUERY_DURATION:
528       res = gst_adder_query_duration (adder, query);
529       break;
530     default:
531       /* FIXME, needs a custom query handler because we have multiple
532        * sinkpads */
533       res = gst_pad_query_default (pad, parent, query);
534       break;
535   }
536 
537   return res;
538 }
539 
540 /* event handling */
541 
542 typedef struct
543 {
544   GstEvent *event;
545   gboolean flush;
546 } EventData;
547 
548 static gboolean
forward_event_func(const GValue * val,GValue * ret,EventData * data)549 forward_event_func (const GValue * val, GValue * ret, EventData * data)
550 {
551   GstPad *pad = g_value_get_object (val);
552   GstEvent *event = data->event;
553   GstPad *peer;
554 
555   gst_event_ref (event);
556   GST_LOG_OBJECT (pad, "About to send event %s", GST_EVENT_TYPE_NAME (event));
557   peer = gst_pad_get_peer (pad);
558   /* collect pad might have been set flushing,
559    * so bypass core checking that and send directly to peer */
560   if (!peer || !gst_pad_send_event (peer, event)) {
561     if (!peer)
562       gst_event_unref (event);
563     GST_WARNING_OBJECT (pad, "Sending event  %p (%s) failed.",
564         event, GST_EVENT_TYPE_NAME (event));
565     /* quick hack to unflush the pads, ideally we need a way to just unflush
566      * this single collect pad */
567     if (data->flush)
568       gst_pad_send_event (pad, gst_event_new_flush_stop (TRUE));
569   } else {
570     g_value_set_boolean (ret, TRUE);
571     GST_LOG_OBJECT (pad, "Sent event  %p (%s).",
572         event, GST_EVENT_TYPE_NAME (event));
573   }
574   if (peer)
575     gst_object_unref (peer);
576 
577   /* continue on other pads, even if one failed */
578   return TRUE;
579 }
580 
581 /* forwards the event to all sinkpads, takes ownership of the
582  * event
583  *
584  * Returns: TRUE if the event could be forwarded on all
585  * sinkpads.
586  */
587 static gboolean
forward_event(GstAdder * adder,GstEvent * event,gboolean flush)588 forward_event (GstAdder * adder, GstEvent * event, gboolean flush)
589 {
590   gboolean ret;
591   GstIterator *it;
592   GstIteratorResult ires;
593   GValue vret = { 0 };
594   EventData data;
595 
596   GST_LOG_OBJECT (adder, "Forwarding event %p (%s)", event,
597       GST_EVENT_TYPE_NAME (event));
598 
599   data.event = event;
600   data.flush = flush;
601 
602   g_value_init (&vret, G_TYPE_BOOLEAN);
603   g_value_set_boolean (&vret, FALSE);
604   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
605   while (TRUE) {
606     ires =
607         gst_iterator_fold (it, (GstIteratorFoldFunction) forward_event_func,
608         &vret, &data);
609     switch (ires) {
610       case GST_ITERATOR_RESYNC:
611         GST_WARNING ("resync");
612         gst_iterator_resync (it);
613         g_value_set_boolean (&vret, TRUE);
614         break;
615       case GST_ITERATOR_OK:
616       case GST_ITERATOR_DONE:
617         ret = g_value_get_boolean (&vret);
618         goto done;
619       default:
620         ret = FALSE;
621         goto done;
622     }
623   }
624 done:
625   gst_iterator_free (it);
626   GST_LOG_OBJECT (adder, "Forwarded event %p (%s), ret=%d", event,
627       GST_EVENT_TYPE_NAME (event), ret);
628   gst_event_unref (event);
629 
630   return ret;
631 }
632 
633 static gboolean
gst_adder_src_event(GstPad * pad,GstObject * parent,GstEvent * event)634 gst_adder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
635 {
636   GstAdder *adder;
637   gboolean result;
638 
639   adder = GST_ADDER (parent);
640 
641   GST_DEBUG_OBJECT (pad, "Got %s event on src pad: %" GST_PTR_FORMAT,
642       GST_EVENT_TYPE_NAME (event), event);
643 
644   switch (GST_EVENT_TYPE (event)) {
645     case GST_EVENT_SEEK:
646     {
647       GstSeekFlags flags;
648       gdouble rate;
649       GstSeekType start_type, stop_type;
650       gint64 start, stop;
651       GstFormat seek_format, dest_format;
652       gboolean flush;
653 
654       /* parse the seek parameters */
655       gst_event_parse_seek (event, &rate, &seek_format, &flags, &start_type,
656           &start, &stop_type, &stop);
657 
658       if ((start_type != GST_SEEK_TYPE_NONE)
659           && (start_type != GST_SEEK_TYPE_SET)) {
660         result = FALSE;
661         GST_DEBUG_OBJECT (adder,
662             "seeking failed, unhandled seek type for start: %d", start_type);
663         goto done;
664       }
665       if ((stop_type != GST_SEEK_TYPE_NONE) && (stop_type != GST_SEEK_TYPE_SET)) {
666         result = FALSE;
667         GST_DEBUG_OBJECT (adder,
668             "seeking failed, unhandled seek type for end: %d", stop_type);
669         goto done;
670       }
671 
672       dest_format = adder->segment.format;
673       if (seek_format != dest_format) {
674         result = FALSE;
675         GST_DEBUG_OBJECT (adder,
676             "seeking failed, unhandled seek format: %d", seek_format);
677         goto done;
678       }
679 
680       flush = (flags & GST_SEEK_FLAG_FLUSH) == GST_SEEK_FLAG_FLUSH;
681 
682       /* check if we are flushing */
683       if (flush) {
684         /* flushing seek, start flush downstream, the flush will be done
685          * when all pads received a FLUSH_STOP.
686          * Make sure we accept nothing anymore and return WRONG_STATE.
687          * We send a flush-start before, to ensure no streaming is done
688          * as we need to take the stream lock.
689          */
690         gst_pad_push_event (adder->srcpad, gst_event_new_flush_start ());
691         gst_collect_pads_set_flushing (adder->collect, TRUE);
692 
693         /* We can't send FLUSH_STOP here since upstream could start pushing data
694          * after we unlock adder->collect.
695          * We set flush_stop_pending to TRUE instead and send FLUSH_STOP after
696          * forwarding the seek upstream or from gst_adder_collected,
697          * whichever happens first.
698          */
699         GST_COLLECT_PADS_STREAM_LOCK (adder->collect);
700         adder->flush_stop_pending = TRUE;
701         GST_COLLECT_PADS_STREAM_UNLOCK (adder->collect);
702         GST_DEBUG_OBJECT (adder, "mark pending flush stop event");
703       }
704       GST_DEBUG_OBJECT (adder, "handling seek event: %" GST_PTR_FORMAT, event);
705 
706       /* now wait for the collected to be finished and mark a new
707        * segment. After we have the lock, no collect function is running and no
708        * new collect function will be called for as long as we're flushing. */
709       GST_COLLECT_PADS_STREAM_LOCK (adder->collect);
710 
711       /* clip position and update our segment */
712       if (adder->segment.stop != -1) {
713         adder->segment.position = adder->segment.stop;
714       }
715       gst_segment_do_seek (&adder->segment, rate, seek_format, flags,
716           start_type, start, stop_type, stop, NULL);
717 
718       if (flush) {
719         /* Yes, we need to call _set_flushing again *WHEN* the streaming threads
720          * have stopped so that the cookie gets properly updated. */
721         gst_collect_pads_set_flushing (adder->collect, TRUE);
722       }
723       GST_COLLECT_PADS_STREAM_UNLOCK (adder->collect);
724       GST_DEBUG_OBJECT (adder, "forwarding seek event: %" GST_PTR_FORMAT,
725           event);
726       GST_DEBUG_OBJECT (adder, "updated segment: %" GST_SEGMENT_FORMAT,
727           &adder->segment);
728 
729       /* we're forwarding seek to all upstream peers and wait for one to reply
730        * with a newsegment-event before we send a newsegment-event downstream */
731       g_atomic_int_set (&adder->new_segment_pending, TRUE);
732       result = forward_event (adder, event, flush);
733       if (!result) {
734         /* seek failed. maybe source is a live source. */
735         GST_DEBUG_OBJECT (adder, "seeking failed");
736       }
737       if (g_atomic_int_compare_and_exchange (&adder->flush_stop_pending,
738               TRUE, FALSE)) {
739         GST_DEBUG_OBJECT (adder, "pending flush stop");
740         if (!gst_pad_push_event (adder->srcpad,
741                 gst_event_new_flush_stop (TRUE))) {
742           GST_WARNING_OBJECT (adder, "Sending flush stop event failed");
743         }
744       }
745       break;
746     }
747     case GST_EVENT_QOS:
748       /* QoS might be tricky */
749       result = FALSE;
750       gst_event_unref (event);
751       break;
752     case GST_EVENT_NAVIGATION:
753       /* navigation is rather pointless. */
754       result = FALSE;
755       gst_event_unref (event);
756       break;
757     default:
758       /* just forward the rest for now */
759       GST_DEBUG_OBJECT (adder, "forward unhandled event: %s",
760           GST_EVENT_TYPE_NAME (event));
761       result = forward_event (adder, event, FALSE);
762       break;
763   }
764 
765 done:
766 
767   return result;
768 }
769 
770 static gboolean
gst_adder_sink_event(GstCollectPads * pads,GstCollectData * pad,GstEvent * event,gpointer user_data)771 gst_adder_sink_event (GstCollectPads * pads, GstCollectData * pad,
772     GstEvent * event, gpointer user_data)
773 {
774   GstAdder *adder = GST_ADDER (user_data);
775   gboolean res = TRUE, discard = FALSE;
776 
777   GST_DEBUG_OBJECT (pad->pad, "Got %s event on sink pad",
778       GST_EVENT_TYPE_NAME (event));
779 
780   switch (GST_EVENT_TYPE (event)) {
781     case GST_EVENT_CAPS:
782     {
783       GstCaps *caps;
784 
785       gst_event_parse_caps (event, &caps);
786       res = gst_adder_setcaps (adder, pad->pad, caps);
787       gst_event_unref (event);
788       event = NULL;
789       break;
790     }
791     case GST_EVENT_FLUSH_START:
792       /* ensure that we will send a flush stop */
793       res = gst_collect_pads_event_default (pads, pad, event, discard);
794       event = NULL;
795       GST_COLLECT_PADS_STREAM_LOCK (adder->collect);
796       adder->flush_stop_pending = TRUE;
797       GST_COLLECT_PADS_STREAM_UNLOCK (adder->collect);
798       break;
799     case GST_EVENT_FLUSH_STOP:
800       /* we received a flush-stop. We will only forward it when
801        * flush_stop_pending is set, and we will unset it then.
802        */
803       g_atomic_int_set (&adder->new_segment_pending, TRUE);
804       GST_COLLECT_PADS_STREAM_LOCK (adder->collect);
805       if (adder->flush_stop_pending) {
806         GST_DEBUG_OBJECT (pad->pad, "forwarding flush stop");
807         res = gst_collect_pads_event_default (pads, pad, event, discard);
808         adder->flush_stop_pending = FALSE;
809         event = NULL;
810       } else {
811         discard = TRUE;
812         GST_DEBUG_OBJECT (pad->pad, "eating flush stop");
813       }
814       GST_COLLECT_PADS_STREAM_UNLOCK (adder->collect);
815       /* Clear pending tags */
816       if (adder->pending_events) {
817         g_list_foreach (adder->pending_events, (GFunc) gst_event_unref, NULL);
818         g_list_free (adder->pending_events);
819         adder->pending_events = NULL;
820       }
821       break;
822     case GST_EVENT_TAG:
823       /* collect tags here so we can push them out when we collect data */
824       adder->pending_events = g_list_append (adder->pending_events, event);
825       event = NULL;
826       break;
827     case GST_EVENT_SEGMENT:{
828       const GstSegment *segment;
829       gst_event_parse_segment (event, &segment);
830       if (segment->rate != adder->segment.rate) {
831         GST_ERROR_OBJECT (pad->pad,
832             "Got segment event with wrong rate %lf, expected %lf",
833             segment->rate, adder->segment.rate);
834         res = FALSE;
835         gst_event_unref (event);
836         event = NULL;
837       }
838       discard = TRUE;
839       break;
840     }
841     default:
842       break;
843   }
844 
845   if (G_LIKELY (event))
846     return gst_collect_pads_event_default (pads, pad, event, discard);
847   else
848     return res;
849 }
850 
851 static void
gst_adder_class_init(GstAdderClass * klass)852 gst_adder_class_init (GstAdderClass * klass)
853 {
854   GObjectClass *gobject_class = (GObjectClass *) klass;
855   GstElementClass *gstelement_class = (GstElementClass *) klass;
856 
857   gobject_class->set_property = gst_adder_set_property;
858   gobject_class->get_property = gst_adder_get_property;
859   gobject_class->dispose = gst_adder_dispose;
860 
861   g_object_class_install_property (gobject_class, PROP_FILTER_CAPS,
862       g_param_spec_boxed ("caps", "Target caps",
863           "Set target format for mixing (NULL means ANY). "
864           "Setting this property takes a reference to the supplied GstCaps "
865           "object.", GST_TYPE_CAPS,
866           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
867 
868   gst_element_class_add_static_pad_template (gstelement_class,
869       &gst_adder_src_template);
870   gst_element_class_add_static_pad_template (gstelement_class,
871       &gst_adder_sink_template);
872   gst_element_class_set_static_metadata (gstelement_class, "Adder",
873       "Generic/Audio", "Add N audio channels together",
874       "Thomas Vander Stichele <thomas at apestaart dot org>");
875 
876   gstelement_class->request_new_pad =
877       GST_DEBUG_FUNCPTR (gst_adder_request_new_pad);
878   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_adder_release_pad);
879   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_adder_change_state);
880 }
881 
882 static void
gst_adder_init(GstAdder * adder)883 gst_adder_init (GstAdder * adder)
884 {
885   GstPadTemplate *template;
886 
887   template = gst_static_pad_template_get (&gst_adder_src_template);
888   adder->srcpad = gst_pad_new_from_template (template, "src");
889   gst_object_unref (template);
890 
891   gst_pad_set_query_function (adder->srcpad,
892       GST_DEBUG_FUNCPTR (gst_adder_src_query));
893   gst_pad_set_event_function (adder->srcpad,
894       GST_DEBUG_FUNCPTR (gst_adder_src_event));
895   GST_PAD_SET_PROXY_CAPS (adder->srcpad);
896   gst_element_add_pad (GST_ELEMENT (adder), adder->srcpad);
897 
898   adder->current_caps = NULL;
899   gst_audio_info_init (&adder->info);
900   adder->padcount = 0;
901 
902   adder->filter_caps = NULL;
903 
904   /* keep track of the sinkpads requested */
905   adder->collect = gst_collect_pads_new ();
906   gst_collect_pads_set_function (adder->collect,
907       GST_DEBUG_FUNCPTR (gst_adder_collected), adder);
908   gst_collect_pads_set_clip_function (adder->collect,
909       GST_DEBUG_FUNCPTR (gst_adder_do_clip), adder);
910   gst_collect_pads_set_event_function (adder->collect,
911       GST_DEBUG_FUNCPTR (gst_adder_sink_event), adder);
912   gst_collect_pads_set_query_function (adder->collect,
913       GST_DEBUG_FUNCPTR (gst_adder_sink_query), adder);
914 }
915 
916 static void
gst_adder_dispose(GObject * object)917 gst_adder_dispose (GObject * object)
918 {
919   GstAdder *adder = GST_ADDER (object);
920 
921   if (adder->collect) {
922     gst_object_unref (adder->collect);
923     adder->collect = NULL;
924   }
925   gst_caps_replace (&adder->filter_caps, NULL);
926   gst_caps_replace (&adder->current_caps, NULL);
927 
928   if (adder->pending_events) {
929     g_list_foreach (adder->pending_events, (GFunc) gst_event_unref, NULL);
930     g_list_free (adder->pending_events);
931     adder->pending_events = NULL;
932   }
933 
934   G_OBJECT_CLASS (parent_class)->dispose (object);
935 }
936 
937 static void
gst_adder_set_property(GObject * object,guint prop_id,const GValue * value,GParamSpec * pspec)938 gst_adder_set_property (GObject * object, guint prop_id,
939     const GValue * value, GParamSpec * pspec)
940 {
941   GstAdder *adder = GST_ADDER (object);
942 
943   switch (prop_id) {
944     case PROP_FILTER_CAPS:{
945       GstCaps *new_caps = NULL;
946       GstCaps *old_caps;
947       const GstCaps *new_caps_val = gst_value_get_caps (value);
948 
949       if (new_caps_val != NULL) {
950         new_caps = (GstCaps *) new_caps_val;
951         gst_caps_ref (new_caps);
952       }
953 
954       GST_OBJECT_LOCK (adder);
955       old_caps = adder->filter_caps;
956       adder->filter_caps = new_caps;
957       GST_OBJECT_UNLOCK (adder);
958 
959       if (old_caps)
960         gst_caps_unref (old_caps);
961 
962       GST_DEBUG_OBJECT (adder, "set new caps %" GST_PTR_FORMAT, new_caps);
963       break;
964     }
965     default:
966       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
967       break;
968   }
969 }
970 
971 static void
gst_adder_get_property(GObject * object,guint prop_id,GValue * value,GParamSpec * pspec)972 gst_adder_get_property (GObject * object, guint prop_id, GValue * value,
973     GParamSpec * pspec)
974 {
975   GstAdder *adder = GST_ADDER (object);
976 
977   switch (prop_id) {
978     case PROP_FILTER_CAPS:
979       GST_OBJECT_LOCK (adder);
980       gst_value_set_caps (value, adder->filter_caps);
981       GST_OBJECT_UNLOCK (adder);
982       break;
983     default:
984       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
985       break;
986   }
987 }
988 
989 
990 static GstPad *
gst_adder_request_new_pad(GstElement * element,GstPadTemplate * templ,const gchar * unused,const GstCaps * caps)991 gst_adder_request_new_pad (GstElement * element, GstPadTemplate * templ,
992     const gchar * unused, const GstCaps * caps)
993 {
994   gchar *name;
995   GstAdder *adder;
996   GstPad *newpad;
997   gint padcount;
998 
999   if (templ->direction != GST_PAD_SINK)
1000     goto not_sink;
1001 
1002   adder = GST_ADDER (element);
1003 
1004   /* increment pad counter */
1005   padcount = g_atomic_int_add (&adder->padcount, 1);
1006 
1007   name = g_strdup_printf ("sink_%u", padcount);
1008   newpad = g_object_new (GST_TYPE_ADDER_PAD, "name", name, "direction",
1009       templ->direction, "template", templ, NULL);
1010   GST_DEBUG_OBJECT (adder, "request new pad %s", name);
1011   g_free (name);
1012 
1013   gst_collect_pads_add_pad (adder->collect, newpad, sizeof (GstCollectData),
1014       NULL, TRUE);
1015 
1016   /* takes ownership of the pad */
1017   if (!gst_element_add_pad (GST_ELEMENT (adder), newpad))
1018     goto could_not_add;
1019 
1020   gst_child_proxy_child_added (GST_CHILD_PROXY (adder), G_OBJECT (newpad),
1021       GST_OBJECT_NAME (newpad));
1022 
1023   return newpad;
1024 
1025   /* errors */
1026 not_sink:
1027   {
1028     g_warning ("gstadder: request new pad that is not a SINK pad\n");
1029     return NULL;
1030   }
1031 could_not_add:
1032   {
1033     GST_DEBUG_OBJECT (adder, "could not add pad");
1034     gst_collect_pads_remove_pad (adder->collect, newpad);
1035     gst_object_unref (newpad);
1036     return NULL;
1037   }
1038 }
1039 
1040 static void
gst_adder_release_pad(GstElement * element,GstPad * pad)1041 gst_adder_release_pad (GstElement * element, GstPad * pad)
1042 {
1043   GstAdder *adder;
1044 
1045   adder = GST_ADDER (element);
1046 
1047   GST_DEBUG_OBJECT (adder, "release pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1048 
1049   gst_child_proxy_child_removed (GST_CHILD_PROXY (adder), G_OBJECT (pad),
1050       GST_OBJECT_NAME (pad));
1051   if (adder->collect)
1052     gst_collect_pads_remove_pad (adder->collect, pad);
1053   gst_element_remove_pad (element, pad);
1054 }
1055 
1056 static GstFlowReturn
gst_adder_do_clip(GstCollectPads * pads,GstCollectData * data,GstBuffer * buffer,GstBuffer ** out,gpointer user_data)1057 gst_adder_do_clip (GstCollectPads * pads, GstCollectData * data,
1058     GstBuffer * buffer, GstBuffer ** out, gpointer user_data)
1059 {
1060   GstAdder *adder = GST_ADDER (user_data);
1061   gint rate, bpf;
1062 
1063   rate = GST_AUDIO_INFO_RATE (&adder->info);
1064   bpf = GST_AUDIO_INFO_BPF (&adder->info);
1065 
1066   buffer = gst_audio_buffer_clip (buffer, &data->segment, rate, bpf);
1067 
1068   *out = buffer;
1069   return GST_FLOW_OK;
1070 }
1071 
1072 /*
1073  * gst_adder_collected:
1074  *
1075  * Combine audio streams by adding data values.
1076  * basic algorithm :
1077  * - this function is called when all pads have a buffer
1078  * - get available bytes on all pads.
1079  * - repeat for each input pad :
1080  *   - read available bytes, copy or add to target buffer
1081  *   - if there's an EOS event, remove the input channel
1082  * - push out the output buffer
1083  *
1084  * Note: this code will run in one of the upstream threads.
1085  *
1086  * TODO: it would be nice to have a mixing mode, instead of only adding
1087  * - for float we could downscale after collect loop
1088  * - for int we need to downscale each input to avoid clipping or
1089  *   mix into a temp (float) buffer and scale afterwards as well
1090  */
1091 static GstFlowReturn
gst_adder_collected(GstCollectPads * pads,gpointer user_data)1092 gst_adder_collected (GstCollectPads * pads, gpointer user_data)
1093 {
1094   GstAdder *adder;
1095   GSList *collected, *next = NULL;
1096   GstFlowReturn ret;
1097   GstBuffer *outbuf = NULL, *gapbuf = NULL;
1098   GstMapInfo outmap = { NULL };
1099   guint outsize;
1100   gint64 next_offset;
1101   gint64 next_timestamp;
1102   gint rate, bps, bpf;
1103   gboolean had_mute = FALSE;
1104   gboolean is_eos = TRUE;
1105   gboolean is_discont = FALSE;
1106 
1107   adder = GST_ADDER (user_data);
1108 
1109   /* this is fatal */
1110   if (G_UNLIKELY (adder->info.finfo->format == GST_AUDIO_FORMAT_UNKNOWN))
1111     goto not_negotiated;
1112 
1113   if (adder->flush_stop_pending) {
1114     GST_INFO_OBJECT (adder->srcpad, "send pending flush stop event");
1115     if (!gst_pad_push_event (adder->srcpad, gst_event_new_flush_stop (TRUE))) {
1116       GST_WARNING_OBJECT (adder->srcpad, "Sending flush stop event failed");
1117     }
1118 
1119     adder->flush_stop_pending = FALSE;
1120   }
1121 
1122   if (adder->send_stream_start) {
1123     gchar s_id[32];
1124     GstEvent *event;
1125 
1126     GST_INFO_OBJECT (adder->srcpad, "send pending stream start event");
1127     /* FIXME: create id based on input ids, we can't use
1128      * gst_pad_create_stream_id() though as that only handles 0..1 sink-pad
1129      */
1130     g_snprintf (s_id, sizeof (s_id), "adder-%08x", g_random_int ());
1131     event = gst_event_new_stream_start (s_id);
1132     gst_event_set_group_id (event, gst_util_group_id_next ());
1133 
1134     if (!gst_pad_push_event (adder->srcpad, event)) {
1135       GST_WARNING_OBJECT (adder->srcpad, "Sending stream start event failed");
1136     }
1137     adder->send_stream_start = FALSE;
1138   }
1139 
1140   if (adder->send_caps) {
1141     GstEvent *caps_event;
1142 
1143     caps_event = gst_event_new_caps (adder->current_caps);
1144     GST_INFO_OBJECT (adder->srcpad, "send pending caps event %" GST_PTR_FORMAT,
1145         caps_event);
1146     if (!gst_pad_push_event (adder->srcpad, caps_event)) {
1147       GST_WARNING_OBJECT (adder->srcpad, "Sending caps event failed");
1148     }
1149     adder->send_caps = FALSE;
1150   }
1151 
1152   rate = GST_AUDIO_INFO_RATE (&adder->info);
1153   bps = GST_AUDIO_INFO_BPS (&adder->info);
1154   bpf = GST_AUDIO_INFO_BPF (&adder->info);
1155 
1156   if (g_atomic_int_compare_and_exchange (&adder->new_segment_pending, TRUE,
1157           FALSE)) {
1158     GstEvent *event;
1159 
1160     /*
1161      * When seeking we set the start and stop positions as given in the seek
1162      * event. We also adjust offset & timestamp accordingly.
1163      * This basically ignores all newsegments sent by upstream.
1164      */
1165     event = gst_event_new_segment (&adder->segment);
1166     if (adder->segment.rate > 0.0) {
1167       adder->segment.position = adder->segment.start;
1168     } else {
1169       adder->segment.position = adder->segment.stop;
1170     }
1171     adder->offset = gst_util_uint64_scale (adder->segment.position,
1172         rate, GST_SECOND);
1173 
1174     GST_INFO_OBJECT (adder->srcpad, "sending pending new segment event %"
1175         GST_SEGMENT_FORMAT, &adder->segment);
1176     if (event) {
1177       if (!gst_pad_push_event (adder->srcpad, event)) {
1178         GST_WARNING_OBJECT (adder->srcpad, "Sending new segment event failed");
1179       }
1180     } else {
1181       GST_WARNING_OBJECT (adder->srcpad, "Creating new segment event for "
1182           "start:%" G_GINT64_FORMAT ", end:%" G_GINT64_FORMAT " failed",
1183           adder->segment.start, adder->segment.stop);
1184     }
1185     is_discont = TRUE;
1186   }
1187 
1188   /* get available bytes for reading, this can be 0 which could mean empty
1189    * buffers or EOS, which we will catch when we loop over the pads. */
1190   outsize = gst_collect_pads_available (pads);
1191 
1192   GST_LOG_OBJECT (adder,
1193       "starting to cycle through channels, %d bytes available (bps = %d, bpf = %d)",
1194       outsize, bps, bpf);
1195 
1196   for (collected = pads->data; collected; collected = next) {
1197     GstCollectData *collect_data;
1198     GstBuffer *inbuf;
1199     gboolean is_gap;
1200     GstAdderPad *pad;
1201     GstClockTime timestamp, stream_time;
1202 
1203     /* take next to see if this is the last collectdata */
1204     next = g_slist_next (collected);
1205 
1206     collect_data = (GstCollectData *) collected->data;
1207     pad = GST_ADDER_PAD (collect_data->pad);
1208 
1209     /* get a buffer of size bytes, if we get a buffer, it is at least outsize
1210      * bytes big. */
1211     inbuf = gst_collect_pads_take_buffer (pads, collect_data, outsize);
1212 
1213     if (!GST_COLLECT_PADS_STATE_IS_SET (collect_data,
1214             GST_COLLECT_PADS_STATE_EOS))
1215       is_eos = FALSE;
1216 
1217     /* NULL means EOS or an empty buffer so we still need to flush in
1218      * case of an empty buffer. */
1219     if (inbuf == NULL) {
1220       GST_LOG_OBJECT (adder, "channel %p: no bytes available", collect_data);
1221       continue;
1222     }
1223 
1224     timestamp = GST_BUFFER_TIMESTAMP (inbuf);
1225     stream_time =
1226         gst_segment_to_stream_time (&collect_data->segment, GST_FORMAT_TIME,
1227         timestamp);
1228 
1229     /* sync object properties on stream time */
1230     if (GST_CLOCK_TIME_IS_VALID (stream_time))
1231       gst_object_sync_values (GST_OBJECT (pad), stream_time);
1232 
1233     GST_OBJECT_LOCK (pad);
1234     if (pad->mute || pad->volume < G_MINDOUBLE) {
1235       had_mute = TRUE;
1236       GST_DEBUG_OBJECT (adder, "channel %p: skipping muted pad", collect_data);
1237       gst_buffer_unref (inbuf);
1238       GST_OBJECT_UNLOCK (pad);
1239       continue;
1240     }
1241 
1242     is_gap = GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_GAP);
1243 
1244     /* Try to make an output buffer */
1245     if (outbuf == NULL) {
1246       /* if this is a gap buffer but we have some more pads to check, skip it.
1247        * If we are at the last buffer, take it, regardless if it is a GAP
1248        * buffer or not. */
1249       if (is_gap && next) {
1250         GST_DEBUG_OBJECT (adder, "skipping, non-last GAP buffer");
1251         /* we keep the GAP buffer, if we don't have anymore buffers (all pads
1252          * EOS, we can use this one as the output buffer. */
1253         if (gapbuf == NULL)
1254           gapbuf = inbuf;
1255         else
1256           gst_buffer_unref (inbuf);
1257         GST_OBJECT_UNLOCK (pad);
1258         continue;
1259       }
1260 
1261       GST_LOG_OBJECT (adder, "channel %p: preparing output buffer of %d bytes",
1262           collect_data, outsize);
1263 
1264       /* make data and metadata writable, can simply return the inbuf when we
1265        * are the only one referencing this buffer. If this is the last (and
1266        * only) GAP buffer, it will automatically copy the GAP flag. */
1267       outbuf = gst_buffer_make_writable (inbuf);
1268       gst_buffer_map (outbuf, &outmap, GST_MAP_READWRITE);
1269 
1270       if (pad->volume != 1.0) {
1271         switch (adder->info.finfo->format) {
1272           case GST_AUDIO_FORMAT_U8:
1273             adder_orc_volume_u8 ((gpointer) outmap.data, pad->volume_i8,
1274                 outmap.size / bps);
1275             break;
1276           case GST_AUDIO_FORMAT_S8:
1277             adder_orc_volume_s8 ((gpointer) outmap.data, pad->volume_i8,
1278                 outmap.size / bps);
1279             break;
1280           case GST_AUDIO_FORMAT_U16:
1281             adder_orc_volume_u16 ((gpointer) outmap.data, pad->volume_i16,
1282                 outmap.size / bps);
1283             break;
1284           case GST_AUDIO_FORMAT_S16:
1285             adder_orc_volume_s16 ((gpointer) outmap.data, pad->volume_i16,
1286                 outmap.size / bps);
1287             break;
1288           case GST_AUDIO_FORMAT_U32:
1289             adder_orc_volume_u32 ((gpointer) outmap.data, pad->volume_i32,
1290                 outmap.size / bps);
1291             break;
1292           case GST_AUDIO_FORMAT_S32:
1293             adder_orc_volume_s32 ((gpointer) outmap.data, pad->volume_i32,
1294                 outmap.size / bps);
1295             break;
1296           case GST_AUDIO_FORMAT_F32:
1297             adder_orc_volume_f32 ((gpointer) outmap.data, pad->volume,
1298                 outmap.size / bps);
1299             break;
1300           case GST_AUDIO_FORMAT_F64:
1301             adder_orc_volume_f64 ((gpointer) outmap.data, pad->volume,
1302                 outmap.size / bps);
1303             break;
1304           default:
1305             g_assert_not_reached ();
1306             break;
1307         }
1308       }
1309     } else {
1310       if (!is_gap) {
1311         /* we had a previous output buffer, mix this non-GAP buffer */
1312         GstMapInfo inmap;
1313 
1314         gst_buffer_map (inbuf, &inmap, GST_MAP_READ);
1315 
1316         /* all buffers should have outsize, there are no short buffers because we
1317          * asked for the max size above */
1318         g_assert (inmap.size == outmap.size);
1319 
1320         GST_LOG_OBJECT (adder, "channel %p: mixing %" G_GSIZE_FORMAT " bytes"
1321             " from data %p", collect_data, inmap.size, inmap.data);
1322 
1323         /* further buffers, need to add them */
1324         if (pad->volume == 1.0) {
1325           switch (adder->info.finfo->format) {
1326             case GST_AUDIO_FORMAT_U8:
1327               adder_orc_add_u8 ((gpointer) outmap.data,
1328                   (gpointer) inmap.data, inmap.size / bps);
1329               break;
1330             case GST_AUDIO_FORMAT_S8:
1331               adder_orc_add_s8 ((gpointer) outmap.data,
1332                   (gpointer) inmap.data, inmap.size / bps);
1333               break;
1334             case GST_AUDIO_FORMAT_U16:
1335               adder_orc_add_u16 ((gpointer) outmap.data,
1336                   (gpointer) inmap.data, inmap.size / bps);
1337               break;
1338             case GST_AUDIO_FORMAT_S16:
1339               adder_orc_add_s16 ((gpointer) outmap.data,
1340                   (gpointer) inmap.data, inmap.size / bps);
1341               break;
1342             case GST_AUDIO_FORMAT_U32:
1343               adder_orc_add_u32 ((gpointer) outmap.data,
1344                   (gpointer) inmap.data, inmap.size / bps);
1345               break;
1346             case GST_AUDIO_FORMAT_S32:
1347               adder_orc_add_s32 ((gpointer) outmap.data,
1348                   (gpointer) inmap.data, inmap.size / bps);
1349               break;
1350             case GST_AUDIO_FORMAT_F32:
1351               adder_orc_add_f32 ((gpointer) outmap.data,
1352                   (gpointer) inmap.data, inmap.size / bps);
1353               break;
1354             case GST_AUDIO_FORMAT_F64:
1355               adder_orc_add_f64 ((gpointer) outmap.data,
1356                   (gpointer) inmap.data, inmap.size / bps);
1357               break;
1358             default:
1359               g_assert_not_reached ();
1360               break;
1361           }
1362         } else {
1363           switch (adder->info.finfo->format) {
1364             case GST_AUDIO_FORMAT_U8:
1365               adder_orc_add_volume_u8 ((gpointer) outmap.data,
1366                   (gpointer) inmap.data, pad->volume_i8, inmap.size / bps);
1367               break;
1368             case GST_AUDIO_FORMAT_S8:
1369               adder_orc_add_volume_s8 ((gpointer) outmap.data,
1370                   (gpointer) inmap.data, pad->volume_i8, inmap.size / bps);
1371               break;
1372             case GST_AUDIO_FORMAT_U16:
1373               adder_orc_add_volume_u16 ((gpointer) outmap.data,
1374                   (gpointer) inmap.data, pad->volume_i16, inmap.size / bps);
1375               break;
1376             case GST_AUDIO_FORMAT_S16:
1377               adder_orc_add_volume_s16 ((gpointer) outmap.data,
1378                   (gpointer) inmap.data, pad->volume_i16, inmap.size / bps);
1379               break;
1380             case GST_AUDIO_FORMAT_U32:
1381               adder_orc_add_volume_u32 ((gpointer) outmap.data,
1382                   (gpointer) inmap.data, pad->volume_i32, inmap.size / bps);
1383               break;
1384             case GST_AUDIO_FORMAT_S32:
1385               adder_orc_add_volume_s32 ((gpointer) outmap.data,
1386                   (gpointer) inmap.data, pad->volume_i32, inmap.size / bps);
1387               break;
1388             case GST_AUDIO_FORMAT_F32:
1389               adder_orc_add_volume_f32 ((gpointer) outmap.data,
1390                   (gpointer) inmap.data, pad->volume, inmap.size / bps);
1391               break;
1392             case GST_AUDIO_FORMAT_F64:
1393               adder_orc_add_volume_f64 ((gpointer) outmap.data,
1394                   (gpointer) inmap.data, pad->volume, inmap.size / bps);
1395               break;
1396             default:
1397               g_assert_not_reached ();
1398               break;
1399           }
1400         }
1401         gst_buffer_unmap (inbuf, &inmap);
1402       } else {
1403         /* skip gap buffer */
1404         GST_LOG_OBJECT (adder, "channel %p: skipping GAP buffer", collect_data);
1405       }
1406       gst_buffer_unref (inbuf);
1407     }
1408     GST_OBJECT_UNLOCK (pad);
1409   }
1410 
1411   if (outbuf)
1412     gst_buffer_unmap (outbuf, &outmap);
1413 
1414   if (is_eos)
1415     goto eos;
1416 
1417   if (outbuf == NULL) {
1418     /* no output buffer, reuse one of the GAP buffers then if we have one */
1419     if (gapbuf) {
1420       GST_LOG_OBJECT (adder, "reusing GAP buffer %p", gapbuf);
1421       outbuf = gapbuf;
1422     } else if (had_mute) {
1423       GstMapInfo map;
1424 
1425       /* Means we had all pads muted, create some silence */
1426       outbuf = gst_buffer_new_allocate (NULL, outsize, NULL);
1427       gst_buffer_map (outbuf, &map, GST_MAP_WRITE);
1428       gst_audio_format_info_fill_silence (adder->info.finfo, map.data, outsize);
1429       gst_buffer_unmap (outbuf, &map);
1430       GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_GAP);
1431     } else {
1432       /* assume EOS otherwise, this should not happen, really */
1433       goto eos;
1434     }
1435   } else if (gapbuf) {
1436     /* we had an output buffer, unref the gapbuffer we kept */
1437     gst_buffer_unref (gapbuf);
1438   }
1439 
1440   if (G_UNLIKELY (adder->pending_events)) {
1441     GList *tmp = adder->pending_events;
1442 
1443     while (tmp) {
1444       GstEvent *ev = (GstEvent *) tmp->data;
1445 
1446       gst_pad_push_event (adder->srcpad, ev);
1447       tmp = g_list_next (tmp);
1448     }
1449     g_list_free (adder->pending_events);
1450     adder->pending_events = NULL;
1451   }
1452 
1453   /* for the next timestamp, use the sample counter, which will
1454    * never accumulate rounding errors */
1455   if (adder->segment.rate > 0.0) {
1456     next_offset = adder->offset + outsize / bpf;
1457   } else {
1458     next_offset = adder->offset - outsize / bpf;
1459   }
1460   next_timestamp = gst_util_uint64_scale (next_offset, GST_SECOND, rate);
1461 
1462   /* set timestamps on the output buffer */
1463   GST_BUFFER_DTS (outbuf) = GST_CLOCK_TIME_NONE;
1464   if (adder->segment.rate > 0.0) {
1465     GST_BUFFER_PTS (outbuf) = adder->segment.position;
1466     GST_BUFFER_OFFSET (outbuf) = adder->offset;
1467     GST_BUFFER_OFFSET_END (outbuf) = next_offset;
1468     GST_BUFFER_DURATION (outbuf) = next_timestamp - adder->segment.position;
1469   } else {
1470     GST_BUFFER_PTS (outbuf) = next_timestamp;
1471     GST_BUFFER_OFFSET (outbuf) = next_offset;
1472     GST_BUFFER_OFFSET_END (outbuf) = adder->offset;
1473     GST_BUFFER_DURATION (outbuf) = adder->segment.position - next_timestamp;
1474   }
1475   if (is_discont) {
1476     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_DISCONT);
1477   } else {
1478     GST_BUFFER_FLAG_UNSET (outbuf, GST_BUFFER_FLAG_DISCONT);
1479   }
1480 
1481   adder->offset = next_offset;
1482   adder->segment.position = next_timestamp;
1483 
1484   /* send it out */
1485   GST_LOG_OBJECT (adder, "pushing outbuf %p, timestamp %" GST_TIME_FORMAT
1486       " offset %" G_GINT64_FORMAT, outbuf,
1487       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1488       GST_BUFFER_OFFSET (outbuf));
1489   ret = gst_pad_push (adder->srcpad, outbuf);
1490 
1491   GST_LOG_OBJECT (adder, "pushed outbuf, result = %s", gst_flow_get_name (ret));
1492 
1493   return ret;
1494 
1495   /* ERRORS */
1496 not_negotiated:
1497   {
1498     GST_ELEMENT_ERROR (adder, STREAM, FORMAT, (NULL),
1499         ("Unknown data received, not negotiated"));
1500     return GST_FLOW_NOT_NEGOTIATED;
1501   }
1502 eos:
1503   {
1504     GST_DEBUG_OBJECT (adder, "no data available, must be EOS");
1505     gst_pad_push_event (adder->srcpad, gst_event_new_eos ());
1506     return GST_FLOW_EOS;
1507   }
1508 }
1509 
1510 static GstStateChangeReturn
gst_adder_change_state(GstElement * element,GstStateChange transition)1511 gst_adder_change_state (GstElement * element, GstStateChange transition)
1512 {
1513   GstAdder *adder;
1514   GstStateChangeReturn ret;
1515 
1516   adder = GST_ADDER (element);
1517 
1518   switch (transition) {
1519     case GST_STATE_CHANGE_NULL_TO_READY:
1520       break;
1521     case GST_STATE_CHANGE_READY_TO_PAUSED:
1522       adder->offset = 0;
1523       adder->flush_stop_pending = FALSE;
1524       adder->new_segment_pending = TRUE;
1525       adder->send_stream_start = TRUE;
1526       adder->send_caps = TRUE;
1527       gst_caps_replace (&adder->current_caps, NULL);
1528       gst_segment_init (&adder->segment, GST_FORMAT_TIME);
1529       gst_collect_pads_start (adder->collect);
1530       break;
1531     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1532       break;
1533     case GST_STATE_CHANGE_PAUSED_TO_READY:
1534       /* need to unblock the collectpads before calling the
1535        * parent change_state so that streaming can finish */
1536       gst_collect_pads_stop (adder->collect);
1537       break;
1538     default:
1539       break;
1540   }
1541 
1542   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1543 
1544   switch (transition) {
1545     default:
1546       break;
1547   }
1548 
1549   return ret;
1550 }
1551 
1552 /* GstChildProxy implementation */
1553 static GObject *
gst_adder_child_proxy_get_child_by_index(GstChildProxy * child_proxy,guint index)1554 gst_adder_child_proxy_get_child_by_index (GstChildProxy * child_proxy,
1555     guint index)
1556 {
1557   GstAdder *adder = GST_ADDER (child_proxy);
1558   GObject *obj = NULL;
1559 
1560   GST_OBJECT_LOCK (adder);
1561   obj = g_list_nth_data (GST_ELEMENT_CAST (adder)->sinkpads, index);
1562   if (obj)
1563     gst_object_ref (obj);
1564   GST_OBJECT_UNLOCK (adder);
1565   return obj;
1566 }
1567 
1568 static guint
gst_adder_child_proxy_get_children_count(GstChildProxy * child_proxy)1569 gst_adder_child_proxy_get_children_count (GstChildProxy * child_proxy)
1570 {
1571   guint count = 0;
1572   GstAdder *adder = GST_ADDER (child_proxy);
1573 
1574   GST_OBJECT_LOCK (adder);
1575   count = GST_ELEMENT_CAST (adder)->numsinkpads;
1576   GST_OBJECT_UNLOCK (adder);
1577   GST_INFO_OBJECT (adder, "Children Count: %d", count);
1578   return count;
1579 }
1580 
1581 static void
gst_adder_child_proxy_init(gpointer g_iface,gpointer iface_data)1582 gst_adder_child_proxy_init (gpointer g_iface, gpointer iface_data)
1583 {
1584   GstChildProxyInterface *iface = g_iface;
1585 
1586   GST_INFO ("initializing child proxy interface");
1587   iface->get_child_by_index = gst_adder_child_proxy_get_child_by_index;
1588   iface->get_children_count = gst_adder_child_proxy_get_children_count;
1589 }
1590 
1591 static gboolean
plugin_init(GstPlugin * plugin)1592 plugin_init (GstPlugin * plugin)
1593 {
1594   gboolean ret = FALSE;
1595   GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "adder", 0,
1596       "audio channel mixing element");
1597 
1598   ret |= GST_ELEMENT_REGISTER (adder, plugin);
1599 
1600   return ret;
1601 }
1602 
1603 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1604     GST_VERSION_MINOR,
1605     adder,
1606     "Adds multiple streams",
1607     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)
1608