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