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