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