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