adder: remove defines we don#t use anymore
[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 curtype, endtype;
682       gint64 cur, end;
683       gboolean flush;
684
685       /* parse the seek parameters */
686       gst_event_parse_seek (event, &rate, NULL, &flags, &curtype,
687           &cur, &endtype, &end);
688
689       if ((curtype != GST_SEEK_TYPE_NONE) && (curtype != GST_SEEK_TYPE_SET)) {
690         result = FALSE;
691         GST_DEBUG_OBJECT (adder,
692             "seeking failed, unhandled seek type for start: %d", curtype);
693         goto done;
694       }
695       if ((endtype != GST_SEEK_TYPE_NONE) && (endtype != GST_SEEK_TYPE_SET)) {
696         result = FALSE;
697         GST_DEBUG_OBJECT (adder,
698             "seeking failed, unhandled seek type for end: %d", endtype);
699         goto done;
700       }
701
702       flush = (flags & GST_SEEK_FLAG_FLUSH) == GST_SEEK_FLAG_FLUSH;
703
704       /* check if we are flushing */
705       if (flush) {
706         /* flushing seek, start flush downstream, the flush will be done
707          * when all pads received a FLUSH_STOP.
708          * Make sure we accept nothing anymore and return WRONG_STATE.
709          * We send a flush-start before, to ensure no streaming is done
710          * as we need to take the stream lock.
711          */
712         gst_pad_push_event (adder->srcpad, gst_event_new_flush_start ());
713         gst_collect_pads_set_flushing (adder->collect, TRUE);
714
715         /* We can't send FLUSH_STOP here since upstream could start pushing data
716          * after we unlock adder->collect.
717          * We set flush_stop_pending to TRUE instead and send FLUSH_STOP after
718          * forwarding the seek upstream or from gst_adder_collected,
719          * whichever happens first.
720          */
721         g_atomic_int_set (&adder->flush_stop_pending, TRUE);
722         GST_DEBUG_OBJECT (adder, "mark pending flush stop event");
723       }
724       GST_DEBUG_OBJECT (adder, "handling seek event: %" GST_PTR_FORMAT, event);
725
726       /* now wait for the collected to be finished and mark a new
727        * segment. After we have the lock, no collect function is running and no
728        * new collect function will be called for as long as we're flushing. */
729       GST_COLLECT_PADS_STREAM_LOCK (adder->collect);
730       adder->segment.rate = rate;
731       if (curtype == GST_SEEK_TYPE_SET)
732         adder->segment.start = cur;
733       else
734         adder->segment.start = 0;
735       if (endtype == GST_SEEK_TYPE_SET)
736         adder->segment.stop = end;
737       else
738         adder->segment.stop = GST_CLOCK_TIME_NONE;
739       if (flush) {
740         /* Yes, we need to call _set_flushing again *WHEN* the streaming threads
741          * have stopped so that the cookie gets properly updated. */
742         gst_collect_pads_set_flushing (adder->collect, TRUE);
743       }
744       GST_COLLECT_PADS_STREAM_UNLOCK (adder->collect);
745       GST_DEBUG_OBJECT (adder, "forwarding seek event: %" GST_PTR_FORMAT,
746           event);
747
748       /* we're forwarding seek to all upstream peers and wait for one to reply
749        * with a newsegment-event before we send a newsegment-event downstream */
750       g_atomic_int_set (&adder->wait_for_new_segment, TRUE);
751       result = forward_event (adder, event, flush);
752       if (!result) {
753         /* seek failed. maybe source is a live source. */
754         GST_DEBUG_OBJECT (adder, "seeking failed");
755       }
756       if (g_atomic_int_compare_and_exchange (&adder->flush_stop_pending,
757               TRUE, FALSE)) {
758         GST_DEBUG_OBJECT (adder, "pending flush stop");
759         if (!gst_pad_push_event (adder->srcpad,
760                 gst_event_new_flush_stop (TRUE))) {
761           GST_WARNING_OBJECT (adder, "Sending flush stop event failed");
762         }
763       }
764       break;
765     }
766     case GST_EVENT_QOS:
767       /* QoS might be tricky */
768       result = FALSE;
769       gst_event_unref (event);
770       break;
771     case GST_EVENT_NAVIGATION:
772       /* navigation is rather pointless. */
773       result = FALSE;
774       gst_event_unref (event);
775       break;
776     default:
777       /* just forward the rest for now */
778       GST_DEBUG_OBJECT (adder, "forward unhandled event: %s",
779           GST_EVENT_TYPE_NAME (event));
780       result = forward_event (adder, event, FALSE);
781       break;
782   }
783
784 done:
785
786   return result;
787 }
788
789 static gboolean
790 gst_adder_sink_event (GstCollectPads * pads, GstCollectData * pad,
791     GstEvent * event, gpointer user_data)
792 {
793   GstAdder *adder = GST_ADDER (user_data);
794   gboolean res = TRUE, discard = FALSE;
795
796   GST_DEBUG_OBJECT (pad->pad, "Got %s event on sink pad",
797       GST_EVENT_TYPE_NAME (event));
798
799   switch (GST_EVENT_TYPE (event)) {
800     case GST_EVENT_CAPS:
801     {
802       GstCaps *caps;
803
804       gst_event_parse_caps (event, &caps);
805       res = gst_adder_setcaps (adder, pad->pad, caps);
806       gst_event_unref (event);
807       event = NULL;
808     }
809     case GST_EVENT_FLUSH_START:
810       /* discard flush start events, as we forwarded one already when handing the
811        * flushing seek on the sink pad */
812       g_atomic_int_set (&adder->need_flush_stop, TRUE);
813       discard = TRUE;
814       GST_DEBUG_OBJECT (pad->pad, "eating flush start");
815       break;
816     case GST_EVENT_FLUSH_STOP:
817       /* we received a flush-stop. We will only forward it when
818        * flush_stop_pending is set, and we will unset it then.
819        */
820       if (g_atomic_int_compare_and_exchange (&adder->flush_stop_pending,
821               TRUE, FALSE)) {
822         g_atomic_int_set (&adder->new_segment_pending, TRUE);
823         GST_DEBUG_OBJECT (pad->pad, "forwarding flush stop");
824       } else {
825         discard = TRUE;
826         GST_DEBUG_OBJECT (pad->pad, "eating flush stop");
827       }
828       /* Clear pending tags */
829       if (adder->pending_events) {
830         g_list_foreach (adder->pending_events, (GFunc) gst_event_unref, NULL);
831         g_list_free (adder->pending_events);
832         adder->pending_events = NULL;
833       }
834       break;
835     case GST_EVENT_TAG:
836       /* collect tags here so we can push them out when we collect data */
837       adder->pending_events = g_list_append (adder->pending_events, event);
838       event = NULL;
839       break;
840     case GST_EVENT_SEGMENT:
841       if (g_atomic_int_compare_and_exchange (&adder->wait_for_new_segment,
842               TRUE, FALSE)) {
843         /* make sure we push a new segment, to inform about new basetime
844          * see FIXME in gst_adder_collected() */
845         g_atomic_int_set (&adder->new_segment_pending, TRUE);
846       }
847       if (g_atomic_int_compare_and_exchange (&adder->need_flush_stop,
848               TRUE, FALSE)) {
849         /* ensure that we'll eventually send a flush-stop
850          * (e.g. after a flushing seek directly sent to an upstream element) */
851         g_atomic_int_set (&adder->flush_stop_pending, TRUE);
852         GST_DEBUG_OBJECT (adder, "mark pending flush stop event");
853       }
854       discard = TRUE;
855       break;
856     default:
857       break;
858   }
859
860   if (G_LIKELY (event))
861     return gst_collect_pads_event_default (pads, pad, event, discard);
862   else
863     return res;
864 }
865
866 static void
867 gst_adder_class_init (GstAdderClass * klass)
868 {
869   GObjectClass *gobject_class = (GObjectClass *) klass;
870   GstElementClass *gstelement_class = (GstElementClass *) klass;
871
872   gobject_class->set_property = gst_adder_set_property;
873   gobject_class->get_property = gst_adder_get_property;
874   gobject_class->dispose = gst_adder_dispose;
875
876   g_object_class_install_property (gobject_class, PROP_FILTER_CAPS,
877       g_param_spec_boxed ("caps", "Target caps",
878           "Set target format for mixing (NULL means ANY). "
879           "Setting this property takes a reference to the supplied GstCaps "
880           "object.", GST_TYPE_CAPS,
881           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
882
883   gst_element_class_add_pad_template (gstelement_class,
884       gst_static_pad_template_get (&gst_adder_src_template));
885   gst_element_class_add_pad_template (gstelement_class,
886       gst_static_pad_template_get (&gst_adder_sink_template));
887   gst_element_class_set_static_metadata (gstelement_class, "Adder",
888       "Generic/Audio",
889       "Add N audio channels together",
890       "Thomas Vander Stichele <thomas at apestaart dot org>");
891
892   gstelement_class->request_new_pad =
893       GST_DEBUG_FUNCPTR (gst_adder_request_new_pad);
894   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_adder_release_pad);
895   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_adder_change_state);
896 }
897
898 static void
899 gst_adder_init (GstAdder * adder)
900 {
901   GstPadTemplate *template;
902
903   template = gst_static_pad_template_get (&gst_adder_src_template);
904   adder->srcpad = gst_pad_new_from_template (template, "src");
905   gst_object_unref (template);
906
907   gst_pad_set_query_function (adder->srcpad,
908       GST_DEBUG_FUNCPTR (gst_adder_src_query));
909   gst_pad_set_event_function (adder->srcpad,
910       GST_DEBUG_FUNCPTR (gst_adder_src_event));
911   GST_PAD_SET_PROXY_CAPS (adder->srcpad);
912   gst_element_add_pad (GST_ELEMENT (adder), adder->srcpad);
913
914   adder->current_caps = NULL;
915   gst_audio_info_init (&adder->info);
916   adder->padcount = 0;
917   adder->func = NULL;
918
919   adder->filter_caps = NULL;
920
921   /* keep track of the sinkpads requested */
922   adder->collect = gst_collect_pads_new ();
923   gst_collect_pads_set_function (adder->collect,
924       GST_DEBUG_FUNCPTR (gst_adder_collected), adder);
925   gst_collect_pads_set_clip_function (adder->collect,
926       GST_DEBUG_FUNCPTR (gst_adder_do_clip), adder);
927   gst_collect_pads_set_event_function (adder->collect,
928       GST_DEBUG_FUNCPTR (gst_adder_sink_event), adder);
929   gst_collect_pads_set_query_function (adder->collect,
930       GST_DEBUG_FUNCPTR (gst_adder_sink_query), adder);
931 }
932
933 static void
934 gst_adder_dispose (GObject * object)
935 {
936   GstAdder *adder = GST_ADDER (object);
937
938   if (adder->collect) {
939     gst_object_unref (adder->collect);
940     adder->collect = NULL;
941   }
942   gst_caps_replace (&adder->filter_caps, NULL);
943   gst_caps_replace (&adder->current_caps, NULL);
944
945   if (adder->pending_events) {
946     g_list_foreach (adder->pending_events, (GFunc) gst_event_unref, NULL);
947     g_list_free (adder->pending_events);
948     adder->pending_events = NULL;
949   }
950
951   G_OBJECT_CLASS (parent_class)->dispose (object);
952 }
953
954 static void
955 gst_adder_set_property (GObject * object, guint prop_id,
956     const GValue * value, GParamSpec * pspec)
957 {
958   GstAdder *adder = GST_ADDER (object);
959
960   switch (prop_id) {
961     case PROP_FILTER_CAPS:{
962       GstCaps *new_caps = NULL;
963       GstCaps *old_caps;
964       const GstCaps *new_caps_val = gst_value_get_caps (value);
965
966       if (new_caps_val != NULL) {
967         new_caps = (GstCaps *) new_caps_val;
968         gst_caps_ref (new_caps);
969       }
970
971       GST_OBJECT_LOCK (adder);
972       old_caps = adder->filter_caps;
973       adder->filter_caps = new_caps;
974       GST_OBJECT_UNLOCK (adder);
975
976       if (old_caps)
977         gst_caps_unref (old_caps);
978
979       GST_DEBUG_OBJECT (adder, "set new caps %" GST_PTR_FORMAT, new_caps);
980       break;
981     }
982     default:
983       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
984       break;
985   }
986 }
987
988 static void
989 gst_adder_get_property (GObject * object, guint prop_id, GValue * value,
990     GParamSpec * pspec)
991 {
992   GstAdder *adder = GST_ADDER (object);
993
994   switch (prop_id) {
995     case PROP_FILTER_CAPS:
996       GST_OBJECT_LOCK (adder);
997       gst_value_set_caps (value, adder->filter_caps);
998       GST_OBJECT_UNLOCK (adder);
999       break;
1000     default:
1001       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1002       break;
1003   }
1004 }
1005
1006
1007 static GstPad *
1008 gst_adder_request_new_pad (GstElement * element, GstPadTemplate * templ,
1009     const gchar * unused, const GstCaps * caps)
1010 {
1011   gchar *name;
1012   GstAdder *adder;
1013   GstPad *newpad;
1014   gint padcount;
1015
1016   if (templ->direction != GST_PAD_SINK)
1017     goto not_sink;
1018
1019   adder = GST_ADDER (element);
1020
1021   /* increment pad counter */
1022   padcount = g_atomic_int_add (&adder->padcount, 1);
1023
1024   name = g_strdup_printf ("sink_%u", padcount);
1025   newpad = gst_pad_new_from_template (templ, name);
1026   GST_DEBUG_OBJECT (adder, "request new pad %s", name);
1027   g_free (name);
1028
1029   gst_collect_pads_add_pad (adder->collect, newpad, sizeof (GstCollectData),
1030       NULL, TRUE);
1031
1032   /* takes ownership of the pad */
1033   if (!gst_element_add_pad (GST_ELEMENT (adder), newpad))
1034     goto could_not_add;
1035
1036   return newpad;
1037
1038   /* errors */
1039 not_sink:
1040   {
1041     g_warning ("gstadder: request new pad that is not a SINK pad\n");
1042     return NULL;
1043   }
1044 could_not_add:
1045   {
1046     GST_DEBUG_OBJECT (adder, "could not add pad");
1047     gst_collect_pads_remove_pad (adder->collect, newpad);
1048     gst_object_unref (newpad);
1049     return NULL;
1050   }
1051 }
1052
1053 static void
1054 gst_adder_release_pad (GstElement * element, GstPad * pad)
1055 {
1056   GstAdder *adder;
1057
1058   adder = GST_ADDER (element);
1059
1060   GST_DEBUG_OBJECT (adder, "release pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1061
1062   if (adder->collect)
1063     gst_collect_pads_remove_pad (adder->collect, pad);
1064   gst_element_remove_pad (element, pad);
1065 }
1066
1067 static GstFlowReturn
1068 gst_adder_do_clip (GstCollectPads * pads, GstCollectData * data,
1069     GstBuffer * buffer, GstBuffer ** out, gpointer user_data)
1070 {
1071   GstAdder *adder = GST_ADDER (user_data);
1072   gint rate, bpf;
1073
1074   rate = GST_AUDIO_INFO_RATE (&adder->info);
1075   bpf = GST_AUDIO_INFO_BPF (&adder->info);
1076
1077   buffer = gst_audio_buffer_clip (buffer, &data->segment, rate, bpf);
1078
1079   *out = buffer;
1080   return GST_FLOW_OK;
1081 }
1082
1083 static GstFlowReturn
1084 gst_adder_collected (GstCollectPads * pads, gpointer user_data)
1085 {
1086   /*
1087    * combine streams by adding data values
1088    * basic algorithm :
1089    * - this function is called when all pads have a buffer
1090    * - get available bytes on all pads.
1091    * - repeat for each input pad :
1092    *   - read available bytes, copy or add to target buffer
1093    *   - if there's an EOS event, remove the input channel
1094    * - push out the output buffer
1095    *
1096    * todo:
1097    * - would be nice to have a mixing mode, where instead of adding we mix
1098    *   - for float we could downscale after collect loop
1099    *   - for int we need to downscale each input to avoid clipping or
1100    *     mix into a temp (float) buffer and scale afterwards as well
1101    */
1102   GstAdder *adder;
1103   GSList *collected, *next = NULL;
1104   GstFlowReturn ret;
1105   GstBuffer *outbuf = NULL, *gapbuf = NULL;
1106   GstMapInfo outmap = { NULL };
1107   guint outsize;
1108   gint64 next_offset;
1109   gint64 next_timestamp;
1110   gint rate, bps, bpf;
1111
1112   adder = GST_ADDER (user_data);
1113
1114   /* this is fatal */
1115   if (G_UNLIKELY (adder->func == NULL))
1116     goto not_negotiated;
1117
1118   if (g_atomic_int_compare_and_exchange (&adder->flush_stop_pending,
1119           TRUE, FALSE)) {
1120     GST_INFO_OBJECT (adder->srcpad, "send pending flush stop event");
1121     if (!gst_pad_push_event (adder->srcpad, gst_event_new_flush_stop (TRUE))) {
1122       GST_WARNING_OBJECT (adder->srcpad, "Sending flush stop event failed");
1123     }
1124   }
1125
1126   if (adder->send_stream_start) {
1127     gchar s_id[32];
1128
1129     GST_INFO_OBJECT (adder->srcpad, "send pending stream start event");
1130     /* stream-start (FIXME: create id based on input ids) */
1131     g_snprintf (s_id, sizeof (s_id), "adder-%08x", g_random_int ());
1132     if (!gst_pad_push_event (adder->srcpad, gst_event_new_stream_start (s_id))) {
1133       GST_WARNING_OBJECT (adder->srcpad, "Sending stream start event failed");
1134     }
1135     adder->send_stream_start = FALSE;
1136   }
1137
1138   if (adder->send_caps) {
1139     GstEvent *caps_event;
1140
1141     caps_event = gst_event_new_caps (adder->current_caps);
1142     GST_INFO_OBJECT (adder->srcpad, "send pending caps event %" GST_PTR_FORMAT,
1143         caps_event);
1144     if (!gst_pad_push_event (adder->srcpad, caps_event)) {
1145       GST_WARNING_OBJECT (adder->srcpad, "Sending caps event failed");
1146     }
1147     adder->send_caps = FALSE;
1148   }
1149
1150   /* get available bytes for reading, this can be 0 which could mean empty
1151    * buffers or EOS, which we will catch when we loop over the pads. */
1152   outsize = gst_collect_pads_available (pads);
1153   /* can only happen when no pads to collect or all EOS */
1154   if (outsize == 0)
1155     goto eos;
1156
1157   rate = GST_AUDIO_INFO_RATE (&adder->info);
1158   bps = GST_AUDIO_INFO_BPS (&adder->info);
1159   bpf = GST_AUDIO_INFO_BPF (&adder->info);
1160
1161   GST_LOG_OBJECT (adder,
1162       "starting to cycle through channels, %d bytes available (bps = %d, bpf = %d)",
1163       outsize, bps, bpf);
1164
1165   for (collected = pads->data; collected; collected = next) {
1166     GstCollectData *collect_data;
1167     GstBuffer *inbuf;
1168     gboolean is_gap;
1169
1170     /* take next to see if this is the last collectdata */
1171     next = g_slist_next (collected);
1172
1173     collect_data = (GstCollectData *) collected->data;
1174
1175     /* get a buffer of size bytes, if we get a buffer, it is at least outsize
1176      * bytes big. */
1177     inbuf = gst_collect_pads_take_buffer (pads, collect_data, outsize);
1178     /* NULL means EOS or an empty buffer so we still need to flush in
1179      * case of an empty buffer. */
1180     if (inbuf == NULL) {
1181       GST_LOG_OBJECT (adder, "channel %p: no bytes available", collect_data);
1182       continue;
1183     }
1184
1185     is_gap = GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_GAP);
1186
1187     /* Try to make an output buffer */
1188     if (outbuf == NULL) {
1189       /* if this is a gap buffer but we have some more pads to check, skip it.
1190        * If we are at the last buffer, take it, regardless if it is a GAP
1191        * buffer or not. */
1192       if (is_gap && next) {
1193         GST_DEBUG_OBJECT (adder, "skipping, non-last GAP buffer");
1194         /* we keep the GAP buffer, if we don't have anymore buffers (all pads
1195          * EOS, we can use this one as the output buffer. */
1196         if (gapbuf == NULL)
1197           gapbuf = inbuf;
1198         else
1199           gst_buffer_unref (inbuf);
1200         continue;
1201       }
1202
1203       GST_LOG_OBJECT (adder, "channel %p: preparing output buffer of %d bytes",
1204           collect_data, outsize);
1205
1206       /* make data and metadata writable, can simply return the inbuf when we
1207        * are the only one referencing this buffer. If this is the last (and
1208        * only) GAP buffer, it will automatically copy the GAP flag. */
1209       outbuf = gst_buffer_make_writable (inbuf);
1210       gst_buffer_map (outbuf, &outmap, GST_MAP_WRITE);
1211     } else {
1212       if (!is_gap) {
1213         /* we had a previous output buffer, mix this non-GAP buffer */
1214         GstMapInfo inmap;
1215
1216         gst_buffer_map (inbuf, &inmap, GST_MAP_READ);
1217
1218         /* all buffers should have outsize, there are no short buffers because we
1219          * asked for the max size above */
1220         g_assert (inmap.size == outmap.size);
1221
1222         GST_LOG_OBJECT (adder, "channel %p: mixing %" G_GSIZE_FORMAT " bytes"
1223             " from data %p", collect_data, inmap.size, inmap.data);
1224
1225         /* further buffers, need to add them */
1226         adder->func ((gpointer) outmap.data, (gpointer) inmap.data,
1227             inmap.size / bps);
1228         gst_buffer_unmap (inbuf, &inmap);
1229       } else {
1230         /* skip gap buffer */
1231         GST_LOG_OBJECT (adder, "channel %p: skipping GAP buffer", collect_data);
1232       }
1233       gst_buffer_unref (inbuf);
1234     }
1235   }
1236   if (outbuf)
1237     gst_buffer_unmap (outbuf, &outmap);
1238
1239   if (outbuf == NULL) {
1240     /* no output buffer, reuse one of the GAP buffers then if we have one */
1241     if (gapbuf) {
1242       GST_LOG_OBJECT (adder, "reusing GAP buffer %p", gapbuf);
1243       outbuf = gapbuf;
1244     } else
1245       /* assume EOS otherwise, this should not happen, really */
1246       goto eos;
1247   } else if (gapbuf)
1248     /* we had an output buffer, unref the gapbuffer we kept */
1249     gst_buffer_unref (gapbuf);
1250
1251   if (g_atomic_int_compare_and_exchange (&adder->new_segment_pending, TRUE,
1252           FALSE)) {
1253     GstEvent *event;
1254
1255     /* FIXME, use rate/applied_rate as set on all sinkpads.
1256      * - currently we just set rate as received from last seek-event
1257      *
1258      * When seeking we set the start and stop positions as given in the seek
1259      * event. We also adjust offset & timestamp accordingly.
1260      * This basically ignores all newsegments sent by upstream.
1261      */
1262     event = gst_event_new_segment (&adder->segment);
1263
1264     if (adder->segment.rate > 0.0) {
1265       adder->segment.position = adder->segment.start;
1266     } else {
1267       adder->segment.position = adder->segment.stop;
1268     }
1269     adder->offset = gst_util_uint64_scale (adder->segment.position,
1270         rate, GST_SECOND);
1271     GST_INFO_OBJECT (adder->srcpad, "sending pending new segment event %"
1272         GST_PTR_FORMAT, adder->segment);
1273     if (event) {
1274       if (!gst_pad_push_event (adder->srcpad, event)) {
1275         GST_WARNING_OBJECT (adder->srcpad, "Sending new segment event failed");
1276       }
1277     } else {
1278       GST_WARNING_OBJECT (adder->srcpad, "Creating new segment event for "
1279           "start:%" G_GINT64_FORMAT "  end:%" G_GINT64_FORMAT " failed",
1280           adder->segment.start, adder->segment.stop);
1281     }
1282   }
1283
1284   if (G_UNLIKELY (adder->pending_events)) {
1285     GList *tmp = adder->pending_events;
1286
1287     while (tmp) {
1288       GstEvent *ev = (GstEvent *) tmp->data;
1289
1290       gst_pad_push_event (adder->srcpad, ev);
1291       tmp = g_list_next (tmp);
1292     }
1293     g_list_free (adder->pending_events);
1294     adder->pending_events = NULL;
1295   }
1296
1297   /* for the next timestamp, use the sample counter, which will
1298    * never accumulate rounding errors */
1299   if (adder->segment.rate > 0.0) {
1300     next_offset = adder->offset + outsize / bpf;
1301   } else {
1302     next_offset = adder->offset - outsize / bpf;
1303   }
1304   next_timestamp = gst_util_uint64_scale (next_offset, GST_SECOND, rate);
1305
1306
1307   /* set timestamps on the output buffer */
1308   if (adder->segment.rate > 0.0) {
1309     GST_BUFFER_TIMESTAMP (outbuf) = adder->segment.position;
1310     GST_BUFFER_OFFSET (outbuf) = adder->offset;
1311     GST_BUFFER_OFFSET_END (outbuf) = next_offset;
1312     GST_BUFFER_DURATION (outbuf) = next_timestamp - adder->segment.position;
1313   } else {
1314     GST_BUFFER_TIMESTAMP (outbuf) = next_timestamp;
1315     GST_BUFFER_OFFSET (outbuf) = next_offset;
1316     GST_BUFFER_OFFSET_END (outbuf) = adder->offset;
1317     GST_BUFFER_DURATION (outbuf) = adder->segment.position - next_timestamp;
1318   }
1319
1320   adder->offset = next_offset;
1321   adder->segment.position = next_timestamp;
1322
1323   /* send it out */
1324   GST_LOG_OBJECT (adder, "pushing outbuf %p, timestamp %" GST_TIME_FORMAT
1325       " offset %" G_GINT64_FORMAT, outbuf,
1326       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1327       GST_BUFFER_OFFSET (outbuf));
1328   ret = gst_pad_push (adder->srcpad, outbuf);
1329
1330   GST_LOG_OBJECT (adder, "pushed outbuf, result = %s", gst_flow_get_name (ret));
1331
1332   return ret;
1333
1334   /* ERRORS */
1335 not_negotiated:
1336   {
1337     GST_ELEMENT_ERROR (adder, STREAM, FORMAT, (NULL),
1338         ("Unknown data received, not negotiated"));
1339     return GST_FLOW_NOT_NEGOTIATED;
1340   }
1341 eos:
1342   {
1343     GST_DEBUG_OBJECT (adder, "no data available, must be EOS");
1344     gst_pad_push_event (adder->srcpad, gst_event_new_eos ());
1345     return GST_FLOW_EOS;
1346   }
1347 }
1348
1349 static GstStateChangeReturn
1350 gst_adder_change_state (GstElement * element, GstStateChange transition)
1351 {
1352   GstAdder *adder;
1353   GstStateChangeReturn ret;
1354
1355   adder = GST_ADDER (element);
1356
1357   switch (transition) {
1358     case GST_STATE_CHANGE_NULL_TO_READY:
1359       break;
1360     case GST_STATE_CHANGE_READY_TO_PAUSED:
1361       adder->segment.position = 0;
1362       adder->offset = 0;
1363       adder->flush_stop_pending = FALSE;
1364       adder->new_segment_pending = TRUE;
1365       adder->wait_for_new_segment = FALSE;
1366       adder->send_stream_start = TRUE;
1367       adder->send_caps = TRUE;
1368       gst_caps_replace (&adder->current_caps, NULL);
1369       gst_segment_init (&adder->segment, GST_FORMAT_TIME);
1370       gst_collect_pads_start (adder->collect);
1371       break;
1372     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1373       break;
1374     case GST_STATE_CHANGE_PAUSED_TO_READY:
1375       /* need to unblock the collectpads before calling the
1376        * parent change_state so that streaming can finish */
1377       gst_collect_pads_stop (adder->collect);
1378       break;
1379     default:
1380       break;
1381   }
1382
1383   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1384
1385   switch (transition) {
1386     default:
1387       break;
1388   }
1389
1390   return ret;
1391 }
1392
1393 static gboolean
1394 plugin_init (GstPlugin * plugin)
1395 {
1396   GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "adder", 0,
1397       "audio channel mixing element");
1398
1399   if (!gst_element_register (plugin, "adder", GST_RANK_NONE, GST_TYPE_ADDER)) {
1400     return FALSE;
1401   }
1402
1403   return TRUE;
1404 }
1405
1406 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1407     GST_VERSION_MINOR,
1408     adder,
1409     "Adds multiple streams",
1410     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)