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