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