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