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