626fd3c15edabb155ac958649b7a538f253e1e57
[platform/upstream/gstreamer.git] / plugins / elements / gstinputselector.c
1 /* GStreamer input selector
2  * Copyright (C) 2003 Julien Moutte <julien@moutte.net>
3  * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
4  * Copyright (C) 2005 Jan Schmidt <thaytan@mad.scientist.com>
5  * Copyright (C) 2007 Wim Taymans <wim.taymans@gmail.com>
6  * Copyright (C) 2007 Andy Wingo <wingo@pobox.com>
7  * Copyright (C) 2008 Nokia Corporation. (contact <stefan.kost@nokia.com>)
8  * Copyright (C) 2011 Sebastian Dröge <sebastian.droege@collabora.co.uk>
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public
21  * License along with this library; if not, write to the
22  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23  * Boston, MA 02110-1301, USA.
24  */
25
26 /**
27  * SECTION:element-input-selector
28  * @see_also: #GstOutputSelector
29  *
30  * Direct one out of N input streams to the output pad.
31  *
32  * The input pads are from a GstPad subclass and have additional
33  * properties, which users may find useful, namely:
34  *
35  * <itemizedlist>
36  * <listitem>
37  * "running-time": Running time of stream on pad (#gint64)
38  * </listitem>
39  * <listitem>
40  * "tags": The currently active tags on the pad (#GstTagList, boxed type)
41  * </listitem>
42  * <listitem>
43  * "active": If the pad is currently active (#gboolean)
44  * </listitem>
45  * <listitem>
46  * "always-ok" : Make an inactive pads return #GST_FLOW_OK instead of
47  * #GST_FLOW_NOT_LINKED
48  * </listitem>
49  * </itemizedlist>
50  */
51
52 #ifdef HAVE_CONFIG_H
53 #include "config.h"
54 #endif
55
56 #include <string.h>
57
58 #include "gstinputselector.h"
59
60 #define DEBUG_CACHED_BUFFERS 0
61
62 GST_DEBUG_CATEGORY_STATIC (input_selector_debug);
63 #define GST_CAT_DEFAULT input_selector_debug
64
65 #define GST_TYPE_INPUT_SELECTOR_SYNC_MODE (gst_input_selector_sync_mode_get_type())
66 static GType
67 gst_input_selector_sync_mode_get_type (void)
68 {
69   static GType type = 0;
70   static const GEnumValue data[] = {
71     {GST_INPUT_SELECTOR_SYNC_MODE_ACTIVE_SEGMENT,
72           "Sync using the current active segment",
73         "active-segment"},
74     {GST_INPUT_SELECTOR_SYNC_MODE_CLOCK, "Sync using the clock", "clock"},
75     {0, NULL, NULL},
76   };
77
78   if (!type) {
79     type = g_enum_register_static ("GstInputSelectorSyncMode", data);
80   }
81   return type;
82 }
83
84 #define GST_INPUT_SELECTOR_GET_LOCK(sel) (&((GstInputSelector*)(sel))->lock)
85 #define GST_INPUT_SELECTOR_GET_COND(sel) (&((GstInputSelector*)(sel))->cond)
86 #define GST_INPUT_SELECTOR_LOCK(sel) (g_mutex_lock (GST_INPUT_SELECTOR_GET_LOCK(sel)))
87 #define GST_INPUT_SELECTOR_UNLOCK(sel) (g_mutex_unlock (GST_INPUT_SELECTOR_GET_LOCK(sel)))
88 #define GST_INPUT_SELECTOR_WAIT(sel) (g_cond_wait (GST_INPUT_SELECTOR_GET_COND(sel), \
89                         GST_INPUT_SELECTOR_GET_LOCK(sel)))
90 #define GST_INPUT_SELECTOR_BROADCAST(sel) (g_cond_broadcast (GST_INPUT_SELECTOR_GET_COND(sel)))
91
92 static GstStaticPadTemplate gst_input_selector_sink_factory =
93 GST_STATIC_PAD_TEMPLATE ("sink_%u",
94     GST_PAD_SINK,
95     GST_PAD_REQUEST,
96     GST_STATIC_CAPS_ANY);
97
98 static GstStaticPadTemplate gst_input_selector_src_factory =
99 GST_STATIC_PAD_TEMPLATE ("src",
100     GST_PAD_SRC,
101     GST_PAD_ALWAYS,
102     GST_STATIC_CAPS_ANY);
103
104 enum
105 {
106   PROP_0,
107   PROP_N_PADS,
108   PROP_ACTIVE_PAD,
109   PROP_SYNC_STREAMS,
110   PROP_SYNC_MODE,
111   PROP_CACHE_BUFFERS
112 };
113
114 #define DEFAULT_SYNC_STREAMS TRUE
115 #define DEFAULT_SYNC_MODE GST_INPUT_SELECTOR_SYNC_MODE_ACTIVE_SEGMENT
116 #define DEFAULT_CACHE_BUFFERS FALSE
117 #define DEFAULT_PAD_ALWAYS_OK TRUE
118
119 enum
120 {
121   PROP_PAD_0,
122   PROP_PAD_RUNNING_TIME,
123   PROP_PAD_TAGS,
124   PROP_PAD_ACTIVE,
125   PROP_PAD_ALWAYS_OK
126 };
127
128 static void gst_input_selector_active_pad_changed (GstInputSelector * sel,
129     GParamSpec * pspec, gpointer user_data);
130 static inline gboolean gst_input_selector_is_active_sinkpad (GstInputSelector *
131     sel, GstPad * pad);
132 static GstPad *gst_input_selector_get_active_sinkpad (GstInputSelector * sel);
133 static GstPad *gst_input_selector_get_linked_pad (GstInputSelector * sel,
134     GstPad * pad, gboolean strict);
135
136 #define GST_TYPE_SELECTOR_PAD \
137   (gst_selector_pad_get_type())
138 #define GST_SELECTOR_PAD(obj) \
139   (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_SELECTOR_PAD, GstSelectorPad))
140 #define GST_SELECTOR_PAD_CLASS(klass) \
141   (G_TYPE_CHECK_CLASS_CAST ((klass), GST_TYPE_SELECTOR_PAD, GstSelectorPadClass))
142 #define GST_IS_SELECTOR_PAD(obj) \
143   (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_SELECTOR_PAD))
144 #define GST_IS_SELECTOR_PAD_CLASS(klass) \
145   (G_TYPE_CHECK_CLASS_TYPE ((klass), GST_TYPE_SELECTOR_PAD))
146 #define GST_SELECTOR_PAD_CAST(obj) \
147   ((GstSelectorPad *)(obj))
148
149 typedef struct _GstSelectorPad GstSelectorPad;
150 typedef struct _GstSelectorPadClass GstSelectorPadClass;
151 typedef struct _GstSelectorPadCachedBuffer GstSelectorPadCachedBuffer;
152
153 struct _GstSelectorPad
154 {
155   GstPad parent;
156
157   gboolean pushed;              /* when buffer was pushed downstream since activation */
158   gboolean eos;                 /* when EOS has been received */
159   gboolean eos_sent;            /* when EOS was sent downstream */
160   gboolean discont;             /* after switching we create a discont */
161   gboolean flushing;            /* set after flush-start and before flush-stop */
162   gboolean always_ok;
163   GstTagList *tags;             /* last tags received on the pad */
164
165   GstSegment segment;           /* the current segment on the pad */
166   guint32 segment_seqnum;       /* sequence number of the current segment */
167
168   gboolean events_pending;      /* TRUE if sticky events need to be updated */
169
170   gboolean sending_cached_buffers;
171   GQueue *cached_buffers;
172 };
173
174 struct _GstSelectorPadCachedBuffer
175 {
176   GstBuffer *buffer;
177   GstSegment segment;
178 };
179
180 struct _GstSelectorPadClass
181 {
182   GstPadClass parent;
183 };
184
185 GType gst_selector_pad_get_type (void);
186 static void gst_selector_pad_finalize (GObject * object);
187 static void gst_selector_pad_get_property (GObject * object,
188     guint prop_id, GValue * value, GParamSpec * pspec);
189 static void gst_selector_pad_set_property (GObject * object,
190     guint prop_id, const GValue * value, GParamSpec * pspec);
191
192 static gint64 gst_selector_pad_get_running_time (GstSelectorPad * pad);
193 static void gst_selector_pad_reset (GstSelectorPad * pad);
194 static gboolean gst_selector_pad_event (GstPad * pad, GstObject * parent,
195     GstEvent * event);
196 static gboolean gst_selector_pad_query (GstPad * pad, GstObject * parent,
197     GstQuery * query);
198 static GstIterator *gst_selector_pad_iterate_linked_pads (GstPad * pad,
199     GstObject * parent);
200 static GstFlowReturn gst_selector_pad_chain (GstPad * pad, GstObject * parent,
201     GstBuffer * buf);
202 static void gst_selector_pad_cache_buffer (GstSelectorPad * selpad,
203     GstBuffer * buffer);
204 static void gst_selector_pad_free_cached_buffers (GstSelectorPad * selpad);
205
206 G_DEFINE_TYPE (GstSelectorPad, gst_selector_pad, GST_TYPE_PAD);
207
208 static void
209 gst_selector_pad_class_init (GstSelectorPadClass * klass)
210 {
211   GObjectClass *gobject_class;
212
213   gobject_class = (GObjectClass *) klass;
214
215   gobject_class->finalize = gst_selector_pad_finalize;
216
217   gobject_class->get_property = gst_selector_pad_get_property;
218   gobject_class->set_property = gst_selector_pad_set_property;
219
220   g_object_class_install_property (gobject_class, PROP_PAD_RUNNING_TIME,
221       g_param_spec_int64 ("running-time", "Running time",
222           "Running time of stream on pad", 0, G_MAXINT64, 0,
223           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
224   g_object_class_install_property (gobject_class, PROP_PAD_TAGS,
225       g_param_spec_boxed ("tags", "Tags",
226           "The currently active tags on the pad", GST_TYPE_TAG_LIST,
227           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
228   g_object_class_install_property (gobject_class, PROP_PAD_ACTIVE,
229       g_param_spec_boolean ("active", "Active",
230           "If the pad is currently active", FALSE,
231           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
232   /* FIXME: better property name? */
233   g_object_class_install_property (gobject_class, PROP_PAD_ALWAYS_OK,
234       g_param_spec_boolean ("always-ok", "Always OK",
235           "Make an inactive pad return OK instead of NOT_LINKED",
236           DEFAULT_PAD_ALWAYS_OK, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
237 }
238
239 static void
240 gst_selector_pad_init (GstSelectorPad * pad)
241 {
242   pad->always_ok = DEFAULT_PAD_ALWAYS_OK;
243   gst_selector_pad_reset (pad);
244 }
245
246 static void
247 gst_selector_pad_finalize (GObject * object)
248 {
249   GstSelectorPad *pad;
250
251   pad = GST_SELECTOR_PAD_CAST (object);
252
253   if (pad->tags)
254     gst_tag_list_unref (pad->tags);
255   gst_selector_pad_free_cached_buffers (pad);
256
257   G_OBJECT_CLASS (gst_selector_pad_parent_class)->finalize (object);
258 }
259
260 static void
261 gst_selector_pad_set_property (GObject * object, guint prop_id,
262     const GValue * value, GParamSpec * pspec)
263 {
264   GstSelectorPad *spad = GST_SELECTOR_PAD_CAST (object);
265
266   switch (prop_id) {
267     case PROP_PAD_ALWAYS_OK:
268       GST_OBJECT_LOCK (object);
269       spad->always_ok = g_value_get_boolean (value);
270       GST_OBJECT_UNLOCK (object);
271       break;
272     default:
273       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
274       break;
275   }
276 }
277
278 static void
279 gst_selector_pad_get_property (GObject * object, guint prop_id,
280     GValue * value, GParamSpec * pspec)
281 {
282   GstSelectorPad *spad = GST_SELECTOR_PAD_CAST (object);
283
284   switch (prop_id) {
285     case PROP_PAD_RUNNING_TIME:
286       g_value_set_int64 (value, gst_selector_pad_get_running_time (spad));
287       break;
288     case PROP_PAD_TAGS:
289       GST_OBJECT_LOCK (object);
290       g_value_set_boxed (value, spad->tags);
291       GST_OBJECT_UNLOCK (object);
292       break;
293     case PROP_PAD_ACTIVE:
294     {
295       GstInputSelector *sel;
296
297       sel = GST_INPUT_SELECTOR (gst_pad_get_parent (spad));
298       if (sel) {
299         g_value_set_boolean (value, gst_input_selector_is_active_sinkpad (sel,
300                 GST_PAD_CAST (spad)));
301         gst_object_unref (sel);
302       } else {
303         g_value_set_boolean (value, FALSE);
304       }
305       break;
306     }
307     case PROP_PAD_ALWAYS_OK:
308       GST_OBJECT_LOCK (object);
309       g_value_set_boolean (value, spad->always_ok);
310       GST_OBJECT_UNLOCK (object);
311       break;
312     default:
313       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
314       break;
315   }
316 }
317
318 static gint64
319 gst_selector_pad_get_running_time (GstSelectorPad * pad)
320 {
321   gint64 ret = 0;
322
323   GST_OBJECT_LOCK (pad);
324   if (pad->segment.format == GST_FORMAT_TIME) {
325     ret =
326         gst_segment_to_running_time (&pad->segment, pad->segment.format,
327         pad->segment.position);
328   }
329   GST_OBJECT_UNLOCK (pad);
330
331   GST_DEBUG_OBJECT (pad, "running time: %" GST_TIME_FORMAT
332       " segment: %" GST_SEGMENT_FORMAT, GST_TIME_ARGS (ret), &pad->segment);
333
334   return ret;
335 }
336
337 /* must be called with the SELECTOR_LOCK */
338 static void
339 gst_selector_pad_reset (GstSelectorPad * pad)
340 {
341   GST_OBJECT_LOCK (pad);
342   pad->pushed = FALSE;
343   pad->eos = FALSE;
344   pad->eos_sent = FALSE;
345   pad->events_pending = FALSE;
346   pad->discont = FALSE;
347   pad->flushing = FALSE;
348   gst_segment_init (&pad->segment, GST_FORMAT_UNDEFINED);
349   pad->sending_cached_buffers = FALSE;
350   gst_selector_pad_free_cached_buffers (pad);
351   GST_OBJECT_UNLOCK (pad);
352 }
353
354 static GstSelectorPadCachedBuffer *
355 gst_selector_pad_new_cached_buffer (GstSelectorPad * selpad, GstBuffer * buffer)
356 {
357   GstSelectorPadCachedBuffer *cached_buffer =
358       g_slice_new (GstSelectorPadCachedBuffer);
359   cached_buffer->buffer = buffer;
360   cached_buffer->segment = selpad->segment;
361   return cached_buffer;
362 }
363
364 static void
365 gst_selector_pad_free_cached_buffer (GstSelectorPadCachedBuffer * cached_buffer)
366 {
367   gst_buffer_unref (cached_buffer->buffer);
368   g_slice_free (GstSelectorPadCachedBuffer, cached_buffer);
369 }
370
371 /* must be called with the SELECTOR_LOCK */
372 static void
373 gst_selector_pad_cache_buffer (GstSelectorPad * selpad, GstBuffer * buffer)
374 {
375   if (selpad->segment.format != GST_FORMAT_TIME) {
376     GST_DEBUG_OBJECT (selpad, "Buffer %p with segment not in time format, "
377         "not caching", buffer);
378     return;
379   }
380
381   GST_DEBUG_OBJECT (selpad, "Caching buffer %p", buffer);
382   if (!selpad->cached_buffers)
383     selpad->cached_buffers = g_queue_new ();
384   g_queue_push_tail (selpad->cached_buffers,
385       gst_selector_pad_new_cached_buffer (selpad, buffer));
386 }
387
388 /* must be called with the SELECTOR_LOCK */
389 static void
390 gst_selector_pad_free_cached_buffers (GstSelectorPad * selpad)
391 {
392   if (!selpad->cached_buffers)
393     return;
394
395   GST_DEBUG_OBJECT (selpad, "Freeing cached buffers");
396   g_queue_free_full (selpad->cached_buffers,
397       (GDestroyNotify) gst_selector_pad_free_cached_buffer);
398   selpad->cached_buffers = NULL;
399 }
400
401 /* strictly get the linked pad from the sinkpad. If the pad is active we return
402  * the srcpad else we return NULL */
403 static GstIterator *
404 gst_selector_pad_iterate_linked_pads (GstPad * pad, GstObject * parent)
405 {
406   GstInputSelector *sel;
407   GstPad *otherpad;
408   GstIterator *it = NULL;
409   GValue val = { 0, };
410
411   sel = GST_INPUT_SELECTOR (parent);
412
413   otherpad = gst_input_selector_get_linked_pad (sel, pad, TRUE);
414   if (otherpad) {
415     g_value_init (&val, GST_TYPE_PAD);
416     g_value_set_object (&val, otherpad);
417     it = gst_iterator_new_single (GST_TYPE_PAD, &val);
418     g_value_unset (&val);
419     gst_object_unref (otherpad);
420   }
421
422   return it;
423 }
424
425 static gboolean
426 gst_selector_pad_event (GstPad * pad, GstObject * parent, GstEvent * event)
427 {
428   gboolean res = TRUE;
429   gboolean forward;
430   gboolean new_tags = FALSE;
431   GstInputSelector *sel;
432   GstSelectorPad *selpad;
433   GstPad *prev_active_sinkpad;
434   GstPad *active_sinkpad;
435
436   sel = GST_INPUT_SELECTOR (parent);
437   selpad = GST_SELECTOR_PAD_CAST (pad);
438   GST_DEBUG_OBJECT (selpad, "received event %" GST_PTR_FORMAT, event);
439
440   GST_INPUT_SELECTOR_LOCK (sel);
441   prev_active_sinkpad =
442       sel->active_sinkpad ? gst_object_ref (sel->active_sinkpad) : NULL;
443   active_sinkpad = gst_input_selector_get_active_sinkpad (sel);
444   gst_object_ref (active_sinkpad);
445   GST_INPUT_SELECTOR_UNLOCK (sel);
446
447   if (prev_active_sinkpad != active_sinkpad) {
448     if (prev_active_sinkpad)
449       g_object_notify (G_OBJECT (prev_active_sinkpad), "active");
450     g_object_notify (G_OBJECT (active_sinkpad), "active");
451     g_object_notify (G_OBJECT (sel), "active-pad");
452   }
453   if (prev_active_sinkpad)
454     gst_object_unref (prev_active_sinkpad);
455   gst_object_unref (active_sinkpad);
456
457   GST_INPUT_SELECTOR_LOCK (sel);
458   active_sinkpad = gst_input_selector_get_active_sinkpad (sel);
459
460   /* only forward if we are dealing with the active sinkpad */
461   forward = (pad == active_sinkpad);
462
463   switch (GST_EVENT_TYPE (event)) {
464     case GST_EVENT_STREAM_START:{
465       guint group_id;
466
467       if (!gst_event_parse_group_id (event, &group_id))
468         sel->have_group_id = FALSE;
469       break;
470     }
471     case GST_EVENT_FLUSH_START:
472       /* Unblock the pad if it's waiting */
473       selpad->flushing = TRUE;
474       sel->eos = FALSE;
475       GST_INPUT_SELECTOR_BROADCAST (sel);
476       break;
477     case GST_EVENT_FLUSH_STOP:
478       gst_selector_pad_reset (selpad);
479       break;
480     case GST_EVENT_SEGMENT:
481     {
482       gst_event_copy_segment (event, &selpad->segment);
483       selpad->segment_seqnum = gst_event_get_seqnum (event);
484
485       GST_DEBUG_OBJECT (pad, "configured SEGMENT %" GST_SEGMENT_FORMAT,
486           &selpad->segment);
487       break;
488     }
489     case GST_EVENT_TAG:
490     {
491       GstTagList *tags, *oldtags, *newtags;
492
493       gst_event_parse_tag (event, &tags);
494
495       GST_OBJECT_LOCK (selpad);
496       oldtags = selpad->tags;
497
498       newtags = gst_tag_list_merge (oldtags, tags, GST_TAG_MERGE_REPLACE);
499       selpad->tags = newtags;
500       GST_OBJECT_UNLOCK (selpad);
501
502       if (oldtags)
503         gst_tag_list_unref (oldtags);
504       GST_DEBUG_OBJECT (pad, "received tags %" GST_PTR_FORMAT, newtags);
505
506       new_tags = TRUE;
507       break;
508     }
509     case GST_EVENT_EOS:
510       selpad->eos = TRUE;
511
512       if (!forward) {
513         forward = TRUE;
514         /* Wait until we're the active sink pad or we're flushing */
515         while (!sel->eos && !sel->flushing && !selpad->flushing)
516           GST_INPUT_SELECTOR_WAIT (sel);
517       } else {
518         /* Notify all waiting pads about going EOS now */
519         sel->eos = TRUE;
520         GST_INPUT_SELECTOR_BROADCAST (sel);
521       }
522
523       selpad->eos_sent = TRUE;
524       GST_DEBUG_OBJECT (pad, "received EOS");
525       break;
526     case GST_EVENT_GAP:{
527       GstClockTime ts, dur;
528
529       GST_DEBUG_OBJECT (pad, "Received gap event: %" GST_PTR_FORMAT, event);
530
531       gst_event_parse_gap (event, &ts, &dur);
532       if (GST_CLOCK_TIME_IS_VALID (ts)) {
533         if (GST_CLOCK_TIME_IS_VALID (dur))
534           ts += dur;
535
536         /* update the segment position */
537         GST_OBJECT_LOCK (pad);
538         selpad->segment.position = ts;
539         GST_OBJECT_UNLOCK (pad);
540         if (sel->sync_streams && active_sinkpad == pad)
541           GST_INPUT_SELECTOR_BROADCAST (sel);
542       }
543
544     }
545       break;
546     default:
547       break;
548   }
549   GST_INPUT_SELECTOR_UNLOCK (sel);
550   if (new_tags)
551     g_object_notify (G_OBJECT (selpad), "tags");
552   if (forward) {
553     GST_DEBUG_OBJECT (pad, "forwarding event");
554     res = gst_pad_push_event (sel->srcpad, event);
555   } else {
556     /* If we aren't forwarding the event because the pad is not the
557      * active_sinkpad, then set the flag on the pad
558      * that says a segment needs sending if/when that pad is activated.
559      * For all other cases, we send the event immediately, which makes
560      * sparse streams and other segment updates work correctly downstream.
561      */
562     if (GST_EVENT_IS_STICKY (event))
563       selpad->events_pending = TRUE;
564     gst_event_unref (event);
565   }
566
567   return res;
568 }
569
570 static gboolean
571 gst_selector_pad_query (GstPad * pad, GstObject * parent, GstQuery * query)
572 {
573   gboolean res = FALSE;
574   GstInputSelector *self = (GstInputSelector *) parent;
575
576   switch (GST_QUERY_TYPE (query)) {
577     case GST_QUERY_CAPS:
578       /* always proxy caps query, regardless of active pad or not */
579       res = gst_pad_peer_query (self->srcpad, query);
580       break;
581     case GST_QUERY_ALLOCATION:{
582       GstPad *active_sinkpad;
583       GstInputSelector *sel = GST_INPUT_SELECTOR (parent);
584
585       /* Only do the allocation query for the active sinkpad,
586        * after switching a reconfigure event is sent and upstream
587        * should reconfigure and do a new allocation query
588        */
589       if (GST_PAD_DIRECTION (pad) == GST_PAD_SINK) {
590         GST_INPUT_SELECTOR_LOCK (sel);
591         active_sinkpad = gst_input_selector_get_active_sinkpad (sel);
592         GST_INPUT_SELECTOR_UNLOCK (sel);
593
594         if (pad != active_sinkpad) {
595           res = FALSE;
596           goto done;
597         }
598       }
599     }
600       /* fall through */
601     default:
602       res = gst_pad_query_default (pad, parent, query);
603       break;
604   }
605
606 done:
607   return res;
608 }
609
610 static GstClockTime
611 gst_input_selector_get_clipped_running_time (GstSegment * seg, GstBuffer * buf)
612 {
613   GstClockTime running_time;
614
615   running_time = GST_BUFFER_PTS (buf);
616   /* If possible try to get the running time at the end of the buffer */
617   if (GST_BUFFER_DURATION_IS_VALID (buf))
618     running_time += GST_BUFFER_DURATION (buf);
619   /* Only use the segment to convert to running time if the segment is
620    * in TIME format, otherwise do our best to try to sync */
621   if (GST_CLOCK_TIME_IS_VALID (seg->stop)) {
622     if (running_time > seg->stop) {
623       running_time = seg->stop;
624     }
625   }
626   return gst_segment_to_running_time (seg, GST_FORMAT_TIME, running_time);
627 }
628
629 /* must be called without the SELECTOR_LOCK, will wait until the running time
630  * of the active pad is after this pad or return TRUE when flushing */
631 static gboolean
632 gst_input_selector_wait_running_time (GstInputSelector * sel,
633     GstSelectorPad * selpad, GstBuffer * buf)
634 {
635   GstSegment *seg;
636
637   GST_DEBUG_OBJECT (selpad, "entering wait for buffer %p", buf);
638
639   /* If we have no valid timestamp we can't sync this buffer */
640   if (!GST_BUFFER_PTS_IS_VALID (buf)) {
641     GST_DEBUG_OBJECT (selpad, "leaving wait for buffer with "
642         "invalid timestamp");
643     return FALSE;
644   }
645
646   seg = &selpad->segment;
647
648   /* Wait until
649    *   a) this is the active pad
650    *   b) the pad or the selector is flushing
651    *   c) the buffer running time is before the current running time
652    *      (either active-seg or clock, depending on sync-mode)
653    */
654
655   GST_INPUT_SELECTOR_LOCK (sel);
656   while (TRUE) {
657     GstPad *active_sinkpad;
658     GstSelectorPad *active_selpad;
659     GstClock *clock;
660     gint64 cur_running_time;
661     GstClockTime running_time;
662
663     active_sinkpad = gst_input_selector_get_active_sinkpad (sel);
664     active_selpad = GST_SELECTOR_PAD_CAST (active_sinkpad);
665
666     if (seg->format != GST_FORMAT_TIME) {
667       GST_DEBUG_OBJECT (selpad,
668           "Not waiting because we don't have a TIME segment");
669       GST_INPUT_SELECTOR_UNLOCK (sel);
670       return FALSE;
671     }
672
673     running_time = gst_input_selector_get_clipped_running_time (seg, buf);
674     /* If this is outside the segment don't sync */
675     if (running_time == -1) {
676       GST_DEBUG_OBJECT (selpad,
677           "Not waiting because buffer is outside segment");
678       GST_INPUT_SELECTOR_UNLOCK (sel);
679       return FALSE;
680     }
681
682     cur_running_time = GST_CLOCK_TIME_NONE;
683     if (sel->sync_mode == GST_INPUT_SELECTOR_SYNC_MODE_CLOCK) {
684       clock = gst_element_get_clock (GST_ELEMENT_CAST (sel));
685       if (clock) {
686         GstClockTime base_time;
687
688         cur_running_time = gst_clock_get_time (clock);
689         base_time = gst_element_get_base_time (GST_ELEMENT_CAST (sel));
690         if (base_time <= cur_running_time)
691           cur_running_time -= base_time;
692         else
693           cur_running_time = 0;
694
695         gst_object_unref (clock);
696       }
697     } else {
698       GstSegment *active_seg;
699
700       active_seg = &active_selpad->segment;
701
702       /* If the active segment is configured but not to time format
703        * we can't do any syncing at all */
704       if (active_seg->format != GST_FORMAT_TIME
705           && active_seg->format != GST_FORMAT_UNDEFINED) {
706         GST_DEBUG_OBJECT (selpad,
707             "Not waiting because active segment isn't in TIME format");
708         GST_INPUT_SELECTOR_UNLOCK (sel);
709         return FALSE;
710       }
711
712       /* Get active pad's running time, if no configured segment yet keep at -1 */
713       if (active_seg->format == GST_FORMAT_TIME)
714         cur_running_time = gst_segment_to_running_time (active_seg,
715             GST_FORMAT_TIME, active_seg->position);
716     }
717
718     if (selpad != active_selpad && !sel->eos && !sel->flushing
719         && !selpad->flushing && (cur_running_time == GST_CLOCK_TIME_NONE
720             || running_time >= cur_running_time)) {
721       GST_DEBUG_OBJECT (selpad,
722           "Waiting for active streams to advance. %" GST_TIME_FORMAT " >= %"
723           GST_TIME_FORMAT, GST_TIME_ARGS (running_time),
724           GST_TIME_ARGS (cur_running_time));
725       GST_INPUT_SELECTOR_WAIT (sel);
726     } else {
727       GST_INPUT_SELECTOR_UNLOCK (sel);
728       break;
729     }
730   }
731
732   /* Return TRUE if the selector or the pad is flushing */
733   return (sel->flushing || selpad->flushing);
734 }
735
736 static gboolean
737 forward_sticky_events (GstPad * sinkpad, GstEvent ** event, gpointer user_data)
738 {
739   GstInputSelector *sel = GST_INPUT_SELECTOR (user_data);
740
741   if (GST_EVENT_TYPE (*event) == GST_EVENT_SEGMENT) {
742     GstSegment *seg = &GST_SELECTOR_PAD (sinkpad)->segment;
743     GstEvent *e;
744
745     e = gst_event_new_segment (seg);
746     gst_event_set_seqnum (e, GST_SELECTOR_PAD_CAST (sinkpad)->segment_seqnum);
747
748     gst_pad_push_event (sel->srcpad, e);
749   } else if (GST_EVENT_TYPE (*event) == GST_EVENT_STREAM_START
750       && !sel->have_group_id) {
751     GstEvent *tmp =
752         gst_pad_get_sticky_event (sel->srcpad, GST_EVENT_STREAM_START, 0);
753
754     /* Only push stream-start once if not all our streams have a stream-id */
755     if (!tmp) {
756       gst_pad_push_event (sel->srcpad, gst_event_ref (*event));
757     } else {
758       gst_event_unref (tmp);
759     }
760   } else {
761     gst_pad_push_event (sel->srcpad, gst_event_ref (*event));
762   }
763
764   return TRUE;
765 }
766
767 #if DEBUG_CACHED_BUFFERS
768 static void
769 gst_input_selector_debug_cached_buffers (GstInputSelector * sel)
770 {
771   GList *walk;
772
773   if (gst_debug_category_get_threshold (input_selector_debug) < GST_LEVEL_DEBUG)
774     return;
775
776   for (walk = GST_ELEMENT_CAST (sel)->sinkpads; walk; walk = walk->next) {
777     GstSelectorPad *selpad;
778     GString *timestamps;
779     GList *l;
780
781     selpad = GST_SELECTOR_PAD_CAST (walk->data);
782     if (!selpad->cached_buffers) {
783       GST_DEBUG_OBJECT (selpad, "Cached buffers timestamps: <none>");
784       continue;
785     }
786
787     timestamps = g_string_new ("Cached buffers timestamps:");
788     for (l = selpad->cached_buffers->head; l != NULL; l = l->next) {
789       GstSelectorPadCachedBuffer *cached_buffer = l->data;
790
791       g_string_append_printf (timestamps, " %" GST_TIME_FORMAT,
792           GST_TIME_ARGS (GST_BUFFER_PTS (cached_buffer->buffer)));
793     }
794     GST_DEBUG_OBJECT (selpad, "%s", timestamps->str);
795     g_string_free (timestamps, TRUE);
796   }
797 }
798 #endif
799
800 /* must be called with the SELECTOR_LOCK */
801 static void
802 gst_input_selector_cleanup_old_cached_buffers (GstInputSelector * sel,
803     GstPad * pad)
804 {
805   GstClock *clock;
806   gint64 cur_running_time;
807   GList *walk;
808
809   cur_running_time = GST_CLOCK_TIME_NONE;
810   if (sel->sync_mode == GST_INPUT_SELECTOR_SYNC_MODE_CLOCK) {
811     clock = gst_element_get_clock (GST_ELEMENT_CAST (sel));
812     if (clock) {
813       GstClockTime base_time;
814
815       cur_running_time = gst_clock_get_time (clock);
816       base_time = gst_element_get_base_time (GST_ELEMENT_CAST (sel));
817       if (base_time <= cur_running_time)
818         cur_running_time -= base_time;
819       else
820         cur_running_time = 0;
821
822       gst_object_unref (clock);
823     }
824   } else {
825     GstPad *active_sinkpad;
826     GstSelectorPad *active_selpad;
827     GstSegment *active_seg;
828
829     active_sinkpad = gst_input_selector_get_active_sinkpad (sel);
830     active_selpad = GST_SELECTOR_PAD_CAST (active_sinkpad);
831     active_seg = &active_selpad->segment;
832
833     /* Get active pad's running time, if no configured segment yet keep at -1 */
834     if (active_seg->format == GST_FORMAT_TIME)
835       cur_running_time = gst_segment_to_running_time (active_seg,
836           GST_FORMAT_TIME, active_seg->position);
837   }
838
839   if (!GST_CLOCK_TIME_IS_VALID (cur_running_time))
840     return;
841
842   GST_DEBUG_OBJECT (sel, "Cleaning up old cached buffers");
843   for (walk = GST_ELEMENT_CAST (sel)->sinkpads; walk; walk = g_list_next (walk)) {
844     GstSelectorPad *selpad;
845     GstSegment *seg;
846     GstSelectorPadCachedBuffer *cached_buffer;
847     GSList *maybe_remove;
848     guint queue_position;
849
850     selpad = GST_SELECTOR_PAD_CAST (walk->data);
851     if (!selpad->cached_buffers)
852       continue;
853
854     seg = &selpad->segment;
855
856     maybe_remove = NULL;
857     queue_position = 0;
858     while ((cached_buffer = g_queue_peek_nth (selpad->cached_buffers,
859                 queue_position))) {
860       GstBuffer *buffer = cached_buffer->buffer;
861       GstClockTime running_time;
862       GSList *l;
863
864       /* If we have no valid timestamp we can't sync this buffer */
865       if (!GST_BUFFER_PTS_IS_VALID (buffer)) {
866         maybe_remove = g_slist_append (maybe_remove, cached_buffer);
867         queue_position = g_slist_length (maybe_remove);
868         continue;
869       }
870
871       /* the buffer is still valid if its duration is valid and the
872        * timestamp + duration is >= time, or if its duration is invalid
873        * and the timestamp is >= time */
874       running_time = gst_input_selector_get_clipped_running_time (seg, buffer);
875       GST_DEBUG_OBJECT (selpad,
876           "checking if buffer %p running time=%" GST_TIME_FORMAT
877           " >= stream time=%" GST_TIME_FORMAT, buffer,
878           GST_TIME_ARGS (running_time), GST_TIME_ARGS (cur_running_time));
879       if (running_time >= cur_running_time) {
880         break;
881       }
882
883       GST_DEBUG_OBJECT (selpad, "Removing old cached buffer %p", buffer);
884       g_queue_pop_nth (selpad->cached_buffers, queue_position);
885       gst_selector_pad_free_cached_buffer (cached_buffer);
886
887       for (l = maybe_remove; l != NULL; l = g_slist_next (l)) {
888         /* A buffer after some invalid buffers was removed, it means the invalid buffers
889          * are old, lets also remove them */
890         cached_buffer = l->data;
891         g_queue_remove (selpad->cached_buffers, cached_buffer);
892         gst_selector_pad_free_cached_buffer (cached_buffer);
893       }
894
895       g_slist_free (maybe_remove);
896       maybe_remove = NULL;
897       queue_position = 0;
898     }
899
900     g_slist_free (maybe_remove);
901     maybe_remove = NULL;
902
903     if (g_queue_is_empty (selpad->cached_buffers)) {
904       g_queue_free (selpad->cached_buffers);
905       selpad->cached_buffers = NULL;
906     }
907   }
908
909 #if DEBUG_CACHED_BUFFERS
910   gst_input_selector_debug_cached_buffers (sel);
911 #endif
912 }
913
914 static GstFlowReturn
915 gst_selector_pad_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
916 {
917   GstInputSelector *sel;
918   GstFlowReturn res;
919   GstPad *active_sinkpad;
920   GstPad *prev_active_sinkpad = NULL;
921   GstSelectorPad *selpad;
922
923   sel = GST_INPUT_SELECTOR (parent);
924   selpad = GST_SELECTOR_PAD_CAST (pad);
925
926   GST_DEBUG_OBJECT (selpad,
927       "entering chain for buf %p with timestamp %" GST_TIME_FORMAT, buf,
928       GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
929
930   GST_INPUT_SELECTOR_LOCK (sel);
931
932   if (sel->eos) {
933     GST_INPUT_SELECTOR_UNLOCK (sel);
934     goto eos;
935   }
936
937   if (sel->flushing) {
938     GST_INPUT_SELECTOR_UNLOCK (sel);
939     goto flushing;
940   }
941
942   GST_LOG_OBJECT (pad, "getting active pad");
943
944   prev_active_sinkpad =
945       sel->active_sinkpad ? gst_object_ref (sel->active_sinkpad) : NULL;
946   active_sinkpad = gst_input_selector_get_active_sinkpad (sel);
947
948   /* In sync mode wait until the active pad has advanced
949    * after the running time of the current buffer */
950   if (sel->sync_streams) {
951     /* call chain for each cached buffer if we are not the active pad
952      * or if we are the active pad but didn't push anything yet. */
953     if (active_sinkpad != pad || !selpad->pushed) {
954       /* no need to check for sel->cache_buffers as selpad->cached_buffers
955        * will only be valid if cache_buffers is TRUE */
956       if (selpad->cached_buffers && !selpad->sending_cached_buffers) {
957         GstSelectorPadCachedBuffer *cached_buffer;
958         GstSegment saved_segment;
959
960         saved_segment = selpad->segment;
961
962         selpad->sending_cached_buffers = TRUE;
963         while (!sel->eos && !sel->flushing && !selpad->flushing &&
964             (cached_buffer = g_queue_pop_head (selpad->cached_buffers))) {
965           GST_DEBUG_OBJECT (pad, "Cached buffers found, "
966               "invoking chain for cached buffer %p", cached_buffer->buffer);
967
968           selpad->segment = cached_buffer->segment;
969           selpad->events_pending = TRUE;
970           GST_INPUT_SELECTOR_UNLOCK (sel);
971           gst_selector_pad_chain (pad, parent, cached_buffer->buffer);
972           GST_INPUT_SELECTOR_LOCK (sel);
973
974           /* we may have cleaned up the queue in the meantime because of
975            * old buffers */
976           if (!selpad->cached_buffers) {
977             break;
978           }
979         }
980         selpad->sending_cached_buffers = FALSE;
981
982         /* all cached buffers sent, restore segment for current buffer */
983         selpad->segment = saved_segment;
984         selpad->events_pending = TRUE;
985
986         /* Might have changed while calling chain for cached buffers */
987         active_sinkpad = gst_input_selector_get_active_sinkpad (sel);
988       }
989     }
990
991     if (active_sinkpad != pad) {
992       GST_INPUT_SELECTOR_UNLOCK (sel);
993       if (gst_input_selector_wait_running_time (sel, selpad, buf))
994         goto flushing;
995       GST_INPUT_SELECTOR_LOCK (sel);
996     }
997
998     /* Might have changed while waiting */
999     active_sinkpad = gst_input_selector_get_active_sinkpad (sel);
1000   }
1001
1002   if (sel->eos) {
1003     GST_INPUT_SELECTOR_UNLOCK (sel);
1004     goto eos;
1005   }
1006
1007   /* update the segment on the srcpad */
1008   if (GST_BUFFER_PTS_IS_VALID (buf)) {
1009     GstClockTime start_time = GST_BUFFER_PTS (buf);
1010
1011     GST_LOG_OBJECT (pad, "received start time %" GST_TIME_FORMAT,
1012         GST_TIME_ARGS (start_time));
1013     if (GST_BUFFER_DURATION_IS_VALID (buf))
1014       GST_LOG_OBJECT (pad, "received end time %" GST_TIME_FORMAT,
1015           GST_TIME_ARGS (start_time + GST_BUFFER_DURATION (buf)));
1016
1017     GST_OBJECT_LOCK (pad);
1018     selpad->segment.position = start_time;
1019     GST_OBJECT_UNLOCK (pad);
1020   }
1021
1022   /* Ignore buffers from pads except the selected one */
1023   if (pad != active_sinkpad)
1024     goto ignore;
1025
1026   /* Tell all non-active pads that we advanced the running time */
1027   if (sel->sync_streams)
1028     GST_INPUT_SELECTOR_BROADCAST (sel);
1029
1030   GST_INPUT_SELECTOR_UNLOCK (sel);
1031
1032   if (prev_active_sinkpad != active_sinkpad) {
1033     if (prev_active_sinkpad)
1034       g_object_notify (G_OBJECT (prev_active_sinkpad), "active");
1035     g_object_notify (G_OBJECT (active_sinkpad), "active");
1036     g_object_notify (G_OBJECT (sel), "active-pad");
1037   }
1038
1039   /* if we have a pending events, push them now */
1040   if (G_UNLIKELY (prev_active_sinkpad != active_sinkpad
1041           || selpad->events_pending)) {
1042     gst_pad_sticky_events_foreach (GST_PAD_CAST (selpad), forward_sticky_events,
1043         sel);
1044     selpad->events_pending = FALSE;
1045   }
1046
1047   if (prev_active_sinkpad) {
1048     gst_object_unref (prev_active_sinkpad);
1049     prev_active_sinkpad = NULL;
1050   }
1051
1052   if (selpad->discont) {
1053     buf = gst_buffer_make_writable (buf);
1054
1055     GST_DEBUG_OBJECT (pad, "Marking discont buffer %p", buf);
1056     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1057     selpad->discont = FALSE;
1058   }
1059
1060   /* forward */
1061   GST_LOG_OBJECT (pad, "Forwarding buffer %p with timestamp %" GST_TIME_FORMAT,
1062       buf, GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
1063
1064   /* Only make the buffer read-only when necessary */
1065   if (sel->sync_streams && sel->cache_buffers)
1066     buf = gst_buffer_ref (buf);
1067   res = gst_pad_push (sel->srcpad, buf);
1068   GST_LOG_OBJECT (pad, "Buffer %p forwarded result=%d", buf, res);
1069
1070   GST_INPUT_SELECTOR_LOCK (sel);
1071
1072   if (sel->sync_streams && sel->cache_buffers) {
1073     /* Might have changed while pushing */
1074     active_sinkpad = gst_input_selector_get_active_sinkpad (sel);
1075     /* only set pad to pushed if we are still the active pad */
1076     if (active_sinkpad == pad)
1077       selpad->pushed = TRUE;
1078
1079     /* cache buffer as we may need it again if we change pads */
1080     gst_selector_pad_cache_buffer (selpad, buf);
1081     gst_input_selector_cleanup_old_cached_buffers (sel, pad);
1082   } else {
1083     selpad->pushed = TRUE;
1084   }
1085   GST_INPUT_SELECTOR_UNLOCK (sel);
1086
1087 done:
1088
1089   if (prev_active_sinkpad)
1090     gst_object_unref (prev_active_sinkpad);
1091   prev_active_sinkpad = NULL;
1092
1093   return res;
1094
1095   /* dropped buffers */
1096 ignore:
1097   {
1098     gboolean active_pad_pushed = GST_SELECTOR_PAD_CAST (active_sinkpad)->pushed;
1099
1100     GST_DEBUG_OBJECT (pad, "Pad not active, discard buffer %p", buf);
1101     /* when we drop a buffer, we're creating a discont on this pad */
1102     selpad->discont = TRUE;
1103     GST_INPUT_SELECTOR_UNLOCK (sel);
1104     gst_buffer_unref (buf);
1105
1106     /* figure out what to return upstream */
1107     GST_OBJECT_LOCK (selpad);
1108     if (selpad->always_ok || !active_pad_pushed)
1109       res = GST_FLOW_OK;
1110     else
1111       res = GST_FLOW_NOT_LINKED;
1112     GST_OBJECT_UNLOCK (selpad);
1113
1114     goto done;
1115   }
1116 flushing:
1117   {
1118     GST_DEBUG_OBJECT (pad, "We are flushing, discard buffer %p", buf);
1119     gst_buffer_unref (buf);
1120     res = GST_FLOW_FLUSHING;
1121     goto done;
1122   }
1123 eos:
1124   {
1125     GST_DEBUG_OBJECT (pad, "We are eos, discard buffer %p", buf);
1126     gst_buffer_unref (buf);
1127     res = GST_FLOW_EOS;
1128     goto done;
1129   }
1130 }
1131
1132 static void gst_input_selector_dispose (GObject * object);
1133 static void gst_input_selector_finalize (GObject * object);
1134
1135 static void gst_input_selector_set_property (GObject * object,
1136     guint prop_id, const GValue * value, GParamSpec * pspec);
1137 static void gst_input_selector_get_property (GObject * object,
1138     guint prop_id, GValue * value, GParamSpec * pspec);
1139
1140 static GstPad *gst_input_selector_request_new_pad (GstElement * element,
1141     GstPadTemplate * templ, const gchar * unused, const GstCaps * caps);
1142 static void gst_input_selector_release_pad (GstElement * element, GstPad * pad);
1143
1144 static GstStateChangeReturn gst_input_selector_change_state (GstElement *
1145     element, GstStateChange transition);
1146
1147 static gboolean gst_input_selector_event (GstPad * pad, GstObject * parent,
1148     GstEvent * event);
1149
1150 #define _do_init \
1151     GST_DEBUG_CATEGORY_INIT (input_selector_debug, \
1152         "input-selector", 0, "An input stream selector element");
1153 #define gst_input_selector_parent_class parent_class
1154 G_DEFINE_TYPE_WITH_CODE (GstInputSelector, gst_input_selector, GST_TYPE_ELEMENT,
1155     _do_init);
1156
1157 static void
1158 gst_input_selector_class_init (GstInputSelectorClass * klass)
1159 {
1160   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1161   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1162
1163   gobject_class->dispose = gst_input_selector_dispose;
1164   gobject_class->finalize = gst_input_selector_finalize;
1165
1166   gobject_class->set_property = gst_input_selector_set_property;
1167   gobject_class->get_property = gst_input_selector_get_property;
1168
1169   g_object_class_install_property (gobject_class, PROP_N_PADS,
1170       g_param_spec_uint ("n-pads", "Number of Pads",
1171           "The number of sink pads", 0, G_MAXUINT, 0,
1172           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1173
1174   g_object_class_install_property (gobject_class, PROP_ACTIVE_PAD,
1175       g_param_spec_object ("active-pad", "Active pad",
1176           "The currently active sink pad", GST_TYPE_PAD,
1177           G_PARAM_READWRITE | GST_PARAM_MUTABLE_PLAYING |
1178           G_PARAM_STATIC_STRINGS));
1179
1180   /**
1181    * GstInputSelector:sync-streams
1182    *
1183    * If set to %TRUE all inactive streams will be synced to the
1184    * running time of the active stream or to the current clock.
1185    *
1186    * To make sure no buffers are dropped by input-selector
1187    * that might be needed when switching the active pad,
1188    * sync-mode should be set to "clock" and cache-buffers to TRUE.
1189    */
1190   g_object_class_install_property (gobject_class, PROP_SYNC_STREAMS,
1191       g_param_spec_boolean ("sync-streams", "Sync Streams",
1192           "Synchronize inactive streams to the running time of the active "
1193           "stream or to the current clock",
1194           DEFAULT_SYNC_STREAMS,
1195           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
1196           GST_PARAM_MUTABLE_READY));
1197
1198   /**
1199    * GstInputSelector:sync-mode
1200    *
1201    * Select how input-selector will sync buffers when in sync-streams mode.
1202    *
1203    * Note that when using the "active-segment" mode, the "active-segment" may
1204    * be ahead of current clock time when switching the active pad, as the current
1205    * active pad may have pushed more buffers than what was displayed/consumed,
1206    * which may cause delays and some missing buffers.
1207    */
1208   g_object_class_install_property (gobject_class, PROP_SYNC_MODE,
1209       g_param_spec_enum ("sync-mode", "Sync mode",
1210           "Behavior in sync-streams mode", GST_TYPE_INPUT_SELECTOR_SYNC_MODE,
1211           DEFAULT_SYNC_MODE,
1212           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
1213           GST_PARAM_MUTABLE_READY));
1214
1215   /**
1216    * GstInputSelector:cache-buffers
1217    *
1218    * If set to %TRUE and GstInputSelector:sync-streams is also set to %TRUE,
1219    * the active pad will cache the buffers still considered valid (after current
1220    * running time, see sync-mode) to avoid missing frames if/when the pad is
1221    * reactivated.
1222    *
1223    * The active pad may push more buffers than what is currently displayed/consumed
1224    * and when changing pads those buffers will be discarded and the only way to
1225    * reactivate that pad without loosing the already consumed buffers is to enable cache.
1226    */
1227   g_object_class_install_property (gobject_class, PROP_CACHE_BUFFERS,
1228       g_param_spec_boolean ("cache-buffers", "Cache Buffers",
1229           "Cache buffers for active-pad",
1230           DEFAULT_CACHE_BUFFERS,
1231           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS |
1232           GST_PARAM_MUTABLE_READY));
1233
1234   gst_element_class_set_static_metadata (gstelement_class, "Input selector",
1235       "Generic", "N-to-1 input stream selector",
1236       "Julien Moutte <julien@moutte.net>, "
1237       "Jan Schmidt <thaytan@mad.scientist.com>, "
1238       "Wim Taymans <wim.taymans@gmail.com>");
1239   gst_element_class_add_pad_template (gstelement_class,
1240       gst_static_pad_template_get (&gst_input_selector_sink_factory));
1241   gst_element_class_add_pad_template (gstelement_class,
1242       gst_static_pad_template_get (&gst_input_selector_src_factory));
1243
1244   gstelement_class->request_new_pad = gst_input_selector_request_new_pad;
1245   gstelement_class->release_pad = gst_input_selector_release_pad;
1246   gstelement_class->change_state = gst_input_selector_change_state;
1247 }
1248
1249 static void
1250 gst_input_selector_init (GstInputSelector * sel)
1251 {
1252   sel->srcpad = gst_pad_new ("src", GST_PAD_SRC);
1253   gst_pad_set_iterate_internal_links_function (sel->srcpad,
1254       GST_DEBUG_FUNCPTR (gst_selector_pad_iterate_linked_pads));
1255   gst_pad_set_event_function (sel->srcpad,
1256       GST_DEBUG_FUNCPTR (gst_input_selector_event));
1257   GST_OBJECT_FLAG_SET (sel->srcpad, GST_PAD_FLAG_PROXY_CAPS);
1258   gst_element_add_pad (GST_ELEMENT (sel), sel->srcpad);
1259   /* sinkpad management */
1260   sel->active_sinkpad = NULL;
1261   sel->padcount = 0;
1262   sel->sync_streams = DEFAULT_SYNC_STREAMS;
1263   sel->have_group_id = TRUE;
1264
1265   g_mutex_init (&sel->lock);
1266   g_cond_init (&sel->cond);
1267   sel->eos = FALSE;
1268
1269   /* lets give a change for downstream to do something on
1270    * active-pad change before we start pushing new buffers */
1271   g_signal_connect_data (sel, "notify::active-pad",
1272       (GCallback) gst_input_selector_active_pad_changed, NULL,
1273       NULL, G_CONNECT_AFTER);
1274 }
1275
1276 static void
1277 gst_input_selector_dispose (GObject * object)
1278 {
1279   GstInputSelector *sel = GST_INPUT_SELECTOR (object);
1280
1281   if (sel->active_sinkpad) {
1282     gst_object_unref (sel->active_sinkpad);
1283     sel->active_sinkpad = NULL;
1284   }
1285   G_OBJECT_CLASS (parent_class)->dispose (object);
1286 }
1287
1288 static void
1289 gst_input_selector_finalize (GObject * object)
1290 {
1291   GstInputSelector *sel = GST_INPUT_SELECTOR (object);
1292
1293   g_mutex_clear (&sel->lock);
1294   g_cond_clear (&sel->cond);
1295
1296   G_OBJECT_CLASS (parent_class)->finalize (object);
1297 }
1298
1299 /* this function must be called with the SELECTOR_LOCK. It returns TRUE when the
1300  * active pad changed. */
1301 static gboolean
1302 gst_input_selector_set_active_pad (GstInputSelector * self, GstPad * pad)
1303 {
1304   GstSelectorPad *old, *new;
1305   GstPad **active_pad_p;
1306
1307   if (pad == self->active_sinkpad)
1308     return FALSE;
1309
1310   old = GST_SELECTOR_PAD_CAST (self->active_sinkpad);
1311   new = GST_SELECTOR_PAD_CAST (pad);
1312
1313   GST_DEBUG_OBJECT (self, "setting active pad to %s:%s",
1314       GST_DEBUG_PAD_NAME (new));
1315
1316   if (old)
1317     old->pushed = FALSE;
1318   if (new)
1319     new->pushed = FALSE;
1320
1321   /* Send a new SEGMENT event on the new pad next */
1322   if (old != new && new)
1323     new->events_pending = TRUE;
1324
1325   active_pad_p = &self->active_sinkpad;
1326   gst_object_replace ((GstObject **) active_pad_p, GST_OBJECT_CAST (pad));
1327
1328   if (old && old != new)
1329     gst_pad_push_event (GST_PAD_CAST (old), gst_event_new_reconfigure ());
1330   if (new)
1331     gst_pad_push_event (GST_PAD_CAST (new), gst_event_new_reconfigure ());
1332
1333   GST_DEBUG_OBJECT (self, "New active pad is %" GST_PTR_FORMAT,
1334       self->active_sinkpad);
1335
1336   if (old != new && new && new->eos && !new->eos_sent) {
1337     self->eos = TRUE;
1338     GST_INPUT_SELECTOR_BROADCAST (self);
1339   }
1340
1341   return TRUE;
1342 }
1343
1344 static void
1345 gst_input_selector_set_property (GObject * object, guint prop_id,
1346     const GValue * value, GParamSpec * pspec)
1347 {
1348   GstInputSelector *sel = GST_INPUT_SELECTOR (object);
1349
1350   switch (prop_id) {
1351     case PROP_ACTIVE_PAD:
1352     {
1353       GstPad *pad;
1354
1355       pad = g_value_get_object (value);
1356
1357       GST_INPUT_SELECTOR_LOCK (sel);
1358
1359 #if DEBUG_CACHED_BUFFERS
1360       gst_input_selector_debug_cached_buffers (sel);
1361 #endif
1362
1363       gst_input_selector_set_active_pad (sel, pad);
1364
1365 #if DEBUG_CACHED_BUFFERS
1366       gst_input_selector_debug_cached_buffers (sel);
1367 #endif
1368
1369       GST_INPUT_SELECTOR_UNLOCK (sel);
1370       break;
1371     }
1372     case PROP_SYNC_STREAMS:
1373       GST_INPUT_SELECTOR_LOCK (sel);
1374       sel->sync_streams = g_value_get_boolean (value);
1375       GST_INPUT_SELECTOR_UNLOCK (sel);
1376       break;
1377     case PROP_SYNC_MODE:
1378       GST_INPUT_SELECTOR_LOCK (sel);
1379       sel->sync_mode = g_value_get_enum (value);
1380       GST_INPUT_SELECTOR_UNLOCK (sel);
1381       break;
1382     case PROP_CACHE_BUFFERS:
1383       GST_INPUT_SELECTOR_LOCK (object);
1384       sel->cache_buffers = g_value_get_boolean (value);
1385       GST_INPUT_SELECTOR_UNLOCK (object);
1386       break;
1387     default:
1388       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1389       break;
1390   }
1391 }
1392
1393 static void
1394 gst_input_selector_active_pad_changed (GstInputSelector * sel,
1395     GParamSpec * pspec, gpointer user_data)
1396 {
1397   /* Wake up all non-active pads in sync mode, they might be
1398    * the active pad now */
1399   if (sel->sync_streams)
1400     GST_INPUT_SELECTOR_BROADCAST (sel);
1401 }
1402
1403 static void
1404 gst_input_selector_get_property (GObject * object, guint prop_id,
1405     GValue * value, GParamSpec * pspec)
1406 {
1407   GstInputSelector *sel = GST_INPUT_SELECTOR (object);
1408
1409   switch (prop_id) {
1410     case PROP_N_PADS:
1411       GST_INPUT_SELECTOR_LOCK (object);
1412       g_value_set_uint (value, sel->n_pads);
1413       GST_INPUT_SELECTOR_UNLOCK (object);
1414       break;
1415     case PROP_ACTIVE_PAD:
1416       GST_INPUT_SELECTOR_LOCK (object);
1417       g_value_set_object (value, sel->active_sinkpad);
1418       GST_INPUT_SELECTOR_UNLOCK (object);
1419       break;
1420     case PROP_SYNC_STREAMS:
1421       GST_INPUT_SELECTOR_LOCK (object);
1422       g_value_set_boolean (value, sel->sync_streams);
1423       GST_INPUT_SELECTOR_UNLOCK (object);
1424       break;
1425     case PROP_SYNC_MODE:
1426       GST_INPUT_SELECTOR_LOCK (object);
1427       g_value_set_enum (value, sel->sync_mode);
1428       GST_INPUT_SELECTOR_UNLOCK (object);
1429       break;
1430     case PROP_CACHE_BUFFERS:
1431       GST_INPUT_SELECTOR_LOCK (object);
1432       g_value_set_boolean (value, sel->cache_buffers);
1433       GST_INPUT_SELECTOR_UNLOCK (object);
1434       break;
1435     default:
1436       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1437       break;
1438   }
1439 }
1440
1441 static GstPad *
1442 gst_input_selector_get_linked_pad (GstInputSelector * sel, GstPad * pad,
1443     gboolean strict)
1444 {
1445   GstPad *otherpad = NULL;
1446
1447   GST_INPUT_SELECTOR_LOCK (sel);
1448   if (pad == sel->srcpad)
1449     otherpad = sel->active_sinkpad;
1450   else if (pad == sel->active_sinkpad || !strict)
1451     otherpad = sel->srcpad;
1452   if (otherpad)
1453     gst_object_ref (otherpad);
1454   GST_INPUT_SELECTOR_UNLOCK (sel);
1455
1456   return otherpad;
1457 }
1458
1459 static gboolean
1460 gst_input_selector_event (GstPad * pad, GstObject * parent, GstEvent * event)
1461 {
1462   GstInputSelector *sel;
1463   gboolean result = FALSE;
1464   GstIterator *iter;
1465   gboolean done = FALSE;
1466   GValue item = { 0, };
1467   GstPad *eventpad;
1468   GList *pushed_pads = NULL;
1469
1470   sel = GST_INPUT_SELECTOR (parent);
1471   /* Send upstream events to all sinkpads */
1472   iter = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (sel));
1473
1474   /* This is now essentially a copy of gst_pad_event_default_dispatch
1475    * with a different iterator */
1476   while (!done) {
1477     switch (gst_iterator_next (iter, &item)) {
1478       case GST_ITERATOR_OK:
1479         eventpad = g_value_get_object (&item);
1480
1481         /* if already pushed,  skip */
1482         if (g_list_find (pushed_pads, eventpad)) {
1483           g_value_reset (&item);
1484           break;
1485         }
1486
1487         gst_event_ref (event);
1488         result |= gst_pad_push_event (eventpad, event);
1489
1490         g_value_reset (&item);
1491         break;
1492       case GST_ITERATOR_RESYNC:
1493         /* We don't reset the result here because we don't push the event
1494          * again on pads that got the event already and because we need
1495          * to consider the result of the previous pushes */
1496         gst_iterator_resync (iter);
1497         break;
1498       case GST_ITERATOR_ERROR:
1499         GST_ERROR_OBJECT (pad, "Could not iterate over sinkpads");
1500         done = TRUE;
1501         break;
1502       case GST_ITERATOR_DONE:
1503         done = TRUE;
1504         break;
1505     }
1506   }
1507   g_value_unset (&item);
1508   gst_iterator_free (iter);
1509
1510   g_list_free (pushed_pads);
1511
1512   gst_event_unref (event);
1513
1514   return result;
1515 }
1516
1517 /* check if the pad is the active sinkpad */
1518 static inline gboolean
1519 gst_input_selector_is_active_sinkpad (GstInputSelector * sel, GstPad * pad)
1520 {
1521   gboolean res;
1522
1523   GST_INPUT_SELECTOR_LOCK (sel);
1524   res = (pad == sel->active_sinkpad);
1525   GST_INPUT_SELECTOR_UNLOCK (sel);
1526
1527   return res;
1528 }
1529
1530 /* Get or create the active sinkpad, must be called with SELECTOR_LOCK */
1531 static GstPad *
1532 gst_input_selector_get_active_sinkpad (GstInputSelector * sel)
1533 {
1534   GstPad *active_sinkpad;
1535
1536   active_sinkpad = sel->active_sinkpad;
1537   if (active_sinkpad == NULL) {
1538     GValue item = G_VALUE_INIT;
1539     GstIterator *iter = gst_element_iterate_sink_pads (GST_ELEMENT_CAST (sel));
1540     GstIteratorResult ires;
1541
1542     while ((ires = gst_iterator_next (iter, &item)) == GST_ITERATOR_RESYNC)
1543       gst_iterator_resync (iter);
1544     if (ires == GST_ITERATOR_OK) {
1545       /* If no pad is currently selected, we return the first usable pad to
1546        * guarantee consistency */
1547
1548       active_sinkpad = sel->active_sinkpad = g_value_dup_object (&item);
1549       g_value_reset (&item);
1550       GST_DEBUG_OBJECT (sel, "Activating pad %s:%s",
1551           GST_DEBUG_PAD_NAME (active_sinkpad));
1552     } else
1553       GST_WARNING_OBJECT (sel, "Couldn't find a default sink pad");
1554     gst_iterator_free (iter);
1555   }
1556
1557   return active_sinkpad;
1558 }
1559
1560 static GstPad *
1561 gst_input_selector_request_new_pad (GstElement * element,
1562     GstPadTemplate * templ, const gchar * unused, const GstCaps * caps)
1563 {
1564   GstInputSelector *sel;
1565   gchar *name = NULL;
1566   GstPad *sinkpad = NULL;
1567
1568   g_return_val_if_fail (templ->direction == GST_PAD_SINK, NULL);
1569
1570   sel = GST_INPUT_SELECTOR (element);
1571
1572   GST_INPUT_SELECTOR_LOCK (sel);
1573
1574   GST_LOG_OBJECT (sel, "Creating new pad sink_%u", sel->padcount);
1575   name = g_strdup_printf ("sink_%u", sel->padcount++);
1576   sinkpad = g_object_new (GST_TYPE_SELECTOR_PAD,
1577       "name", name, "direction", templ->direction, "template", templ, NULL);
1578   g_free (name);
1579
1580   sel->n_pads++;
1581
1582   gst_pad_set_event_function (sinkpad,
1583       GST_DEBUG_FUNCPTR (gst_selector_pad_event));
1584   gst_pad_set_query_function (sinkpad,
1585       GST_DEBUG_FUNCPTR (gst_selector_pad_query));
1586   gst_pad_set_chain_function (sinkpad,
1587       GST_DEBUG_FUNCPTR (gst_selector_pad_chain));
1588   gst_pad_set_iterate_internal_links_function (sinkpad,
1589       GST_DEBUG_FUNCPTR (gst_selector_pad_iterate_linked_pads));
1590
1591   GST_OBJECT_FLAG_SET (sinkpad, GST_PAD_FLAG_PROXY_CAPS);
1592   GST_OBJECT_FLAG_SET (sinkpad, GST_PAD_FLAG_PROXY_ALLOCATION);
1593   gst_pad_set_active (sinkpad, TRUE);
1594   gst_element_add_pad (GST_ELEMENT (sel), sinkpad);
1595   GST_INPUT_SELECTOR_UNLOCK (sel);
1596
1597   return sinkpad;
1598 }
1599
1600 static void
1601 gst_input_selector_release_pad (GstElement * element, GstPad * pad)
1602 {
1603   GstInputSelector *sel;
1604
1605   sel = GST_INPUT_SELECTOR (element);
1606   GST_LOG_OBJECT (sel, "Releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1607
1608   GST_INPUT_SELECTOR_LOCK (sel);
1609   /* if the pad was the active pad, makes us select a new one */
1610   if (sel->active_sinkpad == pad) {
1611     GST_DEBUG_OBJECT (sel, "Deactivating pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1612     gst_object_unref (sel->active_sinkpad);
1613     sel->active_sinkpad = NULL;
1614   }
1615   sel->n_pads--;
1616   GST_INPUT_SELECTOR_UNLOCK (sel);
1617
1618   gst_pad_set_active (pad, FALSE);
1619   gst_element_remove_pad (GST_ELEMENT (sel), pad);
1620 }
1621
1622 static void
1623 gst_input_selector_reset (GstInputSelector * sel)
1624 {
1625   GList *walk;
1626
1627   GST_INPUT_SELECTOR_LOCK (sel);
1628   /* clear active pad */
1629   if (sel->active_sinkpad) {
1630     gst_object_unref (sel->active_sinkpad);
1631     sel->active_sinkpad = NULL;
1632   }
1633   /* reset each of our sinkpads state */
1634   for (walk = GST_ELEMENT_CAST (sel)->sinkpads; walk; walk = g_list_next (walk)) {
1635     GstSelectorPad *selpad = GST_SELECTOR_PAD_CAST (walk->data);
1636
1637     gst_selector_pad_reset (selpad);
1638
1639     if (selpad->tags) {
1640       gst_tag_list_unref (selpad->tags);
1641       selpad->tags = NULL;
1642     }
1643   }
1644   sel->have_group_id = TRUE;
1645   GST_INPUT_SELECTOR_UNLOCK (sel);
1646 }
1647
1648 static GstStateChangeReturn
1649 gst_input_selector_change_state (GstElement * element,
1650     GstStateChange transition)
1651 {
1652   GstInputSelector *self = GST_INPUT_SELECTOR (element);
1653   GstStateChangeReturn result;
1654
1655   switch (transition) {
1656     case GST_STATE_CHANGE_READY_TO_PAUSED:
1657       GST_INPUT_SELECTOR_LOCK (self);
1658       self->eos = FALSE;
1659       self->flushing = FALSE;
1660       GST_INPUT_SELECTOR_UNLOCK (self);
1661       break;
1662     case GST_STATE_CHANGE_PAUSED_TO_READY:
1663       /* first unlock before we call the parent state change function, which
1664        * tries to acquire the stream lock when going to ready. */
1665       GST_INPUT_SELECTOR_LOCK (self);
1666       self->eos = TRUE;
1667       self->flushing = TRUE;
1668       GST_INPUT_SELECTOR_BROADCAST (self);
1669       GST_INPUT_SELECTOR_UNLOCK (self);
1670       break;
1671     default:
1672       break;
1673   }
1674
1675   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1676
1677   switch (transition) {
1678     case GST_STATE_CHANGE_PAUSED_TO_READY:
1679       gst_input_selector_reset (self);
1680       break;
1681     default:
1682       break;
1683   }
1684
1685   return result;
1686 }