decodebin: Fix list iteration
[platform/upstream/gst-plugins-base.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   GList *filtered_errors;       /* filtered error messages */
187
188   GList *buffering_status;      /* element currently buffering messages */
189 };
190
191 struct _GstDecodeBinClass
192 {
193   GstBinClass parent_class;
194
195   /* signal fired when we found a pad that we cannot decode */
196   void (*unknown_type) (GstElement * element, GstPad * pad, GstCaps * caps);
197
198   /* signal fired to know if we continue trying to decode the given caps */
199     gboolean (*autoplug_continue) (GstElement * element, GstPad * pad,
200       GstCaps * caps);
201   /* signal fired to get a list of factories to try to autoplug */
202   GValueArray *(*autoplug_factories) (GstElement * element, GstPad * pad,
203       GstCaps * caps);
204   /* signal fired to sort the factories */
205   GValueArray *(*autoplug_sort) (GstElement * element, GstPad * pad,
206       GstCaps * caps, GValueArray * factories);
207   /* signal fired to select from the proposed list of factories */
208     GstAutoplugSelectResult (*autoplug_select) (GstElement * element,
209       GstPad * pad, GstCaps * caps, GstElementFactory * factory);
210   /* signal fired when a autoplugged element that is not linked downstream
211    * or exposed wants to query something */
212     gboolean (*autoplug_query) (GstElement * element, GstPad * pad,
213       GstQuery * query);
214
215   /* fired when the last group is drained */
216   void (*drained) (GstElement * element);
217 };
218
219 /* signals */
220 enum
221 {
222   SIGNAL_UNKNOWN_TYPE,
223   SIGNAL_AUTOPLUG_CONTINUE,
224   SIGNAL_AUTOPLUG_FACTORIES,
225   SIGNAL_AUTOPLUG_SELECT,
226   SIGNAL_AUTOPLUG_SORT,
227   SIGNAL_AUTOPLUG_QUERY,
228   SIGNAL_DRAINED,
229   LAST_SIGNAL
230 };
231
232 /* automatic sizes, while prerolling we buffer up to 2MB, we ignore time
233  * and buffers in this case. */
234 #define AUTO_PREROLL_SIZE_BYTES                  2 * 1024 * 1024
235 #define AUTO_PREROLL_SIZE_BUFFERS                0
236 #define AUTO_PREROLL_NOT_SEEKABLE_SIZE_TIME      10 * GST_SECOND
237 #define AUTO_PREROLL_SEEKABLE_SIZE_TIME          0
238
239 /* when playing, keep a max of 2MB of data but try to keep the number of buffers
240  * as low as possible (try to aim for 5 buffers) */
241 #define AUTO_PLAY_SIZE_BYTES        2 * 1024 * 1024
242 #define AUTO_PLAY_SIZE_BUFFERS      5
243 #define AUTO_PLAY_SIZE_TIME         0
244
245 #define DEFAULT_SUBTITLE_ENCODING NULL
246 #define DEFAULT_USE_BUFFERING     FALSE
247 #define DEFAULT_LOW_PERCENT       10
248 #define DEFAULT_HIGH_PERCENT      99
249 /* by default we use the automatic values above */
250 #define DEFAULT_MAX_SIZE_BYTES    0
251 #define DEFAULT_MAX_SIZE_BUFFERS  0
252 #define DEFAULT_MAX_SIZE_TIME     0
253 #define DEFAULT_POST_STREAM_TOPOLOGY FALSE
254 #define DEFAULT_EXPOSE_ALL_STREAMS  TRUE
255 #define DEFAULT_CONNECTION_SPEED    0
256
257 /* Properties */
258 enum
259 {
260   PROP_0,
261   PROP_CAPS,
262   PROP_SUBTITLE_ENCODING,
263   PROP_SINK_CAPS,
264   PROP_USE_BUFFERING,
265   PROP_LOW_PERCENT,
266   PROP_HIGH_PERCENT,
267   PROP_MAX_SIZE_BYTES,
268   PROP_MAX_SIZE_BUFFERS,
269   PROP_MAX_SIZE_TIME,
270   PROP_POST_STREAM_TOPOLOGY,
271   PROP_EXPOSE_ALL_STREAMS,
272   PROP_CONNECTION_SPEED
273 };
274
275 static GstBinClass *parent_class;
276 static guint gst_decode_bin_signals[LAST_SIGNAL] = { 0 };
277
278 static GstStaticCaps default_raw_caps = GST_STATIC_CAPS (DEFAULT_RAW_CAPS);
279
280 static void do_async_start (GstDecodeBin * dbin);
281 static void do_async_done (GstDecodeBin * dbin);
282
283 static void type_found (GstElement * typefind, guint probability,
284     GstCaps * caps, GstDecodeBin * decode_bin);
285
286 static void decodebin_set_queue_size (GstDecodeBin * dbin,
287     GstElement * multiqueue, gboolean preroll, gboolean seekable);
288 static void decodebin_set_queue_size_full (GstDecodeBin * dbin,
289     GstElement * multiqueue, gboolean use_buffering, gboolean preroll,
290     gboolean seekable);
291
292 static gboolean gst_decode_bin_autoplug_continue (GstElement * element,
293     GstPad * pad, GstCaps * caps);
294 static GValueArray *gst_decode_bin_autoplug_factories (GstElement *
295     element, GstPad * pad, GstCaps * caps);
296 static GValueArray *gst_decode_bin_autoplug_sort (GstElement * element,
297     GstPad * pad, GstCaps * caps, GValueArray * factories);
298 static GstAutoplugSelectResult gst_decode_bin_autoplug_select (GstElement *
299     element, GstPad * pad, GstCaps * caps, GstElementFactory * factory);
300 static gboolean gst_decode_bin_autoplug_query (GstElement * element,
301     GstPad * pad, GstQuery * query);
302
303 static void gst_decode_bin_set_property (GObject * object, guint prop_id,
304     const GValue * value, GParamSpec * pspec);
305 static void gst_decode_bin_get_property (GObject * object, guint prop_id,
306     GValue * value, GParamSpec * pspec);
307 static void gst_decode_bin_set_caps (GstDecodeBin * dbin, GstCaps * caps);
308 static GstCaps *gst_decode_bin_get_caps (GstDecodeBin * dbin);
309 static void caps_notify_cb (GstPad * pad, GParamSpec * unused,
310     GstDecodeChain * chain);
311
312 static void flush_chain (GstDecodeChain * chain, gboolean flushing);
313 static void flush_group (GstDecodeGroup * group, gboolean flushing);
314 static GstPad *find_sink_pad (GstElement * element);
315 static GstStateChangeReturn gst_decode_bin_change_state (GstElement * element,
316     GstStateChange transition);
317 static void gst_decode_bin_handle_message (GstBin * bin, GstMessage * message);
318
319 static gboolean check_upstream_seekable (GstDecodeBin * dbin, GstPad * pad);
320
321 static GstCaps *get_pad_caps (GstPad * pad);
322
323 #define EXPOSE_LOCK(dbin) G_STMT_START {                                \
324     GST_LOG_OBJECT (dbin,                                               \
325                     "expose locking from thread %p",                    \
326                     g_thread_self ());                                  \
327     g_mutex_lock (&GST_DECODE_BIN_CAST(dbin)->expose_lock);             \
328     GST_LOG_OBJECT (dbin,                                               \
329                     "expose locked from thread %p",                     \
330                     g_thread_self ());                                  \
331 } G_STMT_END
332
333 #define EXPOSE_UNLOCK(dbin) G_STMT_START {                              \
334     GST_LOG_OBJECT (dbin,                                               \
335                     "expose unlocking from thread %p",                  \
336                     g_thread_self ());                                  \
337     g_mutex_unlock (&GST_DECODE_BIN_CAST(dbin)->expose_lock);           \
338 } G_STMT_END
339
340 #define DYN_LOCK(dbin) G_STMT_START {                   \
341     GST_LOG_OBJECT (dbin,                                               \
342                     "dynlocking from thread %p",                        \
343                     g_thread_self ());                                  \
344     g_mutex_lock (&GST_DECODE_BIN_CAST(dbin)->dyn_lock);                        \
345     GST_LOG_OBJECT (dbin,                                               \
346                     "dynlocked from thread %p",                         \
347                     g_thread_self ());                                  \
348 } G_STMT_END
349
350 #define DYN_UNLOCK(dbin) G_STMT_START {                 \
351     GST_LOG_OBJECT (dbin,                                               \
352                     "dynunlocking from thread %p",                      \
353                     g_thread_self ());                                  \
354     g_mutex_unlock (&GST_DECODE_BIN_CAST(dbin)->dyn_lock);              \
355 } G_STMT_END
356
357 #define SUBTITLE_LOCK(dbin) G_STMT_START {                              \
358     GST_LOG_OBJECT (dbin,                                               \
359                     "subtitle locking from thread %p",                  \
360                     g_thread_self ());                                  \
361     g_mutex_lock (&GST_DECODE_BIN_CAST(dbin)->subtitle_lock);           \
362     GST_LOG_OBJECT (dbin,                                               \
363                     "subtitle lock from thread %p",                     \
364                     g_thread_self ());                                  \
365 } G_STMT_END
366
367 #define SUBTITLE_UNLOCK(dbin) G_STMT_START {                            \
368     GST_LOG_OBJECT (dbin,                                               \
369                     "subtitle unlocking from thread %p",                \
370                     g_thread_self ());                                  \
371     g_mutex_unlock (&GST_DECODE_BIN_CAST(dbin)->subtitle_lock);         \
372 } G_STMT_END
373
374 struct _GstPendingPad
375 {
376   GstPad *pad;
377   GstDecodeChain *chain;
378   gulong event_probe_id;
379   gulong notify_caps_id;
380 };
381
382 struct _GstDecodeElement
383 {
384   GstElement *element;
385   GstElement *capsfilter;       /* Optional capsfilter for Parser/Convert */
386   gulong pad_added_id;
387   gulong pad_removed_id;
388   gulong no_more_pads_id;
389 };
390
391 /* GstDecodeGroup
392  *
393  * Streams belonging to the same group/chain of a media file
394  *
395  * When changing something here lock the parent chain!
396  */
397 struct _GstDecodeGroup
398 {
399   GstDecodeBin *dbin;
400   GstDecodeChain *parent;
401
402   GstElement *multiqueue;       /* Used for linking all child chains */
403   gulong overrunsig;            /* the overrun signal for multiqueue */
404
405   gboolean overrun;             /* TRUE if the multiqueue signaled overrun. This
406                                  * means that we should really expose the group */
407
408   gboolean no_more_pads;        /* TRUE if the demuxer signaled no-more-pads */
409   gboolean drained;             /* TRUE if the all children are drained */
410
411   GList *children;              /* List of GstDecodeChains in this group */
412
413   GList *reqpads;               /* List of RequestPads for multiqueue, there is
414                                  * exactly one RequestPad per child chain */
415 };
416
417 struct _GstDecodeChain
418 {
419   GstDecodeGroup *parent;
420   GstDecodeBin *dbin;
421
422   GMutex lock;                  /* Protects this chain and its groups */
423
424   GstPad *pad;                  /* srcpad that caused creation of this chain */
425
426   gboolean drained;             /* TRUE if the all children are drained */
427   gboolean demuxer;             /* TRUE if elements->data is a demuxer */
428   gboolean adaptive_demuxer;    /* TRUE if elements->data is an adaptive streaming demuxer */
429   gboolean seekable;            /* TRUE if this chain ends on a demuxer and is seekable */
430   GList *elements;              /* All elements in this group, first
431                                    is the latest and most downstream element */
432
433   /* Note: there are only groups if the last element of this chain
434    * is a demuxer, otherwise the chain will end with an endpad.
435    * The other way around this means, that endpad only exists if this
436    * chain doesn't end with a demuxer! */
437
438   GstDecodeGroup *active_group; /* Currently active group */
439   GList *next_groups;           /* head is newest group, tail is next group.
440                                    a new group will be created only if the head
441                                    group had no-more-pads. If it's only exposed
442                                    all new pads will be ignored! */
443   GList *pending_pads;          /* Pads that have no fixed caps yet */
444
445   GstDecodePad *current_pad;    /* Current ending pad of the chain that can't
446                                  * be exposed yet but would be the same as endpad
447                                  * once it can be exposed */
448   GstDecodePad *endpad;         /* Pad of this chain that could be exposed */
449   gboolean deadend;             /* This chain is incomplete and can't be completed,
450                                    e.g. no suitable decoder could be found
451                                    e.g. stream got EOS without buffers
452                                  */
453   gchar *deadend_details;
454   GstCaps *endcaps;             /* Caps that were used when linking to the endpad
455                                    or that resulted in the deadend
456                                  */
457
458   /* FIXME: This should be done directly via a thread! */
459   GList *old_groups;            /* Groups that should be freed later */
460 };
461
462 static void gst_decode_chain_free (GstDecodeChain * chain);
463 static GstDecodeChain *gst_decode_chain_new (GstDecodeBin * dbin,
464     GstDecodeGroup * group, GstPad * pad);
465 static void gst_decode_group_hide (GstDecodeGroup * group);
466 static void gst_decode_group_free (GstDecodeGroup * group);
467 static GstDecodeGroup *gst_decode_group_new (GstDecodeBin * dbin,
468     GstDecodeChain * chain);
469 static gboolean gst_decode_chain_is_complete (GstDecodeChain * chain);
470 static gboolean gst_decode_chain_expose (GstDecodeChain * chain,
471     GList ** endpads, gboolean * missing_plugin,
472     GString * missing_plugin_details, gboolean * last_group);
473 static gboolean gst_decode_chain_is_drained (GstDecodeChain * chain);
474 static gboolean gst_decode_chain_reset_buffering (GstDecodeChain * chain);
475 static gboolean gst_decode_group_is_complete (GstDecodeGroup * group);
476 static GstPad *gst_decode_group_control_demuxer_pad (GstDecodeGroup * group,
477     GstPad * pad);
478 static gboolean gst_decode_group_is_drained (GstDecodeGroup * group);
479 static gboolean gst_decode_group_reset_buffering (GstDecodeGroup * group);
480
481 static gboolean gst_decode_bin_expose (GstDecodeBin * dbin);
482 static void gst_decode_bin_reset_buffering (GstDecodeBin * dbin);
483
484 #define CHAIN_MUTEX_LOCK(chain) G_STMT_START {                          \
485     GST_LOG_OBJECT (chain->dbin,                                        \
486                     "locking chain %p from thread %p",                  \
487                     chain, g_thread_self ());                           \
488     g_mutex_lock (&chain->lock);                                                \
489     GST_LOG_OBJECT (chain->dbin,                                        \
490                     "locked chain %p from thread %p",                   \
491                     chain, g_thread_self ());                           \
492 } G_STMT_END
493
494 #define CHAIN_MUTEX_UNLOCK(chain) G_STMT_START {                        \
495     GST_LOG_OBJECT (chain->dbin,                                        \
496                     "unlocking chain %p from thread %p",                \
497                     chain, g_thread_self ());                           \
498     g_mutex_unlock (&chain->lock);                                      \
499 } G_STMT_END
500
501 /* GstDecodePad
502  *
503  * GstPad private used for source pads of chains
504  */
505 struct _GstDecodePad
506 {
507   GstGhostPad parent;
508   GstDecodeBin *dbin;
509   GstDecodeChain *chain;
510
511   gboolean blocked;             /* the *target* pad is blocked */
512   gboolean exposed;             /* the pad is exposed */
513   gboolean drained;             /* an EOS has been seen on the pad */
514
515   gulong block_id;
516 };
517
518 GType gst_decode_pad_get_type (void);
519 G_DEFINE_TYPE (GstDecodePad, gst_decode_pad, GST_TYPE_GHOST_PAD);
520 #define GST_TYPE_DECODE_PAD (gst_decode_pad_get_type ())
521 #define GST_DECODE_PAD(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_DECODE_PAD,GstDecodePad))
522
523 static GstDecodePad *gst_decode_pad_new (GstDecodeBin * dbin,
524     GstDecodeChain * chain);
525 static void gst_decode_pad_activate (GstDecodePad * dpad,
526     GstDecodeChain * chain);
527 static void gst_decode_pad_unblock (GstDecodePad * dpad);
528 static void gst_decode_pad_set_blocked (GstDecodePad * dpad, gboolean blocked);
529 static gboolean gst_decode_pad_query (GstPad * pad, GstObject * parent,
530     GstQuery * query);
531
532 static void gst_pending_pad_free (GstPendingPad * ppad);
533 static GstPadProbeReturn pad_event_cb (GstPad * pad, GstPadProbeInfo * info,
534     gpointer data);
535
536 /********************************
537  * Standard GObject boilerplate *
538  ********************************/
539
540 static void gst_decode_bin_class_init (GstDecodeBinClass * klass);
541 static void gst_decode_bin_init (GstDecodeBin * decode_bin);
542 static void gst_decode_bin_dispose (GObject * object);
543 static void gst_decode_bin_finalize (GObject * object);
544
545 static GType
546 gst_decode_bin_get_type (void)
547 {
548   static GType gst_decode_bin_type = 0;
549
550   if (!gst_decode_bin_type) {
551     static const GTypeInfo gst_decode_bin_info = {
552       sizeof (GstDecodeBinClass),
553       NULL,
554       NULL,
555       (GClassInitFunc) gst_decode_bin_class_init,
556       NULL,
557       NULL,
558       sizeof (GstDecodeBin),
559       0,
560       (GInstanceInitFunc) gst_decode_bin_init,
561       NULL
562     };
563
564     gst_decode_bin_type =
565         g_type_register_static (GST_TYPE_BIN, "GstDecodeBin",
566         &gst_decode_bin_info, 0);
567   }
568
569   return gst_decode_bin_type;
570 }
571
572 static gboolean
573 _gst_boolean_accumulator (GSignalInvocationHint * ihint,
574     GValue * return_accu, const GValue * handler_return, gpointer dummy)
575 {
576   gboolean myboolean;
577
578   myboolean = g_value_get_boolean (handler_return);
579   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
580     g_value_set_boolean (return_accu, myboolean);
581
582   /* stop emission if FALSE */
583   return myboolean;
584 }
585
586 static gboolean
587 _gst_boolean_or_accumulator (GSignalInvocationHint * ihint,
588     GValue * return_accu, const GValue * handler_return, gpointer dummy)
589 {
590   gboolean myboolean;
591   gboolean retboolean;
592
593   myboolean = g_value_get_boolean (handler_return);
594   retboolean = g_value_get_boolean (return_accu);
595
596   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
597     g_value_set_boolean (return_accu, myboolean || retboolean);
598
599   return TRUE;
600 }
601
602 /* we collect the first result */
603 static gboolean
604 _gst_array_accumulator (GSignalInvocationHint * ihint,
605     GValue * return_accu, const GValue * handler_return, gpointer dummy)
606 {
607   gpointer array;
608
609   array = g_value_get_boxed (handler_return);
610   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
611     g_value_set_boxed (return_accu, array);
612
613   return FALSE;
614 }
615
616 static gboolean
617 _gst_select_accumulator (GSignalInvocationHint * ihint,
618     GValue * return_accu, const GValue * handler_return, gpointer dummy)
619 {
620   GstAutoplugSelectResult res;
621
622   res = g_value_get_enum (handler_return);
623   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
624     g_value_set_enum (return_accu, res);
625
626   /* Call the next handler in the chain (if any) when the current callback
627    * returns TRY. This makes it possible to register separate autoplug-select
628    * handlers that implement different TRY/EXPOSE/SKIP strategies.
629    */
630   if (res == GST_AUTOPLUG_SELECT_TRY)
631     return TRUE;
632
633   return FALSE;
634 }
635
636 static gboolean
637 _gst_array_hasvalue_accumulator (GSignalInvocationHint * ihint,
638     GValue * return_accu, const GValue * handler_return, gpointer dummy)
639 {
640   gpointer array;
641
642   array = g_value_get_boxed (handler_return);
643   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
644     g_value_set_boxed (return_accu, array);
645
646   if (array != NULL)
647     return FALSE;
648
649   return TRUE;
650 }
651
652 static void
653 gst_decode_bin_class_init (GstDecodeBinClass * klass)
654 {
655   GObjectClass *gobject_klass;
656   GstElementClass *gstelement_klass;
657   GstBinClass *gstbin_klass;
658
659   gobject_klass = (GObjectClass *) klass;
660   gstelement_klass = (GstElementClass *) klass;
661   gstbin_klass = (GstBinClass *) klass;
662
663   parent_class = g_type_class_peek_parent (klass);
664
665   gobject_klass->dispose = gst_decode_bin_dispose;
666   gobject_klass->finalize = gst_decode_bin_finalize;
667   gobject_klass->set_property = gst_decode_bin_set_property;
668   gobject_klass->get_property = gst_decode_bin_get_property;
669
670   /**
671    * GstDecodeBin::unknown-type:
672    * @bin: The decodebin.
673    * @pad: The new pad containing caps that cannot be resolved to a 'final'
674    *       stream type.
675    * @caps: The #GstCaps of the pad that cannot be resolved.
676    *
677    * This signal is emitted when a pad for which there is no further possible
678    * decoding is added to the decodebin.
679    */
680   gst_decode_bin_signals[SIGNAL_UNKNOWN_TYPE] =
681       g_signal_new ("unknown-type", G_TYPE_FROM_CLASS (klass),
682       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, unknown_type),
683       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
684       GST_TYPE_PAD, GST_TYPE_CAPS);
685
686   /**
687    * GstDecodeBin::autoplug-continue:
688    * @bin: The decodebin.
689    * @pad: The #GstPad.
690    * @caps: The #GstCaps found.
691    *
692    * This signal is emitted whenever decodebin finds a new stream. It is
693    * emitted before looking for any elements that can handle that stream.
694    *
695    * <note>
696    *   Invocation of signal handlers stops after the first signal handler
697    *   returns #FALSE. Signal handlers are invoked in the order they were
698    *   connected in.
699    * </note>
700    *
701    * Returns: #TRUE if you wish decodebin to look for elements that can
702    * handle the given @caps. If #FALSE, those caps will be considered as
703    * final and the pad will be exposed as such (see 'pad-added' signal of
704    * #GstElement).
705    */
706   gst_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE] =
707       g_signal_new ("autoplug-continue", G_TYPE_FROM_CLASS (klass),
708       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_continue),
709       _gst_boolean_accumulator, NULL, g_cclosure_marshal_generic,
710       G_TYPE_BOOLEAN, 2, GST_TYPE_PAD, GST_TYPE_CAPS);
711
712   /**
713    * GstDecodeBin::autoplug-factories:
714    * @bin: The decodebin.
715    * @pad: The #GstPad.
716    * @caps: The #GstCaps found.
717    *
718    * This function is emited when an array of possible factories for @caps on
719    * @pad is needed. Decodebin will by default return an array with all
720    * compatible factories, sorted by rank.
721    *
722    * If this function returns NULL, @pad will be exposed as a final caps.
723    *
724    * If this function returns an empty array, the pad will be considered as
725    * having an unhandled type media type.
726    *
727    * <note>
728    *   Only the signal handler that is connected first will ever by invoked.
729    *   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
730    *   signal, they will never be invoked!
731    * </note>
732    *
733    * Returns: a #GValueArray* with a list of factories to try. The factories are
734    * by default tried in the returned order or based on the index returned by
735    * "autoplug-select".
736    */
737   gst_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES] =
738       g_signal_new ("autoplug-factories", G_TYPE_FROM_CLASS (klass),
739       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass,
740           autoplug_factories), _gst_array_accumulator, NULL,
741       g_cclosure_marshal_generic, G_TYPE_VALUE_ARRAY, 2,
742       GST_TYPE_PAD, GST_TYPE_CAPS);
743
744   /**
745    * GstDecodeBin::autoplug-sort:
746    * @bin: The decodebin.
747    * @pad: The #GstPad.
748    * @caps: The #GstCaps.
749    * @factories: A #GValueArray of possible #GstElementFactory to use.
750    *
751    * Once decodebin has found the possible #GstElementFactory objects to try
752    * for @caps on @pad, this signal is emited. The purpose of the signal is for
753    * the application to perform additional sorting or filtering on the element
754    * factory array.
755    *
756    * The callee should copy and modify @factories or return #NULL if the
757    * order should not change.
758    *
759    * <note>
760    *   Invocation of signal handlers stops after one signal handler has
761    *   returned something else than #NULL. Signal handlers are invoked in
762    *   the order they were connected in.
763    *   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
764    *   signal, they will never be invoked!
765    * </note>
766    *
767    * Returns: A new sorted array of #GstElementFactory objects.
768    */
769   gst_decode_bin_signals[SIGNAL_AUTOPLUG_SORT] =
770       g_signal_new ("autoplug-sort", G_TYPE_FROM_CLASS (klass),
771       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_sort),
772       _gst_array_hasvalue_accumulator, NULL,
773       g_cclosure_marshal_generic, G_TYPE_VALUE_ARRAY, 3, GST_TYPE_PAD,
774       GST_TYPE_CAPS, G_TYPE_VALUE_ARRAY | G_SIGNAL_TYPE_STATIC_SCOPE);
775
776   /**
777    * GstDecodeBin::autoplug-select:
778    * @bin: The decodebin.
779    * @pad: The #GstPad.
780    * @caps: The #GstCaps.
781    * @factory: A #GstElementFactory to use.
782    *
783    * This signal is emitted once decodebin has found all the possible
784    * #GstElementFactory that can be used to handle the given @caps. For each of
785    * those factories, this signal is emitted.
786    *
787    * The signal handler should return a #GST_TYPE_AUTOPLUG_SELECT_RESULT enum
788    * value indicating what decodebin should do next.
789    *
790    * A value of #GST_AUTOPLUG_SELECT_TRY will try to autoplug an element from
791    * @factory.
792    *
793    * A value of #GST_AUTOPLUG_SELECT_EXPOSE will expose @pad without plugging
794    * any element to it.
795    *
796    * A value of #GST_AUTOPLUG_SELECT_SKIP will skip @factory and move to the
797    * next factory.
798    *
799    * <note>
800    *   The signal handler will not be invoked if any of the previously
801    *   registered signal handlers (if any) return a value other than
802    *   GST_AUTOPLUG_SELECT_TRY. Which also means that if you return
803    *   GST_AUTOPLUG_SELECT_TRY from one signal handler, handlers that get
804    *   registered next (again, if any) can override that decision.
805    * </note>
806    *
807    * Returns: a #GST_TYPE_AUTOPLUG_SELECT_RESULT that indicates the required
808    * operation. the default handler will always return
809    * #GST_AUTOPLUG_SELECT_TRY.
810    */
811   gst_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT] =
812       g_signal_new ("autoplug-select", G_TYPE_FROM_CLASS (klass),
813       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_select),
814       _gst_select_accumulator, NULL,
815       g_cclosure_marshal_generic,
816       GST_TYPE_AUTOPLUG_SELECT_RESULT, 3, GST_TYPE_PAD, GST_TYPE_CAPS,
817       GST_TYPE_ELEMENT_FACTORY);
818
819   /**
820    * GstDecodeBin::autoplug-query:
821    * @bin: The decodebin.
822    * @child: The child element doing the query
823    * @pad: The #GstPad.
824    * @element: The #GstElement.
825    * @query: The #GstQuery.
826    *
827    * This signal is emitted whenever an autoplugged element that is
828    * not linked downstream yet and not exposed does a query. It can
829    * be used to tell the element about the downstream supported caps
830    * for example.
831    *
832    * Returns: #TRUE if the query was handled, #FALSE otherwise.
833    */
834   gst_decode_bin_signals[SIGNAL_AUTOPLUG_QUERY] =
835       g_signal_new ("autoplug-query", G_TYPE_FROM_CLASS (klass),
836       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_query),
837       _gst_boolean_or_accumulator, NULL, g_cclosure_marshal_generic,
838       G_TYPE_BOOLEAN, 3, GST_TYPE_PAD, GST_TYPE_ELEMENT,
839       GST_TYPE_QUERY | G_SIGNAL_TYPE_STATIC_SCOPE);
840
841   /**
842    * GstDecodeBin::drained
843    * @bin: The decodebin
844    *
845    * This signal is emitted once decodebin has finished decoding all the data.
846    */
847   gst_decode_bin_signals[SIGNAL_DRAINED] =
848       g_signal_new ("drained", G_TYPE_FROM_CLASS (klass),
849       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, drained),
850       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 0, G_TYPE_NONE);
851
852   g_object_class_install_property (gobject_klass, PROP_CAPS,
853       g_param_spec_boxed ("caps", "Caps", "The caps on which to stop decoding.",
854           GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
855
856   g_object_class_install_property (gobject_klass, PROP_SUBTITLE_ENCODING,
857       g_param_spec_string ("subtitle-encoding", "subtitle encoding",
858           "Encoding to assume if input subtitles are not in UTF-8 encoding. "
859           "If not set, the GST_SUBTITLE_ENCODING environment variable will "
860           "be checked for an encoding to use. If that is not set either, "
861           "ISO-8859-15 will be assumed.", NULL,
862           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
863
864   g_object_class_install_property (gobject_klass, PROP_SINK_CAPS,
865       g_param_spec_boxed ("sink-caps", "Sink Caps",
866           "The caps of the input data. (NULL = use typefind element)",
867           GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
868
869   /**
870    * GstDecodeBin::use-buffering
871    *
872    * Activate buffering in decodebin. This will instruct the multiqueues behind
873    * decoders to emit BUFFERING messages.
874    */
875   g_object_class_install_property (gobject_klass, PROP_USE_BUFFERING,
876       g_param_spec_boolean ("use-buffering", "Use Buffering",
877           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
878           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
879
880   /**
881    * GstDecodeBin:low-percent
882    *
883    * Low threshold percent for buffering to start.
884    */
885   g_object_class_install_property (gobject_klass, PROP_LOW_PERCENT,
886       g_param_spec_int ("low-percent", "Low percent",
887           "Low threshold for buffering to start", 0, 100,
888           DEFAULT_LOW_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
889   /**
890    * GstDecodeBin:high-percent
891    *
892    * High threshold percent for buffering to finish.
893    */
894   g_object_class_install_property (gobject_klass, PROP_HIGH_PERCENT,
895       g_param_spec_int ("high-percent", "High percent",
896           "High threshold for buffering to finish", 0, 100,
897           DEFAULT_HIGH_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
898
899   /**
900    * GstDecodeBin:max-size-bytes
901    *
902    * Max amount of bytes in the queue (0=automatic).
903    */
904   g_object_class_install_property (gobject_klass, PROP_MAX_SIZE_BYTES,
905       g_param_spec_uint ("max-size-bytes", "Max. size (bytes)",
906           "Max. amount of bytes in the queue (0=automatic)",
907           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
908           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
909   /**
910    * GstDecodeBin:max-size-buffers
911    *
912    * Max amount of buffers in the queue (0=automatic).
913    */
914   g_object_class_install_property (gobject_klass, PROP_MAX_SIZE_BUFFERS,
915       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
916           "Max. number of buffers in the queue (0=automatic)",
917           0, G_MAXUINT, DEFAULT_MAX_SIZE_BUFFERS,
918           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
919   /**
920    * GstDecodeBin:max-size-time
921    *
922    * Max amount of time in the queue (in ns, 0=automatic).
923    */
924   g_object_class_install_property (gobject_klass, PROP_MAX_SIZE_TIME,
925       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
926           "Max. amount of data in the queue (in ns, 0=automatic)",
927           0, G_MAXUINT64,
928           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
929
930   /**
931    * GstDecodeBin::post-stream-topology
932    *
933    * Post stream-topology messages on the bus every time the topology changes.
934    */
935   g_object_class_install_property (gobject_klass, PROP_POST_STREAM_TOPOLOGY,
936       g_param_spec_boolean ("post-stream-topology", "Post Stream Topology",
937           "Post stream-topology messages",
938           DEFAULT_POST_STREAM_TOPOLOGY,
939           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
940
941   /**
942    * GstDecodeBin::expose-all-streams
943    *
944    * Expose streams of unknown type.
945    *
946    * If set to %FALSE, then only the streams that can be decoded to the final
947    * caps (see 'caps' property) will have a pad exposed. Streams that do not
948    * match those caps but could have been decoded will not have decoder plugged
949    * in internally and will not have a pad exposed.
950    */
951   g_object_class_install_property (gobject_klass, PROP_EXPOSE_ALL_STREAMS,
952       g_param_spec_boolean ("expose-all-streams", "Expose All Streams",
953           "Expose all streams, including those of unknown type or that don't match the 'caps' property",
954           DEFAULT_EXPOSE_ALL_STREAMS,
955           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
956
957   /**
958    * GstDecodeBin2::connection-speed
959    *
960    * Network connection speed in kbps (0 = unknownw)
961    */
962   g_object_class_install_property (gobject_klass, PROP_CONNECTION_SPEED,
963       g_param_spec_uint64 ("connection-speed", "Connection Speed",
964           "Network connection speed in kbps (0 = unknown)",
965           0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
966           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
967
968
969
970   klass->autoplug_continue =
971       GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_continue);
972   klass->autoplug_factories =
973       GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_factories);
974   klass->autoplug_sort = GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_sort);
975   klass->autoplug_select = GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_select);
976   klass->autoplug_query = GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_query);
977
978   gst_element_class_add_pad_template (gstelement_klass,
979       gst_static_pad_template_get (&decoder_bin_sink_template));
980   gst_element_class_add_pad_template (gstelement_klass,
981       gst_static_pad_template_get (&decoder_bin_src_template));
982
983   gst_element_class_set_static_metadata (gstelement_klass,
984       "Decoder Bin", "Generic/Bin/Decoder",
985       "Autoplug and decode to raw media",
986       "Edward Hervey <edward.hervey@collabora.co.uk>, "
987       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
988
989   gstelement_klass->change_state =
990       GST_DEBUG_FUNCPTR (gst_decode_bin_change_state);
991
992   gstbin_klass->handle_message =
993       GST_DEBUG_FUNCPTR (gst_decode_bin_handle_message);
994
995   g_type_class_ref (GST_TYPE_DECODE_PAD);
996 }
997
998 gint
999 _decode_bin_compare_factories_func (gconstpointer p1, gconstpointer p2)
1000 {
1001   GstPluginFeature *f1, *f2;
1002   gboolean is_parser1, is_parser2;
1003
1004   f1 = (GstPluginFeature *) p1;
1005   f2 = (GstPluginFeature *) p2;
1006
1007   is_parser1 = gst_element_factory_list_is_type (GST_ELEMENT_FACTORY_CAST (f1),
1008       GST_ELEMENT_FACTORY_TYPE_PARSER);
1009   is_parser2 = gst_element_factory_list_is_type (GST_ELEMENT_FACTORY_CAST (f2),
1010       GST_ELEMENT_FACTORY_TYPE_PARSER);
1011
1012
1013   /* We want all parsers first as we always want to plug parsers
1014    * before decoders */
1015   if (is_parser1 && !is_parser2)
1016     return -1;
1017   else if (!is_parser1 && is_parser2)
1018     return 1;
1019
1020   /* And if it's a both a parser we first sort by rank
1021    * and then by factory name */
1022   return gst_plugin_feature_rank_compare_func (p1, p2);
1023 }
1024
1025 /* Must be called with factories lock! */
1026 static void
1027 gst_decode_bin_update_factories_list (GstDecodeBin * dbin)
1028 {
1029   guint cookie;
1030
1031   cookie = gst_registry_get_feature_list_cookie (gst_registry_get ());
1032   if (!dbin->factories || dbin->factories_cookie != cookie) {
1033     if (dbin->factories)
1034       gst_plugin_feature_list_free (dbin->factories);
1035     dbin->factories =
1036         gst_element_factory_list_get_elements
1037         (GST_ELEMENT_FACTORY_TYPE_DECODABLE, GST_RANK_MARGINAL);
1038     dbin->factories =
1039         g_list_sort (dbin->factories, _decode_bin_compare_factories_func);
1040     dbin->factories_cookie = cookie;
1041   }
1042 }
1043
1044 static void
1045 gst_decode_bin_init (GstDecodeBin * decode_bin)
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
1081   g_mutex_init (&decode_bin->expose_lock);
1082   decode_bin->decode_chain = NULL;
1083
1084   g_mutex_init (&decode_bin->dyn_lock);
1085   decode_bin->shutdown = FALSE;
1086   decode_bin->blocked_pads = NULL;
1087
1088   g_mutex_init (&decode_bin->subtitle_lock);
1089
1090   decode_bin->encoding = g_strdup (DEFAULT_SUBTITLE_ENCODING);
1091   decode_bin->caps = gst_static_caps_get (&default_raw_caps);
1092   decode_bin->use_buffering = DEFAULT_USE_BUFFERING;
1093   decode_bin->low_percent = DEFAULT_LOW_PERCENT;
1094   decode_bin->high_percent = DEFAULT_HIGH_PERCENT;
1095
1096   decode_bin->max_size_bytes = DEFAULT_MAX_SIZE_BYTES;
1097   decode_bin->max_size_buffers = DEFAULT_MAX_SIZE_BUFFERS;
1098   decode_bin->max_size_time = DEFAULT_MAX_SIZE_TIME;
1099
1100   decode_bin->expose_allstreams = DEFAULT_EXPOSE_ALL_STREAMS;
1101   decode_bin->connection_speed = DEFAULT_CONNECTION_SPEED;
1102 }
1103
1104 static void
1105 gst_decode_bin_dispose (GObject * object)
1106 {
1107   GstDecodeBin *decode_bin;
1108
1109   decode_bin = GST_DECODE_BIN (object);
1110
1111   if (decode_bin->factories)
1112     gst_plugin_feature_list_free (decode_bin->factories);
1113   decode_bin->factories = NULL;
1114
1115   if (decode_bin->decode_chain)
1116     gst_decode_chain_free (decode_bin->decode_chain);
1117   decode_bin->decode_chain = NULL;
1118
1119   if (decode_bin->caps)
1120     gst_caps_unref (decode_bin->caps);
1121   decode_bin->caps = NULL;
1122
1123   g_free (decode_bin->encoding);
1124   decode_bin->encoding = NULL;
1125
1126   g_list_free (decode_bin->subtitles);
1127   decode_bin->subtitles = NULL;
1128
1129   G_OBJECT_CLASS (parent_class)->dispose (object);
1130 }
1131
1132 static void
1133 gst_decode_bin_finalize (GObject * object)
1134 {
1135   GstDecodeBin *decode_bin;
1136
1137   decode_bin = GST_DECODE_BIN (object);
1138
1139   g_mutex_clear (&decode_bin->expose_lock);
1140   g_mutex_clear (&decode_bin->dyn_lock);
1141   g_mutex_clear (&decode_bin->subtitle_lock);
1142   g_mutex_clear (&decode_bin->factories_lock);
1143
1144   G_OBJECT_CLASS (parent_class)->finalize (object);
1145 }
1146
1147 /* _set_caps
1148  * Changes the caps on which decodebin will stop decoding.
1149  * Will unref the previously set one. The refcount of the given caps will be
1150  * increased.
1151  * @caps can be NULL.
1152  *
1153  * MT-safe
1154  */
1155 static void
1156 gst_decode_bin_set_caps (GstDecodeBin * dbin, GstCaps * caps)
1157 {
1158   GST_DEBUG_OBJECT (dbin, "Setting new caps: %" GST_PTR_FORMAT, caps);
1159
1160   GST_OBJECT_LOCK (dbin);
1161   gst_caps_replace (&dbin->caps, caps);
1162   GST_OBJECT_UNLOCK (dbin);
1163 }
1164
1165 /* _get_caps
1166  * Returns the currently configured caps on which decodebin will stop decoding.
1167  * The returned caps (if not NULL), will have its refcount incremented.
1168  *
1169  * MT-safe
1170  */
1171 static GstCaps *
1172 gst_decode_bin_get_caps (GstDecodeBin * dbin)
1173 {
1174   GstCaps *caps;
1175
1176   GST_DEBUG_OBJECT (dbin, "Getting currently set caps");
1177
1178   GST_OBJECT_LOCK (dbin);
1179   caps = dbin->caps;
1180   if (caps)
1181     gst_caps_ref (caps);
1182   GST_OBJECT_UNLOCK (dbin);
1183
1184   return caps;
1185 }
1186
1187 static void
1188 gst_decode_bin_set_sink_caps (GstDecodeBin * dbin, GstCaps * caps)
1189 {
1190   GST_DEBUG_OBJECT (dbin, "Setting new caps: %" GST_PTR_FORMAT, caps);
1191
1192   g_object_set (dbin->typefind, "force-caps", caps, NULL);
1193 }
1194
1195 static GstCaps *
1196 gst_decode_bin_get_sink_caps (GstDecodeBin * dbin)
1197 {
1198   GstCaps *caps;
1199
1200   GST_DEBUG_OBJECT (dbin, "Getting currently set caps");
1201
1202   g_object_get (dbin->typefind, "force-caps", &caps, NULL);
1203
1204   return caps;
1205 }
1206
1207 static void
1208 gst_decode_bin_set_subs_encoding (GstDecodeBin * dbin, const gchar * encoding)
1209 {
1210   GList *walk;
1211
1212   GST_DEBUG_OBJECT (dbin, "Setting new encoding: %s", GST_STR_NULL (encoding));
1213
1214   SUBTITLE_LOCK (dbin);
1215   g_free (dbin->encoding);
1216   dbin->encoding = g_strdup (encoding);
1217
1218   /* set the subtitle encoding on all added elements */
1219   for (walk = dbin->subtitles; walk; walk = g_list_next (walk)) {
1220     g_object_set (G_OBJECT (walk->data), "subtitle-encoding", dbin->encoding,
1221         NULL);
1222   }
1223   SUBTITLE_UNLOCK (dbin);
1224 }
1225
1226 static gchar *
1227 gst_decode_bin_get_subs_encoding (GstDecodeBin * dbin)
1228 {
1229   gchar *encoding;
1230
1231   GST_DEBUG_OBJECT (dbin, "Getting currently set encoding");
1232
1233   SUBTITLE_LOCK (dbin);
1234   encoding = g_strdup (dbin->encoding);
1235   SUBTITLE_UNLOCK (dbin);
1236
1237   return encoding;
1238 }
1239
1240 static void
1241 gst_decode_bin_set_property (GObject * object, guint prop_id,
1242     const GValue * value, GParamSpec * pspec)
1243 {
1244   GstDecodeBin *dbin;
1245
1246   dbin = GST_DECODE_BIN (object);
1247
1248   switch (prop_id) {
1249     case PROP_CAPS:
1250       gst_decode_bin_set_caps (dbin, g_value_get_boxed (value));
1251       break;
1252     case PROP_SUBTITLE_ENCODING:
1253       gst_decode_bin_set_subs_encoding (dbin, g_value_get_string (value));
1254       break;
1255     case PROP_SINK_CAPS:
1256       gst_decode_bin_set_sink_caps (dbin, g_value_get_boxed (value));
1257       break;
1258     case PROP_USE_BUFFERING:
1259       dbin->use_buffering = g_value_get_boolean (value);
1260       break;
1261     case PROP_LOW_PERCENT:
1262       dbin->low_percent = g_value_get_int (value);
1263       break;
1264     case PROP_HIGH_PERCENT:
1265       dbin->high_percent = g_value_get_int (value);
1266       break;
1267     case PROP_MAX_SIZE_BYTES:
1268       dbin->max_size_bytes = g_value_get_uint (value);
1269       break;
1270     case PROP_MAX_SIZE_BUFFERS:
1271       dbin->max_size_buffers = g_value_get_uint (value);
1272       break;
1273     case PROP_MAX_SIZE_TIME:
1274       dbin->max_size_time = g_value_get_uint64 (value);
1275       break;
1276     case PROP_POST_STREAM_TOPOLOGY:
1277       dbin->post_stream_topology = g_value_get_boolean (value);
1278       break;
1279     case PROP_EXPOSE_ALL_STREAMS:
1280       dbin->expose_allstreams = g_value_get_boolean (value);
1281       break;
1282     case PROP_CONNECTION_SPEED:
1283       GST_OBJECT_LOCK (dbin);
1284       dbin->connection_speed = g_value_get_uint64 (value) * 1000;
1285       GST_OBJECT_UNLOCK (dbin);
1286       break;
1287     default:
1288       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1289       break;
1290   }
1291 }
1292
1293 static void
1294 gst_decode_bin_get_property (GObject * object, guint prop_id,
1295     GValue * value, GParamSpec * pspec)
1296 {
1297   GstDecodeBin *dbin;
1298
1299   dbin = GST_DECODE_BIN (object);
1300   switch (prop_id) {
1301     case PROP_CAPS:
1302       g_value_take_boxed (value, gst_decode_bin_get_caps (dbin));
1303       break;
1304     case PROP_SUBTITLE_ENCODING:
1305       g_value_take_string (value, gst_decode_bin_get_subs_encoding (dbin));
1306       break;
1307     case PROP_SINK_CAPS:
1308       g_value_take_boxed (value, gst_decode_bin_get_sink_caps (dbin));
1309       break;
1310     case PROP_USE_BUFFERING:
1311       g_value_set_boolean (value, dbin->use_buffering);
1312       break;
1313     case PROP_LOW_PERCENT:
1314       g_value_set_int (value, dbin->low_percent);
1315       break;
1316     case PROP_HIGH_PERCENT:
1317       g_value_set_int (value, dbin->high_percent);
1318       break;
1319     case PROP_MAX_SIZE_BYTES:
1320       g_value_set_uint (value, dbin->max_size_bytes);
1321       break;
1322     case PROP_MAX_SIZE_BUFFERS:
1323       g_value_set_uint (value, dbin->max_size_buffers);
1324       break;
1325     case PROP_MAX_SIZE_TIME:
1326       g_value_set_uint64 (value, dbin->max_size_time);
1327       break;
1328     case PROP_POST_STREAM_TOPOLOGY:
1329       g_value_set_boolean (value, dbin->post_stream_topology);
1330       break;
1331     case PROP_EXPOSE_ALL_STREAMS:
1332       g_value_set_boolean (value, dbin->expose_allstreams);
1333       break;
1334     case PROP_CONNECTION_SPEED:
1335       GST_OBJECT_LOCK (dbin);
1336       g_value_set_uint64 (value, dbin->connection_speed / 1000);
1337       GST_OBJECT_UNLOCK (dbin);
1338       break;
1339     default:
1340       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1341       break;
1342   }
1343 }
1344
1345
1346 /*****
1347  * Default autoplug signal handlers
1348  *****/
1349 static gboolean
1350 gst_decode_bin_autoplug_continue (GstElement * element, GstPad * pad,
1351     GstCaps * caps)
1352 {
1353   GST_DEBUG_OBJECT (element, "autoplug-continue returns TRUE");
1354
1355   /* by default we always continue */
1356   return TRUE;
1357 }
1358
1359 static GValueArray *
1360 gst_decode_bin_autoplug_factories (GstElement * element, GstPad * pad,
1361     GstCaps * caps)
1362 {
1363   GList *list, *tmp;
1364   GValueArray *result;
1365   GstDecodeBin *dbin = GST_DECODE_BIN_CAST (element);
1366
1367   GST_DEBUG_OBJECT (element, "finding factories");
1368
1369   /* return all compatible factories for caps */
1370   g_mutex_lock (&dbin->factories_lock);
1371   gst_decode_bin_update_factories_list (dbin);
1372   list =
1373       gst_element_factory_list_filter (dbin->factories, caps, GST_PAD_SINK,
1374       gst_caps_is_fixed (caps));
1375   g_mutex_unlock (&dbin->factories_lock);
1376
1377   result = g_value_array_new (g_list_length (list));
1378   for (tmp = list; tmp; tmp = tmp->next) {
1379     GstElementFactory *factory = GST_ELEMENT_FACTORY_CAST (tmp->data);
1380     GValue val = { 0, };
1381
1382     g_value_init (&val, G_TYPE_OBJECT);
1383     g_value_set_object (&val, factory);
1384     g_value_array_append (result, &val);
1385     g_value_unset (&val);
1386   }
1387   gst_plugin_feature_list_free (list);
1388
1389   GST_DEBUG_OBJECT (element, "autoplug-factories returns %p", result);
1390
1391   return result;
1392 }
1393
1394 static GValueArray *
1395 gst_decode_bin_autoplug_sort (GstElement * element, GstPad * pad,
1396     GstCaps * caps, GValueArray * factories)
1397 {
1398   return NULL;
1399 }
1400
1401 static GstAutoplugSelectResult
1402 gst_decode_bin_autoplug_select (GstElement * element, GstPad * pad,
1403     GstCaps * caps, GstElementFactory * factory)
1404 {
1405   GST_DEBUG_OBJECT (element, "default autoplug-select returns TRY");
1406
1407   /* Try factory. */
1408   return GST_AUTOPLUG_SELECT_TRY;
1409 }
1410
1411 static gboolean
1412 gst_decode_bin_autoplug_query (GstElement * element, GstPad * pad,
1413     GstQuery * query)
1414 {
1415   /* No query handled here */
1416   return FALSE;
1417 }
1418
1419 /********
1420  * Discovery methods
1421  *****/
1422
1423 static gboolean are_final_caps (GstDecodeBin * dbin, GstCaps * caps);
1424 static gboolean is_demuxer_element (GstElement * srcelement);
1425 static gboolean is_adaptive_demuxer_element (GstElement * srcelement);
1426
1427 static gboolean connect_pad (GstDecodeBin * dbin, GstElement * src,
1428     GstDecodePad * dpad, GstPad * pad, GstCaps * caps, GValueArray * factories,
1429     GstDecodeChain * chain, gchar ** deadend_details);
1430 static GList *connect_element (GstDecodeBin * dbin, GstDecodeElement * delem,
1431     GstDecodeChain * chain);
1432 static void expose_pad (GstDecodeBin * dbin, GstElement * src,
1433     GstDecodePad * dpad, GstPad * pad, GstCaps * caps, GstDecodeChain * chain);
1434
1435 static void pad_added_cb (GstElement * element, GstPad * pad,
1436     GstDecodeChain * chain);
1437 static void pad_removed_cb (GstElement * element, GstPad * pad,
1438     GstDecodeChain * chain);
1439 static void no_more_pads_cb (GstElement * element, GstDecodeChain * chain);
1440
1441 static GstDecodeGroup *gst_decode_chain_get_current_group (GstDecodeChain *
1442     chain);
1443
1444 static gboolean
1445 clear_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
1446 {
1447   GST_DEBUG_OBJECT (pad, "clearing sticky event %" GST_PTR_FORMAT, *event);
1448   gst_event_unref (*event);
1449   *event = NULL;
1450   return TRUE;
1451 }
1452
1453 static gboolean
1454 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
1455 {
1456   GstPad *gpad = GST_PAD_CAST (user_data);
1457
1458   GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
1459   gst_pad_store_sticky_event (gpad, *event);
1460
1461   return TRUE;
1462 }
1463
1464 static void
1465 decode_pad_set_target (GstDecodePad * dpad, GstPad * target)
1466 {
1467   gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (dpad), target);
1468   if (target == NULL)
1469     gst_pad_sticky_events_foreach (GST_PAD_CAST (dpad), clear_sticky_events,
1470         NULL);
1471   else
1472     gst_pad_sticky_events_foreach (target, copy_sticky_events, dpad);
1473 }
1474
1475 /* called when a new pad is discovered. It will perform some basic actions
1476  * before trying to link something to it.
1477  *
1478  *  - Check the caps, don't do anything when there are no caps or when they have
1479  *    no good type.
1480  *  - signal AUTOPLUG_CONTINUE to check if we need to continue autoplugging this
1481  *    pad.
1482  *  - if the caps are non-fixed, setup a handler to continue autoplugging when
1483  *    the caps become fixed (connect to notify::caps).
1484  *  - get list of factories to autoplug.
1485  *  - continue autoplugging to one of the factories.
1486  */
1487 static void
1488 analyze_new_pad (GstDecodeBin * dbin, GstElement * src, GstPad * pad,
1489     GstCaps * caps, GstDecodeChain * chain)
1490 {
1491   gboolean apcontinue = TRUE;
1492   GValueArray *factories = NULL, *result = NULL;
1493   GstDecodePad *dpad;
1494   GstElementFactory *factory;
1495   const gchar *classification;
1496   gboolean is_parser_converter = FALSE;
1497   gboolean res;
1498   gchar *deadend_details = NULL;
1499
1500   GST_DEBUG_OBJECT (dbin, "Pad %s:%s caps:%" GST_PTR_FORMAT,
1501       GST_DEBUG_PAD_NAME (pad), caps);
1502
1503   if (chain->elements
1504       && src != ((GstDecodeElement *) chain->elements->data)->element
1505       && src != ((GstDecodeElement *) chain->elements->data)->capsfilter) {
1506     GST_ERROR_OBJECT (dbin, "New pad from not the last element in this chain");
1507     return;
1508   }
1509
1510   if (chain->endpad) {
1511     GST_ERROR_OBJECT (dbin, "New pad in a chain that is already complete");
1512     return;
1513   }
1514
1515   if (chain->demuxer) {
1516     GstDecodeGroup *group;
1517     GstDecodeChain *oldchain = chain;
1518     GstDecodeElement *demux = (chain->elements ? chain->elements->data : NULL);
1519
1520     if (chain->current_pad)
1521       gst_object_unref (chain->current_pad);
1522     chain->current_pad = NULL;
1523
1524     /* we are adding a new pad for a demuxer (see is_demuxer_element(),
1525      * start a new chain for it */
1526     CHAIN_MUTEX_LOCK (oldchain);
1527     group = gst_decode_chain_get_current_group (chain);
1528     if (group && !g_list_find (group->children, chain)) {
1529       chain = gst_decode_chain_new (dbin, group, pad);
1530       group->children = g_list_prepend (group->children, chain);
1531     }
1532     CHAIN_MUTEX_UNLOCK (oldchain);
1533     if (!group) {
1534       GST_WARNING_OBJECT (dbin, "No current group");
1535       return;
1536     }
1537
1538     /* If this is not a dynamic pad demuxer, we're no-more-pads
1539      * already before anything else happens
1540      */
1541     if (demux == NULL || !demux->no_more_pads_id)
1542       group->no_more_pads = TRUE;
1543   }
1544
1545   /* From here on we own a reference to the caps as
1546    * we might create new caps below and would need
1547    * to unref them later */
1548   if (caps)
1549     gst_caps_ref (caps);
1550
1551   if ((caps == NULL) || gst_caps_is_empty (caps))
1552     goto unknown_type;
1553
1554   if (gst_caps_is_any (caps))
1555     goto any_caps;
1556
1557   if (!chain->current_pad)
1558     chain->current_pad = gst_decode_pad_new (dbin, chain);
1559
1560   dpad = gst_object_ref (chain->current_pad);
1561   gst_pad_set_active (GST_PAD_CAST (dpad), TRUE);
1562   decode_pad_set_target (dpad, pad);
1563
1564   /* 1. Emit 'autoplug-continue' the result will tell us if this pads needs
1565    * further autoplugging. Only do this for fixed caps, for unfixed caps
1566    * we will later come here again from the notify::caps handler. The
1567    * problem with unfixed caps is that, we can't reliably tell if the output
1568    * is e.g. accepted by a sink because only parts of the possible final
1569    * caps might be accepted by the sink. */
1570   if (gst_caps_is_fixed (caps))
1571     g_signal_emit (G_OBJECT (dbin),
1572         gst_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE], 0, dpad, caps,
1573         &apcontinue);
1574   else
1575     apcontinue = TRUE;
1576
1577   /* 1.a if autoplug-continue is FALSE or caps is a raw format, goto pad_is_final */
1578   if ((!apcontinue) || are_final_caps (dbin, caps))
1579     goto expose_pad;
1580
1581   /* 1.b For Parser/Converter that can output different stream formats
1582    * we insert a capsfilter with the sorted caps of all possible next
1583    * elements and continue with the capsfilter srcpad */
1584   factory = gst_element_get_factory (src);
1585   classification =
1586       gst_element_factory_get_metadata (factory, GST_ELEMENT_METADATA_KLASS);
1587   is_parser_converter = (strstr (classification, "Parser")
1588       && strstr (classification, "Converter"));
1589
1590   /* 1.c when the caps are not fixed yet, we can't be sure what element to
1591    * connect. We delay autoplugging until the caps are fixed */
1592   if (!is_parser_converter && !gst_caps_is_fixed (caps)) {
1593     goto non_fixed;
1594   } else if (!is_parser_converter) {
1595     gst_caps_unref (caps);
1596     caps = gst_pad_get_current_caps (pad);
1597     if (!caps) {
1598       GST_DEBUG_OBJECT (dbin, "No final caps set yet, delaying autoplugging");
1599       gst_object_unref (dpad);
1600       goto setup_caps_delay;
1601     }
1602   }
1603
1604   /* 1.d else get the factories and if there's no compatible factory goto
1605    * unknown_type */
1606   g_signal_emit (G_OBJECT (dbin),
1607       gst_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES], 0, dpad, caps,
1608       &factories);
1609
1610   /* NULL means that we can expose the pad */
1611   if (factories == NULL)
1612     goto expose_pad;
1613
1614   /* if the array is empty, we have a type for which we have no decoder */
1615   if (factories->n_values == 0) {
1616     if (!dbin->expose_allstreams) {
1617       GstCaps *raw = gst_static_caps_get (&default_raw_caps);
1618
1619       /* If the caps are raw, this just means we don't want to expose them */
1620       if (gst_caps_is_subset (caps, raw)) {
1621         g_value_array_free (factories);
1622         gst_caps_unref (raw);
1623         gst_object_unref (dpad);
1624         goto discarded_type;
1625       }
1626       gst_caps_unref (raw);
1627     }
1628
1629     /* if not we have a unhandled type with no compatible factories */
1630     g_value_array_free (factories);
1631     gst_object_unref (dpad);
1632     goto unknown_type;
1633   }
1634
1635   /* 1.e sort some more. */
1636   g_signal_emit (G_OBJECT (dbin),
1637       gst_decode_bin_signals[SIGNAL_AUTOPLUG_SORT], 0, dpad, caps, factories,
1638       &result);
1639   if (result) {
1640     g_value_array_free (factories);
1641     factories = result;
1642   }
1643
1644   /* At this point we have a potential decoder, but we might not need it
1645    * if it doesn't match the output caps  */
1646   if (!dbin->expose_allstreams && gst_caps_is_fixed (caps)) {
1647     guint i;
1648     const GList *tmps;
1649     gboolean dontuse = FALSE;
1650
1651     GST_DEBUG ("Checking if we can abort early");
1652
1653     /* 1.f Do an early check to see if the candidates are potential decoders, but
1654      * due to the fact that they decode to a mediatype that is not final we don't
1655      * need them */
1656
1657     for (i = 0; i < factories->n_values && !dontuse; i++) {
1658       GstElementFactory *factory =
1659           g_value_get_object (g_value_array_get_nth (factories, i));
1660       GstCaps *tcaps;
1661
1662       /* We are only interested in skipping decoders */
1663       if (strstr (gst_element_factory_get_metadata (factory,
1664                   GST_ELEMENT_METADATA_KLASS), "Decoder")) {
1665
1666         GST_DEBUG ("Trying factory %s",
1667             gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
1668
1669         /* Check the source pad template caps to see if they match raw caps but don't match
1670          * our final caps*/
1671         for (tmps = gst_element_factory_get_static_pad_templates (factory);
1672             tmps && !dontuse; tmps = tmps->next) {
1673           GstStaticPadTemplate *st = (GstStaticPadTemplate *) tmps->data;
1674           if (st->direction != GST_PAD_SRC)
1675             continue;
1676           tcaps = gst_static_pad_template_get_caps (st);
1677
1678           apcontinue = TRUE;
1679
1680           /* Emit autoplug-continue to see if the caps are considered to be raw caps */
1681           g_signal_emit (G_OBJECT (dbin),
1682               gst_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE], 0, dpad, tcaps,
1683               &apcontinue);
1684
1685           /* If autoplug-continue returns TRUE and the caps are not final, don't use them */
1686           if (apcontinue && !are_final_caps (dbin, tcaps))
1687             dontuse = TRUE;
1688           gst_caps_unref (tcaps);
1689         }
1690       }
1691     }
1692
1693     if (dontuse) {
1694       gst_object_unref (dpad);
1695       g_value_array_free (factories);
1696       goto discarded_type;
1697     }
1698   }
1699
1700   /* 1.g now get the factory template caps and insert the capsfilter if this
1701    * is a parser/converter
1702    */
1703   if (is_parser_converter) {
1704     GstCaps *filter_caps;
1705     gint i;
1706     GstPad *p;
1707     GstDecodeElement *delem;
1708
1709     g_assert (chain->elements != NULL);
1710     delem = (GstDecodeElement *) chain->elements->data;
1711
1712     filter_caps = gst_caps_new_empty ();
1713     for (i = 0; i < factories->n_values; i++) {
1714       GstElementFactory *factory =
1715           g_value_get_object (g_value_array_get_nth (factories, i));
1716       GstCaps *tcaps, *intersection;
1717       const GList *tmps;
1718
1719       GST_DEBUG ("Trying factory %s",
1720           gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
1721
1722       if (gst_element_get_factory (src) == factory ||
1723           gst_element_factory_list_is_type (factory,
1724               GST_ELEMENT_FACTORY_TYPE_PARSER)) {
1725         GST_DEBUG ("Skipping factory");
1726         continue;
1727       }
1728
1729       for (tmps = gst_element_factory_get_static_pad_templates (factory); tmps;
1730           tmps = tmps->next) {
1731         GstStaticPadTemplate *st = (GstStaticPadTemplate *) tmps->data;
1732         if (st->direction != GST_PAD_SINK || st->presence != GST_PAD_ALWAYS)
1733           continue;
1734         tcaps = gst_static_pad_template_get_caps (st);
1735         intersection =
1736             gst_caps_intersect_full (tcaps, caps, GST_CAPS_INTERSECT_FIRST);
1737         filter_caps = gst_caps_merge (filter_caps, intersection);
1738         gst_caps_unref (tcaps);
1739       }
1740     }
1741
1742     /* Append the parser caps to prevent any not-negotiated errors */
1743     filter_caps = gst_caps_merge (filter_caps, gst_caps_ref (caps));
1744
1745     delem->capsfilter = gst_element_factory_make ("capsfilter", NULL);
1746     g_object_set (G_OBJECT (delem->capsfilter), "caps", filter_caps, NULL);
1747     gst_caps_unref (filter_caps);
1748     gst_element_set_state (delem->capsfilter, GST_STATE_PAUSED);
1749     gst_bin_add (GST_BIN_CAST (dbin), gst_object_ref (delem->capsfilter));
1750
1751     decode_pad_set_target (dpad, NULL);
1752     p = gst_element_get_static_pad (delem->capsfilter, "sink");
1753     gst_pad_link_full (pad, p, GST_PAD_LINK_CHECK_NOTHING);
1754     gst_object_unref (p);
1755     p = gst_element_get_static_pad (delem->capsfilter, "src");
1756     decode_pad_set_target (dpad, p);
1757     pad = p;
1758
1759     gst_caps_unref (caps);
1760
1761     caps = gst_pad_get_current_caps (pad);
1762     if (!caps) {
1763       GST_DEBUG_OBJECT (dbin, "No final caps set yet, delaying autoplugging");
1764       gst_object_unref (dpad);
1765       g_value_array_free (factories);
1766       goto setup_caps_delay;
1767     }
1768   }
1769
1770   /* 1.h else continue autoplugging something from the list. */
1771   GST_LOG_OBJECT (pad, "Let's continue discovery on this pad");
1772   res =
1773       connect_pad (dbin, src, dpad, pad, caps, factories, chain,
1774       &deadend_details);
1775
1776   /* Need to unref the capsfilter srcpad here if
1777    * we inserted a capsfilter */
1778   if (is_parser_converter)
1779     gst_object_unref (pad);
1780
1781   gst_object_unref (dpad);
1782   g_value_array_free (factories);
1783
1784   if (!res)
1785     goto unknown_type;
1786
1787   gst_caps_unref (caps);
1788
1789   return;
1790
1791 expose_pad:
1792   {
1793     GST_LOG_OBJECT (dbin, "Pad is final. autoplug-continue:%d", apcontinue);
1794     expose_pad (dbin, src, dpad, pad, caps, chain);
1795     gst_object_unref (dpad);
1796     gst_caps_unref (caps);
1797     return;
1798   }
1799
1800 discarded_type:
1801   {
1802     GST_LOG_OBJECT (pad, "Known type, but discarded because not final caps");
1803     chain->deadend = TRUE;
1804     chain->endcaps = caps;
1805     gst_object_replace ((GstObject **) & chain->current_pad, NULL);
1806
1807     /* Try to expose anything */
1808     EXPOSE_LOCK (dbin);
1809     if (dbin->decode_chain) {
1810       if (gst_decode_chain_is_complete (dbin->decode_chain)) {
1811         gst_decode_bin_expose (dbin);
1812       }
1813     }
1814     EXPOSE_UNLOCK (dbin);
1815     do_async_done (dbin);
1816
1817     return;
1818   }
1819
1820 unknown_type:
1821   {
1822     GST_LOG_OBJECT (pad, "Unknown type, posting message and firing signal");
1823
1824     chain->deadend_details = deadend_details;
1825     chain->deadend = TRUE;
1826     chain->endcaps = caps;
1827     gst_object_replace ((GstObject **) & chain->current_pad, NULL);
1828
1829     gst_element_post_message (GST_ELEMENT_CAST (dbin),
1830         gst_missing_decoder_message_new (GST_ELEMENT_CAST (dbin), caps));
1831
1832     g_signal_emit (G_OBJECT (dbin),
1833         gst_decode_bin_signals[SIGNAL_UNKNOWN_TYPE], 0, pad, caps);
1834
1835     /* Try to expose anything */
1836     EXPOSE_LOCK (dbin);
1837     if (dbin->decode_chain) {
1838       if (gst_decode_chain_is_complete (dbin->decode_chain)) {
1839         gst_decode_bin_expose (dbin);
1840       }
1841     }
1842     EXPOSE_UNLOCK (dbin);
1843
1844     if (src == dbin->typefind) {
1845       if (!caps || gst_caps_is_empty (caps)) {
1846         GST_ELEMENT_ERROR (dbin, STREAM, TYPE_NOT_FOUND,
1847             (_("Could not determine type of stream")), (NULL));
1848       }
1849       do_async_done (dbin);
1850     }
1851     return;
1852   }
1853 non_fixed:
1854   {
1855     GST_DEBUG_OBJECT (pad, "pad has non-fixed caps delay autoplugging");
1856     gst_object_unref (dpad);
1857     goto setup_caps_delay;
1858   }
1859 any_caps:
1860   {
1861     GST_DEBUG_OBJECT (pad, "pad has ANY caps, delaying auto-pluggin");
1862     goto setup_caps_delay;
1863   }
1864 setup_caps_delay:
1865   {
1866     GstPendingPad *ppad;
1867
1868     /* connect to caps notification */
1869     CHAIN_MUTEX_LOCK (chain);
1870     GST_LOG_OBJECT (dbin, "Chain %p has now %d dynamic pads", chain,
1871         g_list_length (chain->pending_pads));
1872     ppad = g_slice_new0 (GstPendingPad);
1873     ppad->pad = gst_object_ref (pad);
1874     ppad->chain = chain;
1875     ppad->event_probe_id =
1876         gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
1877         pad_event_cb, ppad, NULL);
1878     chain->pending_pads = g_list_prepend (chain->pending_pads, ppad);
1879     ppad->notify_caps_id = g_signal_connect (pad, "notify::caps",
1880         G_CALLBACK (caps_notify_cb), chain);
1881     CHAIN_MUTEX_UNLOCK (chain);
1882
1883     /* If we're here because we have a Parser/Converter
1884      * we have to unref the pad */
1885     if (is_parser_converter)
1886       gst_object_unref (pad);
1887     if (caps)
1888       gst_caps_unref (caps);
1889
1890     return;
1891   }
1892 }
1893
1894 static void
1895 add_error_filter (GstDecodeBin * dbin, GstElement * element)
1896 {
1897   GST_OBJECT_LOCK (dbin);
1898   dbin->filtered = g_list_prepend (dbin->filtered, element);
1899   GST_OBJECT_UNLOCK (dbin);
1900 }
1901
1902 static void
1903 remove_error_filter (GstDecodeBin * dbin, GstElement * element,
1904     GstMessage ** error)
1905 {
1906   GList *l;
1907
1908   GST_OBJECT_LOCK (dbin);
1909   dbin->filtered = g_list_remove (dbin->filtered, element);
1910
1911   if (error)
1912     *error = NULL;
1913
1914   l = dbin->filtered_errors;
1915   while (l) {
1916     GstMessage *msg = l->data;
1917
1918     if (GST_MESSAGE_SRC (msg) == GST_OBJECT_CAST (element)) {
1919       /* Get the last error of this element, i.e. the earliest */
1920       if (error)
1921         gst_message_replace (error, msg);
1922       gst_message_unref (msg);
1923       l = dbin->filtered_errors = g_list_delete_link (dbin->filtered_errors, l);
1924     } else {
1925       l = l->next;
1926     }
1927   }
1928   GST_OBJECT_UNLOCK (dbin);
1929 }
1930
1931 typedef struct
1932 {
1933   gboolean ret;
1934   GstPad *peer;
1935 } SendStickyEventsData;
1936
1937 static gboolean
1938 send_sticky_event (GstPad * pad, GstEvent ** event, gpointer user_data)
1939 {
1940   SendStickyEventsData *data = user_data;
1941   gboolean ret;
1942
1943   ret = gst_pad_send_event (data->peer, gst_event_ref (*event));
1944   if (!ret)
1945     data->ret = FALSE;
1946
1947   return data->ret;
1948 }
1949
1950 static gboolean
1951 send_sticky_events (GstDecodeBin * dbin, GstPad * pad)
1952 {
1953   SendStickyEventsData data;
1954
1955   data.ret = TRUE;
1956   data.peer = gst_pad_get_peer (pad);
1957
1958   gst_pad_sticky_events_foreach (pad, send_sticky_event, &data);
1959
1960   gst_object_unref (data.peer);
1961
1962   return data.ret;
1963 }
1964
1965 static gchar *
1966 error_message_to_string (GstMessage * msg)
1967 {
1968   GError *err;
1969   gchar *debug, *message, *full_message;
1970
1971   gst_message_parse_error (msg, &err, &debug);
1972
1973   message = gst_error_get_message (err->domain, err->code);
1974
1975   if (debug)
1976     full_message = g_strdup_printf ("%s\n%s\n%s", message, err->message, debug);
1977   else
1978     full_message = g_strdup_printf ("%s\n%s", message, err->message);
1979
1980   g_free (message);
1981   g_free (debug);
1982   g_clear_error (&err);
1983
1984   return full_message;
1985 }
1986
1987 /* We consider elements as "simple demuxer" when they are a demuxer
1988  * with one and only one ALWAYS source pad.
1989  */
1990 static gboolean
1991 is_simple_demuxer_factory (GstElementFactory * factory)
1992 {
1993   if (strstr (gst_element_factory_get_metadata (factory,
1994               GST_ELEMENT_METADATA_KLASS), "Demuxer")) {
1995     const GList *tmp;
1996     gint num_alway_srcpads = 0;
1997
1998     for (tmp = gst_element_factory_get_static_pad_templates (factory);
1999         tmp; tmp = tmp->next) {
2000       GstStaticPadTemplate *template = tmp->data;
2001
2002       if (template->direction == GST_PAD_SRC) {
2003         if (template->presence == GST_PAD_ALWAYS) {
2004           if (num_alway_srcpads >= 0)
2005             num_alway_srcpads++;
2006         } else {
2007           num_alway_srcpads = -1;
2008         }
2009       }
2010
2011     }
2012
2013     if (num_alway_srcpads == 1)
2014       return TRUE;
2015   }
2016
2017   return FALSE;
2018 }
2019
2020 static GstPadProbeReturn
2021 demuxer_source_pad_probe (GstPad * pad, GstPadProbeInfo * info,
2022     gpointer user_data)
2023 {
2024   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
2025   GstDecodeGroup *group = (GstDecodeGroup *) user_data;
2026   GstDecodeChain *parent_chain = group->parent;
2027
2028   GST_DEBUG_OBJECT (pad, "Saw event %s", GST_EVENT_TYPE_NAME (event));
2029   /* Check if we are the active group, if not we need to proxy the flush
2030    * events to the other groups (of which at least one is exposed, ensuring
2031    * flushing properly propagates downstream of decodebin */
2032   if (parent_chain->active_group == group)
2033     return GST_PAD_PROBE_OK;
2034
2035   switch (GST_EVENT_TYPE (event)) {
2036     case GST_EVENT_FLUSH_START:
2037     case GST_EVENT_FLUSH_STOP:
2038     {
2039       GList *tmp;
2040       GST_DEBUG_OBJECT (pad, "Proxying flush events to inactive groups");
2041       /* Proxy to active group */
2042       for (tmp = parent_chain->active_group->reqpads; tmp; tmp = tmp->next) {
2043         GstPad *reqpad = (GstPad *) tmp->data;
2044         gst_pad_send_event (reqpad, gst_event_ref (event));
2045       }
2046       /* Proxy to other non-active groups (except ourself) */
2047       for (tmp = parent_chain->next_groups; tmp; tmp = tmp->next) {
2048         GList *tmp2;
2049         GstDecodeGroup *tmpgroup = (GstDecodeGroup *) tmp->data;
2050         if (tmpgroup != group) {
2051           for (tmp2 = tmpgroup->reqpads; tmp2; tmp2 = tmp2->next) {
2052             GstPad *reqpad = (GstPad *) tmp2->data;
2053             gst_pad_send_event (reqpad, gst_event_ref (event));
2054           }
2055         }
2056       }
2057       flush_chain (parent_chain,
2058           GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_START);
2059     }
2060       break;
2061     default:
2062       break;
2063   }
2064
2065   return GST_PAD_PROBE_OK;
2066 }
2067
2068 /* connect_pad:
2069  *
2070  * Try to connect the given pad to an element created from one of the factories,
2071  * and recursively.
2072  *
2073  * Note that dpad is ghosting pad, and so pad is linked; be sure to unset dpad's
2074  * target before trying to link pad.
2075  *
2076  * Returns TRUE if an element was properly created and linked
2077  */
2078 static gboolean
2079 connect_pad (GstDecodeBin * dbin, GstElement * src, GstDecodePad * dpad,
2080     GstPad * pad, GstCaps * caps, GValueArray * factories,
2081     GstDecodeChain * chain, gchar ** deadend_details)
2082 {
2083   gboolean res = FALSE;
2084   GstPad *mqpad = NULL;
2085   gboolean is_demuxer = chain->parent && !chain->elements;      /* First pad after the demuxer */
2086   GString *error_details = NULL;
2087
2088   g_return_val_if_fail (factories != NULL, FALSE);
2089   g_return_val_if_fail (factories->n_values > 0, FALSE);
2090
2091   GST_DEBUG_OBJECT (dbin,
2092       "pad %s:%s , chain:%p, %d factories, caps %" GST_PTR_FORMAT,
2093       GST_DEBUG_PAD_NAME (pad), chain, factories->n_values, caps);
2094
2095   /* 1. is element demuxer or parser */
2096   if (is_demuxer) {
2097     GST_LOG_OBJECT (src,
2098         "is a demuxer, connecting the pad through multiqueue '%s'",
2099         GST_OBJECT_NAME (chain->parent->multiqueue));
2100
2101     /* Set a flush-start/-stop probe on the downstream events */
2102     gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_FLUSH,
2103         demuxer_source_pad_probe, chain->parent, NULL);
2104
2105     decode_pad_set_target (dpad, NULL);
2106     if (!(mqpad = gst_decode_group_control_demuxer_pad (chain->parent, pad)))
2107       goto beach;
2108     src = chain->parent->multiqueue;
2109     pad = mqpad;
2110     decode_pad_set_target (dpad, pad);
2111   }
2112
2113   error_details = g_string_new ("");
2114
2115   /* 2. Try to create an element and link to it */
2116   while (factories->n_values > 0) {
2117     GstAutoplugSelectResult ret;
2118     GstElementFactory *factory;
2119     GstDecodeElement *delem;
2120     GstElement *element;
2121     GstPad *sinkpad;
2122     GParamSpec *pspec;
2123     gboolean subtitle;
2124     GList *to_connect = NULL;
2125     gboolean is_parser_converter = FALSE, is_simple_demuxer = FALSE;
2126
2127     /* Set dpad target to pad again, it might've been unset
2128      * below but we came back here because something failed
2129      */
2130     decode_pad_set_target (dpad, pad);
2131
2132     /* take first factory */
2133     factory = g_value_get_object (g_value_array_get_nth (factories, 0));
2134     /* Remove selected factory from the list. */
2135     g_value_array_remove (factories, 0);
2136
2137     GST_LOG_OBJECT (src, "trying factory %" GST_PTR_FORMAT, factory);
2138
2139     /* Check if the caps are really supported by the factory. The
2140      * factory list is non-empty-subset filtered while caps
2141      * are only accepted by a pad if they are a subset of the
2142      * pad caps.
2143      *
2144      * FIXME: Only do this for fixed caps here. Non-fixed caps
2145      * can happen if a Parser/Converter was autoplugged before
2146      * this. We then assume that it will be able to convert to
2147      * everything that the decoder would want.
2148      *
2149      * A subset check will fail here because the parser caps
2150      * will be generic and while the decoder will only
2151      * support a subset of the parser caps.
2152      */
2153     if (gst_caps_is_fixed (caps)) {
2154       const GList *templs;
2155       gboolean skip = FALSE;
2156
2157       templs = gst_element_factory_get_static_pad_templates (factory);
2158
2159       while (templs) {
2160         GstStaticPadTemplate *templ = (GstStaticPadTemplate *) templs->data;
2161
2162         if (templ->direction == GST_PAD_SINK) {
2163           GstCaps *templcaps = gst_static_caps_get (&templ->static_caps);
2164
2165           if (!gst_caps_is_subset (caps, templcaps)) {
2166             GST_DEBUG_OBJECT (src,
2167                 "caps %" GST_PTR_FORMAT " not subset of %" GST_PTR_FORMAT, caps,
2168                 templcaps);
2169             gst_caps_unref (templcaps);
2170             skip = TRUE;
2171             break;
2172           }
2173
2174           gst_caps_unref (templcaps);
2175         }
2176         templs = g_list_next (templs);
2177       }
2178       if (skip)
2179         continue;
2180     }
2181
2182     /* If the factory is for a parser we first check if the factory
2183      * was already used for the current chain. If it was used already
2184      * we would otherwise create an infinite loop here because the
2185      * parser apparently accepts its own output as input.
2186      * This is only done for parsers because it's perfectly valid
2187      * to have other element classes after each other because a
2188      * parser is the only one that does not change the data. A
2189      * valid example for this would be multiple id3demux in a row.
2190      */
2191     is_parser_converter = strstr (gst_element_factory_get_metadata (factory,
2192             GST_ELEMENT_METADATA_KLASS), "Parser") != NULL;
2193     is_simple_demuxer = is_simple_demuxer_factory (factory);
2194
2195     if (is_parser_converter) {
2196       gboolean skip = FALSE;
2197       GList *l;
2198
2199       CHAIN_MUTEX_LOCK (chain);
2200       for (l = chain->elements; l; l = l->next) {
2201         GstDecodeElement *delem = (GstDecodeElement *) l->data;
2202         GstElement *otherelement = delem->element;
2203
2204         if (gst_element_get_factory (otherelement) == factory) {
2205           skip = TRUE;
2206           break;
2207         }
2208       }
2209
2210       if (!skip && chain->parent && chain->parent->parent) {
2211         GstDecodeChain *parent_chain = chain->parent->parent;
2212         GstDecodeElement *pelem =
2213             parent_chain->elements ? parent_chain->elements->data : NULL;
2214
2215         if (pelem && gst_element_get_factory (pelem->element) == factory)
2216           skip = TRUE;
2217       }
2218       CHAIN_MUTEX_UNLOCK (chain);
2219       if (skip) {
2220         GST_DEBUG_OBJECT (dbin,
2221             "Skipping factory '%s' because it was already used in this chain",
2222             gst_plugin_feature_get_name (GST_PLUGIN_FEATURE_CAST (factory)));
2223         continue;
2224       }
2225
2226     }
2227
2228     /* emit autoplug-select to see what we should do with it. */
2229     g_signal_emit (G_OBJECT (dbin),
2230         gst_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT],
2231         0, dpad, caps, factory, &ret);
2232
2233     switch (ret) {
2234       case GST_AUTOPLUG_SELECT_TRY:
2235         GST_DEBUG_OBJECT (dbin, "autoplug select requested try");
2236         break;
2237       case GST_AUTOPLUG_SELECT_EXPOSE:
2238         GST_DEBUG_OBJECT (dbin, "autoplug select requested expose");
2239         /* expose the pad, we don't have the source element */
2240         expose_pad (dbin, src, dpad, pad, caps, chain);
2241         res = TRUE;
2242         goto beach;
2243       case GST_AUTOPLUG_SELECT_SKIP:
2244         GST_DEBUG_OBJECT (dbin, "autoplug select requested skip");
2245         continue;
2246       default:
2247         GST_WARNING_OBJECT (dbin, "autoplug select returned unhandled %d", ret);
2248         break;
2249     }
2250
2251     /* 2.0. Unlink pad */
2252     decode_pad_set_target (dpad, NULL);
2253
2254     /* 2.1. Try to create an element */
2255     if ((element = gst_element_factory_create (factory, NULL)) == NULL) {
2256       GST_WARNING_OBJECT (dbin, "Could not create an element from %s",
2257           gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
2258       g_string_append_printf (error_details,
2259           "Could not create an element from %s\n",
2260           gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
2261       continue;
2262     }
2263
2264     /* Filter errors, this will prevent the element from causing the pipeline
2265      * to error while we test it using READY state. */
2266     add_error_filter (dbin, element);
2267
2268     /* We don't yet want the bin to control the element's state */
2269     gst_element_set_locked_state (element, TRUE);
2270
2271     /* ... add it ... */
2272     if (!(gst_bin_add (GST_BIN_CAST (dbin), element))) {
2273       GST_WARNING_OBJECT (dbin, "Couldn't add %s to the bin",
2274           GST_ELEMENT_NAME (element));
2275       remove_error_filter (dbin, element, NULL);
2276       g_string_append_printf (error_details, "Couldn't add %s to the bin\n",
2277           GST_ELEMENT_NAME (element));
2278       gst_object_unref (element);
2279       continue;
2280     }
2281
2282     /* Find its sink pad. */
2283     if (!(sinkpad = find_sink_pad (element))) {
2284       GST_WARNING_OBJECT (dbin, "Element %s doesn't have a sink pad",
2285           GST_ELEMENT_NAME (element));
2286       remove_error_filter (dbin, element, NULL);
2287       g_string_append_printf (error_details,
2288           "Element %s doesn't have a sink pad", GST_ELEMENT_NAME (element));
2289       gst_bin_remove (GST_BIN (dbin), element);
2290       continue;
2291     }
2292
2293     /* ... and try to link */
2294     if ((gst_pad_link_full (pad, sinkpad,
2295                 GST_PAD_LINK_CHECK_NOTHING)) != GST_PAD_LINK_OK) {
2296       GST_WARNING_OBJECT (dbin, "Link failed on pad %s:%s",
2297           GST_DEBUG_PAD_NAME (sinkpad));
2298       remove_error_filter (dbin, element, NULL);
2299       g_string_append_printf (error_details, "Link failed on pad %s:%s",
2300           GST_DEBUG_PAD_NAME (sinkpad));
2301       gst_object_unref (sinkpad);
2302       gst_bin_remove (GST_BIN (dbin), element);
2303       continue;
2304     }
2305
2306     /* ... activate it ... */
2307     if ((gst_element_set_state (element,
2308                 GST_STATE_READY)) == GST_STATE_CHANGE_FAILURE) {
2309       GstMessage *error_msg;
2310
2311       GST_WARNING_OBJECT (dbin, "Couldn't set %s to READY",
2312           GST_ELEMENT_NAME (element));
2313       remove_error_filter (dbin, element, &error_msg);
2314
2315       if (error_msg) {
2316         gchar *error_string = error_message_to_string (error_msg);
2317         g_string_append_printf (error_details, "Couldn't set %s to READY:\n%s",
2318             GST_ELEMENT_NAME (element), error_string);
2319         gst_message_unref (error_msg);
2320         g_free (error_string);
2321       } else {
2322         g_string_append_printf (error_details, "Couldn't set %s to READY",
2323             GST_ELEMENT_NAME (element));
2324       }
2325       gst_object_unref (sinkpad);
2326       gst_bin_remove (GST_BIN (dbin), element);
2327       continue;
2328     }
2329
2330     /* check if we still accept the caps on the pad after setting
2331      * the element to READY */
2332     if (!gst_pad_query_accept_caps (sinkpad, caps)) {
2333       GstMessage *error_msg;
2334
2335       GST_WARNING_OBJECT (dbin, "Element %s does not accept caps",
2336           GST_ELEMENT_NAME (element));
2337
2338       remove_error_filter (dbin, element, &error_msg);
2339
2340       if (error_msg) {
2341         gchar *error_string = error_message_to_string (error_msg);
2342         g_string_append_printf (error_details,
2343             "Element %s does not accept caps:\n%s", GST_ELEMENT_NAME (element),
2344             error_string);
2345         gst_message_unref (error_msg);
2346         g_free (error_string);
2347       } else {
2348         g_string_append_printf (error_details,
2349             "Element %s does not accept caps", GST_ELEMENT_NAME (element));
2350       }
2351
2352       gst_element_set_state (element, GST_STATE_NULL);
2353       gst_object_unref (sinkpad);
2354       gst_bin_remove (GST_BIN (dbin), element);
2355       continue;
2356     }
2357
2358     gst_object_unref (sinkpad);
2359     GST_LOG_OBJECT (dbin, "linked on pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2360
2361     CHAIN_MUTEX_LOCK (chain);
2362     delem = g_slice_new0 (GstDecodeElement);
2363     delem->element = gst_object_ref (element);
2364     delem->capsfilter = NULL;
2365     chain->elements = g_list_prepend (chain->elements, delem);
2366     chain->demuxer = is_demuxer_element (element);
2367     chain->adaptive_demuxer = is_adaptive_demuxer_element (element);
2368
2369     /* For adaptive streaming demuxer we insert a multiqueue after
2370      * this demuxer.
2371      * Now for the case where we have a container stream inside these
2372      * buffers, another demuxer will be plugged and after this second
2373      * demuxer there will be a second multiqueue. This second multiqueue
2374      * will get smaller buffers and will be the one emitting buffering
2375      * messages.
2376      * If we don't have a container stream inside the fragment buffers,
2377      * we'll insert a multiqueue below right after the next element after
2378      * the adaptive streaming demuxer. This is going to be a parser or
2379      * decoder, and will output smaller buffers.
2380      */
2381     if (chain->parent && chain->parent->parent) {
2382       GstDecodeChain *parent_chain = chain->parent->parent;
2383
2384       if (parent_chain->adaptive_demuxer)
2385         chain->demuxer = TRUE;
2386     }
2387
2388     CHAIN_MUTEX_UNLOCK (chain);
2389
2390     /* Set connection-speed property if needed */
2391     if (chain->demuxer) {
2392       GParamSpec *pspec;
2393
2394       if ((pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (element),
2395                   "connection-speed"))) {
2396         guint64 speed = dbin->connection_speed / 1000;
2397         gboolean wrong_type = FALSE;
2398
2399         if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_UINT) {
2400           GParamSpecUInt *pspecuint = G_PARAM_SPEC_UINT (pspec);
2401
2402           speed = CLAMP (speed, pspecuint->minimum, pspecuint->maximum);
2403         } else if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_INT) {
2404           GParamSpecInt *pspecint = G_PARAM_SPEC_INT (pspec);
2405
2406           speed = CLAMP (speed, pspecint->minimum, pspecint->maximum);
2407         } else if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_UINT64) {
2408           GParamSpecUInt64 *pspecuint = G_PARAM_SPEC_UINT64 (pspec);
2409
2410           speed = CLAMP (speed, pspecuint->minimum, pspecuint->maximum);
2411         } else if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_INT64) {
2412           GParamSpecInt64 *pspecint = G_PARAM_SPEC_INT64 (pspec);
2413
2414           speed = CLAMP (speed, pspecint->minimum, pspecint->maximum);
2415         } else {
2416           GST_WARNING_OBJECT (dbin,
2417               "The connection speed property %" G_GUINT64_FORMAT " of type %s"
2418               " is not usefull not setting it", speed,
2419               g_type_name (G_PARAM_SPEC_TYPE (pspec)));
2420           wrong_type = TRUE;
2421         }
2422
2423         if (!wrong_type) {
2424           GST_DEBUG_OBJECT (dbin, "setting connection-speed=%" G_GUINT64_FORMAT
2425               " to demuxer element", speed);
2426
2427           g_object_set (element, "connection-speed", speed, NULL);
2428         }
2429       }
2430     }
2431
2432     /* try to configure the subtitle encoding property when we can */
2433     pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (element),
2434         "subtitle-encoding");
2435     if (pspec && G_PARAM_SPEC_VALUE_TYPE (pspec) == G_TYPE_STRING) {
2436       SUBTITLE_LOCK (dbin);
2437       GST_DEBUG_OBJECT (dbin,
2438           "setting subtitle-encoding=%s to element", dbin->encoding);
2439       g_object_set (G_OBJECT (element), "subtitle-encoding", dbin->encoding,
2440           NULL);
2441       SUBTITLE_UNLOCK (dbin);
2442       subtitle = TRUE;
2443     } else {
2444       subtitle = FALSE;
2445     }
2446
2447     /* link this element further */
2448     to_connect = connect_element (dbin, delem, chain);
2449
2450     if ((is_simple_demuxer || is_parser_converter) && to_connect) {
2451       GList *l;
2452       for (l = to_connect; l; l = g_list_next (l)) {
2453         GstPad *opad = GST_PAD_CAST (l->data);
2454         GstCaps *ocaps;
2455
2456         ocaps = get_pad_caps (opad);
2457         analyze_new_pad (dbin, delem->element, opad, ocaps, chain);
2458         if (ocaps)
2459           gst_caps_unref (ocaps);
2460
2461         gst_object_unref (opad);
2462       }
2463       g_list_free (to_connect);
2464       to_connect = NULL;
2465     }
2466
2467     /* Bring the element to the state of the parent */
2468
2469     /* First lock element's sinkpad stream lock so no data reaches
2470      * the possible new element added when caps are sent by element
2471      * while we're still sending sticky events */
2472     GST_PAD_STREAM_LOCK (sinkpad);
2473
2474     if ((gst_element_set_state (element,
2475                 GST_STATE_PAUSED)) == GST_STATE_CHANGE_FAILURE ||
2476         !send_sticky_events (dbin, pad)) {
2477       GstDecodeElement *dtmp = NULL;
2478       GstElement *tmp = NULL;
2479       GstMessage *error_msg;
2480
2481       GST_PAD_STREAM_UNLOCK (sinkpad);
2482
2483       GST_WARNING_OBJECT (dbin, "Couldn't set %s to PAUSED",
2484           GST_ELEMENT_NAME (element));
2485
2486       g_list_foreach (to_connect, (GFunc) gst_object_unref, NULL);
2487       g_list_free (to_connect);
2488       to_connect = NULL;
2489
2490       remove_error_filter (dbin, element, &error_msg);
2491
2492       if (error_msg) {
2493         gchar *error_string = error_message_to_string (error_msg);
2494         g_string_append_printf (error_details, "Couldn't set %s to PAUSED:\n%s",
2495             GST_ELEMENT_NAME (element), error_string);
2496         gst_message_unref (error_msg);
2497         g_free (error_string);
2498       } else {
2499         g_string_append_printf (error_details, "Couldn't set %s to PAUSED",
2500             GST_ELEMENT_NAME (element));
2501       }
2502
2503       /* Remove all elements in this chain that were just added. No
2504        * other thread could've added elements in the meantime */
2505       CHAIN_MUTEX_LOCK (chain);
2506       do {
2507         GList *l;
2508
2509         dtmp = chain->elements->data;
2510         tmp = dtmp->element;
2511
2512         /* Disconnect any signal handlers that might be connected
2513          * in connect_element() or analyze_pad() */
2514         if (dtmp->pad_added_id)
2515           g_signal_handler_disconnect (tmp, dtmp->pad_added_id);
2516         if (dtmp->pad_removed_id)
2517           g_signal_handler_disconnect (tmp, dtmp->pad_removed_id);
2518         if (dtmp->no_more_pads_id)
2519           g_signal_handler_disconnect (tmp, dtmp->no_more_pads_id);
2520
2521         for (l = chain->pending_pads; l;) {
2522           GstPendingPad *pp = l->data;
2523           GList *n;
2524
2525           if (GST_PAD_PARENT (pp->pad) != tmp) {
2526             l = l->next;
2527             continue;
2528           }
2529
2530           gst_pending_pad_free (pp);
2531
2532           /* Remove element from the list, update list head and go to the
2533            * next element in the list */
2534           n = l->next;
2535           chain->pending_pads = g_list_delete_link (chain->pending_pads, l);
2536           l = n;
2537         }
2538
2539         if (dtmp->capsfilter) {
2540           gst_bin_remove (GST_BIN (dbin), dtmp->capsfilter);
2541           gst_element_set_state (dtmp->capsfilter, GST_STATE_NULL);
2542           gst_object_unref (dtmp->capsfilter);
2543         }
2544
2545         gst_bin_remove (GST_BIN (dbin), tmp);
2546         gst_element_set_state (tmp, GST_STATE_NULL);
2547
2548         gst_object_unref (tmp);
2549         g_slice_free (GstDecodeElement, dtmp);
2550
2551         chain->elements = g_list_delete_link (chain->elements, chain->elements);
2552       } while (tmp != element);
2553       CHAIN_MUTEX_UNLOCK (chain);
2554
2555       continue;
2556     } else {
2557       /* Everything went well, the spice must flow now */
2558       GST_PAD_STREAM_UNLOCK (sinkpad);
2559     }
2560
2561     /* Remove error filter now, from now on we can't gracefully
2562      * handle errors of the element anymore */
2563     remove_error_filter (dbin, element, NULL);
2564
2565     /* Now let the bin handle the state */
2566     gst_element_set_locked_state (element, FALSE);
2567
2568     if (subtitle) {
2569       SUBTITLE_LOCK (dbin);
2570       /* we added the element now, add it to the list of subtitle-encoding
2571        * elements when we can set the property */
2572       dbin->subtitles = g_list_prepend (dbin->subtitles, element);
2573       SUBTITLE_UNLOCK (dbin);
2574     }
2575
2576     if (to_connect) {
2577       GList *l;
2578       for (l = to_connect; l; l = g_list_next (l)) {
2579         GstPad *opad = GST_PAD_CAST (l->data);
2580         GstCaps *ocaps;
2581
2582         ocaps = get_pad_caps (opad);
2583         analyze_new_pad (dbin, delem->element, opad, ocaps, chain);
2584         if (ocaps)
2585           gst_caps_unref (ocaps);
2586
2587         gst_object_unref (opad);
2588       }
2589       g_list_free (to_connect);
2590       to_connect = NULL;
2591     }
2592
2593     res = TRUE;
2594     break;
2595   }
2596
2597 beach:
2598   if (mqpad)
2599     gst_object_unref (mqpad);
2600
2601   if (error_details)
2602     *deadend_details = g_string_free (error_details, (error_details->len == 0
2603             || res));
2604   else
2605     *deadend_details = NULL;
2606
2607   return res;
2608 }
2609
2610 static GstCaps *
2611 get_pad_caps (GstPad * pad)
2612 {
2613   GstCaps *caps;
2614
2615   /* first check the pad caps, if this is set, we are positively sure it is
2616    * fixed and exactly what the element will produce. */
2617   caps = gst_pad_get_current_caps (pad);
2618
2619   /* then use the getcaps function if we don't have caps. These caps might not
2620    * be fixed in some cases, in which case analyze_new_pad will set up a
2621    * notify::caps signal to continue autoplugging. */
2622   if (caps == NULL)
2623     caps = gst_pad_query_caps (pad, NULL);
2624
2625   return caps;
2626 }
2627
2628 /* Returns a list of pads that can be connected to already and
2629  * connects to pad-added and related signals */
2630 static GList *
2631 connect_element (GstDecodeBin * dbin, GstDecodeElement * delem,
2632     GstDecodeChain * chain)
2633 {
2634   GstElement *element = delem->element;
2635   GList *pads;
2636   gboolean dynamic = FALSE;
2637   GList *to_connect = NULL;
2638
2639   GST_DEBUG_OBJECT (dbin, "Attempting to connect element %s [chain:%p] further",
2640       GST_ELEMENT_NAME (element), chain);
2641
2642   /* 1. Loop over pad templates, grabbing existing pads along the way */
2643   for (pads = GST_ELEMENT_GET_CLASS (element)->padtemplates; pads;
2644       pads = g_list_next (pads)) {
2645     GstPadTemplate *templ = GST_PAD_TEMPLATE (pads->data);
2646     const gchar *templ_name;
2647
2648     /* we are only interested in source pads */
2649     if (GST_PAD_TEMPLATE_DIRECTION (templ) != GST_PAD_SRC)
2650       continue;
2651
2652     templ_name = GST_PAD_TEMPLATE_NAME_TEMPLATE (templ);
2653     GST_DEBUG_OBJECT (dbin, "got a source pad template %s", templ_name);
2654
2655     /* figure out what kind of pad this is */
2656     switch (GST_PAD_TEMPLATE_PRESENCE (templ)) {
2657       case GST_PAD_ALWAYS:
2658       {
2659         /* get the pad that we need to autoplug */
2660         GstPad *pad = gst_element_get_static_pad (element, templ_name);
2661
2662         if (pad) {
2663           GST_DEBUG_OBJECT (dbin, "got the pad for always template %s",
2664               templ_name);
2665           /* here is the pad, we need to autoplug it */
2666           to_connect = g_list_prepend (to_connect, pad);
2667         } else {
2668           /* strange, pad is marked as always but it's not
2669            * there. Fix the element */
2670           GST_WARNING_OBJECT (dbin,
2671               "could not get the pad for always template %s", templ_name);
2672         }
2673         break;
2674       }
2675       case GST_PAD_SOMETIMES:
2676       {
2677         /* try to get the pad to see if it is already created or
2678          * not */
2679         GstPad *pad = gst_element_get_static_pad (element, templ_name);
2680
2681         if (pad) {
2682           GST_DEBUG_OBJECT (dbin, "got the pad for sometimes template %s",
2683               templ_name);
2684           /* the pad is created, we need to autoplug it */
2685           to_connect = g_list_prepend (to_connect, pad);
2686         } else {
2687           GST_DEBUG_OBJECT (dbin,
2688               "did not get the sometimes pad of template %s", templ_name);
2689           /* we have an element that will create dynamic pads */
2690           dynamic = TRUE;
2691         }
2692         break;
2693       }
2694       case GST_PAD_REQUEST:
2695         /* ignore request pads */
2696         GST_DEBUG_OBJECT (dbin, "ignoring request padtemplate %s", templ_name);
2697         break;
2698     }
2699   }
2700
2701   /* 2. if there are more potential pads, connect to relevant signals */
2702   if (dynamic) {
2703     GST_LOG_OBJECT (dbin, "Adding signals to element %s in chain %p",
2704         GST_ELEMENT_NAME (element), chain);
2705     delem->pad_added_id = g_signal_connect (element, "pad-added",
2706         G_CALLBACK (pad_added_cb), chain);
2707     delem->pad_removed_id = g_signal_connect (element, "pad-removed",
2708         G_CALLBACK (pad_removed_cb), chain);
2709     delem->no_more_pads_id = g_signal_connect (element, "no-more-pads",
2710         G_CALLBACK (no_more_pads_cb), chain);
2711   }
2712
2713   /* 3. return all pads that can be connected to already */
2714
2715   return to_connect;
2716 }
2717
2718 /* expose_pad:
2719  *
2720  * Expose the given pad on the chain as a decoded pad.
2721  */
2722 static void
2723 expose_pad (GstDecodeBin * dbin, GstElement * src, GstDecodePad * dpad,
2724     GstPad * pad, GstCaps * caps, GstDecodeChain * chain)
2725 {
2726   GstPad *mqpad = NULL;
2727
2728   GST_DEBUG_OBJECT (dbin, "pad %s:%s, chain:%p",
2729       GST_DEBUG_PAD_NAME (pad), chain);
2730
2731   /* If this is the first pad for this chain, there are no other elements
2732    * and the source element is not the multiqueue we must link through the
2733    * multiqueue.
2734    *
2735    * This is the case if a demuxer directly exposed a raw pad.
2736    */
2737   if (chain->parent && !chain->elements && src != chain->parent->multiqueue) {
2738     GST_LOG_OBJECT (src, "connecting the pad through multiqueue");
2739
2740     decode_pad_set_target (dpad, NULL);
2741     if (!(mqpad = gst_decode_group_control_demuxer_pad (chain->parent, pad)))
2742       goto beach;
2743     pad = mqpad;
2744     decode_pad_set_target (dpad, pad);
2745   }
2746
2747   gst_decode_pad_activate (dpad, chain);
2748   chain->endpad = gst_object_ref (dpad);
2749   chain->endcaps = gst_caps_ref (caps);
2750
2751   EXPOSE_LOCK (dbin);
2752   if (dbin->decode_chain) {
2753     if (gst_decode_chain_is_complete (dbin->decode_chain)) {
2754       gst_decode_bin_expose (dbin);
2755     }
2756   }
2757   EXPOSE_UNLOCK (dbin);
2758
2759   if (mqpad)
2760     gst_object_unref (mqpad);
2761
2762 beach:
2763   return;
2764 }
2765
2766 /* check_upstream_seekable:
2767  *
2768  * Check if upstream is seekable.
2769  */
2770 static gboolean
2771 check_upstream_seekable (GstDecodeBin * dbin, GstPad * pad)
2772 {
2773   GstQuery *query;
2774   gint64 start = -1, stop = -1;
2775   gboolean seekable = FALSE;
2776
2777   query = gst_query_new_seeking (GST_FORMAT_BYTES);
2778   if (!gst_pad_peer_query (pad, query)) {
2779     GST_DEBUG_OBJECT (dbin, "seeking query failed");
2780     gst_query_unref (query);
2781     return FALSE;
2782   }
2783
2784   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
2785
2786   gst_query_unref (query);
2787
2788   /* try harder to query upstream size if we didn't get it the first time */
2789   if (seekable && stop == -1) {
2790     GST_DEBUG_OBJECT (dbin, "doing duration query to fix up unset stop");
2791     gst_pad_peer_query_duration (pad, GST_FORMAT_BYTES, &stop);
2792   }
2793
2794   /* if upstream doesn't know the size, it's likely that it's not seekable in
2795    * practice even if it technically may be seekable */
2796   if (seekable && (start != 0 || stop <= start)) {
2797     GST_DEBUG_OBJECT (dbin, "seekable but unknown start/stop -> disable");
2798     return FALSE;
2799   }
2800
2801   GST_DEBUG_OBJECT (dbin, "upstream seekable: %d", seekable);
2802   return seekable;
2803 }
2804
2805 static void
2806 type_found (GstElement * typefind, guint probability,
2807     GstCaps * caps, GstDecodeBin * decode_bin)
2808 {
2809   GstPad *pad, *sink_pad;
2810
2811   GST_DEBUG_OBJECT (decode_bin, "typefind found caps %" GST_PTR_FORMAT, caps);
2812
2813   /* If the typefinder (but not something else) finds text/plain - i.e. that's
2814    * the top-level type of the file - then error out.
2815    */
2816   if (gst_structure_has_name (gst_caps_get_structure (caps, 0), "text/plain")) {
2817     GST_ELEMENT_ERROR (decode_bin, STREAM, WRONG_TYPE,
2818         (_("This appears to be a text file")),
2819         ("decodebin cannot decode plain text files"));
2820     goto exit;
2821   }
2822
2823   /* FIXME: we can only deal with one type, we don't yet support dynamically changing
2824    * caps from the typefind element */
2825   if (decode_bin->have_type || decode_bin->decode_chain)
2826     goto exit;
2827
2828   decode_bin->have_type = TRUE;
2829
2830   pad = gst_element_get_static_pad (typefind, "src");
2831   sink_pad = gst_element_get_static_pad (typefind, "sink");
2832
2833   /* need some lock here to prevent race with shutdown state change
2834    * which might yank away e.g. decode_chain while building stuff here.
2835    * In typical cases, STREAM_LOCK is held and handles that, it need not
2836    * be held (if called from a proxied setcaps), so grab it anyway */
2837   GST_PAD_STREAM_LOCK (sink_pad);
2838   decode_bin->decode_chain = gst_decode_chain_new (decode_bin, NULL, pad);
2839   analyze_new_pad (decode_bin, typefind, pad, caps, decode_bin->decode_chain);
2840   GST_PAD_STREAM_UNLOCK (sink_pad);
2841
2842   gst_object_unref (sink_pad);
2843   gst_object_unref (pad);
2844
2845 exit:
2846   return;
2847 }
2848
2849 static GstPadProbeReturn
2850 pad_event_cb (GstPad * pad, GstPadProbeInfo * info, gpointer data)
2851 {
2852   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
2853   GstPendingPad *ppad = (GstPendingPad *) data;
2854   GstDecodeChain *chain = ppad->chain;
2855   GstDecodeBin *dbin = chain->dbin;
2856
2857   g_assert (ppad);
2858   g_assert (chain);
2859   g_assert (dbin);
2860   switch (GST_EVENT_TYPE (event)) {
2861     case GST_EVENT_EOS:
2862       GST_DEBUG_OBJECT (pad, "Received EOS on a non final pad, this stream "
2863           "ended too early");
2864       chain->deadend = TRUE;
2865       chain->drained = TRUE;
2866       gst_object_replace ((GstObject **) & chain->current_pad, NULL);
2867       /* we don't set the endcaps because NULL endcaps means early EOS */
2868
2869       EXPOSE_LOCK (dbin);
2870       if (dbin->decode_chain)
2871         if (gst_decode_chain_is_complete (dbin->decode_chain))
2872           gst_decode_bin_expose (dbin);
2873       EXPOSE_UNLOCK (dbin);
2874       break;
2875     default:
2876       break;
2877   }
2878   return GST_PAD_PROBE_OK;
2879 }
2880
2881 static void
2882 pad_added_cb (GstElement * element, GstPad * pad, GstDecodeChain * chain)
2883 {
2884   GstCaps *caps;
2885   GstDecodeBin *dbin;
2886
2887   dbin = chain->dbin;
2888
2889   GST_DEBUG_OBJECT (pad, "pad added, chain:%p", chain);
2890
2891   caps = get_pad_caps (pad);
2892   analyze_new_pad (dbin, element, pad, caps, chain);
2893   if (caps)
2894     gst_caps_unref (caps);
2895
2896   EXPOSE_LOCK (dbin);
2897   if (dbin->decode_chain) {
2898     if (gst_decode_chain_is_complete (dbin->decode_chain)) {
2899       GST_LOG_OBJECT (dbin,
2900           "That was the last dynamic object, now attempting to expose the group");
2901       if (!gst_decode_bin_expose (dbin))
2902         GST_WARNING_OBJECT (dbin, "Couldn't expose group");
2903     }
2904   } else {
2905     GST_DEBUG_OBJECT (dbin, "No decode chain, new pad ignored");
2906   }
2907   EXPOSE_UNLOCK (dbin);
2908 }
2909
2910 static GstPadProbeReturn
2911 sink_pad_event_probe (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2912 {
2913   GstDecodeGroup *group = (GstDecodeGroup *) user_data;
2914   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
2915   GstPad *peer = gst_pad_get_peer (pad);
2916   GstPadProbeReturn proberet = GST_PAD_PROBE_OK;
2917
2918   GST_DEBUG_OBJECT (pad, "Got upstream event %s", GST_EVENT_TYPE_NAME (event));
2919
2920   if (peer == NULL) {
2921     GST_DEBUG_OBJECT (pad, "We are unlinked !");
2922     if (group->parent && group->parent->next_groups) {
2923       GstDecodeGroup *last_group =
2924           g_list_last (group->parent->next_groups)->data;
2925       GST_DEBUG_OBJECT (pad, "We could send the event to another group (%p)",
2926           last_group);
2927       /* Grab another sinkpad for that last group through which we will forward this event */
2928       if (last_group->reqpads) {
2929         GstPad *sinkpad = (GstPad *) last_group->reqpads->data;
2930         GstPad *otherpeer = gst_pad_get_peer (sinkpad);
2931         if (otherpeer) {
2932           GST_DEBUG_OBJECT (otherpeer, "Attempting to forward event");
2933           if (gst_pad_send_event (otherpeer, gst_event_ref (event))) {
2934             proberet = GST_PAD_PROBE_HANDLED;
2935           }
2936           gst_object_unref (otherpeer);
2937         }
2938       } else
2939         GST_DEBUG_OBJECT (pad, "No request pads, can't forward event");
2940     }
2941   } else
2942     gst_object_unref (peer);
2943
2944   return proberet;
2945 }
2946
2947 static GstPadProbeReturn
2948 sink_pad_query_probe (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2949 {
2950   GstDecodeGroup *group = (GstDecodeGroup *) user_data;
2951   GstPad *peer = gst_pad_get_peer (pad);
2952   GstQuery *query = GST_PAD_PROBE_INFO_QUERY (info);
2953   GstPadProbeReturn proberet = GST_PAD_PROBE_OK;
2954
2955   GST_DEBUG_OBJECT (pad, "Got upstream query %s", GST_QUERY_TYPE_NAME (query));
2956
2957   if (peer == NULL) {
2958     GST_DEBUG_OBJECT (pad, "We are unlinked !");
2959     if (group->parent && group->parent->next_groups) {
2960       GstDecodeGroup *last_group =
2961           g_list_last (group->parent->next_groups)->data;
2962       GST_DEBUG_OBJECT (pad, "We could send the query to another group");
2963       /* Grab another sinkpad for that last group through which we will forward this event */
2964       if (last_group->reqpads) {
2965         GstPad *sinkpad = (GstPad *) last_group->reqpads->data;
2966         GstPad *otherpeer = gst_pad_get_peer (sinkpad);
2967         if (otherpeer) {
2968           GST_DEBUG_OBJECT (otherpeer, "Attempting to forward query");
2969           if (gst_pad_query (otherpeer, query)) {
2970             proberet = GST_PAD_PROBE_HANDLED;
2971           } else
2972             GST_DEBUG ("FAILURE");
2973           gst_object_unref (otherpeer);
2974         } else
2975           GST_DEBUG_OBJECT (sinkpad, "request pad not connected ??");
2976       } else
2977         GST_DEBUG_OBJECT (pad, "No request pads ???");
2978     }
2979   } else
2980     gst_object_unref (peer);
2981
2982   return proberet;
2983 }
2984
2985 static void
2986 pad_removed_cb (GstElement * element, GstPad * pad, GstDecodeChain * chain)
2987 {
2988   GList *l;
2989
2990   GST_LOG_OBJECT (pad, "pad removed, chain:%p", chain);
2991
2992   /* In fact, we don't have to do anything here, the active group will be
2993    * removed when the group's multiqueue is drained */
2994   CHAIN_MUTEX_LOCK (chain);
2995   for (l = chain->pending_pads; l; l = l->next) {
2996     GstPendingPad *ppad = l->data;
2997     GstPad *opad = ppad->pad;
2998
2999     if (pad == opad) {
3000       gst_pending_pad_free (ppad);
3001       chain->pending_pads = g_list_delete_link (chain->pending_pads, l);
3002       break;
3003     }
3004   }
3005   CHAIN_MUTEX_UNLOCK (chain);
3006 }
3007
3008 static void
3009 no_more_pads_cb (GstElement * element, GstDecodeChain * chain)
3010 {
3011   GstDecodeGroup *group = NULL;
3012
3013   GST_LOG_OBJECT (element, "got no more pads");
3014
3015   CHAIN_MUTEX_LOCK (chain);
3016   if (!chain->elements
3017       || ((GstDecodeElement *) chain->elements->data)->element != element) {
3018     GST_LOG_OBJECT (chain->dbin, "no-more-pads from old chain element '%s'",
3019         GST_OBJECT_NAME (element));
3020     CHAIN_MUTEX_UNLOCK (chain);
3021     return;
3022   } else if (!chain->demuxer) {
3023     GST_LOG_OBJECT (chain->dbin, "no-more-pads from a non-demuxer element '%s'",
3024         GST_OBJECT_NAME (element));
3025     CHAIN_MUTEX_UNLOCK (chain);
3026     return;
3027   }
3028
3029   /* when we received no_more_pads, we can complete the pads of the chain */
3030   if (!chain->next_groups && chain->active_group) {
3031     group = chain->active_group;
3032   } else if (chain->next_groups) {
3033     GList *iter;
3034     for (iter = chain->next_groups; iter; iter = g_list_next (iter)) {
3035       group = iter->data;
3036       if (!group->no_more_pads)
3037         break;
3038     }
3039   }
3040   if (!group) {
3041     GST_ERROR_OBJECT (chain->dbin, "can't find group for element");
3042     CHAIN_MUTEX_UNLOCK (chain);
3043     return;
3044   }
3045
3046   GST_DEBUG_OBJECT (element, "Setting group %p to complete", group);
3047
3048   group->no_more_pads = TRUE;
3049   /* this group has prerolled enough to not need more pads,
3050    * we can probably set its buffering state to playing now */
3051   GST_DEBUG_OBJECT (group->dbin, "Setting group %p multiqueue to "
3052       "'playing' buffering mode", group);
3053   decodebin_set_queue_size (group->dbin, group->multiqueue, FALSE,
3054       (group->parent ? group->parent->seekable : TRUE));
3055   CHAIN_MUTEX_UNLOCK (chain);
3056
3057   EXPOSE_LOCK (chain->dbin);
3058   if (chain->dbin->decode_chain) {
3059     if (gst_decode_chain_is_complete (chain->dbin->decode_chain)) {
3060       gst_decode_bin_expose (chain->dbin);
3061     }
3062   }
3063   EXPOSE_UNLOCK (chain->dbin);
3064 }
3065
3066 static void
3067 caps_notify_cb (GstPad * pad, GParamSpec * unused, GstDecodeChain * chain)
3068 {
3069   GstElement *element;
3070   GList *l;
3071
3072   GST_LOG_OBJECT (pad, "Notified caps for pad %s:%s", GST_DEBUG_PAD_NAME (pad));
3073
3074   /* Disconnect this; if we still need it, we'll reconnect to this in
3075    * analyze_new_pad */
3076   element = GST_ELEMENT_CAST (gst_pad_get_parent (pad));
3077
3078   CHAIN_MUTEX_LOCK (chain);
3079   for (l = chain->pending_pads; l; l = l->next) {
3080     GstPendingPad *ppad = l->data;
3081     if (ppad->pad == pad) {
3082       gst_pending_pad_free (ppad);
3083       chain->pending_pads = g_list_delete_link (chain->pending_pads, l);
3084       break;
3085     }
3086   }
3087   CHAIN_MUTEX_UNLOCK (chain);
3088
3089   pad_added_cb (element, pad, chain);
3090
3091   gst_object_unref (element);
3092 }
3093
3094 /* Decide whether an element is a demuxer based on the
3095  * klass and number/type of src pad templates it has */
3096 static gboolean
3097 is_demuxer_element (GstElement * srcelement)
3098 {
3099   GstElementFactory *srcfactory;
3100   GstElementClass *elemclass;
3101   GList *walk;
3102   const gchar *klass;
3103   gint potential_src_pads = 0;
3104
3105   srcfactory = gst_element_get_factory (srcelement);
3106   klass =
3107       gst_element_factory_get_metadata (srcfactory, GST_ELEMENT_METADATA_KLASS);
3108
3109   /* Can't be a demuxer unless it has Demux in the klass name */
3110   if (!strstr (klass, "Demux"))
3111     return FALSE;
3112
3113   /* Walk the src pad templates and count how many the element
3114    * might produce */
3115   elemclass = GST_ELEMENT_GET_CLASS (srcelement);
3116
3117   walk = gst_element_class_get_pad_template_list (elemclass);
3118   while (walk != NULL) {
3119     GstPadTemplate *templ;
3120
3121     templ = (GstPadTemplate *) walk->data;
3122     if (GST_PAD_TEMPLATE_DIRECTION (templ) == GST_PAD_SRC) {
3123       switch (GST_PAD_TEMPLATE_PRESENCE (templ)) {
3124         case GST_PAD_ALWAYS:
3125         case GST_PAD_SOMETIMES:
3126           if (strstr (GST_PAD_TEMPLATE_NAME_TEMPLATE (templ), "%"))
3127             potential_src_pads += 2;    /* Might make multiple pads */
3128           else
3129             potential_src_pads += 1;
3130           break;
3131         case GST_PAD_REQUEST:
3132           potential_src_pads += 2;
3133           break;
3134       }
3135     }
3136     walk = g_list_next (walk);
3137   }
3138
3139   if (potential_src_pads < 2)
3140     return FALSE;
3141
3142   return TRUE;
3143 }
3144
3145 static gboolean
3146 is_adaptive_demuxer_element (GstElement * srcelement)
3147 {
3148   GstElementFactory *srcfactory;
3149   const gchar *klass;
3150
3151   srcfactory = gst_element_get_factory (srcelement);
3152   klass =
3153       gst_element_factory_get_metadata (srcfactory, GST_ELEMENT_METADATA_KLASS);
3154
3155   /* Can't be a demuxer unless it has Demux in the klass name */
3156   if (!strstr (klass, "Demux") || !strstr (klass, "Adaptive"))
3157     return FALSE;
3158
3159   return TRUE;
3160 }
3161
3162 /* Returns TRUE if the caps are compatible with the caps specified in the 'caps'
3163  * property (which by default are the raw caps)
3164  *
3165  * The decodebin_lock should be taken !
3166  */
3167 static gboolean
3168 are_final_caps (GstDecodeBin * dbin, GstCaps * caps)
3169 {
3170   gboolean res;
3171
3172   GST_LOG_OBJECT (dbin, "Checking with caps %" GST_PTR_FORMAT, caps);
3173
3174   /* lock for getting the caps */
3175   GST_OBJECT_LOCK (dbin);
3176   res = gst_caps_is_subset (caps, dbin->caps);
3177   GST_OBJECT_UNLOCK (dbin);
3178
3179   GST_LOG_OBJECT (dbin, "Caps are %sfinal caps", res ? "" : "not ");
3180
3181   return res;
3182 }
3183
3184 /* gst_decode_bin_reset_buffering:
3185  *
3186  * Enables buffering on the last multiqueue of each group only,
3187  * disabling the rest
3188  *
3189  */
3190 static void
3191 gst_decode_bin_reset_buffering (GstDecodeBin * dbin)
3192 {
3193   if (!dbin->use_buffering)
3194     return;
3195
3196   GST_DEBUG_OBJECT (dbin, "Reseting multiqueues buffering");
3197   if (dbin->decode_chain) {
3198     CHAIN_MUTEX_LOCK (dbin->decode_chain);
3199     gst_decode_chain_reset_buffering (dbin->decode_chain);
3200     CHAIN_MUTEX_UNLOCK (dbin->decode_chain);
3201   }
3202 }
3203
3204 /****
3205  * GstDecodeChain functions
3206  ****/
3207
3208 static gboolean
3209 gst_decode_chain_reset_buffering (GstDecodeChain * chain)
3210 {
3211   GstDecodeGroup *group;
3212
3213   group = chain->active_group;
3214   GST_LOG_OBJECT (chain->dbin, "Resetting chain %p buffering, active group: %p",
3215       chain, group);
3216   if (group) {
3217     return gst_decode_group_reset_buffering (group);
3218   }
3219   return FALSE;
3220 }
3221
3222 /* gst_decode_chain_get_current_group:
3223  *
3224  * Returns the current group of this chain, to which
3225  * new chains should be attached or NULL if the last
3226  * group didn't have no-more-pads.
3227  *
3228  * Not MT-safe: Call with parent chain lock!
3229  */
3230 static GstDecodeGroup *
3231 gst_decode_chain_get_current_group (GstDecodeChain * chain)
3232 {
3233   GstDecodeGroup *group;
3234
3235   if (!chain->next_groups && chain->active_group
3236       && chain->active_group->overrun && !chain->active_group->no_more_pads) {
3237     GST_WARNING_OBJECT (chain->dbin,
3238         "Currently active group %p is exposed"
3239         " and wants to add a new pad without having signaled no-more-pads",
3240         chain->active_group);
3241     return NULL;
3242   }
3243
3244   if (chain->next_groups && (group = chain->next_groups->data) && group->overrun
3245       && !group->no_more_pads) {
3246     GST_WARNING_OBJECT (chain->dbin,
3247         "Currently newest pending group %p "
3248         "had overflow but didn't signal no-more-pads", group);
3249     return NULL;
3250   }
3251
3252   /* Now we know that we can really return something useful */
3253   if (!chain->active_group) {
3254     chain->active_group = group = gst_decode_group_new (chain->dbin, chain);
3255   } else if (!chain->active_group->overrun
3256       && !chain->active_group->no_more_pads) {
3257     group = chain->active_group;
3258   } else {
3259     GList *iter;
3260     group = NULL;
3261     for (iter = chain->next_groups; iter; iter = g_list_next (iter)) {
3262       GstDecodeGroup *next_group = iter->data;
3263
3264       if (!next_group->overrun && !next_group->no_more_pads) {
3265         group = next_group;
3266         break;
3267       }
3268     }
3269   }
3270   if (!group) {
3271     group = gst_decode_group_new (chain->dbin, chain);
3272     chain->next_groups = g_list_append (chain->next_groups, group);
3273   }
3274
3275   return group;
3276 }
3277
3278 static void gst_decode_group_free_internal (GstDecodeGroup * group,
3279     gboolean hide);
3280
3281 static void
3282 gst_decode_chain_free_internal (GstDecodeChain * chain, gboolean hide)
3283 {
3284   GList *l, *set_to_null = NULL;
3285
3286   CHAIN_MUTEX_LOCK (chain);
3287
3288   GST_DEBUG_OBJECT (chain->dbin, "%s chain %p", (hide ? "Hiding" : "Freeing"),
3289       chain);
3290
3291   if (chain->active_group) {
3292     gst_decode_group_free_internal (chain->active_group, hide);
3293     if (!hide)
3294       chain->active_group = NULL;
3295   }
3296
3297   for (l = chain->next_groups; l; l = l->next) {
3298     gst_decode_group_free_internal ((GstDecodeGroup *) l->data, hide);
3299     if (!hide)
3300       l->data = NULL;
3301   }
3302   if (!hide) {
3303     g_list_free (chain->next_groups);
3304     chain->next_groups = NULL;
3305   }
3306
3307   if (!hide) {
3308     for (l = chain->old_groups; l; l = l->next) {
3309       GstDecodeGroup *group = l->data;
3310
3311       gst_decode_group_free (group);
3312     }
3313     g_list_free (chain->old_groups);
3314     chain->old_groups = NULL;
3315   }
3316
3317   for (l = chain->pending_pads; l; l = l->next) {
3318     GstPendingPad *ppad = l->data;
3319     gst_pending_pad_free (ppad);
3320     l->data = NULL;
3321   }
3322   g_list_free (chain->pending_pads);
3323   chain->pending_pads = NULL;
3324
3325   for (l = chain->elements; l; l = l->next) {
3326     GstDecodeElement *delem = l->data;
3327     GstElement *element = delem->element;
3328
3329     if (delem->pad_added_id)
3330       g_signal_handler_disconnect (element, delem->pad_added_id);
3331     delem->pad_added_id = 0;
3332     if (delem->pad_removed_id)
3333       g_signal_handler_disconnect (element, delem->pad_removed_id);
3334     delem->pad_removed_id = 0;
3335     if (delem->no_more_pads_id)
3336       g_signal_handler_disconnect (element, delem->no_more_pads_id);
3337     delem->no_more_pads_id = 0;
3338
3339     if (delem->capsfilter) {
3340       if (GST_OBJECT_PARENT (delem->capsfilter) ==
3341           GST_OBJECT_CAST (chain->dbin))
3342         gst_bin_remove (GST_BIN_CAST (chain->dbin), delem->capsfilter);
3343       if (!hide) {
3344         set_to_null =
3345             g_list_append (set_to_null, gst_object_ref (delem->capsfilter));
3346       }
3347     }
3348
3349     if (GST_OBJECT_PARENT (element) == GST_OBJECT_CAST (chain->dbin))
3350       gst_bin_remove (GST_BIN_CAST (chain->dbin), element);
3351     if (!hide) {
3352       set_to_null = g_list_append (set_to_null, gst_object_ref (element));
3353     }
3354
3355     SUBTITLE_LOCK (chain->dbin);
3356     /* remove possible subtitle element */
3357     chain->dbin->subtitles = g_list_remove (chain->dbin->subtitles, element);
3358     SUBTITLE_UNLOCK (chain->dbin);
3359
3360     if (!hide) {
3361       if (delem->capsfilter) {
3362         gst_object_unref (delem->capsfilter);
3363         delem->capsfilter = NULL;
3364       }
3365
3366       gst_object_unref (element);
3367       l->data = NULL;
3368
3369       g_slice_free (GstDecodeElement, delem);
3370     }
3371   }
3372   if (!hide) {
3373     g_list_free (chain->elements);
3374     chain->elements = NULL;
3375   }
3376
3377   if (chain->endpad) {
3378     if (chain->endpad->exposed) {
3379       GstPad *endpad = GST_PAD_CAST (chain->endpad);
3380       gst_pad_push_event (endpad, gst_event_new_flush_start ());
3381       gst_pad_push_event (endpad, gst_event_new_flush_stop (FALSE));
3382       gst_element_remove_pad (GST_ELEMENT_CAST (chain->dbin), endpad);
3383     }
3384
3385     decode_pad_set_target (chain->endpad, NULL);
3386     chain->endpad->exposed = FALSE;
3387     if (!hide) {
3388       gst_object_unref (chain->endpad);
3389       chain->endpad = NULL;
3390     }
3391   }
3392
3393   if (!hide && chain->current_pad) {
3394     gst_object_unref (chain->current_pad);
3395     chain->current_pad = NULL;
3396   }
3397
3398   if (chain->pad) {
3399     gst_object_unref (chain->pad);
3400     chain->pad = NULL;
3401   }
3402
3403   if (chain->endcaps) {
3404     gst_caps_unref (chain->endcaps);
3405     chain->endcaps = NULL;
3406   }
3407   g_free (chain->deadend_details);
3408   chain->deadend_details = NULL;
3409
3410   GST_DEBUG_OBJECT (chain->dbin, "%s chain %p", (hide ? "Hidden" : "Freed"),
3411       chain);
3412   CHAIN_MUTEX_UNLOCK (chain);
3413
3414   while (set_to_null) {
3415     GstElement *element = set_to_null->data;
3416     set_to_null = g_list_delete_link (set_to_null, set_to_null);
3417     gst_element_set_state (element, GST_STATE_NULL);
3418     gst_object_unref (element);
3419   }
3420
3421   if (!hide) {
3422     g_mutex_clear (&chain->lock);
3423     g_slice_free (GstDecodeChain, chain);
3424   }
3425 }
3426
3427 /* gst_decode_chain_free:
3428  *
3429  * Completely frees and removes the chain and all
3430  * child groups from decodebin.
3431  *
3432  * MT-safe, don't hold the chain lock or any child chain's lock
3433  * when calling this!
3434  */
3435 static void
3436 gst_decode_chain_free (GstDecodeChain * chain)
3437 {
3438   gst_decode_chain_free_internal (chain, FALSE);
3439 }
3440
3441 /* gst_decode_chain_new:
3442  *
3443  * Creates a new decode chain and initializes it.
3444  *
3445  * It's up to the caller to add it to the list of child chains of
3446  * a group!
3447  */
3448 static GstDecodeChain *
3449 gst_decode_chain_new (GstDecodeBin * dbin, GstDecodeGroup * parent,
3450     GstPad * pad)
3451 {
3452   GstDecodeChain *chain = g_slice_new0 (GstDecodeChain);
3453
3454   GST_DEBUG_OBJECT (dbin, "Creating new chain %p with parent group %p", chain,
3455       parent);
3456
3457   chain->dbin = dbin;
3458   chain->parent = parent;
3459   g_mutex_init (&chain->lock);
3460   chain->pad = gst_object_ref (pad);
3461
3462   return chain;
3463 }
3464
3465 /****
3466  * GstDecodeGroup functions
3467  ****/
3468
3469 /* The overrun callback is used to expose groups that have not yet had their
3470  * no_more_pads called while the (large) multiqueue overflowed. When this
3471  * happens we must assume that the no_more_pads will not arrive anymore and we
3472  * must expose the pads that we have.
3473  */
3474 static void
3475 multi_queue_overrun_cb (GstElement * queue, GstDecodeGroup * group)
3476 {
3477   GstDecodeBin *dbin;
3478
3479   dbin = group->dbin;
3480
3481   GST_LOG_OBJECT (dbin, "multiqueue '%s' (%p) is full", GST_OBJECT_NAME (queue),
3482       queue);
3483
3484   group->overrun = TRUE;
3485   /* this group has prerolled enough to not need more pads,
3486    * we can probably set its buffering state to playing now */
3487   GST_DEBUG_OBJECT (group->dbin, "Setting group %p multiqueue to "
3488       "'playing' buffering mode", group);
3489   decodebin_set_queue_size (group->dbin, group->multiqueue, FALSE,
3490       (group->parent ? group->parent->seekable : TRUE));
3491
3492   /* FIXME: We should make sure that everything gets exposed now
3493    * even if child chains are not complete because the will never
3494    * be complete! Ignore any non-complete chains when exposing
3495    * and never expose them later
3496    */
3497
3498   EXPOSE_LOCK (dbin);
3499   if (dbin->decode_chain) {
3500     if (gst_decode_chain_is_complete (dbin->decode_chain)) {
3501       if (!gst_decode_bin_expose (dbin))
3502         GST_WARNING_OBJECT (dbin, "Couldn't expose group");
3503     }
3504   }
3505   EXPOSE_UNLOCK (dbin);
3506 }
3507
3508 static void
3509 gst_decode_group_free_internal (GstDecodeGroup * group, gboolean hide)
3510 {
3511   GList *l;
3512
3513   GST_DEBUG_OBJECT (group->dbin, "%s group %p", (hide ? "Hiding" : "Freeing"),
3514       group);
3515   for (l = group->children; l; l = l->next) {
3516     GstDecodeChain *chain = (GstDecodeChain *) l->data;
3517
3518     gst_decode_chain_free_internal (chain, hide);
3519     if (!hide)
3520       l->data = NULL;
3521   }
3522   if (!hide) {
3523     g_list_free (group->children);
3524     group->children = NULL;
3525   }
3526
3527   if (!hide) {
3528     for (l = group->reqpads; l; l = l->next) {
3529       GstPad *pad = l->data;
3530
3531       gst_element_release_request_pad (group->multiqueue, pad);
3532       gst_object_unref (pad);
3533       l->data = NULL;
3534     }
3535     g_list_free (group->reqpads);
3536     group->reqpads = NULL;
3537   }
3538
3539   if (group->multiqueue) {
3540     if (group->overrunsig) {
3541       g_signal_handler_disconnect (group->multiqueue, group->overrunsig);
3542       group->overrunsig = 0;
3543     }
3544
3545     if (GST_OBJECT_PARENT (group->multiqueue) == GST_OBJECT_CAST (group->dbin))
3546       gst_bin_remove (GST_BIN_CAST (group->dbin), group->multiqueue);
3547     if (!hide) {
3548       gst_element_set_state (group->multiqueue, GST_STATE_NULL);
3549       gst_object_unref (group->multiqueue);
3550       group->multiqueue = NULL;
3551     }
3552   }
3553
3554   GST_DEBUG_OBJECT (group->dbin, "%s group %p", (hide ? "Hid" : "Freed"),
3555       group);
3556   if (!hide)
3557     g_slice_free (GstDecodeGroup, group);
3558 }
3559
3560 /* gst_decode_group_free:
3561  *
3562  * Completely frees and removes the decode group and all
3563  * it's children.
3564  *
3565  * Never call this from any streaming thread!
3566  *
3567  * Not MT-safe, call with parent's chain lock!
3568  */
3569 static void
3570 gst_decode_group_free (GstDecodeGroup * group)
3571 {
3572   gst_decode_group_free_internal (group, FALSE);
3573 }
3574
3575 /* gst_decode_group_hide:
3576  *
3577  * Hide the decode group only, this means that
3578  * all child endpads are removed from decodebin
3579  * and all signals are unconnected.
3580  *
3581  * No element is set to NULL state and completely
3582  * unrefed here.
3583  *
3584  * Can be called from streaming threads.
3585  *
3586  * Not MT-safe, call with parent's chain lock!
3587  */
3588 static void
3589 gst_decode_group_hide (GstDecodeGroup * group)
3590 {
3591   gst_decode_group_free_internal (group, TRUE);
3592 }
3593
3594 /* gst_decode_chain_free_hidden_groups:
3595  *
3596  * Frees any decode groups that were hidden previously.
3597  * This allows keeping memory use from ballooning when
3598  * switching chains repeatedly.
3599  *
3600  * A new throwaway thread will be created to free the
3601  * groups, so any delay does not block the setup of a
3602  * new group.
3603  *
3604  * Not MT-safe, call with parent's chain lock!
3605  */
3606 static void
3607 gst_decode_chain_free_hidden_groups (GList * old_groups)
3608 {
3609   GList *l;
3610
3611   for (l = old_groups; l; l = l->next) {
3612     GstDecodeGroup *group = l->data;
3613
3614     gst_decode_group_free (group);
3615   }
3616   g_list_free (old_groups);
3617 }
3618
3619 static void
3620 gst_decode_chain_start_free_hidden_groups_thread (GstDecodeChain * chain)
3621 {
3622   GThread *thread;
3623   GError *error = NULL;
3624   GList *old_groups;
3625
3626   old_groups = chain->old_groups;
3627   if (!old_groups)
3628     return;
3629
3630   chain->old_groups = NULL;
3631   thread = g_thread_try_new ("free-hidden-groups",
3632       (GThreadFunc) gst_decode_chain_free_hidden_groups, old_groups, &error);
3633   if (!thread || error) {
3634     GST_ERROR ("Failed to start free-hidden-groups thread: %s",
3635         error ? error->message : "unknown reason");
3636     g_clear_error (&error);
3637     chain->old_groups = old_groups;
3638     return;
3639   }
3640   GST_DEBUG_OBJECT (chain->dbin, "Started free-hidden-groups thread");
3641   /* We do not need to wait for it or get any results from it */
3642   g_thread_unref (thread);
3643 }
3644
3645 static void
3646 decodebin_set_queue_size (GstDecodeBin * dbin, GstElement * multiqueue,
3647     gboolean preroll, gboolean seekable)
3648 {
3649   gboolean use_buffering;
3650
3651   /* get the current config from the multiqueue */
3652   g_object_get (multiqueue, "use-buffering", &use_buffering, NULL);
3653
3654   decodebin_set_queue_size_full (dbin, multiqueue, use_buffering, preroll,
3655       seekable);
3656 }
3657
3658 /* configure queue sizes, this depends on the buffering method and if we are
3659  * playing or prerolling. */
3660 static void
3661 decodebin_set_queue_size_full (GstDecodeBin * dbin, GstElement * multiqueue,
3662     gboolean use_buffering, gboolean preroll, gboolean seekable)
3663 {
3664   guint max_bytes, max_buffers;
3665   guint64 max_time;
3666
3667   GST_DEBUG_OBJECT (multiqueue, "use buffering %d", use_buffering);
3668
3669   if (preroll || use_buffering) {
3670     /* takes queue limits, initially we only queue up up to the max bytes limit,
3671      * with a default of 2MB. we use the same values for buffering mode. */
3672     if (preroll || (max_bytes = dbin->max_size_bytes) == 0)
3673       max_bytes = AUTO_PREROLL_SIZE_BYTES;
3674     if (preroll || (max_buffers = dbin->max_size_buffers) == 0)
3675       max_buffers = AUTO_PREROLL_SIZE_BUFFERS;
3676     if (preroll || (max_time = dbin->max_size_time) == 0) {
3677       if (dbin->use_buffering && !preroll)
3678         max_time = 5 * GST_SECOND;
3679       else
3680         max_time = seekable ? AUTO_PREROLL_SEEKABLE_SIZE_TIME :
3681             AUTO_PREROLL_NOT_SEEKABLE_SIZE_TIME;
3682     }
3683   } else {
3684     /* update runtime limits. At runtime, we try to keep the amount of buffers
3685      * in the queues as low as possible (but at least 5 buffers). */
3686     if (dbin->use_buffering)
3687       max_bytes = 0;
3688     else if ((max_bytes = dbin->max_size_bytes) == 0)
3689       max_bytes = AUTO_PLAY_SIZE_BYTES;
3690     if ((max_buffers = dbin->max_size_buffers) == 0)
3691       max_buffers = AUTO_PLAY_SIZE_BUFFERS;
3692     /* this is a multiqueue with disabled buffering, don't limit max_time */
3693     if (dbin->use_buffering)
3694       max_time = 0;
3695     else if ((max_time = dbin->max_size_time) == 0)
3696       max_time = AUTO_PLAY_SIZE_TIME;
3697   }
3698
3699   GST_DEBUG_OBJECT (multiqueue, "setting limits %u bytes, %u buffers, "
3700       "%" G_GUINT64_FORMAT " time", max_bytes, max_buffers, max_time);
3701   g_object_set (multiqueue,
3702       "max-size-bytes", max_bytes, "max-size-time", max_time,
3703       "max-size-buffers", max_buffers, NULL);
3704 }
3705
3706 /* gst_decode_group_new:
3707  * @dbin: Parent decodebin
3708  * @parent: Parent chain or %NULL
3709  *
3710  * Creates a new GstDecodeGroup. It is up to the caller to add it to the list
3711  * of groups.
3712  */
3713 static GstDecodeGroup *
3714 gst_decode_group_new (GstDecodeBin * dbin, GstDecodeChain * parent)
3715 {
3716   GstDecodeGroup *group = g_slice_new0 (GstDecodeGroup);
3717   GstElement *mq;
3718   gboolean seekable;
3719
3720   GST_DEBUG_OBJECT (dbin, "Creating new group %p with parent chain %p", group,
3721       parent);
3722
3723   group->dbin = dbin;
3724   group->parent = parent;
3725
3726   mq = group->multiqueue = gst_element_factory_make ("multiqueue", NULL);
3727   if (G_UNLIKELY (!group->multiqueue))
3728     goto missing_multiqueue;
3729
3730   /* configure queue sizes for preroll */
3731   seekable = FALSE;
3732   if (parent && parent->demuxer) {
3733     GstElement *element =
3734         ((GstDecodeElement *) parent->elements->data)->element;
3735     GstPad *pad = gst_element_get_static_pad (element, "sink");
3736     if (pad) {
3737       seekable = parent->seekable = check_upstream_seekable (dbin, pad);
3738       gst_object_unref (pad);
3739     }
3740   }
3741   decodebin_set_queue_size_full (dbin, mq, FALSE, TRUE, seekable);
3742
3743   group->overrunsig = g_signal_connect (mq, "overrun",
3744       G_CALLBACK (multi_queue_overrun_cb), group);
3745
3746   gst_element_set_state (mq, GST_STATE_PAUSED);
3747   gst_bin_add (GST_BIN (dbin), gst_object_ref (mq));
3748
3749   return group;
3750
3751   /* ERRORS */
3752 missing_multiqueue:
3753   {
3754     gst_element_post_message (GST_ELEMENT_CAST (dbin),
3755         gst_missing_element_message_new (GST_ELEMENT_CAST (dbin),
3756             "multiqueue"));
3757     GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL), ("no multiqueue!"));
3758     g_slice_free (GstDecodeGroup, group);
3759     return NULL;
3760   }
3761 }
3762
3763 /* gst_decode_group_control_demuxer_pad
3764  *
3765  * Adds a new demuxer srcpad to the given group.
3766  *
3767  * Returns the srcpad of the multiqueue corresponding the given pad.
3768  * Returns NULL if there was an error.
3769  */
3770 static GstPad *
3771 gst_decode_group_control_demuxer_pad (GstDecodeGroup * group, GstPad * pad)
3772 {
3773   GstDecodeBin *dbin;
3774   GstPad *srcpad, *sinkpad;
3775   GstIterator *it = NULL;
3776   GValue item = { 0, };
3777
3778   dbin = group->dbin;
3779
3780   GST_LOG_OBJECT (dbin, "group:%p pad %s:%s", group, GST_DEBUG_PAD_NAME (pad));
3781
3782   srcpad = NULL;
3783
3784   if (G_UNLIKELY (!group->multiqueue))
3785     return NULL;
3786
3787   if (!(sinkpad = gst_element_get_request_pad (group->multiqueue, "sink_%u"))) {
3788     GST_ERROR_OBJECT (dbin, "Couldn't get sinkpad from multiqueue");
3789     return NULL;
3790   }
3791
3792   if ((gst_pad_link_full (pad, sinkpad,
3793               GST_PAD_LINK_CHECK_NOTHING) != GST_PAD_LINK_OK)) {
3794     GST_ERROR_OBJECT (dbin, "Couldn't link demuxer and multiqueue");
3795     goto error;
3796   }
3797
3798   it = gst_pad_iterate_internal_links (sinkpad);
3799
3800   if (!it || (gst_iterator_next (it, &item)) != GST_ITERATOR_OK
3801       || ((srcpad = g_value_dup_object (&item)) == NULL)) {
3802     GST_ERROR_OBJECT (dbin,
3803         "Couldn't get srcpad from multiqueue for sinkpad %" GST_PTR_FORMAT,
3804         sinkpad);
3805     goto error;
3806   }
3807   gst_pad_add_probe (sinkpad, GST_PAD_PROBE_TYPE_EVENT_UPSTREAM,
3808       sink_pad_event_probe, group, NULL);
3809   gst_pad_add_probe (sinkpad, GST_PAD_PROBE_TYPE_QUERY_UPSTREAM,
3810       sink_pad_query_probe, group, NULL);
3811
3812   CHAIN_MUTEX_LOCK (group->parent);
3813   group->reqpads = g_list_prepend (group->reqpads, gst_object_ref (sinkpad));
3814   CHAIN_MUTEX_UNLOCK (group->parent);
3815
3816 beach:
3817   if (G_IS_VALUE (&item))
3818     g_value_unset (&item);
3819   if (it)
3820     gst_iterator_free (it);
3821   gst_object_unref (sinkpad);
3822   return srcpad;
3823
3824 error:
3825   gst_element_release_request_pad (group->multiqueue, sinkpad);
3826   goto beach;
3827 }
3828
3829 /* gst_decode_group_is_complete:
3830  *
3831  * Checks if the group is complete, this means that
3832  * a) overrun of the multiqueue or no-more-pads happened
3833  * b) all child chains are complete
3834  *
3835  * Not MT-safe, always call with decodebin expose lock
3836  */
3837 static gboolean
3838 gst_decode_group_is_complete (GstDecodeGroup * group)
3839 {
3840   GList *l;
3841   gboolean complete = TRUE;
3842
3843   if (!group->overrun && !group->no_more_pads) {
3844     complete = FALSE;
3845     goto out;
3846   }
3847
3848   for (l = group->children; l; l = l->next) {
3849     GstDecodeChain *chain = l->data;
3850
3851     if (!gst_decode_chain_is_complete (chain)) {
3852       complete = FALSE;
3853       goto out;
3854     }
3855   }
3856
3857 out:
3858   GST_DEBUG_OBJECT (group->dbin, "Group %p is complete: %d", group, complete);
3859   return complete;
3860 }
3861
3862 /* gst_decode_chain_is_complete:
3863  *
3864  * Returns TRUE if the chain is complete, this means either
3865  * a) This chain is a dead end, i.e. we have no suitable plugins
3866  * b) This chain ends in an endpad and this is blocked or exposed
3867  *
3868  * Not MT-safe, always call with decodebin expose lock
3869  */
3870 static gboolean
3871 gst_decode_chain_is_complete (GstDecodeChain * chain)
3872 {
3873   gboolean complete = FALSE;
3874
3875   CHAIN_MUTEX_LOCK (chain);
3876   if (chain->dbin->shutdown)
3877     goto out;
3878
3879   if (chain->deadend) {
3880     complete = TRUE;
3881     goto out;
3882   }
3883
3884   if (chain->endpad && (chain->endpad->blocked || chain->endpad->exposed)) {
3885     complete = TRUE;
3886     goto out;
3887   }
3888
3889   if (chain->demuxer) {
3890     if (chain->active_group
3891         && gst_decode_group_is_complete (chain->active_group)) {
3892       complete = TRUE;
3893       goto out;
3894     }
3895   }
3896
3897 out:
3898   CHAIN_MUTEX_UNLOCK (chain);
3899   GST_DEBUG_OBJECT (chain->dbin, "Chain %p is complete: %d", chain, complete);
3900   return complete;
3901 }
3902
3903 /* Flushing group/chains */
3904 static void
3905 flush_group (GstDecodeGroup * group, gboolean flushing)
3906 {
3907   GList *tmp;
3908
3909   GST_DEBUG ("group %p flushing:%d", group, flushing);
3910
3911   if (group->drained == flushing)
3912     return;
3913   for (tmp = group->children; tmp; tmp = tmp->next) {
3914     GstDecodeChain *chain = (GstDecodeChain *) tmp->data;
3915     flush_chain (chain, flushing);
3916   }
3917   GST_DEBUG ("Setting group %p to drained:%d", group, flushing);
3918   group->drained = flushing;
3919 }
3920
3921 static void
3922 flush_chain (GstDecodeChain * chain, gboolean flushing)
3923 {
3924   GList *tmp;
3925   GstDecodeBin *dbin = chain->dbin;
3926
3927   GST_DEBUG_OBJECT (dbin, "chain %p (pad %s:%s) flushing:%d", chain,
3928       GST_DEBUG_PAD_NAME (chain->pad), flushing);
3929   if (chain->drained == flushing)
3930     return;
3931   /* if unflushing, check if we should switch to last group */
3932   if (flushing == FALSE && chain->next_groups) {
3933     GstDecodeGroup *target_group =
3934         (GstDecodeGroup *) g_list_last (chain->next_groups)->data;
3935     gst_decode_chain_start_free_hidden_groups_thread (chain);
3936     /* Hide active group (we're sure it's not that one we'll be using) */
3937     GST_DEBUG_OBJECT (dbin, "Switching from active group %p to group %p",
3938         chain->active_group, target_group);
3939     gst_decode_group_hide (chain->active_group);
3940     chain->old_groups = g_list_prepend (chain->old_groups, chain->active_group);
3941     chain->active_group = target_group;
3942     /* Hide all groups but the target_group */
3943     for (tmp = chain->next_groups; tmp; tmp = tmp->next) {
3944       GstDecodeGroup *group = (GstDecodeGroup *) tmp->data;
3945       if (group != target_group) {
3946         gst_decode_group_hide (group);
3947         chain->old_groups = g_list_prepend (chain->old_groups, group);
3948       }
3949     }
3950     /* Clear next groups */
3951     g_list_free (chain->next_groups);
3952     chain->next_groups = NULL;
3953   }
3954   /* Mark all groups as flushing */
3955   if (chain->active_group)
3956     flush_group (chain->active_group, flushing);
3957   for (tmp = chain->next_groups; tmp; tmp = tmp->next) {
3958     GstDecodeGroup *group = (GstDecodeGroup *) tmp->data;
3959     flush_group (group, flushing);
3960   }
3961   GST_DEBUG ("Setting chain %p to drained:%d", chain, flushing);
3962   chain->drained = flushing;
3963 }
3964
3965 static gboolean
3966 drain_and_switch_chains (GstDecodeChain * chain, GstDecodePad * drainpad,
3967     gboolean * last_group, gboolean * drained, gboolean * switched);
3968 /* drain_and_switch_chains/groups:
3969  *
3970  * CALL WITH CHAIN LOCK (or group parent) TAKEN !
3971  *
3972  * Goes down the chains/groups until it finds the chain
3973  * to which the drainpad belongs.
3974  *
3975  * It marks that pad/chain as drained and then will figure
3976  * out which group to switch to or not.
3977  *
3978  * last_chain will be set to TRUE if the group to which the
3979  * pad belongs is the last one.
3980  *
3981  * drained will be set to TRUE if the chain/group is drained.
3982  *
3983  * Returns: TRUE if the chain contained the target pad */
3984 static gboolean
3985 drain_and_switch_group (GstDecodeGroup * group, GstDecodePad * drainpad,
3986     gboolean * last_group, gboolean * drained, gboolean * switched)
3987 {
3988   gboolean handled = FALSE;
3989   GList *tmp;
3990
3991   GST_DEBUG ("Checking group %p (target pad %s:%s)",
3992       group, GST_DEBUG_PAD_NAME (drainpad));
3993
3994   /* Definitely can't be in drained groups */
3995   if (G_UNLIKELY (group->drained)) {
3996     goto beach;
3997   }
3998
3999   /* Figure out if all our chains are drained with the
4000    * new information */
4001   group->drained = TRUE;
4002   for (tmp = group->children; tmp; tmp = tmp->next) {
4003     GstDecodeChain *chain = (GstDecodeChain *) tmp->data;
4004     gboolean subdrained = FALSE;
4005
4006     handled |=
4007         drain_and_switch_chains (chain, drainpad, last_group, &subdrained,
4008         switched);
4009     if (!subdrained)
4010       group->drained = FALSE;
4011   }
4012
4013 beach:
4014   GST_DEBUG ("group %p (last_group:%d, drained:%d, switched:%d, handled:%d)",
4015       group, *last_group, group->drained, *switched, handled);
4016   *drained = group->drained;
4017   return handled;
4018 }
4019
4020 static gboolean
4021 drain_and_switch_chains (GstDecodeChain * chain, GstDecodePad * drainpad,
4022     gboolean * last_group, gboolean * drained, gboolean * switched)
4023 {
4024   gboolean handled = FALSE;
4025   GstDecodeBin *dbin = chain->dbin;
4026
4027   GST_DEBUG ("Checking chain %p %s:%s (target pad %s:%s)",
4028       chain, GST_DEBUG_PAD_NAME (chain->pad), GST_DEBUG_PAD_NAME (drainpad));
4029
4030   CHAIN_MUTEX_LOCK (chain);
4031
4032   /* Definitely can't be in drained chains */
4033   if (G_UNLIKELY (chain->drained)) {
4034     goto beach;
4035   }
4036
4037   if (chain->endpad) {
4038     /* Check if we're reached the target endchain */
4039     if (drainpad != NULL && chain == drainpad->chain) {
4040       GST_DEBUG ("Found the target chain");
4041       drainpad->drained = TRUE;
4042       handled = TRUE;
4043     }
4044
4045     chain->drained = chain->endpad->drained;
4046     goto beach;
4047   }
4048
4049   /* We known there are groups to switch to */
4050   if (chain->next_groups)
4051     *last_group = FALSE;
4052
4053   /* Check the active group */
4054   if (chain->active_group) {
4055     gboolean subdrained = FALSE;
4056     handled = drain_and_switch_group (chain->active_group, drainpad,
4057         last_group, &subdrained, switched);
4058
4059     /* The group is drained, see if we can switch to another */
4060     if ((handled || drainpad == NULL) && subdrained && !*switched) {
4061       if (chain->next_groups) {
4062         /* Switch to next group */
4063         GST_DEBUG_OBJECT (dbin, "Hiding current group %p", chain->active_group);
4064         gst_decode_chain_start_free_hidden_groups_thread (chain);
4065         gst_decode_group_hide (chain->active_group);
4066         chain->old_groups =
4067             g_list_prepend (chain->old_groups, chain->active_group);
4068         GST_DEBUG_OBJECT (dbin, "Switching to next group %p",
4069             chain->next_groups->data);
4070         chain->active_group = chain->next_groups->data;
4071         chain->next_groups =
4072             g_list_delete_link (chain->next_groups, chain->next_groups);
4073         *switched = TRUE;
4074         chain->drained = FALSE;
4075       } else {
4076         GST_DEBUG ("Group %p was the last in chain %p", chain->active_group,
4077             chain);
4078         chain->drained = TRUE;
4079         /* We're drained ! */
4080       }
4081     } else {
4082       if (subdrained && !chain->next_groups)
4083         *drained = TRUE;
4084     }
4085   }
4086
4087 beach:
4088   CHAIN_MUTEX_UNLOCK (chain);
4089
4090   GST_DEBUG ("Chain %p (handled:%d, last_group:%d, drained:%d, switched:%d)",
4091       chain, handled, *last_group, chain->drained, *switched);
4092
4093   *drained = chain->drained;
4094
4095   if (*drained)
4096     g_signal_emit (dbin, gst_decode_bin_signals[SIGNAL_DRAINED], 0, NULL);
4097
4098   return handled;
4099 }
4100
4101 /* check if the group is drained, meaning all pads have seen an EOS
4102  * event.  */
4103 static gboolean
4104 gst_decode_pad_handle_eos (GstDecodePad * pad)
4105 {
4106   gboolean last_group = TRUE;
4107   gboolean switched = FALSE;
4108   gboolean drained = FALSE;
4109   GstDecodeChain *chain = pad->chain;
4110   GstDecodeBin *dbin = chain->dbin;
4111
4112   GST_LOG_OBJECT (dbin, "pad %p", pad);
4113   EXPOSE_LOCK (dbin);
4114   if (dbin->decode_chain) {
4115     drain_and_switch_chains (dbin->decode_chain, pad, &last_group, &drained,
4116         &switched);
4117
4118     if (switched) {
4119       /* If we resulted in a group switch, expose what's needed */
4120       if (gst_decode_chain_is_complete (dbin->decode_chain))
4121         gst_decode_bin_expose (dbin);
4122     }
4123   }
4124   EXPOSE_UNLOCK (dbin);
4125
4126   return last_group;
4127 }
4128
4129 /* gst_decode_group_is_drained:
4130  *
4131  * Check is this group is drained and cache this result.
4132  * The group is drained if all child chains are drained.
4133  *
4134  * Not MT-safe, call with group->parent's lock */
4135 static gboolean
4136 gst_decode_group_is_drained (GstDecodeGroup * group)
4137 {
4138   GList *l;
4139   gboolean drained = TRUE;
4140
4141   if (group->drained) {
4142     drained = TRUE;
4143     goto out;
4144   }
4145
4146   for (l = group->children; l; l = l->next) {
4147     GstDecodeChain *chain = l->data;
4148
4149     CHAIN_MUTEX_LOCK (chain);
4150     if (!gst_decode_chain_is_drained (chain))
4151       drained = FALSE;
4152     CHAIN_MUTEX_UNLOCK (chain);
4153     if (!drained)
4154       goto out;
4155   }
4156   group->drained = drained;
4157
4158 out:
4159   GST_DEBUG_OBJECT (group->dbin, "Group %p is drained: %d", group, drained);
4160   return drained;
4161 }
4162
4163 /* gst_decode_chain_is_drained:
4164  *
4165  * Check is the chain is drained, which means that
4166  * either
4167  *
4168  * a) it's endpad is drained
4169  * b) there are no pending pads, the active group is drained
4170  *    and there are no next groups
4171  *
4172  * Not MT-safe, call with chain lock
4173  */
4174 static gboolean
4175 gst_decode_chain_is_drained (GstDecodeChain * chain)
4176 {
4177   gboolean drained = FALSE;
4178
4179   if (chain->endpad) {
4180     drained = chain->endpad->drained;
4181     goto out;
4182   }
4183
4184   if (chain->pending_pads) {
4185     drained = FALSE;
4186     goto out;
4187   }
4188
4189   if (chain->active_group && gst_decode_group_is_drained (chain->active_group)
4190       && !chain->next_groups) {
4191     drained = TRUE;
4192     goto out;
4193   }
4194
4195 out:
4196   GST_DEBUG_OBJECT (chain->dbin, "Chain %p is drained: %d", chain, drained);
4197   return drained;
4198 }
4199
4200 static gboolean
4201 gst_decode_group_reset_buffering (GstDecodeGroup * group)
4202 {
4203   GList *l;
4204   gboolean ret = TRUE;
4205
4206   GST_DEBUG_OBJECT (group->dbin, "Group reset buffering %p %s", group,
4207       GST_ELEMENT_NAME (group->multiqueue));
4208   for (l = group->children; l; l = l->next) {
4209     GstDecodeChain *chain = l->data;
4210
4211     CHAIN_MUTEX_LOCK (chain);
4212     if (!gst_decode_chain_reset_buffering (chain)) {
4213       ret = FALSE;
4214     }
4215     CHAIN_MUTEX_UNLOCK (chain);
4216   }
4217
4218   decodebin_set_queue_size_full (group->dbin, group->multiqueue, !ret,
4219       FALSE, (group->parent ? group->parent->seekable : TRUE));
4220
4221   if (ret) {
4222     /* all chains are buffering already, no need to do it here */
4223     g_object_set (group->multiqueue, "use-buffering", FALSE, NULL);
4224   } else {
4225     g_object_set (group->multiqueue, "use-buffering", TRUE,
4226         "low-percent", group->dbin->low_percent,
4227         "high-percent", group->dbin->high_percent, NULL);
4228   }
4229
4230   GST_DEBUG_OBJECT (group->dbin, "Setting %s buffering to %d",
4231       GST_ELEMENT_NAME (group->multiqueue), !ret);
4232   return TRUE;
4233 }
4234
4235
4236 /* sort_end_pads:
4237  * GCompareFunc to use with lists of GstPad.
4238  * Sorts pads by mime type.
4239  * First video (raw, then non-raw), then audio (raw, then non-raw),
4240  * then others.
4241  *
4242  * Return: negative if a<b, 0 if a==b, positive if a>b
4243  */
4244 static gint
4245 sort_end_pads (GstDecodePad * da, GstDecodePad * db)
4246 {
4247   gint va, vb;
4248   GstCaps *capsa, *capsb;
4249   GstStructure *sa, *sb;
4250   const gchar *namea, *nameb;
4251   gchar *ida, *idb;
4252   gint ret;
4253
4254   capsa = get_pad_caps (GST_PAD_CAST (da));
4255   capsb = get_pad_caps (GST_PAD_CAST (db));
4256
4257   sa = gst_caps_get_structure ((const GstCaps *) capsa, 0);
4258   sb = gst_caps_get_structure ((const GstCaps *) capsb, 0);
4259
4260   namea = gst_structure_get_name (sa);
4261   nameb = gst_structure_get_name (sb);
4262
4263   if (g_strrstr (namea, "video/x-raw"))
4264     va = 0;
4265   else if (g_strrstr (namea, "video/"))
4266     va = 1;
4267   else if (g_strrstr (namea, "audio/x-raw"))
4268     va = 2;
4269   else if (g_strrstr (namea, "audio/"))
4270     va = 3;
4271   else
4272     va = 4;
4273
4274   if (g_strrstr (nameb, "video/x-raw"))
4275     vb = 0;
4276   else if (g_strrstr (nameb, "video/"))
4277     vb = 1;
4278   else if (g_strrstr (nameb, "audio/x-raw"))
4279     vb = 2;
4280   else if (g_strrstr (nameb, "audio/"))
4281     vb = 3;
4282   else
4283     vb = 4;
4284
4285   gst_caps_unref (capsa);
4286   gst_caps_unref (capsb);
4287
4288   if (va != vb)
4289     return va - vb;
4290
4291   /* if otherwise the same, sort by stream-id */
4292   ida = gst_pad_get_stream_id (GST_PAD_CAST (da));
4293   idb = gst_pad_get_stream_id (GST_PAD_CAST (db));
4294   ret = (ida) ? ((idb) ? strcmp (ida, idb) : -1) : 1;
4295   g_free (ida);
4296   g_free (idb);
4297
4298   return ret;
4299 }
4300
4301 static GstCaps *
4302 _gst_element_get_linked_caps (GstElement * src, GstElement * sink,
4303     GstPad ** srcpad)
4304 {
4305   GstIterator *it;
4306   GstElement *parent;
4307   GstPad *pad, *peer;
4308   gboolean done = FALSE;
4309   GstCaps *caps = NULL;
4310   GValue item = { 0, };
4311
4312   it = gst_element_iterate_src_pads (src);
4313   while (!done) {
4314     switch (gst_iterator_next (it, &item)) {
4315       case GST_ITERATOR_OK:
4316         pad = g_value_get_object (&item);
4317         peer = gst_pad_get_peer (pad);
4318         if (peer) {
4319           parent = gst_pad_get_parent_element (peer);
4320           if (parent == sink) {
4321             caps = gst_pad_get_current_caps (pad);
4322             if (srcpad) {
4323               gst_object_ref (pad);
4324               *srcpad = pad;
4325             }
4326             done = TRUE;
4327           }
4328
4329           if (parent)
4330             gst_object_unref (parent);
4331           gst_object_unref (peer);
4332         }
4333         g_value_reset (&item);
4334         break;
4335       case GST_ITERATOR_RESYNC:
4336         gst_iterator_resync (it);
4337         break;
4338       case GST_ITERATOR_ERROR:
4339       case GST_ITERATOR_DONE:
4340         done = TRUE;
4341         break;
4342     }
4343   }
4344   g_value_unset (&item);
4345   gst_iterator_free (it);
4346
4347   return caps;
4348 }
4349
4350 static GQuark topology_structure_name = 0;
4351 static GQuark topology_caps = 0;
4352 static GQuark topology_next = 0;
4353 static GQuark topology_pad = 0;
4354 static GQuark topology_element_srcpad = 0;
4355
4356 /* FIXME: Invent gst_structure_take_structure() to prevent all the
4357  * structure copying for nothing
4358  */
4359 static GstStructure *
4360 gst_decode_chain_get_topology (GstDecodeChain * chain)
4361 {
4362   GstStructure *s, *u;
4363   GList *l;
4364   GstCaps *caps;
4365
4366   if (G_UNLIKELY ((chain->endpad || chain->deadend)
4367           && (chain->endcaps == NULL))) {
4368     GST_WARNING ("End chain without valid caps !");
4369     return NULL;
4370   }
4371
4372   u = gst_structure_new_id_empty (topology_structure_name);
4373
4374   /* Now at the last element */
4375   if ((chain->elements || !chain->active_group) &&
4376       (chain->endpad || chain->deadend)) {
4377     s = gst_structure_new_id_empty (topology_structure_name);
4378     gst_structure_id_set (u, topology_caps, GST_TYPE_CAPS, chain->endcaps,
4379         NULL);
4380
4381     if (chain->endpad) {
4382       gst_structure_id_set (u, topology_pad, GST_TYPE_PAD, chain->endpad, NULL);
4383       gst_structure_id_set (u, topology_element_srcpad, GST_TYPE_PAD,
4384           chain->endpad, NULL);
4385     }
4386     gst_structure_id_set (s, topology_next, GST_TYPE_STRUCTURE, u, NULL);
4387     gst_structure_free (u);
4388     u = s;
4389   } else if (chain->active_group) {
4390     GValue list = { 0, };
4391     GValue item = { 0, };
4392
4393     g_value_init (&list, GST_TYPE_LIST);
4394     g_value_init (&item, GST_TYPE_STRUCTURE);
4395     for (l = chain->active_group->children; l; l = l->next) {
4396       s = gst_decode_chain_get_topology (l->data);
4397       if (s) {
4398         gst_value_set_structure (&item, s);
4399         gst_value_list_append_value (&list, &item);
4400         g_value_reset (&item);
4401         gst_structure_free (s);
4402       }
4403     }
4404     gst_structure_id_set_value (u, topology_next, &list);
4405     g_value_unset (&list);
4406     g_value_unset (&item);
4407   }
4408
4409   /* Get caps between all elements in this chain */
4410   l = (chain->elements && chain->elements->next) ? chain->elements : NULL;
4411   for (; l && l->next; l = l->next) {
4412     GstDecodeElement *delem, *delem_next;
4413     GstElement *elem, *elem_next;
4414     GstCaps *caps;
4415     GstPad *srcpad;
4416
4417     delem = l->data;
4418     elem = delem->element;
4419     delem_next = l->next->data;
4420     elem_next = delem_next->element;
4421     srcpad = NULL;
4422
4423     caps = _gst_element_get_linked_caps (elem_next, elem, &srcpad);
4424
4425     if (caps) {
4426       s = gst_structure_new_id_empty (topology_structure_name);
4427       gst_structure_id_set (u, topology_caps, GST_TYPE_CAPS, caps, NULL);
4428       gst_caps_unref (caps);
4429
4430       gst_structure_id_set (s, topology_next, GST_TYPE_STRUCTURE, u, NULL);
4431       gst_structure_free (u);
4432       u = s;
4433     }
4434
4435     if (srcpad) {
4436       gst_structure_id_set (u, topology_element_srcpad, GST_TYPE_PAD, srcpad,
4437           NULL);
4438       gst_object_unref (srcpad);
4439     }
4440   }
4441
4442   /* Caps that resulted in this chain */
4443   caps = gst_pad_get_current_caps (chain->pad);
4444   if (!caps) {
4445     caps = get_pad_caps (chain->pad);
4446     if (G_UNLIKELY (!gst_caps_is_fixed (caps))) {
4447       GST_ERROR_OBJECT (chain->pad,
4448           "Couldn't get fixed caps, got %" GST_PTR_FORMAT, caps);
4449       gst_caps_unref (caps);
4450       caps = NULL;
4451     }
4452   }
4453   gst_structure_id_set (u, topology_caps, GST_TYPE_CAPS, caps, NULL);
4454   gst_structure_id_set (u, topology_element_srcpad, GST_TYPE_PAD, chain->pad,
4455       NULL);
4456   gst_caps_unref (caps);
4457
4458   return u;
4459 }
4460
4461 static void
4462 gst_decode_bin_post_topology_message (GstDecodeBin * dbin)
4463 {
4464   GstStructure *s;
4465   GstMessage *msg;
4466
4467   s = gst_decode_chain_get_topology (dbin->decode_chain);
4468
4469   msg = gst_message_new_element (GST_OBJECT (dbin), s);
4470   gst_element_post_message (GST_ELEMENT (dbin), msg);
4471 }
4472
4473 static gboolean
4474 debug_sticky_event (GstPad * pad, GstEvent ** event, gpointer user_data)
4475 {
4476   GST_DEBUG_OBJECT (pad, "sticky event %s (%p)", GST_EVENT_TYPE_NAME (*event),
4477       *event);
4478   return TRUE;
4479 }
4480
4481
4482 /* Must only be called if the toplevel chain is complete and blocked! */
4483 /* Not MT-safe, call with decodebin expose lock! */
4484 static gboolean
4485 gst_decode_bin_expose (GstDecodeBin * dbin)
4486 {
4487   GList *tmp, *endpads;
4488   gboolean missing_plugin;
4489   GString *missing_plugin_details;
4490   gboolean already_exposed;
4491   gboolean last_group;
4492
4493 retry:
4494   endpads = NULL;
4495   missing_plugin = FALSE;
4496   already_exposed = TRUE;
4497   last_group = TRUE;
4498
4499   missing_plugin_details = g_string_new ("");
4500
4501   GST_DEBUG_OBJECT (dbin, "Exposing currently active chains/groups");
4502
4503   /* Don't expose if we're currently shutting down */
4504   DYN_LOCK (dbin);
4505   if (G_UNLIKELY (dbin->shutdown)) {
4506     GST_WARNING_OBJECT (dbin, "Currently, shutting down, aborting exposing");
4507     DYN_UNLOCK (dbin);
4508     return FALSE;
4509   }
4510   DYN_UNLOCK (dbin);
4511
4512   /* Get the pads that we're going to expose and mark things as exposed */
4513   if (!gst_decode_chain_expose (dbin->decode_chain, &endpads, &missing_plugin,
4514           missing_plugin_details, &last_group)) {
4515     g_list_foreach (endpads, (GFunc) gst_object_unref, NULL);
4516     g_list_free (endpads);
4517     g_string_free (missing_plugin_details, TRUE);
4518     GST_ERROR_OBJECT (dbin, "Broken chain/group tree");
4519     g_return_val_if_reached (FALSE);
4520     return FALSE;
4521   }
4522   if (endpads == NULL) {
4523     if (missing_plugin) {
4524       if (missing_plugin_details->len > 0) {
4525         gchar *details = g_string_free (missing_plugin_details, FALSE);
4526         GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL),
4527             ("no suitable plugins found:\n%s", details));
4528         g_free (details);
4529       } else {
4530         g_string_free (missing_plugin_details, TRUE);
4531         GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL),
4532             ("no suitable plugins found"));
4533       }
4534     } else {
4535       /* in this case, the stream ended without buffers,
4536        * just post a warning */
4537       g_string_free (missing_plugin_details, TRUE);
4538
4539       GST_WARNING_OBJECT (dbin, "All streams finished without buffers. "
4540           "Last group: %d", last_group);
4541       if (last_group) {
4542         GST_ELEMENT_ERROR (dbin, STREAM, FAILED, (NULL),
4543             ("all streams without buffers"));
4544       } else {
4545         gboolean switched = FALSE;
4546         gboolean drained = FALSE;
4547
4548         drain_and_switch_chains (dbin->decode_chain, NULL, &last_group,
4549             &drained, &switched);
4550         GST_ELEMENT_WARNING (dbin, STREAM, FAILED, (NULL),
4551             ("all streams without buffers"));
4552         if (switched) {
4553           if (gst_decode_chain_is_complete (dbin->decode_chain))
4554             goto retry;
4555           else
4556             return FALSE;
4557         }
4558       }
4559     }
4560
4561     do_async_done (dbin);
4562     return FALSE;
4563   }
4564
4565   g_string_free (missing_plugin_details, TRUE);
4566
4567   /* Check if this was called when everything was exposed already */
4568   for (tmp = endpads; tmp && already_exposed; tmp = tmp->next) {
4569     GstDecodePad *dpad = tmp->data;
4570
4571     already_exposed &= dpad->exposed;
4572     if (!already_exposed)
4573       break;
4574   }
4575   if (already_exposed) {
4576     GST_DEBUG_OBJECT (dbin, "Everything was exposed already!");
4577     g_list_foreach (endpads, (GFunc) gst_object_unref, NULL);
4578     g_list_free (endpads);
4579     return TRUE;
4580   }
4581
4582   /* going to expose something, reset buffering */
4583   gst_decode_bin_reset_buffering (dbin);
4584
4585   /* Set all already exposed pads to blocked */
4586   for (tmp = endpads; tmp; tmp = tmp->next) {
4587     GstDecodePad *dpad = tmp->data;
4588
4589     if (dpad->exposed) {
4590       GST_DEBUG_OBJECT (dpad, "blocking exposed pad");
4591       gst_decode_pad_set_blocked (dpad, TRUE);
4592     }
4593   }
4594
4595   /* re-order pads : video, then audio, then others */
4596   endpads = g_list_sort (endpads, (GCompareFunc) sort_end_pads);
4597
4598   /* Expose pads */
4599   for (tmp = endpads; tmp; tmp = tmp->next) {
4600     GstDecodePad *dpad = (GstDecodePad *) tmp->data;
4601     gchar *padname;
4602
4603     /* 1. rewrite name */
4604     padname = g_strdup_printf ("src_%u", dbin->nbpads);
4605     dbin->nbpads++;
4606     GST_DEBUG_OBJECT (dbin, "About to expose dpad %s as %s",
4607         GST_OBJECT_NAME (dpad), padname);
4608     gst_object_set_name (GST_OBJECT (dpad), padname);
4609     g_free (padname);
4610
4611     gst_pad_sticky_events_foreach (GST_PAD_CAST (dpad), debug_sticky_event,
4612         dpad);
4613
4614     /* 2. activate and add */
4615     if (!dpad->exposed) {
4616       dpad->exposed = TRUE;
4617       if (!gst_element_add_pad (GST_ELEMENT (dbin), GST_PAD_CAST (dpad))) {
4618         /* not really fatal, we can try to add the other pads */
4619         g_warning ("error adding pad to decodebin");
4620         dpad->exposed = FALSE;
4621         continue;
4622       }
4623     }
4624
4625     /* 3. emit signal */
4626     GST_INFO_OBJECT (dpad, "added new decoded pad");
4627   }
4628
4629   /* 4. Signal no-more-pads. This allows the application to hook stuff to the
4630    * exposed pads */
4631   GST_LOG_OBJECT (dbin, "signaling no-more-pads");
4632   gst_element_no_more_pads (GST_ELEMENT (dbin));
4633
4634   /* 5. Send a custom element message with the stream topology */
4635   if (dbin->post_stream_topology)
4636     gst_decode_bin_post_topology_message (dbin);
4637
4638   /* 6. Unblock internal pads. The application should have connected stuff now
4639    * so that streaming can continue. */
4640   for (tmp = endpads; tmp; tmp = tmp->next) {
4641     GstDecodePad *dpad = (GstDecodePad *) tmp->data;
4642
4643     GST_DEBUG_OBJECT (dpad, "unblocking");
4644     gst_decode_pad_unblock (dpad);
4645     GST_DEBUG_OBJECT (dpad, "unblocked");
4646     gst_object_unref (dpad);
4647   }
4648   g_list_free (endpads);
4649
4650   do_async_done (dbin);
4651   GST_DEBUG_OBJECT (dbin, "Exposed everything");
4652   return TRUE;
4653 }
4654
4655 /* gst_decode_chain_expose:
4656  *
4657  * Check if the chain can be exposed and add all endpads
4658  * to the endpads list.
4659  *
4660  * Also update the active group's multiqueue to the
4661  * runtime limits.
4662  *
4663  * Not MT-safe, call with decodebin expose lock! *
4664  */
4665 static gboolean
4666 gst_decode_chain_expose (GstDecodeChain * chain, GList ** endpads,
4667     gboolean * missing_plugin, GString * missing_plugin_details,
4668     gboolean * last_group)
4669 {
4670   GstDecodeGroup *group;
4671   GList *l;
4672   GstDecodeBin *dbin;
4673
4674   if (chain->deadend) {
4675     if (chain->endcaps) {
4676       if (chain->deadend_details) {
4677         g_string_append (missing_plugin_details, chain->deadend_details);
4678         g_string_append_c (missing_plugin_details, '\n');
4679       } else {
4680         gchar *desc = gst_pb_utils_get_codec_description (chain->endcaps);
4681         gchar *caps_str = gst_caps_to_string (chain->endcaps);
4682         g_string_append_printf (missing_plugin_details,
4683             "Missing decoder: %s (%s)\n", desc, caps_str);
4684         g_free (caps_str);
4685         g_free (desc);
4686       }
4687       *missing_plugin = TRUE;
4688     }
4689     return TRUE;
4690   }
4691
4692   if (chain->endpad) {
4693     if (!chain->endpad->blocked && !chain->endpad->exposed)
4694       return FALSE;
4695     *endpads = g_list_prepend (*endpads, gst_object_ref (chain->endpad));
4696     return TRUE;
4697   }
4698
4699   if (chain->next_groups)
4700     *last_group = FALSE;
4701
4702   group = chain->active_group;
4703   if (!group)
4704     return FALSE;
4705   if (!group->no_more_pads && !group->overrun)
4706     return FALSE;
4707
4708   dbin = group->dbin;
4709
4710   /* we can now disconnect any overrun signal, which is used to expose the
4711    * group. */
4712   if (group->overrunsig) {
4713     GST_LOG_OBJECT (dbin, "Disconnecting overrun");
4714     g_signal_handler_disconnect (group->multiqueue, group->overrunsig);
4715     group->overrunsig = 0;
4716   }
4717
4718   for (l = group->children; l; l = l->next) {
4719     GstDecodeChain *childchain = l->data;
4720
4721     if (!gst_decode_chain_expose (childchain, endpads, missing_plugin,
4722             missing_plugin_details, last_group))
4723       return FALSE;
4724   }
4725
4726   return TRUE;
4727 }
4728
4729 /*************************
4730  * GstDecodePad functions
4731  *************************/
4732
4733 static void
4734 gst_decode_pad_class_init (GstDecodePadClass * klass)
4735 {
4736 }
4737
4738 static void
4739 gst_decode_pad_init (GstDecodePad * pad)
4740 {
4741   pad->chain = NULL;
4742   pad->blocked = FALSE;
4743   pad->exposed = FALSE;
4744   pad->drained = FALSE;
4745   gst_object_ref_sink (pad);
4746 }
4747
4748 static GstPadProbeReturn
4749 source_pad_blocked_cb (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
4750 {
4751   GstDecodePad *dpad = user_data;
4752   GstDecodeChain *chain;
4753   GstDecodeBin *dbin;
4754   GstPadProbeReturn ret = GST_PAD_PROBE_OK;
4755
4756   if (GST_PAD_PROBE_INFO_TYPE (info) & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM) {
4757     GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
4758
4759     GST_LOG_OBJECT (pad, "Seeing event '%s'", GST_EVENT_TYPE_NAME (event));
4760
4761     if (!GST_EVENT_IS_SERIALIZED (event)) {
4762       /* do not block on sticky or out of band events otherwise the allocation query
4763          from demuxer might block the loop thread */
4764       GST_LOG_OBJECT (pad, "Letting OOB event through");
4765       return GST_PAD_PROBE_PASS;
4766     }
4767
4768     if (GST_EVENT_IS_STICKY (event) && GST_EVENT_TYPE (event) != GST_EVENT_EOS) {
4769       /* manually push sticky events to ghost pad to avoid exposing pads
4770        * that don't have the sticky events. Handle EOS separately as we
4771        * want to block the pad on it if we didn't get any buffers before
4772        * EOS and expose the pad then. */
4773       gst_pad_push_event (GST_PAD_CAST (dpad), gst_event_ref (event));
4774
4775       /* let the sticky events pass */
4776       ret = GST_PAD_PROBE_PASS;
4777
4778       /* we only want to try to expose on CAPS events */
4779       if (GST_EVENT_TYPE (event) != GST_EVENT_CAPS) {
4780         GST_LOG_OBJECT (pad, "Letting sticky non-CAPS event through");
4781         goto done;
4782       }
4783     }
4784   } else if (GST_PAD_PROBE_INFO_TYPE (info) &
4785       GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM) {
4786     GstQuery *query = GST_PAD_PROBE_INFO_QUERY (info);
4787
4788     if (!GST_QUERY_IS_SERIALIZED (query)) {
4789       /* do not block on non-serialized queries */
4790       GST_LOG_OBJECT (pad, "Letting non-serialized query through");
4791       return GST_PAD_PROBE_PASS;
4792     }
4793     if (!gst_pad_has_current_caps (pad)) {
4794       /* do not block on allocation queries before we have caps,
4795        * this would deadlock because we are doing no autoplugging
4796        * without caps.
4797        * TODO: Try to do autoplugging based on the query caps
4798        */
4799       GST_LOG_OBJECT (pad, "Letting serialized query before caps through");
4800       return GST_PAD_PROBE_PASS;
4801     }
4802   }
4803   chain = dpad->chain;
4804   dbin = chain->dbin;
4805
4806   GST_LOG_OBJECT (dpad, "blocked: dpad->chain:%p", chain);
4807
4808   dpad->blocked = TRUE;
4809
4810   EXPOSE_LOCK (dbin);
4811   if (dbin->decode_chain) {
4812     if (gst_decode_chain_is_complete (dbin->decode_chain)) {
4813       if (!gst_decode_bin_expose (dbin))
4814         GST_WARNING_OBJECT (dbin, "Couldn't expose group");
4815     }
4816   }
4817   EXPOSE_UNLOCK (dbin);
4818
4819 done:
4820   return ret;
4821 }
4822
4823 static GstPadProbeReturn
4824 source_pad_event_probe (GstPad * pad, GstPadProbeInfo * info,
4825     gpointer user_data)
4826 {
4827   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
4828   GstDecodePad *dpad = user_data;
4829   gboolean res = TRUE;
4830
4831   GST_LOG_OBJECT (pad, "%s dpad:%p", GST_EVENT_TYPE_NAME (event), dpad);
4832
4833   if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
4834     GST_DEBUG_OBJECT (pad, "we received EOS");
4835
4836     /* Check if all pads are drained.
4837      * * If there is no next group, we will let the EOS go through.
4838      * * If there is a next group but the current group isn't completely
4839      *   drained, we will drop the EOS event.
4840      * * If there is a next group to expose and this was the last non-drained
4841      *   pad for that group, we will remove the ghostpad of the current group
4842      *   first, which unlinks the peer and so drops the EOS. */
4843     res = gst_decode_pad_handle_eos (dpad);
4844   }
4845   if (res)
4846     return GST_PAD_PROBE_OK;
4847   else
4848     return GST_PAD_PROBE_DROP;
4849 }
4850
4851 static void
4852 gst_decode_pad_set_blocked (GstDecodePad * dpad, gboolean blocked)
4853 {
4854   GstDecodeBin *dbin = dpad->dbin;
4855   GstPad *opad;
4856
4857   DYN_LOCK (dbin);
4858
4859   GST_DEBUG_OBJECT (dpad, "blocking pad: %d", blocked);
4860
4861   opad = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (dpad));
4862   if (!opad)
4863     goto out;
4864
4865   /* do not block if shutting down.
4866    * we do not consider/expect it blocked further below, but use other trick */
4867   if (!blocked || !dbin->shutdown) {
4868     if (blocked) {
4869       if (dpad->block_id == 0)
4870         dpad->block_id =
4871             gst_pad_add_probe (opad,
4872             GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM |
4873             GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM, source_pad_blocked_cb,
4874             gst_object_ref (dpad), (GDestroyNotify) gst_object_unref);
4875     } else {
4876       if (dpad->block_id != 0) {
4877         gst_pad_remove_probe (opad, dpad->block_id);
4878         dpad->block_id = 0;
4879       }
4880       dpad->blocked = FALSE;
4881     }
4882   }
4883
4884   if (blocked) {
4885     if (dbin->shutdown) {
4886       /* deactivate to force flushing state to prevent NOT_LINKED errors */
4887       gst_pad_set_active (GST_PAD_CAST (dpad), FALSE);
4888       /* note that deactivating the target pad would have no effect here,
4889        * since elements are typically connected first (and pads exposed),
4890        * and only then brought to PAUSED state (so pads activated) */
4891     } else {
4892       gst_object_ref (dpad);
4893       dbin->blocked_pads = g_list_prepend (dbin->blocked_pads, dpad);
4894     }
4895   } else {
4896     GList *l;
4897
4898     if ((l = g_list_find (dbin->blocked_pads, dpad))) {
4899       gst_object_unref (dpad);
4900       dbin->blocked_pads = g_list_delete_link (dbin->blocked_pads, l);
4901     }
4902   }
4903   gst_object_unref (opad);
4904 out:
4905   DYN_UNLOCK (dbin);
4906 }
4907
4908 static void
4909 gst_decode_pad_add_drained_check (GstDecodePad * dpad)
4910 {
4911   gst_pad_add_probe (GST_PAD_CAST (dpad), GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
4912       source_pad_event_probe, dpad, NULL);
4913 }
4914
4915 static void
4916 gst_decode_pad_activate (GstDecodePad * dpad, GstDecodeChain * chain)
4917 {
4918   g_return_if_fail (chain != NULL);
4919
4920   dpad->chain = chain;
4921   gst_pad_set_active (GST_PAD_CAST (dpad), TRUE);
4922   gst_decode_pad_set_blocked (dpad, TRUE);
4923   gst_decode_pad_add_drained_check (dpad);
4924 }
4925
4926 static void
4927 gst_decode_pad_unblock (GstDecodePad * dpad)
4928 {
4929   gst_decode_pad_set_blocked (dpad, FALSE);
4930 }
4931
4932 static gboolean
4933 gst_decode_pad_query (GstPad * pad, GstObject * parent, GstQuery * query)
4934 {
4935   GstDecodePad *dpad = GST_DECODE_PAD (parent);
4936   gboolean ret = FALSE;
4937
4938   CHAIN_MUTEX_LOCK (dpad->chain);
4939   if (!dpad->exposed && !dpad->dbin->shutdown && !dpad->chain->deadend
4940       && dpad->chain->elements) {
4941     GstDecodeElement *delem = dpad->chain->elements->data;
4942
4943     ret = FALSE;
4944     GST_DEBUG_OBJECT (dpad->dbin,
4945         "calling autoplug-query for %s (element %s): %" GST_PTR_FORMAT,
4946         GST_PAD_NAME (dpad), GST_ELEMENT_NAME (delem->element), query);
4947     g_signal_emit (G_OBJECT (dpad->dbin),
4948         gst_decode_bin_signals[SIGNAL_AUTOPLUG_QUERY], 0, dpad, delem->element,
4949         query, &ret);
4950
4951     if (ret)
4952       GST_DEBUG_OBJECT (dpad->dbin,
4953           "autoplug-query returned %d: %" GST_PTR_FORMAT, ret, query);
4954     else
4955       GST_DEBUG_OBJECT (dpad->dbin, "autoplug-query returned %d", ret);
4956   }
4957   CHAIN_MUTEX_UNLOCK (dpad->chain);
4958
4959   /* If exposed or nothing handled the query use the default handler */
4960   if (!ret)
4961     ret = gst_pad_query_default (pad, parent, query);
4962
4963   return ret;
4964 }
4965
4966 /*gst_decode_pad_new:
4967  *
4968  * Creates a new GstDecodePad for the given pad.
4969  */
4970 static GstDecodePad *
4971 gst_decode_pad_new (GstDecodeBin * dbin, GstDecodeChain * chain)
4972 {
4973   GstDecodePad *dpad;
4974   GstProxyPad *ppad;
4975   GstPadTemplate *pad_tmpl;
4976
4977   GST_DEBUG_OBJECT (dbin, "making new decodepad");
4978   pad_tmpl = gst_static_pad_template_get (&decoder_bin_src_template);
4979   dpad =
4980       g_object_new (GST_TYPE_DECODE_PAD, "direction", GST_PAD_SRC,
4981       "template", pad_tmpl, NULL);
4982   gst_ghost_pad_construct (GST_GHOST_PAD_CAST (dpad));
4983   dpad->chain = chain;
4984   dpad->dbin = dbin;
4985   gst_object_unref (pad_tmpl);
4986
4987   ppad = gst_proxy_pad_get_internal (GST_PROXY_PAD (dpad));
4988   gst_pad_set_query_function (GST_PAD_CAST (ppad), gst_decode_pad_query);
4989   gst_object_unref (ppad);
4990
4991   return dpad;
4992 }
4993
4994 static void
4995 gst_pending_pad_free (GstPendingPad * ppad)
4996 {
4997   g_assert (ppad);
4998   g_assert (ppad->pad);
4999
5000   if (ppad->event_probe_id != 0)
5001     gst_pad_remove_probe (ppad->pad, ppad->event_probe_id);
5002   if (ppad->notify_caps_id)
5003     g_signal_handler_disconnect (ppad->pad, ppad->notify_caps_id);
5004   gst_object_unref (ppad->pad);
5005   g_slice_free (GstPendingPad, ppad);
5006 }
5007
5008 /*****
5009  * Element add/remove
5010  *****/
5011
5012 static void
5013 do_async_start (GstDecodeBin * dbin)
5014 {
5015   GstMessage *message;
5016
5017   dbin->async_pending = TRUE;
5018
5019   message = gst_message_new_async_start (GST_OBJECT_CAST (dbin));
5020   parent_class->handle_message (GST_BIN_CAST (dbin), message);
5021 }
5022
5023 static void
5024 do_async_done (GstDecodeBin * dbin)
5025 {
5026   GstMessage *message;
5027
5028   if (dbin->async_pending) {
5029     message =
5030         gst_message_new_async_done (GST_OBJECT_CAST (dbin),
5031         GST_CLOCK_TIME_NONE);
5032     parent_class->handle_message (GST_BIN_CAST (dbin), message);
5033
5034     dbin->async_pending = FALSE;
5035   }
5036 }
5037
5038 /*****
5039  * convenience functions
5040  *****/
5041
5042 /* find_sink_pad
5043  *
5044  * Returns the first sink pad of the given element, or NULL if it doesn't have
5045  * any.
5046  */
5047
5048 static GstPad *
5049 find_sink_pad (GstElement * element)
5050 {
5051   GstIterator *it;
5052   GstPad *pad = NULL;
5053   GValue item = { 0, };
5054
5055   it = gst_element_iterate_sink_pads (element);
5056
5057   if ((gst_iterator_next (it, &item)) == GST_ITERATOR_OK)
5058     pad = g_value_dup_object (&item);
5059   g_value_unset (&item);
5060   gst_iterator_free (it);
5061
5062   return pad;
5063 }
5064
5065 /* call with dyn_lock held */
5066 static void
5067 unblock_pads (GstDecodeBin * dbin)
5068 {
5069   GList *tmp;
5070
5071   GST_LOG_OBJECT (dbin, "unblocking pads");
5072
5073   for (tmp = dbin->blocked_pads; tmp; tmp = tmp->next) {
5074     GstDecodePad *dpad = (GstDecodePad *) tmp->data;
5075     GstPad *opad;
5076
5077     opad = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (dpad));
5078     if (!opad)
5079       continue;
5080
5081     GST_DEBUG_OBJECT (dpad, "unblocking");
5082     if (dpad->block_id != 0) {
5083       gst_pad_remove_probe (opad, dpad->block_id);
5084       dpad->block_id = 0;
5085     }
5086     dpad->blocked = FALSE;
5087     /* make flushing, prevent NOT_LINKED */
5088     GST_PAD_SET_FLUSHING (GST_PAD_CAST (dpad));
5089     gst_object_unref (dpad);
5090     gst_object_unref (opad);
5091     GST_DEBUG_OBJECT (dpad, "unblocked");
5092   }
5093
5094   /* clear, no more blocked pads */
5095   g_list_free (dbin->blocked_pads);
5096   dbin->blocked_pads = NULL;
5097 }
5098
5099 static GstStateChangeReturn
5100 gst_decode_bin_change_state (GstElement * element, GstStateChange transition)
5101 {
5102   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
5103   GstDecodeBin *dbin = GST_DECODE_BIN (element);
5104   GstDecodeChain *chain_to_free = NULL;
5105
5106   switch (transition) {
5107     case GST_STATE_CHANGE_NULL_TO_READY:
5108       if (dbin->typefind == NULL)
5109         goto missing_typefind;
5110       break;
5111     case GST_STATE_CHANGE_READY_TO_PAUSED:
5112       /* Make sure we've cleared all existing chains */
5113       EXPOSE_LOCK (dbin);
5114       if (dbin->decode_chain) {
5115         gst_decode_chain_free (dbin->decode_chain);
5116         dbin->decode_chain = NULL;
5117       }
5118       EXPOSE_UNLOCK (dbin);
5119       DYN_LOCK (dbin);
5120       GST_LOG_OBJECT (dbin, "clearing shutdown flag");
5121       dbin->shutdown = FALSE;
5122       DYN_UNLOCK (dbin);
5123       dbin->have_type = FALSE;
5124       ret = GST_STATE_CHANGE_ASYNC;
5125       do_async_start (dbin);
5126
5127
5128       /* connect a signal to find out when the typefind element found
5129        * a type */
5130       dbin->have_type_id =
5131           g_signal_connect (dbin->typefind, "have-type",
5132           G_CALLBACK (type_found), dbin);
5133       break;
5134     case GST_STATE_CHANGE_PAUSED_TO_READY:
5135       if (dbin->have_type_id)
5136         g_signal_handler_disconnect (dbin->typefind, dbin->have_type_id);
5137       dbin->have_type_id = 0;
5138       DYN_LOCK (dbin);
5139       GST_LOG_OBJECT (dbin, "setting shutdown flag");
5140       dbin->shutdown = TRUE;
5141       unblock_pads (dbin);
5142       DYN_UNLOCK (dbin);
5143     default:
5144       break;
5145   }
5146
5147   {
5148     GstStateChangeReturn bret;
5149
5150     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5151     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
5152       goto activate_failed;
5153     else if (G_UNLIKELY (bret == GST_STATE_CHANGE_NO_PREROLL)) {
5154       do_async_done (dbin);
5155       ret = bret;
5156     }
5157   }
5158   switch (transition) {
5159     case GST_STATE_CHANGE_PAUSED_TO_READY:
5160       do_async_done (dbin);
5161       EXPOSE_LOCK (dbin);
5162       if (dbin->decode_chain) {
5163         chain_to_free = dbin->decode_chain;
5164         gst_decode_chain_free_internal (dbin->decode_chain, TRUE);
5165         dbin->decode_chain = NULL;
5166       }
5167       EXPOSE_UNLOCK (dbin);
5168       if (chain_to_free)
5169         gst_decode_chain_free (chain_to_free);
5170       g_list_free_full (dbin->buffering_status,
5171           (GDestroyNotify) gst_message_unref);
5172       dbin->buffering_status = NULL;
5173       break;
5174     case GST_STATE_CHANGE_READY_TO_NULL:
5175     default:
5176       break;
5177   }
5178
5179   return ret;
5180
5181 /* ERRORS */
5182 missing_typefind:
5183   {
5184     gst_element_post_message (element,
5185         gst_missing_element_message_new (element, "typefind"));
5186     GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL), ("no typefind!"));
5187     return GST_STATE_CHANGE_FAILURE;
5188   }
5189 activate_failed:
5190   {
5191     GST_DEBUG_OBJECT (element,
5192         "element failed to change states -- activation problem?");
5193     return GST_STATE_CHANGE_FAILURE;
5194   }
5195 }
5196
5197 static void
5198 gst_decode_bin_handle_message (GstBin * bin, GstMessage * msg)
5199 {
5200   GstDecodeBin *dbin = GST_DECODE_BIN (bin);
5201   gboolean drop = FALSE;
5202
5203   if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_ERROR) {
5204     GST_OBJECT_LOCK (dbin);
5205     drop = (g_list_find (dbin->filtered, GST_MESSAGE_SRC (msg)) != NULL);
5206     if (drop)
5207       dbin->filtered_errors =
5208           g_list_prepend (dbin->filtered_errors, gst_message_ref (msg));
5209     GST_OBJECT_UNLOCK (dbin);
5210   } else if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_BUFFERING) {
5211     gint perc, msg_perc;
5212     gint smaller_perc = 100;
5213     GstMessage *smaller = NULL;
5214     GList *found = NULL;
5215     GList *iter;
5216
5217     /* buffering messages must be aggregated as there might be multiple
5218      * multiqueue in the pipeline and their independent buffering messages
5219      * will confuse the application
5220      *
5221      * decodebin keeps a list of messages received from elements that are
5222      * buffering.
5223      * Rules are:
5224      * 1) Always post the smaller buffering %
5225      * 2) If an element posts a 100% buffering message, remove it from the list
5226      * 3) When there are no more messages on the list, post 100% message
5227      * 4) When an element posts a new buffering message, update the one
5228      *    on the list to this new value
5229      */
5230
5231     GST_OBJECT_LOCK (dbin);
5232     gst_message_parse_buffering (msg, &msg_perc);
5233
5234     /*
5235      * Single loop for 2 things:
5236      * 1) Look for a message with the same source
5237      *   1.1) If the received message is 100%, remove it from the list
5238      * 2) Find the minimum buffering from the list
5239      */
5240     for (iter = dbin->buffering_status; iter;) {
5241       GstMessage *bufstats = iter->data;
5242       if (GST_MESSAGE_SRC (bufstats) == GST_MESSAGE_SRC (msg)) {
5243         found = iter;
5244         if (msg_perc < 100) {
5245           gst_message_unref (iter->data);
5246           bufstats = iter->data = gst_message_ref (msg);
5247         } else {
5248           GList *current = iter;
5249
5250           /* remove the element here and avoid confusing the loop */
5251           iter = g_list_next (iter);
5252
5253           gst_message_unref (current->data);
5254           dbin->buffering_status =
5255               g_list_delete_link (dbin->buffering_status, current);
5256
5257           continue;
5258         }
5259       }
5260
5261       gst_message_parse_buffering (bufstats, &perc);
5262       if (perc < smaller_perc) {
5263         smaller_perc = perc;
5264         smaller = bufstats;
5265       }
5266       iter = g_list_next (iter);
5267     }
5268
5269     if (found == NULL && msg_perc < 100) {
5270       if (msg_perc < smaller_perc) {
5271         smaller_perc = msg_perc;
5272         smaller = msg;
5273       }
5274       dbin->buffering_status =
5275           g_list_prepend (dbin->buffering_status, gst_message_ref (msg));
5276     }
5277
5278     /* now compute the buffering message that should be posted */
5279     if (smaller_perc == 100) {
5280       g_assert (dbin->buffering_status == NULL);
5281       /* we are posting the original received msg */
5282     } else {
5283       gst_message_replace (&msg, smaller);
5284     }
5285     GST_OBJECT_UNLOCK (dbin);
5286   }
5287
5288   if (drop)
5289     gst_message_unref (msg);
5290   else
5291     GST_BIN_CLASS (parent_class)->handle_message (bin, msg);
5292 }
5293
5294 gboolean
5295 gst_decode_bin_plugin_init (GstPlugin * plugin)
5296 {
5297   GST_DEBUG_CATEGORY_INIT (gst_decode_bin_debug, "decodebin", 0, "decoder bin");
5298
5299   /* Register some quarks here for the stream topology message */
5300   topology_structure_name = g_quark_from_static_string ("stream-topology");
5301   topology_caps = g_quark_from_static_string ("caps");
5302   topology_next = g_quark_from_static_string ("next");
5303   topology_pad = g_quark_from_static_string ("pad");
5304   topology_element_srcpad = g_quark_from_static_string ("element-srcpad");
5305
5306   return gst_element_register (plugin, "decodebin", GST_RANK_NONE,
5307       GST_TYPE_DECODE_BIN);
5308 }