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