inputselector: Only wait until the active pad's running time is reached if the active...
[platform/upstream/gstreamer.git] / plugins / elements / gstinputselector.c
1 /* GStreamer input selector
2  * Copyright (C) 2003 Julien Moutte <julien@moutte.net>
3  * Copyright (C) 2005 Ronald S. Bultje <rbultje@ronald.bitfreak.net>
4  * Copyright (C) 2005 Jan Schmidt <thaytan@mad.scientist.com>
5  * Copyright (C) 2007 Wim Taymans <wim.taymans@gmail.com>
6  * Copyright (C) 2007 Andy Wingo <wingo@pobox.com>
7  * Copyright (C) 2008 Nokia Corporation. (contact <stefan.kost@nokia.com>)
8  * Copyright (C) 2011 Sebastian Dröge <sebastian.droege@collabora.co.uk>
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Library General Public
12  * License as published by the Free Software Foundation; either
13  * version 2 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Library General Public License for more details.
19  *
20  * You should have received a copy of the GNU Library General Public
21  * License along with this library; if not, write to the
22  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23  * Boston, MA 02111-1307, USA.
24  */
25
26 /**
27  * SECTION:element-input-selector
28  * @see_also: #GstOutputSelector
29  *
30  * Direct one out of N input streams to the output pad.
31  *
32  * The input pads are from a GstPad subclass and have additional
33  * properties, which users may find useful, namely:
34  *
35  * <itemizedlist>
36  * <listitem>
37  * "running-time": Running time of stream on pad (#gint64)
38  * </listitem>
39  * <listitem>
40  * "tags": The currently active tags on the pad (#GstTagList, boxed type)
41  * </listitem>
42  * <listitem>
43  * "active": If the pad is currently active (#gboolean)
44  * </listitem>
45  * <listitem>
46  * "always-ok" : Make an inactive pads return #GST_FLOW_OK instead of
47  * #GST_FLOW_NOT_LINKED
48  * </listitem>
49  * </itemizedlist>
50  *
51  * Since: 0.10.32
52  */
53
54 #ifdef HAVE_CONFIG_H
55 #include "config.h"
56 #endif
57
58 #include <string.h>
59
60 #include "gstinputselector.h"
61
62 #include "gst/glib-compat-private.h"
63
64 GST_DEBUG_CATEGORY_STATIC (input_selector_debug);
65 #define GST_CAT_DEFAULT input_selector_debug
66
67 #if GLIB_CHECK_VERSION(2, 26, 0)
68 #define NOTIFY_MUTEX_LOCK()
69 #define NOTIFY_MUTEX_UNLOCK()
70 #else
71 static GStaticRecMutex notify_mutex = G_STATIC_REC_MUTEX_INIT;
72 #define NOTIFY_MUTEX_LOCK() g_static_rec_mutex_lock (&notify_mutex)
73 #define NOTIFY_MUTEX_UNLOCK() g_static_rec_mutex_unlock (&notify_mutex)
74 #endif
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%d",
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 };
103
104 #define DEFAULT_SYNC_STREAMS FALSE
105
106 #define DEFAULT_PAD_ALWAYS_OK TRUE
107
108 enum
109 {
110   PROP_PAD_0,
111   PROP_PAD_RUNNING_TIME,
112   PROP_PAD_TAGS,
113   PROP_PAD_ACTIVE,
114   PROP_PAD_ALWAYS_OK
115 };
116
117 enum
118 {
119   /* methods */
120   SIGNAL_BLOCK,
121   SIGNAL_SWITCH,
122   LAST_SIGNAL
123 };
124 static guint gst_input_selector_signals[LAST_SIGNAL] = { 0 };
125
126 static inline gboolean gst_input_selector_is_active_sinkpad (GstInputSelector *
127     sel, GstPad * pad);
128 static GstPad *gst_input_selector_activate_sinkpad (GstInputSelector * sel,
129     GstPad * pad);
130 static GstPad *gst_input_selector_get_linked_pad (GstInputSelector * sel,
131     GstPad * pad, gboolean strict);
132
133 #define GST_TYPE_SELECTOR_PAD \
134   (gst_selector_pad_get_type())
135 #define GST_SELECTOR_PAD(obj) \
136   (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_SELECTOR_PAD, GstSelectorPad))
137 #define GST_SELECTOR_PAD_CLASS(klass) \
138   (G_TYPE_CHECK_CLASS_CAST ((klass), GST_TYPE_SELECTOR_PAD, GstSelectorPadClass))
139 #define GST_IS_SELECTOR_PAD(obj) \
140   (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GST_TYPE_SELECTOR_PAD))
141 #define GST_IS_SELECTOR_PAD_CLASS(klass) \
142   (G_TYPE_CHECK_CLASS_TYPE ((klass), GST_TYPE_SELECTOR_PAD))
143 #define GST_SELECTOR_PAD_CAST(obj) \
144   ((GstSelectorPad *)(obj))
145
146 typedef struct _GstSelectorPad GstSelectorPad;
147 typedef struct _GstSelectorPadClass GstSelectorPadClass;
148
149 struct _GstSelectorPad
150 {
151   GstPad parent;
152
153   gboolean active;              /* when buffer have passed the pad */
154   gboolean pushed;              /* when buffer was pushed downstream since activation */
155   gboolean eos;                 /* when EOS has been received */
156   gboolean eos_sent;            /* when EOS was sent downstream */
157   gboolean discont;             /* after switching we create a discont */
158   gboolean flushing;            /* set after flush-start and before flush-stop */
159   gboolean always_ok;
160   GstSegment segment;           /* the current segment on the pad */
161   GstTagList *tags;             /* last tags received on the pad */
162
163   gboolean segment_pending;
164 };
165
166 struct _GstSelectorPadClass
167 {
168   GstPadClass parent;
169 };
170
171 static void gst_selector_pad_class_init (GstSelectorPadClass * klass);
172 static void gst_selector_pad_init (GstSelectorPad * pad);
173 static void gst_selector_pad_finalize (GObject * object);
174 static void gst_selector_pad_get_property (GObject * object,
175     guint prop_id, GValue * value, GParamSpec * pspec);
176 static void gst_selector_pad_set_property (GObject * object,
177     guint prop_id, const GValue * value, GParamSpec * pspec);
178
179 static GstPadClass *selector_pad_parent_class = NULL;
180
181 static gint64 gst_selector_pad_get_running_time (GstSelectorPad * pad);
182 static void gst_selector_pad_reset (GstSelectorPad * pad);
183 static gboolean gst_selector_pad_event (GstPad * pad, GstEvent * event);
184 static GstCaps *gst_selector_pad_getcaps (GstPad * pad);
185 static gboolean gst_selector_pad_acceptcaps (GstPad * pad, GstCaps * caps);
186 static GstIterator *gst_selector_pad_iterate_linked_pads (GstPad * pad);
187 static GstFlowReturn gst_selector_pad_chain (GstPad * pad, GstBuffer * buf);
188 static GstFlowReturn gst_selector_pad_bufferalloc (GstPad * pad,
189     guint64 offset, guint size, GstCaps * caps, GstBuffer ** buf);
190
191 static GType
192 gst_selector_pad_get_type (void)
193 {
194   static volatile gsize selector_pad_type = 0;
195   static const GTypeInfo selector_pad_info = {
196     sizeof (GstSelectorPadClass),
197     NULL,
198     NULL,
199     (GClassInitFunc) gst_selector_pad_class_init,
200     NULL,
201     NULL,
202     sizeof (GstSelectorPad),
203     0,
204     (GInstanceInitFunc) gst_selector_pad_init,
205   };
206
207   if (g_once_init_enter (&selector_pad_type)) {
208     GType tmp = g_type_register_static (GST_TYPE_PAD, "GstSelectorPad",
209         &selector_pad_info, 0);
210     g_once_init_leave (&selector_pad_type, tmp);
211   }
212
213   return (GType) selector_pad_type;
214 }
215
216 static void
217 gst_selector_pad_class_init (GstSelectorPadClass * klass)
218 {
219   GObjectClass *gobject_class;
220
221   gobject_class = (GObjectClass *) klass;
222
223   selector_pad_parent_class = g_type_class_peek_parent (klass);
224
225   gobject_class->finalize = gst_selector_pad_finalize;
226
227   gobject_class->get_property = gst_selector_pad_get_property;
228   gobject_class->set_property = gst_selector_pad_set_property;
229
230   g_object_class_install_property (gobject_class, PROP_PAD_RUNNING_TIME,
231       g_param_spec_int64 ("running-time", "Running time",
232           "Running time of stream on pad", 0, G_MAXINT64, 0,
233           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
234   g_object_class_install_property (gobject_class, PROP_PAD_TAGS,
235       g_param_spec_boxed ("tags", "Tags",
236           "The currently active tags on the pad", GST_TYPE_TAG_LIST,
237           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
238   g_object_class_install_property (gobject_class, PROP_PAD_ACTIVE,
239       g_param_spec_boolean ("active", "Active",
240           "If the pad is currently active", FALSE,
241           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
242   /* FIXME: better property name? */
243   g_object_class_install_property (gobject_class, PROP_PAD_ALWAYS_OK,
244       g_param_spec_boolean ("always-ok", "Always OK",
245           "Make an inactive pad return OK instead of NOT_LINKED",
246           DEFAULT_PAD_ALWAYS_OK, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
247 }
248
249 static void
250 gst_selector_pad_init (GstSelectorPad * pad)
251 {
252   pad->always_ok = DEFAULT_PAD_ALWAYS_OK;
253   gst_selector_pad_reset (pad);
254 }
255
256 static void
257 gst_selector_pad_finalize (GObject * object)
258 {
259   GstSelectorPad *pad;
260
261   pad = GST_SELECTOR_PAD_CAST (object);
262
263   if (pad->tags)
264     gst_tag_list_free (pad->tags);
265
266   G_OBJECT_CLASS (selector_pad_parent_class)->finalize (object);
267 }
268
269 static void
270 gst_selector_pad_set_property (GObject * object, guint prop_id,
271     const GValue * value, GParamSpec * pspec)
272 {
273   GstSelectorPad *spad = GST_SELECTOR_PAD_CAST (object);
274
275   switch (prop_id) {
276     case PROP_PAD_ALWAYS_OK:
277       GST_OBJECT_LOCK (object);
278       spad->always_ok = g_value_get_boolean (value);
279       GST_OBJECT_UNLOCK (object);
280       break;
281     default:
282       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
283       break;
284   }
285 }
286
287 static void
288 gst_selector_pad_get_property (GObject * object, guint prop_id,
289     GValue * value, GParamSpec * pspec)
290 {
291   GstSelectorPad *spad = GST_SELECTOR_PAD_CAST (object);
292
293   switch (prop_id) {
294     case PROP_PAD_RUNNING_TIME:
295       g_value_set_int64 (value, gst_selector_pad_get_running_time (spad));
296       break;
297     case PROP_PAD_TAGS:
298       GST_OBJECT_LOCK (object);
299       g_value_set_boxed (value, spad->tags);
300       GST_OBJECT_UNLOCK (object);
301       break;
302     case PROP_PAD_ACTIVE:
303     {
304       GstInputSelector *sel;
305
306       sel = GST_INPUT_SELECTOR (gst_pad_get_parent (spad));
307       g_value_set_boolean (value, gst_input_selector_is_active_sinkpad (sel,
308               GST_PAD_CAST (spad)));
309       gst_object_unref (sel);
310       break;
311     }
312     case PROP_PAD_ALWAYS_OK:
313       GST_OBJECT_LOCK (object);
314       g_value_set_boolean (value, spad->always_ok);
315       GST_OBJECT_UNLOCK (object);
316       break;
317     default:
318       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
319       break;
320   }
321 }
322
323 static gint64
324 gst_selector_pad_get_running_time (GstSelectorPad * pad)
325 {
326   gint64 ret = 0;
327
328   GST_OBJECT_LOCK (pad);
329   if (pad->active) {
330     gint64 last_stop = pad->segment.last_stop;
331
332     if (last_stop >= 0)
333       ret = gst_segment_to_running_time (&pad->segment, GST_FORMAT_TIME,
334           last_stop);
335   }
336   GST_OBJECT_UNLOCK (pad);
337
338   GST_DEBUG_OBJECT (pad, "running time: %" GST_TIME_FORMAT,
339       GST_TIME_ARGS (ret));
340
341   return ret;
342 }
343
344 static void
345 gst_selector_pad_reset (GstSelectorPad * pad)
346 {
347   GST_OBJECT_LOCK (pad);
348   pad->active = FALSE;
349   pad->pushed = FALSE;
350   pad->eos = FALSE;
351   pad->eos_sent = FALSE;
352   pad->segment_pending = FALSE;
353   pad->discont = FALSE;
354   pad->flushing = FALSE;
355   gst_segment_init (&pad->segment, GST_FORMAT_UNDEFINED);
356   GST_OBJECT_UNLOCK (pad);
357 }
358
359 /* strictly get the linked pad from the sinkpad. If the pad is active we return
360  * the srcpad else we return NULL */
361 static GstIterator *
362 gst_selector_pad_iterate_linked_pads (GstPad * pad)
363 {
364   GstInputSelector *sel;
365   GstPad *otherpad;
366   GstIterator *it;
367
368   sel = GST_INPUT_SELECTOR (gst_pad_get_parent (pad));
369   if (G_UNLIKELY (sel == NULL))
370     return NULL;
371
372   otherpad = gst_input_selector_get_linked_pad (sel, pad, TRUE);
373   it = gst_iterator_new_single (GST_TYPE_PAD, otherpad,
374       (GstCopyFunction) gst_object_ref, (GFreeFunc) gst_object_unref);
375
376   if (otherpad)
377     gst_object_unref (otherpad);
378   gst_object_unref (sel);
379
380   return it;
381 }
382
383 static gboolean
384 gst_selector_pad_event (GstPad * pad, GstEvent * event)
385 {
386   gboolean res = TRUE;
387   gboolean forward;
388   GstInputSelector *sel;
389   GstSelectorPad *selpad;
390   GstPad *prev_active_sinkpad;
391   GstPad *active_sinkpad;
392
393   sel = GST_INPUT_SELECTOR (gst_pad_get_parent (pad));
394   if (G_UNLIKELY (sel == NULL)) {
395     gst_event_unref (event);
396     return FALSE;
397   }
398   selpad = GST_SELECTOR_PAD_CAST (pad);
399
400   GST_INPUT_SELECTOR_LOCK (sel);
401   prev_active_sinkpad = sel->active_sinkpad;
402   active_sinkpad = gst_input_selector_activate_sinkpad (sel, pad);
403
404   /* only forward if we are dealing with the active sinkpad */
405   forward = (pad == active_sinkpad);
406   GST_INPUT_SELECTOR_UNLOCK (sel);
407
408   if (prev_active_sinkpad != active_sinkpad && pad == active_sinkpad) {
409     NOTIFY_MUTEX_LOCK ();
410     g_object_notify (G_OBJECT (sel), "active-pad");
411     NOTIFY_MUTEX_UNLOCK ();
412   }
413
414   switch (GST_EVENT_TYPE (event)) {
415     case GST_EVENT_FLUSH_START:
416       /* Unblock the pad if it's waiting */
417       GST_INPUT_SELECTOR_LOCK (sel);
418       selpad->flushing = TRUE;
419       GST_INPUT_SELECTOR_BROADCAST (sel);
420       GST_INPUT_SELECTOR_UNLOCK (sel);
421       break;
422     case GST_EVENT_FLUSH_STOP:
423       GST_INPUT_SELECTOR_LOCK (sel);
424       gst_selector_pad_reset (selpad);
425       sel->pending_close = FALSE;
426       GST_INPUT_SELECTOR_UNLOCK (sel);
427       break;
428     case GST_EVENT_NEWSEGMENT:
429     {
430       gboolean update;
431       GstFormat format;
432       gdouble rate, arate;
433       gint64 start, stop, time;
434
435       gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
436           &start, &stop, &time);
437
438       GST_DEBUG_OBJECT (pad,
439           "configured NEWSEGMENT update %d, rate %lf, applied rate %lf, "
440           "format %d, "
441           "%" G_GINT64_FORMAT " -- %" G_GINT64_FORMAT ", time %"
442           G_GINT64_FORMAT, update, rate, arate, format, start, stop, time);
443
444       GST_INPUT_SELECTOR_LOCK (sel);
445       GST_OBJECT_LOCK (selpad);
446       gst_segment_set_newsegment_full (&selpad->segment, update,
447           rate, arate, format, start, stop, time);
448       GST_OBJECT_UNLOCK (selpad);
449
450       /* If we aren't forwarding the event because the pad is not the
451        * active_sinkpad, then set the flag on the pad
452        * that says a segment needs sending if/when that pad is activated.
453        * For all other cases, we send the event immediately, which makes
454        * sparse streams and other segment updates work correctly downstream.
455        */
456       if (!forward)
457         selpad->segment_pending = TRUE;
458
459       GST_INPUT_SELECTOR_UNLOCK (sel);
460       break;
461     }
462     case GST_EVENT_TAG:
463     {
464       GstTagList *tags, *oldtags, *newtags;
465
466       gst_event_parse_tag (event, &tags);
467
468       GST_OBJECT_LOCK (selpad);
469       oldtags = selpad->tags;
470
471       newtags = gst_tag_list_merge (oldtags, tags, GST_TAG_MERGE_REPLACE);
472       selpad->tags = newtags;
473       if (oldtags)
474         gst_tag_list_free (oldtags);
475       GST_DEBUG_OBJECT (pad, "received tags %" GST_PTR_FORMAT, newtags);
476       GST_OBJECT_UNLOCK (selpad);
477
478       g_object_notify (G_OBJECT (selpad), "tags");
479       break;
480     }
481     case GST_EVENT_EOS:
482       selpad->eos = TRUE;
483
484       if (forward) {
485         selpad->eos_sent = TRUE;
486       } else {
487         GstSelectorPad *tmp;
488
489         /* If the active sinkpad is in EOS state but EOS
490          * was not sent downstream this means that the pad
491          * got EOS before it was set as active pad and that
492          * the previously active pad got EOS after it was
493          * active
494          */
495         GST_INPUT_SELECTOR_LOCK (sel);
496         active_sinkpad = gst_input_selector_activate_sinkpad (sel, pad);
497         tmp = GST_SELECTOR_PAD (active_sinkpad);
498         forward = (tmp->eos && !tmp->eos_sent);
499         tmp->eos_sent = TRUE;
500         GST_INPUT_SELECTOR_UNLOCK (sel);
501       }
502       GST_DEBUG_OBJECT (pad, "received EOS");
503       break;
504     default:
505       break;
506   }
507   if (forward) {
508     GST_DEBUG_OBJECT (pad, "forwarding event");
509     res = gst_pad_push_event (sel->srcpad, event);
510   } else
511     gst_event_unref (event);
512
513   gst_object_unref (sel);
514
515   return res;
516 }
517
518 static GstCaps *
519 gst_selector_pad_getcaps (GstPad * pad)
520 {
521   GstInputSelector *sel;
522   GstCaps *caps;
523
524   sel = GST_INPUT_SELECTOR (gst_pad_get_parent (pad));
525   if (G_UNLIKELY (sel == NULL))
526     return gst_caps_new_any ();
527
528   GST_DEBUG_OBJECT (sel, "Getting caps of srcpad peer");
529   caps = gst_pad_peer_get_caps_reffed (sel->srcpad);
530   if (caps == NULL)
531     caps = gst_caps_new_any ();
532
533   gst_object_unref (sel);
534
535   return caps;
536 }
537
538 static gboolean
539 gst_selector_pad_acceptcaps (GstPad * pad, GstCaps * caps)
540 {
541   GstInputSelector *sel;
542   gboolean res;
543
544   sel = GST_INPUT_SELECTOR (gst_pad_get_parent (pad));
545   if (G_UNLIKELY (sel == NULL))
546     return FALSE;
547
548   GST_DEBUG_OBJECT (sel, "Checking acceptcaps of srcpad peer");
549   res = gst_pad_peer_accept_caps (sel->srcpad, caps);
550   gst_object_unref (sel);
551
552   return res;
553 }
554
555 static GstFlowReturn
556 gst_selector_pad_bufferalloc (GstPad * pad, guint64 offset,
557     guint size, GstCaps * caps, GstBuffer ** buf)
558 {
559   GstInputSelector *sel;
560   GstFlowReturn result;
561   GstPad *active_sinkpad;
562   GstPad *prev_active_sinkpad;
563   GstSelectorPad *selpad;
564
565   sel = GST_INPUT_SELECTOR (gst_pad_get_parent (pad));
566   if (G_UNLIKELY (sel == NULL))
567     return GST_FLOW_WRONG_STATE;
568
569   selpad = GST_SELECTOR_PAD_CAST (pad);
570
571   GST_LOG_OBJECT (pad, "received alloc");
572
573   GST_INPUT_SELECTOR_LOCK (sel);
574   prev_active_sinkpad = sel->active_sinkpad;
575   active_sinkpad = gst_input_selector_activate_sinkpad (sel, pad);
576
577   if (pad != active_sinkpad)
578     goto not_active;
579
580   GST_INPUT_SELECTOR_UNLOCK (sel);
581
582   if (prev_active_sinkpad != active_sinkpad && pad == active_sinkpad) {
583     NOTIFY_MUTEX_LOCK ();
584     g_object_notify (G_OBJECT (sel), "active-pad");
585     NOTIFY_MUTEX_UNLOCK ();
586   }
587
588   result = gst_pad_alloc_buffer (sel->srcpad, offset, size, caps, buf);
589
590 done:
591   gst_object_unref (sel);
592
593   return result;
594
595   /* ERRORS */
596 not_active:
597   {
598     gboolean active_pad_pushed = GST_SELECTOR_PAD_CAST (active_sinkpad)->pushed;
599
600     GST_INPUT_SELECTOR_UNLOCK (sel);
601
602     /* unselected pad, perform fallback alloc or return unlinked when
603      * asked */
604     GST_OBJECT_LOCK (selpad);
605     if (selpad->always_ok || !active_pad_pushed) {
606       GST_DEBUG_OBJECT (pad, "Not selected, performing fallback allocation");
607       *buf = NULL;
608       result = GST_FLOW_OK;
609     } else {
610       GST_DEBUG_OBJECT (pad, "Not selected, return NOT_LINKED");
611       result = GST_FLOW_NOT_LINKED;
612     }
613     GST_OBJECT_UNLOCK (selpad);
614
615     goto done;
616   }
617 }
618
619 /* must be called with the SELECTOR_LOCK, will block while the pad is blocked 
620  * or return TRUE when flushing */
621 static gboolean
622 gst_input_selector_wait (GstInputSelector * self, GstSelectorPad * pad)
623 {
624   while (self->blocked && !self->flushing && !pad->flushing) {
625     /* we can be unlocked here when we are shutting down (flushing) or when we
626      * get unblocked */
627     GST_INPUT_SELECTOR_WAIT (self);
628   }
629   return self->flushing;
630 }
631
632 /* must be called with the SELECTOR_LOCK, will block until the running time
633  * of the active pad is after this pad or return TRUE when flushing */
634 static gboolean
635 gst_input_selector_wait_running_time (GstInputSelector * sel,
636     GstSelectorPad * pad, GstBuffer * buf)
637 {
638   GstPad *active_sinkpad;
639   GstSelectorPad *active_selpad;
640   GstSegment *seg, *active_seg;
641   GstClockTime running_time, active_running_time = GST_CLOCK_TIME_NONE;
642
643   seg = &pad->segment;
644
645   active_sinkpad =
646       gst_input_selector_activate_sinkpad (sel, GST_PAD_CAST (pad));
647   active_selpad = GST_SELECTOR_PAD_CAST (active_sinkpad);
648   active_seg = &active_selpad->segment;
649
650   /* We can only sync if the segments are in time format or
651    * if the active pad had no newsegment event yet */
652   if (seg->format != GST_FORMAT_TIME ||
653       (active_seg->format != GST_FORMAT_TIME
654           && active_seg->format != GST_FORMAT_UNDEFINED))
655     return FALSE;
656
657   /* If we have no valid timestamp we can't sync this buffer */
658   if (!GST_BUFFER_TIMESTAMP_IS_VALID (buf))
659     return FALSE;
660
661   running_time = GST_BUFFER_TIMESTAMP (buf);
662   /* If possible try to get the running time at the end of the buffer */
663   if (GST_BUFFER_DURATION_IS_VALID (buf))
664     running_time += GST_BUFFER_DURATION (buf);
665   if (running_time > seg->stop)
666     running_time = seg->stop;
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     return FALSE;
672
673   /* Get active pad's running time, if no configured segment yet keep at -1 */
674   if (active_seg->format == GST_FORMAT_TIME)
675     active_running_time =
676         gst_segment_to_running_time (active_seg, GST_FORMAT_TIME,
677         active_seg->last_stop);
678
679   /* Wait until
680    *   a) this is the active pad
681    *   b) the pad or the selector is flushing
682    *   c) the selector is not blocked
683    *   d) the active pad has no running time or the active
684    *      pad's running time is before this running time
685    *   e) the active pad has a non-time segment
686    *   f) the active pad changed and has not pushed anything
687    */
688   while (pad != active_selpad && !sel->flushing && !pad->flushing
689       && active_selpad->pushed && (sel->blocked || active_running_time == -1
690           || running_time >= active_running_time)) {
691     if (!sel->blocked)
692       GST_DEBUG_OBJECT (pad,
693           "Waiting for active streams to advance. %" GST_TIME_FORMAT " >= %"
694           GST_TIME_FORMAT, GST_TIME_ARGS (running_time),
695           GST_TIME_ARGS (active_running_time));
696
697     GST_INPUT_SELECTOR_WAIT (sel);
698
699     /* Get new active pad, it might have changed */
700     active_sinkpad =
701         gst_input_selector_activate_sinkpad (sel, GST_PAD_CAST (pad));
702     active_selpad = GST_SELECTOR_PAD_CAST (active_sinkpad);
703     active_seg = &active_selpad->segment;
704
705     /* If the active segment is configured but not to time format
706      * we can't do any syncing at all */
707     if (active_seg->format != GST_FORMAT_TIME
708         && active_seg->format != GST_FORMAT_UNDEFINED)
709       break;
710
711     /* Get the new active pad running time */
712     if (active_seg->format == GST_FORMAT_TIME)
713       active_running_time =
714           gst_segment_to_running_time (active_seg, GST_FORMAT_TIME,
715           active_seg->last_stop);
716     else
717       active_running_time = -1;
718
719     if (!sel->blocked)
720       GST_DEBUG_OBJECT (pad,
721           "Waited for active streams to advance. %" GST_TIME_FORMAT " >= %"
722           GST_TIME_FORMAT, GST_TIME_ARGS (running_time),
723           GST_TIME_ARGS (active_running_time));
724
725   }
726
727   /* Return TRUE if the selector or the pad is flushing */
728   return (sel->flushing || pad->flushing);
729 }
730
731
732 static GstFlowReturn
733 gst_selector_pad_chain (GstPad * pad, GstBuffer * buf)
734 {
735   GstInputSelector *sel;
736   GstFlowReturn res;
737   GstPad *active_sinkpad;
738   GstPad *prev_active_sinkpad;
739   GstSelectorPad *selpad;
740   GstClockTime start_time;
741   GstSegment *seg;
742   GstEvent *close_event = NULL, *start_event = NULL;
743   GstCaps *caps;
744
745   sel = GST_INPUT_SELECTOR (gst_pad_get_parent (pad));
746   selpad = GST_SELECTOR_PAD_CAST (pad);
747   seg = &selpad->segment;
748
749   GST_INPUT_SELECTOR_LOCK (sel);
750   /* wait or check for flushing */
751   if (gst_input_selector_wait (sel, selpad))
752     goto flushing;
753
754   GST_LOG_OBJECT (pad, "getting active pad");
755
756   prev_active_sinkpad = sel->active_sinkpad;
757   active_sinkpad = gst_input_selector_activate_sinkpad (sel, pad);
758
759   /* In sync mode wait until the active pad has advanced
760    * after the running time of the current buffer */
761   if (sel->sync_streams && active_sinkpad != pad) {
762     if (gst_input_selector_wait_running_time (sel, selpad, buf))
763       goto flushing;
764   }
765
766   /* Might have changed while waiting */
767   active_sinkpad = gst_input_selector_activate_sinkpad (sel, pad);
768
769   /* update the segment on the srcpad */
770   start_time = GST_BUFFER_TIMESTAMP (buf);
771   if (GST_CLOCK_TIME_IS_VALID (start_time)) {
772     GST_LOG_OBJECT (pad, "received start time %" GST_TIME_FORMAT,
773         GST_TIME_ARGS (start_time));
774     if (GST_BUFFER_DURATION_IS_VALID (buf))
775       GST_LOG_OBJECT (pad, "received end time %" GST_TIME_FORMAT,
776           GST_TIME_ARGS (start_time + GST_BUFFER_DURATION (buf)));
777
778     GST_OBJECT_LOCK (pad);
779     gst_segment_set_last_stop (seg, seg->format, start_time);
780     GST_OBJECT_UNLOCK (pad);
781   }
782
783   /* Ignore buffers from pads except the selected one */
784   if (pad != active_sinkpad)
785     goto ignore;
786
787   /* Tell all non-active pads that we advanced the running time */
788   if (sel->sync_streams)
789     GST_INPUT_SELECTOR_BROADCAST (sel);
790
791   if (G_UNLIKELY (sel->pending_close)) {
792     GstSegment *cseg = &sel->segment;
793
794     GST_DEBUG_OBJECT (sel,
795         "pushing close NEWSEGMENT update %d, rate %lf, applied rate %lf, "
796         "format %d, "
797         "%" G_GINT64_FORMAT " -- %" G_GINT64_FORMAT ", time %"
798         G_GINT64_FORMAT, TRUE, cseg->rate, cseg->applied_rate, cseg->format,
799         cseg->start, cseg->stop, cseg->time);
800
801     /* create update segment */
802     close_event = gst_event_new_new_segment_full (TRUE, cseg->rate,
803         cseg->applied_rate, cseg->format, cseg->start, cseg->stop, cseg->time);
804
805     sel->pending_close = FALSE;
806   }
807   /* if we have a pending segment, push it out now */
808   if (G_UNLIKELY (selpad->segment_pending)) {
809     if (G_UNLIKELY (seg->format == GST_FORMAT_UNDEFINED)) {
810       GST_ERROR_OBJECT (pad, "Buffers arrived before NEWSEGMENT event");
811
812     } else {
813       GST_DEBUG_OBJECT (pad,
814           "pushing pending NEWSEGMENT update %d, rate %lf, applied rate %lf, "
815           "format %d, "
816           "%" G_GINT64_FORMAT " -- %" G_GINT64_FORMAT ", time %"
817           G_GINT64_FORMAT, FALSE, seg->rate, seg->applied_rate, seg->format,
818           seg->start, seg->stop, seg->time);
819
820       start_event = gst_event_new_new_segment_full (FALSE, seg->rate,
821           seg->applied_rate, seg->format, seg->start, seg->stop, seg->time);
822       selpad->segment_pending = FALSE;
823     }
824   }
825   GST_INPUT_SELECTOR_UNLOCK (sel);
826
827   if (prev_active_sinkpad != active_sinkpad && pad == active_sinkpad) {
828     NOTIFY_MUTEX_LOCK ();
829     g_object_notify (G_OBJECT (sel), "active-pad");
830     NOTIFY_MUTEX_UNLOCK ();
831   }
832
833   if (close_event)
834     gst_pad_push_event (sel->srcpad, close_event);
835
836   if (start_event)
837     gst_pad_push_event (sel->srcpad, start_event);
838
839   if (selpad->discont) {
840     buf = gst_buffer_make_metadata_writable (buf);
841
842     GST_DEBUG_OBJECT (pad, "Marking discont buffer %p", buf);
843     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
844     selpad->discont = FALSE;
845   }
846
847   /* forward */
848   GST_LOG_OBJECT (pad, "Forwarding buffer %p", buf);
849
850   if ((caps = GST_BUFFER_CAPS (buf))) {
851     if (GST_PAD_CAPS (sel->srcpad) != caps)
852       gst_pad_set_caps (sel->srcpad, caps);
853   }
854
855   res = gst_pad_push (sel->srcpad, buf);
856   selpad->pushed = TRUE;
857
858 done:
859   gst_object_unref (sel);
860   return res;
861
862   /* dropped buffers */
863 ignore:
864   {
865     gboolean active_pad_pushed = GST_SELECTOR_PAD_CAST (active_sinkpad)->pushed;
866
867     GST_DEBUG_OBJECT (pad, "Pad not active, discard buffer %p", buf);
868     /* when we drop a buffer, we're creating a discont on this pad */
869     selpad->discont = TRUE;
870     GST_INPUT_SELECTOR_UNLOCK (sel);
871     gst_buffer_unref (buf);
872
873     /* figure out what to return upstream */
874     GST_OBJECT_LOCK (selpad);
875     if (selpad->always_ok || !active_pad_pushed)
876       res = GST_FLOW_OK;
877     else
878       res = GST_FLOW_NOT_LINKED;
879     GST_OBJECT_UNLOCK (selpad);
880
881     goto done;
882   }
883 flushing:
884   {
885     GST_DEBUG_OBJECT (pad, "We are flushing, discard buffer %p", buf);
886     GST_INPUT_SELECTOR_UNLOCK (sel);
887     gst_buffer_unref (buf);
888     res = GST_FLOW_WRONG_STATE;
889     goto done;
890   }
891 }
892
893 static void gst_input_selector_dispose (GObject * object);
894
895 static void gst_input_selector_set_property (GObject * object,
896     guint prop_id, const GValue * value, GParamSpec * pspec);
897 static void gst_input_selector_get_property (GObject * object,
898     guint prop_id, GValue * value, GParamSpec * pspec);
899
900 static GstPad *gst_input_selector_request_new_pad (GstElement * element,
901     GstPadTemplate * templ, const gchar * unused);
902 static void gst_input_selector_release_pad (GstElement * element, GstPad * pad);
903
904 static GstStateChangeReturn gst_input_selector_change_state (GstElement *
905     element, GstStateChange transition);
906
907 static GstCaps *gst_input_selector_getcaps (GstPad * pad);
908 static gboolean gst_input_selector_event (GstPad * pad, GstEvent * event);
909 static gboolean gst_input_selector_query (GstPad * pad, GstQuery * query);
910 static gint64 gst_input_selector_block (GstInputSelector * self);
911 static void gst_input_selector_switch (GstInputSelector * self,
912     GstPad * pad, gint64 stop_time, gint64 start_time);
913
914 /* FIXME: create these marshallers using glib-genmarshal */
915 #define g_marshal_value_peek_object(v)   (v)->data[0].v_pointer
916 #define g_marshal_value_peek_int64(v)    (v)->data[0].v_int64
917
918 static void
919 gst_input_selector_marshal_INT64__VOID (GClosure * closure,
920     GValue * return_value G_GNUC_UNUSED,
921     guint n_param_values,
922     const GValue * param_values,
923     gpointer invocation_hint G_GNUC_UNUSED, gpointer marshal_data)
924 {
925   typedef gint64 (*GMarshalFunc_INT64__VOID) (gpointer data1, gpointer data2);
926   register GMarshalFunc_INT64__VOID callback;
927   register GCClosure *cc = (GCClosure *) closure;
928   register gpointer data1, data2;
929   gint64 v_return;
930
931   g_return_if_fail (return_value != NULL);
932   g_return_if_fail (n_param_values == 1);
933
934   if (G_CCLOSURE_SWAP_DATA (closure)) {
935     data1 = closure->data;
936     data2 = g_value_peek_pointer (param_values + 0);
937   } else {
938     data1 = g_value_peek_pointer (param_values + 0);
939     data2 = closure->data;
940   }
941   callback =
942       (GMarshalFunc_INT64__VOID) (marshal_data ? marshal_data : cc->callback);
943
944   v_return = callback (data1, data2);
945
946   g_value_set_int64 (return_value, v_return);
947 }
948
949 static void
950 gst_input_selector_marshal_VOID__OBJECT_INT64_INT64 (GClosure * closure,
951     GValue * return_value G_GNUC_UNUSED,
952     guint n_param_values,
953     const GValue * param_values,
954     gpointer invocation_hint G_GNUC_UNUSED, gpointer marshal_data)
955 {
956   typedef void (*GMarshalFunc_VOID__OBJECT_INT64_INT64) (gpointer data1,
957       gpointer arg_1, gint64 arg_2, gint64 arg_3, gpointer data2);
958   register GMarshalFunc_VOID__OBJECT_INT64_INT64 callback;
959   register GCClosure *cc = (GCClosure *) closure;
960   register gpointer data1, data2;
961
962   g_return_if_fail (n_param_values == 4);
963
964   if (G_CCLOSURE_SWAP_DATA (closure)) {
965     data1 = closure->data;
966     data2 = g_value_peek_pointer (param_values + 0);
967   } else {
968     data1 = g_value_peek_pointer (param_values + 0);
969     data2 = closure->data;
970   }
971   callback =
972       (GMarshalFunc_VOID__OBJECT_INT64_INT64) (marshal_data ? marshal_data :
973       cc->callback);
974
975   callback (data1,
976       g_marshal_value_peek_object (param_values + 1),
977       g_marshal_value_peek_int64 (param_values + 2),
978       g_marshal_value_peek_int64 (param_values + 3), data2);
979 }
980
981 #define _do_init(bla) \
982     GST_DEBUG_CATEGORY_INIT (input_selector_debug, \
983         "input-selector", 0, "An input stream selector element");
984
985 GST_BOILERPLATE_FULL (GstInputSelector, gst_input_selector, GstElement,
986     GST_TYPE_ELEMENT, _do_init);
987
988 static void
989 gst_input_selector_base_init (gpointer g_class)
990 {
991   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
992
993   gst_element_class_set_details_simple (element_class, "Input selector",
994       "Generic", "N-to-1 input stream selector",
995       "Julien Moutte <julien@moutte.net>, "
996       "Jan Schmidt <thaytan@mad.scientist.com>, "
997       "Wim Taymans <wim.taymans@gmail.com>");
998   gst_element_class_add_pad_template (element_class,
999       gst_static_pad_template_get (&gst_input_selector_sink_factory));
1000   gst_element_class_add_pad_template (element_class,
1001       gst_static_pad_template_get (&gst_input_selector_src_factory));
1002 }
1003
1004 static void
1005 gst_input_selector_class_init (GstInputSelectorClass * klass)
1006 {
1007   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1008   GstElementClass *gstelement_class = GST_ELEMENT_CLASS (klass);
1009
1010   gobject_class->dispose = gst_input_selector_dispose;
1011
1012   gobject_class->set_property = gst_input_selector_set_property;
1013   gobject_class->get_property = gst_input_selector_get_property;
1014
1015   g_object_class_install_property (gobject_class, PROP_N_PADS,
1016       g_param_spec_uint ("n-pads", "Number of Pads",
1017           "The number of sink pads", 0, G_MAXUINT, 0,
1018           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
1019
1020   g_object_class_install_property (gobject_class, PROP_ACTIVE_PAD,
1021       g_param_spec_object ("active-pad", "Active pad",
1022           "The currently active sink pad", GST_TYPE_PAD,
1023           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1024
1025   /**
1026    * GstInputSelector:sync-streams
1027    *
1028    * If set to %TRUE all inactive streams will be synced to the
1029    * running time of the active stream. This makes sure that no
1030    * buffers are dropped by input-selector that might be needed
1031    * when switching the active pad.
1032    *
1033    * Since: 0.10.36
1034    */
1035   g_object_class_install_property (gobject_class, PROP_SYNC_STREAMS,
1036       g_param_spec_boolean ("sync-streams", "Sync Streams",
1037           "Synchronize inactive streams to the running time of the active stream",
1038           DEFAULT_SYNC_STREAMS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1039
1040   /**
1041    * GstInputSelector::block:
1042    * @inputselector: the #GstInputSelector
1043    *
1044    * Block all sink pads in preparation for a switch. Returns the stop time of
1045    * the current switch segment, as a running time, or 0 if there is no current
1046    * active pad or the current active pad never received data.
1047    */
1048   gst_input_selector_signals[SIGNAL_BLOCK] =
1049       g_signal_new ("block", G_TYPE_FROM_CLASS (klass),
1050       G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
1051       G_STRUCT_OFFSET (GstInputSelectorClass, block), NULL, NULL,
1052       gst_input_selector_marshal_INT64__VOID, G_TYPE_INT64, 0);
1053   /**
1054    * GstInputSelector::switch:
1055    * @inputselector: the #GstInputSelector
1056    * @pad:            the pad to switch to
1057    * @stop_time:      running time at which to close the previous segment, or -1
1058    *                  to use the running time of the previously active sink pad
1059    * @start_time:     running time at which to start the new segment, or -1 to
1060    *                  use the running time of the newly active sink pad
1061    *
1062    * Switch to a new feed. The segment opened by the previously active pad, if
1063    * any, will be closed, and a new segment opened before data flows again.
1064    *
1065    * This signal must be emitted when the element has been blocked via the <link
1066    * linkend="GstInputSelector-block">block</link> signal.
1067    *
1068    * If you have a stream with only one switch element, such as an audio-only
1069    * stream, a stream switch should be performed by first emitting the block
1070    * signal, and then emitting the switch signal with -1 for the stop and start
1071    * time values.
1072    *
1073    * The intention of the @stop_time and @start_time arguments is to allow
1074    * multiple switch elements to switch and maintain stream synchronization.
1075    * When switching a stream with multiple feeds, you will need as many switch
1076    * elements as you have feeds. For example, a feed with audio and video will
1077    * have one switch element between the audio feeds and one for video.
1078    *
1079    * A switch over multiple switch elements should be performed as follows:
1080    * First, emit the <link linkend="GstInputSelector-block">block</link>
1081    * signal, collecting the returned values. The maximum running time returned
1082    * by block should then be used as the time at which to close the previous
1083    * segment.
1084    *
1085    * Then, query the running times of the new audio and video pads that you will
1086    * switch to. Naturally, these pads are on separate switch elements. Take the
1087    * minimum running time for those streams and use it for the time at which to
1088    * open the new segment.
1089    *
1090    * If @pad is the same as the current active pad, the element will cancel any
1091    * previous block without adjusting segments.
1092    *
1093    * <note><simpara>
1094    * the signal changed from accepting the pad name to the pad object.
1095    * </simpara></note>
1096    *
1097    * Since: 0.10.7
1098    */
1099   gst_input_selector_signals[SIGNAL_SWITCH] =
1100       g_signal_new ("switch", G_TYPE_FROM_CLASS (klass), G_SIGNAL_RUN_LAST,
1101       G_STRUCT_OFFSET (GstInputSelectorClass, switch_),
1102       NULL, NULL, gst_input_selector_marshal_VOID__OBJECT_INT64_INT64,
1103       G_TYPE_NONE, 3, GST_TYPE_PAD, G_TYPE_INT64, G_TYPE_INT64);
1104
1105   gstelement_class->request_new_pad = gst_input_selector_request_new_pad;
1106   gstelement_class->release_pad = gst_input_selector_release_pad;
1107   gstelement_class->change_state = gst_input_selector_change_state;
1108
1109   klass->block = GST_DEBUG_FUNCPTR (gst_input_selector_block);
1110   /* note the underscore because switch is a keyword otherwise */
1111   klass->switch_ = GST_DEBUG_FUNCPTR (gst_input_selector_switch);
1112 }
1113
1114 static void
1115 gst_input_selector_init (GstInputSelector * sel,
1116     GstInputSelectorClass * g_class)
1117 {
1118   sel->srcpad = gst_pad_new ("src", GST_PAD_SRC);
1119   gst_pad_set_iterate_internal_links_function (sel->srcpad,
1120       GST_DEBUG_FUNCPTR (gst_selector_pad_iterate_linked_pads));
1121   gst_pad_set_getcaps_function (sel->srcpad,
1122       GST_DEBUG_FUNCPTR (gst_input_selector_getcaps));
1123   gst_pad_set_query_function (sel->srcpad,
1124       GST_DEBUG_FUNCPTR (gst_input_selector_query));
1125   gst_pad_set_event_function (sel->srcpad,
1126       GST_DEBUG_FUNCPTR (gst_input_selector_event));
1127   gst_element_add_pad (GST_ELEMENT (sel), sel->srcpad);
1128   /* sinkpad management */
1129   sel->active_sinkpad = NULL;
1130   sel->padcount = 0;
1131   gst_segment_init (&sel->segment, GST_FORMAT_UNDEFINED);
1132   sel->sync_streams = DEFAULT_SYNC_STREAMS;
1133
1134   sel->lock = g_mutex_new ();
1135   sel->cond = g_cond_new ();
1136   sel->blocked = FALSE;
1137 }
1138
1139 static void
1140 gst_input_selector_dispose (GObject * object)
1141 {
1142   GstInputSelector *sel = GST_INPUT_SELECTOR (object);
1143
1144   if (sel->active_sinkpad) {
1145     gst_object_unref (sel->active_sinkpad);
1146     sel->active_sinkpad = NULL;
1147   }
1148   if (sel->lock) {
1149     g_mutex_free (sel->lock);
1150     sel->lock = NULL;
1151   }
1152   if (sel->cond) {
1153     g_cond_free (sel->cond);
1154     sel->cond = NULL;
1155   }
1156
1157   G_OBJECT_CLASS (parent_class)->dispose (object);
1158 }
1159
1160 /* Solve the following equation for B.timestamp, and set that as the segment
1161  * stop:
1162  * B.running_time = (B.timestamp - NS.start) / NS.abs_rate + NS.accum
1163  */
1164 static gint64
1165 gst_segment_get_timestamp (GstSegment * segment, gint64 running_time)
1166 {
1167   if (running_time <= segment->accum)
1168     return segment->start;
1169   else
1170     return (running_time - segment->accum) * segment->abs_rate + segment->start;
1171 }
1172
1173 static void
1174 gst_segment_set_stop (GstSegment * segment, gint64 running_time)
1175 {
1176   segment->stop = gst_segment_get_timestamp (segment, running_time);
1177   segment->last_stop = -1;
1178 }
1179
1180 static void
1181 gst_segment_set_start (GstSegment * segment, gint64 running_time)
1182 {
1183   gint64 new_start, duration;
1184
1185   new_start = gst_segment_get_timestamp (segment, running_time);
1186
1187   /* this is the duration we skipped */
1188   duration = new_start - segment->start;
1189   /* add the duration to the accumulated segment time */
1190   segment->accum += duration;
1191   /* move position in the segment */
1192   segment->time += duration;
1193   segment->start += duration;
1194 }
1195
1196 /* this function must be called with the SELECTOR_LOCK. It returns TRUE when the
1197  * active pad changed. */
1198 static gboolean
1199 gst_input_selector_set_active_pad (GstInputSelector * self,
1200     GstPad * pad, gint64 stop_time, gint64 start_time)
1201 {
1202   GstSelectorPad *old, *new;
1203   GstPad **active_pad_p;
1204
1205   if (pad == self->active_sinkpad)
1206     return FALSE;
1207
1208   old = GST_SELECTOR_PAD_CAST (self->active_sinkpad);
1209   new = GST_SELECTOR_PAD_CAST (pad);
1210
1211   GST_DEBUG_OBJECT (self, "setting active pad to %s:%s",
1212       GST_DEBUG_PAD_NAME (new));
1213
1214   if (!GST_CLOCK_TIME_IS_VALID (stop_time) && old) {
1215     /* no stop time given, get the latest running_time on the active pad to 
1216      * close and open the new segment */
1217     stop_time = start_time = gst_selector_pad_get_running_time (old);
1218     GST_DEBUG_OBJECT (self, "using start/stop of %" GST_TIME_FORMAT,
1219         GST_TIME_ARGS (start_time));
1220   }
1221
1222   if (old && old->active && !self->pending_close && stop_time >= 0) {
1223     /* schedule a last_stop update if one isn't already scheduled, and a
1224        segment has been pushed before. */
1225     memcpy (&self->segment, &old->segment, sizeof (self->segment));
1226
1227     GST_DEBUG_OBJECT (self, "setting stop_time to %" GST_TIME_FORMAT,
1228         GST_TIME_ARGS (stop_time));
1229     gst_segment_set_stop (&self->segment, stop_time);
1230     self->pending_close = TRUE;
1231   }
1232   if (old)
1233     old->pushed = FALSE;
1234
1235   if (new && new->active && start_time >= 0) {
1236     GST_DEBUG_OBJECT (self, "setting start_time to %" GST_TIME_FORMAT,
1237         GST_TIME_ARGS (start_time));
1238     /* schedule a new segment push */
1239     gst_segment_set_start (&new->segment, start_time);
1240     new->segment_pending = TRUE;
1241   }
1242   if (new)
1243     new->pushed = FALSE;
1244
1245   active_pad_p = &self->active_sinkpad;
1246   gst_object_replace ((GstObject **) active_pad_p, GST_OBJECT_CAST (pad));
1247
1248   /* Wake up all non-active pads in sync mode, they might be
1249    * the active pad now */
1250   if (self->sync_streams)
1251     GST_INPUT_SELECTOR_BROADCAST (self);
1252
1253   GST_DEBUG_OBJECT (self, "New active pad is %" GST_PTR_FORMAT,
1254       self->active_sinkpad);
1255
1256   return TRUE;
1257 }
1258
1259 static void
1260 gst_input_selector_set_property (GObject * object, guint prop_id,
1261     const GValue * value, GParamSpec * pspec)
1262 {
1263   GstInputSelector *sel = GST_INPUT_SELECTOR (object);
1264
1265   switch (prop_id) {
1266     case PROP_ACTIVE_PAD:
1267     {
1268       GstPad *pad;
1269
1270       pad = g_value_get_object (value);
1271
1272       GST_INPUT_SELECTOR_LOCK (sel);
1273       gst_input_selector_set_active_pad (sel, pad,
1274           GST_CLOCK_TIME_NONE, GST_CLOCK_TIME_NONE);
1275       GST_INPUT_SELECTOR_UNLOCK (sel);
1276       break;
1277     }
1278     case PROP_SYNC_STREAMS:
1279     {
1280       GST_INPUT_SELECTOR_LOCK (sel);
1281       sel->sync_streams = g_value_get_boolean (value);
1282       GST_INPUT_SELECTOR_UNLOCK (sel);
1283       break;
1284     }
1285     default:
1286       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1287       break;
1288   }
1289 }
1290
1291 static void
1292 gst_input_selector_get_property (GObject * object, guint prop_id,
1293     GValue * value, GParamSpec * pspec)
1294 {
1295   GstInputSelector *sel = GST_INPUT_SELECTOR (object);
1296
1297   switch (prop_id) {
1298     case PROP_N_PADS:
1299       GST_INPUT_SELECTOR_LOCK (object);
1300       g_value_set_uint (value, sel->n_pads);
1301       GST_INPUT_SELECTOR_UNLOCK (object);
1302       break;
1303     case PROP_ACTIVE_PAD:
1304       GST_INPUT_SELECTOR_LOCK (object);
1305       g_value_set_object (value, sel->active_sinkpad);
1306       GST_INPUT_SELECTOR_UNLOCK (object);
1307       break;
1308     case PROP_SYNC_STREAMS:
1309       GST_INPUT_SELECTOR_LOCK (object);
1310       g_value_set_boolean (value, sel->sync_streams);
1311       GST_INPUT_SELECTOR_UNLOCK (object);
1312       break;
1313     default:
1314       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1315       break;
1316   }
1317 }
1318
1319 static GstPad *
1320 gst_input_selector_get_linked_pad (GstInputSelector * sel, GstPad * pad,
1321     gboolean strict)
1322 {
1323   GstPad *otherpad = NULL;
1324
1325   GST_INPUT_SELECTOR_LOCK (sel);
1326   if (pad == sel->srcpad)
1327     otherpad = sel->active_sinkpad;
1328   else if (pad == sel->active_sinkpad || !strict)
1329     otherpad = sel->srcpad;
1330   if (otherpad)
1331     gst_object_ref (otherpad);
1332   GST_INPUT_SELECTOR_UNLOCK (sel);
1333
1334   return otherpad;
1335 }
1336
1337 static gboolean
1338 gst_input_selector_event (GstPad * pad, GstEvent * event)
1339 {
1340   GstInputSelector *sel;
1341   gboolean res = FALSE;
1342   GstPad *otherpad;
1343
1344   sel = GST_INPUT_SELECTOR (gst_pad_get_parent (pad));
1345   if (G_UNLIKELY (sel == NULL)) {
1346     gst_event_unref (event);
1347     return FALSE;
1348   }
1349
1350   otherpad = gst_input_selector_get_linked_pad (sel, pad, TRUE);
1351   if (otherpad) {
1352     res = gst_pad_push_event (otherpad, event);
1353
1354     gst_object_unref (otherpad);
1355   } else
1356     gst_event_unref (event);
1357
1358   gst_object_unref (sel);
1359   return res;
1360 }
1361
1362 /* query on the srcpad. We override this function because by default it will
1363  * only forward the query to one random sinkpad */
1364 static gboolean
1365 gst_input_selector_query (GstPad * pad, GstQuery * query)
1366 {
1367   gboolean res = TRUE;
1368   GstInputSelector *sel;
1369   GstPad *otherpad;
1370
1371   sel = GST_INPUT_SELECTOR (gst_pad_get_parent (pad));
1372   if (G_UNLIKELY (sel == NULL))
1373     return FALSE;
1374
1375   otherpad = gst_input_selector_get_linked_pad (sel, pad, TRUE);
1376
1377   switch (GST_QUERY_TYPE (query)) {
1378     case GST_QUERY_LATENCY:
1379     {
1380       GList *walk;
1381       GstClockTime resmin, resmax;
1382       gboolean reslive;
1383
1384       resmin = 0;
1385       resmax = -1;
1386       reslive = FALSE;
1387
1388       /* assume FALSE, we become TRUE if one query succeeds */
1389       res = FALSE;
1390
1391       /* perform the query on all sinkpads and combine the results. We take the
1392        * max of min and the min of max for the result latency. */
1393       GST_INPUT_SELECTOR_LOCK (sel);
1394       for (walk = GST_ELEMENT_CAST (sel)->sinkpads; walk;
1395           walk = g_list_next (walk)) {
1396         GstPad *sinkpad = GST_PAD_CAST (walk->data);
1397
1398         if (gst_pad_peer_query (sinkpad, query)) {
1399           GstClockTime min, max;
1400           gboolean live;
1401
1402           /* one query succeeded, we succeed too */
1403           res = TRUE;
1404
1405           gst_query_parse_latency (query, &live, &min, &max);
1406
1407           GST_DEBUG_OBJECT (sinkpad,
1408               "peer latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
1409               ", live %d", GST_TIME_ARGS (min), GST_TIME_ARGS (max), live);
1410
1411           if (live) {
1412             if (min > resmin)
1413               resmin = min;
1414             if (resmax == -1)
1415               resmax = max;
1416             else if (max < resmax)
1417               resmax = max;
1418             if (reslive == FALSE)
1419               reslive = live;
1420           }
1421         }
1422       }
1423       GST_INPUT_SELECTOR_UNLOCK (sel);
1424       if (res) {
1425         gst_query_set_latency (query, reslive, resmin, resmax);
1426
1427         GST_DEBUG_OBJECT (sel,
1428             "total latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
1429             ", live %d", GST_TIME_ARGS (resmin), GST_TIME_ARGS (resmax),
1430             reslive);
1431       }
1432
1433       break;
1434     }
1435     default:
1436       if (otherpad)
1437         res = gst_pad_peer_query (otherpad, query);
1438       break;
1439   }
1440   if (otherpad)
1441     gst_object_unref (otherpad);
1442   gst_object_unref (sel);
1443
1444   return res;
1445 }
1446
1447 static GstCaps *
1448 gst_input_selector_getcaps (GstPad * pad)
1449 {
1450   GstPad *otherpad;
1451   GstInputSelector *sel;
1452   GstCaps *caps;
1453
1454   sel = GST_INPUT_SELECTOR (gst_pad_get_parent (pad));
1455   if (G_UNLIKELY (sel == NULL))
1456     return gst_caps_new_any ();
1457
1458   otherpad = gst_input_selector_get_linked_pad (sel, pad, FALSE);
1459
1460   if (!otherpad) {
1461     GST_DEBUG_OBJECT (pad, "Pad not linked, returning ANY");
1462     caps = gst_caps_new_any ();
1463   } else {
1464     GST_DEBUG_OBJECT (pad, "Pad is linked (to %s:%s), returning peer caps",
1465         GST_DEBUG_PAD_NAME (otherpad));
1466     /* if the peer has caps, use those. If the pad is not linked, this function
1467      * returns NULL and we return ANY */
1468     if (!(caps = gst_pad_peer_get_caps_reffed (otherpad)))
1469       caps = gst_caps_new_any ();
1470     gst_object_unref (otherpad);
1471   }
1472
1473   gst_object_unref (sel);
1474   return caps;
1475 }
1476
1477 /* check if the pad is the active sinkpad */
1478 static inline gboolean
1479 gst_input_selector_is_active_sinkpad (GstInputSelector * sel, GstPad * pad)
1480 {
1481   gboolean res;
1482
1483   GST_INPUT_SELECTOR_LOCK (sel);
1484   res = (pad == sel->active_sinkpad);
1485   GST_INPUT_SELECTOR_UNLOCK (sel);
1486
1487   return res;
1488 }
1489
1490 /* Get or create the active sinkpad, must be called with SELECTOR_LOCK */
1491 static GstPad *
1492 gst_input_selector_activate_sinkpad (GstInputSelector * sel, GstPad * pad)
1493 {
1494   GstPad *active_sinkpad;
1495   GstSelectorPad *selpad;
1496
1497   selpad = GST_SELECTOR_PAD_CAST (pad);
1498
1499   selpad->active = TRUE;
1500   active_sinkpad = sel->active_sinkpad;
1501   if (active_sinkpad == NULL) {
1502     /* first pad we get activity on becomes the activated pad by default */
1503     if (sel->active_sinkpad)
1504       gst_object_unref (sel->active_sinkpad);
1505     active_sinkpad = sel->active_sinkpad = gst_object_ref (pad);
1506     GST_DEBUG_OBJECT (sel, "Activating pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1507   }
1508
1509   return active_sinkpad;
1510 }
1511
1512 static GstPad *
1513 gst_input_selector_request_new_pad (GstElement * element,
1514     GstPadTemplate * templ, const gchar * unused)
1515 {
1516   GstInputSelector *sel;
1517   gchar *name = NULL;
1518   GstPad *sinkpad = NULL;
1519
1520   g_return_val_if_fail (templ->direction == GST_PAD_SINK, NULL);
1521
1522   sel = GST_INPUT_SELECTOR (element);
1523
1524   GST_INPUT_SELECTOR_LOCK (sel);
1525
1526   GST_LOG_OBJECT (sel, "Creating new pad %d", sel->padcount);
1527   name = g_strdup_printf ("sink%d", sel->padcount++);
1528   sinkpad = g_object_new (GST_TYPE_SELECTOR_PAD,
1529       "name", name, "direction", templ->direction, "template", templ, NULL);
1530   g_free (name);
1531
1532   sel->n_pads++;
1533
1534   gst_pad_set_event_function (sinkpad,
1535       GST_DEBUG_FUNCPTR (gst_selector_pad_event));
1536   gst_pad_set_getcaps_function (sinkpad,
1537       GST_DEBUG_FUNCPTR (gst_selector_pad_getcaps));
1538   gst_pad_set_acceptcaps_function (sinkpad,
1539       GST_DEBUG_FUNCPTR (gst_selector_pad_acceptcaps));
1540   gst_pad_set_chain_function (sinkpad,
1541       GST_DEBUG_FUNCPTR (gst_selector_pad_chain));
1542   gst_pad_set_iterate_internal_links_function (sinkpad,
1543       GST_DEBUG_FUNCPTR (gst_selector_pad_iterate_linked_pads));
1544   gst_pad_set_bufferalloc_function (sinkpad,
1545       GST_DEBUG_FUNCPTR (gst_selector_pad_bufferalloc));
1546
1547   gst_pad_set_active (sinkpad, TRUE);
1548   gst_element_add_pad (GST_ELEMENT (sel), sinkpad);
1549   GST_INPUT_SELECTOR_UNLOCK (sel);
1550
1551   return sinkpad;
1552 }
1553
1554 static void
1555 gst_input_selector_release_pad (GstElement * element, GstPad * pad)
1556 {
1557   GstInputSelector *sel;
1558
1559   sel = GST_INPUT_SELECTOR (element);
1560   GST_LOG_OBJECT (sel, "Releasing pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1561
1562   GST_INPUT_SELECTOR_LOCK (sel);
1563   /* if the pad was the active pad, makes us select a new one */
1564   if (sel->active_sinkpad == pad) {
1565     GST_DEBUG_OBJECT (sel, "Deactivating pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1566     gst_object_unref (sel->active_sinkpad);
1567     sel->active_sinkpad = NULL;
1568   }
1569   sel->n_pads--;
1570
1571   gst_pad_set_active (pad, FALSE);
1572   gst_element_remove_pad (GST_ELEMENT (sel), pad);
1573   GST_INPUT_SELECTOR_UNLOCK (sel);
1574 }
1575
1576 static void
1577 gst_input_selector_reset (GstInputSelector * sel)
1578 {
1579   GList *walk;
1580
1581   GST_INPUT_SELECTOR_LOCK (sel);
1582   /* clear active pad */
1583   if (sel->active_sinkpad) {
1584     gst_object_unref (sel->active_sinkpad);
1585     sel->active_sinkpad = NULL;
1586   }
1587   /* reset segment */
1588   gst_segment_init (&sel->segment, GST_FORMAT_UNDEFINED);
1589   sel->pending_close = FALSE;
1590   /* reset each of our sinkpads state */
1591   for (walk = GST_ELEMENT_CAST (sel)->sinkpads; walk; walk = g_list_next (walk)) {
1592     GstSelectorPad *selpad = GST_SELECTOR_PAD_CAST (walk->data);
1593
1594     gst_selector_pad_reset (selpad);
1595
1596     if (selpad->tags) {
1597       gst_tag_list_free (selpad->tags);
1598       selpad->tags = NULL;
1599     }
1600   }
1601   GST_INPUT_SELECTOR_UNLOCK (sel);
1602 }
1603
1604 static GstStateChangeReturn
1605 gst_input_selector_change_state (GstElement * element,
1606     GstStateChange transition)
1607 {
1608   GstInputSelector *self = GST_INPUT_SELECTOR (element);
1609   GstStateChangeReturn result;
1610
1611   switch (transition) {
1612     case GST_STATE_CHANGE_READY_TO_PAUSED:
1613       GST_INPUT_SELECTOR_LOCK (self);
1614       self->blocked = FALSE;
1615       self->flushing = FALSE;
1616       GST_INPUT_SELECTOR_UNLOCK (self);
1617       break;
1618     case GST_STATE_CHANGE_PAUSED_TO_READY:
1619       /* first unlock before we call the parent state change function, which
1620        * tries to acquire the stream lock when going to ready. */
1621       GST_INPUT_SELECTOR_LOCK (self);
1622       self->blocked = FALSE;
1623       self->flushing = TRUE;
1624       GST_INPUT_SELECTOR_BROADCAST (self);
1625       GST_INPUT_SELECTOR_UNLOCK (self);
1626       break;
1627     default:
1628       break;
1629   }
1630
1631   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1632
1633   switch (transition) {
1634     case GST_STATE_CHANGE_PAUSED_TO_READY:
1635       gst_input_selector_reset (self);
1636       break;
1637     default:
1638       break;
1639   }
1640
1641   return result;
1642 }
1643
1644 static gint64
1645 gst_input_selector_block (GstInputSelector * self)
1646 {
1647   gint64 ret = 0;
1648   GstSelectorPad *spad;
1649
1650   GST_INPUT_SELECTOR_LOCK (self);
1651
1652   if (self->blocked)
1653     GST_WARNING_OBJECT (self, "switch already blocked");
1654
1655   self->blocked = TRUE;
1656   spad = GST_SELECTOR_PAD_CAST (self->active_sinkpad);
1657
1658   if (spad)
1659     ret = gst_selector_pad_get_running_time (spad);
1660   else
1661     GST_DEBUG_OBJECT (self, "no active pad while blocking");
1662
1663   GST_INPUT_SELECTOR_UNLOCK (self);
1664
1665   return ret;
1666 }
1667
1668 /* stop_time and start_time are running times */
1669 static void
1670 gst_input_selector_switch (GstInputSelector * self, GstPad * pad,
1671     gint64 stop_time, gint64 start_time)
1672 {
1673   gboolean changed;
1674
1675   g_return_if_fail (self->blocked == TRUE);
1676
1677   GST_INPUT_SELECTOR_LOCK (self);
1678   changed =
1679       gst_input_selector_set_active_pad (self, pad, stop_time, start_time);
1680
1681   self->blocked = FALSE;
1682   GST_INPUT_SELECTOR_BROADCAST (self);
1683   GST_INPUT_SELECTOR_UNLOCK (self);
1684
1685   if (changed) {
1686     NOTIFY_MUTEX_LOCK ();
1687     g_object_notify (G_OBJECT (self), "active-pad");
1688     NOTIFY_MUTEX_UNLOCK ();
1689   }
1690 }