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