gst/adder/gstadder.*: Remember the start position asked in the incoming seeks, so...
[platform/upstream/gstreamer.git] / gst / adder / gstadder.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2001 Thomas <thomas@apestaart.org>
4  *               2005,2006 Wim Taymans <wim@fluendo.com>
5  *
6  * adder.c: Adder element, N in, one out, samples are added
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23 /**
24  * SECTION:element-adder
25  *
26  * <refsect2>
27  * The Adder allows to mix several streams into one by adding the data.
28  * Mixed data is clamped to the min/max values of the data format.
29  * <title>Example launch line</title>
30  * <para>
31  * <programlisting>
32  * gst-launch audiotestsrc freq=100 ! adder name=mix ! audioconvert ! alsasink audiotestsrc freq=500 ! mix.
33  * </programlisting>
34  * This pipeline produces two sine waves mixed together.
35  * </para>
36  * <para>
37  * The Adder currently mixes all data received on the sinkpads as soon as possible
38  * without trying to synchronize the streams.
39  * </para>
40  * </refsect2>
41  *
42  * Last reviewed on 2006-05-09 (0.10.7)
43  */
44 /* Element-Checklist-Version: 5 */
45
46 #ifdef HAVE_CONFIG_H
47 #include "config.h"
48 #endif
49 #include "gstadder.h"
50 #include <gst/audio/audio.h>
51 #include <string.h>             /* strcmp */
52
53 /* highest positive/lowest negative x-bit value we can use for clamping */
54 #define MAX_INT_32  ((gint32) (0x7fffffff))
55 #define MAX_INT_16  ((gint16) (0x7fff))
56 #define MAX_INT_8   ((gint8)  (0x7f))
57 #define MAX_UINT_32 ((guint32)(0xffffffff))
58 #define MAX_UINT_16 ((guint16)(0xffff))
59 #define MAX_UINT_8  ((guint8) (0xff))
60
61 #define MIN_INT_32  ((gint32) (0x80000000))
62 #define MIN_INT_16  ((gint16) (0x8000))
63 #define MIN_INT_8   ((gint8)  (0x80))
64 #define MIN_UINT_32 ((guint32)(0x00000000))
65 #define MIN_UINT_16 ((guint16)(0x0000))
66 #define MIN_UINT_8  ((guint8) (0x00))
67
68 #define GST_CAT_DEFAULT gst_adder_debug
69 GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
70
71 /* elementfactory information */
72 static const GstElementDetails adder_details = GST_ELEMENT_DETAILS ("Adder",
73     "Generic/Audio",
74     "Add N audio channels together",
75     "Thomas <thomas@apestaart.org>");
76
77 static GstStaticPadTemplate gst_adder_src_template =
78     GST_STATIC_PAD_TEMPLATE ("src",
79     GST_PAD_SRC,
80     GST_PAD_ALWAYS,
81     GST_STATIC_CAPS (GST_AUDIO_INT_PAD_TEMPLATE_CAPS "; "
82         GST_AUDIO_FLOAT_PAD_TEMPLATE_CAPS)
83     );
84
85 static GstStaticPadTemplate gst_adder_sink_template =
86     GST_STATIC_PAD_TEMPLATE ("sink%d",
87     GST_PAD_SINK,
88     GST_PAD_REQUEST,
89     GST_STATIC_CAPS (GST_AUDIO_INT_PAD_TEMPLATE_CAPS "; "
90         GST_AUDIO_FLOAT_PAD_TEMPLATE_CAPS)
91     );
92
93 static void gst_adder_class_init (GstAdderClass * klass);
94 static void gst_adder_init (GstAdder * adder);
95 static void gst_adder_finalize (GObject * object);
96
97 static gboolean gst_adder_setcaps (GstPad * pad, GstCaps * caps);
98 static gboolean gst_adder_query (GstPad * pad, GstQuery * query);
99 static gboolean gst_adder_src_event (GstPad * pad, GstEvent * event);
100 static gboolean gst_adder_sink_event (GstPad * pad, GstEvent * event);
101
102 static GstPad *gst_adder_request_new_pad (GstElement * element,
103     GstPadTemplate * temp, const gchar * unused);
104 static void gst_adder_release_pad (GstElement * element, GstPad * pad);
105
106 static GstStateChangeReturn gst_adder_change_state (GstElement * element,
107     GstStateChange transition);
108
109 static GstFlowReturn gst_adder_collected (GstCollectPads * pads,
110     gpointer user_data);
111
112 static GstElementClass *parent_class = NULL;
113
114 GType
115 gst_adder_get_type (void)
116 {
117   static GType adder_type = 0;
118
119   if (G_UNLIKELY (adder_type == 0)) {
120     static const GTypeInfo adder_info = {
121       sizeof (GstAdderClass), NULL, NULL,
122       (GClassInitFunc) gst_adder_class_init, NULL, NULL,
123       sizeof (GstAdder), 0,
124       (GInstanceInitFunc) gst_adder_init,
125     };
126
127     adder_type = g_type_register_static (GST_TYPE_ELEMENT, "GstAdder",
128         &adder_info, 0);
129     GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "adder", 0,
130         "audio channel mixing element");
131   }
132   return adder_type;
133 }
134
135 /* clipping versions */
136 #define MAKE_FUNC(name,type,ttype,min,max)                      \
137 static void name (type *out, type *in, gint bytes) {            \
138   gint i;                                                       \
139   for (i = 0; i < bytes / sizeof (type); i++)                   \
140     out[i] = CLAMP ((ttype)out[i] + (ttype)in[i], min, max);    \
141 }
142
143 /* non-clipping versions (for float) */
144 #define MAKE_FUNC_NC(name,type,ttype)                           \
145 static void name (type *out, type *in, gint bytes) {            \
146   gint i;                                                       \
147   for (i = 0; i < bytes / sizeof (type); i++)                   \
148     out[i] = (ttype)out[i] + (ttype)in[i];                      \
149 }
150
151 /* *INDENT-OFF* */
152 MAKE_FUNC (add_int32, gint32, gint64, MIN_INT_32, MAX_INT_32)
153 MAKE_FUNC (add_int16, gint16, gint32, MIN_INT_16, MAX_INT_16)
154 MAKE_FUNC (add_int8, gint8, gint16, MIN_INT_8, MAX_INT_8)
155 MAKE_FUNC (add_uint32, guint32, guint64, MIN_UINT_32, MAX_UINT_32)
156 MAKE_FUNC (add_uint16, guint16, guint32, MIN_UINT_16, MAX_UINT_16)
157 MAKE_FUNC (add_uint8, guint8, guint16, MIN_UINT_8, MAX_UINT_8)
158 MAKE_FUNC_NC (add_float64, gdouble, gdouble)
159 MAKE_FUNC_NC (add_float32, gfloat, gfloat)
160 /* *INDENT-ON* */
161
162 static gboolean
163 gst_adder_setcaps (GstPad * pad, GstCaps * caps)
164 {
165   GstAdder *adder;
166   GList *pads;
167   GstStructure *structure;
168   const char *media_type;
169
170   adder = GST_ADDER (GST_PAD_PARENT (pad));
171
172   /* FIXME, see if the other pads can accept the format. Also lock the
173    * format on the other pads to this new format. */
174   GST_OBJECT_LOCK (adder);
175   pads = GST_ELEMENT (adder)->pads;
176   while (pads) {
177     GstPad *otherpad = GST_PAD (pads->data);
178
179     if (otherpad != pad) {
180       gst_caps_replace (&GST_PAD_CAPS (otherpad), caps);
181     }
182     pads = g_list_next (pads);
183   }
184   GST_OBJECT_UNLOCK (adder);
185
186   /* parse caps now */
187   structure = gst_caps_get_structure (caps, 0);
188   media_type = gst_structure_get_name (structure);
189   if (strcmp (media_type, "audio/x-raw-int") == 0) {
190     GST_DEBUG_OBJECT (adder, "parse_caps sets adder to format int");
191     adder->format = GST_ADDER_FORMAT_INT;
192     gst_structure_get_int (structure, "width", &adder->width);
193     gst_structure_get_int (structure, "depth", &adder->depth);
194     gst_structure_get_int (structure, "endianness", &adder->endianness);
195     gst_structure_get_boolean (structure, "signed", &adder->is_signed);
196
197     if (adder->endianness != G_BYTE_ORDER)
198       goto not_supported;
199
200     switch (adder->width) {
201       case 8:
202         adder->func = (adder->is_signed ?
203             (GstAdderFunction) add_int8 : (GstAdderFunction) add_uint8);
204         break;
205       case 16:
206         adder->func = (adder->is_signed ?
207             (GstAdderFunction) add_int16 : (GstAdderFunction) add_uint16);
208         break;
209       case 32:
210         adder->func = (adder->is_signed ?
211             (GstAdderFunction) add_int32 : (GstAdderFunction) add_uint32);
212         break;
213       default:
214         goto not_supported;
215     }
216   } else if (strcmp (media_type, "audio/x-raw-float") == 0) {
217     GST_DEBUG_OBJECT (adder, "parse_caps sets adder to format float");
218     adder->format = GST_ADDER_FORMAT_FLOAT;
219     gst_structure_get_int (structure, "width", &adder->width);
220
221     switch (adder->width) {
222       case 32:
223         adder->func = (GstAdderFunction) add_float32;
224         break;
225       case 64:
226         adder->func = (GstAdderFunction) add_float64;
227         break;
228       default:
229         goto not_supported;
230     }
231   } else {
232     goto not_supported;
233   }
234
235   gst_structure_get_int (structure, "channels", &adder->channels);
236   gst_structure_get_int (structure, "rate", &adder->rate);
237   /* precalc bps */
238   adder->bps = (adder->width / 8) * adder->channels;
239
240   return TRUE;
241
242   /* ERRORS */
243 not_supported:
244   {
245     GST_DEBUG_OBJECT (adder, "unsupported format set as caps");
246     return FALSE;
247   }
248 }
249
250 /* FIXME, the duration query should reflect how long you will produce
251  * data, that is the amount of stream time until you will emit EOS. 
252  *
253  * For synchronized mixing this is always the max of all the durations
254  * of upstream since we emit EOS when all of them finished.
255  *
256  * We don't do synchronized mixing so this really depends on where the
257  * streams where punched in and what their relative offsets are against
258  * eachother which we can get from the first timestamps we see.
259  *
260  * When we add a new stream (or remove a stream) the duration might
261  * also become invalid again and we need to post a new DURATION
262  * message to notify this fact to the parent.
263  * For now we take the max of all the upstream elements so the simple
264  * cases work at least somewhat. 
265  */
266 static gboolean
267 gst_adder_query_duration (GstAdder * adder, GstQuery * query)
268 {
269   gint64 max;
270   gboolean res;
271   GstFormat format;
272   GstIterator *it;
273   gboolean done;
274
275   /* parse format */
276   gst_query_parse_duration (query, &format, NULL);
277
278   max = -1;
279   res = TRUE;
280   done = FALSE;
281
282   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
283   while (!done) {
284     GstIteratorResult ires;
285     gpointer item;
286
287     ires = gst_iterator_next (it, &item);
288     switch (ires) {
289       case GST_ITERATOR_DONE:
290         done = TRUE;
291         break;
292       case GST_ITERATOR_OK:
293       {
294         GstPad *pad = GST_PAD_CAST (item);
295         gint64 duration;
296
297         /* ask sink peer for duration */
298         res &= gst_pad_query_peer_duration (pad, &format, &duration);
299         /* take max from all valid return values */
300         if (res) {
301           /* valid unknown length, stop searching */
302           if (duration == -1) {
303             max = duration;
304             done = TRUE;
305           }
306           /* else see if bigger than current max */
307           else if (duration > max)
308             max = duration;
309         }
310         break;
311       }
312       case GST_ITERATOR_RESYNC:
313         max = -1;
314         res = TRUE;
315         break;
316       default:
317         res = FALSE;
318         done = TRUE;
319         break;
320     }
321   }
322   gst_iterator_free (it);
323
324   if (res) {
325     /* and store the max */
326     gst_query_set_duration (query, format, max);
327   }
328
329   return res;
330 }
331
332 static gboolean
333 gst_adder_query (GstPad * pad, GstQuery * query)
334 {
335   GstAdder *adder = GST_ADDER (gst_pad_get_parent (pad));
336   gboolean res = FALSE;
337
338   switch (GST_QUERY_TYPE (query)) {
339     case GST_QUERY_POSITION:
340     {
341       GstFormat format;
342
343       gst_query_parse_position (query, &format, NULL);
344
345       switch (format) {
346         case GST_FORMAT_TIME:
347           /* FIXME, bring to stream time, might be tricky */
348           gst_query_set_position (query, format, adder->timestamp);
349           res = TRUE;
350           break;
351         case GST_FORMAT_DEFAULT:
352           gst_query_set_position (query, format, adder->offset);
353           res = TRUE;
354           break;
355         default:
356           break;
357       }
358       break;
359     }
360     case GST_QUERY_DURATION:
361       res = gst_adder_query_duration (adder, query);
362       break;
363     default:
364       /* FIXME, needs a custom query handler because we have multiple
365        * sinkpads */
366       res = gst_pad_query_default (pad, query);
367       break;
368   }
369
370   gst_object_unref (adder);
371   return res;
372 }
373
374 static gboolean
375 forward_event_func (GstPad * pad, GValue * ret, GstEvent * event)
376 {
377   gst_event_ref (event);
378   GST_LOG_OBJECT (pad, "About to send event %s", GST_EVENT_TYPE_NAME (event));
379   if (!gst_pad_push_event (pad, event)) {
380     g_value_set_boolean (ret, FALSE);
381     GST_WARNING_OBJECT (pad, "Sending event  %p (%s) failed.",
382         event, GST_EVENT_TYPE_NAME (event));
383   } else {
384     GST_LOG_OBJECT (pad, "Sent event  %p (%s).",
385         event, GST_EVENT_TYPE_NAME (event));
386   }
387   gst_object_unref (pad);
388   return TRUE;
389 }
390
391 /* forwards the event to all sinkpads, takes ownership of the 
392  * event
393  *
394  * Returns: TRUE if the event could be forwarded on all
395  * sinkpads.
396  */
397 static gboolean
398 forward_event (GstAdder * adder, GstEvent * event)
399 {
400   gboolean ret;
401   GstIterator *it;
402   GValue vret = { 0 };
403
404   GST_LOG_OBJECT (adder, "Forwarding event %p (%s)", event,
405       GST_EVENT_TYPE_NAME (event));
406
407   ret = TRUE;
408
409   g_value_init (&vret, G_TYPE_BOOLEAN);
410   g_value_set_boolean (&vret, TRUE);
411   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
412   gst_iterator_fold (it, (GstIteratorFoldFunction) forward_event_func, &vret,
413       event);
414   gst_iterator_free (it);
415   gst_event_unref (event);
416
417   ret = g_value_get_boolean (&vret);
418
419   return ret;
420 }
421
422 static gboolean
423 gst_adder_src_event (GstPad * pad, GstEvent * event)
424 {
425   GstAdder *adder;
426   gboolean result;
427
428   adder = GST_ADDER (gst_pad_get_parent (pad));
429
430   switch (GST_EVENT_TYPE (event)) {
431     case GST_EVENT_QOS:
432       /* QoS might be tricky */
433       result = FALSE;
434       break;
435     case GST_EVENT_SEEK:
436     {
437       GstSeekFlags flags;
438       GstSeekType curtype;
439       guint64 cur;
440
441       /* parse the flushing flag */
442       gst_event_parse_seek (event, NULL, NULL, &flags, &curtype, &cur, NULL,
443           NULL);
444
445       /* if we are not flushing, just forward */
446       if (!flags & GST_SEEK_FLAG_FLUSH)
447         goto done;
448
449       /* make sure we accept nothing anymore and return WRONG_STATE */
450       gst_collect_pads_set_flushing (adder->collect, TRUE);
451
452       /* flushing seek, start flush downstream, the flush will be done
453        * when all pads received a FLUSH_STOP. */
454       gst_pad_push_event (adder->srcpad, gst_event_new_flush_start ());
455
456       /* now wait for the collected to be finished and mark a new 
457        * segment */
458       GST_OBJECT_LOCK (adder->collect);
459       if (curtype == GST_SEEK_TYPE_SET)
460         adder->segment_position = cur;
461       else
462         adder->segment_position = 0;
463       adder->segment_pending = TRUE;
464       GST_OBJECT_UNLOCK (adder->collect);
465
466     done:
467       result = forward_event (adder, event);
468       break;
469     }
470     case GST_EVENT_NAVIGATION:
471       /* navigation is rather pointless. */
472       result = FALSE;
473       break;
474     default:
475       /* just forward the rest for now */
476       result = forward_event (adder, event);
477       break;
478   }
479   gst_object_unref (adder);
480
481   return result;
482 }
483
484 static gboolean
485 gst_adder_sink_event (GstPad * pad, GstEvent * event)
486 {
487   GstAdder *adder;
488   gboolean ret;
489
490   adder = GST_ADDER (gst_pad_get_parent (pad));
491
492   GST_DEBUG ("Got %s event on pad %s:%s", GST_EVENT_TYPE_NAME (event),
493       GST_DEBUG_PAD_NAME (pad));
494
495   switch (GST_EVENT_TYPE (event)) {
496     case GST_EVENT_FLUSH_STOP:
497       /* mark a pending new segment. This event is synchronized
498        * with the streaming thread so we can safely update the 
499        * variable without races. It's somewhat weird because we
500        * assume the collectpads forwarded the FLUSH_STOP past us
501        * and downstream (using our source pad, the bastard!).
502        */
503       adder->segment_pending = TRUE;
504       break;
505     default:
506       break;
507   }
508
509   /* now GstCollectPads can take care of the rest, e.g. EOS */
510   ret = adder->collect_event (pad, event);
511
512   gst_object_unref (adder);
513   return ret;
514 }
515
516 static void
517 gst_adder_class_init (GstAdderClass * klass)
518 {
519   GObjectClass *gobject_class;
520   GstElementClass *gstelement_class;
521
522   gobject_class = (GObjectClass *) klass;
523
524   gobject_class->finalize = gst_adder_finalize;
525
526   gstelement_class = (GstElementClass *) klass;
527
528   gst_element_class_add_pad_template (gstelement_class,
529       gst_static_pad_template_get (&gst_adder_src_template));
530   gst_element_class_add_pad_template (gstelement_class,
531       gst_static_pad_template_get (&gst_adder_sink_template));
532   gst_element_class_set_details (gstelement_class, &adder_details);
533
534   parent_class = g_type_class_peek_parent (klass);
535
536   gstelement_class->request_new_pad = gst_adder_request_new_pad;
537   gstelement_class->release_pad = gst_adder_release_pad;
538   gstelement_class->change_state = gst_adder_change_state;
539 }
540
541 static void
542 gst_adder_init (GstAdder * adder)
543 {
544   GstPadTemplate *template;
545
546   template = gst_static_pad_template_get (&gst_adder_src_template);
547   adder->srcpad = gst_pad_new_from_template (template, "src");
548   gst_object_unref (template);
549   gst_pad_set_getcaps_function (adder->srcpad,
550       GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
551   gst_pad_set_setcaps_function (adder->srcpad,
552       GST_DEBUG_FUNCPTR (gst_adder_setcaps));
553   gst_pad_set_query_function (adder->srcpad,
554       GST_DEBUG_FUNCPTR (gst_adder_query));
555   gst_pad_set_event_function (adder->srcpad,
556       GST_DEBUG_FUNCPTR (gst_adder_src_event));
557   gst_element_add_pad (GST_ELEMENT (adder), adder->srcpad);
558
559   adder->format = GST_ADDER_FORMAT_UNSET;
560   adder->padcount = 0;
561   adder->func = NULL;
562
563   /* keep track of the sinkpads requested */
564   adder->collect = gst_collect_pads_new ();
565   gst_collect_pads_set_function (adder->collect,
566       GST_DEBUG_FUNCPTR (gst_adder_collected), adder);
567 }
568
569 static void
570 gst_adder_finalize (GObject * object)
571 {
572   GstAdder *adder = GST_ADDER (object);
573
574   gst_object_unref (adder->collect);
575   adder->collect = NULL;
576
577   G_OBJECT_CLASS (parent_class)->finalize (object);
578 }
579
580 static GstPad *
581 gst_adder_request_new_pad (GstElement * element, GstPadTemplate * templ,
582     const gchar * unused)
583 {
584   gchar *name;
585   GstAdder *adder;
586   GstPad *newpad;
587   gint padcount;
588
589   if (templ->direction != GST_PAD_SINK)
590     goto not_sink;
591
592   adder = GST_ADDER (element);
593
594   /* increment pad counter */
595   padcount = g_atomic_int_exchange_and_add (&adder->padcount, 1);
596
597   name = g_strdup_printf ("sink%d", padcount);
598   newpad = gst_pad_new_from_template (templ, name);
599   GST_DEBUG_OBJECT (adder, "request new pad %s", name);
600   g_free (name);
601
602   gst_pad_set_getcaps_function (newpad,
603       GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
604   gst_pad_set_setcaps_function (newpad, GST_DEBUG_FUNCPTR (gst_adder_setcaps));
605   gst_collect_pads_add_pad (adder->collect, newpad, sizeof (GstCollectData));
606
607   /* FIXME: hacked way to override/extend the event function of
608    * GstCollectPads; because it sets its own event function giving the
609    * element no access to events */
610   adder->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
611   gst_pad_set_event_function (newpad, GST_DEBUG_FUNCPTR (gst_adder_sink_event));
612
613   /* takes ownership of the pad */
614   if (!gst_element_add_pad (GST_ELEMENT (adder), newpad))
615     goto could_not_add;
616
617   return newpad;
618
619   /* errors */
620 not_sink:
621   {
622     g_warning ("gstadder: request new pad that is not a SINK pad\n");
623     return NULL;
624   }
625 could_not_add:
626   {
627     GST_DEBUG_OBJECT (adder, "could not add pad");
628     gst_collect_pads_remove_pad (adder->collect, newpad);
629     gst_object_unref (newpad);
630     return NULL;
631   }
632 }
633
634 static void
635 gst_adder_release_pad (GstElement * element, GstPad * pad)
636 {
637   GstAdder *adder;
638
639   adder = GST_ADDER (element);
640
641   GST_DEBUG_OBJECT (adder, "release pad %s:%s", GST_DEBUG_PAD_NAME (pad));
642
643   gst_collect_pads_remove_pad (adder->collect, pad);
644   gst_element_remove_pad (element, pad);
645 }
646
647 static GstFlowReturn
648 gst_adder_collected (GstCollectPads * pads, gpointer user_data)
649 {
650   /*
651    * combine channels by adding sample values
652    * basic algorithm :
653    * - this function is called when all pads have a buffer
654    * - get available bytes on all pads.
655    * - repeat for each input pad :
656    *   - read available bytes, copy or add to target buffer
657    *   - if there's an EOS event, remove the input channel
658    * - push out the output buffer
659    */
660   GstAdder *adder;
661   guint size;
662   GSList *collected;
663   GstBuffer *outbuf;
664   GstFlowReturn ret;
665   gpointer outbytes;
666
667   adder = GST_ADDER (user_data);
668
669   /* this is fatal */
670   if (G_UNLIKELY (adder->func == NULL))
671     goto not_negotiated;
672
673   outbuf = NULL;
674   outbytes = NULL;
675
676   /* get available bytes for reading, this can be 0 which could mean
677    * empty buffers or EOS, which we will catch when we loop over the
678    * pads. */
679   size = gst_collect_pads_available (pads);
680
681   GST_LOG_OBJECT (adder,
682       "starting to cycle through channels, %d bytes available", size);
683
684   for (collected = pads->data; collected; collected = g_slist_next (collected)) {
685     GstCollectData *data;
686     guint8 *bytes;
687     guint len;
688
689     data = (GstCollectData *) collected->data;
690
691     /* get pointer to copy size bytes */
692     len = gst_collect_pads_read (pads, data, &bytes, size);
693     /* length 0 means EOS or an empty buffer so we still need to flush in
694      * case of an empty buffer. */
695     if (len == 0) {
696       GST_LOG_OBJECT (adder, "channel %p: no bytes available", data);
697       goto next;
698     }
699
700     if (outbuf == NULL) {
701       GST_LOG_OBJECT (adder, "channel %p: making output buffer of %d bytes",
702           data, size);
703
704       /* first buffer, alloc size bytes. FIXME, we can easily subbuffer
705        * and _make_writable. */
706       outbuf = gst_buffer_new_and_alloc (size);
707       outbytes = GST_BUFFER_DATA (outbuf);
708       gst_buffer_set_caps (outbuf, GST_PAD_CAPS (adder->srcpad));
709
710       /* clear if we are only going to fill a partial buffer */
711       if (G_UNLIKELY (size > len))
712         memset (outbytes, 0, size);
713
714       GST_LOG_OBJECT (adder, "channel %p: copying %d bytes from data %p",
715           data, len, bytes);
716
717       /* and copy the data into it */
718       memcpy (outbytes, bytes, len);
719     } else {
720       GST_LOG_OBJECT (adder, "channel %p: mixing %d bytes from data %p",
721           data, len, bytes);
722       /* other buffers, need to add them */
723       adder->func ((gpointer) outbytes, (gpointer) bytes, len);
724     }
725   next:
726     gst_collect_pads_flush (pads, data, len);
727   }
728
729   /* can only happen when no pads to collect or all EOS */
730   if (outbuf == NULL)
731     goto eos;
732
733   /* our timestamping is very simple, just an ever incrementing 
734    * counter, the new segment time will take care of their respective
735    * stream time. */
736   if (adder->segment_pending) {
737     GstEvent *event;
738
739     /* FIXME, use rate/applied_rate as set on all sinkpads.
740      * We could potentially figure out the duration as well using
741      * the current segment positions and the stated stop positions.
742      * Also we just start from stream time 0 which is rather
743      * weird. For non-synchronized mixing, the time should be
744      * the min of the stream times of all received segments,
745      * rationale being that the duration is at least going to
746      * be as long as the earliest stream we start mixing. This
747      * would also be correct for synchronized mixing but then
748      * the later streams would be delayed until the stream times
749      * match.
750      */
751     event = gst_event_new_new_segment_full (FALSE, 1.0,
752         1.0, GST_FORMAT_TIME, adder->timestamp, -1, adder->segment_position);
753
754     gst_pad_push_event (adder->srcpad, event);
755     adder->segment_pending = FALSE;
756     adder->segment_position = 0;
757   }
758
759   /* set timestamps on the output buffer */
760   GST_BUFFER_TIMESTAMP (outbuf) = adder->timestamp;
761   GST_BUFFER_OFFSET (outbuf) = adder->offset;
762
763   /* for the next timestamp, use the sample counter, which will
764    * never accumulate rounding errors */
765   adder->offset += size / adder->bps;
766   adder->timestamp = gst_util_uint64_scale_int (adder->offset,
767       GST_SECOND, adder->rate);
768
769   /* now we can set the duration of the buffer */
770   GST_BUFFER_DURATION (outbuf) = adder->timestamp -
771       GST_BUFFER_TIMESTAMP (outbuf);
772
773   /* send it out */
774   GST_LOG_OBJECT (adder, "pushing outbuf, timestamp %" GST_TIME_FORMAT,
775       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)));
776   ret = gst_pad_push (adder->srcpad, outbuf);
777
778   return ret;
779
780   /* ERRORS */
781 not_negotiated:
782   {
783     GST_ELEMENT_ERROR (adder, STREAM, FORMAT, (NULL),
784         ("Unknown data received, not negotiated"));
785     return GST_FLOW_NOT_NEGOTIATED;
786   }
787 eos:
788   {
789     GST_DEBUG_OBJECT (adder, "no data available, must be EOS");
790     gst_pad_push_event (adder->srcpad, gst_event_new_eos ());
791     return GST_FLOW_UNEXPECTED;
792   }
793 }
794
795 static GstStateChangeReturn
796 gst_adder_change_state (GstElement * element, GstStateChange transition)
797 {
798   GstAdder *adder;
799   GstStateChangeReturn ret;
800
801   adder = GST_ADDER (element);
802
803   switch (transition) {
804     case GST_STATE_CHANGE_NULL_TO_READY:
805       break;
806     case GST_STATE_CHANGE_READY_TO_PAUSED:
807       adder->timestamp = 0;
808       adder->offset = 0;
809       adder->segment_pending = TRUE;
810       adder->segment_position = 0;
811       gst_segment_init (&adder->segment, GST_FORMAT_UNDEFINED);
812       gst_collect_pads_start (adder->collect);
813       break;
814     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
815       break;
816     case GST_STATE_CHANGE_PAUSED_TO_READY:
817       /* need to unblock the collectpads before calling the
818        * parent change_state so that streaming can finish */
819       gst_collect_pads_stop (adder->collect);
820       break;
821     default:
822       break;
823   }
824
825   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
826
827   switch (transition) {
828     default:
829       break;
830   }
831
832   return ret;
833 }
834
835
836 static gboolean
837 plugin_init (GstPlugin * plugin)
838 {
839   if (!gst_element_register (plugin, "adder", GST_RANK_NONE, GST_TYPE_ADDER)) {
840     return FALSE;
841   }
842
843   return TRUE;
844 }
845
846 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
847     GST_VERSION_MINOR,
848     "adder",
849     "Adds multiple streams",
850     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)