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