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