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