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