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