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