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