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