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