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