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