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