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