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