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