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