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