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