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