Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / gst / adder / gstadder.c
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., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23 /**
24  * SECTION:element-adder
25  *
26  * The adder allows to mix several streams into one by adding the data.
27  * Mixed data is clamped to the min/max values of the data format.
28  *
29  * The adder currently mixes all data received on the sinkpads as soon as
30  * possible without trying to synchronize the streams.
31  *
32  * <refsect2>
33  * <title>Example launch line</title>
34  * |[
35  * gst-launch audiotestsrc freq=100 ! adder name=mix ! audioconvert ! alsasink audiotestsrc freq=500 ! mix.
36  * ]| This pipeline produces two sine waves mixed together.
37  * </refsect2>
38  *
39  * Last reviewed on 2006-05-09 (0.10.7)
40  */
41 /* Element-Checklist-Version: 5 */
42
43 #ifdef HAVE_CONFIG_H
44 #include "config.h"
45 #endif
46 #include "gstadder.h"
47 #include <string.h>             /* strcmp */
48 #include "gstadderorc.h"
49
50 /* highest positive/lowest negative x-bit value we can use for clamping */
51 #define MAX_INT_32  ((gint32) (0x7fffffff))
52 #define MAX_INT_16  ((gint16) (0x7fff))
53 #define MAX_INT_8   ((gint8)  (0x7f))
54 #define MAX_UINT_32 ((guint32)(0xffffffff))
55 #define MAX_UINT_16 ((guint16)(0xffff))
56 #define MAX_UINT_8  ((guint8) (0xff))
57
58 #define MIN_INT_32  ((gint32) (0x80000000))
59 #define MIN_INT_16  ((gint16) (0x8000))
60 #define MIN_INT_8   ((gint8)  (0x80))
61 #define MIN_UINT_32 ((guint32)(0x00000000))
62 #define MIN_UINT_16 ((guint16)(0x0000))
63 #define MIN_UINT_8  ((guint8) (0x00))
64
65 enum
66 {
67   PROP_0,
68   PROP_FILTER_CAPS
69 };
70
71 #define GST_CAT_DEFAULT gst_adder_debug
72 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
73
74 /* elementfactory information */
75
76 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
77 #define CAPS \
78   GST_AUDIO_CAPS_MAKE ("{ S32LE, U32LE, S16LE, U16LE, S8, U8, F32LE, F64LE }")
79 #else
80 #define CAPS \
81   GST_AUDIO_CAPS_MAKE ("{ S32BE, U32BE, S16BE, U16BE, S8, U8, F32BE, F64BE }")
82 #endif
83
84 static GstStaticPadTemplate gst_adder_src_template =
85 GST_STATIC_PAD_TEMPLATE ("src",
86     GST_PAD_SRC,
87     GST_PAD_ALWAYS,
88     GST_STATIC_CAPS (CAPS)
89     );
90
91 static GstStaticPadTemplate gst_adder_sink_template =
92 GST_STATIC_PAD_TEMPLATE ("sink%d",
93     GST_PAD_SINK,
94     GST_PAD_REQUEST,
95     GST_STATIC_CAPS (CAPS)
96     );
97
98 #define gst_adder_parent_class parent_class
99 G_DEFINE_TYPE (GstAdder, gst_adder, GST_TYPE_ELEMENT);
100
101 static void gst_adder_dispose (GObject * object);
102 static void gst_adder_set_property (GObject * object, guint prop_id,
103     const GValue * value, GParamSpec * pspec);
104 static void gst_adder_get_property (GObject * object, guint prop_id,
105     GValue * value, GParamSpec * pspec);
106
107 static gboolean gst_adder_setcaps (GstAdder * adder, GstPad * pad,
108     GstCaps * caps);
109 static gboolean gst_adder_query (GstPad * pad, GstQuery * query);
110 static gboolean gst_adder_src_event (GstPad * pad, GstEvent * event);
111 static gboolean gst_adder_sink_event (GstPad * pad, GstEvent * event);
112
113 static GstPad *gst_adder_request_new_pad (GstElement * element,
114     GstPadTemplate * temp, const gchar * unused, const GstCaps * caps);
115 static void gst_adder_release_pad (GstElement * element, GstPad * pad);
116
117 static GstStateChangeReturn gst_adder_change_state (GstElement * element,
118     GstStateChange transition);
119
120 static GstBuffer *gst_adder_do_clip (GstCollectPads * pads,
121     GstCollectData * data, GstBuffer * buffer, gpointer user_data);
122 static GstFlowReturn gst_adder_collected (GstCollectPads * pads,
123     gpointer user_data);
124
125 /* non-clipping versions (for float) */
126 #define MAKE_FUNC_NC(name,type)                                 \
127 static void name (type *out, type *in, gint samples) {          \
128   gint i;                                                       \
129   for (i = 0; i < samples; i++)                                 \
130     out[i] += in[i];                                            \
131 }
132
133 /* *INDENT-OFF* */
134 MAKE_FUNC_NC (add_float64, gdouble)
135 /* *INDENT-ON* */
136
137 /* we can only accept caps that we and downstream can handle.
138  * if we have filtercaps set, use those to constrain the target caps.
139  */
140 static GstCaps *
141 gst_adder_sink_getcaps (GstPad * pad, GstCaps * filter)
142 {
143   GstAdder *adder;
144   GstCaps *result, *peercaps, *sinkcaps, *filter_caps;
145
146   adder = GST_ADDER (GST_PAD_PARENT (pad));
147
148   GST_OBJECT_LOCK (adder);
149   /* take filter */
150   if ((filter_caps = adder->filter_caps)) {
151     if (filter)
152       filter_caps =
153           gst_caps_intersect_full (filter, filter_caps,
154           GST_CAPS_INTERSECT_FIRST);
155     else
156       gst_caps_ref (filter_caps);
157   } else {
158     filter_caps = gst_caps_ref (filter);
159   }
160   GST_OBJECT_UNLOCK (adder);
161
162   if (filter_caps && gst_caps_is_empty (filter_caps)) {
163     GST_WARNING_OBJECT (pad, "Empty filter caps");
164     return filter_caps;
165   }
166
167   /* get the downstream possible caps */
168   peercaps = gst_pad_peer_get_caps (adder->srcpad, filter_caps);
169
170   /* get the allowed caps on this sinkpad */
171   sinkcaps = gst_pad_get_current_caps (pad);
172   if (sinkcaps == NULL) {
173     sinkcaps = gst_pad_get_pad_template_caps (pad);
174     if (!sinkcaps)
175       sinkcaps = gst_caps_new_any ();
176   }
177
178   if (peercaps) {
179     /* if the peer has caps, intersect */
180     GST_DEBUG_OBJECT (adder, "intersecting peer and template caps");
181     result =
182         gst_caps_intersect_full (peercaps, sinkcaps, GST_CAPS_INTERSECT_FIRST);
183     gst_caps_unref (peercaps);
184     gst_caps_unref (sinkcaps);
185   } else {
186     /* the peer has no caps (or there is no peer), just use the allowed caps
187      * of this sinkpad. */
188     /* restrict with filter-caps if any */
189     if (filter_caps) {
190       GST_DEBUG_OBJECT (adder, "no peer caps, using filtered sinkcaps");
191       result =
192           gst_caps_intersect_full (filter_caps, sinkcaps,
193           GST_CAPS_INTERSECT_FIRST);
194       gst_caps_unref (sinkcaps);
195     } else {
196       GST_DEBUG_OBJECT (adder, "no peer caps, using sinkcaps");
197       result = sinkcaps;
198     }
199   }
200
201   if (filter_caps)
202     gst_caps_unref (filter_caps);
203
204   GST_LOG_OBJECT (adder, "getting caps on pad %p,%s to %" GST_PTR_FORMAT, pad,
205       GST_PAD_NAME (pad), result);
206
207   return result;
208 }
209
210 typedef struct
211 {
212   GstPad *pad;
213   GstCaps *caps;
214 } IterData;
215
216 static void
217 setcapsfunc (const GValue * item, IterData * data)
218 {
219   GstPad *otherpad = g_value_get_object (item);
220
221   if (otherpad != data->pad)
222     gst_pad_set_caps (data->pad, data->caps);
223 }
224
225 /* the first caps we receive on any of the sinkpads will define the caps for all
226  * the other sinkpads because we can only mix streams with the same caps.
227  */
228 static gboolean
229 gst_adder_setcaps (GstAdder * adder, GstPad * pad, GstCaps * caps)
230 {
231   GstAudioInfo info;
232   GstIterator *it;
233   GstIteratorResult ires;
234   IterData idata;
235   gboolean done;
236
237   GST_LOG_OBJECT (adder, "setting caps pad %p,%s to %" GST_PTR_FORMAT, pad,
238       GST_PAD_NAME (pad), caps);
239
240   it = gst_element_iterate_pads (GST_ELEMENT_CAST (adder));
241
242   /* FIXME, see if the other pads can accept the format. Also lock the
243    * format on the other pads to this new format. */
244   idata.caps = caps;
245   idata.pad = pad;
246
247   done = FALSE;
248   while (!done) {
249     ires = gst_iterator_foreach (it, (GstIteratorForeachFunction) setcapsfunc,
250         &idata);
251
252     switch (ires) {
253       case GST_ITERATOR_RESYNC:
254         gst_iterator_resync (it);
255         break;
256       default:
257         done = TRUE;
258         break;
259     }
260   }
261
262   if (!gst_audio_info_from_caps (&info, caps))
263     goto invalid_format;
264
265   switch (GST_AUDIO_INFO_FORMAT (&info)) {
266     case GST_AUDIO_FORMAT_S8:
267       adder->func = (GstAdderFunction) add_int8;
268       break;
269     case GST_AUDIO_FORMAT_U8:
270       adder->func = (GstAdderFunction) add_uint8;
271       break;
272     case GST_AUDIO_FORMAT_S16:
273       adder->func = (GstAdderFunction) add_int16;
274       break;
275     case GST_AUDIO_FORMAT_U16:
276       adder->func = (GstAdderFunction) add_uint16;
277       break;
278     case GST_AUDIO_FORMAT_S32:
279       adder->func = (GstAdderFunction) add_int32;
280       break;
281     case GST_AUDIO_FORMAT_U32:
282       adder->func = (GstAdderFunction) add_uint32;
283       break;
284     case GST_AUDIO_FORMAT_F32:
285       adder->func = (GstAdderFunction) add_float32;
286       break;
287     case GST_AUDIO_FORMAT_F64:
288       adder->func = (GstAdderFunction) add_float64;
289       break;
290     default:
291       goto invalid_format;
292   }
293   return TRUE;
294
295   /* ERRORS */
296 invalid_format:
297   {
298     GST_DEBUG_OBJECT (adder, "invalid format set as caps");
299     return FALSE;
300   }
301 }
302
303 /* FIXME, the duration query should reflect how long you will produce
304  * data, that is the amount of stream time until you will emit EOS.
305  *
306  * For synchronized mixing this is always the max of all the durations
307  * of upstream since we emit EOS when all of them finished.
308  *
309  * We don't do synchronized mixing so this really depends on where the
310  * streams where punched in and what their relative offsets are against
311  * eachother which we can get from the first timestamps we see.
312  *
313  * When we add a new stream (or remove a stream) the duration might
314  * also become invalid again and we need to post a new DURATION
315  * message to notify this fact to the parent.
316  * For now we take the max of all the upstream elements so the simple
317  * cases work at least somewhat.
318  */
319 static gboolean
320 gst_adder_query_duration (GstAdder * adder, GstQuery * query)
321 {
322   gint64 max;
323   gboolean res;
324   GstFormat format;
325   GstIterator *it;
326   gboolean done;
327   GValue item = { 0, };
328
329   /* parse format */
330   gst_query_parse_duration (query, &format, NULL);
331
332   max = -1;
333   res = TRUE;
334   done = FALSE;
335
336   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
337   while (!done) {
338     GstIteratorResult ires;
339
340     ires = gst_iterator_next (it, &item);
341     switch (ires) {
342       case GST_ITERATOR_DONE:
343         done = TRUE;
344         break;
345       case GST_ITERATOR_OK:
346       {
347         GstPad *pad = g_value_get_object (&item);
348         gint64 duration;
349
350         /* ask sink peer for duration */
351         res &= gst_pad_query_peer_duration (pad, format, &duration);
352         /* take max from all valid return values */
353         if (res) {
354           /* valid unknown length, stop searching */
355           if (duration == -1) {
356             max = duration;
357             done = TRUE;
358           }
359           /* else see if bigger than current max */
360           else if (duration > max)
361             max = duration;
362         }
363         g_value_reset (&item);
364         break;
365       }
366       case GST_ITERATOR_RESYNC:
367         max = -1;
368         res = TRUE;
369         gst_iterator_resync (it);
370         break;
371       default:
372         res = FALSE;
373         done = TRUE;
374         break;
375     }
376   }
377   g_value_unset (&item);
378   gst_iterator_free (it);
379
380   if (res) {
381     /* and store the max */
382     GST_DEBUG_OBJECT (adder, "Total duration in format %s: %"
383         GST_TIME_FORMAT, gst_format_get_name (format), GST_TIME_ARGS (max));
384     gst_query_set_duration (query, format, max);
385   }
386
387   return res;
388 }
389
390 static gboolean
391 gst_adder_query_latency (GstAdder * adder, GstQuery * query)
392 {
393   GstClockTime min, max;
394   gboolean live;
395   gboolean res;
396   GstIterator *it;
397   gboolean done;
398   GValue item = { 0, };
399
400   res = TRUE;
401   done = FALSE;
402
403   live = FALSE;
404   min = 0;
405   max = GST_CLOCK_TIME_NONE;
406
407   /* Take maximum of all latency values */
408   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
409   while (!done) {
410     GstIteratorResult ires;
411
412     ires = gst_iterator_next (it, &item);
413     switch (ires) {
414       case GST_ITERATOR_DONE:
415         done = TRUE;
416         break;
417       case GST_ITERATOR_OK:
418       {
419         GstPad *pad = g_value_get_object (&item);
420         GstQuery *peerquery;
421         GstClockTime min_cur, max_cur;
422         gboolean live_cur;
423
424         peerquery = gst_query_new_latency ();
425
426         /* Ask peer for latency */
427         res &= gst_pad_peer_query (pad, peerquery);
428
429         /* take max from all valid return values */
430         if (res) {
431           gst_query_parse_latency (peerquery, &live_cur, &min_cur, &max_cur);
432
433           if (min_cur > min)
434             min = min_cur;
435
436           if (max_cur != GST_CLOCK_TIME_NONE &&
437               ((max != GST_CLOCK_TIME_NONE && max_cur > max) ||
438                   (max == GST_CLOCK_TIME_NONE)))
439             max = max_cur;
440
441           live = live || live_cur;
442         }
443
444         gst_query_unref (peerquery);
445         g_value_reset (&item);
446         break;
447       }
448       case GST_ITERATOR_RESYNC:
449         live = FALSE;
450         min = 0;
451         max = GST_CLOCK_TIME_NONE;
452         res = TRUE;
453         gst_iterator_resync (it);
454         break;
455       default:
456         res = FALSE;
457         done = TRUE;
458         break;
459     }
460   }
461   g_value_unset (&item);
462   gst_iterator_free (it);
463
464   if (res) {
465     /* store the results */
466     GST_DEBUG_OBJECT (adder, "Calculated total latency: live %s, min %"
467         GST_TIME_FORMAT ", max %" GST_TIME_FORMAT,
468         (live ? "yes" : "no"), GST_TIME_ARGS (min), GST_TIME_ARGS (max));
469     gst_query_set_latency (query, live, min, max);
470   }
471
472   return res;
473 }
474
475 static gboolean
476 gst_adder_query (GstPad * pad, GstQuery * query)
477 {
478   GstAdder *adder = GST_ADDER (gst_pad_get_parent (pad));
479   gboolean res = FALSE;
480
481   switch (GST_QUERY_TYPE (query)) {
482     case GST_QUERY_POSITION:
483     {
484       GstFormat format;
485
486       gst_query_parse_position (query, &format, NULL);
487
488       switch (format) {
489         case GST_FORMAT_TIME:
490           /* FIXME, bring to stream time, might be tricky */
491           gst_query_set_position (query, format, adder->segment.position);
492           res = TRUE;
493           break;
494         case GST_FORMAT_DEFAULT:
495           gst_query_set_position (query, format, adder->offset);
496           res = TRUE;
497           break;
498         default:
499           break;
500       }
501       break;
502     }
503     case GST_QUERY_DURATION:
504       res = gst_adder_query_duration (adder, query);
505       break;
506     case GST_QUERY_LATENCY:
507       res = gst_adder_query_latency (adder, query);
508       break;
509     default:
510       /* FIXME, needs a custom query handler because we have multiple
511        * sinkpads */
512       res = gst_pad_query_default (pad, query);
513       break;
514   }
515
516   gst_object_unref (adder);
517   return res;
518 }
519
520 typedef struct
521 {
522   GstEvent *event;
523   gboolean flush;
524 } EventData;
525
526 static gboolean
527 forward_event_func (const GValue * val, GValue * ret, EventData * data)
528 {
529   GstPad *pad = g_value_get_object (val);
530   GstEvent *event = data->event;
531
532   gst_event_ref (event);
533   GST_LOG_OBJECT (pad, "About to send event %s", GST_EVENT_TYPE_NAME (event));
534   if (!gst_pad_push_event (pad, event)) {
535     GST_WARNING_OBJECT (pad, "Sending event  %p (%s) failed.",
536         event, GST_EVENT_TYPE_NAME (event));
537     /* quick hack to unflush the pads, ideally we need a way to just unflush
538      * this single collect pad */
539     if (data->flush)
540       gst_pad_send_event (pad, gst_event_new_flush_stop (TRUE));
541   } else {
542     g_value_set_boolean (ret, TRUE);
543     GST_LOG_OBJECT (pad, "Sent event  %p (%s).",
544         event, GST_EVENT_TYPE_NAME (event));
545   }
546
547   /* continue on other pads, even if one failed */
548   return TRUE;
549 }
550
551 /* forwards the event to all sinkpads, takes ownership of the
552  * event
553  *
554  * Returns: TRUE if the event could be forwarded on all
555  * sinkpads.
556  */
557 static gboolean
558 forward_event (GstAdder * adder, GstEvent * event, gboolean flush)
559 {
560   gboolean ret;
561   GstIterator *it;
562   GstIteratorResult ires;
563   GValue vret = { 0 };
564   EventData data;
565
566   GST_LOG_OBJECT (adder, "Forwarding event %p (%s)", event,
567       GST_EVENT_TYPE_NAME (event));
568
569   data.event = event;
570   data.flush = flush;
571
572   g_value_init (&vret, G_TYPE_BOOLEAN);
573   g_value_set_boolean (&vret, FALSE);
574   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
575   while (TRUE) {
576     ires =
577         gst_iterator_fold (it, (GstIteratorFoldFunction) forward_event_func,
578         &vret, &data);
579     switch (ires) {
580       case GST_ITERATOR_RESYNC:
581         GST_WARNING ("resync");
582         gst_iterator_resync (it);
583         g_value_set_boolean (&vret, TRUE);
584         break;
585       case GST_ITERATOR_OK:
586       case GST_ITERATOR_DONE:
587         ret = g_value_get_boolean (&vret);
588         goto done;
589       default:
590         ret = FALSE;
591         goto done;
592     }
593   }
594 done:
595   gst_iterator_free (it);
596   GST_LOG_OBJECT (adder, "Forwarded event %p (%s), ret=%d", event,
597       GST_EVENT_TYPE_NAME (event), ret);
598   gst_event_unref (event);
599
600   return ret;
601 }
602
603 static gboolean
604 gst_adder_src_event (GstPad * pad, GstEvent * event)
605 {
606   GstAdder *adder;
607   gboolean result;
608
609   adder = GST_ADDER (gst_pad_get_parent (pad));
610
611   GST_DEBUG_OBJECT (pad, "Got %s event on src pad",
612       GST_EVENT_TYPE_NAME (event));
613
614   switch (GST_EVENT_TYPE (event)) {
615     case GST_EVENT_SEEK:
616     {
617       GstSeekFlags flags;
618       gdouble rate;
619       GstSeekType curtype, endtype;
620       gint64 cur, end;
621       gboolean flush;
622
623       /* parse the seek parameters */
624       gst_event_parse_seek (event, &rate, NULL, &flags, &curtype,
625           &cur, &endtype, &end);
626
627       if ((curtype != GST_SEEK_TYPE_NONE) && (curtype != GST_SEEK_TYPE_SET)) {
628         result = FALSE;
629         GST_DEBUG_OBJECT (adder,
630             "seeking failed, unhandled seek type for start: %d", curtype);
631         goto done;
632       }
633       if ((endtype != GST_SEEK_TYPE_NONE) && (endtype != GST_SEEK_TYPE_SET)) {
634         result = FALSE;
635         GST_DEBUG_OBJECT (adder,
636             "seeking failed, unhandled seek type for end: %d", endtype);
637         goto done;
638       }
639
640       flush = (flags & GST_SEEK_FLAG_FLUSH) == GST_SEEK_FLAG_FLUSH;
641
642       /* check if we are flushing */
643       if (flush) {
644         /* make sure we accept nothing anymore and return WRONG_STATE */
645         gst_collect_pads_set_flushing (adder->collect, TRUE);
646
647         /* flushing seek, start flush downstream, the flush will be done
648          * when all pads received a FLUSH_STOP. */
649         gst_pad_push_event (adder->srcpad, gst_event_new_flush_start ());
650
651         /* We can't send FLUSH_STOP here since upstream could start pushing data
652          * after we unlock adder->collect.
653          * We set flush_stop_pending to TRUE instead and send FLUSH_STOP after
654          * forwarding the seek upstream or from gst_adder_collected,
655          * whichever happens first.
656          */
657         g_atomic_int_set (&adder->flush_stop_pending, TRUE);
658       }
659       GST_DEBUG_OBJECT (adder, "handling seek event: %" GST_PTR_FORMAT, event);
660
661       /* now wait for the collected to be finished and mark a new
662        * segment. After we have the lock, no collect function is running and no
663        * new collect function will be called for as long as we're flushing. */
664       GST_OBJECT_LOCK (adder->collect);
665       adder->segment.rate = rate;
666       if (curtype == GST_SEEK_TYPE_SET)
667         adder->segment.start = cur;
668       else
669         adder->segment.start = 0;
670       if (endtype == GST_SEEK_TYPE_SET)
671         adder->segment.stop = end;
672       else
673         adder->segment.stop = GST_CLOCK_TIME_NONE;
674       if (flush) {
675         /* Yes, we need to call _set_flushing again *WHEN* the streaming threads
676          * have stopped so that the cookie gets properly updated. */
677         gst_collect_pads_set_flushing (adder->collect, TRUE);
678       }
679       GST_OBJECT_UNLOCK (adder->collect);
680       GST_DEBUG_OBJECT (adder, "forwarding seek event: %" GST_PTR_FORMAT,
681           event);
682
683       /* we're forwarding seek to all upstream peers and wait for one to reply
684        * with a newsegment-event before we send a newsegment-event downstream */
685       g_atomic_int_set (&adder->wait_for_new_segment, TRUE);
686       result = forward_event (adder, event, flush);
687       if (!result) {
688         /* seek failed. maybe source is a live source. */
689         GST_DEBUG_OBJECT (adder, "seeking failed");
690       }
691       if (g_atomic_int_compare_and_exchange (&adder->flush_stop_pending,
692               TRUE, FALSE)) {
693         GST_DEBUG_OBJECT (adder, "pending flush stop");
694         gst_pad_push_event (adder->srcpad, gst_event_new_flush_stop (TRUE));
695       }
696       break;
697     }
698     case GST_EVENT_QOS:
699       /* QoS might be tricky */
700       result = FALSE;
701       break;
702     case GST_EVENT_NAVIGATION:
703       /* navigation is rather pointless. */
704       result = FALSE;
705       break;
706     default:
707       /* just forward the rest for now */
708       GST_DEBUG_OBJECT (adder, "forward unhandled event: %s",
709           GST_EVENT_TYPE_NAME (event));
710       result = forward_event (adder, event, FALSE);
711       break;
712   }
713
714 done:
715   gst_object_unref (adder);
716
717   return result;
718 }
719
720 static gboolean
721 gst_adder_sink_event (GstPad * pad, GstEvent * event)
722 {
723   GstAdder *adder;
724   gboolean ret = TRUE;
725
726   adder = GST_ADDER (gst_pad_get_parent (pad));
727
728   GST_DEBUG_OBJECT (pad, "Got %s event on sink pad",
729       GST_EVENT_TYPE_NAME (event));
730
731   switch (GST_EVENT_TYPE (event)) {
732     case GST_EVENT_CAPS:
733     {
734       GstCaps *caps;
735
736       gst_event_parse_caps (event, &caps);
737       ret = gst_adder_setcaps (adder, pad, caps);
738       gst_event_unref (event);
739
740       goto beach;
741     }
742     case GST_EVENT_FLUSH_STOP:
743       /* we received a flush-stop. The collect_event function will push the
744        * event past our element. We simply forward all flush-stop events, even
745        * when no flush-stop was pending, this is required because collectpads
746        * does not provide an API to handle-but-not-forward the flush-stop.
747        * We unset the pending flush-stop flag so that we don't send anymore
748        * flush-stop from the collect function later.
749        */
750       GST_OBJECT_LOCK (adder->collect);
751       g_atomic_int_set (&adder->new_segment_pending, TRUE);
752       g_atomic_int_set (&adder->flush_stop_pending, FALSE);
753       /* Clear pending tags */
754       if (adder->pending_events) {
755         g_list_foreach (adder->pending_events, (GFunc) gst_event_unref, NULL);
756         g_list_free (adder->pending_events);
757         adder->pending_events = NULL;
758       }
759       GST_OBJECT_UNLOCK (adder->collect);
760       break;
761     case GST_EVENT_TAG:
762       GST_OBJECT_LOCK (adder->collect);
763       /* collect tags here so we can push them out when we collect data */
764       adder->pending_events = g_list_append (adder->pending_events, event);
765       GST_OBJECT_UNLOCK (adder->collect);
766       goto beach;
767     case GST_EVENT_SEGMENT:
768       if (g_atomic_int_compare_and_exchange (&adder->wait_for_new_segment,
769               TRUE, FALSE)) {
770         /* make sure we push a new segment, to inform about new basetime
771          * see FIXME in gst_adder_collected() */
772         g_atomic_int_set (&adder->new_segment_pending, TRUE);
773       }
774       break;
775     default:
776       break;
777   }
778
779   /* now GstCollectPads can take care of the rest, e.g. EOS */
780   ret = adder->collect_event (pad, event);
781
782 beach:
783   gst_object_unref (adder);
784   return ret;
785 }
786
787 static void
788 gst_adder_class_init (GstAdderClass * klass)
789 {
790   GObjectClass *gobject_class = (GObjectClass *) klass;
791   GstElementClass *gstelement_class = (GstElementClass *) klass;
792
793   gobject_class->set_property = gst_adder_set_property;
794   gobject_class->get_property = gst_adder_get_property;
795   gobject_class->dispose = gst_adder_dispose;
796
797   /**
798    * GstAdder:caps:
799    *
800    * Since: 0.10.24
801    */
802   g_object_class_install_property (gobject_class, PROP_FILTER_CAPS,
803       g_param_spec_boxed ("caps", "Target caps",
804           "Set target format for mixing (NULL means ANY). "
805           "Setting this property takes a reference to the supplied GstCaps "
806           "object.", GST_TYPE_CAPS,
807           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
808
809   gst_element_class_add_pad_template (gstelement_class,
810       gst_static_pad_template_get (&gst_adder_src_template));
811   gst_element_class_add_pad_template (gstelement_class,
812       gst_static_pad_template_get (&gst_adder_sink_template));
813   gst_element_class_set_details_simple (gstelement_class, "Adder",
814       "Generic/Audio",
815       "Add N audio channels together",
816       "Thomas Vander Stichele <thomas at apestaart dot org>");
817
818   gstelement_class->request_new_pad =
819       GST_DEBUG_FUNCPTR (gst_adder_request_new_pad);
820   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_adder_release_pad);
821   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_adder_change_state);
822 }
823
824 static void
825 gst_adder_init (GstAdder * adder)
826 {
827   GstPadTemplate *template;
828
829   template = gst_static_pad_template_get (&gst_adder_src_template);
830   adder->srcpad = gst_pad_new_from_template (template, "src");
831   gst_object_unref (template);
832
833   gst_pad_set_getcaps_function (adder->srcpad,
834       GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
835   gst_pad_set_query_function (adder->srcpad,
836       GST_DEBUG_FUNCPTR (gst_adder_query));
837   gst_pad_set_event_function (adder->srcpad,
838       GST_DEBUG_FUNCPTR (gst_adder_src_event));
839   gst_element_add_pad (GST_ELEMENT (adder), adder->srcpad);
840
841   gst_audio_info_init (&adder->info);
842   adder->padcount = 0;
843   adder->func = NULL;
844
845   adder->filter_caps = NULL;
846
847   /* keep track of the sinkpads requested */
848   adder->collect = gst_collect_pads_new ();
849   gst_collect_pads_set_function (adder->collect,
850       GST_DEBUG_FUNCPTR (gst_adder_collected), adder);
851   gst_collect_pads_set_clip_function (adder->collect,
852       GST_DEBUG_FUNCPTR (gst_adder_do_clip), adder);
853 }
854
855 static void
856 gst_adder_dispose (GObject * object)
857 {
858   GstAdder *adder = GST_ADDER (object);
859
860   if (adder->collect) {
861     gst_object_unref (adder->collect);
862     adder->collect = NULL;
863   }
864   gst_caps_replace (&adder->filter_caps, NULL);
865   if (adder->pending_events) {
866     g_list_foreach (adder->pending_events, (GFunc) gst_event_unref, NULL);
867     g_list_free (adder->pending_events);
868     adder->pending_events = NULL;
869   }
870
871   G_OBJECT_CLASS (parent_class)->dispose (object);
872 }
873
874 static void
875 gst_adder_set_property (GObject * object, guint prop_id,
876     const GValue * value, GParamSpec * pspec)
877 {
878   GstAdder *adder = GST_ADDER (object);
879
880   switch (prop_id) {
881     case PROP_FILTER_CAPS:{
882       GstCaps *new_caps = NULL;
883       GstCaps *old_caps;
884       const GstCaps *new_caps_val = gst_value_get_caps (value);
885
886       if (new_caps_val != NULL) {
887         new_caps = (GstCaps *) new_caps_val;
888         gst_caps_ref (new_caps);
889       }
890
891       GST_OBJECT_LOCK (adder);
892       old_caps = adder->filter_caps;
893       adder->filter_caps = new_caps;
894       GST_OBJECT_UNLOCK (adder);
895
896       if (old_caps)
897         gst_caps_unref (old_caps);
898
899       GST_DEBUG_OBJECT (adder, "set new caps %" GST_PTR_FORMAT, new_caps);
900       break;
901     }
902     default:
903       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
904       break;
905   }
906 }
907
908 static void
909 gst_adder_get_property (GObject * object, guint prop_id, GValue * value,
910     GParamSpec * pspec)
911 {
912   GstAdder *adder = GST_ADDER (object);
913
914   switch (prop_id) {
915     case PROP_FILTER_CAPS:
916       GST_OBJECT_LOCK (adder);
917       gst_value_set_caps (value, adder->filter_caps);
918       GST_OBJECT_UNLOCK (adder);
919       break;
920     default:
921       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
922       break;
923   }
924 }
925
926
927 static GstPad *
928 gst_adder_request_new_pad (GstElement * element, GstPadTemplate * templ,
929     const gchar * unused, const GstCaps * caps)
930 {
931   gchar *name;
932   GstAdder *adder;
933   GstPad *newpad;
934   gint padcount;
935
936   if (templ->direction != GST_PAD_SINK)
937     goto not_sink;
938
939   adder = GST_ADDER (element);
940
941   /* increment pad counter */
942 #if GLIB_CHECK_VERSION(2,29,5)
943   padcount = g_atomic_int_add (&adder->padcount, 1);
944 #else
945   padcount = g_atomic_int_exchange_and_add (&adder->padcount, 1);
946 #endif
947
948   name = g_strdup_printf ("sink%d", padcount);
949   newpad = gst_pad_new_from_template (templ, name);
950   GST_DEBUG_OBJECT (adder, "request new pad %s", name);
951   g_free (name);
952
953   gst_pad_set_getcaps_function (newpad,
954       GST_DEBUG_FUNCPTR (gst_adder_sink_getcaps));
955   gst_collect_pads_add_pad (adder->collect, newpad, sizeof (GstCollectData));
956
957   /* FIXME: hacked way to override/extend the event function of
958    * GstCollectPads; because it sets its own event function giving the
959    * element no access to events */
960   adder->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
961   gst_pad_set_event_function (newpad, GST_DEBUG_FUNCPTR (gst_adder_sink_event));
962
963   /* takes ownership of the pad */
964   if (!gst_element_add_pad (GST_ELEMENT (adder), newpad))
965     goto could_not_add;
966
967   return newpad;
968
969   /* errors */
970 not_sink:
971   {
972     g_warning ("gstadder: request new pad that is not a SINK pad\n");
973     return NULL;
974   }
975 could_not_add:
976   {
977     GST_DEBUG_OBJECT (adder, "could not add pad");
978     gst_collect_pads_remove_pad (adder->collect, newpad);
979     gst_object_unref (newpad);
980     return NULL;
981   }
982 }
983
984 static void
985 gst_adder_release_pad (GstElement * element, GstPad * pad)
986 {
987   GstAdder *adder;
988
989   adder = GST_ADDER (element);
990
991   GST_DEBUG_OBJECT (adder, "release pad %s:%s", GST_DEBUG_PAD_NAME (pad));
992
993   gst_collect_pads_remove_pad (adder->collect, pad);
994   gst_element_remove_pad (element, pad);
995 }
996
997 static GstBuffer *
998 gst_adder_do_clip (GstCollectPads * pads, GstCollectData * data,
999     GstBuffer * buffer, gpointer user_data)
1000 {
1001   GstAdder *adder = GST_ADDER (user_data);
1002   gint rate, bpf;
1003
1004   rate = GST_AUDIO_INFO_RATE (&adder->info);
1005   bpf = GST_AUDIO_INFO_BPF (&adder->info);
1006
1007   buffer = gst_audio_buffer_clip (buffer, &data->segment, rate, bpf);
1008
1009   return buffer;
1010 }
1011
1012 static GstFlowReturn
1013 gst_adder_collected (GstCollectPads * pads, gpointer user_data)
1014 {
1015   /*
1016    * combine streams by adding data values
1017    * basic algorithm :
1018    * - this function is called when all pads have a buffer
1019    * - get available bytes on all pads.
1020    * - repeat for each input pad :
1021    *   - read available bytes, copy or add to target buffer
1022    *   - if there's an EOS event, remove the input channel
1023    * - push out the output buffer
1024    *
1025    * todo:
1026    * - would be nice to have a mixing mode, where instead of adding we mix
1027    *   - for float we could downscale after collect loop
1028    *   - for int we need to downscale each input to avoid clipping or
1029    *     mix into a temp (float) buffer and scale afterwards as well
1030    */
1031   GstAdder *adder;
1032   GSList *collected, *next = NULL;
1033   GstFlowReturn ret;
1034   GstBuffer *outbuf = NULL, *gapbuf = NULL;
1035   gpointer outdata = NULL;
1036   guint outsize;
1037   gint64 next_offset;
1038   gint64 next_timestamp;
1039   gint rate, bps, bpf;
1040
1041   adder = GST_ADDER (user_data);
1042
1043   /* this is fatal */
1044   if (G_UNLIKELY (adder->func == NULL))
1045     goto not_negotiated;
1046
1047   if (g_atomic_int_compare_and_exchange (&adder->flush_stop_pending,
1048           TRUE, FALSE)) {
1049     GST_DEBUG_OBJECT (adder, "pending flush stop");
1050     gst_pad_push_event (adder->srcpad, gst_event_new_flush_stop (TRUE));
1051   }
1052
1053   /* get available bytes for reading, this can be 0 which could mean empty
1054    * buffers or EOS, which we will catch when we loop over the pads. */
1055   outsize = gst_collect_pads_available (pads);
1056   /* can only happen when no pads to collect or all EOS */
1057   if (outsize == 0)
1058     goto eos;
1059
1060   rate = GST_AUDIO_INFO_RATE (&adder->info);
1061   bps = GST_AUDIO_INFO_BPS (&adder->info);
1062   bpf = GST_AUDIO_INFO_BPF (&adder->info);
1063
1064   GST_LOG_OBJECT (adder,
1065       "starting to cycle through channels, %d bytes available (bps = %d)",
1066       outsize, bpf);
1067
1068   for (collected = pads->data; collected; collected = next) {
1069     GstCollectData *collect_data;
1070     GstBuffer *inbuf;
1071     gboolean is_gap;
1072
1073     /* take next to see if this is the last collectdata */
1074     next = g_slist_next (collected);
1075
1076     collect_data = (GstCollectData *) collected->data;
1077
1078     /* get a buffer of size bytes, if we get a buffer, it is at least outsize
1079      * bytes big. */
1080     inbuf = gst_collect_pads_take_buffer (pads, collect_data, outsize);
1081     /* NULL means EOS or an empty buffer so we still need to flush in
1082      * case of an empty buffer. */
1083     if (inbuf == NULL) {
1084       GST_LOG_OBJECT (adder, "channel %p: no bytes available", collect_data);
1085       continue;
1086     }
1087
1088     is_gap = GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_GAP);
1089
1090     /* Try to make an output buffer */
1091     if (outbuf == NULL) {
1092       /* if this is a gap buffer but we have some more pads to check, skip it.
1093        * If we are at the last buffer, take it, regardless if it is a GAP
1094        * buffer or not. */
1095       if (is_gap && next) {
1096         GST_DEBUG_OBJECT (adder, "skipping, non-last GAP buffer");
1097         /* we keep the GAP buffer, if we don't have anymore buffers (all pads
1098          * EOS, we can use this one as the output buffer. */
1099         if (gapbuf == NULL)
1100           gapbuf = inbuf;
1101         else
1102           gst_buffer_unref (inbuf);
1103         continue;
1104       }
1105
1106       GST_LOG_OBJECT (adder, "channel %p: preparing output buffer of %d bytes",
1107           collect_data, outsize);
1108
1109       outdata = gst_buffer_map (outbuf, NULL, NULL, GST_MAP_WRITE);
1110     } else {
1111       if (!is_gap) {
1112         /* we had a previous output buffer, mix this non-GAP buffer */
1113         guint8 *indata;
1114         gsize insize;
1115
1116         indata = gst_buffer_map (inbuf, &insize, NULL, GST_MAP_READ);
1117
1118         /* all buffers should have outsize, there are no short buffers because we
1119          * asked for the max size above */
1120         g_assert (insize == outsize);
1121
1122         GST_LOG_OBJECT (adder, "channel %p: mixing %" G_GSIZE_FORMAT " bytes"
1123             " from data %p", collect_data, insize, indata);
1124
1125         /* further buffers, need to add them */
1126         adder->func ((gpointer) outdata, (gpointer) indata, insize / bps);
1127         gst_buffer_unmap (inbuf, indata, insize);
1128       } else {
1129         /* skip gap buffer */
1130         GST_LOG_OBJECT (adder, "channel %p: skipping GAP buffer", collect_data);
1131       }
1132       gst_buffer_unref (inbuf);
1133     }
1134   }
1135   if (outbuf)
1136     gst_buffer_unmap (outbuf, outdata, outsize);
1137
1138   if (outbuf == NULL) {
1139     /* no output buffer, reuse one of the GAP buffers then if we have one */
1140     if (gapbuf) {
1141       GST_LOG_OBJECT (adder, "reusing GAP buffer %p", gapbuf);
1142       outbuf = gapbuf;
1143     } else
1144       /* assume EOS otherwise, this should not happen, really */
1145       goto eos;
1146   } else if (gapbuf)
1147     /* we had an output buffer, unref the gapbuffer we kept */
1148     gst_buffer_unref (gapbuf);
1149
1150   if (g_atomic_int_compare_and_exchange (&adder->new_segment_pending, TRUE,
1151           FALSE)) {
1152     GstEvent *event;
1153
1154     /* FIXME, use rate/applied_rate as set on all sinkpads.
1155      * - currently we just set rate as received from last seek-event
1156      *
1157      * When seeking we set the start and stop positions as given in the seek
1158      * event. We also adjust offset & timestamp acordingly.
1159      * This basically ignores all newsegments sent by upstream.
1160      */
1161     event = gst_event_new_segment (&adder->segment);
1162
1163     if (adder->segment.rate > 0.0) {
1164       adder->segment.position = adder->segment.start;
1165     } else {
1166       adder->segment.position = adder->segment.stop;
1167     }
1168     adder->offset = gst_util_uint64_scale (adder->segment.position,
1169         rate, GST_SECOND);
1170     GST_INFO_OBJECT (adder, "seg_start %" G_GUINT64_FORMAT ", seg_end %"
1171         G_GUINT64_FORMAT, adder->segment.start, adder->segment.stop);
1172     GST_INFO_OBJECT (adder, "timestamp %" G_GINT64_FORMAT ",new offset %"
1173         G_GINT64_FORMAT, adder->segment.position, adder->offset);
1174
1175     if (event) {
1176       if (!gst_pad_push_event (adder->srcpad, event)) {
1177         GST_WARNING_OBJECT (adder->srcpad, "Sending event failed");
1178       }
1179     } else {
1180       GST_WARNING_OBJECT (adder->srcpad, "Creating new segment event for "
1181           "start:%" G_GINT64_FORMAT "  end:%" G_GINT64_FORMAT " failed",
1182           adder->segment.start, adder->segment.stop);
1183     }
1184   }
1185
1186   if (G_UNLIKELY (adder->pending_events)) {
1187     GList *tmp = adder->pending_events;
1188
1189     while (tmp) {
1190       GstEvent *ev = (GstEvent *) tmp->data;
1191
1192       gst_pad_push_event (adder->srcpad, ev);
1193       tmp = g_list_next (tmp);
1194     }
1195     g_list_free (adder->pending_events);
1196     adder->pending_events = NULL;
1197   }
1198
1199   /* for the next timestamp, use the sample counter, which will
1200    * never accumulate rounding errors */
1201   if (adder->segment.rate > 0.0) {
1202     next_offset = adder->offset + outsize / bpf;
1203   } else {
1204     next_offset = adder->offset - outsize / bpf;
1205   }
1206   next_timestamp = gst_util_uint64_scale (next_offset, GST_SECOND, rate);
1207
1208
1209   /* set timestamps on the output buffer */
1210   if (adder->segment.rate > 0.0) {
1211     GST_BUFFER_TIMESTAMP (outbuf) = adder->segment.position;
1212     GST_BUFFER_OFFSET (outbuf) = adder->offset;
1213     GST_BUFFER_OFFSET_END (outbuf) = next_offset;
1214     GST_BUFFER_DURATION (outbuf) = next_timestamp - adder->segment.position;
1215   } else {
1216     GST_BUFFER_TIMESTAMP (outbuf) = next_timestamp;
1217     GST_BUFFER_OFFSET (outbuf) = next_offset;
1218     GST_BUFFER_OFFSET_END (outbuf) = adder->offset;
1219     GST_BUFFER_DURATION (outbuf) = adder->segment.position - next_timestamp;
1220   }
1221
1222   adder->offset = next_offset;
1223   adder->segment.position = next_timestamp;
1224
1225   /* send it out */
1226   GST_LOG_OBJECT (adder, "pushing outbuf %p, timestamp %" GST_TIME_FORMAT
1227       " offset %" G_GINT64_FORMAT, outbuf,
1228       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1229       GST_BUFFER_OFFSET (outbuf));
1230   ret = gst_pad_push (adder->srcpad, outbuf);
1231
1232   GST_LOG_OBJECT (adder, "pushed outbuf, result = %s", gst_flow_get_name (ret));
1233
1234   return ret;
1235
1236   /* ERRORS */
1237 not_negotiated:
1238   {
1239     GST_ELEMENT_ERROR (adder, STREAM, FORMAT, (NULL),
1240         ("Unknown data received, not negotiated"));
1241     return GST_FLOW_NOT_NEGOTIATED;
1242   }
1243 eos:
1244   {
1245     GST_DEBUG_OBJECT (adder, "no data available, must be EOS");
1246     gst_pad_push_event (adder->srcpad, gst_event_new_eos ());
1247     return GST_FLOW_UNEXPECTED;
1248   }
1249 }
1250
1251 static GstStateChangeReturn
1252 gst_adder_change_state (GstElement * element, GstStateChange transition)
1253 {
1254   GstAdder *adder;
1255   GstStateChangeReturn ret;
1256
1257   adder = GST_ADDER (element);
1258
1259   switch (transition) {
1260     case GST_STATE_CHANGE_NULL_TO_READY:
1261       break;
1262     case GST_STATE_CHANGE_READY_TO_PAUSED:
1263       adder->segment.position = 0;
1264       adder->offset = 0;
1265       adder->flush_stop_pending = FALSE;
1266       adder->new_segment_pending = TRUE;
1267       adder->wait_for_new_segment = FALSE;
1268       gst_segment_init (&adder->segment, GST_FORMAT_TIME);
1269       gst_collect_pads_start (adder->collect);
1270       break;
1271     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1272       break;
1273     case GST_STATE_CHANGE_PAUSED_TO_READY:
1274       /* need to unblock the collectpads before calling the
1275        * parent change_state so that streaming can finish */
1276       gst_collect_pads_stop (adder->collect);
1277       break;
1278     default:
1279       break;
1280   }
1281
1282   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1283
1284   switch (transition) {
1285     default:
1286       break;
1287   }
1288
1289   return ret;
1290 }
1291
1292
1293 static gboolean
1294 plugin_init (GstPlugin * plugin)
1295 {
1296   GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "adder", 0,
1297       "audio channel mixing element");
1298
1299   gst_adder_orc_init ();
1300
1301   if (!gst_element_register (plugin, "adder", GST_RANK_NONE, GST_TYPE_ADDER)) {
1302     return FALSE;
1303   }
1304
1305   return TRUE;
1306 }
1307
1308 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1309     GST_VERSION_MINOR,
1310     "adder",
1311     "Adds multiple streams",
1312     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)