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