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