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