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