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