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