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