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