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