adder: keep sending newsegments after seeking
[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   GST_LOG_OBJECT (adder, "getting caps on pad %p,%s to %" GST_PTR_FORMAT, pad,
246       GST_PAD_NAME (pad), result);
247
248   return result;
249 }
250
251 /* the first caps we receive on any of the sinkpads will define the caps for all
252  * the other sinkpads because we can only mix streams with the same caps.
253  * */
254 static gboolean
255 gst_adder_setcaps (GstPad * pad, GstCaps * caps)
256 {
257   GstAdder *adder;
258   GList *pads;
259   GstStructure *structure;
260   const char *media_type;
261
262   adder = GST_ADDER (GST_PAD_PARENT (pad));
263
264   GST_LOG_OBJECT (adder, "setting caps on pad %p,%s to %" GST_PTR_FORMAT, pad,
265       GST_PAD_NAME (pad), caps);
266
267   /* FIXME, see if the other pads can accept the format. Also lock the
268    * format on the other pads to this new format. */
269   GST_OBJECT_LOCK (adder);
270   pads = GST_ELEMENT (adder)->pads;
271   while (pads) {
272     GstPad *otherpad = GST_PAD (pads->data);
273
274     if (otherpad != pad) {
275       gst_caps_replace (&GST_PAD_CAPS (otherpad), caps);
276     }
277     pads = g_list_next (pads);
278   }
279   GST_OBJECT_UNLOCK (adder);
280
281   /* parse caps now */
282   structure = gst_caps_get_structure (caps, 0);
283   media_type = gst_structure_get_name (structure);
284   if (strcmp (media_type, "audio/x-raw-int") == 0) {
285     adder->format = GST_ADDER_FORMAT_INT;
286     gst_structure_get_int (structure, "width", &adder->width);
287     gst_structure_get_int (structure, "depth", &adder->depth);
288     gst_structure_get_int (structure, "endianness", &adder->endianness);
289     gst_structure_get_boolean (structure, "signed", &adder->is_signed);
290
291     GST_INFO_OBJECT (pad, "parse_caps sets adder to format int, %d bit",
292         adder->width);
293
294     if (adder->endianness != G_BYTE_ORDER)
295       goto not_supported;
296
297     switch (adder->width) {
298       case 8:
299         adder->func = (adder->is_signed ?
300             (GstAdderFunction) add_int8 : (GstAdderFunction) add_uint8);
301         break;
302       case 16:
303         adder->func = (adder->is_signed ?
304             (GstAdderFunction) add_int16 : (GstAdderFunction) add_uint16);
305         break;
306       case 32:
307         adder->func = (adder->is_signed ?
308             (GstAdderFunction) add_int32 : (GstAdderFunction) add_uint32);
309         break;
310       default:
311         goto not_supported;
312     }
313   } else if (strcmp (media_type, "audio/x-raw-float") == 0) {
314     adder->format = GST_ADDER_FORMAT_FLOAT;
315     gst_structure_get_int (structure, "width", &adder->width);
316     gst_structure_get_int (structure, "endianness", &adder->endianness);
317
318     GST_INFO_OBJECT (pad, "parse_caps sets adder to format float, %d bit",
319         adder->width);
320
321     if (adder->endianness != G_BYTE_ORDER)
322       goto not_supported;
323
324     switch (adder->width) {
325       case 32:
326         adder->func = (GstAdderFunction) add_float32;
327         break;
328       case 64:
329         adder->func = (GstAdderFunction) add_float64;
330         break;
331       default:
332         goto not_supported;
333     }
334   } else {
335     goto not_supported;
336   }
337
338   gst_structure_get_int (structure, "channels", &adder->channels);
339   gst_structure_get_int (structure, "rate", &adder->rate);
340   /* precalc bps */
341   adder->bps = (adder->width / 8) * adder->channels;
342
343   return TRUE;
344
345   /* ERRORS */
346 not_supported:
347   {
348     GST_DEBUG_OBJECT (adder, "unsupported format set as caps");
349     return FALSE;
350   }
351 }
352
353 /* FIXME, the duration query should reflect how long you will produce
354  * data, that is the amount of stream time until you will emit EOS.
355  *
356  * For synchronized mixing this is always the max of all the durations
357  * of upstream since we emit EOS when all of them finished.
358  *
359  * We don't do synchronized mixing so this really depends on where the
360  * streams where punched in and what their relative offsets are against
361  * eachother which we can get from the first timestamps we see.
362  *
363  * When we add a new stream (or remove a stream) the duration might
364  * also become invalid again and we need to post a new DURATION
365  * message to notify this fact to the parent.
366  * For now we take the max of all the upstream elements so the simple
367  * cases work at least somewhat.
368  */
369 static gboolean
370 gst_adder_query_duration (GstAdder * adder, GstQuery * query)
371 {
372   gint64 max;
373   gboolean res;
374   GstFormat format;
375   GstIterator *it;
376   gboolean done;
377
378   /* parse format */
379   gst_query_parse_duration (query, &format, NULL);
380
381   max = -1;
382   res = TRUE;
383   done = FALSE;
384
385   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
386   while (!done) {
387     GstIteratorResult ires;
388
389     gpointer item;
390
391     ires = gst_iterator_next (it, &item);
392     switch (ires) {
393       case GST_ITERATOR_DONE:
394         done = TRUE;
395         break;
396       case GST_ITERATOR_OK:
397       {
398         GstPad *pad = GST_PAD_CAST (item);
399
400         gint64 duration;
401
402         /* ask sink peer for duration */
403         res &= gst_pad_query_peer_duration (pad, &format, &duration);
404         /* take max from all valid return values */
405         if (res) {
406           /* valid unknown length, stop searching */
407           if (duration == -1) {
408             max = duration;
409             done = TRUE;
410           }
411           /* else see if bigger than current max */
412           else if (duration > max)
413             max = duration;
414         }
415         gst_object_unref (pad);
416         break;
417       }
418       case GST_ITERATOR_RESYNC:
419         max = -1;
420         res = TRUE;
421         gst_iterator_resync (it);
422         break;
423       default:
424         res = FALSE;
425         done = TRUE;
426         break;
427     }
428   }
429   gst_iterator_free (it);
430
431   if (res) {
432     /* and store the max */
433     GST_DEBUG_OBJECT (adder, "Total duration in format %s: %"
434         GST_TIME_FORMAT, gst_format_get_name (format), GST_TIME_ARGS (max));
435     gst_query_set_duration (query, format, max);
436   }
437
438   return res;
439 }
440
441 static gboolean
442 gst_adder_query_latency (GstAdder * adder, GstQuery * query)
443 {
444   GstClockTime min, max;
445   gboolean live;
446   gboolean res;
447   GstIterator *it;
448   gboolean done;
449
450   res = TRUE;
451   done = FALSE;
452
453   live = FALSE;
454   min = 0;
455   max = GST_CLOCK_TIME_NONE;
456
457   /* Take maximum of all latency values */
458   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
459   while (!done) {
460     GstIteratorResult ires;
461
462     gpointer item;
463
464     ires = gst_iterator_next (it, &item);
465     switch (ires) {
466       case GST_ITERATOR_DONE:
467         done = TRUE;
468         break;
469       case GST_ITERATOR_OK:
470       {
471         GstPad *pad = GST_PAD_CAST (item);
472         GstQuery *peerquery;
473         GstClockTime min_cur, max_cur;
474         gboolean live_cur;
475
476         peerquery = gst_query_new_latency ();
477
478         /* Ask peer for latency */
479         res &= gst_pad_peer_query (pad, peerquery);
480
481         /* take max from all valid return values */
482         if (res) {
483           gst_query_parse_latency (peerquery, &live_cur, &min_cur, &max_cur);
484
485           if (min_cur > min)
486             min = min_cur;
487
488           if (max_cur != GST_CLOCK_TIME_NONE &&
489               ((max != GST_CLOCK_TIME_NONE && max_cur > max) ||
490                   (max == GST_CLOCK_TIME_NONE)))
491             max = max_cur;
492
493           live = live || live_cur;
494         }
495
496         gst_query_unref (peerquery);
497         gst_object_unref (pad);
498         break;
499       }
500       case GST_ITERATOR_RESYNC:
501         live = FALSE;
502         min = 0;
503         max = GST_CLOCK_TIME_NONE;
504         res = TRUE;
505         gst_iterator_resync (it);
506         break;
507       default:
508         res = FALSE;
509         done = TRUE;
510         break;
511     }
512   }
513   gst_iterator_free (it);
514
515   if (res) {
516     /* store the results */
517     GST_DEBUG_OBJECT (adder, "Calculated total latency: live %s, min %"
518         GST_TIME_FORMAT ", max %" GST_TIME_FORMAT,
519         (live ? "yes" : "no"), GST_TIME_ARGS (min), GST_TIME_ARGS (max));
520     gst_query_set_latency (query, live, min, max);
521   }
522
523   return res;
524 }
525
526 static gboolean
527 gst_adder_query (GstPad * pad, GstQuery * query)
528 {
529   GstAdder *adder = GST_ADDER (gst_pad_get_parent (pad));
530   gboolean res = FALSE;
531
532   switch (GST_QUERY_TYPE (query)) {
533     case GST_QUERY_POSITION:
534     {
535       GstFormat format;
536
537       gst_query_parse_position (query, &format, NULL);
538
539       switch (format) {
540         case GST_FORMAT_TIME:
541           /* FIXME, bring to stream time, might be tricky */
542           gst_query_set_position (query, format, adder->timestamp);
543           res = TRUE;
544           break;
545         case GST_FORMAT_DEFAULT:
546           gst_query_set_position (query, format, adder->offset);
547           res = TRUE;
548           break;
549         default:
550           break;
551       }
552       break;
553     }
554     case GST_QUERY_DURATION:
555       res = gst_adder_query_duration (adder, query);
556       break;
557     case GST_QUERY_LATENCY:
558       res = gst_adder_query_latency (adder, query);
559       break;
560     default:
561       /* FIXME, needs a custom query handler because we have multiple
562        * sinkpads */
563       res = gst_pad_query_default (pad, query);
564       break;
565   }
566
567   gst_object_unref (adder);
568   return res;
569 }
570
571 typedef struct
572 {
573   GstEvent *event;
574   gboolean flush;
575 } EventData;
576
577 static gboolean
578 forward_event_func (GstPad * pad, GValue * ret, EventData * data)
579 {
580   GstEvent *event = data->event;
581
582   gst_event_ref (event);
583   GST_LOG_OBJECT (pad, "About to send event %s", GST_EVENT_TYPE_NAME (event));
584   if (!gst_pad_push_event (pad, event)) {
585     g_value_set_boolean (ret, FALSE);
586     GST_WARNING_OBJECT (pad, "Sending event  %p (%s) failed.",
587         event, GST_EVENT_TYPE_NAME (event));
588     /* quick hack to unflush the pads, ideally we need a way to just unflush
589      * this single collect pad */
590     if (data->flush)
591       gst_pad_send_event (pad, gst_event_new_flush_stop ());
592   } else {
593     GST_LOG_OBJECT (pad, "Sent event  %p (%s).",
594         event, GST_EVENT_TYPE_NAME (event));
595   }
596   gst_object_unref (pad);
597
598   /* continue on other pads, even if one failed */
599   return TRUE;
600 }
601
602 /* forwards the event to all sinkpads, takes ownership of the
603  * event
604  *
605  * Returns: TRUE if the event could be forwarded on all
606  * sinkpads.
607  */
608 static gboolean
609 forward_event (GstAdder * adder, GstEvent * event, gboolean flush)
610 {
611   gboolean ret;
612   GstIterator *it;
613   GstIteratorResult ires;
614   GValue vret = { 0 };
615   EventData data;
616
617   GST_LOG_OBJECT (adder, "Forwarding event %p (%s)", event,
618       GST_EVENT_TYPE_NAME (event));
619
620   ret = TRUE;
621   data.event = event;
622   data.flush = flush;
623
624   g_value_init (&vret, G_TYPE_BOOLEAN);
625   g_value_set_boolean (&vret, TRUE);
626   it = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (adder));
627   while (TRUE) {
628     ires = gst_iterator_fold (it, (GstIteratorFoldFunction) forward_event_func,
629         &vret, &data);
630     switch (ires) {
631       case GST_ITERATOR_RESYNC:
632         GST_WARNING ("resync");
633         gst_iterator_resync (it);
634         g_value_set_boolean (&vret, TRUE);
635         break;
636       case GST_ITERATOR_OK:
637       case GST_ITERATOR_DONE:
638         ret = g_value_get_boolean (&vret);
639         goto done;
640       default:
641         ret = FALSE;
642         goto done;
643     }
644   }
645 done:
646   gst_iterator_free (it);
647   GST_LOG_OBJECT (adder, "Forwarded event %p (%s), ret=%d", event,
648       GST_EVENT_TYPE_NAME (event), ret);
649   gst_event_unref (event);
650
651   return ret;
652 }
653
654 static gboolean
655 gst_adder_src_event (GstPad * pad, GstEvent * event)
656 {
657   GstAdder *adder;
658   gboolean result;
659
660   adder = GST_ADDER (gst_pad_get_parent (pad));
661
662   switch (GST_EVENT_TYPE (event)) {
663     case GST_EVENT_SEEK:
664     {
665       GstSeekFlags flags;
666       GstSeekType curtype;
667       gint64 cur;
668       gboolean flush;
669
670       /* parse the seek parameters */
671       gst_event_parse_seek (event, &adder->segment_rate, NULL, &flags, &curtype,
672           &cur, NULL, NULL);
673
674       flush = (flags & GST_SEEK_FLAG_FLUSH) == GST_SEEK_FLAG_FLUSH;
675
676       /* check if we are flushing */
677       if (flush) {
678         /* make sure we accept nothing anymore and return WRONG_STATE */
679         gst_collect_pads_set_flushing (adder->collect, TRUE);
680
681         /* flushing seek, start flush downstream, the flush will be done
682          * when all pads received a FLUSH_STOP. */
683         gst_pad_push_event (adder->srcpad, gst_event_new_flush_start ());
684       }
685       GST_DEBUG_OBJECT (adder, "handling seek event: %" GST_PTR_FORMAT, event);
686
687       /* now wait for the collected to be finished and mark a new
688        * segment. After we have the lock, no collect function is running and no
689        * new collect function will be called for as long as we're flushing. */
690       GST_OBJECT_LOCK (adder->collect);
691       if (curtype == GST_SEEK_TYPE_SET)
692         adder->segment_position = cur;
693       else
694         adder->segment_position = 0;
695       /* make sure we push a new segment, to inform about new basetime
696        * see FIXME in gst_adder_collected() */
697       adder->segment_pending = TRUE;
698       if (flush) {
699         /* Yes, we need to call _set_flushing again *WHEN* the streaming threads
700          * have stopped so that the cookie gets properly updated. */
701         gst_collect_pads_set_flushing (adder->collect, TRUE);
702       }
703       /* we might have a pending flush_stop event now. This event will either be
704        * sent by an upstream element when it completes the seek or we will push
705        * one in the collected callback ourself */
706       adder->flush_stop_pending = flush;
707       GST_OBJECT_UNLOCK (adder->collect);
708       GST_DEBUG_OBJECT (adder, "forwarding seek event: %" GST_PTR_FORMAT,
709           event);
710
711       result = forward_event (adder, event, flush);
712       if (!result) {
713         /* seek failed. maybe source is a live source. */
714         GST_DEBUG_OBJECT (adder, "seeking failed");
715       }
716       /* FIXME: ideally we would like to send a flush-stop event from here but
717        * collectpads does not have a method that allows us to do that. Instead
718        * we forward all flush-stop events we receive on the sinkpads. We might
719        * be sending too many flush-stop events. */
720       break;
721     }
722     case GST_EVENT_QOS:
723       /* QoS might be tricky */
724       result = FALSE;
725       break;
726     case GST_EVENT_NAVIGATION:
727       /* navigation is rather pointless. */
728       result = FALSE;
729       break;
730     default:
731       /* just forward the rest for now */
732       GST_DEBUG_OBJECT (adder, "forward unhandled event: %s",
733           GST_EVENT_TYPE_NAME (event));
734       result = forward_event (adder, event, FALSE);
735       break;
736   }
737   gst_object_unref (adder);
738
739   return result;
740 }
741
742 static gboolean
743 gst_adder_sink_event (GstPad * pad, GstEvent * event)
744 {
745   GstAdder *adder;
746   gboolean ret;
747
748   adder = GST_ADDER (gst_pad_get_parent (pad));
749
750   GST_DEBUG ("Got %s event on pad %s:%s", GST_EVENT_TYPE_NAME (event),
751       GST_DEBUG_PAD_NAME (pad));
752
753   switch (GST_EVENT_TYPE (event)) {
754     case GST_EVENT_FLUSH_STOP:
755       /* we received a flush-stop. The collect_event function will push the
756        * event past our element. We simply forward all flush-stop events, even
757        * when no flush-stop was pendingk, this is required because collectpads
758        * does not provide an API to handle-but-not-forward the flush-stop.
759        * We unset the pending flush-stop flag so that we don't send anymore
760        * flush-stop from the collect function later.
761        */
762       GST_OBJECT_LOCK (adder->collect);
763       adder->segment_pending = TRUE;
764       adder->flush_stop_pending = FALSE;
765       GST_OBJECT_UNLOCK (adder->collect);
766       break;
767     default:
768       break;
769   }
770
771   /* now GstCollectPads can take care of the rest, e.g. EOS */
772   ret = adder->collect_event (pad, event);
773
774   gst_object_unref (adder);
775   return ret;
776 }
777
778 static void
779 gst_adder_class_init (GstAdderClass * klass)
780 {
781   GObjectClass *gobject_class = (GObjectClass *) klass;
782   GstElementClass *gstelement_class = (GstElementClass *) klass;
783
784   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_adder_finalize);
785
786   gst_element_class_add_pad_template (gstelement_class,
787       gst_static_pad_template_get (&gst_adder_src_template));
788   gst_element_class_add_pad_template (gstelement_class,
789       gst_static_pad_template_get (&gst_adder_sink_template));
790   gst_element_class_set_details_simple (gstelement_class, "Adder",
791       "Generic/Audio",
792       "Add N audio channels together",
793       "Thomas Vander Stichele <thomas at apestaart dot org>");
794
795   parent_class = g_type_class_peek_parent (klass);
796
797   gstelement_class->request_new_pad =
798       GST_DEBUG_FUNCPTR (gst_adder_request_new_pad);
799   gstelement_class->release_pad = GST_DEBUG_FUNCPTR (gst_adder_release_pad);
800   gstelement_class->change_state = GST_DEBUG_FUNCPTR (gst_adder_change_state);
801 }
802
803 static void
804 gst_adder_init (GstAdder * adder)
805 {
806   GstPadTemplate *template;
807
808   template = gst_static_pad_template_get (&gst_adder_src_template);
809   adder->srcpad = gst_pad_new_from_template (template, "src");
810   gst_object_unref (template);
811
812   gst_pad_set_getcaps_function (adder->srcpad,
813       GST_DEBUG_FUNCPTR (gst_pad_proxy_getcaps));
814   gst_pad_set_setcaps_function (adder->srcpad,
815       GST_DEBUG_FUNCPTR (gst_adder_setcaps));
816   gst_pad_set_query_function (adder->srcpad,
817       GST_DEBUG_FUNCPTR (gst_adder_query));
818   gst_pad_set_event_function (adder->srcpad,
819       GST_DEBUG_FUNCPTR (gst_adder_src_event));
820   gst_element_add_pad (GST_ELEMENT (adder), adder->srcpad);
821
822   adder->format = GST_ADDER_FORMAT_UNSET;
823   adder->padcount = 0;
824   adder->func = NULL;
825
826   /* keep track of the sinkpads requested */
827   adder->collect = gst_collect_pads_new ();
828   gst_collect_pads_set_function (adder->collect,
829       GST_DEBUG_FUNCPTR (gst_adder_collected), adder);
830 }
831
832 static void
833 gst_adder_finalize (GObject * object)
834 {
835   GstAdder *adder = GST_ADDER (object);
836
837   gst_object_unref (adder->collect);
838   adder->collect = NULL;
839
840   G_OBJECT_CLASS (parent_class)->finalize (object);
841 }
842
843 static GstPad *
844 gst_adder_request_new_pad (GstElement * element, GstPadTemplate * templ,
845     const gchar * unused)
846 {
847   gchar *name;
848   GstAdder *adder;
849   GstPad *newpad;
850   gint padcount;
851
852   if (templ->direction != GST_PAD_SINK)
853     goto not_sink;
854
855   adder = GST_ADDER (element);
856
857   /* increment pad counter */
858   padcount = g_atomic_int_exchange_and_add (&adder->padcount, 1);
859
860   name = g_strdup_printf ("sink%d", padcount);
861   newpad = gst_pad_new_from_template (templ, name);
862   GST_DEBUG_OBJECT (adder, "request new pad %s", name);
863   g_free (name);
864
865   gst_pad_set_getcaps_function (newpad,
866       GST_DEBUG_FUNCPTR (gst_adder_sink_getcaps));
867   gst_pad_set_setcaps_function (newpad, GST_DEBUG_FUNCPTR (gst_adder_setcaps));
868   gst_collect_pads_add_pad (adder->collect, newpad, sizeof (GstCollectData));
869
870   /* FIXME: hacked way to override/extend the event function of
871    * GstCollectPads; because it sets its own event function giving the
872    * element no access to events */
873   adder->collect_event = (GstPadEventFunction) GST_PAD_EVENTFUNC (newpad);
874   gst_pad_set_event_function (newpad, GST_DEBUG_FUNCPTR (gst_adder_sink_event));
875
876   /* takes ownership of the pad */
877   if (!gst_element_add_pad (GST_ELEMENT (adder), newpad))
878     goto could_not_add;
879
880   return newpad;
881
882   /* errors */
883 not_sink:
884   {
885     g_warning ("gstadder: request new pad that is not a SINK pad\n");
886     return NULL;
887   }
888 could_not_add:
889   {
890     GST_DEBUG_OBJECT (adder, "could not add pad");
891     gst_collect_pads_remove_pad (adder->collect, newpad);
892     gst_object_unref (newpad);
893     return NULL;
894   }
895 }
896
897 static void
898 gst_adder_release_pad (GstElement * element, GstPad * pad)
899 {
900   GstAdder *adder;
901
902   adder = GST_ADDER (element);
903
904   GST_DEBUG_OBJECT (adder, "release pad %s:%s", GST_DEBUG_PAD_NAME (pad));
905
906   gst_collect_pads_remove_pad (adder->collect, pad);
907   gst_element_remove_pad (element, pad);
908 }
909
910 static GstFlowReturn
911 gst_adder_collected (GstCollectPads * pads, gpointer user_data)
912 {
913   /*
914    * combine streams by adding data values
915    * basic algorithm :
916    * - this function is called when all pads have a buffer
917    * - get available bytes on all pads.
918    * - repeat for each input pad :
919    *   - read available bytes, copy or add to target buffer
920    *   - if there's an EOS event, remove the input channel
921    * - push out the output buffer
922    *
923    * todo:
924    * - would be nice to have a mixing mode, where instead of adding we mix
925    *   - for float we could downscale after collect loop
926    *   - for int we need to downscale each input to avoid clipping or
927    *     mix into a temp (float) buffer and scale afterwards as well
928    */
929   GstAdder *adder;
930   GSList *collected;
931   GstFlowReturn ret;
932   GstBuffer *outbuf = NULL;
933   gpointer outdata = NULL;
934   guint outsize;
935   gboolean empty = TRUE;
936
937   adder = GST_ADDER (user_data);
938
939   /* this is fatal */
940   if (G_UNLIKELY (adder->func == NULL))
941     goto not_negotiated;
942
943   if (adder->flush_stop_pending) {
944     gst_pad_push_event (adder->srcpad, gst_event_new_flush_stop ());
945     adder->flush_stop_pending = FALSE;
946   }
947
948   /* get available bytes for reading, this can be 0 which could mean empty
949    * buffers or EOS, which we will catch when we loop over the pads. */
950   outsize = gst_collect_pads_available (pads);
951
952   GST_LOG_OBJECT (adder,
953       "starting to cycle through channels, %d bytes available (bps = %d)",
954       outsize, adder->bps);
955
956   for (collected = pads->data; collected; collected = g_slist_next (collected)) {
957     GstCollectData *collect_data;
958     GstBuffer *inbuf;
959     guint8 *indata;
960     guint insize;
961
962     collect_data = (GstCollectData *) collected->data;
963
964     /* get a subbuffer of size bytes */
965     inbuf = gst_collect_pads_take_buffer (pads, collect_data, outsize);
966     /* NULL means EOS or an empty buffer so we still need to flush in
967      * case of an empty buffer. */
968     if (inbuf == NULL) {
969       GST_LOG_OBJECT (adder, "channel %p: no bytes available", collect_data);
970       continue;
971     }
972
973     indata = GST_BUFFER_DATA (inbuf);
974     insize = GST_BUFFER_SIZE (inbuf);
975
976     if (outbuf == NULL) {
977       GST_LOG_OBJECT (adder, "channel %p: making output buffer of %d bytes",
978           collect_data, outsize);
979
980       /* first buffer, alloc outsize.
981        * FIXME: we can easily subbuffer and _make_writable.
982        * FIXME: only create empty buffer for first non-gap buffer, so that we
983        * only use adder function when really adding
984        */
985       outbuf = gst_buffer_new_and_alloc (outsize);
986       outdata = GST_BUFFER_DATA (outbuf);
987       gst_buffer_set_caps (outbuf, GST_PAD_CAPS (adder->srcpad));
988
989       if (!GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_GAP)) {
990         GST_LOG_OBJECT (adder, "channel %p: copying %d bytes from data %p",
991             collect_data, insize, indata);
992         /* clear if we are only going to fill a partial buffer */
993         if (G_UNLIKELY (outsize > insize))
994           memset ((guint8 *) outdata + insize, 0, outsize - insize);
995         /* and copy the data into it */
996         memcpy (outdata, indata, insize);
997         empty = FALSE;
998       } else {
999         /* clear whole buffer */
1000         GST_LOG_OBJECT (adder, "channel %p: zeroing %d bytes from data %p",
1001             collect_data, insize, indata);
1002         memset (outdata, 0, outsize);
1003       }
1004     } else {
1005       if (!GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_GAP)) {
1006         GST_LOG_OBJECT (adder, "channel %p: mixing %d bytes from data %p",
1007             collect_data, insize, indata);
1008         /* further buffers, need to add them */
1009         adder->func ((gpointer) outdata, (gpointer) indata, insize);
1010         empty = FALSE;
1011       } else {
1012         GST_LOG_OBJECT (adder, "channel %p: skipping %d bytes from data %p",
1013             collect_data, insize, indata);
1014       }
1015     }
1016     gst_buffer_unref (inbuf);
1017   }
1018
1019   /* can only happen when no pads to collect or all EOS */
1020   if (outbuf == NULL)
1021     goto eos;
1022
1023   /* our timestamping is very simple, just an ever incrementing
1024    * counter, the new segment time will take care of their respective
1025    * stream time. */
1026   if (adder->segment_pending) {
1027     GstEvent *event;
1028
1029     /* FIXME, use rate/applied_rate as set on all sinkpads.
1030      * - currently we just set rate as received from last seek-event
1031      * We could potentially figure out the duration as well using
1032      * the current segment positions and the stated stop positions.
1033      * Also we just start from stream time 0 which is rather
1034      * weird. For non-synchronized mixing, the time should be
1035      * the min of the stream times of all received segments,
1036      * rationale being that the duration is at least going to
1037      * be as long as the earliest stream we start mixing. This
1038      * would also be correct for synchronized mixing but then
1039      * the later streams would be delayed until the stream times
1040      * match.
1041      */
1042     event = gst_event_new_new_segment_full (FALSE, adder->segment_rate,
1043         1.0, GST_FORMAT_TIME, adder->timestamp, -1, adder->segment_position);
1044
1045     if (event) {
1046       if (!gst_pad_push_event (adder->srcpad, event)) {
1047         GST_WARNING_OBJECT (adder->srcpad, "Sending event  %p (%s) failed.",
1048             event, GST_EVENT_TYPE_NAME (event));
1049       }
1050       adder->segment_pending = FALSE;
1051       adder->segment_position = 0;
1052     } else {
1053       GST_WARNING_OBJECT (adder->srcpad, "Creating new segment event for "
1054           "start:%" G_GINT64_FORMAT "  pos:%" G_GINT64_FORMAT " failed",
1055           adder->timestamp, adder->segment_position);
1056     }
1057   }
1058
1059   /* set timestamps on the output buffer */
1060   GST_BUFFER_TIMESTAMP (outbuf) = adder->timestamp;
1061   GST_BUFFER_OFFSET (outbuf) = adder->offset;
1062
1063   /* for the next timestamp, use the sample counter, which will
1064    * never accumulate rounding errors */
1065   adder->offset += outsize / adder->bps;
1066   adder->timestamp = gst_util_uint64_scale_int (adder->offset,
1067       GST_SECOND, adder->rate);
1068
1069   /* now we can set the duration of the buffer */
1070   GST_BUFFER_DURATION (outbuf) = adder->timestamp -
1071       GST_BUFFER_TIMESTAMP (outbuf);
1072
1073   /* if we only processed silence, mark output again as silence */
1074   if (empty)
1075     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_GAP);
1076
1077   /* send it out */
1078   GST_LOG_OBJECT (adder, "pushing outbuf, timestamp %" GST_TIME_FORMAT,
1079       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)));
1080   ret = gst_pad_push (adder->srcpad, outbuf);
1081
1082   GST_LOG_OBJECT (adder, "pushed outbuf, result = %s", gst_flow_get_name (ret));
1083
1084   return ret;
1085
1086   /* ERRORS */
1087 not_negotiated:
1088   {
1089     GST_ELEMENT_ERROR (adder, STREAM, FORMAT, (NULL),
1090         ("Unknown data received, not negotiated"));
1091     return GST_FLOW_NOT_NEGOTIATED;
1092   }
1093 eos:
1094   {
1095     GST_DEBUG_OBJECT (adder, "no data available, must be EOS");
1096     gst_pad_push_event (adder->srcpad, gst_event_new_eos ());
1097     return GST_FLOW_UNEXPECTED;
1098   }
1099 }
1100
1101 static GstStateChangeReturn
1102 gst_adder_change_state (GstElement * element, GstStateChange transition)
1103 {
1104   GstAdder *adder;
1105   GstStateChangeReturn ret;
1106
1107   adder = GST_ADDER (element);
1108
1109   switch (transition) {
1110     case GST_STATE_CHANGE_NULL_TO_READY:
1111       break;
1112     case GST_STATE_CHANGE_READY_TO_PAUSED:
1113       adder->timestamp = 0;
1114       adder->offset = 0;
1115       adder->segment_pending = TRUE;
1116       adder->segment_position = 0;
1117       adder->segment_rate = 1.0;
1118       gst_segment_init (&adder->segment, GST_FORMAT_UNDEFINED);
1119       gst_collect_pads_start (adder->collect);
1120       break;
1121     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1122       break;
1123     case GST_STATE_CHANGE_PAUSED_TO_READY:
1124       /* need to unblock the collectpads before calling the
1125        * parent change_state so that streaming can finish */
1126       gst_collect_pads_stop (adder->collect);
1127       break;
1128     default:
1129       break;
1130   }
1131
1132   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1133
1134   switch (transition) {
1135     default:
1136       break;
1137   }
1138
1139   return ret;
1140 }
1141
1142
1143 static gboolean
1144 plugin_init (GstPlugin * plugin)
1145 {
1146   /*oil_init (); */
1147
1148   if (!gst_element_register (plugin, "adder", GST_RANK_NONE, GST_TYPE_ADDER)) {
1149     return FALSE;
1150   }
1151
1152   return TRUE;
1153 }
1154
1155 GST_PLUGIN_DEFINE (GST_VERSION_MAJOR,
1156     GST_VERSION_MINOR,
1157     "adder",
1158     "Adds multiple streams",
1159     plugin_init, VERSION, "LGPL", GST_PACKAGE_NAME, GST_PACKAGE_ORIGIN)