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