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