8d0e23aa47a78fd80a4398b4624de4bb511bc8d8
[platform/upstream/gstreamer.git] / gst / playback / gstdecodebin2.c
1 /* GStreamer
2  * Copyright (C) <2006> Edward Hervey <edward@fluendo.com>
3  * Copyright (C) <2009> Sebastian Dröge <sebastian.droege@collabora.co.uk>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:element-decodebin
23  *
24  * #GstBin that auto-magically constructs a decoding pipeline using available
25  * decoders and demuxers via auto-plugging.
26  *
27  * decodebin is considered stable now and replaces the old #decodebin element.
28  * #uridecodebin uses decodebin internally and is often more convenient to
29  * use, as it creates a suitable source element as well.
30  */
31
32 /* Implementation notes:
33  *
34  * The following section describes how decodebin works internally.
35  *
36  * The first part of decodebin is its typefind element, which tries
37  * to determine the media type of the input stream. If the type is found
38  * autoplugging starts.
39  *
40  * decodebin internally organizes the elements it autoplugged into GstDecodeChains
41  * and GstDecodeGroups. A decode chain is a single chain of decoding, this
42  * means that if decodebin every autoplugs an element with two+ srcpads
43  * (e.g. a demuxer) this will end the chain and everything following this
44  * demuxer will be put into decode groups below the chain. Otherwise,
45  * if an element has a single srcpad that outputs raw data the decode chain
46  * is ended too and a GstDecodePad is stored and blocked.
47  *
48  * A decode group combines a number of chains that are created by a
49  * demuxer element. All those chains are connected through a multiqueue to
50  * the demuxer. A new group for the same demuxer is only created if the
51  * demuxer has signaled no-more-pads, in which case all following pads
52  * create a new chain in the new group.
53  *
54  * This continues until the top-level decode chain is complete. A decode
55  * chain is complete if it either ends with a blocked endpad, if autoplugging
56  * stopped because no suitable plugins could be found or if the active group
57  * is complete. A decode group on the other hand is complete if all child
58  * chains are complete.
59  *
60  * If this happens at some point, all endpads of all active groups are exposed.
61  * For this decodebin adds the endpads, signals no-more-pads and then unblocks
62  * them. Now playback starts.
63  *
64  * If one of the chains that end on a endpad receives EOS decodebin checks
65  * if all chains and groups are drained. In that case everything goes into EOS.
66  * If there is a chain where the active group is drained but there exist next
67  * groups, the active group is hidden (endpads are removed) and the next group
68  * is exposed. This means that in some cases more pads may be created even
69  * after the initial no-more-pads signal. This happens for example with
70  * so-called "chained oggs", most commonly found among ogg/vorbis internet
71  * radio streams.
72  *
73  * Note 1: If we're talking about blocked endpads this really means that the
74  * *target* pads of the endpads are blocked. Pads that are exposed to the outside
75  * should never ever be blocked!
76  *
77  * Note 2: If a group is complete and the parent's chain demuxer adds new pads
78  * but never signaled no-more-pads this additional pads will be ignored!
79  *
80  */
81
82 #ifdef HAVE_CONFIG_H
83 #include "config.h"
84 #endif
85
86 #include <gst/gst-i18n-plugin.h>
87
88 #include <string.h>
89 #include <gst/gst.h>
90 #include <gst/pbutils/pbutils.h>
91
92 #include "gstplay-marshal.h"
93 #include "gstplay-enum.h"
94 #include "gstplayback.h"
95 #include "gstrawcaps.h"
96
97 /* generic templates */
98 static GstStaticPadTemplate decoder_bin_sink_template =
99 GST_STATIC_PAD_TEMPLATE ("sink",
100     GST_PAD_SINK,
101     GST_PAD_ALWAYS,
102     GST_STATIC_CAPS_ANY);
103
104 static GstStaticPadTemplate decoder_bin_src_template =
105 GST_STATIC_PAD_TEMPLATE ("src%d",
106     GST_PAD_SRC,
107     GST_PAD_SOMETIMES,
108     GST_STATIC_CAPS_ANY);
109
110 GST_DEBUG_CATEGORY_STATIC (gst_decode_bin_debug);
111 #define GST_CAT_DEFAULT gst_decode_bin_debug
112
113 typedef struct _GstPendingPad GstPendingPad;
114 typedef struct _GstDecodeChain GstDecodeChain;
115 typedef struct _GstDecodeGroup GstDecodeGroup;
116 typedef struct _GstDecodePad GstDecodePad;
117 typedef GstGhostPadClass GstDecodePadClass;
118 typedef struct _GstDecodeBin GstDecodeBin;
119 typedef struct _GstDecodeBinClass GstDecodeBinClass;
120
121 #define GST_TYPE_DECODE_BIN             (gst_decode_bin_get_type())
122 #define GST_DECODE_BIN_CAST(obj)        ((GstDecodeBin*)(obj))
123 #define GST_DECODE_BIN(obj)             (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_DECODE_BIN,GstDecodeBin))
124 #define GST_DECODE_BIN_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_DECODE_BIN,GstDecodeBinClass))
125 #define GST_IS_DECODE_BIN(obj)          (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_DECODE_BIN))
126 #define GST_IS_DECODE_BIN_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_DECODE_BIN))
127
128 /**
129  *  GstDecodeBin:
130  *
131  *  The opaque #GstDecodeBin data structure
132  */
133 struct _GstDecodeBin
134 {
135   GstBin bin;                   /* we extend GstBin */
136
137   /* properties */
138   GstCaps *caps;                /* caps on which to stop decoding */
139   gchar *encoding;              /* encoding of subtitles */
140   gboolean use_buffering;       /* configure buffering on multiqueues */
141   gint low_percent;
142   gint high_percent;
143   guint max_size_bytes;
144   guint max_size_buffers;
145   guint64 max_size_time;
146   gboolean post_stream_topology;
147
148   GstElement *typefind;         /* this holds the typefind object */
149
150   GMutex *expose_lock;          /* Protects exposal and removal of groups */
151   GstDecodeChain *decode_chain; /* Top level decode chain */
152   gint nbpads;                  /* unique identifier for source pads */
153
154   GMutex *factories_lock;
155   guint32 factories_cookie;     /* Cookie from last time when factories was updated */
156   GList *factories;             /* factories we can use for selecting elements */
157
158   GMutex *subtitle_lock;        /* Protects changes to subtitles and encoding */
159   GList *subtitles;             /* List of elements with subtitle-encoding,
160                                  * protected by above mutex! */
161
162   gboolean have_type;           /* if we received the have_type signal */
163   guint have_type_id;           /* signal id for have-type from typefind */
164
165   gboolean async_pending;       /* async-start has been emited */
166
167   GMutex *dyn_lock;             /* lock protecting pad blocking */
168   gboolean shutdown;            /* if we are shutting down */
169   GList *blocked_pads;          /* pads that have set to block */
170
171   gboolean expose_allstreams;   /* Whether to expose unknow type streams or not */
172
173   gboolean upstream_seekable;   /* if upstream is seekable */
174 };
175
176 struct _GstDecodeBinClass
177 {
178   GstBinClass parent_class;
179
180   /* signal fired when we found a pad that we cannot decode */
181   void (*unknown_type) (GstElement * element, GstPad * pad, GstCaps * caps);
182
183   /* signal fired to know if we continue trying to decode the given caps */
184     gboolean (*autoplug_continue) (GstElement * element, GstPad * pad,
185       GstCaps * caps);
186   /* signal fired to get a list of factories to try to autoplug */
187   GValueArray *(*autoplug_factories) (GstElement * element, GstPad * pad,
188       GstCaps * caps);
189   /* signal fired to sort the factories */
190   GValueArray *(*autoplug_sort) (GstElement * element, GstPad * pad,
191       GstCaps * caps, GValueArray * factories);
192   /* signal fired to select from the proposed list of factories */
193     GstAutoplugSelectResult (*autoplug_select) (GstElement * element,
194       GstPad * pad, GstCaps * caps, GstElementFactory * factory);
195
196   /* fired when the last group is drained */
197   void (*drained) (GstElement * element);
198 };
199
200 /* signals */
201 enum
202 {
203   SIGNAL_UNKNOWN_TYPE,
204   SIGNAL_AUTOPLUG_CONTINUE,
205   SIGNAL_AUTOPLUG_FACTORIES,
206   SIGNAL_AUTOPLUG_SELECT,
207   SIGNAL_AUTOPLUG_SORT,
208   SIGNAL_DRAINED,
209   LAST_SIGNAL
210 };
211
212 /* automatic sizes, while prerolling we buffer up to 2MB, we ignore time
213  * and buffers in this case. */
214 #define AUTO_PREROLL_SIZE_BYTES                  2 * 1024 * 1024
215 #define AUTO_PREROLL_SIZE_BUFFERS                0
216 #define AUTO_PREROLL_NOT_SEEKABLE_SIZE_TIME      0
217 #define AUTO_PREROLL_SEEKABLE_SIZE_TIME          10 * GST_SECOND
218
219 /* whan playing, keep a max of 2MB of data but try to keep the number of buffers
220  * as low as possible (try to aim for 5 buffers) */
221 #define AUTO_PLAY_SIZE_BYTES        2 * 1024 * 1024
222 #define AUTO_PLAY_SIZE_BUFFERS      5
223 #define AUTO_PLAY_SIZE_TIME         0
224
225 #define DEFAULT_SUBTITLE_ENCODING NULL
226 #define DEFAULT_USE_BUFFERING     FALSE
227 #define DEFAULT_LOW_PERCENT       10
228 #define DEFAULT_HIGH_PERCENT      99
229 /* by default we use the automatic values above */
230 #define DEFAULT_MAX_SIZE_BYTES    0
231 #define DEFAULT_MAX_SIZE_BUFFERS  0
232 #define DEFAULT_MAX_SIZE_TIME     0
233 #define DEFAULT_POST_STREAM_TOPOLOGY FALSE
234 #define DEFAULT_EXPOSE_ALL_STREAMS  TRUE
235
236 /* Properties */
237 enum
238 {
239   PROP_0,
240   PROP_CAPS,
241   PROP_SUBTITLE_ENCODING,
242   PROP_SINK_CAPS,
243   PROP_USE_BUFFERING,
244   PROP_LOW_PERCENT,
245   PROP_HIGH_PERCENT,
246   PROP_MAX_SIZE_BYTES,
247   PROP_MAX_SIZE_BUFFERS,
248   PROP_MAX_SIZE_TIME,
249   PROP_POST_STREAM_TOPOLOGY,
250   PROP_EXPOSE_ALL_STREAMS,
251   PROP_LAST
252 };
253
254 static GstBinClass *parent_class;
255 static guint gst_decode_bin_signals[LAST_SIGNAL] = { 0 };
256
257 static GstStaticCaps default_raw_caps = GST_STATIC_CAPS (DEFAULT_RAW_CAPS);
258
259 static void do_async_start (GstDecodeBin * dbin);
260 static void do_async_done (GstDecodeBin * dbin);
261
262 static void type_found (GstElement * typefind, guint probability,
263     GstCaps * caps, GstDecodeBin * decode_bin);
264
265 static void decodebin_set_queue_size (GstDecodeBin * dbin,
266     GstElement * multiqueue, gboolean preroll);
267
268 static gboolean gst_decode_bin_autoplug_continue (GstElement * element,
269     GstPad * pad, GstCaps * caps);
270 static GValueArray *gst_decode_bin_autoplug_factories (GstElement *
271     element, GstPad * pad, GstCaps * caps);
272 static GValueArray *gst_decode_bin_autoplug_sort (GstElement * element,
273     GstPad * pad, GstCaps * caps, GValueArray * factories);
274 static GstAutoplugSelectResult gst_decode_bin_autoplug_select (GstElement *
275     element, GstPad * pad, GstCaps * caps, GstElementFactory * factory);
276
277 static void gst_decode_bin_set_property (GObject * object, guint prop_id,
278     const GValue * value, GParamSpec * pspec);
279 static void gst_decode_bin_get_property (GObject * object, guint prop_id,
280     GValue * value, GParamSpec * pspec);
281 static void gst_decode_bin_set_caps (GstDecodeBin * dbin, GstCaps * caps);
282 static GstCaps *gst_decode_bin_get_caps (GstDecodeBin * dbin);
283 static void caps_notify_cb (GstPad * pad, GParamSpec * unused,
284     GstDecodeChain * chain);
285
286 static GstPad *find_sink_pad (GstElement * element);
287 static GstStateChangeReturn gst_decode_bin_change_state (GstElement * element,
288     GstStateChange transition);
289
290 #define EXPOSE_LOCK(dbin) G_STMT_START {                                \
291     GST_LOG_OBJECT (dbin,                                               \
292                     "expose locking from thread %p",                    \
293                     g_thread_self ());                                  \
294     g_mutex_lock (GST_DECODE_BIN_CAST(dbin)->expose_lock);              \
295     GST_LOG_OBJECT (dbin,                                               \
296                     "expose locked from thread %p",                     \
297                     g_thread_self ());                                  \
298 } G_STMT_END
299
300 #define EXPOSE_UNLOCK(dbin) G_STMT_START {                              \
301     GST_LOG_OBJECT (dbin,                                               \
302                     "expose unlocking from thread %p",                  \
303                     g_thread_self ());                                  \
304     g_mutex_unlock (GST_DECODE_BIN_CAST(dbin)->expose_lock);            \
305 } G_STMT_END
306
307 #define DYN_LOCK(dbin) G_STMT_START {                   \
308     GST_LOG_OBJECT (dbin,                                               \
309                     "dynlocking from thread %p",                        \
310                     g_thread_self ());                                  \
311     g_mutex_lock (GST_DECODE_BIN_CAST(dbin)->dyn_lock);                 \
312     GST_LOG_OBJECT (dbin,                                               \
313                     "dynlocked from thread %p",                         \
314                     g_thread_self ());                                  \
315 } G_STMT_END
316
317 #define DYN_UNLOCK(dbin) G_STMT_START {                 \
318     GST_LOG_OBJECT (dbin,                                               \
319                     "dynunlocking from thread %p",                      \
320                     g_thread_self ());                                  \
321     g_mutex_unlock (GST_DECODE_BIN_CAST(dbin)->dyn_lock);               \
322 } G_STMT_END
323
324 #define SUBTITLE_LOCK(dbin) G_STMT_START {                              \
325     GST_LOG_OBJECT (dbin,                                               \
326                     "subtitle locking from thread %p",                  \
327                     g_thread_self ());                                  \
328     g_mutex_lock (GST_DECODE_BIN_CAST(dbin)->subtitle_lock);            \
329     GST_LOG_OBJECT (dbin,                                               \
330                     "subtitle lock from thread %p",                     \
331                     g_thread_self ());                                  \
332 } G_STMT_END
333
334 #define SUBTITLE_UNLOCK(dbin) G_STMT_START {                            \
335     GST_LOG_OBJECT (dbin,                                               \
336                     "subtitle unlocking from thread %p",                \
337                     g_thread_self ());                                  \
338     g_mutex_unlock (GST_DECODE_BIN_CAST(dbin)->subtitle_lock);          \
339 } G_STMT_END
340
341 struct _GstPendingPad
342 {
343   GstPad *pad;
344   GstDecodeChain *chain;
345   gulong event_probe_id;
346 };
347
348 /* GstDecodeGroup
349  *
350  * Streams belonging to the same group/chain of a media file
351  *
352  * When changing something here lock the parent chain!
353  */
354 struct _GstDecodeGroup
355 {
356   GstDecodeBin *dbin;
357   GstDecodeChain *parent;
358
359   GstElement *multiqueue;       /* Used for linking all child chains */
360   gulong overrunsig;            /* the overrun signal for multiqueue */
361
362   gboolean overrun;             /* TRUE if the multiqueue signaled overrun. This
363                                  * means that we should really expose the group */
364
365   gboolean no_more_pads;        /* TRUE if the demuxer signaled no-more-pads */
366   gboolean drained;             /* TRUE if the all children are drained */
367
368   GList *children;              /* List of GstDecodeChains in this group */
369
370   GList *reqpads;               /* List of RequestPads for multiqueue, there is
371                                  * exactly one RequestPad per child chain */
372 };
373
374 struct _GstDecodeChain
375 {
376   GstDecodeGroup *parent;
377   GstDecodeBin *dbin;
378
379   GMutex *lock;                 /* Protects this chain and its groups */
380
381   GstPad *pad;                  /* srcpad that caused creation of this chain */
382
383   gboolean demuxer;             /* TRUE if elements->data is a demuxer */
384   GList *elements;              /* All elements in this group, first
385                                    is the latest and most downstream element */
386
387   /* Note: there are only groups if the last element of this chain
388    * is a demuxer, otherwise the chain will end with an endpad.
389    * The other way around this means, that endpad only exists if this
390    * chain doesn't end with a demuxer! */
391
392   GstDecodeGroup *active_group; /* Currently active group */
393   GList *next_groups;           /* head is newest group, tail is next group.
394                                    a new group will be created only if the head
395                                    group had no-more-pads. If it's only exposed
396                                    all new pads will be ignored! */
397   GList *pending_pads;          /* Pads that have no fixed caps yet */
398
399   GstDecodePad *endpad;         /* Pad of this chain that could be exposed */
400   gboolean deadend;             /* This chain is incomplete and can't be completed,
401                                    e.g. no suitable decoder could be found
402                                    e.g. stream got EOS without buffers
403                                  */
404   GstCaps *endcaps;             /* Caps that were used when linking to the endpad
405                                    or that resulted in the deadend
406                                  */
407
408   /* FIXME: This should be done directly via a thread! */
409   GList *old_groups;            /* Groups that should be freed later */
410 };
411
412 static void gst_decode_chain_free (GstDecodeChain * chain);
413 static GstDecodeChain *gst_decode_chain_new (GstDecodeBin * dbin,
414     GstDecodeGroup * group, GstPad * pad);
415 static void gst_decode_group_hide (GstDecodeGroup * group);
416 static void gst_decode_group_free (GstDecodeGroup * group);
417 static GstDecodeGroup *gst_decode_group_new (GstDecodeBin * dbin,
418     GstDecodeChain * chain);
419 static gboolean gst_decode_chain_is_complete (GstDecodeChain * chain);
420 static gboolean gst_decode_chain_handle_eos (GstDecodeChain * chain);
421 static gboolean gst_decode_chain_expose (GstDecodeChain * chain,
422     GList ** endpads, gboolean * missing_plugin);
423 static gboolean gst_decode_chain_is_drained (GstDecodeChain * chain);
424 static gboolean gst_decode_group_is_complete (GstDecodeGroup * group);
425 static GstPad *gst_decode_group_control_demuxer_pad (GstDecodeGroup * group,
426     GstPad * pad);
427 static gboolean gst_decode_group_is_drained (GstDecodeGroup * group);
428
429 static gboolean gst_decode_bin_expose (GstDecodeBin * dbin);
430
431 #define CHAIN_MUTEX_LOCK(chain) G_STMT_START {                          \
432     GST_LOG_OBJECT (chain->dbin,                                        \
433                     "locking chain %p from thread %p",                  \
434                     chain, g_thread_self ());                           \
435     g_mutex_lock (chain->lock);                                         \
436     GST_LOG_OBJECT (chain->dbin,                                        \
437                     "locked chain %p from thread %p",                   \
438                     chain, g_thread_self ());                           \
439 } G_STMT_END
440
441 #define CHAIN_MUTEX_UNLOCK(chain) G_STMT_START {                        \
442     GST_LOG_OBJECT (chain->dbin,                                        \
443                     "unlocking chain %p from thread %p",                \
444                     chain, g_thread_self ());                           \
445     g_mutex_unlock (chain->lock);                                       \
446 } G_STMT_END
447
448 /* GstDecodePad
449  *
450  * GstPad private used for source pads of chains
451  */
452 struct _GstDecodePad
453 {
454   GstGhostPad parent;
455   GstDecodeBin *dbin;
456   GstDecodeChain *chain;
457
458   gboolean blocked;             /* the *target* pad is blocked */
459   gboolean exposed;             /* the pad is exposed */
460   gboolean drained;             /* an EOS has been seen on the pad */
461
462   gulong block_id;
463 };
464
465 GType gst_decode_pad_get_type (void);
466 G_DEFINE_TYPE (GstDecodePad, gst_decode_pad, GST_TYPE_GHOST_PAD);
467 #define GST_TYPE_DECODE_PAD (gst_decode_pad_get_type ())
468 #define GST_DECODE_PAD(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_DECODE_PAD,GstDecodePad))
469
470 static GstDecodePad *gst_decode_pad_new (GstDecodeBin * dbin, GstPad * pad,
471     GstDecodeChain * chain);
472 static void gst_decode_pad_activate (GstDecodePad * dpad,
473     GstDecodeChain * chain);
474 static void gst_decode_pad_unblock (GstDecodePad * dpad);
475 static void gst_decode_pad_set_blocked (GstDecodePad * dpad, gboolean blocked);
476
477 static void gst_pending_pad_free (GstPendingPad * ppad);
478 static GstProbeReturn pad_event_cb (GstPad * pad, GstProbeType type,
479     gpointer type_data, gpointer data);
480
481 /********************************
482  * Standard GObject boilerplate *
483  ********************************/
484
485 static void gst_decode_bin_class_init (GstDecodeBinClass * klass);
486 static void gst_decode_bin_init (GstDecodeBin * decode_bin);
487 static void gst_decode_bin_dispose (GObject * object);
488 static void gst_decode_bin_finalize (GObject * object);
489
490 static GType
491 gst_decode_bin_get_type (void)
492 {
493   static GType gst_decode_bin_type = 0;
494
495   if (!gst_decode_bin_type) {
496     static const GTypeInfo gst_decode_bin_info = {
497       sizeof (GstDecodeBinClass),
498       NULL,
499       NULL,
500       (GClassInitFunc) gst_decode_bin_class_init,
501       NULL,
502       NULL,
503       sizeof (GstDecodeBin),
504       0,
505       (GInstanceInitFunc) gst_decode_bin_init,
506       NULL
507     };
508
509     gst_decode_bin_type =
510         g_type_register_static (GST_TYPE_BIN, "GstDecodeBin",
511         &gst_decode_bin_info, 0);
512   }
513
514   return gst_decode_bin_type;
515 }
516
517 static gboolean
518 _gst_boolean_accumulator (GSignalInvocationHint * ihint,
519     GValue * return_accu, const GValue * handler_return, gpointer dummy)
520 {
521   gboolean myboolean;
522
523   myboolean = g_value_get_boolean (handler_return);
524   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
525     g_value_set_boolean (return_accu, myboolean);
526
527   /* stop emission if FALSE */
528   return myboolean;
529 }
530
531 /* we collect the first result */
532 static gboolean
533 _gst_array_accumulator (GSignalInvocationHint * ihint,
534     GValue * return_accu, const GValue * handler_return, gpointer dummy)
535 {
536   gpointer array;
537
538   array = g_value_get_boxed (handler_return);
539   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
540     g_value_set_boxed (return_accu, array);
541
542   return FALSE;
543 }
544
545 static gboolean
546 _gst_select_accumulator (GSignalInvocationHint * ihint,
547     GValue * return_accu, const GValue * handler_return, gpointer dummy)
548 {
549   GstAutoplugSelectResult res;
550
551   res = g_value_get_enum (handler_return);
552   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
553     g_value_set_enum (return_accu, res);
554
555   return FALSE;
556 }
557
558 static gboolean
559 _gst_array_hasvalue_accumulator (GSignalInvocationHint * ihint,
560     GValue * return_accu, const GValue * handler_return, gpointer dummy)
561 {
562   gpointer array;
563
564   array = g_value_get_boxed (handler_return);
565   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
566     g_value_set_boxed (return_accu, array);
567
568   if (array != NULL)
569     return FALSE;
570
571   return TRUE;
572 }
573
574 static void
575 gst_decode_bin_class_init (GstDecodeBinClass * klass)
576 {
577   GObjectClass *gobject_klass;
578   GstElementClass *gstelement_klass;
579
580   gobject_klass = (GObjectClass *) klass;
581   gstelement_klass = (GstElementClass *) klass;
582
583   parent_class = g_type_class_peek_parent (klass);
584
585   gobject_klass->dispose = gst_decode_bin_dispose;
586   gobject_klass->finalize = gst_decode_bin_finalize;
587   gobject_klass->set_property = gst_decode_bin_set_property;
588   gobject_klass->get_property = gst_decode_bin_get_property;
589
590   /**
591    * GstDecodeBin::unknown-type:
592    * @bin: The decodebin.
593    * @pad: The new pad containing caps that cannot be resolved to a 'final'
594    *       stream type.
595    * @caps: The #GstCaps of the pad that cannot be resolved.
596    *
597    * This signal is emitted when a pad for which there is no further possible
598    * decoding is added to the decodebin.
599    */
600   gst_decode_bin_signals[SIGNAL_UNKNOWN_TYPE] =
601       g_signal_new ("unknown-type", G_TYPE_FROM_CLASS (klass),
602       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, unknown_type),
603       NULL, NULL, gst_marshal_VOID__OBJECT_BOXED, G_TYPE_NONE, 2,
604       GST_TYPE_PAD, GST_TYPE_CAPS);
605
606   /**
607    * GstDecodeBin::autoplug-continue:
608    * @bin: The decodebin.
609    * @pad: The #GstPad.
610    * @caps: The #GstCaps found.
611    *
612    * This signal is emitted whenever decodebin finds a new stream. It is
613    * emitted before looking for any elements that can handle that stream.
614    *
615    * <note>
616    *   Invocation of signal handlers stops after the first signal handler
617    *   returns #FALSE. Signal handlers are invoked in the order they were
618    *   connected in.
619    * </note>
620    *
621    * Returns: #TRUE if you wish decodebin to look for elements that can
622    * handle the given @caps. If #FALSE, those caps will be considered as
623    * final and the pad will be exposed as such (see 'pad-added' signal of
624    * #GstElement).
625    */
626   gst_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE] =
627       g_signal_new ("autoplug-continue", G_TYPE_FROM_CLASS (klass),
628       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_continue),
629       _gst_boolean_accumulator, NULL, gst_play_marshal_BOOLEAN__OBJECT_BOXED,
630       G_TYPE_BOOLEAN, 2, GST_TYPE_PAD, GST_TYPE_CAPS);
631
632   /**
633    * GstDecodeBin::autoplug-factories:
634    * @bin: The decodebin.
635    * @pad: The #GstPad.
636    * @caps: The #GstCaps found.
637    *
638    * This function is emited when an array of possible factories for @caps on
639    * @pad is needed. Decodebin will by default return an array with all
640    * compatible factories, sorted by rank.
641    *
642    * If this function returns NULL, @pad will be exposed as a final caps.
643    *
644    * If this function returns an empty array, the pad will be considered as
645    * having an unhandled type media type.
646    *
647    * <note>
648    *   Only the signal handler that is connected first will ever by invoked.
649    *   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
650    *   signal, they will never be invoked!
651    * </note>
652    *
653    * Returns: a #GValueArray* with a list of factories to try. The factories are
654    * by default tried in the returned order or based on the index returned by
655    * "autoplug-select".
656    */
657   gst_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES] =
658       g_signal_new ("autoplug-factories", G_TYPE_FROM_CLASS (klass),
659       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass,
660           autoplug_factories), _gst_array_accumulator, NULL,
661       gst_play_marshal_BOXED__OBJECT_BOXED, G_TYPE_VALUE_ARRAY, 2,
662       GST_TYPE_PAD, GST_TYPE_CAPS);
663
664   /**
665    * GstDecodeBin::autoplug-sort:
666    * @bin: The decodebin.
667    * @pad: The #GstPad.
668    * @caps: The #GstCaps.
669    * @factories: A #GValueArray of possible #GstElementFactory to use.
670    *
671    * Once decodebin has found the possible #GstElementFactory objects to try
672    * for @caps on @pad, this signal is emited. The purpose of the signal is for
673    * the application to perform additional sorting or filtering on the element
674    * factory array.
675    *
676    * The callee should copy and modify @factories or return #NULL if the
677    * order should not change.
678    *
679    * <note>
680    *   Invocation of signal handlers stops after one signal handler has
681    *   returned something else than #NULL. Signal handlers are invoked in
682    *   the order they were connected in.
683    *   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
684    *   signal, they will never be invoked!
685    * </note>
686    *
687    * Returns: A new sorted array of #GstElementFactory objects.
688    */
689   gst_decode_bin_signals[SIGNAL_AUTOPLUG_SORT] =
690       g_signal_new ("autoplug-sort", G_TYPE_FROM_CLASS (klass),
691       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_sort),
692       _gst_array_hasvalue_accumulator, NULL,
693       gst_play_marshal_BOXED__OBJECT_BOXED_BOXED, G_TYPE_VALUE_ARRAY, 3,
694       GST_TYPE_PAD, GST_TYPE_CAPS, G_TYPE_VALUE_ARRAY);
695
696   /**
697    * GstDecodeBin::autoplug-select:
698    * @bin: The decodebin.
699    * @pad: The #GstPad.
700    * @caps: The #GstCaps.
701    * @factory: A #GstElementFactory to use.
702    *
703    * This signal is emitted once decodebin has found all the possible
704    * #GstElementFactory that can be used to handle the given @caps. For each of
705    * those factories, this signal is emited.
706    *
707    * The signal handler should return a #GST_TYPE_AUTOPLUG_SELECT_RESULT enum
708    * value indicating what decodebin should do next.
709    *
710    * A value of #GST_AUTOPLUG_SELECT_TRY will try to autoplug an element from
711    * @factory.
712    *
713    * A value of #GST_AUTOPLUG_SELECT_EXPOSE will expose @pad without plugging
714    * any element to it.
715    *
716    * A value of #GST_AUTOPLUG_SELECT_SKIP will skip @factory and move to the
717    * next factory.
718    *
719    * <note>
720    *   Only the signal handler that is connected first will ever by invoked.
721    *   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
722    *   signal, they will never be invoked!
723    * </note>
724    *
725    * Returns: a #GST_TYPE_AUTOPLUG_SELECT_RESULT that indicates the required
726    * operation. the default handler will always return
727    * #GST_AUTOPLUG_SELECT_TRY.
728    */
729   gst_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT] =
730       g_signal_new ("autoplug-select", G_TYPE_FROM_CLASS (klass),
731       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_select),
732       _gst_select_accumulator, NULL,
733       gst_play_marshal_ENUM__OBJECT_BOXED_OBJECT,
734       GST_TYPE_AUTOPLUG_SELECT_RESULT, 3, GST_TYPE_PAD, GST_TYPE_CAPS,
735       GST_TYPE_ELEMENT_FACTORY);
736
737   /**
738    * GstDecodeBin::drained
739    * @bin: The decodebin
740    *
741    * This signal is emitted once decodebin has finished decoding all the data.
742    *
743    * Since: 0.10.16
744    */
745   gst_decode_bin_signals[SIGNAL_DRAINED] =
746       g_signal_new ("drained", G_TYPE_FROM_CLASS (klass),
747       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, drained),
748       NULL, NULL, gst_marshal_VOID__VOID, G_TYPE_NONE, 0, G_TYPE_NONE);
749
750   g_object_class_install_property (gobject_klass, PROP_CAPS,
751       g_param_spec_boxed ("caps", "Caps", "The caps on which to stop decoding.",
752           GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
753
754   g_object_class_install_property (gobject_klass, PROP_SUBTITLE_ENCODING,
755       g_param_spec_string ("subtitle-encoding", "subtitle encoding",
756           "Encoding to assume if input subtitles are not in UTF-8 encoding. "
757           "If not set, the GST_SUBTITLE_ENCODING environment variable will "
758           "be checked for an encoding to use. If that is not set either, "
759           "ISO-8859-15 will be assumed.", NULL,
760           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
761
762   g_object_class_install_property (gobject_klass, PROP_SINK_CAPS,
763       g_param_spec_boxed ("sink-caps", "Sink Caps",
764           "The caps of the input data. (NULL = use typefind element)",
765           GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
766
767   /**
768    * GstDecodeBin::use-buffering
769    *
770    * Activate buffering in decodebin. This will instruct the multiqueues behind
771    * decoders to emit BUFFERING messages.
772
773    * Since: 0.10.26
774    */
775   g_object_class_install_property (gobject_klass, PROP_USE_BUFFERING,
776       g_param_spec_boolean ("use-buffering", "Use Buffering",
777           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
778           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
779
780   /**
781    * GstDecodeBin:low-percent
782    *
783    * Low threshold percent for buffering to start.
784    *
785    * Since: 0.10.26
786    */
787   g_object_class_install_property (gobject_klass, PROP_LOW_PERCENT,
788       g_param_spec_int ("low-percent", "Low percent",
789           "Low threshold for buffering to start", 0, 100,
790           DEFAULT_LOW_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
791   /**
792    * GstDecodeBin:high-percent
793    *
794    * High threshold percent for buffering to finish.
795    *
796    * Since: 0.10.26
797    */
798   g_object_class_install_property (gobject_klass, PROP_HIGH_PERCENT,
799       g_param_spec_int ("high-percent", "High percent",
800           "High threshold for buffering to finish", 0, 100,
801           DEFAULT_HIGH_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
802
803   /**
804    * GstDecodeBin:max-size-bytes
805    *
806    * Max amount amount of bytes in the queue (0=automatic).
807    *
808    * Since: 0.10.26
809    */
810   g_object_class_install_property (gobject_klass, PROP_MAX_SIZE_BYTES,
811       g_param_spec_uint ("max-size-bytes", "Max. size (bytes)",
812           "Max. amount of bytes in the queue (0=automatic)",
813           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
814           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
815   /**
816    * GstDecodeBin:max-size-buffers
817    *
818    * Max amount amount of buffers in the queue (0=automatic).
819    *
820    * Since: 0.10.26
821    */
822   g_object_class_install_property (gobject_klass, PROP_MAX_SIZE_BUFFERS,
823       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
824           "Max. number of buffers in the queue (0=automatic)",
825           0, G_MAXUINT, DEFAULT_MAX_SIZE_BUFFERS,
826           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
827   /**
828    * GstDecodeBin:max-size-time
829    *
830    * Max amount amount of time in the queue (in ns, 0=automatic).
831    *
832    * Since: 0.10.26
833    */
834   g_object_class_install_property (gobject_klass, PROP_MAX_SIZE_TIME,
835       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
836           "Max. amount of data in the queue (in ns, 0=automatic)",
837           0, G_MAXUINT64,
838           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
839
840   /**
841    * GstDecodeBin::post-stream-topology
842    *
843    * Post stream-topology messages on the bus every time the topology changes.
844    *
845    * Since: 0.10.26
846    */
847   g_object_class_install_property (gobject_klass, PROP_POST_STREAM_TOPOLOGY,
848       g_param_spec_boolean ("post-stream-topology", "Post Stream Topology",
849           "Post stream-topology messages",
850           DEFAULT_POST_STREAM_TOPOLOGY,
851           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
852
853   /**
854    * GstDecodeBin::expose-all-streams
855    *
856    * Expose streams of unknown type.
857    *
858    * If set to %FALSE, then only the streams that can be decoded to the final
859    * caps (see 'caps' property) will have a pad exposed. Streams that do not
860    * match those caps but could have been decoded will not have decoder plugged
861    * in internally and will not have a pad exposed.
862    *
863    * Since: 0.10.30
864    */
865   g_object_class_install_property (gobject_klass, PROP_EXPOSE_ALL_STREAMS,
866       g_param_spec_boolean ("expose-all-streams", "Expose All Streams",
867           "Expose all streams, including those of unknown type or that don't match the 'caps' property",
868           DEFAULT_EXPOSE_ALL_STREAMS,
869           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
870
871
872
873   klass->autoplug_continue =
874       GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_continue);
875   klass->autoplug_factories =
876       GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_factories);
877   klass->autoplug_sort = GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_sort);
878   klass->autoplug_select = GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_select);
879
880   gst_element_class_add_pad_template (gstelement_klass,
881       gst_static_pad_template_get (&decoder_bin_sink_template));
882   gst_element_class_add_pad_template (gstelement_klass,
883       gst_static_pad_template_get (&decoder_bin_src_template));
884
885   gst_element_class_set_details_simple (gstelement_klass,
886       "Decoder Bin", "Generic/Bin/Decoder",
887       "Autoplug and decode to raw media",
888       "Edward Hervey <edward.hervey@collabora.co.uk>, "
889       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
890
891   gstelement_klass->change_state =
892       GST_DEBUG_FUNCPTR (gst_decode_bin_change_state);
893 }
894
895 /* Must be called with factories lock! */
896 static void
897 gst_decode_bin_update_factories_list (GstDecodeBin * dbin)
898 {
899   if (!dbin->factories
900       || dbin->factories_cookie !=
901       gst_default_registry_get_feature_list_cookie ()) {
902     if (dbin->factories)
903       gst_plugin_feature_list_free (dbin->factories);
904     dbin->factories =
905         gst_element_factory_list_get_elements
906         (GST_ELEMENT_FACTORY_TYPE_DECODABLE, GST_RANK_MARGINAL);
907     dbin->factories_cookie = gst_default_registry_get_feature_list_cookie ();
908   }
909 }
910
911 static void
912 gst_decode_bin_init (GstDecodeBin * decode_bin)
913 {
914   /* first filter out the interesting element factories */
915   decode_bin->factories_lock = g_mutex_new ();
916
917   /* we create the typefind element only once */
918   decode_bin->typefind = gst_element_factory_make ("typefind", "typefind");
919   if (!decode_bin->typefind) {
920     g_warning ("can't find typefind element, decodebin will not work");
921   } else {
922     GstPad *pad;
923     GstPad *gpad;
924     GstPadTemplate *pad_tmpl;
925
926     /* add the typefind element */
927     if (!gst_bin_add (GST_BIN (decode_bin), decode_bin->typefind)) {
928       g_warning ("Could not add typefind element, decodebin will not work");
929       gst_object_unref (decode_bin->typefind);
930       decode_bin->typefind = NULL;
931     }
932
933     /* get the sinkpad */
934     pad = gst_element_get_static_pad (decode_bin->typefind, "sink");
935
936     /* get the pad template */
937     pad_tmpl = gst_static_pad_template_get (&decoder_bin_sink_template);
938
939     /* ghost the sink pad to ourself */
940     gpad = gst_ghost_pad_new_from_template ("sink", pad, pad_tmpl);
941     gst_pad_set_active (gpad, TRUE);
942     gst_element_add_pad (GST_ELEMENT (decode_bin), gpad);
943
944     gst_object_unref (pad_tmpl);
945     gst_object_unref (pad);
946
947     /* connect a signal to find out when the typefind element found
948      * a type */
949     decode_bin->have_type_id =
950         g_signal_connect (G_OBJECT (decode_bin->typefind), "have-type",
951         G_CALLBACK (type_found), decode_bin);
952   }
953
954   decode_bin->expose_lock = g_mutex_new ();
955   decode_bin->decode_chain = NULL;
956
957   decode_bin->dyn_lock = g_mutex_new ();
958   decode_bin->shutdown = FALSE;
959   decode_bin->blocked_pads = NULL;
960
961   decode_bin->subtitle_lock = g_mutex_new ();
962
963   decode_bin->encoding = g_strdup (DEFAULT_SUBTITLE_ENCODING);
964   decode_bin->caps = gst_static_caps_get (&default_raw_caps);
965   decode_bin->use_buffering = DEFAULT_USE_BUFFERING;
966   decode_bin->low_percent = DEFAULT_LOW_PERCENT;
967   decode_bin->high_percent = DEFAULT_HIGH_PERCENT;
968
969   decode_bin->max_size_bytes = DEFAULT_MAX_SIZE_BYTES;
970   decode_bin->max_size_buffers = DEFAULT_MAX_SIZE_BUFFERS;
971   decode_bin->max_size_time = DEFAULT_MAX_SIZE_TIME;
972
973   decode_bin->expose_allstreams = DEFAULT_EXPOSE_ALL_STREAMS;
974 }
975
976 static void
977 gst_decode_bin_dispose (GObject * object)
978 {
979   GstDecodeBin *decode_bin;
980
981   decode_bin = GST_DECODE_BIN (object);
982
983   if (decode_bin->factories)
984     gst_plugin_feature_list_free (decode_bin->factories);
985   decode_bin->factories = NULL;
986
987   if (decode_bin->decode_chain)
988     gst_decode_chain_free (decode_bin->decode_chain);
989   decode_bin->decode_chain = NULL;
990
991   if (decode_bin->caps)
992     gst_caps_unref (decode_bin->caps);
993   decode_bin->caps = NULL;
994
995   g_free (decode_bin->encoding);
996   decode_bin->encoding = NULL;
997
998   g_list_free (decode_bin->subtitles);
999   decode_bin->subtitles = NULL;
1000
1001   G_OBJECT_CLASS (parent_class)->dispose (object);
1002 }
1003
1004 static void
1005 gst_decode_bin_finalize (GObject * object)
1006 {
1007   GstDecodeBin *decode_bin;
1008
1009   decode_bin = GST_DECODE_BIN (object);
1010
1011   if (decode_bin->expose_lock) {
1012     g_mutex_free (decode_bin->expose_lock);
1013     decode_bin->expose_lock = NULL;
1014   }
1015
1016   if (decode_bin->dyn_lock) {
1017     g_mutex_free (decode_bin->dyn_lock);
1018     decode_bin->dyn_lock = NULL;
1019   }
1020
1021   if (decode_bin->subtitle_lock) {
1022     g_mutex_free (decode_bin->subtitle_lock);
1023     decode_bin->subtitle_lock = NULL;
1024   }
1025
1026   if (decode_bin->factories_lock) {
1027     g_mutex_free (decode_bin->factories_lock);
1028     decode_bin->factories_lock = NULL;
1029   }
1030
1031   G_OBJECT_CLASS (parent_class)->finalize (object);
1032 }
1033
1034 /* _set_caps
1035  * Changes the caps on which decodebin will stop decoding.
1036  * Will unref the previously set one. The refcount of the given caps will be
1037  * increased.
1038  * @caps can be NULL.
1039  *
1040  * MT-safe
1041  */
1042 static void
1043 gst_decode_bin_set_caps (GstDecodeBin * dbin, GstCaps * caps)
1044 {
1045   GST_DEBUG_OBJECT (dbin, "Setting new caps: %" GST_PTR_FORMAT, caps);
1046
1047   GST_OBJECT_LOCK (dbin);
1048   gst_caps_replace (&dbin->caps, caps);
1049   GST_OBJECT_UNLOCK (dbin);
1050 }
1051
1052 /* _get_caps
1053  * Returns the currently configured caps on which decodebin will stop decoding.
1054  * The returned caps (if not NULL), will have its refcount incremented.
1055  *
1056  * MT-safe
1057  */
1058 static GstCaps *
1059 gst_decode_bin_get_caps (GstDecodeBin * dbin)
1060 {
1061   GstCaps *caps;
1062
1063   GST_DEBUG_OBJECT (dbin, "Getting currently set caps");
1064
1065   GST_OBJECT_LOCK (dbin);
1066   caps = dbin->caps;
1067   if (caps)
1068     gst_caps_ref (caps);
1069   GST_OBJECT_UNLOCK (dbin);
1070
1071   return caps;
1072 }
1073
1074 static void
1075 gst_decode_bin_set_sink_caps (GstDecodeBin * dbin, GstCaps * caps)
1076 {
1077   GST_DEBUG_OBJECT (dbin, "Setting new caps: %" GST_PTR_FORMAT, caps);
1078
1079   g_object_set (dbin->typefind, "force-caps", caps, NULL);
1080 }
1081
1082 static GstCaps *
1083 gst_decode_bin_get_sink_caps (GstDecodeBin * dbin)
1084 {
1085   GstCaps *caps;
1086
1087   GST_DEBUG_OBJECT (dbin, "Getting currently set caps");
1088
1089   g_object_get (dbin->typefind, "force-caps", &caps, NULL);
1090
1091   return caps;
1092 }
1093
1094 static void
1095 gst_decode_bin_set_subs_encoding (GstDecodeBin * dbin, const gchar * encoding)
1096 {
1097   GList *walk;
1098
1099   GST_DEBUG_OBJECT (dbin, "Setting new encoding: %s", GST_STR_NULL (encoding));
1100
1101   SUBTITLE_LOCK (dbin);
1102   g_free (dbin->encoding);
1103   dbin->encoding = g_strdup (encoding);
1104
1105   /* set the subtitle encoding on all added elements */
1106   for (walk = dbin->subtitles; walk; walk = g_list_next (walk)) {
1107     g_object_set (G_OBJECT (walk->data), "subtitle-encoding", dbin->encoding,
1108         NULL);
1109   }
1110   SUBTITLE_UNLOCK (dbin);
1111 }
1112
1113 static gchar *
1114 gst_decode_bin_get_subs_encoding (GstDecodeBin * dbin)
1115 {
1116   gchar *encoding;
1117
1118   GST_DEBUG_OBJECT (dbin, "Getting currently set encoding");
1119
1120   SUBTITLE_LOCK (dbin);
1121   encoding = g_strdup (dbin->encoding);
1122   SUBTITLE_UNLOCK (dbin);
1123
1124   return encoding;
1125 }
1126
1127 static void
1128 gst_decode_bin_set_property (GObject * object, guint prop_id,
1129     const GValue * value, GParamSpec * pspec)
1130 {
1131   GstDecodeBin *dbin;
1132
1133   dbin = GST_DECODE_BIN (object);
1134
1135   switch (prop_id) {
1136     case PROP_CAPS:
1137       gst_decode_bin_set_caps (dbin, g_value_get_boxed (value));
1138       break;
1139     case PROP_SUBTITLE_ENCODING:
1140       gst_decode_bin_set_subs_encoding (dbin, g_value_get_string (value));
1141       break;
1142     case PROP_SINK_CAPS:
1143       gst_decode_bin_set_sink_caps (dbin, g_value_get_boxed (value));
1144       break;
1145     case PROP_USE_BUFFERING:
1146       dbin->use_buffering = g_value_get_boolean (value);
1147       break;
1148     case PROP_LOW_PERCENT:
1149       dbin->low_percent = g_value_get_int (value);
1150       break;
1151     case PROP_HIGH_PERCENT:
1152       dbin->high_percent = g_value_get_int (value);
1153       break;
1154     case PROP_MAX_SIZE_BYTES:
1155       dbin->max_size_bytes = g_value_get_uint (value);
1156       break;
1157     case PROP_MAX_SIZE_BUFFERS:
1158       dbin->max_size_buffers = g_value_get_uint (value);
1159       break;
1160     case PROP_MAX_SIZE_TIME:
1161       dbin->max_size_time = g_value_get_uint64 (value);
1162       break;
1163     case PROP_POST_STREAM_TOPOLOGY:
1164       dbin->post_stream_topology = g_value_get_boolean (value);
1165       break;
1166     case PROP_EXPOSE_ALL_STREAMS:
1167       dbin->expose_allstreams = g_value_get_boolean (value);
1168       break;
1169     default:
1170       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1171       break;
1172   }
1173 }
1174
1175 static void
1176 gst_decode_bin_get_property (GObject * object, guint prop_id,
1177     GValue * value, GParamSpec * pspec)
1178 {
1179   GstDecodeBin *dbin;
1180
1181   dbin = GST_DECODE_BIN (object);
1182   switch (prop_id) {
1183     case PROP_CAPS:
1184       g_value_take_boxed (value, gst_decode_bin_get_caps (dbin));
1185       break;
1186     case PROP_SUBTITLE_ENCODING:
1187       g_value_take_string (value, gst_decode_bin_get_subs_encoding (dbin));
1188       break;
1189     case PROP_SINK_CAPS:
1190       g_value_take_boxed (value, gst_decode_bin_get_sink_caps (dbin));
1191       break;
1192     case PROP_USE_BUFFERING:
1193       g_value_set_boolean (value, dbin->use_buffering);
1194       break;
1195     case PROP_LOW_PERCENT:
1196       g_value_set_int (value, dbin->low_percent);
1197       break;
1198     case PROP_HIGH_PERCENT:
1199       g_value_set_int (value, dbin->high_percent);
1200       break;
1201     case PROP_MAX_SIZE_BYTES:
1202       g_value_set_uint (value, dbin->max_size_bytes);
1203       break;
1204     case PROP_MAX_SIZE_BUFFERS:
1205       g_value_set_uint (value, dbin->max_size_buffers);
1206       break;
1207     case PROP_MAX_SIZE_TIME:
1208       g_value_set_uint64 (value, dbin->max_size_time);
1209       break;
1210     case PROP_POST_STREAM_TOPOLOGY:
1211       g_value_set_boolean (value, dbin->post_stream_topology);
1212       break;
1213     case PROP_EXPOSE_ALL_STREAMS:
1214       g_value_set_boolean (value, dbin->expose_allstreams);
1215       break;
1216     default:
1217       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1218       break;
1219   }
1220 }
1221
1222
1223 /*****
1224  * Default autoplug signal handlers
1225  *****/
1226 static gboolean
1227 gst_decode_bin_autoplug_continue (GstElement * element, GstPad * pad,
1228     GstCaps * caps)
1229 {
1230   GST_DEBUG_OBJECT (element, "autoplug-continue returns TRUE");
1231
1232   /* by default we always continue */
1233   return TRUE;
1234 }
1235
1236 static GValueArray *
1237 gst_decode_bin_autoplug_factories (GstElement * element, GstPad * pad,
1238     GstCaps * caps)
1239 {
1240   GList *list, *tmp;
1241   GValueArray *result;
1242   GstDecodeBin *dbin = GST_DECODE_BIN_CAST (element);
1243
1244   GST_DEBUG_OBJECT (element, "finding factories");
1245
1246   /* return all compatible factories for caps */
1247   g_mutex_lock (dbin->factories_lock);
1248   gst_decode_bin_update_factories_list (dbin);
1249   list =
1250       gst_element_factory_list_filter (dbin->factories, caps, GST_PAD_SINK,
1251       FALSE);
1252   g_mutex_unlock (dbin->factories_lock);
1253
1254   result = g_value_array_new (g_list_length (list));
1255   for (tmp = list; tmp; tmp = tmp->next) {
1256     GstElementFactory *factory = GST_ELEMENT_FACTORY_CAST (tmp->data);
1257     GValue val = { 0, };
1258
1259     g_value_init (&val, G_TYPE_OBJECT);
1260     g_value_set_object (&val, factory);
1261     g_value_array_append (result, &val);
1262     g_value_unset (&val);
1263   }
1264   gst_plugin_feature_list_free (list);
1265
1266   GST_DEBUG_OBJECT (element, "autoplug-factories returns %p", result);
1267
1268   return result;
1269 }
1270
1271 static GValueArray *
1272 gst_decode_bin_autoplug_sort (GstElement * element, GstPad * pad,
1273     GstCaps * caps, GValueArray * factories)
1274 {
1275   return NULL;
1276 }
1277
1278 static GstAutoplugSelectResult
1279 gst_decode_bin_autoplug_select (GstElement * element, GstPad * pad,
1280     GstCaps * caps, GstElementFactory * factory)
1281 {
1282   GST_DEBUG_OBJECT (element, "default autoplug-select returns TRY");
1283
1284   /* Try factory. */
1285   return GST_AUTOPLUG_SELECT_TRY;
1286 }
1287
1288 /********
1289  * Discovery methods
1290  *****/
1291
1292 static gboolean are_final_caps (GstDecodeBin * dbin, GstCaps * caps);
1293 static gboolean is_demuxer_element (GstElement * srcelement);
1294
1295 static gboolean connect_pad (GstDecodeBin * dbin, GstElement * src,
1296     GstDecodePad * dpad, GstPad * pad, GstCaps * caps, GValueArray * factories,
1297     GstDecodeChain * chain);
1298 static gboolean connect_element (GstDecodeBin * dbin, GstElement * element,
1299     GstDecodeChain * chain);
1300 static void expose_pad (GstDecodeBin * dbin, GstElement * src,
1301     GstDecodePad * dpad, GstPad * pad, GstCaps * caps, GstDecodeChain * chain);
1302
1303 static void pad_added_cb (GstElement * element, GstPad * pad,
1304     GstDecodeChain * chain);
1305 static void pad_removed_cb (GstElement * element, GstPad * pad,
1306     GstDecodeChain * chain);
1307 static void no_more_pads_cb (GstElement * element, GstDecodeChain * chain);
1308
1309 static GstDecodeGroup *gst_decode_chain_get_current_group (GstDecodeChain *
1310     chain);
1311
1312 /* called when a new pad is discovered. It will perform some basic actions
1313  * before trying to link something to it.
1314  *
1315  *  - Check the caps, don't do anything when there are no caps or when they have
1316  *    no good type.
1317  *  - signal AUTOPLUG_CONTINUE to check if we need to continue autoplugging this
1318  *    pad.
1319  *  - if the caps are non-fixed, setup a handler to continue autoplugging when
1320  *    the caps become fixed (connect to notify::caps).
1321  *  - get list of factories to autoplug.
1322  *  - continue autoplugging to one of the factories.
1323  */
1324 static void
1325 analyze_new_pad (GstDecodeBin * dbin, GstElement * src, GstPad * pad,
1326     GstCaps * caps, GstDecodeChain * chain)
1327 {
1328   gboolean apcontinue = TRUE;
1329   GValueArray *factories = NULL, *result = NULL;
1330   GstDecodePad *dpad;
1331
1332   GST_DEBUG_OBJECT (dbin, "Pad %s:%s caps:%" GST_PTR_FORMAT,
1333       GST_DEBUG_PAD_NAME (pad), caps);
1334
1335   if (chain->elements && src != chain->elements->data) {
1336     GST_ERROR_OBJECT (dbin, "New pad from not the last element in this chain");
1337     return;
1338   }
1339
1340   if (chain->endpad) {
1341     GST_ERROR_OBJECT (dbin, "New pad in a chain that is already complete");
1342     return;
1343   }
1344
1345   if (chain->demuxer) {
1346     GstDecodeGroup *group;
1347     GstDecodeChain *oldchain = chain;
1348
1349     /* we are adding a new pad for a demuxer (see is_demuxer_element(),
1350      * start a new chain for it */
1351     CHAIN_MUTEX_LOCK (oldchain);
1352     group = gst_decode_chain_get_current_group (chain);
1353     if (group) {
1354       chain = gst_decode_chain_new (dbin, group, pad);
1355       group->children = g_list_prepend (group->children, chain);
1356     }
1357     CHAIN_MUTEX_UNLOCK (oldchain);
1358     if (!group) {
1359       GST_WARNING_OBJECT (dbin, "No current group");
1360       return;
1361     }
1362   }
1363
1364   if ((caps == NULL) || gst_caps_is_empty (caps))
1365     goto unknown_type;
1366
1367   if (gst_caps_is_any (caps))
1368     goto any_caps;
1369
1370   dpad = gst_decode_pad_new (dbin, pad, chain);
1371
1372   /* 1. Emit 'autoplug-continue' the result will tell us if this pads needs
1373    * further autoplugging. */
1374   g_signal_emit (G_OBJECT (dbin),
1375       gst_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE], 0, dpad, caps,
1376       &apcontinue);
1377
1378   /* 1.a if autoplug-continue is FALSE or caps is a raw format, goto pad_is_final */
1379   if ((!apcontinue) || are_final_caps (dbin, caps))
1380     goto expose_pad;
1381
1382   /* 1.b when the caps are not fixed yet, we can't be sure what element to
1383    * connect. We delay autoplugging until the caps are fixed */
1384   if (!gst_caps_is_fixed (caps))
1385     goto non_fixed;
1386
1387   /* 1.c else get the factories and if there's no compatible factory goto
1388    * unknown_type */
1389   g_signal_emit (G_OBJECT (dbin),
1390       gst_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES], 0, dpad, caps,
1391       &factories);
1392
1393   /* NULL means that we can expose the pad */
1394   if (factories == NULL)
1395     goto expose_pad;
1396
1397   /* if the array is empty, we have a type for which we have no decoder */
1398   if (factories->n_values == 0) {
1399     if (!dbin->expose_allstreams) {
1400       GstCaps *raw = gst_static_caps_get (&default_raw_caps);
1401
1402       /* If the caps are raw, this just means we don't want to expose them */
1403       if (gst_caps_can_intersect (raw, caps)) {
1404         gst_caps_unref (raw);
1405         gst_object_unref (dpad);
1406         goto discarded_type;
1407       }
1408       gst_caps_unref (raw);
1409     }
1410
1411     /* if not we have a unhandled type with no compatible factories */
1412     g_value_array_free (factories);
1413     gst_object_unref (dpad);
1414     goto unknown_type;
1415   }
1416
1417   /* 1.d sort some more. */
1418   g_signal_emit (G_OBJECT (dbin),
1419       gst_decode_bin_signals[SIGNAL_AUTOPLUG_SORT], 0, dpad, caps, factories,
1420       &result);
1421   if (result) {
1422     g_value_array_free (factories);
1423     factories = result;
1424   }
1425
1426   /* At this point we have a potential decoder, but we might not need it
1427    * if it doesn't match the output caps  */
1428   if (!dbin->expose_allstreams) {
1429     guint i;
1430     const GList *tmps;
1431     gboolean dontuse = FALSE;
1432
1433     GST_DEBUG ("Checking if we can abort early");
1434
1435     /* 1.e Do an early check to see if the candidates are potential decoders, but
1436      * due to the fact that they decode to a mediatype that is not final we don't
1437      * need them */
1438
1439     for (i = 0; i < factories->n_values && !dontuse; i++) {
1440       GstElementFactory *factory =
1441           g_value_get_object (g_value_array_get_nth (factories, i));
1442       GstCaps *tcaps;
1443
1444       /* We are only interested in skipping decoders */
1445       if (strstr (gst_element_factory_get_klass (factory), "Decoder")) {
1446
1447         GST_DEBUG ("Trying factory %s",
1448             gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
1449
1450         /* Check the source pad template caps to see if they match raw caps but don't match
1451          * our final caps*/
1452         for (tmps = gst_element_factory_get_static_pad_templates (factory);
1453             tmps && !dontuse; tmps = tmps->next) {
1454           GstStaticPadTemplate *st = (GstStaticPadTemplate *) tmps->data;
1455           if (st->direction != GST_PAD_SRC)
1456             continue;
1457           tcaps = gst_static_pad_template_get_caps (st);
1458
1459           apcontinue = TRUE;
1460
1461           /* Emit autoplug-continue to see if the caps are considered to be raw caps */
1462           g_signal_emit (G_OBJECT (dbin),
1463               gst_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE], 0, dpad, tcaps,
1464               &apcontinue);
1465
1466           /* If autoplug-continue returns TRUE and the caps are not final, don't use them */
1467           if (apcontinue && !are_final_caps (dbin, tcaps))
1468             dontuse = TRUE;
1469           gst_caps_unref (tcaps);
1470         }
1471       }
1472     }
1473
1474     if (dontuse) {
1475       gst_object_unref (dpad);
1476       goto discarded_type;
1477     }
1478   }
1479
1480   /* 1.f else continue autoplugging something from the list. */
1481   GST_LOG_OBJECT (pad, "Let's continue discovery on this pad");
1482   connect_pad (dbin, src, dpad, pad, caps, factories, chain);
1483
1484   gst_object_unref (dpad);
1485   g_value_array_free (factories);
1486
1487   return;
1488
1489 expose_pad:
1490   {
1491     GST_LOG_OBJECT (dbin, "Pad is final. autoplug-continue:%d", apcontinue);
1492     expose_pad (dbin, src, dpad, pad, caps, chain);
1493     gst_object_unref (dpad);
1494     return;
1495   }
1496
1497 discarded_type:
1498   {
1499     GST_LOG_OBJECT (pad, "Known type, but discarded because not final caps");
1500     chain->deadend = TRUE;
1501     chain->endcaps = gst_caps_ref (caps);
1502
1503     /* Try to expose anything */
1504     EXPOSE_LOCK (dbin);
1505     if (gst_decode_chain_is_complete (dbin->decode_chain)) {
1506       gst_decode_bin_expose (dbin);
1507     }
1508     EXPOSE_UNLOCK (dbin);
1509     do_async_done (dbin);
1510
1511     return;
1512   }
1513
1514 unknown_type:
1515   {
1516     GST_LOG_OBJECT (pad, "Unknown type, posting message and firing signal");
1517
1518     chain->deadend = TRUE;
1519     chain->endcaps = gst_caps_ref (caps);
1520
1521     gst_element_post_message (GST_ELEMENT_CAST (dbin),
1522         gst_missing_decoder_message_new (GST_ELEMENT_CAST (dbin), caps));
1523
1524     g_signal_emit (G_OBJECT (dbin),
1525         gst_decode_bin_signals[SIGNAL_UNKNOWN_TYPE], 0, pad, caps);
1526
1527     /* Try to expose anything */
1528     EXPOSE_LOCK (dbin);
1529     if (gst_decode_chain_is_complete (dbin->decode_chain)) {
1530       gst_decode_bin_expose (dbin);
1531     }
1532     EXPOSE_UNLOCK (dbin);
1533
1534     if (src == dbin->typefind) {
1535       gchar *desc;
1536
1537       if (caps && !gst_caps_is_empty (caps)) {
1538         desc = gst_pb_utils_get_decoder_description (caps);
1539         GST_ELEMENT_ERROR (dbin, STREAM, CODEC_NOT_FOUND,
1540             (_("A %s plugin is required to play this stream, "
1541                     "but not installed."), desc),
1542             ("No decoder to handle media type '%s'",
1543                 gst_structure_get_name (gst_caps_get_structure (caps, 0))));
1544         g_free (desc);
1545       } else {
1546         GST_ELEMENT_ERROR (dbin, STREAM, TYPE_NOT_FOUND,
1547             (_("Could not determine type of stream")),
1548             ("Stream caps %" GST_PTR_FORMAT, caps));
1549       }
1550       do_async_done (dbin);
1551     }
1552     return;
1553   }
1554 non_fixed:
1555   {
1556     GST_DEBUG_OBJECT (pad, "pad has non-fixed caps delay autoplugging");
1557     gst_object_unref (dpad);
1558     goto setup_caps_delay;
1559   }
1560 any_caps:
1561   {
1562     GST_WARNING_OBJECT (pad,
1563         "pad has ANY caps, not able to autoplug to anything");
1564     goto setup_caps_delay;
1565   }
1566 setup_caps_delay:
1567   {
1568     GstPendingPad *ppad;
1569
1570     /* connect to caps notification */
1571     CHAIN_MUTEX_LOCK (chain);
1572     GST_LOG_OBJECT (dbin, "Chain %p has now %d dynamic pads", chain,
1573         g_list_length (chain->pending_pads));
1574     ppad = g_slice_new0 (GstPendingPad);
1575     ppad->pad = gst_object_ref (pad);
1576     ppad->chain = chain;
1577     ppad->event_probe_id =
1578         gst_pad_add_probe (pad, GST_PROBE_TYPE_EVENT, pad_event_cb, ppad, NULL);
1579     chain->pending_pads = g_list_prepend (chain->pending_pads, ppad);
1580     g_signal_connect (G_OBJECT (pad), "notify::caps",
1581         G_CALLBACK (caps_notify_cb), chain);
1582     CHAIN_MUTEX_UNLOCK (chain);
1583     return;
1584   }
1585 }
1586
1587
1588 /* connect_pad:
1589  *
1590  * Try to connect the given pad to an element created from one of the factories,
1591  * and recursively.
1592  *
1593  * Note that dpad is ghosting pad, and so pad is linked; be sure to unset dpad's
1594  * target before trying to link pad.
1595  *
1596  * Returns TRUE if an element was properly created and linked
1597  */
1598 static gboolean
1599 connect_pad (GstDecodeBin * dbin, GstElement * src, GstDecodePad * dpad,
1600     GstPad * pad, GstCaps * caps, GValueArray * factories,
1601     GstDecodeChain * chain)
1602 {
1603   gboolean res = FALSE;
1604   GstPad *mqpad = NULL;
1605   gboolean is_demuxer = chain->parent && !chain->elements;      /* First pad after the demuxer */
1606
1607   g_return_val_if_fail (factories != NULL, FALSE);
1608   g_return_val_if_fail (factories->n_values > 0, FALSE);
1609
1610   GST_DEBUG_OBJECT (dbin, "pad %s:%s , chain:%p",
1611       GST_DEBUG_PAD_NAME (pad), chain);
1612
1613   /* 1. is element demuxer or parser */
1614   if (is_demuxer) {
1615     GST_LOG_OBJECT (src,
1616         "is a demuxer, connecting the pad through multiqueue '%s'",
1617         GST_OBJECT_NAME (chain->parent->multiqueue));
1618
1619     gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (dpad), NULL);
1620     if (!(mqpad = gst_decode_group_control_demuxer_pad (chain->parent, pad)))
1621       goto beach;
1622     src = chain->parent->multiqueue;
1623     pad = mqpad;
1624     gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (dpad), pad);
1625   }
1626
1627   /* 2. Try to create an element and link to it */
1628   while (factories->n_values > 0) {
1629     GstAutoplugSelectResult ret;
1630     GstElementFactory *factory;
1631     GstElement *element;
1632     GstPad *sinkpad;
1633     gboolean subtitle;
1634
1635     /* Set dpad target to pad again, it might've been unset
1636      * below but we came back here because something failed
1637      */
1638     gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (dpad), pad);
1639
1640     /* take first factory */
1641     factory = g_value_get_object (g_value_array_get_nth (factories, 0));
1642     /* Remove selected factory from the list. */
1643     g_value_array_remove (factories, 0);
1644
1645     /* If the factory is for a parser we first check if the factory
1646      * was already used for the current chain. If it was used already
1647      * we would otherwise create an infinite loop here because the
1648      * parser apparently accepts its own output as input.
1649      * This is only done for parsers because it's perfectly valid
1650      * to have other element classes after each other because a
1651      * parser is the only one that does not change the data. A
1652      * valid example for this would be multiple id3demux in a row.
1653      */
1654     if (strstr (gst_element_factory_get_klass (factory), "Parser")) {
1655       gboolean skip = FALSE;
1656       GList *l;
1657
1658       CHAIN_MUTEX_LOCK (chain);
1659       for (l = chain->elements; l; l = l->next) {
1660         GstElement *otherelement = GST_ELEMENT_CAST (l->data);
1661
1662         if (gst_element_get_factory (otherelement) == factory) {
1663           skip = TRUE;
1664           break;
1665         }
1666       }
1667       CHAIN_MUTEX_UNLOCK (chain);
1668       if (skip) {
1669         GST_DEBUG_OBJECT (dbin,
1670             "Skipping factory '%s' because it was already used in this chain",
1671             gst_plugin_feature_get_name (GST_PLUGIN_FEATURE_CAST (factory)));
1672         continue;
1673       }
1674     }
1675
1676     /* emit autoplug-select to see what we should do with it. */
1677     g_signal_emit (G_OBJECT (dbin),
1678         gst_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT],
1679         0, dpad, caps, factory, &ret);
1680
1681     switch (ret) {
1682       case GST_AUTOPLUG_SELECT_TRY:
1683         GST_DEBUG_OBJECT (dbin, "autoplug select requested try");
1684         break;
1685       case GST_AUTOPLUG_SELECT_EXPOSE:
1686         GST_DEBUG_OBJECT (dbin, "autoplug select requested expose");
1687         /* expose the pad, we don't have the source element */
1688         expose_pad (dbin, src, dpad, pad, caps, chain);
1689         res = TRUE;
1690         goto beach;
1691       case GST_AUTOPLUG_SELECT_SKIP:
1692         GST_DEBUG_OBJECT (dbin, "autoplug select requested skip");
1693         continue;
1694       default:
1695         GST_WARNING_OBJECT (dbin, "autoplug select returned unhandled %d", ret);
1696         break;
1697     }
1698
1699     /* 2.0. Unlink pad */
1700     gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (dpad), NULL);
1701
1702     /* 2.1. Try to create an element */
1703     if ((element = gst_element_factory_create (factory, NULL)) == NULL) {
1704       GST_WARNING_OBJECT (dbin, "Could not create an element from %s",
1705           gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
1706       continue;
1707     }
1708
1709     /* ... activate it ... We do this before adding it to the bin so that we
1710      * don't accidentally make it post error messages that will stop
1711      * everything. */
1712     if ((gst_element_set_state (element,
1713                 GST_STATE_READY)) == GST_STATE_CHANGE_FAILURE) {
1714       GST_WARNING_OBJECT (dbin, "Couldn't set %s to READY",
1715           GST_ELEMENT_NAME (element));
1716       gst_object_unref (element);
1717       continue;
1718     }
1719
1720     /* 2.3. Find its sink pad, this should work after activating it. */
1721     if (!(sinkpad = find_sink_pad (element))) {
1722       GST_WARNING_OBJECT (dbin, "Element %s doesn't have a sink pad",
1723           GST_ELEMENT_NAME (element));
1724       gst_element_set_state (element, GST_STATE_NULL);
1725       gst_object_unref (element);
1726       continue;
1727     }
1728
1729     /* 2.4 add it ... */
1730     if (!(gst_bin_add (GST_BIN_CAST (dbin), element))) {
1731       GST_WARNING_OBJECT (dbin, "Couldn't add %s to the bin",
1732           GST_ELEMENT_NAME (element));
1733       gst_object_unref (sinkpad);
1734       gst_element_set_state (element, GST_STATE_NULL);
1735       gst_object_unref (element);
1736       continue;
1737     }
1738
1739     /* 2.5 ...and try to link */
1740     if ((gst_pad_link (pad, sinkpad)) != GST_PAD_LINK_OK) {
1741       GST_WARNING_OBJECT (dbin, "Link failed on pad %s:%s",
1742           GST_DEBUG_PAD_NAME (sinkpad));
1743       gst_element_set_state (element, GST_STATE_NULL);
1744       gst_object_unref (sinkpad);
1745       gst_bin_remove (GST_BIN (dbin), element);
1746       continue;
1747     }
1748     gst_object_unref (sinkpad);
1749     GST_LOG_OBJECT (dbin, "linked on pad %s:%s", GST_DEBUG_PAD_NAME (pad));
1750
1751     CHAIN_MUTEX_LOCK (chain);
1752     chain->elements =
1753         g_list_prepend (chain->elements, gst_object_ref (element));
1754     chain->demuxer = is_demuxer_element (element);
1755     CHAIN_MUTEX_UNLOCK (chain);
1756
1757     /* link this element further */
1758     connect_element (dbin, element, chain);
1759
1760     /* try to configure the subtitle encoding property when we can */
1761     if (g_object_class_find_property (G_OBJECT_GET_CLASS (element),
1762             "subtitle-encoding")) {
1763       SUBTITLE_LOCK (dbin);
1764       GST_DEBUG_OBJECT (dbin,
1765           "setting subtitle-encoding=%s to element", dbin->encoding);
1766       g_object_set (G_OBJECT (element), "subtitle-encoding", dbin->encoding,
1767           NULL);
1768       SUBTITLE_UNLOCK (dbin);
1769       subtitle = TRUE;
1770     } else
1771       subtitle = FALSE;
1772
1773     /* Bring the element to the state of the parent */
1774     if ((gst_element_set_state (element,
1775                 GST_STATE_PAUSED)) == GST_STATE_CHANGE_FAILURE) {
1776       GstElement *tmp = NULL;
1777
1778       GST_WARNING_OBJECT (dbin, "Couldn't set %s to PAUSED",
1779           GST_ELEMENT_NAME (element));
1780
1781       /* Remove all elements in this chain that were just added. No
1782        * other thread could've added elements in the meantime */
1783       CHAIN_MUTEX_LOCK (chain);
1784       do {
1785         GList *l;
1786
1787         tmp = chain->elements->data;
1788
1789         /* Disconnect any signal handlers that might be connected
1790          * in connect_element() or analyze_pad() */
1791         g_signal_handlers_disconnect_by_func (tmp, pad_added_cb, chain);
1792         g_signal_handlers_disconnect_by_func (tmp, pad_removed_cb, chain);
1793         g_signal_handlers_disconnect_by_func (tmp, no_more_pads_cb, chain);
1794
1795         for (l = chain->pending_pads; l;) {
1796           GstPendingPad *pp = l->data;
1797           GList *n;
1798
1799           if (GST_PAD_PARENT (pp->pad) != tmp) {
1800             l = l->next;
1801             continue;
1802           }
1803
1804           g_signal_handlers_disconnect_by_func (pp->pad, caps_notify_cb, chain);
1805           gst_pad_remove_probe (pp->pad, pp->event_probe_id);
1806           gst_object_unref (pp->pad);
1807           g_slice_free (GstPendingPad, pp);
1808
1809           /* Remove element from the list, update list head and go to the
1810            * next element in the list */
1811           n = l->next;
1812           chain->pending_pads = g_list_delete_link (chain->pending_pads, l);
1813           l = n;
1814         }
1815
1816         gst_bin_remove (GST_BIN (dbin), tmp);
1817         gst_element_set_state (tmp, GST_STATE_NULL);
1818
1819         gst_object_unref (tmp);
1820         chain->elements = g_list_delete_link (chain->elements, chain->elements);
1821       } while (tmp != element);
1822       CHAIN_MUTEX_UNLOCK (chain);
1823
1824       continue;
1825     }
1826     if (subtitle) {
1827       SUBTITLE_LOCK (dbin);
1828       /* we added the element now, add it to the list of subtitle-encoding
1829        * elements when we can set the property */
1830       dbin->subtitles = g_list_prepend (dbin->subtitles, element);
1831       SUBTITLE_UNLOCK (dbin);
1832     }
1833
1834     res = TRUE;
1835     break;
1836   }
1837
1838 beach:
1839   if (mqpad)
1840     gst_object_unref (mqpad);
1841
1842   return res;
1843 }
1844
1845 static GstCaps *
1846 get_pad_caps (GstPad * pad)
1847 {
1848   GstCaps *caps;
1849
1850   /* first check the pad caps, if this is set, we are positively sure it is
1851    * fixed and exactly what the element will produce. */
1852   caps = gst_pad_get_current_caps (pad);
1853
1854   /* then use the getcaps function if we don't have caps. These caps might not
1855    * be fixed in some cases, in which case analyze_new_pad will set up a
1856    * notify::caps signal to continue autoplugging. */
1857   if (caps == NULL)
1858     caps = gst_pad_get_caps (pad, NULL);
1859
1860   return caps;
1861 }
1862
1863 static gboolean
1864 connect_element (GstDecodeBin * dbin, GstElement * element,
1865     GstDecodeChain * chain)
1866 {
1867   GList *pads;
1868   gboolean res = TRUE;
1869   gboolean dynamic = FALSE;
1870   GList *to_connect = NULL;
1871
1872   GST_DEBUG_OBJECT (dbin, "Attempting to connect element %s [chain:%p] further",
1873       GST_ELEMENT_NAME (element), chain);
1874
1875   /* 1. Loop over pad templates, grabbing existing pads along the way */
1876   for (pads = GST_ELEMENT_GET_CLASS (element)->padtemplates; pads;
1877       pads = g_list_next (pads)) {
1878     GstPadTemplate *templ = GST_PAD_TEMPLATE (pads->data);
1879     const gchar *templ_name;
1880
1881     /* we are only interested in source pads */
1882     if (GST_PAD_TEMPLATE_DIRECTION (templ) != GST_PAD_SRC)
1883       continue;
1884
1885     templ_name = GST_PAD_TEMPLATE_NAME_TEMPLATE (templ);
1886     GST_DEBUG_OBJECT (dbin, "got a source pad template %s", templ_name);
1887
1888     /* figure out what kind of pad this is */
1889     switch (GST_PAD_TEMPLATE_PRESENCE (templ)) {
1890       case GST_PAD_ALWAYS:
1891       {
1892         /* get the pad that we need to autoplug */
1893         GstPad *pad = gst_element_get_static_pad (element, templ_name);
1894
1895         if (pad) {
1896           GST_DEBUG_OBJECT (dbin, "got the pad for always template %s",
1897               templ_name);
1898           /* here is the pad, we need to autoplug it */
1899           to_connect = g_list_prepend (to_connect, pad);
1900         } else {
1901           /* strange, pad is marked as always but it's not
1902            * there. Fix the element */
1903           GST_WARNING_OBJECT (dbin,
1904               "could not get the pad for always template %s", templ_name);
1905         }
1906         break;
1907       }
1908       case GST_PAD_SOMETIMES:
1909       {
1910         /* try to get the pad to see if it is already created or
1911          * not */
1912         GstPad *pad = gst_element_get_static_pad (element, templ_name);
1913
1914         if (pad) {
1915           GST_DEBUG_OBJECT (dbin, "got the pad for sometimes template %s",
1916               templ_name);
1917           /* the pad is created, we need to autoplug it */
1918           to_connect = g_list_prepend (to_connect, pad);
1919         } else {
1920           GST_DEBUG_OBJECT (dbin,
1921               "did not get the sometimes pad of template %s", templ_name);
1922           /* we have an element that will create dynamic pads */
1923           dynamic = TRUE;
1924         }
1925         break;
1926       }
1927       case GST_PAD_REQUEST:
1928         /* ignore request pads */
1929         GST_DEBUG_OBJECT (dbin, "ignoring request padtemplate %s", templ_name);
1930         break;
1931     }
1932   }
1933
1934   /* 2. if there are more potential pads, connect to relevant signals */
1935   if (dynamic) {
1936     GST_LOG_OBJECT (dbin, "Adding signals to element %s in chain %p",
1937         GST_ELEMENT_NAME (element), chain);
1938     g_signal_connect (G_OBJECT (element), "pad-added",
1939         G_CALLBACK (pad_added_cb), chain);
1940     g_signal_connect (G_OBJECT (element), "pad-removed",
1941         G_CALLBACK (pad_removed_cb), chain);
1942     g_signal_connect (G_OBJECT (element), "no-more-pads",
1943         G_CALLBACK (no_more_pads_cb), chain);
1944   }
1945
1946   /* 3. for every available pad, connect it */
1947   for (pads = to_connect; pads; pads = g_list_next (pads)) {
1948     GstPad *pad = GST_PAD_CAST (pads->data);
1949     GstCaps *caps;
1950
1951     caps = get_pad_caps (pad);
1952     analyze_new_pad (dbin, element, pad, caps, chain);
1953     if (caps)
1954       gst_caps_unref (caps);
1955
1956     gst_object_unref (pad);
1957   }
1958   g_list_free (to_connect);
1959
1960   return res;
1961 }
1962
1963 /* expose_pad:
1964  *
1965  * Expose the given pad on the chain as a decoded pad.
1966  */
1967 static void
1968 expose_pad (GstDecodeBin * dbin, GstElement * src, GstDecodePad * dpad,
1969     GstPad * pad, GstCaps * caps, GstDecodeChain * chain)
1970 {
1971   GstPad *mqpad = NULL;
1972
1973   GST_DEBUG_OBJECT (dbin, "pad %s:%s, chain:%p",
1974       GST_DEBUG_PAD_NAME (pad), chain);
1975
1976   /* If this is the first pad for this chain, there are no other elements
1977    * and the source element is not the multiqueue we must link through the
1978    * multiqueue.
1979    *
1980    * This is the case if a demuxer directly exposed a raw pad.
1981    */
1982   if (chain->parent && !chain->elements && src != chain->parent->multiqueue) {
1983     GST_LOG_OBJECT (src, "connecting the pad through multiqueue");
1984
1985     gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (dpad), NULL);
1986     if (!(mqpad = gst_decode_group_control_demuxer_pad (chain->parent, pad)))
1987       goto beach;
1988     pad = mqpad;
1989     gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (dpad), pad);
1990   }
1991
1992   gst_decode_pad_activate (dpad, chain);
1993   chain->endpad = gst_object_ref (dpad);
1994   chain->endcaps = gst_caps_ref (caps);
1995
1996   EXPOSE_LOCK (dbin);
1997   if (gst_decode_chain_is_complete (dbin->decode_chain)) {
1998     gst_decode_bin_expose (dbin);
1999   }
2000   EXPOSE_UNLOCK (dbin);
2001
2002   if (mqpad)
2003     gst_object_unref (mqpad);
2004
2005 beach:
2006   return;
2007 }
2008
2009 /* check_upstream_seekable:
2010  *
2011  * Check if upstream is seekable.
2012  */
2013 static void
2014 check_upstream_seekable (GstDecodeBin * dbin, GstPad * pad)
2015 {
2016   GstQuery *query;
2017   gint64 start = -1, stop = -1;
2018
2019   dbin->upstream_seekable = FALSE;
2020
2021   query = gst_query_new_seeking (GST_FORMAT_BYTES);
2022   if (!gst_pad_peer_query (pad, query)) {
2023     GST_DEBUG_OBJECT (dbin, "seeking query failed");
2024     gst_query_unref (query);
2025     return;
2026   }
2027
2028   gst_query_parse_seeking (query, NULL, &dbin->upstream_seekable,
2029       &start, &stop);
2030
2031   gst_query_unref (query);
2032
2033   /* try harder to query upstream size if we didn't get it the first time */
2034   if (dbin->upstream_seekable && stop == -1) {
2035     GST_DEBUG_OBJECT (dbin, "doing duration query to fix up unset stop");
2036     gst_pad_query_peer_duration (pad, GST_FORMAT_BYTES, &stop);
2037   }
2038
2039   /* if upstream doesn't know the size, it's likely that it's not seekable in
2040    * practice even if it technically may be seekable */
2041   if (dbin->upstream_seekable && (start != 0 || stop <= start)) {
2042     GST_DEBUG_OBJECT (dbin, "seekable but unknown start/stop -> disable");
2043     dbin->upstream_seekable = FALSE;
2044   }
2045
2046   GST_DEBUG_OBJECT (dbin, "upstream seekable: %d", dbin->upstream_seekable);
2047 }
2048
2049 static void
2050 type_found (GstElement * typefind, guint probability,
2051     GstCaps * caps, GstDecodeBin * decode_bin)
2052 {
2053   GstPad *pad, *sink_pad;
2054
2055   GST_DEBUG_OBJECT (decode_bin, "typefind found caps %" GST_PTR_FORMAT, caps);
2056
2057   /* If the typefinder (but not something else) finds text/plain - i.e. that's
2058    * the top-level type of the file - then error out.
2059    */
2060   if (gst_structure_has_name (gst_caps_get_structure (caps, 0), "text/plain")) {
2061     GST_ELEMENT_ERROR (decode_bin, STREAM, WRONG_TYPE,
2062         (_("This appears to be a text file")),
2063         ("decodebin cannot decode plain text files"));
2064     goto exit;
2065   }
2066
2067   /* FIXME: we can only deal with one type, we don't yet support dynamically changing
2068    * caps from the typefind element */
2069   if (decode_bin->have_type || decode_bin->decode_chain)
2070     goto exit;
2071
2072   decode_bin->have_type = TRUE;
2073
2074   pad = gst_element_get_static_pad (typefind, "src");
2075   sink_pad = gst_element_get_static_pad (typefind, "sink");
2076
2077   /* if upstream is seekable we can safely set a limit in time to the queues so
2078    * that streams at low bitrates can preroll */
2079   check_upstream_seekable (decode_bin, sink_pad);
2080
2081   /* need some lock here to prevent race with shutdown state change
2082    * which might yank away e.g. decode_chain while building stuff here.
2083    * In typical cases, STREAM_LOCK is held and handles that, it need not
2084    * be held (if called from a proxied setcaps), so grab it anyway */
2085   GST_PAD_STREAM_LOCK (sink_pad);
2086   decode_bin->decode_chain = gst_decode_chain_new (decode_bin, NULL, pad);
2087   analyze_new_pad (decode_bin, typefind, pad, caps, decode_bin->decode_chain);
2088   GST_PAD_STREAM_UNLOCK (sink_pad);
2089
2090   gst_object_unref (sink_pad);
2091   gst_object_unref (pad);
2092
2093 exit:
2094   return;
2095 }
2096
2097 static GstProbeReturn
2098 pad_event_cb (GstPad * pad, GstProbeType type, gpointer type_data,
2099     gpointer data)
2100 {
2101   GstEvent *event = type_data;
2102   GstPendingPad *ppad = (GstPendingPad *) data;
2103   GstDecodeChain *chain = ppad->chain;
2104   GstDecodeBin *dbin = chain->dbin;
2105
2106   g_assert (ppad);
2107   g_assert (chain);
2108   g_assert (dbin);
2109   switch (GST_EVENT_TYPE (event)) {
2110     case GST_EVENT_EOS:
2111       GST_DEBUG_OBJECT (dbin, "Received EOS on a non final pad, this stream "
2112           "ended too early");
2113       chain->deadend = TRUE;
2114       /* we don't set the endcaps because NULL endcaps means early EOS */
2115       EXPOSE_LOCK (dbin);
2116       if (gst_decode_chain_is_complete (dbin->decode_chain))
2117         gst_decode_bin_expose (dbin);
2118       EXPOSE_UNLOCK (dbin);
2119       break;
2120     default:
2121       break;
2122   }
2123   return GST_PROBE_OK;
2124 }
2125
2126 static void
2127 pad_added_cb (GstElement * element, GstPad * pad, GstDecodeChain * chain)
2128 {
2129   GstCaps *caps;
2130   GstDecodeBin *dbin;
2131
2132   dbin = chain->dbin;
2133
2134   GST_DEBUG_OBJECT (pad, "pad added, chain:%p", chain);
2135
2136   caps = get_pad_caps (pad);
2137   analyze_new_pad (dbin, element, pad, caps, chain);
2138   if (caps)
2139     gst_caps_unref (caps);
2140
2141   EXPOSE_LOCK (dbin);
2142   if (gst_decode_chain_is_complete (dbin->decode_chain)) {
2143     GST_LOG_OBJECT (dbin,
2144         "That was the last dynamic object, now attempting to expose the group");
2145     if (!gst_decode_bin_expose (dbin))
2146       GST_WARNING_OBJECT (dbin, "Couldn't expose group");
2147   }
2148   EXPOSE_UNLOCK (dbin);
2149 }
2150
2151 static void
2152 pad_removed_cb (GstElement * element, GstPad * pad, GstDecodeChain * chain)
2153 {
2154   GList *l;
2155
2156   GST_LOG_OBJECT (pad, "pad removed, chain:%p", chain);
2157
2158   /* In fact, we don't have to do anything here, the active group will be
2159    * removed when the group's multiqueue is drained */
2160   CHAIN_MUTEX_LOCK (chain);
2161   for (l = chain->pending_pads; l; l = l->next) {
2162     GstPendingPad *ppad = l->data;
2163     GstPad *opad = ppad->pad;
2164
2165     if (pad == opad) {
2166       g_signal_handlers_disconnect_by_func (pad, caps_notify_cb, chain);
2167       gst_pending_pad_free (ppad);
2168       chain->pending_pads = g_list_delete_link (chain->pending_pads, l);
2169       break;
2170     }
2171   }
2172   CHAIN_MUTEX_UNLOCK (chain);
2173 }
2174
2175 static void
2176 no_more_pads_cb (GstElement * element, GstDecodeChain * chain)
2177 {
2178   GstDecodeGroup *group = NULL;
2179
2180   GST_LOG_OBJECT (element, "got no more pads");
2181
2182   CHAIN_MUTEX_LOCK (chain);
2183   if (!chain->elements || (GstElement *) chain->elements->data != element) {
2184     GST_LOG_OBJECT (chain->dbin, "no-more-pads from old chain element '%s'",
2185         GST_OBJECT_NAME (element));
2186     CHAIN_MUTEX_UNLOCK (chain);
2187     return;
2188   } else if (!chain->demuxer) {
2189     GST_LOG_OBJECT (chain->dbin, "no-more-pads from a non-demuxer element '%s'",
2190         GST_OBJECT_NAME (element));
2191     CHAIN_MUTEX_UNLOCK (chain);
2192     return;
2193   }
2194
2195   /* when we received no_more_pads, we can complete the pads of the chain */
2196   if (!chain->next_groups && chain->active_group) {
2197     group = chain->active_group;
2198   } else if (chain->next_groups) {
2199     group = chain->next_groups->data;
2200   }
2201   if (!group) {
2202     GST_ERROR_OBJECT (chain->dbin, "can't find group for element");
2203     CHAIN_MUTEX_UNLOCK (chain);
2204     return;
2205   }
2206
2207   GST_DEBUG_OBJECT (element, "Setting group %p to complete", group);
2208
2209   group->no_more_pads = TRUE;
2210   /* this group has prerolled enough to not need more pads,
2211    * we can probably set its buffering state to playing now */
2212   GST_DEBUG_OBJECT (group->dbin, "Setting group %p multiqueue to "
2213       "'playing' buffering mode", group);
2214   decodebin_set_queue_size (group->dbin, group->multiqueue, FALSE);
2215   CHAIN_MUTEX_UNLOCK (chain);
2216
2217   EXPOSE_LOCK (chain->dbin);
2218   if (gst_decode_chain_is_complete (chain->dbin->decode_chain)) {
2219     gst_decode_bin_expose (chain->dbin);
2220   }
2221   EXPOSE_UNLOCK (chain->dbin);
2222 }
2223
2224 static void
2225 caps_notify_cb (GstPad * pad, GParamSpec * unused, GstDecodeChain * chain)
2226 {
2227   GstElement *element;
2228   GList *l;
2229
2230   GST_LOG_OBJECT (pad, "Notified caps for pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2231
2232   /* Disconnect this; if we still need it, we'll reconnect to this in
2233    * analyze_new_pad */
2234   g_signal_handlers_disconnect_by_func (pad, caps_notify_cb, chain);
2235
2236   element = GST_ELEMENT_CAST (gst_pad_get_parent (pad));
2237
2238   CHAIN_MUTEX_LOCK (chain);
2239   for (l = chain->pending_pads; l; l = l->next) {
2240     GstPendingPad *ppad = l->data;
2241     if (ppad->pad == pad) {
2242       gst_pending_pad_free (ppad);
2243       chain->pending_pads = g_list_delete_link (chain->pending_pads, l);
2244       break;
2245     }
2246   }
2247   CHAIN_MUTEX_UNLOCK (chain);
2248
2249   pad_added_cb (element, pad, chain);
2250
2251   gst_object_unref (element);
2252 }
2253
2254 /* Decide whether an element is a demuxer based on the
2255  * klass and number/type of src pad templates it has */
2256 static gboolean
2257 is_demuxer_element (GstElement * srcelement)
2258 {
2259   GstElementFactory *srcfactory;
2260   GstElementClass *elemclass;
2261   GList *walk;
2262   const gchar *klass;
2263   gint potential_src_pads = 0;
2264
2265   srcfactory = gst_element_get_factory (srcelement);
2266   klass = gst_element_factory_get_klass (srcfactory);
2267
2268   /* Can't be a demuxer unless it has Demux in the klass name */
2269   if (!strstr (klass, "Demux"))
2270     return FALSE;
2271
2272   /* Walk the src pad templates and count how many the element
2273    * might produce */
2274   elemclass = GST_ELEMENT_GET_CLASS (srcelement);
2275
2276   walk = gst_element_class_get_pad_template_list (elemclass);
2277   while (walk != NULL) {
2278     GstPadTemplate *templ;
2279
2280     templ = (GstPadTemplate *) walk->data;
2281     if (GST_PAD_TEMPLATE_DIRECTION (templ) == GST_PAD_SRC) {
2282       switch (GST_PAD_TEMPLATE_PRESENCE (templ)) {
2283         case GST_PAD_ALWAYS:
2284         case GST_PAD_SOMETIMES:
2285           if (strstr (GST_PAD_TEMPLATE_NAME_TEMPLATE (templ), "%"))
2286             potential_src_pads += 2;    /* Might make multiple pads */
2287           else
2288             potential_src_pads += 1;
2289           break;
2290         case GST_PAD_REQUEST:
2291           potential_src_pads += 2;
2292           break;
2293       }
2294     }
2295     walk = g_list_next (walk);
2296   }
2297
2298   if (potential_src_pads < 2)
2299     return FALSE;
2300
2301   return TRUE;
2302 }
2303
2304 /* Returns TRUE if the caps are compatible with the caps specified in the 'caps'
2305  * property (which by default are the raw caps)
2306  *
2307  * The decodebin_lock should be taken !
2308  */
2309 static gboolean
2310 are_final_caps (GstDecodeBin * dbin, GstCaps * caps)
2311 {
2312   gboolean res;
2313
2314   GST_LOG_OBJECT (dbin, "Checking with caps %" GST_PTR_FORMAT, caps);
2315
2316   /* lock for getting the caps */
2317   GST_OBJECT_LOCK (dbin);
2318   res = gst_caps_can_intersect (dbin->caps, caps);
2319   GST_OBJECT_UNLOCK (dbin);
2320
2321   GST_LOG_OBJECT (dbin, "Caps are %sfinal caps", res ? "" : "not ");
2322
2323   return res;
2324 }
2325
2326 /****
2327  * GstDecodeChain functions
2328  ****/
2329
2330 /* gst_decode_chain_get_current_group:
2331  *
2332  * Returns the current group of this chain, to which
2333  * new chains should be attached or NULL if the last
2334  * group didn't have no-more-pads.
2335  *
2336  * Not MT-safe: Call with parent chain lock!
2337  */
2338 static GstDecodeGroup *
2339 gst_decode_chain_get_current_group (GstDecodeChain * chain)
2340 {
2341   GstDecodeGroup *group;
2342
2343   if (!chain->next_groups && chain->active_group
2344       && chain->active_group->overrun && !chain->active_group->no_more_pads) {
2345     GST_WARNING_OBJECT (chain->dbin,
2346         "Currently active group %p is exposed"
2347         " and wants to add a new pad without having signaled no-more-pads",
2348         chain->active_group);
2349     return NULL;
2350   }
2351
2352   if (chain->next_groups && (group = chain->next_groups->data) && group->overrun
2353       && !group->no_more_pads) {
2354     GST_WARNING_OBJECT (chain->dbin,
2355         "Currently newest pending group %p "
2356         "had overflow but didn't signal no-more-pads", group);
2357     return NULL;
2358   }
2359
2360   /* Now we know that we can really return something useful */
2361   if (!chain->active_group) {
2362     chain->active_group = group = gst_decode_group_new (chain->dbin, chain);
2363   } else if (!chain->active_group->overrun
2364       && !chain->active_group->no_more_pads) {
2365     group = chain->active_group;
2366   } else if (chain->next_groups && (group = chain->next_groups->data)
2367       && !group->overrun && !group->no_more_pads) {
2368     /* group = chain->next_groups->data */
2369   } else {
2370     group = gst_decode_group_new (chain->dbin, chain);
2371     chain->next_groups = g_list_prepend (chain->next_groups, group);
2372   }
2373
2374   return group;
2375 }
2376
2377 static void gst_decode_group_free_internal (GstDecodeGroup * group,
2378     gboolean hide);
2379
2380 static void
2381 gst_decode_chain_free_internal (GstDecodeChain * chain, gboolean hide)
2382 {
2383   GList *l;
2384
2385   CHAIN_MUTEX_LOCK (chain);
2386
2387   GST_DEBUG_OBJECT (chain->dbin, "%s chain %p", (hide ? "Hiding" : "Freeing"),
2388       chain);
2389
2390   if (chain->active_group) {
2391     gst_decode_group_free_internal (chain->active_group, hide);
2392     if (!hide)
2393       chain->active_group = NULL;
2394   }
2395
2396   for (l = chain->next_groups; l; l = l->next) {
2397     gst_decode_group_free_internal ((GstDecodeGroup *) l->data, hide);
2398     if (!hide)
2399       l->data = NULL;
2400   }
2401   if (!hide) {
2402     g_list_free (chain->next_groups);
2403     chain->next_groups = NULL;
2404   }
2405
2406   if (!hide) {
2407     for (l = chain->old_groups; l; l = l->next) {
2408       GstDecodeGroup *group = l->data;
2409
2410       gst_decode_group_free (group);
2411     }
2412     g_list_free (chain->old_groups);
2413     chain->old_groups = NULL;
2414   }
2415
2416   for (l = chain->pending_pads; l; l = l->next) {
2417     GstPendingPad *ppad = l->data;
2418     GstPad *pad = ppad->pad;
2419
2420     g_signal_handlers_disconnect_by_func (pad, caps_notify_cb, chain);
2421     gst_pending_pad_free (ppad);
2422     l->data = NULL;
2423   }
2424   g_list_free (chain->pending_pads);
2425   chain->pending_pads = NULL;
2426
2427   for (l = chain->elements; l; l = l->next) {
2428     GstElement *element = GST_ELEMENT (l->data);
2429
2430     g_signal_handlers_disconnect_by_func (element, pad_added_cb, chain);
2431     g_signal_handlers_disconnect_by_func (element, pad_removed_cb, chain);
2432     g_signal_handlers_disconnect_by_func (element, no_more_pads_cb, chain);
2433
2434     if (GST_OBJECT_PARENT (element) == GST_OBJECT_CAST (chain->dbin))
2435       gst_bin_remove (GST_BIN_CAST (chain->dbin), element);
2436     if (!hide) {
2437       gst_element_set_state (element, GST_STATE_NULL);
2438     }
2439
2440     SUBTITLE_LOCK (chain->dbin);
2441     /* remove possible subtitle element */
2442     chain->dbin->subtitles = g_list_remove (chain->dbin->subtitles, element);
2443     SUBTITLE_UNLOCK (chain->dbin);
2444
2445     if (!hide) {
2446       gst_object_unref (element);
2447       l->data = NULL;
2448     }
2449   }
2450   if (!hide) {
2451     g_list_free (chain->elements);
2452     chain->elements = NULL;
2453   }
2454
2455   if (chain->endpad) {
2456     if (chain->endpad->exposed) {
2457       gst_element_remove_pad (GST_ELEMENT_CAST (chain->dbin),
2458           GST_PAD_CAST (chain->endpad));
2459     }
2460
2461     gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (chain->endpad), NULL);
2462     chain->endpad->exposed = FALSE;
2463     if (!hide) {
2464       gst_object_unref (chain->endpad);
2465       chain->endpad = NULL;
2466     }
2467   }
2468
2469   if (chain->pad) {
2470     gst_object_unref (chain->pad);
2471     chain->pad = NULL;
2472   }
2473
2474   if (chain->endcaps) {
2475     gst_caps_unref (chain->endcaps);
2476     chain->endcaps = NULL;
2477   }
2478
2479   GST_DEBUG_OBJECT (chain->dbin, "%s chain %p", (hide ? "Hidden" : "Freed"),
2480       chain);
2481   CHAIN_MUTEX_UNLOCK (chain);
2482   if (!hide) {
2483     g_mutex_free (chain->lock);
2484     g_slice_free (GstDecodeChain, chain);
2485   }
2486 }
2487
2488 /* gst_decode_chain_free:
2489  *
2490  * Completely frees and removes the chain and all
2491  * child groups from decodebin.
2492  *
2493  * MT-safe, don't hold the chain lock or any child chain's lock
2494  * when calling this!
2495  */
2496 static void
2497 gst_decode_chain_free (GstDecodeChain * chain)
2498 {
2499   gst_decode_chain_free_internal (chain, FALSE);
2500 }
2501
2502 /* gst_decode_chain_new:
2503  *
2504  * Creates a new decode chain and initializes it.
2505  *
2506  * It's up to the caller to add it to the list of child chains of
2507  * a group!
2508  */
2509 static GstDecodeChain *
2510 gst_decode_chain_new (GstDecodeBin * dbin, GstDecodeGroup * parent,
2511     GstPad * pad)
2512 {
2513   GstDecodeChain *chain = g_slice_new0 (GstDecodeChain);
2514
2515   GST_DEBUG_OBJECT (dbin, "Creating new chain %p with parent group %p", chain,
2516       parent);
2517
2518   chain->dbin = dbin;
2519   chain->parent = parent;
2520   chain->lock = g_mutex_new ();
2521   chain->pad = gst_object_ref (pad);
2522
2523   return chain;
2524 }
2525
2526 /****
2527  * GstDecodeGroup functions
2528  ****/
2529
2530 /* The overrun callback is used to expose groups that have not yet had their
2531  * no_more_pads called while the (large) multiqueue overflowed. When this
2532  * happens we must assume that the no_more_pads will not arrive anymore and we
2533  * must expose the pads that we have.
2534  */
2535 static void
2536 multi_queue_overrun_cb (GstElement * queue, GstDecodeGroup * group)
2537 {
2538   GstDecodeBin *dbin;
2539
2540   dbin = group->dbin;
2541
2542   GST_LOG_OBJECT (dbin, "multiqueue '%s' (%p) is full", GST_OBJECT_NAME (queue),
2543       queue);
2544
2545   group->overrun = TRUE;
2546
2547   /* FIXME: We should make sure that everything gets exposed now
2548    * even if child chains are not complete because the will never
2549    * be complete! Ignore any non-complete chains when exposing
2550    * and never expose them later
2551    */
2552
2553   EXPOSE_LOCK (dbin);
2554   if (gst_decode_chain_is_complete (dbin->decode_chain)) {
2555     if (!gst_decode_bin_expose (dbin))
2556       GST_WARNING_OBJECT (dbin, "Couldn't expose group");
2557   }
2558   EXPOSE_UNLOCK (group->dbin);
2559 }
2560
2561 static void
2562 gst_decode_group_free_internal (GstDecodeGroup * group, gboolean hide)
2563 {
2564   GList *l;
2565
2566   GST_DEBUG_OBJECT (group->dbin, "%s group %p", (hide ? "Hiding" : "Freeing"),
2567       group);
2568   for (l = group->children; l; l = l->next) {
2569     GstDecodeChain *chain = (GstDecodeChain *) l->data;
2570
2571     gst_decode_chain_free_internal (chain, hide);
2572     if (!hide)
2573       l->data = NULL;
2574   }
2575   if (!hide) {
2576     g_list_free (group->children);
2577     group->children = NULL;
2578   }
2579
2580   if (!hide) {
2581     for (l = group->reqpads; l; l = l->next) {
2582       GstPad *pad = l->data;
2583
2584       gst_element_release_request_pad (group->multiqueue, pad);
2585       gst_object_unref (pad);
2586       l->data = NULL;
2587     }
2588     g_list_free (group->reqpads);
2589     group->reqpads = NULL;
2590   }
2591
2592   if (group->multiqueue) {
2593     if (group->overrunsig) {
2594       g_signal_handler_disconnect (group->multiqueue, group->overrunsig);
2595       group->overrunsig = 0;
2596     }
2597
2598     if (GST_OBJECT_PARENT (group->multiqueue) == GST_OBJECT_CAST (group->dbin))
2599       gst_bin_remove (GST_BIN_CAST (group->dbin), group->multiqueue);
2600     if (!hide) {
2601       gst_element_set_state (group->multiqueue, GST_STATE_NULL);
2602       gst_object_unref (group->multiqueue);
2603       group->multiqueue = NULL;
2604     }
2605   }
2606
2607   GST_DEBUG_OBJECT (group->dbin, "%s group %p", (hide ? "Hided" : "Freed"),
2608       group);
2609   if (!hide)
2610     g_slice_free (GstDecodeGroup, group);
2611 }
2612
2613 /* gst_decode_group_free:
2614  *
2615  * Completely frees and removes the decode group and all
2616  * it's children.
2617  *
2618  * Never call this from any streaming thread!
2619  *
2620  * Not MT-safe, call with parent's chain lock!
2621  */
2622 static void
2623 gst_decode_group_free (GstDecodeGroup * group)
2624 {
2625   gst_decode_group_free_internal (group, FALSE);
2626 }
2627
2628 /* gst_decode_group_hide:
2629  *
2630  * Hide the decode group only, this means that
2631  * all child endpads are removed from decodebin
2632  * and all signals are unconnected.
2633  *
2634  * No element is set to NULL state and completely
2635  * unrefed here.
2636  *
2637  * Can be called from streaming threads.
2638  *
2639  * Not MT-safe, call with parent's chain lock!
2640  */
2641 static void
2642 gst_decode_group_hide (GstDecodeGroup * group)
2643 {
2644   gst_decode_group_free_internal (group, TRUE);
2645 }
2646
2647 /* configure queue sizes, this depends on the buffering method and if we are
2648  * playing or prerolling. */
2649 static void
2650 decodebin_set_queue_size (GstDecodeBin * dbin, GstElement * multiqueue,
2651     gboolean preroll)
2652 {
2653   guint max_bytes, max_buffers;
2654   guint64 max_time;
2655
2656   if (preroll || dbin->use_buffering) {
2657     /* takes queue limits, initially we only queue up up to the max bytes limit,
2658      * with a default of 2MB. we use the same values for buffering mode. */
2659     if ((max_bytes = dbin->max_size_bytes) == 0)
2660       max_bytes = AUTO_PREROLL_SIZE_BYTES;
2661     if ((max_buffers = dbin->max_size_buffers) == 0)
2662       max_buffers = AUTO_PREROLL_SIZE_BUFFERS;
2663     if ((max_time = dbin->max_size_time) == 0)
2664       max_time = dbin->upstream_seekable ? AUTO_PREROLL_SEEKABLE_SIZE_TIME :
2665           AUTO_PREROLL_NOT_SEEKABLE_SIZE_TIME;
2666   } else {
2667     /* update runtime limits. At runtime, we try to keep the amount of buffers
2668      * in the queues as low as possible (but at least 5 buffers). */
2669     if ((max_bytes = dbin->max_size_bytes) == 0)
2670       max_bytes = AUTO_PLAY_SIZE_BYTES;
2671     if ((max_buffers = dbin->max_size_buffers) == 0)
2672       max_buffers = AUTO_PLAY_SIZE_BUFFERS;
2673     if ((max_time = dbin->max_size_time) == 0)
2674       max_time = AUTO_PLAY_SIZE_TIME;
2675   }
2676
2677   g_object_set (multiqueue,
2678       "max-size-bytes", max_bytes, "max-size-time", max_time,
2679       "max-size-buffers", max_buffers, NULL);
2680 }
2681
2682 /* gst_decode_group_new:
2683  * @dbin: Parent decodebin
2684  * @parent: Parent chain or %NULL
2685  *
2686  * Creates a new GstDecodeGroup. It is up to the caller to add it to the list
2687  * of groups.
2688  */
2689 static GstDecodeGroup *
2690 gst_decode_group_new (GstDecodeBin * dbin, GstDecodeChain * parent)
2691 {
2692   GstDecodeGroup *group = g_slice_new0 (GstDecodeGroup);
2693   GstElement *mq;
2694
2695   GST_DEBUG_OBJECT (dbin, "Creating new group %p with parent chain %p", group,
2696       parent);
2697
2698   group->dbin = dbin;
2699   group->parent = parent;
2700
2701   mq = group->multiqueue = gst_element_factory_make ("multiqueue", NULL);
2702   if (G_UNLIKELY (!group->multiqueue))
2703     goto missing_multiqueue;
2704
2705   /* default is for use-buffering is FALSE */
2706   if (dbin->use_buffering) {
2707     g_object_set (mq,
2708         "use-buffering", TRUE,
2709         "low-percent", dbin->low_percent,
2710         "high-percent", dbin->high_percent, NULL);
2711   }
2712
2713   /* configure queue sizes for preroll */
2714   decodebin_set_queue_size (dbin, mq, TRUE);
2715
2716   group->overrunsig = g_signal_connect (G_OBJECT (mq), "overrun",
2717       G_CALLBACK (multi_queue_overrun_cb), group);
2718
2719   gst_bin_add (GST_BIN (dbin), gst_object_ref (mq));
2720   gst_element_set_state (mq, GST_STATE_PAUSED);
2721
2722   return group;
2723
2724   /* ERRORS */
2725 missing_multiqueue:
2726   {
2727     gst_element_post_message (GST_ELEMENT_CAST (dbin),
2728         gst_missing_element_message_new (GST_ELEMENT_CAST (dbin),
2729             "multiqueue"));
2730     GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL), ("no multiqueue!"));
2731     g_slice_free (GstDecodeGroup, group);
2732     return NULL;
2733   }
2734 }
2735
2736 /* gst_decode_group_control_demuxer_pad
2737  *
2738  * Adds a new demuxer srcpad to the given group.
2739  *
2740  * Returns the srcpad of the multiqueue corresponding the given pad.
2741  * Returns NULL if there was an error.
2742  */
2743 static GstPad *
2744 gst_decode_group_control_demuxer_pad (GstDecodeGroup * group, GstPad * pad)
2745 {
2746   GstDecodeBin *dbin;
2747   GstPad *srcpad, *sinkpad;
2748   GstIterator *it = NULL;
2749   GValue item = { 0, };
2750
2751   dbin = group->dbin;
2752
2753   GST_LOG_OBJECT (dbin, "group:%p pad %s:%s", group, GST_DEBUG_PAD_NAME (pad));
2754
2755   srcpad = NULL;
2756
2757   if (G_UNLIKELY (!group->multiqueue))
2758     return NULL;
2759
2760   if (!(sinkpad = gst_element_get_request_pad (group->multiqueue, "sink%d"))) {
2761     GST_ERROR_OBJECT (dbin, "Couldn't get sinkpad from multiqueue");
2762     return NULL;
2763   }
2764
2765   if ((gst_pad_link (pad, sinkpad) != GST_PAD_LINK_OK)) {
2766     GST_ERROR_OBJECT (dbin, "Couldn't link demuxer and multiqueue");
2767     goto error;
2768   }
2769
2770   it = gst_pad_iterate_internal_links (sinkpad);
2771
2772   if (!it || (gst_iterator_next (it, &item)) != GST_ITERATOR_OK
2773       || ((srcpad = g_value_dup_object (&item)) == NULL)) {
2774     GST_ERROR_OBJECT (dbin,
2775         "Couldn't get srcpad from multiqueue for sinkpad %" GST_PTR_FORMAT,
2776         sinkpad);
2777     goto error;
2778   }
2779   CHAIN_MUTEX_LOCK (group->parent);
2780   group->reqpads = g_list_prepend (group->reqpads, gst_object_ref (sinkpad));
2781   CHAIN_MUTEX_UNLOCK (group->parent);
2782
2783 beach:
2784   g_value_unset (&item);
2785   if (it)
2786     gst_iterator_free (it);
2787   gst_object_unref (sinkpad);
2788   return srcpad;
2789
2790 error:
2791   gst_element_release_request_pad (group->multiqueue, sinkpad);
2792   goto beach;
2793 }
2794
2795 /* gst_decode_group_is_complete:
2796  *
2797  * Checks if the group is complete, this means that
2798  * a) overrun of the multiqueue or no-more-pads happened
2799  * b) all child chains are complete
2800  *
2801  * Not MT-safe, always call with decodebin expose lock
2802  */
2803 static gboolean
2804 gst_decode_group_is_complete (GstDecodeGroup * group)
2805 {
2806   GList *l;
2807   gboolean complete = TRUE;
2808
2809   if (!group->overrun && !group->no_more_pads) {
2810     complete = FALSE;
2811     goto out;
2812   }
2813
2814   for (l = group->children; l; l = l->next) {
2815     GstDecodeChain *chain = l->data;
2816
2817     if (!gst_decode_chain_is_complete (chain)) {
2818       complete = FALSE;
2819       goto out;
2820     }
2821   }
2822
2823 out:
2824   GST_DEBUG_OBJECT (group->dbin, "Group %p is complete: %d", group, complete);
2825   return complete;
2826 }
2827
2828 /* gst_decode_chain_is_complete:
2829  *
2830  * Returns TRUE if the chain is complete, this means either
2831  * a) This chain is a dead end, i.e. we have no suitable plugins
2832  * b) This chain ends in an endpad and this is blocked or exposed
2833  *
2834  * Not MT-safe, always call with decodebin expose lock
2835  */
2836 static gboolean
2837 gst_decode_chain_is_complete (GstDecodeChain * chain)
2838 {
2839   gboolean complete = FALSE;
2840
2841   CHAIN_MUTEX_LOCK (chain);
2842   if (chain->deadend) {
2843     complete = TRUE;
2844     goto out;
2845   }
2846
2847   if (chain->endpad && (chain->endpad->blocked || chain->endpad->exposed)) {
2848     complete = TRUE;
2849     goto out;
2850   }
2851
2852   if (chain->demuxer) {
2853     if (chain->active_group
2854         && gst_decode_group_is_complete (chain->active_group)) {
2855       complete = TRUE;
2856       goto out;
2857     }
2858   }
2859
2860 out:
2861   CHAIN_MUTEX_UNLOCK (chain);
2862   GST_DEBUG_OBJECT (chain->dbin, "Chain %p is complete: %d", chain, complete);
2863   return complete;
2864 }
2865
2866 /* check if the group is drained, meaning all pads have seen an EOS
2867  * event.  */
2868 static gboolean
2869 gst_decode_pad_handle_eos (GstDecodePad * pad)
2870 {
2871   GstDecodeChain *chain = pad->chain;
2872
2873   GST_LOG_OBJECT (pad->dbin, "chain : %p, pad %p", chain, pad);
2874   pad->drained = TRUE;
2875   return gst_decode_chain_handle_eos (chain);
2876 }
2877
2878 /* gst_decode_chain_handle_eos:
2879  *
2880  * Checks if there are next groups in any parent chain
2881  * to which we can switch or if everything is drained.
2882  *
2883  * If there are groups to switch to, hide the current active
2884  * one and expose the new one.
2885  *
2886  * If a group isn't completely drained (i.e. we received EOS
2887  * only on one of the streams) this function will return FALSE
2888  * to indicate the EOS on the given chain should be dropped
2889  * to avoid it from going downstream.
2890  *
2891  * MT-safe, don't call with chain lock!
2892  */
2893 static gboolean
2894 gst_decode_chain_handle_eos (GstDecodeChain * eos_chain)
2895 {
2896   GstDecodeBin *dbin = eos_chain->dbin;
2897   GstDecodeGroup *group;
2898   GstDecodeChain *chain = eos_chain;
2899   gboolean drained;
2900   gboolean forward_eos = TRUE;
2901
2902   g_return_val_if_fail (eos_chain->endpad, TRUE);
2903
2904   CHAIN_MUTEX_LOCK (chain);
2905   while ((group = chain->parent)) {
2906     CHAIN_MUTEX_UNLOCK (chain);
2907     chain = group->parent;
2908     CHAIN_MUTEX_LOCK (chain);
2909
2910     if (gst_decode_group_is_drained (group)) {
2911       continue;
2912     }
2913     break;
2914   }
2915
2916   drained = chain->active_group ?
2917       gst_decode_group_is_drained (chain->active_group) : TRUE;
2918
2919   /* Now either group == NULL and chain == dbin->decode_chain
2920    * or chain is the lowest chain that has a non-drained group */
2921   if (chain->active_group && drained && chain->next_groups) {
2922     /* There's an active group which is drained and we have another
2923      * one to switch to. */
2924     GST_DEBUG_OBJECT (dbin, "Hiding current group %p", chain->active_group);
2925     gst_decode_group_hide (chain->active_group);
2926     chain->old_groups = g_list_prepend (chain->old_groups, chain->active_group);
2927     GST_DEBUG_OBJECT (dbin, "Switching to next group %p",
2928         chain->next_groups->data);
2929     chain->active_group = chain->next_groups->data;
2930     chain->next_groups =
2931         g_list_delete_link (chain->next_groups, chain->next_groups);
2932     CHAIN_MUTEX_UNLOCK (chain);
2933     EXPOSE_LOCK (dbin);
2934     if (gst_decode_chain_is_complete (dbin->decode_chain))
2935       gst_decode_bin_expose (dbin);
2936     EXPOSE_UNLOCK (dbin);
2937   } else if (!chain->active_group || drained) {
2938     /* The group is drained and there isn't a future one */
2939     g_assert (chain == dbin->decode_chain);
2940     CHAIN_MUTEX_UNLOCK (chain);
2941
2942     GST_LOG_OBJECT (dbin, "all groups drained, fire signal");
2943     g_signal_emit (G_OBJECT (dbin), gst_decode_bin_signals[SIGNAL_DRAINED], 0,
2944         NULL);
2945   } else {
2946     CHAIN_MUTEX_UNLOCK (chain);
2947     GST_DEBUG_OBJECT (dbin,
2948         "Current active group in chain %p is not drained yet", chain);
2949     /* Instruct caller to drop EOS event if we have future groups */
2950     if (chain->next_groups)
2951       forward_eos = FALSE;
2952   }
2953
2954   return forward_eos;
2955 }
2956
2957 /* gst_decode_group_is_drained:
2958  *
2959  * Check is this group is drained and cache this result.
2960  * The group is drained if all child chains are drained.
2961  *
2962  * Not MT-safe, call with group->parent's lock */
2963 static gboolean
2964 gst_decode_group_is_drained (GstDecodeGroup * group)
2965 {
2966   GList *l;
2967   gboolean drained = TRUE;
2968
2969   if (group->drained) {
2970     drained = TRUE;
2971     goto out;
2972   }
2973
2974   for (l = group->children; l; l = l->next) {
2975     GstDecodeChain *chain = l->data;
2976
2977     CHAIN_MUTEX_LOCK (chain);
2978     if (!gst_decode_chain_is_drained (chain))
2979       drained = FALSE;
2980     CHAIN_MUTEX_UNLOCK (chain);
2981     if (!drained)
2982       goto out;
2983   }
2984   group->drained = drained;
2985
2986 out:
2987   GST_DEBUG_OBJECT (group->dbin, "Group %p is drained: %d", group, drained);
2988   return drained;
2989 }
2990
2991 /* gst_decode_chain_is_drained:
2992  *
2993  * Check is the chain is drained, which means that
2994  * either
2995  *
2996  * a) it's endpad is drained
2997  * b) there are no pending pads, the active group is drained
2998  *    and there are no next groups
2999  *
3000  * Not MT-safe, call with chain lock
3001  */
3002 static gboolean
3003 gst_decode_chain_is_drained (GstDecodeChain * chain)
3004 {
3005   gboolean drained = FALSE;
3006
3007   if (chain->endpad) {
3008     drained = chain->endpad->drained;
3009     goto out;
3010   }
3011
3012   if (chain->pending_pads) {
3013     drained = FALSE;
3014     goto out;
3015   }
3016
3017   if (chain->active_group && gst_decode_group_is_drained (chain->active_group)
3018       && !chain->next_groups) {
3019     drained = TRUE;
3020     goto out;
3021   }
3022
3023 out:
3024   GST_DEBUG_OBJECT (chain->dbin, "Chain %p is drained: %d", chain, drained);
3025   return drained;
3026 }
3027
3028 /* sort_end_pads:
3029  * GCompareFunc to use with lists of GstPad.
3030  * Sorts pads by mime type.
3031  * First video (raw, then non-raw), then audio (raw, then non-raw),
3032  * then others.
3033  *
3034  * Return: negative if a<b, 0 if a==b, positive if a>b
3035  */
3036 static gint
3037 sort_end_pads (GstDecodePad * da, GstDecodePad * db)
3038 {
3039   gint va, vb;
3040   GstCaps *capsa, *capsb;
3041   GstStructure *sa, *sb;
3042   const gchar *namea, *nameb;
3043
3044   capsa = get_pad_caps (GST_PAD_CAST (da));
3045   capsb = get_pad_caps (GST_PAD_CAST (db));
3046
3047   sa = gst_caps_get_structure ((const GstCaps *) capsa, 0);
3048   sb = gst_caps_get_structure ((const GstCaps *) capsb, 0);
3049
3050   namea = gst_structure_get_name (sa);
3051   nameb = gst_structure_get_name (sb);
3052
3053   if (g_strrstr (namea, "video/x-raw"))
3054     va = 0;
3055   else if (g_strrstr (namea, "video/"))
3056     va = 1;
3057   else if (g_strrstr (namea, "audio/x-raw"))
3058     va = 2;
3059   else if (g_strrstr (namea, "audio/"))
3060     va = 3;
3061   else
3062     va = 4;
3063
3064   if (g_strrstr (nameb, "video/x-raw"))
3065     vb = 0;
3066   else if (g_strrstr (nameb, "video/"))
3067     vb = 1;
3068   else if (g_strrstr (nameb, "audio/x-raw"))
3069     vb = 2;
3070   else if (g_strrstr (nameb, "audio/"))
3071     vb = 3;
3072   else
3073     vb = 4;
3074
3075   gst_caps_unref (capsa);
3076   gst_caps_unref (capsb);
3077
3078   return va - vb;
3079 }
3080
3081 static GstCaps *
3082 _gst_element_get_linked_caps (GstElement * src, GstElement * sink)
3083 {
3084   GstIterator *it;
3085   GstElement *parent;
3086   GstPad *pad, *peer;
3087   gboolean done = FALSE;
3088   GstCaps *caps = NULL;
3089   GValue item = { 0, };
3090
3091   it = gst_element_iterate_src_pads (src);
3092   while (!done) {
3093     switch (gst_iterator_next (it, &item)) {
3094       case GST_ITERATOR_OK:
3095         pad = g_value_get_object (&item);
3096         peer = gst_pad_get_peer (pad);
3097         if (peer) {
3098           parent = gst_pad_get_parent_element (peer);
3099           if (parent == sink) {
3100             caps = gst_pad_get_current_caps (pad);
3101             done = TRUE;
3102           }
3103
3104           if (parent)
3105             gst_object_unref (parent);
3106           gst_object_unref (peer);
3107         }
3108         g_value_reset (&item);
3109         break;
3110       case GST_ITERATOR_RESYNC:
3111         gst_iterator_resync (it);
3112         break;
3113       case GST_ITERATOR_ERROR:
3114       case GST_ITERATOR_DONE:
3115         done = TRUE;
3116         break;
3117     }
3118   }
3119   g_value_unset (&item);
3120   gst_iterator_free (it);
3121
3122   return caps;
3123 }
3124
3125 static GQuark topology_structure_name = 0;
3126 static GQuark topology_caps = 0;
3127 static GQuark topology_next = 0;
3128 static GQuark topology_pad = 0;
3129
3130 /* FIXME: Invent gst_structure_take_structure() to prevent all the
3131  * structure copying for nothing
3132  */
3133 static GstStructure *
3134 gst_decode_chain_get_topology (GstDecodeChain * chain)
3135 {
3136   GstStructure *s, *u;
3137   GList *l;
3138   GstCaps *caps;
3139
3140   if (G_UNLIKELY ((chain->endpad || chain->deadend)
3141           && (chain->endcaps == NULL))) {
3142     GST_WARNING ("End chain without valid caps !");
3143     return NULL;
3144   }
3145
3146   u = gst_structure_id_empty_new (topology_structure_name);
3147
3148   /* Now at the last element */
3149   if (chain->elements && (chain->endpad || chain->deadend)) {
3150     s = gst_structure_id_empty_new (topology_structure_name);
3151     gst_structure_id_set (u, topology_caps, GST_TYPE_CAPS, chain->endcaps,
3152         NULL);
3153
3154     if (chain->endpad)
3155       gst_structure_id_set (u, topology_pad, GST_TYPE_PAD, chain->endpad, NULL);
3156     gst_structure_id_set (s, topology_next, GST_TYPE_STRUCTURE, u, NULL);
3157     gst_structure_free (u);
3158     u = s;
3159   } else if (chain->active_group) {
3160     GValue list = { 0, };
3161     GValue item = { 0, };
3162
3163     g_value_init (&list, GST_TYPE_LIST);
3164     g_value_init (&item, GST_TYPE_STRUCTURE);
3165     for (l = chain->active_group->children; l; l = l->next) {
3166       s = gst_decode_chain_get_topology (l->data);
3167       if (s) {
3168         gst_value_set_structure (&item, s);
3169         gst_value_list_append_value (&list, &item);
3170         g_value_reset (&item);
3171         gst_structure_free (s);
3172       }
3173     }
3174     gst_structure_id_set_value (u, topology_next, &list);
3175     g_value_unset (&list);
3176     g_value_unset (&item);
3177   }
3178
3179   /* Get caps between all elements in this chain */
3180   l = (chain->elements && chain->elements->next) ? chain->elements : NULL;
3181   for (; l && l->next; l = l->next) {
3182     GstCaps *caps = _gst_element_get_linked_caps (l->next->data, l->data);
3183
3184     if (caps) {
3185       s = gst_structure_id_empty_new (topology_structure_name);
3186       gst_structure_id_set (u, topology_caps, GST_TYPE_CAPS, caps, NULL);
3187       gst_caps_unref (caps);
3188
3189       gst_structure_id_set (s, topology_next, GST_TYPE_STRUCTURE, u, NULL);
3190       gst_structure_free (u);
3191       u = s;
3192     }
3193   }
3194
3195   /* Caps that resulted in this chain */
3196   caps = gst_pad_get_current_caps (chain->pad);
3197   if (!caps) {
3198     caps = get_pad_caps (chain->pad);
3199     if (G_UNLIKELY (!gst_caps_is_fixed (caps))) {
3200       GST_ERROR_OBJECT (chain->pad,
3201           "Couldn't get fixed caps, got %" GST_PTR_FORMAT, caps);
3202       gst_caps_unref (caps);
3203       caps = NULL;
3204     }
3205   }
3206   gst_structure_set (u, "caps", GST_TYPE_CAPS, caps, NULL);
3207   gst_caps_unref (caps);
3208
3209   return u;
3210 }
3211
3212 static void
3213 gst_decode_bin_post_topology_message (GstDecodeBin * dbin)
3214 {
3215   GstStructure *s;
3216   GstMessage *msg;
3217
3218   s = gst_decode_chain_get_topology (dbin->decode_chain);
3219
3220   msg = gst_message_new_element (GST_OBJECT (dbin), s);
3221   gst_element_post_message (GST_ELEMENT (dbin), msg);
3222 }
3223
3224 /* Must only be called if the toplevel chain is complete and blocked! */
3225 /* Not MT-safe, call with decodebin expose lock! */
3226 static gboolean
3227 gst_decode_bin_expose (GstDecodeBin * dbin)
3228 {
3229   GList *tmp, *endpads = NULL;
3230   gboolean missing_plugin = FALSE;
3231   gboolean already_exposed = TRUE;
3232
3233   GST_DEBUG_OBJECT (dbin, "Exposing currently active chains/groups");
3234
3235   /* Don't expose if we're currently shutting down */
3236   DYN_LOCK (dbin);
3237   if (G_UNLIKELY (dbin->shutdown == TRUE)) {
3238     GST_WARNING_OBJECT (dbin, "Currently, shutting down, aborting exposing");
3239     DYN_UNLOCK (dbin);
3240     return FALSE;
3241   }
3242   DYN_UNLOCK (dbin);
3243
3244   /* Get the pads that we're going to expose and mark things as exposed */
3245   if (!gst_decode_chain_expose (dbin->decode_chain, &endpads, &missing_plugin)) {
3246     g_list_foreach (endpads, (GFunc) gst_object_unref, NULL);
3247     g_list_free (endpads);
3248     GST_ERROR_OBJECT (dbin, "Broken chain/group tree");
3249     g_return_val_if_reached (FALSE);
3250     return FALSE;
3251   }
3252   if (endpads == NULL) {
3253     if (missing_plugin) {
3254       GST_WARNING_OBJECT (dbin, "No suitable plugins found");
3255       GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL),
3256           ("no suitable plugins found"));
3257     } else {
3258       /* in this case, the stream ended without buffers,
3259        * just post a warning */
3260       GST_WARNING_OBJECT (dbin, "All streams finished without buffers");
3261       GST_ELEMENT_ERROR (dbin, STREAM, FAILED, (NULL),
3262           ("all streams without buffers"));
3263     }
3264     return FALSE;
3265   }
3266
3267   /* Check if this was called when everything was exposed already */
3268   for (tmp = endpads; tmp && already_exposed; tmp = tmp->next) {
3269     GstDecodePad *dpad = tmp->data;
3270
3271     already_exposed &= dpad->exposed;
3272     if (!already_exposed)
3273       break;
3274   }
3275   if (already_exposed) {
3276     GST_DEBUG_OBJECT (dbin, "Everything was exposed already!");
3277     g_list_foreach (endpads, (GFunc) gst_object_unref, NULL);
3278     g_list_free (endpads);
3279     return TRUE;
3280   }
3281
3282   /* Set all already exposed pads to blocked */
3283   for (tmp = endpads; tmp; tmp = tmp->next) {
3284     GstDecodePad *dpad = tmp->data;
3285
3286     if (dpad->exposed) {
3287       GST_DEBUG_OBJECT (dpad, "blocking exposed pad");
3288       gst_decode_pad_set_blocked (dpad, TRUE);
3289     }
3290   }
3291
3292   /* re-order pads : video, then audio, then others */
3293   endpads = g_list_sort (endpads, (GCompareFunc) sort_end_pads);
3294
3295   /* Expose pads */
3296   for (tmp = endpads; tmp; tmp = tmp->next) {
3297     GstDecodePad *dpad = (GstDecodePad *) tmp->data;
3298     gchar *padname;
3299
3300     /* 1. rewrite name */
3301     padname = g_strdup_printf ("src%d", dbin->nbpads);
3302     dbin->nbpads++;
3303     GST_DEBUG_OBJECT (dbin, "About to expose dpad %s as %s",
3304         GST_OBJECT_NAME (dpad), padname);
3305     gst_object_set_name (GST_OBJECT (dpad), padname);
3306     g_free (padname);
3307
3308     /* 2. activate and add */
3309     if (!dpad->exposed
3310         && !gst_element_add_pad (GST_ELEMENT (dbin), GST_PAD_CAST (dpad))) {
3311       /* not really fatal, we can try to add the other pads */
3312       g_warning ("error adding pad to decodebin");
3313       continue;
3314     }
3315     dpad->exposed = TRUE;
3316
3317     /* 3. emit signal */
3318     GST_INFO_OBJECT (dpad, "added new decoded pad");
3319   }
3320
3321   /* 4. Signal no-more-pads. This allows the application to hook stuff to the
3322    * exposed pads */
3323   GST_LOG_OBJECT (dbin, "signalling no-more-pads");
3324   gst_element_no_more_pads (GST_ELEMENT (dbin));
3325
3326   /* 5. Send a custom element message with the stream topology */
3327   if (dbin->post_stream_topology)
3328     gst_decode_bin_post_topology_message (dbin);
3329
3330   /* 6. Unblock internal pads. The application should have connected stuff now
3331    * so that streaming can continue. */
3332   for (tmp = endpads; tmp; tmp = tmp->next) {
3333     GstDecodePad *dpad = (GstDecodePad *) tmp->data;
3334
3335     GST_DEBUG_OBJECT (dpad, "unblocking");
3336     gst_decode_pad_unblock (dpad);
3337     GST_DEBUG_OBJECT (dpad, "unblocked");
3338     gst_object_unref (dpad);
3339   }
3340   g_list_free (endpads);
3341
3342   do_async_done (dbin);
3343   GST_DEBUG_OBJECT (dbin, "Exposed everything");
3344   return TRUE;
3345 }
3346
3347 /* gst_decode_chain_expose:
3348  *
3349  * Check if the chain can be exposed and add all endpads
3350  * to the endpads list.
3351  *
3352  * Also update the active group's multiqueue to the
3353  * runtime limits.
3354  *
3355  * Not MT-safe, call with decodebin expose lock! *
3356  */
3357 static gboolean
3358 gst_decode_chain_expose (GstDecodeChain * chain, GList ** endpads,
3359     gboolean * missing_plugin)
3360 {
3361   GstDecodeGroup *group;
3362   GList *l;
3363   GstDecodeBin *dbin;
3364
3365   if (chain->deadend) {
3366     if (chain->endcaps)
3367       *missing_plugin = TRUE;
3368     return TRUE;
3369   }
3370
3371   if (chain->endpad) {
3372     if (!chain->endpad->blocked && !chain->endpad->exposed)
3373       return FALSE;
3374     *endpads = g_list_prepend (*endpads, gst_object_ref (chain->endpad));
3375     return TRUE;
3376   }
3377
3378   group = chain->active_group;
3379   if (!group)
3380     return FALSE;
3381   if (!group->no_more_pads && !group->overrun)
3382     return FALSE;
3383
3384   dbin = group->dbin;
3385
3386   /* configure queues for playback */
3387   decodebin_set_queue_size (dbin, group->multiqueue, FALSE);
3388
3389   /* we can now disconnect any overrun signal, which is used to expose the
3390    * group. */
3391   if (group->overrunsig) {
3392     GST_LOG_OBJECT (dbin, "Disconnecting overrun");
3393     g_signal_handler_disconnect (group->multiqueue, group->overrunsig);
3394     group->overrunsig = 0;
3395   }
3396
3397   for (l = group->children; l; l = l->next) {
3398     GstDecodeChain *childchain = l->data;
3399
3400     if (!gst_decode_chain_expose (childchain, endpads, missing_plugin))
3401       return FALSE;
3402   }
3403
3404   return TRUE;
3405 }
3406
3407 /*************************
3408  * GstDecodePad functions
3409  *************************/
3410
3411 static void
3412 gst_decode_pad_class_init (GstDecodePadClass * klass)
3413 {
3414 }
3415
3416 static void
3417 gst_decode_pad_init (GstDecodePad * pad)
3418 {
3419   pad->chain = NULL;
3420   pad->blocked = FALSE;
3421   pad->exposed = FALSE;
3422   pad->drained = FALSE;
3423   gst_object_ref_sink (pad);
3424 }
3425
3426 static GstProbeReturn
3427 source_pad_blocked_cb (GstPad * pad, GstProbeType type, gpointer type_data,
3428     gpointer user_data)
3429 {
3430   GstDecodePad *dpad = user_data;
3431   GstDecodeChain *chain;
3432   GstDecodeBin *dbin;
3433
3434   chain = dpad->chain;
3435   dbin = chain->dbin;
3436
3437   GST_LOG_OBJECT (dpad, "blocked: dpad->chain:%p", chain);
3438
3439   dpad->blocked = TRUE;
3440
3441   EXPOSE_LOCK (dbin);
3442   if (gst_decode_chain_is_complete (dbin->decode_chain)) {
3443     if (!gst_decode_bin_expose (dbin))
3444       GST_WARNING_OBJECT (dbin, "Couldn't expose group");
3445   }
3446   EXPOSE_UNLOCK (dbin);
3447
3448   return GST_PROBE_OK;
3449 }
3450
3451 static GstProbeReturn
3452 source_pad_event_probe (GstPad * pad, GstProbeType type, gpointer type_data,
3453     gpointer user_data)
3454 {
3455   GstEvent *event = type_data;
3456   GstDecodePad *dpad = user_data;
3457   gboolean res = TRUE;
3458
3459   GST_LOG_OBJECT (pad, "%s dpad:%p", GST_EVENT_TYPE_NAME (event), dpad);
3460
3461   if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
3462     GST_DEBUG_OBJECT (pad, "we received EOS");
3463
3464     /* Check if all pads are drained.
3465      * * If there is no next group, we will let the EOS go through.
3466      * * If there is a next group but the current group isn't completely
3467      *   drained, we will drop the EOS event.
3468      * * If there is a next group to expose and this was the last non-drained
3469      *   pad for that group, we will remove the ghostpad of the current group
3470      *   first, which unlinks the peer and so drops the EOS. */
3471     res = gst_decode_pad_handle_eos (dpad);
3472   }
3473   if (res)
3474     return GST_PROBE_OK;
3475   else
3476     return GST_PROBE_DROP;
3477 }
3478
3479 static void
3480 gst_decode_pad_set_blocked (GstDecodePad * dpad, gboolean blocked)
3481 {
3482   GstDecodeBin *dbin = dpad->dbin;
3483   GstPad *opad;
3484
3485   DYN_LOCK (dbin);
3486
3487   GST_DEBUG_OBJECT (dpad, "blocking pad: %d", blocked);
3488
3489   opad = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (dpad));
3490   if (!opad)
3491     goto out;
3492
3493   /* do not block if shutting down.
3494    * we do not consider/expect it blocked further below, but use other trick */
3495   if (!blocked || !dbin->shutdown) {
3496     if (blocked) {
3497       if (dpad->block_id == 0)
3498         dpad->block_id = gst_pad_add_probe (opad, GST_PROBE_TYPE_BLOCK,
3499             source_pad_blocked_cb, gst_object_ref (dpad),
3500             (GDestroyNotify) gst_object_unref);
3501     } else {
3502       if (dpad->block_id != 0) {
3503         gst_pad_remove_probe (opad, dpad->block_id);
3504         dpad->block_id = 0;
3505       }
3506       dpad->blocked = FALSE;
3507     }
3508   }
3509
3510   if (blocked) {
3511     if (dbin->shutdown) {
3512       /* deactivate to force flushing state to prevent NOT_LINKED errors */
3513       gst_pad_set_active (GST_PAD_CAST (dpad), FALSE);
3514       /* note that deactivating the target pad would have no effect here,
3515        * since elements are typically connected first (and pads exposed),
3516        * and only then brought to PAUSED state (so pads activated) */
3517     } else {
3518       gst_object_ref (dpad);
3519       dbin->blocked_pads = g_list_prepend (dbin->blocked_pads, dpad);
3520     }
3521   } else {
3522     GList *l;
3523
3524     if ((l = g_list_find (dbin->blocked_pads, dpad))) {
3525       gst_object_unref (dpad);
3526       dbin->blocked_pads = g_list_delete_link (dbin->blocked_pads, l);
3527     }
3528   }
3529   gst_object_unref (opad);
3530 out:
3531   DYN_UNLOCK (dbin);
3532 }
3533
3534 static void
3535 gst_decode_pad_add_drained_check (GstDecodePad * dpad)
3536 {
3537   gst_pad_add_probe (GST_PAD_CAST (dpad), GST_PROBE_TYPE_EVENT,
3538       source_pad_event_probe, dpad, NULL);
3539 }
3540
3541 static void
3542 gst_decode_pad_activate (GstDecodePad * dpad, GstDecodeChain * chain)
3543 {
3544   g_return_if_fail (chain != NULL);
3545
3546   dpad->chain = chain;
3547   gst_pad_set_active (GST_PAD_CAST (dpad), TRUE);
3548   gst_decode_pad_set_blocked (dpad, TRUE);
3549   gst_decode_pad_add_drained_check (dpad);
3550 }
3551
3552 static void
3553 gst_decode_pad_unblock (GstDecodePad * dpad)
3554 {
3555   gst_decode_pad_set_blocked (dpad, FALSE);
3556 }
3557
3558 /*gst_decode_pad_new:
3559  *
3560  * Creates a new GstDecodePad for the given pad.
3561  */
3562 static GstDecodePad *
3563 gst_decode_pad_new (GstDecodeBin * dbin, GstPad * pad, GstDecodeChain * chain)
3564 {
3565   GstDecodePad *dpad;
3566   GstPadTemplate *pad_tmpl;
3567
3568   GST_DEBUG_OBJECT (dbin, "making new decodepad");
3569   pad_tmpl = gst_static_pad_template_get (&decoder_bin_src_template);
3570   dpad =
3571       g_object_new (GST_TYPE_DECODE_PAD, "direction", GST_PAD_DIRECTION (pad),
3572       "template", pad_tmpl, NULL);
3573   gst_ghost_pad_construct (GST_GHOST_PAD_CAST (dpad));
3574   gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (dpad), pad);
3575   dpad->chain = chain;
3576   dpad->dbin = dbin;
3577   gst_object_unref (pad_tmpl);
3578
3579   return dpad;
3580 }
3581
3582 static void
3583 gst_pending_pad_free (GstPendingPad * ppad)
3584 {
3585   g_assert (ppad);
3586   g_assert (ppad->pad);
3587
3588   if (ppad->event_probe_id != 0)
3589     gst_pad_remove_probe (ppad->pad, ppad->event_probe_id);
3590   gst_object_unref (ppad->pad);
3591   g_slice_free (GstPendingPad, ppad);
3592 }
3593
3594 /*****
3595  * Element add/remove
3596  *****/
3597
3598 static void
3599 do_async_start (GstDecodeBin * dbin)
3600 {
3601   GstMessage *message;
3602
3603   dbin->async_pending = TRUE;
3604
3605   message = gst_message_new_async_start (GST_OBJECT_CAST (dbin));
3606   parent_class->handle_message (GST_BIN_CAST (dbin), message);
3607 }
3608
3609 static void
3610 do_async_done (GstDecodeBin * dbin)
3611 {
3612   GstMessage *message;
3613
3614   if (dbin->async_pending) {
3615     message = gst_message_new_async_done (GST_OBJECT_CAST (dbin), FALSE);
3616     parent_class->handle_message (GST_BIN_CAST (dbin), message);
3617
3618     dbin->async_pending = FALSE;
3619   }
3620 }
3621
3622 /*****
3623  * convenience functions
3624  *****/
3625
3626 /* find_sink_pad
3627  *
3628  * Returns the first sink pad of the given element, or NULL if it doesn't have
3629  * any.
3630  */
3631
3632 static GstPad *
3633 find_sink_pad (GstElement * element)
3634 {
3635   GstIterator *it;
3636   GstPad *pad = NULL;
3637   GValue item = { 0, };
3638
3639   it = gst_element_iterate_sink_pads (element);
3640
3641   if ((gst_iterator_next (it, &item)) == GST_ITERATOR_OK)
3642     pad = g_value_dup_object (&item);
3643   g_value_unset (&item);
3644   gst_iterator_free (it);
3645
3646   return pad;
3647 }
3648
3649 /* call with dyn_lock held */
3650 static void
3651 unblock_pads (GstDecodeBin * dbin)
3652 {
3653   GList *tmp;
3654
3655   GST_LOG_OBJECT (dbin, "unblocking pads");
3656
3657   for (tmp = dbin->blocked_pads; tmp; tmp = tmp->next) {
3658     GstDecodePad *dpad = (GstDecodePad *) tmp->data;
3659     GstPad *opad;
3660
3661     opad = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (dpad));
3662     if (!opad)
3663       continue;
3664
3665     GST_DEBUG_OBJECT (dpad, "unblocking");
3666     if (dpad->block_id != 0) {
3667       gst_pad_remove_probe (opad, dpad->block_id);
3668       dpad->block_id = 0;
3669     }
3670     dpad->blocked = FALSE;
3671     /* make flushing, prevent NOT_LINKED */
3672     GST_PAD_SET_FLUSHING (GST_PAD_CAST (dpad));
3673     gst_object_unref (dpad);
3674     gst_object_unref (opad);
3675     GST_DEBUG_OBJECT (dpad, "unblocked");
3676   }
3677
3678   /* clear, no more blocked pads */
3679   g_list_free (dbin->blocked_pads);
3680   dbin->blocked_pads = NULL;
3681 }
3682
3683 static GstStateChangeReturn
3684 gst_decode_bin_change_state (GstElement * element, GstStateChange transition)
3685 {
3686   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
3687   GstDecodeBin *dbin = GST_DECODE_BIN (element);
3688
3689   switch (transition) {
3690     case GST_STATE_CHANGE_NULL_TO_READY:
3691       if (dbin->typefind == NULL)
3692         goto missing_typefind;
3693       break;
3694     case GST_STATE_CHANGE_READY_TO_PAUSED:
3695       /* Make sure we've cleared all existing chains */
3696       if (dbin->decode_chain) {
3697         gst_decode_chain_free (dbin->decode_chain);
3698         dbin->decode_chain = NULL;
3699       }
3700       DYN_LOCK (dbin);
3701       GST_LOG_OBJECT (dbin, "clearing shutdown flag");
3702       dbin->shutdown = FALSE;
3703       DYN_UNLOCK (dbin);
3704       dbin->have_type = FALSE;
3705       ret = GST_STATE_CHANGE_ASYNC;
3706       do_async_start (dbin);
3707       break;
3708     case GST_STATE_CHANGE_PAUSED_TO_READY:
3709       DYN_LOCK (dbin);
3710       GST_LOG_OBJECT (dbin, "setting shutdown flag");
3711       dbin->shutdown = TRUE;
3712       unblock_pads (dbin);
3713       DYN_UNLOCK (dbin);
3714     default:
3715       break;
3716   }
3717
3718   {
3719     GstStateChangeReturn bret;
3720
3721     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3722     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
3723       goto activate_failed;
3724     else if (G_UNLIKELY (bret == GST_STATE_CHANGE_NO_PREROLL)) {
3725       do_async_done (dbin);
3726       ret = bret;
3727     }
3728   }
3729   switch (transition) {
3730     case GST_STATE_CHANGE_PAUSED_TO_READY:
3731       do_async_done (dbin);
3732       if (dbin->decode_chain) {
3733         gst_decode_chain_free (dbin->decode_chain);
3734         dbin->decode_chain = NULL;
3735       }
3736       break;
3737     case GST_STATE_CHANGE_READY_TO_NULL:
3738     default:
3739       break;
3740   }
3741
3742   return ret;
3743
3744 /* ERRORS */
3745 missing_typefind:
3746   {
3747     gst_element_post_message (element,
3748         gst_missing_element_message_new (element, "typefind"));
3749     GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL), ("no typefind!"));
3750     return GST_STATE_CHANGE_FAILURE;
3751   }
3752 activate_failed:
3753   {
3754     GST_DEBUG_OBJECT (element,
3755         "element failed to change states -- activation problem?");
3756     return GST_STATE_CHANGE_FAILURE;
3757   }
3758 }
3759
3760 gboolean
3761 gst_decode_bin_plugin_init (GstPlugin * plugin)
3762 {
3763   GST_DEBUG_CATEGORY_INIT (gst_decode_bin_debug, "decodebin", 0, "decoder bin");
3764
3765   /* Register some quarks here for the stream topology message */
3766   topology_structure_name = g_quark_from_static_string ("stream-topology");
3767   topology_caps = g_quark_from_static_string ("caps");
3768   topology_next = g_quark_from_static_string ("next");
3769   topology_pad = g_quark_from_static_string ("pad");
3770
3771   return gst_element_register (plugin, "decodebin", GST_RANK_NONE,
3772       GST_TYPE_DECODE_BIN);
3773 }