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