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