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