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