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