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