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