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