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