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