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