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