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