Merge branch 'upstream/1.16' into tizen_gst_1.16.2
[platform/upstream/gst-plugins-base.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  * Copyright (C) <2013> Collabora Ltd.
7  *   Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /**
26  * SECTION:element-decodebin
27  * @title: decodebin
28  *
29  * #GstBin that auto-magically constructs a decoding pipeline using available
30  * decoders and demuxers via auto-plugging.
31  *
32  * decodebin is considered stable now and replaces the old #decodebin element.
33  * #uridecodebin uses decodebin internally and is often more convenient to
34  * use, as it creates a suitable source element as well.
35  */
36
37 /* Implementation notes:
38  *
39  * The following section describes how decodebin works internally.
40  *
41  * The first part of decodebin is its typefind element, which tries
42  * to determine the media type of the input stream. If the type is found
43  * autoplugging starts.
44  *
45  * decodebin internally organizes the elements it autoplugged into GstDecodeChains
46  * and GstDecodeGroups. A decode chain is a single chain of decoding, this
47  * means that if decodebin every autoplugs an element with two+ srcpads
48  * (e.g. a demuxer) this will end the chain and everything following this
49  * demuxer will be put into decode groups below the chain. Otherwise,
50  * if an element has a single srcpad that outputs raw data the decode chain
51  * is ended too and a GstDecodePad is stored and blocked.
52  *
53  * A decode group combines a number of chains that are created by a
54  * demuxer element. All those chains are connected through a multiqueue to
55  * the demuxer. A new group for the same demuxer is only created if the
56  * demuxer has signaled no-more-pads, in which case all following pads
57  * create a new chain in the new group.
58  *
59  * This continues until the top-level decode chain is complete. A decode
60  * chain is complete if it either ends with a blocked endpad, if autoplugging
61  * stopped because no suitable plugins could be found or if the active group
62  * is complete. A decode group on the other hand is complete if all child
63  * chains are complete.
64  *
65  * If this happens at some point, all endpads of all active groups are exposed.
66  * For this decodebin adds the endpads, signals no-more-pads and then unblocks
67  * them. Now playback starts.
68  *
69  * If one of the chains that end on a endpad receives EOS decodebin checks
70  * if all chains and groups are drained. In that case everything goes into EOS.
71  * If there is a chain where the active group is drained but there exist next
72  * groups, the active group is hidden (endpads are removed) and the next group
73  * is exposed. This means that in some cases more pads may be created even
74  * after the initial no-more-pads signal. This happens for example with
75  * so-called "chained oggs", most commonly found among ogg/vorbis internet
76  * radio streams.
77  *
78  * Note 1: If we're talking about blocked endpads this really means that the
79  * *target* pads of the endpads are blocked. Pads that are exposed to the outside
80  * should never ever be blocked!
81  *
82  * Note 2: If a group is complete and the parent's chain demuxer adds new pads
83  * but never signaled no-more-pads this additional pads will be ignored!
84  *
85  */
86
87 /* FIXME 0.11: suppress warnings for deprecated API such as GValueArray
88  * with newer GLib versions (>= 2.31.0) */
89 #define GLIB_DISABLE_DEPRECATION_WARNINGS
90
91 #ifdef HAVE_CONFIG_H
92 #include "config.h"
93 #endif
94
95 #include <gst/gst-i18n-plugin.h>
96
97 #include <string.h>
98 #include <gst/gst.h>
99 #include <gst/pbutils/pbutils.h>
100
101 #include "gstplay-enum.h"
102 #include "gstplayback.h"
103 #include "gstrawcaps.h"
104 #include "gstplaybackutils.h"
105
106 /* generic templates */
107 static GstStaticPadTemplate decoder_bin_sink_template =
108 GST_STATIC_PAD_TEMPLATE ("sink",
109     GST_PAD_SINK,
110     GST_PAD_ALWAYS,
111     GST_STATIC_CAPS_ANY);
112
113 static GstStaticPadTemplate decoder_bin_src_template =
114 GST_STATIC_PAD_TEMPLATE ("src_%u",
115     GST_PAD_SRC,
116     GST_PAD_SOMETIMES,
117     GST_STATIC_CAPS_ANY);
118
119 GST_DEBUG_CATEGORY_STATIC (gst_decode_bin_debug);
120 #define GST_CAT_DEFAULT gst_decode_bin_debug
121
122 typedef struct _GstPendingPad GstPendingPad;
123 typedef struct _GstDecodeElement GstDecodeElement;
124 typedef struct _GstDemuxerPad GstDemuxerPad;
125 typedef struct _GstDecodeChain GstDecodeChain;
126 typedef struct _GstDecodeGroup GstDecodeGroup;
127 typedef struct _GstDecodePad GstDecodePad;
128 typedef GstGhostPadClass GstDecodePadClass;
129 typedef struct _GstDecodeBin GstDecodeBin;
130 typedef struct _GstDecodeBinClass GstDecodeBinClass;
131
132 #define GST_TYPE_DECODE_BIN             (gst_decode_bin_get_type())
133 #define GST_DECODE_BIN_CAST(obj)        ((GstDecodeBin*)(obj))
134 #define GST_DECODE_BIN(obj)             (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_DECODE_BIN,GstDecodeBin))
135 #define GST_DECODE_BIN_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_DECODE_BIN,GstDecodeBinClass))
136 #define GST_IS_DECODE_BIN(obj)          (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_DECODE_BIN))
137 #define GST_IS_DECODE_BIN_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_DECODE_BIN))
138
139 /**
140  *  GstDecodeBin:
141  *
142  *  The opaque #GstDecodeBin data structure
143  */
144 struct _GstDecodeBin
145 {
146   GstBin bin;                   /* we extend GstBin */
147
148   /* properties */
149   GstCaps *caps;                /* caps on which to stop decoding */
150   gchar *encoding;              /* encoding of subtitles */
151   gboolean use_buffering;       /* configure buffering on multiqueues */
152   gint low_percent;
153   gint high_percent;
154   guint max_size_bytes;
155   guint max_size_buffers;
156   guint64 max_size_time;
157   gboolean post_stream_topology;
158   guint64 connection_speed;
159
160   GstElement *typefind;         /* this holds the typefind object */
161
162   GMutex expose_lock;           /* Protects exposal and removal of groups */
163   GstDecodeChain *decode_chain; /* Top level decode chain */
164   guint nbpads;                 /* unique identifier for source pads */
165
166   GMutex factories_lock;
167   guint32 factories_cookie;     /* Cookie from last time when factories was updated */
168   GList *factories;             /* factories we can use for selecting elements */
169
170   GMutex subtitle_lock;         /* Protects changes to subtitles and encoding */
171   GList *subtitles;             /* List of elements with subtitle-encoding,
172                                  * protected by above mutex! */
173
174   gboolean have_type;           /* if we received the have_type signal */
175   guint have_type_id;           /* signal id for have-type from typefind */
176
177   gboolean async_pending;       /* async-start has been emitted */
178
179   GMutex dyn_lock;              /* lock protecting pad blocking */
180   gboolean shutdown;            /* if we are shutting down */
181   GList *blocked_pads;          /* pads that have set to block */
182
183   gboolean expose_allstreams;   /* Whether to expose unknow type streams or not */
184
185 #ifdef TIZEN_FEATURE_TRUSTZONE
186   /*tzmultiqueue patch : use trustzone flag*/
187   gboolean use_trustzone;
188 #endif
189   GList *filtered;              /* elements for which error messages are filtered */
190   GList *filtered_errors;       /* filtered error messages */
191
192   GList *buffering_status;      /* element currently buffering messages */
193   GMutex buffering_lock;
194   GMutex buffering_post_lock;
195
196   GMutex cleanup_lock;          /* Mutex used to protect the cleanup thread */
197   GThread *cleanup_thread;      /* thread used to free chains asynchronously.
198                                  * We store it to make sure we end up joining it
199                                  * before stopping the element.
200                                  * Protected by the object lock */
201   GList *cleanup_groups;        /* List of groups to free  */
202 };
203
204 struct _GstDecodeBinClass
205 {
206   GstBinClass parent_class;
207
208   /* signal fired when we found a pad that we cannot decode */
209   void (*unknown_type) (GstElement * element, GstPad * pad, GstCaps * caps);
210
211   /* signal fired to know if we continue trying to decode the given caps */
212     gboolean (*autoplug_continue) (GstElement * element, GstPad * pad,
213       GstCaps * caps);
214   /* signal fired to get a list of factories to try to autoplug */
215   GValueArray *(*autoplug_factories) (GstElement * element, GstPad * pad,
216       GstCaps * caps);
217   /* signal fired to sort the factories */
218   GValueArray *(*autoplug_sort) (GstElement * element, GstPad * pad,
219       GstCaps * caps, GValueArray * factories);
220   /* signal fired to select from the proposed list of factories */
221     GstAutoplugSelectResult (*autoplug_select) (GstElement * element,
222       GstPad * pad, GstCaps * caps, GstElementFactory * factory);
223   /* signal fired when a autoplugged element that is not linked downstream
224    * or exposed wants to query something */
225     gboolean (*autoplug_query) (GstElement * element, GstPad * pad,
226       GstQuery * query);
227
228   /* fired when the last group is drained */
229   void (*drained) (GstElement * element);
230 };
231
232 /* signals */
233 enum
234 {
235   SIGNAL_UNKNOWN_TYPE,
236   SIGNAL_AUTOPLUG_CONTINUE,
237   SIGNAL_AUTOPLUG_FACTORIES,
238   SIGNAL_AUTOPLUG_SELECT,
239   SIGNAL_AUTOPLUG_SORT,
240   SIGNAL_AUTOPLUG_QUERY,
241   SIGNAL_DRAINED,
242   LAST_SIGNAL
243 };
244
245 /* automatic sizes, while prerolling we buffer up to 2MB, we ignore time
246  * and buffers in this case. */
247 #define AUTO_PREROLL_SIZE_BYTES                  2 * 1024 * 1024
248 #define AUTO_PREROLL_SIZE_BUFFERS                0
249 #define AUTO_PREROLL_NOT_SEEKABLE_SIZE_TIME      10 * GST_SECOND
250 #define AUTO_PREROLL_SEEKABLE_SIZE_TIME          0
251
252 /* when playing, keep a max of 2MB of data but try to keep the number of buffers
253  * as low as possible (try to aim for 5 buffers) */
254 #define AUTO_PLAY_SIZE_BYTES        2 * 1024 * 1024
255 #define AUTO_PLAY_SIZE_BUFFERS      5
256 #define AUTO_PLAY_SIZE_TIME         0
257
258 #define DEFAULT_SUBTITLE_ENCODING NULL
259 #define DEFAULT_USE_BUFFERING     FALSE
260 #define DEFAULT_LOW_PERCENT       10
261 #define DEFAULT_HIGH_PERCENT      99
262 /* by default we use the automatic values above */
263 #define DEFAULT_MAX_SIZE_BYTES    0
264 #define DEFAULT_MAX_SIZE_BUFFERS  0
265 #define DEFAULT_MAX_SIZE_TIME     0
266 #define DEFAULT_POST_STREAM_TOPOLOGY FALSE
267 #define DEFAULT_EXPOSE_ALL_STREAMS  TRUE
268 #define DEFAULT_CONNECTION_SPEED    0
269
270 /* Properties */
271 enum
272 {
273   PROP_0,
274   PROP_CAPS,
275   PROP_SUBTITLE_ENCODING,
276   PROP_SINK_CAPS,
277   PROP_USE_BUFFERING,
278   PROP_LOW_PERCENT,
279   PROP_HIGH_PERCENT,
280   PROP_MAX_SIZE_BYTES,
281   PROP_MAX_SIZE_BUFFERS,
282   PROP_MAX_SIZE_TIME,
283   PROP_POST_STREAM_TOPOLOGY,
284   PROP_EXPOSE_ALL_STREAMS,
285   PROP_CONNECTION_SPEED
286 #ifdef TIZEN_FEATURE_TRUSTZONE
287   /*tzmultiqueue patch : use trustzone flag*/
288   ,PROP_USE_TRUSTZONE
289 #endif
290 };
291
292 static GstBinClass *parent_class;
293 static guint gst_decode_bin_signals[LAST_SIGNAL] = { 0 };
294
295 static GstStaticCaps default_raw_caps = GST_STATIC_CAPS (DEFAULT_RAW_CAPS);
296
297 static void do_async_start (GstDecodeBin * dbin);
298 static void do_async_done (GstDecodeBin * dbin);
299
300 static void type_found (GstElement * typefind, guint probability,
301     GstCaps * caps, GstDecodeBin * decode_bin);
302
303 static void decodebin_set_queue_size (GstDecodeBin * dbin,
304     GstElement * multiqueue, gboolean preroll, gboolean seekable);
305 static void decodebin_set_queue_size_full (GstDecodeBin * dbin,
306     GstElement * multiqueue, gboolean use_buffering, gboolean preroll,
307     gboolean seekable);
308
309 static gboolean gst_decode_bin_autoplug_continue (GstElement * element,
310     GstPad * pad, GstCaps * caps);
311 static GValueArray *gst_decode_bin_autoplug_factories (GstElement *
312     element, GstPad * pad, GstCaps * caps);
313 static GValueArray *gst_decode_bin_autoplug_sort (GstElement * element,
314     GstPad * pad, GstCaps * caps, GValueArray * factories);
315 static GstAutoplugSelectResult gst_decode_bin_autoplug_select (GstElement *
316     element, GstPad * pad, GstCaps * caps, GstElementFactory * factory);
317 static gboolean gst_decode_bin_autoplug_query (GstElement * element,
318     GstPad * pad, GstQuery * query);
319
320 static void gst_decode_bin_set_property (GObject * object, guint prop_id,
321     const GValue * value, GParamSpec * pspec);
322 static void gst_decode_bin_get_property (GObject * object, guint prop_id,
323     GValue * value, GParamSpec * pspec);
324 static void gst_decode_bin_set_caps (GstDecodeBin * dbin, GstCaps * caps);
325 static GstCaps *gst_decode_bin_get_caps (GstDecodeBin * dbin);
326 static void caps_notify_cb (GstPad * pad, GParamSpec * unused,
327     GstDecodeChain * chain);
328
329 static void flush_chain (GstDecodeChain * chain, gboolean flushing);
330 static void flush_group (GstDecodeGroup * group, gboolean flushing);
331 static GstPad *find_sink_pad (GstElement * element);
332 static GstStateChangeReturn gst_decode_bin_change_state (GstElement * element,
333     GstStateChange transition);
334 static void gst_decode_bin_handle_message (GstBin * bin, GstMessage * message);
335 static gboolean gst_decode_bin_remove_element (GstBin * bin,
336     GstElement * element);
337
338 static gboolean check_upstream_seekable (GstDecodeBin * dbin, GstPad * pad);
339
340 static GstCaps *get_pad_caps (GstPad * pad);
341 static void unblock_pads (GstDecodeBin * dbin);
342
343 #define EXPOSE_LOCK(dbin) G_STMT_START {                                \
344     GST_LOG_OBJECT (dbin,                                               \
345                     "expose locking from thread %p",                    \
346                     g_thread_self ());                                  \
347     g_mutex_lock (&GST_DECODE_BIN_CAST(dbin)->expose_lock);             \
348     GST_LOG_OBJECT (dbin,                                               \
349                     "expose locked from thread %p",                     \
350                     g_thread_self ());                                  \
351 } G_STMT_END
352
353 #define EXPOSE_UNLOCK(dbin) G_STMT_START {                              \
354     GST_LOG_OBJECT (dbin,                                               \
355                     "expose unlocking from thread %p",                  \
356                     g_thread_self ());                                  \
357     g_mutex_unlock (&GST_DECODE_BIN_CAST(dbin)->expose_lock);           \
358 } G_STMT_END
359
360 #define DYN_LOCK(dbin) G_STMT_START {                   \
361     GST_LOG_OBJECT (dbin,                                               \
362                     "dynlocking from thread %p",                        \
363                     g_thread_self ());                                  \
364     g_mutex_lock (&GST_DECODE_BIN_CAST(dbin)->dyn_lock);                        \
365     GST_LOG_OBJECT (dbin,                                               \
366                     "dynlocked from thread %p",                         \
367                     g_thread_self ());                                  \
368 } G_STMT_END
369
370 #define DYN_UNLOCK(dbin) G_STMT_START {                 \
371     GST_LOG_OBJECT (dbin,                                               \
372                     "dynunlocking from thread %p",                      \
373                     g_thread_self ());                                  \
374     g_mutex_unlock (&GST_DECODE_BIN_CAST(dbin)->dyn_lock);              \
375 } G_STMT_END
376
377 #define SUBTITLE_LOCK(dbin) G_STMT_START {                              \
378     GST_LOG_OBJECT (dbin,                                               \
379                     "subtitle locking from thread %p",                  \
380                     g_thread_self ());                                  \
381     g_mutex_lock (&GST_DECODE_BIN_CAST(dbin)->subtitle_lock);           \
382     GST_LOG_OBJECT (dbin,                                               \
383                     "subtitle lock from thread %p",                     \
384                     g_thread_self ());                                  \
385 } G_STMT_END
386
387 #define SUBTITLE_UNLOCK(dbin) G_STMT_START {                            \
388     GST_LOG_OBJECT (dbin,                                               \
389                     "subtitle unlocking from thread %p",                \
390                     g_thread_self ());                                  \
391     g_mutex_unlock (&GST_DECODE_BIN_CAST(dbin)->subtitle_lock);         \
392 } G_STMT_END
393
394 #define BUFFERING_LOCK(dbin) G_STMT_START {                             \
395     GST_LOG_OBJECT (dbin,                                               \
396                     "buffering locking from thread %p",                 \
397                     g_thread_self ());                                  \
398     g_mutex_lock (&GST_DECODE_BIN_CAST(dbin)->buffering_lock);          \
399     GST_LOG_OBJECT (dbin,                                               \
400                     "buffering lock from thread %p",                    \
401                     g_thread_self ());                                  \
402 } G_STMT_END
403
404 #define BUFFERING_UNLOCK(dbin) G_STMT_START {                           \
405     GST_LOG_OBJECT (dbin,                                               \
406                     "buffering unlocking from thread %p",               \
407                     g_thread_self ());                                  \
408     g_mutex_unlock (&GST_DECODE_BIN_CAST(dbin)->buffering_lock);                \
409 } G_STMT_END
410
411 struct _GstPendingPad
412 {
413   GstPad *pad;
414   GstDecodeChain *chain;
415   gulong event_probe_id;
416   gulong notify_caps_id;
417 };
418
419 struct _GstDecodeElement
420 {
421   GstElement *element;
422   GstElement *capsfilter;       /* Optional capsfilter for Parser/Convert */
423   gulong pad_added_id;
424   gulong pad_removed_id;
425   gulong no_more_pads_id;
426 };
427
428 struct _GstDemuxerPad
429 {
430   GWeakRef weakPad;
431   gulong event_probe_id;
432   gulong query_probe_id;
433 };
434
435
436 /* GstDecodeGroup
437  *
438  * Streams belonging to the same group/chain of a media file
439  *
440  * When changing something here lock the parent chain!
441  */
442 struct _GstDecodeGroup
443 {
444   GstDecodeBin *dbin;
445   GstDecodeChain *parent;
446
447   GstElement *multiqueue;       /* Used for linking all child chains */
448   gulong overrunsig;            /* the overrun signal for multiqueue */
449
450   gboolean overrun;             /* TRUE if the multiqueue signaled overrun. This
451                                  * means that we should really expose the group */
452
453   gboolean no_more_pads;        /* TRUE if the demuxer signaled no-more-pads */
454   gboolean drained;             /* TRUE if the all children are drained */
455
456   GList *children;              /* List of GstDecodeChains in this group */
457   GList *demuxer_pad_probe_ids;
458
459   GList *reqpads;               /* List of RequestPads for multiqueue, there is
460                                  * exactly one RequestPad per child chain */
461 };
462
463 struct _GstDecodeChain
464 {
465   GstDecodeGroup *parent;
466   GstDecodeBin *dbin;
467
468   gint refs;                    /* Number of references to this object */
469
470   GMutex lock;                  /* Protects this chain and its groups */
471
472   GstPad *pad;                  /* srcpad that caused creation of this chain */
473   gulong pad_probe_id;          /* id for the demuxer_source_pad_probe probe */
474
475   gboolean drained;             /* TRUE if the all children are drained */
476   gboolean demuxer;             /* TRUE if elements->data is a demuxer */
477   gboolean adaptive_demuxer;    /* TRUE if elements->data is an adaptive streaming demuxer */
478   gboolean seekable;            /* TRUE if this chain ends on a demuxer and is seekable */
479   GList *elements;              /* All elements in this group, first
480                                    is the latest and most downstream element */
481
482   /* Note: there are only groups if the last element of this chain
483    * is a demuxer, otherwise the chain will end with an endpad.
484    * The other way around this means, that endpad only exists if this
485    * chain doesn't end with a demuxer! */
486
487   GstDecodeGroup *active_group; /* Currently active group */
488   GList *next_groups;           /* head is newest group, tail is next group.
489                                    a new group will be created only if the head
490                                    group had no-more-pads. If it's only exposed
491                                    all new pads will be ignored! */
492   GList *pending_pads;          /* Pads that have no fixed caps yet */
493
494   GstDecodePad *current_pad;    /* Current ending pad of the chain that can't
495                                  * be exposed yet but would be the same as endpad
496                                  * once it can be exposed */
497   GstDecodePad *endpad;         /* Pad of this chain that could be exposed */
498   gboolean deadend;             /* This chain is incomplete and can't be completed,
499                                    e.g. no suitable decoder could be found
500                                    e.g. stream got EOS without buffers
501                                  */
502   gchar *deadend_details;
503   GstCaps *endcaps;             /* Caps that were used when linking to the endpad
504                                    or that resulted in the deadend
505                                  */
506
507   /* FIXME: This should be done directly via a thread! */
508   GList *old_groups;            /* Groups that should be freed later */
509 };
510
511 static GstDecodeChain *gst_decode_chain_ref (GstDecodeChain * chain);
512 static void gst_decode_chain_unref (GstDecodeChain * chain);
513 static void gst_decode_chain_free (GstDecodeChain * chain);
514 static GstDecodeChain *gst_decode_chain_new (GstDecodeBin * dbin,
515     GstDecodeGroup * group, GstPad * pad);
516 static void gst_decode_group_hide (GstDecodeGroup * group);
517 static void gst_decode_group_free (GstDecodeGroup * group);
518 static GstDecodeGroup *gst_decode_group_new (GstDecodeBin * dbin,
519     GstDecodeChain * chain);
520 static gboolean gst_decode_chain_is_complete (GstDecodeChain * chain);
521 static gboolean gst_decode_chain_expose (GstDecodeChain * chain,
522     GList ** endpads, gboolean * missing_plugin,
523     GString * missing_plugin_details, gboolean * last_group);
524 static gboolean gst_decode_chain_is_drained (GstDecodeChain * chain);
525 static gboolean gst_decode_chain_reset_buffering (GstDecodeChain * chain);
526 static gboolean gst_decode_group_is_complete (GstDecodeGroup * group);
527 static GstPad *gst_decode_group_control_demuxer_pad (GstDecodeGroup * group,
528     GstPad * pad);
529 static gboolean gst_decode_group_is_drained (GstDecodeGroup * group);
530 static gboolean gst_decode_group_reset_buffering (GstDecodeGroup * group);
531
532 static gboolean gst_decode_bin_expose (GstDecodeBin * dbin);
533 static void gst_decode_bin_reset_buffering (GstDecodeBin * dbin);
534
535 #define CHAIN_MUTEX_LOCK(chain) G_STMT_START {                          \
536     GST_LOG_OBJECT (chain->dbin,                                        \
537                     "locking chain %p from thread %p",                  \
538                     chain, g_thread_self ());                           \
539     g_mutex_lock (&chain->lock);                                                \
540     GST_LOG_OBJECT (chain->dbin,                                        \
541                     "locked chain %p from thread %p",                   \
542                     chain, g_thread_self ());                           \
543 } G_STMT_END
544
545 #define CHAIN_MUTEX_UNLOCK(chain) G_STMT_START {                        \
546     GST_LOG_OBJECT (chain->dbin,                                        \
547                     "unlocking chain %p from thread %p",                \
548                     chain, g_thread_self ());                           \
549     g_mutex_unlock (&chain->lock);                                      \
550 } G_STMT_END
551
552 /* GstDecodePad
553  *
554  * GstPad private used for source pads of chains
555  */
556 struct _GstDecodePad
557 {
558   GstGhostPad parent;
559   GstDecodeBin *dbin;
560   GstDecodeChain *chain;
561
562   gboolean blocked;             /* the *target* pad is blocked */
563   gboolean exposed;             /* the pad is exposed */
564   gboolean drained;             /* an EOS has been seen on the pad */
565
566   gulong block_id;
567 };
568
569 GType gst_decode_pad_get_type (void);
570 G_DEFINE_TYPE (GstDecodePad, gst_decode_pad, GST_TYPE_GHOST_PAD);
571 #define GST_TYPE_DECODE_PAD (gst_decode_pad_get_type ())
572 #define GST_DECODE_PAD(obj) (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_DECODE_PAD,GstDecodePad))
573
574 static GstDecodePad *gst_decode_pad_new (GstDecodeBin * dbin,
575     GstDecodeChain * chain);
576 static void gst_decode_pad_activate (GstDecodePad * dpad,
577     GstDecodeChain * chain);
578 static void gst_decode_pad_unblock (GstDecodePad * dpad);
579 static void gst_decode_pad_set_blocked (GstDecodePad * dpad, gboolean blocked);
580 static gboolean gst_decode_pad_query (GstPad * pad, GstObject * parent,
581     GstQuery * query);
582 static gboolean gst_decode_pad_is_exposable (GstDecodePad * endpad);
583
584 static void gst_pending_pad_free (GstPendingPad * ppad);
585 static GstPadProbeReturn pad_event_cb (GstPad * pad, GstPadProbeInfo * info,
586     gpointer data);
587
588 /********************************
589  * Standard GObject boilerplate *
590  ********************************/
591
592 static void gst_decode_bin_class_init (GstDecodeBinClass * klass);
593 static void gst_decode_bin_init (GstDecodeBin * decode_bin);
594 static void gst_decode_bin_dispose (GObject * object);
595 static void gst_decode_bin_finalize (GObject * object);
596
597 static GType
598 gst_decode_bin_get_type (void)
599 {
600   static GType gst_decode_bin_type = 0;
601
602   if (!gst_decode_bin_type) {
603     static const GTypeInfo gst_decode_bin_info = {
604       sizeof (GstDecodeBinClass),
605       NULL,
606       NULL,
607       (GClassInitFunc) gst_decode_bin_class_init,
608       NULL,
609       NULL,
610       sizeof (GstDecodeBin),
611       0,
612       (GInstanceInitFunc) gst_decode_bin_init,
613       NULL
614     };
615
616     gst_decode_bin_type =
617         g_type_register_static (GST_TYPE_BIN, "GstDecodeBin",
618         &gst_decode_bin_info, 0);
619   }
620
621   return gst_decode_bin_type;
622 }
623
624 static gboolean
625 _gst_boolean_accumulator (GSignalInvocationHint * ihint,
626     GValue * return_accu, const GValue * handler_return, gpointer dummy)
627 {
628   gboolean myboolean;
629
630   myboolean = g_value_get_boolean (handler_return);
631   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
632     g_value_set_boolean (return_accu, myboolean);
633
634   /* stop emission if FALSE */
635   return myboolean;
636 }
637
638 static gboolean
639 _gst_boolean_or_accumulator (GSignalInvocationHint * ihint,
640     GValue * return_accu, const GValue * handler_return, gpointer dummy)
641 {
642   gboolean myboolean;
643   gboolean retboolean;
644
645   myboolean = g_value_get_boolean (handler_return);
646   retboolean = g_value_get_boolean (return_accu);
647
648   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
649     g_value_set_boolean (return_accu, myboolean || retboolean);
650
651   return TRUE;
652 }
653
654 /* we collect the first result */
655 static gboolean
656 _gst_array_accumulator (GSignalInvocationHint * ihint,
657     GValue * return_accu, const GValue * handler_return, gpointer dummy)
658 {
659   gpointer array;
660
661   array = g_value_get_boxed (handler_return);
662   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
663     g_value_set_boxed (return_accu, array);
664
665   return FALSE;
666 }
667
668 static gboolean
669 _gst_select_accumulator (GSignalInvocationHint * ihint,
670     GValue * return_accu, const GValue * handler_return, gpointer dummy)
671 {
672   GstAutoplugSelectResult res;
673
674   res = g_value_get_enum (handler_return);
675   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
676     g_value_set_enum (return_accu, res);
677
678   /* Call the next handler in the chain (if any) when the current callback
679    * returns TRY. This makes it possible to register separate autoplug-select
680    * handlers that implement different TRY/EXPOSE/SKIP strategies.
681    */
682   if (res == GST_AUTOPLUG_SELECT_TRY)
683     return TRUE;
684
685   return FALSE;
686 }
687
688 static gboolean
689 _gst_array_hasvalue_accumulator (GSignalInvocationHint * ihint,
690     GValue * return_accu, const GValue * handler_return, gpointer dummy)
691 {
692   gpointer array;
693
694   array = g_value_get_boxed (handler_return);
695   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
696     g_value_set_boxed (return_accu, array);
697
698   if (array != NULL)
699     return FALSE;
700
701   return TRUE;
702 }
703
704 static void
705 gst_decode_bin_class_init (GstDecodeBinClass * klass)
706 {
707   GObjectClass *gobject_klass;
708   GstElementClass *gstelement_klass;
709   GstBinClass *gstbin_klass;
710
711   gobject_klass = (GObjectClass *) klass;
712   gstelement_klass = (GstElementClass *) klass;
713   gstbin_klass = (GstBinClass *) klass;
714
715   parent_class = g_type_class_peek_parent (klass);
716
717   gobject_klass->dispose = gst_decode_bin_dispose;
718   gobject_klass->finalize = gst_decode_bin_finalize;
719   gobject_klass->set_property = gst_decode_bin_set_property;
720   gobject_klass->get_property = gst_decode_bin_get_property;
721
722   /**
723    * GstDecodeBin::unknown-type:
724    * @bin: The decodebin.
725    * @pad: The new pad containing caps that cannot be resolved to a 'final'
726    *       stream type.
727    * @caps: The #GstCaps of the pad that cannot be resolved.
728    *
729    * This signal is emitted when a pad for which there is no further possible
730    * decoding is added to the decodebin.
731    */
732   gst_decode_bin_signals[SIGNAL_UNKNOWN_TYPE] =
733       g_signal_new ("unknown-type", G_TYPE_FROM_CLASS (klass),
734       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, unknown_type),
735       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
736       GST_TYPE_PAD, GST_TYPE_CAPS);
737
738   /**
739    * GstDecodeBin::autoplug-continue:
740    * @bin: The decodebin.
741    * @pad: The #GstPad.
742    * @caps: The #GstCaps found.
743    *
744    * This signal is emitted whenever decodebin finds a new stream. It is
745    * emitted before looking for any elements that can handle that stream.
746    *
747    * >   Invocation of signal handlers stops after the first signal handler
748    * >   returns %FALSE. Signal handlers are invoked in the order they were
749    * >   connected in.
750    *
751    * Returns: %TRUE if you wish decodebin to look for elements that can
752    * handle the given @caps. If %FALSE, those caps will be considered as
753    * final and the pad will be exposed as such (see 'pad-added' signal of
754    * #GstElement).
755    */
756   gst_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE] =
757       g_signal_new ("autoplug-continue", G_TYPE_FROM_CLASS (klass),
758       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_continue),
759       _gst_boolean_accumulator, NULL, g_cclosure_marshal_generic,
760       G_TYPE_BOOLEAN, 2, GST_TYPE_PAD, GST_TYPE_CAPS);
761
762   /**
763    * GstDecodeBin::autoplug-factories:
764    * @bin: The decodebin.
765    * @pad: The #GstPad.
766    * @caps: The #GstCaps found.
767    *
768    * This signal is emitted when an array of possible factories for @caps on
769    * @pad is needed. Decodebin will by default return an array with all
770    * compatible factories, sorted by rank.
771    *
772    * If this function returns NULL, @pad will be exposed as a final caps.
773    *
774    * If this function returns an empty array, the pad will be considered as
775    * having an unhandled type media type.
776    *
777    * >   Only the signal handler that is connected first will ever by invoked.
778    * >   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
779    * >   signal, they will never be invoked!
780    *
781    * Returns: a #GValueArray* with a list of factories to try. The factories are
782    * by default tried in the returned order or based on the index returned by
783    * "autoplug-select".
784    */
785   gst_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES] =
786       g_signal_new ("autoplug-factories", G_TYPE_FROM_CLASS (klass),
787       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass,
788           autoplug_factories), _gst_array_accumulator, NULL,
789       g_cclosure_marshal_generic, G_TYPE_VALUE_ARRAY, 2,
790       GST_TYPE_PAD, GST_TYPE_CAPS);
791
792   /**
793    * GstDecodeBin::autoplug-sort:
794    * @bin: The decodebin.
795    * @pad: The #GstPad.
796    * @caps: The #GstCaps.
797    * @factories: A #GValueArray of possible #GstElementFactory to use.
798    *
799    * Once decodebin has found the possible #GstElementFactory objects to try
800    * for @caps on @pad, this signal is emitted. The purpose of the signal is for
801    * the application to perform additional sorting or filtering on the element
802    * factory array.
803    *
804    * The callee should copy and modify @factories or return %NULL if the
805    * order should not change.
806    *
807    * >   Invocation of signal handlers stops after one signal handler has
808    * >   returned something else than %NULL. Signal handlers are invoked in
809    * >   the order they were connected in.
810    * >   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
811    * >   signal, they will never be invoked!
812    *
813    * Returns: A new sorted array of #GstElementFactory objects.
814    */
815   gst_decode_bin_signals[SIGNAL_AUTOPLUG_SORT] =
816       g_signal_new ("autoplug-sort", G_TYPE_FROM_CLASS (klass),
817       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_sort),
818       _gst_array_hasvalue_accumulator, NULL,
819       g_cclosure_marshal_generic, G_TYPE_VALUE_ARRAY, 3, GST_TYPE_PAD,
820       GST_TYPE_CAPS, G_TYPE_VALUE_ARRAY | G_SIGNAL_TYPE_STATIC_SCOPE);
821
822   /**
823    * GstDecodeBin::autoplug-select:
824    * @bin: The decodebin.
825    * @pad: The #GstPad.
826    * @caps: The #GstCaps.
827    * @factory: A #GstElementFactory to use.
828    *
829    * This signal is emitted once decodebin has found all the possible
830    * #GstElementFactory that can be used to handle the given @caps. For each of
831    * those factories, this signal is emitted.
832    *
833    * The signal handler should return a #GST_TYPE_AUTOPLUG_SELECT_RESULT enum
834    * value indicating what decodebin should do next.
835    *
836    * A value of #GST_AUTOPLUG_SELECT_TRY will try to autoplug an element from
837    * @factory.
838    *
839    * A value of #GST_AUTOPLUG_SELECT_EXPOSE will expose @pad without plugging
840    * any element to it.
841    *
842    * A value of #GST_AUTOPLUG_SELECT_SKIP will skip @factory and move to the
843    * next factory.
844    *
845    * >   The signal handler will not be invoked if any of the previously
846    * >   registered signal handlers (if any) return a value other than
847    * >   GST_AUTOPLUG_SELECT_TRY. Which also means that if you return
848    * >   GST_AUTOPLUG_SELECT_TRY from one signal handler, handlers that get
849    * >   registered next (again, if any) can override that decision.
850    *
851    * Returns: a #GST_TYPE_AUTOPLUG_SELECT_RESULT that indicates the required
852    * operation. the default handler will always return
853    * #GST_AUTOPLUG_SELECT_TRY.
854    */
855   gst_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT] =
856       g_signal_new ("autoplug-select", G_TYPE_FROM_CLASS (klass),
857       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_select),
858       _gst_select_accumulator, NULL,
859       g_cclosure_marshal_generic,
860       GST_TYPE_AUTOPLUG_SELECT_RESULT, 3, GST_TYPE_PAD, GST_TYPE_CAPS,
861       GST_TYPE_ELEMENT_FACTORY);
862
863   /**
864    * GstDecodeBin::autoplug-query:
865    * @bin: The decodebin.
866    * @pad: The #GstPad.
867    * @child: The child element doing the query
868    * @query: The #GstQuery.
869    *
870    * This signal is emitted whenever an autoplugged element that is
871    * not linked downstream yet and not exposed does a query. It can
872    * be used to tell the element about the downstream supported caps
873    * for example.
874    *
875    * Returns: %TRUE if the query was handled, %FALSE otherwise.
876    */
877   gst_decode_bin_signals[SIGNAL_AUTOPLUG_QUERY] =
878       g_signal_new ("autoplug-query", G_TYPE_FROM_CLASS (klass),
879       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, autoplug_query),
880       _gst_boolean_or_accumulator, NULL, g_cclosure_marshal_generic,
881       G_TYPE_BOOLEAN, 3, GST_TYPE_PAD, GST_TYPE_ELEMENT,
882       GST_TYPE_QUERY | G_SIGNAL_TYPE_STATIC_SCOPE);
883
884   /**
885    * GstDecodeBin::drained
886    * @bin: The decodebin
887    *
888    * This signal is emitted once decodebin has finished decoding all the data.
889    */
890   gst_decode_bin_signals[SIGNAL_DRAINED] =
891       g_signal_new ("drained", G_TYPE_FROM_CLASS (klass),
892       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstDecodeBinClass, drained),
893       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 0, G_TYPE_NONE);
894
895   g_object_class_install_property (gobject_klass, PROP_CAPS,
896       g_param_spec_boxed ("caps", "Caps", "The caps on which to stop decoding.",
897           GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
898
899   g_object_class_install_property (gobject_klass, PROP_SUBTITLE_ENCODING,
900       g_param_spec_string ("subtitle-encoding", "subtitle encoding",
901           "Encoding to assume if input subtitles are not in UTF-8 encoding. "
902           "If not set, the GST_SUBTITLE_ENCODING environment variable will "
903           "be checked for an encoding to use. If that is not set either, "
904           "ISO-8859-15 will be assumed.", NULL,
905           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
906
907   g_object_class_install_property (gobject_klass, PROP_SINK_CAPS,
908       g_param_spec_boxed ("sink-caps", "Sink Caps",
909           "The caps of the input data. (NULL = use typefind element)",
910           GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
911
912   /**
913    * GstDecodeBin::use-buffering
914    *
915    * Activate buffering in decodebin. This will instruct the multiqueues behind
916    * decoders to emit BUFFERING messages.
917    */
918   g_object_class_install_property (gobject_klass, PROP_USE_BUFFERING,
919       g_param_spec_boolean ("use-buffering", "Use Buffering",
920           "Emit GST_MESSAGE_BUFFERING based on low-/high-percent thresholds",
921           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
922
923   /**
924    * GstDecodeBin:low-percent
925    *
926    * Low threshold percent for buffering to start.
927    */
928   g_object_class_install_property (gobject_klass, PROP_LOW_PERCENT,
929       g_param_spec_int ("low-percent", "Low percent",
930           "Low threshold for buffering to start", 0, 100,
931           DEFAULT_LOW_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
932   /**
933    * GstDecodeBin:high-percent
934    *
935    * High threshold percent for buffering to finish.
936    */
937   g_object_class_install_property (gobject_klass, PROP_HIGH_PERCENT,
938       g_param_spec_int ("high-percent", "High percent",
939           "High threshold for buffering to finish", 0, 100,
940           DEFAULT_HIGH_PERCENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
941
942   /**
943    * GstDecodeBin:max-size-bytes
944    *
945    * Max amount of bytes in the queue (0=automatic).
946    */
947   g_object_class_install_property (gobject_klass, PROP_MAX_SIZE_BYTES,
948       g_param_spec_uint ("max-size-bytes", "Max. size (bytes)",
949           "Max. amount of bytes in the queue (0=automatic)",
950           0, G_MAXUINT, DEFAULT_MAX_SIZE_BYTES,
951           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
952   /**
953    * GstDecodeBin:max-size-buffers
954    *
955    * Max amount of buffers in the queue (0=automatic).
956    */
957   g_object_class_install_property (gobject_klass, PROP_MAX_SIZE_BUFFERS,
958       g_param_spec_uint ("max-size-buffers", "Max. size (buffers)",
959           "Max. number of buffers in the queue (0=automatic)",
960           0, G_MAXUINT, DEFAULT_MAX_SIZE_BUFFERS,
961           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
962   /**
963    * GstDecodeBin:max-size-time
964    *
965    * Max amount of time in the queue (in ns, 0=automatic).
966    */
967   g_object_class_install_property (gobject_klass, PROP_MAX_SIZE_TIME,
968       g_param_spec_uint64 ("max-size-time", "Max. size (ns)",
969           "Max. amount of data in the queue (in ns, 0=automatic)",
970           0, G_MAXUINT64,
971           DEFAULT_MAX_SIZE_TIME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
972
973   /**
974    * GstDecodeBin::post-stream-topology
975    *
976    * Post stream-topology messages on the bus every time the topology changes.
977    */
978   g_object_class_install_property (gobject_klass, PROP_POST_STREAM_TOPOLOGY,
979       g_param_spec_boolean ("post-stream-topology", "Post Stream Topology",
980           "Post stream-topology messages",
981           DEFAULT_POST_STREAM_TOPOLOGY,
982           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
983
984   /**
985    * GstDecodeBin::expose-all-streams
986    *
987    * Expose streams of unknown type.
988    *
989    * If set to %FALSE, then only the streams that can be decoded to the final
990    * caps (see 'caps' property) will have a pad exposed. Streams that do not
991    * match those caps but could have been decoded will not have decoder plugged
992    * in internally and will not have a pad exposed.
993    */
994   g_object_class_install_property (gobject_klass, PROP_EXPOSE_ALL_STREAMS,
995       g_param_spec_boolean ("expose-all-streams", "Expose All Streams",
996           "Expose all streams, including those of unknown type or that don't match the 'caps' property",
997           DEFAULT_EXPOSE_ALL_STREAMS,
998           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
999
1000 #ifdef TIZEN_FEATURE_TRUSTZONE
1001   /*tzmultiqueue patch : use-trustzone property*/
1002   g_object_class_install_property (gobject_klass, PROP_USE_TRUSTZONE,
1003       g_param_spec_boolean ("use-trustzone", "Add trustzone flag to decodebin2",
1004           "Add trustzone flag to decodebin2 to add tzmultiqueue element",
1005           0,
1006           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1007 #endif
1008   /**
1009    * GstDecodeBin2::connection-speed
1010    *
1011    * Network connection speed in kbps (0 = unknownw)
1012    */
1013   g_object_class_install_property (gobject_klass, PROP_CONNECTION_SPEED,
1014       g_param_spec_uint64 ("connection-speed", "Connection Speed",
1015           "Network connection speed in kbps (0 = unknown)",
1016           0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
1017           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
1018
1019
1020
1021   klass->autoplug_continue =
1022       GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_continue);
1023   klass->autoplug_factories =
1024       GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_factories);
1025   klass->autoplug_sort = GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_sort);
1026   klass->autoplug_select = GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_select);
1027   klass->autoplug_query = GST_DEBUG_FUNCPTR (gst_decode_bin_autoplug_query);
1028
1029   gst_element_class_add_static_pad_template (gstelement_klass,
1030       &decoder_bin_sink_template);
1031   gst_element_class_add_static_pad_template (gstelement_klass,
1032       &decoder_bin_src_template);
1033
1034   gst_element_class_set_static_metadata (gstelement_klass,
1035       "Decoder Bin", "Generic/Bin/Decoder",
1036       "Autoplug and decode to raw media",
1037       "Edward Hervey <edward.hervey@collabora.co.uk>, "
1038       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
1039
1040   gstelement_klass->change_state =
1041       GST_DEBUG_FUNCPTR (gst_decode_bin_change_state);
1042
1043   gstbin_klass->handle_message =
1044       GST_DEBUG_FUNCPTR (gst_decode_bin_handle_message);
1045
1046   gstbin_klass->remove_element =
1047       GST_DEBUG_FUNCPTR (gst_decode_bin_remove_element);
1048
1049   g_type_class_ref (GST_TYPE_DECODE_PAD);
1050 }
1051
1052 /* Must be called with factories lock! */
1053 static void
1054 gst_decode_bin_update_factories_list (GstDecodeBin * dbin)
1055 {
1056   guint cookie;
1057
1058   cookie = gst_registry_get_feature_list_cookie (gst_registry_get ());
1059   if (!dbin->factories || dbin->factories_cookie != cookie) {
1060     if (dbin->factories)
1061       gst_plugin_feature_list_free (dbin->factories);
1062     dbin->factories =
1063         gst_element_factory_list_get_elements
1064         (GST_ELEMENT_FACTORY_TYPE_DECODABLE, GST_RANK_MARGINAL);
1065     dbin->factories =
1066         g_list_sort (dbin->factories,
1067         gst_playback_utils_compare_factories_func);
1068     dbin->factories_cookie = cookie;
1069   }
1070 }
1071
1072 static void
1073 gst_decode_bin_init (GstDecodeBin * decode_bin)
1074 {
1075   /* first filter out the interesting element factories */
1076   g_mutex_init (&decode_bin->factories_lock);
1077
1078   /* we create the typefind element only once */
1079   decode_bin->typefind = gst_element_factory_make ("typefind", "typefind");
1080   if (!decode_bin->typefind) {
1081     g_warning ("can't find typefind element, decodebin will not work");
1082   } else {
1083     GstPad *pad;
1084     GstPad *gpad;
1085     GstPadTemplate *pad_tmpl;
1086
1087     /* add the typefind element */
1088     if (!gst_bin_add (GST_BIN (decode_bin), decode_bin->typefind)) {
1089       g_warning ("Could not add typefind element, decodebin will not work");
1090       gst_object_unref (decode_bin->typefind);
1091       decode_bin->typefind = NULL;
1092     }
1093
1094     /* get the sinkpad */
1095     pad = gst_element_get_static_pad (decode_bin->typefind, "sink");
1096
1097     /* get the pad template */
1098     pad_tmpl = gst_static_pad_template_get (&decoder_bin_sink_template);
1099
1100     /* ghost the sink pad to ourself */
1101     gpad = gst_ghost_pad_new_from_template ("sink", pad, pad_tmpl);
1102     gst_pad_set_active (gpad, TRUE);
1103     gst_element_add_pad (GST_ELEMENT (decode_bin), gpad);
1104
1105     gst_object_unref (pad_tmpl);
1106     gst_object_unref (pad);
1107   }
1108
1109   g_mutex_init (&decode_bin->expose_lock);
1110   decode_bin->decode_chain = NULL;
1111
1112   g_mutex_init (&decode_bin->dyn_lock);
1113   decode_bin->shutdown = FALSE;
1114   decode_bin->blocked_pads = NULL;
1115
1116   g_mutex_init (&decode_bin->subtitle_lock);
1117   g_mutex_init (&decode_bin->buffering_lock);
1118   g_mutex_init (&decode_bin->buffering_post_lock);
1119
1120   g_mutex_init (&decode_bin->cleanup_lock);
1121   decode_bin->cleanup_thread = NULL;
1122
1123   decode_bin->encoding = g_strdup (DEFAULT_SUBTITLE_ENCODING);
1124   decode_bin->caps = gst_static_caps_get (&default_raw_caps);
1125   decode_bin->use_buffering = DEFAULT_USE_BUFFERING;
1126   decode_bin->low_percent = DEFAULT_LOW_PERCENT;
1127   decode_bin->high_percent = DEFAULT_HIGH_PERCENT;
1128
1129   decode_bin->max_size_bytes = DEFAULT_MAX_SIZE_BYTES;
1130   decode_bin->max_size_buffers = DEFAULT_MAX_SIZE_BUFFERS;
1131   decode_bin->max_size_time = DEFAULT_MAX_SIZE_TIME;
1132
1133   decode_bin->expose_allstreams = DEFAULT_EXPOSE_ALL_STREAMS;
1134   decode_bin->connection_speed = DEFAULT_CONNECTION_SPEED;
1135 }
1136
1137 static void
1138 gst_decode_bin_dispose (GObject * object)
1139 {
1140   GstDecodeBin *decode_bin;
1141
1142   decode_bin = GST_DECODE_BIN (object);
1143
1144   if (decode_bin->factories)
1145     gst_plugin_feature_list_free (decode_bin->factories);
1146   decode_bin->factories = NULL;
1147
1148   if (decode_bin->decode_chain)
1149     gst_decode_chain_free (decode_bin->decode_chain);
1150   decode_bin->decode_chain = NULL;
1151
1152   if (decode_bin->caps)
1153     gst_caps_unref (decode_bin->caps);
1154   decode_bin->caps = NULL;
1155
1156   g_free (decode_bin->encoding);
1157   decode_bin->encoding = NULL;
1158
1159   g_list_free (decode_bin->subtitles);
1160   decode_bin->subtitles = NULL;
1161
1162   unblock_pads (decode_bin);
1163
1164   G_OBJECT_CLASS (parent_class)->dispose (object);
1165 }
1166
1167 static void
1168 gst_decode_bin_finalize (GObject * object)
1169 {
1170   GstDecodeBin *decode_bin;
1171
1172   decode_bin = GST_DECODE_BIN (object);
1173
1174   g_mutex_clear (&decode_bin->expose_lock);
1175   g_mutex_clear (&decode_bin->dyn_lock);
1176   g_mutex_clear (&decode_bin->subtitle_lock);
1177   g_mutex_clear (&decode_bin->buffering_lock);
1178   g_mutex_clear (&decode_bin->buffering_post_lock);
1179   g_mutex_clear (&decode_bin->factories_lock);
1180   g_mutex_clear (&decode_bin->cleanup_lock);
1181
1182   G_OBJECT_CLASS (parent_class)->finalize (object);
1183 }
1184
1185 /* _set_caps
1186  * Changes the caps on which decodebin will stop decoding.
1187  * Will unref the previously set one. The refcount of the given caps will be
1188  * increased.
1189  * @caps can be NULL.
1190  *
1191  * MT-safe
1192  */
1193 static void
1194 gst_decode_bin_set_caps (GstDecodeBin * dbin, GstCaps * caps)
1195 {
1196   GST_DEBUG_OBJECT (dbin, "Setting new caps: %" GST_PTR_FORMAT, caps);
1197
1198   GST_OBJECT_LOCK (dbin);
1199   gst_caps_replace (&dbin->caps, caps);
1200   GST_OBJECT_UNLOCK (dbin);
1201 }
1202
1203 /* _get_caps
1204  * Returns the currently configured caps on which decodebin will stop decoding.
1205  * The returned caps (if not NULL), will have its refcount incremented.
1206  *
1207  * MT-safe
1208  */
1209 static GstCaps *
1210 gst_decode_bin_get_caps (GstDecodeBin * dbin)
1211 {
1212   GstCaps *caps;
1213
1214   GST_DEBUG_OBJECT (dbin, "Getting currently set caps");
1215
1216   GST_OBJECT_LOCK (dbin);
1217   caps = dbin->caps;
1218   if (caps)
1219     gst_caps_ref (caps);
1220   GST_OBJECT_UNLOCK (dbin);
1221
1222   return caps;
1223 }
1224
1225 static void
1226 gst_decode_bin_set_sink_caps (GstDecodeBin * dbin, GstCaps * caps)
1227 {
1228   GST_DEBUG_OBJECT (dbin, "Setting new caps: %" GST_PTR_FORMAT, caps);
1229
1230   g_object_set (dbin->typefind, "force-caps", caps, NULL);
1231 }
1232
1233 static GstCaps *
1234 gst_decode_bin_get_sink_caps (GstDecodeBin * dbin)
1235 {
1236   GstCaps *caps;
1237
1238   GST_DEBUG_OBJECT (dbin, "Getting currently set caps");
1239
1240   g_object_get (dbin->typefind, "force-caps", &caps, NULL);
1241
1242   return caps;
1243 }
1244
1245 static void
1246 gst_decode_bin_set_subs_encoding (GstDecodeBin * dbin, const gchar * encoding)
1247 {
1248   GList *walk;
1249
1250   GST_DEBUG_OBJECT (dbin, "Setting new encoding: %s", GST_STR_NULL (encoding));
1251
1252   SUBTITLE_LOCK (dbin);
1253   g_free (dbin->encoding);
1254   dbin->encoding = g_strdup (encoding);
1255
1256   /* set the subtitle encoding on all added elements */
1257   for (walk = dbin->subtitles; walk; walk = g_list_next (walk)) {
1258     g_object_set (G_OBJECT (walk->data), "subtitle-encoding", dbin->encoding,
1259         NULL);
1260   }
1261   SUBTITLE_UNLOCK (dbin);
1262 }
1263
1264 static gchar *
1265 gst_decode_bin_get_subs_encoding (GstDecodeBin * dbin)
1266 {
1267   gchar *encoding;
1268
1269   GST_DEBUG_OBJECT (dbin, "Getting currently set encoding");
1270
1271   SUBTITLE_LOCK (dbin);
1272   encoding = g_strdup (dbin->encoding);
1273   SUBTITLE_UNLOCK (dbin);
1274
1275   return encoding;
1276 }
1277
1278 static void
1279 gst_decode_bin_set_property (GObject * object, guint prop_id,
1280     const GValue * value, GParamSpec * pspec)
1281 {
1282   GstDecodeBin *dbin;
1283
1284   dbin = GST_DECODE_BIN (object);
1285
1286   switch (prop_id) {
1287     case PROP_CAPS:
1288       gst_decode_bin_set_caps (dbin, g_value_get_boxed (value));
1289       break;
1290     case PROP_SUBTITLE_ENCODING:
1291       gst_decode_bin_set_subs_encoding (dbin, g_value_get_string (value));
1292       break;
1293     case PROP_SINK_CAPS:
1294       gst_decode_bin_set_sink_caps (dbin, g_value_get_boxed (value));
1295       break;
1296     case PROP_USE_BUFFERING:
1297       dbin->use_buffering = g_value_get_boolean (value);
1298       break;
1299     case PROP_LOW_PERCENT:
1300       dbin->low_percent = g_value_get_int (value);
1301       break;
1302     case PROP_HIGH_PERCENT:
1303       dbin->high_percent = g_value_get_int (value);
1304       break;
1305     case PROP_MAX_SIZE_BYTES:
1306       dbin->max_size_bytes = g_value_get_uint (value);
1307       break;
1308     case PROP_MAX_SIZE_BUFFERS:
1309       dbin->max_size_buffers = g_value_get_uint (value);
1310       break;
1311     case PROP_MAX_SIZE_TIME:
1312       dbin->max_size_time = g_value_get_uint64 (value);
1313       break;
1314     case PROP_POST_STREAM_TOPOLOGY:
1315       dbin->post_stream_topology = g_value_get_boolean (value);
1316       break;
1317     case PROP_EXPOSE_ALL_STREAMS:
1318       dbin->expose_allstreams = g_value_get_boolean (value);
1319       break;
1320 #ifdef TIZEN_FEATURE_TRUSTZONE
1321     /*tzmultiqueue patch : use-trustzone property*/
1322     case PROP_USE_TRUSTZONE:
1323       GST_DEBUG_OBJECT (dbin, "set dbin->use_trustzone to %d", g_value_get_boolean(value));
1324       dbin->use_trustzone = g_value_get_boolean (value);
1325       break;
1326 #endif
1327     case PROP_CONNECTION_SPEED:
1328       GST_OBJECT_LOCK (dbin);
1329       dbin->connection_speed = g_value_get_uint64 (value) * 1000;
1330       GST_OBJECT_UNLOCK (dbin);
1331       break;
1332     default:
1333       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1334       break;
1335   }
1336 }
1337
1338 static void
1339 gst_decode_bin_get_property (GObject * object, guint prop_id,
1340     GValue * value, GParamSpec * pspec)
1341 {
1342   GstDecodeBin *dbin;
1343
1344   dbin = GST_DECODE_BIN (object);
1345   switch (prop_id) {
1346     case PROP_CAPS:
1347       g_value_take_boxed (value, gst_decode_bin_get_caps (dbin));
1348       break;
1349     case PROP_SUBTITLE_ENCODING:
1350       g_value_take_string (value, gst_decode_bin_get_subs_encoding (dbin));
1351       break;
1352     case PROP_SINK_CAPS:
1353       g_value_take_boxed (value, gst_decode_bin_get_sink_caps (dbin));
1354       break;
1355     case PROP_USE_BUFFERING:
1356       g_value_set_boolean (value, dbin->use_buffering);
1357       break;
1358     case PROP_LOW_PERCENT:
1359       g_value_set_int (value, dbin->low_percent);
1360       break;
1361     case PROP_HIGH_PERCENT:
1362       g_value_set_int (value, dbin->high_percent);
1363       break;
1364     case PROP_MAX_SIZE_BYTES:
1365       g_value_set_uint (value, dbin->max_size_bytes);
1366       break;
1367     case PROP_MAX_SIZE_BUFFERS:
1368       g_value_set_uint (value, dbin->max_size_buffers);
1369       break;
1370     case PROP_MAX_SIZE_TIME:
1371       g_value_set_uint64 (value, dbin->max_size_time);
1372       break;
1373     case PROP_POST_STREAM_TOPOLOGY:
1374       g_value_set_boolean (value, dbin->post_stream_topology);
1375       break;
1376     case PROP_EXPOSE_ALL_STREAMS:
1377       g_value_set_boolean (value, dbin->expose_allstreams);
1378       break;
1379 #ifdef TIZEN_FEATURE_TRUSTZONE
1380     /*tzmultiqueue patch : use-trustzone property*/
1381     case PROP_USE_TRUSTZONE:
1382       g_value_set_boolean (value, dbin->use_trustzone);
1383       break;
1384 #endif
1385     case PROP_CONNECTION_SPEED:
1386       GST_OBJECT_LOCK (dbin);
1387       g_value_set_uint64 (value, dbin->connection_speed / 1000);
1388       GST_OBJECT_UNLOCK (dbin);
1389       break;
1390     default:
1391       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1392       break;
1393   }
1394 }
1395
1396
1397 /*****
1398  * Default autoplug signal handlers
1399  *****/
1400 static gboolean
1401 gst_decode_bin_autoplug_continue (GstElement * element, GstPad * pad,
1402     GstCaps * caps)
1403 {
1404   GST_DEBUG_OBJECT (element, "autoplug-continue returns TRUE");
1405
1406   /* by default we always continue */
1407   return TRUE;
1408 }
1409
1410 static GValueArray *
1411 gst_decode_bin_autoplug_factories (GstElement * element, GstPad * pad,
1412     GstCaps * caps)
1413 {
1414   GList *list, *tmp;
1415   GValueArray *result;
1416   GstDecodeBin *dbin = GST_DECODE_BIN_CAST (element);
1417
1418   GST_DEBUG_OBJECT (element, "finding factories");
1419
1420   /* return all compatible factories for caps */
1421   g_mutex_lock (&dbin->factories_lock);
1422   gst_decode_bin_update_factories_list (dbin);
1423   list =
1424       gst_element_factory_list_filter (dbin->factories, caps, GST_PAD_SINK,
1425       gst_caps_is_fixed (caps));
1426   g_mutex_unlock (&dbin->factories_lock);
1427
1428   result = g_value_array_new (g_list_length (list));
1429   for (tmp = list; tmp; tmp = tmp->next) {
1430     GstElementFactory *factory = GST_ELEMENT_FACTORY_CAST (tmp->data);
1431     GValue val = { 0, };
1432
1433     g_value_init (&val, G_TYPE_OBJECT);
1434     g_value_set_object (&val, factory);
1435     g_value_array_append (result, &val);
1436     g_value_unset (&val);
1437   }
1438   gst_plugin_feature_list_free (list);
1439
1440   GST_DEBUG_OBJECT (element, "autoplug-factories returns %p", result);
1441
1442   return result;
1443 }
1444
1445 static GValueArray *
1446 gst_decode_bin_autoplug_sort (GstElement * element, GstPad * pad,
1447     GstCaps * caps, GValueArray * factories)
1448 {
1449   return NULL;
1450 }
1451
1452 static GstAutoplugSelectResult
1453 gst_decode_bin_autoplug_select (GstElement * element, GstPad * pad,
1454     GstCaps * caps, GstElementFactory * factory)
1455 {
1456   GST_DEBUG_OBJECT (element, "default autoplug-select returns TRY");
1457
1458   /* Try factory. */
1459   return GST_AUTOPLUG_SELECT_TRY;
1460 }
1461
1462 static gboolean
1463 gst_decode_bin_autoplug_query (GstElement * element, GstPad * pad,
1464     GstQuery * query)
1465 {
1466   /* No query handled here */
1467   return FALSE;
1468 }
1469
1470 /********
1471  * Discovery methods
1472  *****/
1473
1474 static gboolean are_final_caps (GstDecodeBin * dbin, GstCaps * caps);
1475 static gboolean is_demuxer_element (GstElement * srcelement);
1476 static gboolean is_adaptive_demuxer_element (GstElement * srcelement);
1477
1478 static gboolean connect_pad (GstDecodeBin * dbin, GstElement * src,
1479     GstDecodePad * dpad, GstPad * pad, GstCaps * caps, GValueArray * factories,
1480     GstDecodeChain * chain, gchar ** deadend_details);
1481 static GList *connect_element (GstDecodeBin * dbin, GstDecodeElement * delem,
1482     GstDecodeChain * chain);
1483 static void expose_pad (GstDecodeBin * dbin, GstElement * src,
1484     GstDecodePad * dpad, GstPad * pad, GstCaps * caps, GstDecodeChain * chain);
1485
1486 static void pad_added_cb (GstElement * element, GstPad * pad,
1487     GstDecodeChain * chain);
1488 static void pad_removed_cb (GstElement * element, GstPad * pad,
1489     GstDecodeChain * chain);
1490 static void no_more_pads_cb (GstElement * element, GstDecodeChain * chain);
1491
1492 static GstDecodeGroup *gst_decode_chain_get_current_group (GstDecodeChain *
1493     chain);
1494
1495 static gboolean
1496 clear_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
1497 {
1498   GST_DEBUG_OBJECT (pad, "clearing sticky event %" GST_PTR_FORMAT, *event);
1499   gst_event_unref (*event);
1500   *event = NULL;
1501   return TRUE;
1502 }
1503
1504 static gboolean
1505 copy_sticky_events (GstPad * pad, GstEvent ** event, gpointer user_data)
1506 {
1507   GstPad *gpad = GST_PAD_CAST (user_data);
1508
1509   GST_DEBUG_OBJECT (gpad, "store sticky event %" GST_PTR_FORMAT, *event);
1510   gst_pad_store_sticky_event (gpad, *event);
1511
1512   return TRUE;
1513 }
1514
1515 static void
1516 decode_pad_set_target (GstDecodePad * dpad, GstPad * target)
1517 {
1518   gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (dpad), target);
1519   if (target == NULL)
1520     gst_pad_sticky_events_foreach (GST_PAD_CAST (dpad), clear_sticky_events,
1521         NULL);
1522   else
1523     gst_pad_sticky_events_foreach (target, copy_sticky_events, dpad);
1524 }
1525
1526 /* called when a new pad is discovered. It will perform some basic actions
1527  * before trying to link something to it.
1528  *
1529  *  - Check the caps, don't do anything when there are no caps or when they have
1530  *    no good type.
1531  *  - signal AUTOPLUG_CONTINUE to check if we need to continue autoplugging this
1532  *    pad.
1533  *  - if the caps are non-fixed, setup a handler to continue autoplugging when
1534  *    the caps become fixed (connect to notify::caps).
1535  *  - get list of factories to autoplug.
1536  *  - continue autoplugging to one of the factories.
1537  */
1538 /* returns whether to expose the pad */
1539 static gboolean
1540 analyze_new_pad (GstDecodeBin * dbin, GstElement * src, GstPad * pad,
1541     GstCaps * caps, GstDecodeChain * chain, GstDecodeChain ** new_chain)
1542 {
1543   gboolean apcontinue = TRUE;
1544   GValueArray *factories = NULL, *result = NULL;
1545   GstDecodePad *dpad;
1546   GstElementFactory *factory;
1547   const gchar *classification;
1548   gboolean is_parser_converter = FALSE;
1549   gboolean res;
1550   gchar *deadend_details = NULL;
1551
1552   GST_DEBUG_OBJECT (dbin, "Pad %s:%s caps:%" GST_PTR_FORMAT,
1553       GST_DEBUG_PAD_NAME (pad), caps);
1554
1555   if (new_chain)
1556     *new_chain = chain;
1557
1558   if (chain->elements
1559       && src != ((GstDecodeElement *) chain->elements->data)->element
1560       && src != ((GstDecodeElement *) chain->elements->data)->capsfilter) {
1561     GST_ERROR_OBJECT (dbin, "New pad from not the last element in this chain");
1562     return FALSE;
1563   }
1564
1565   if (chain->endpad) {
1566     GST_ERROR_OBJECT (dbin, "New pad in a chain that is already complete");
1567     return FALSE;
1568   }
1569
1570   if (chain->demuxer) {
1571     GstDecodeGroup *group;
1572     GstDecodeChain *oldchain = chain;
1573     GstDecodeElement *demux = (chain->elements ? chain->elements->data : NULL);
1574
1575     if (chain->current_pad)
1576       gst_object_unref (chain->current_pad);
1577     chain->current_pad = NULL;
1578
1579     /* we are adding a new pad for a demuxer (see is_demuxer_element(),
1580      * start a new chain for it */
1581     CHAIN_MUTEX_LOCK (oldchain);
1582     group = gst_decode_chain_get_current_group (chain);
1583     if (group && !g_list_find (group->children, chain)) {
1584       g_assert (new_chain != NULL);
1585       *new_chain = chain = gst_decode_chain_new (dbin, group, pad);
1586       group->children = g_list_prepend (group->children, chain);
1587     }
1588     CHAIN_MUTEX_UNLOCK (oldchain);
1589     if (!group) {
1590       GST_WARNING_OBJECT (dbin, "No current group");
1591       return FALSE;
1592     }
1593
1594     /* If this is not a dynamic pad demuxer, we're no-more-pads
1595      * already before anything else happens
1596      */
1597     if (demux == NULL || !demux->no_more_pads_id)
1598       group->no_more_pads = TRUE;
1599   }
1600
1601   /* From here on we own a reference to the caps as
1602    * we might create new caps below and would need
1603    * to unref them later */
1604   if (caps)
1605     gst_caps_ref (caps);
1606
1607   if ((caps == NULL) || gst_caps_is_empty (caps))
1608     goto unknown_type;
1609
1610   if (gst_caps_is_any (caps))
1611     goto any_caps;
1612
1613   if (!chain->current_pad)
1614     chain->current_pad = gst_decode_pad_new (dbin, chain);
1615
1616   dpad = gst_object_ref (chain->current_pad);
1617   gst_pad_set_active (GST_PAD_CAST (dpad), TRUE);
1618   decode_pad_set_target (dpad, pad);
1619
1620   /* 1. Emit 'autoplug-continue' the result will tell us if this pads needs
1621    * further autoplugging. Only do this for fixed caps, for unfixed caps
1622    * we will later come here again from the notify::caps handler. The
1623    * problem with unfixed caps is that, we can't reliably tell if the output
1624    * is e.g. accepted by a sink because only parts of the possible final
1625    * caps might be accepted by the sink. */
1626   if (gst_caps_is_fixed (caps))
1627     g_signal_emit (G_OBJECT (dbin),
1628         gst_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE], 0, dpad, caps,
1629         &apcontinue);
1630   else
1631     apcontinue = TRUE;
1632
1633   /* 1.a if autoplug-continue is FALSE or caps is a raw format, goto pad_is_final */
1634   if ((!apcontinue) || are_final_caps (dbin, caps))
1635     goto expose_pad;
1636
1637   /* 1.b For Parser/Converter that can output different stream formats
1638    * we insert a capsfilter with the sorted caps of all possible next
1639    * elements and continue with the capsfilter srcpad */
1640   factory = gst_element_get_factory (src);
1641   classification =
1642       gst_element_factory_get_metadata (factory, GST_ELEMENT_METADATA_KLASS);
1643   is_parser_converter = (strstr (classification, "Parser")
1644       && strstr (classification, "Converter"));
1645
1646   /* 1.c when the caps are not fixed yet, we can't be sure what element to
1647    * connect. We delay autoplugging until the caps are fixed */
1648   if (!is_parser_converter && !gst_caps_is_fixed (caps)) {
1649     goto non_fixed;
1650   } else if (!is_parser_converter) {
1651     gst_caps_unref (caps);
1652     caps = gst_pad_get_current_caps (pad);
1653     if (!caps) {
1654       GST_DEBUG_OBJECT (dbin, "No final caps set yet, delaying autoplugging");
1655       gst_object_unref (dpad);
1656       goto setup_caps_delay;
1657     }
1658   }
1659
1660   /* 1.d else get the factories and if there's no compatible factory goto
1661    * unknown_type */
1662   g_signal_emit (G_OBJECT (dbin),
1663       gst_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES], 0, dpad, caps,
1664       &factories);
1665
1666   /* NULL means that we can expose the pad */
1667   if (factories == NULL)
1668     goto expose_pad;
1669
1670   /* if the array is empty, we have a type for which we have no decoder */
1671   if (factories->n_values == 0) {
1672     if (!dbin->expose_allstreams) {
1673       GstCaps *raw = gst_static_caps_get (&default_raw_caps);
1674
1675       /* If the caps are raw, this just means we don't want to expose them */
1676       if (gst_caps_is_subset (caps, raw)) {
1677         g_value_array_free (factories);
1678         gst_caps_unref (raw);
1679         gst_object_unref (dpad);
1680         goto discarded_type;
1681       }
1682       gst_caps_unref (raw);
1683     }
1684
1685     /* if not we have a unhandled type with no compatible factories */
1686     g_value_array_free (factories);
1687     gst_object_unref (dpad);
1688     goto unknown_type;
1689   }
1690
1691   /* 1.e sort some more. */
1692   g_signal_emit (G_OBJECT (dbin),
1693       gst_decode_bin_signals[SIGNAL_AUTOPLUG_SORT], 0, dpad, caps, factories,
1694       &result);
1695   if (result) {
1696     g_value_array_free (factories);
1697     factories = result;
1698   }
1699
1700   /* At this point we have a potential decoder, but we might not need it
1701    * if it doesn't match the output caps  */
1702   if (!dbin->expose_allstreams && gst_caps_is_fixed (caps)) {
1703     guint i;
1704     const GList *tmps;
1705     gboolean dontuse = FALSE;
1706
1707     GST_DEBUG ("Checking if we can abort early");
1708
1709     /* 1.f Do an early check to see if the candidates are potential decoders, but
1710      * due to the fact that they decode to a mediatype that is not final we don't
1711      * need them */
1712
1713     for (i = 0; i < factories->n_values && !dontuse; i++) {
1714       GstElementFactory *factory =
1715           g_value_get_object (g_value_array_get_nth (factories, i));
1716       GstCaps *tcaps;
1717
1718       /* We are only interested in skipping decoders */
1719       if (strstr (gst_element_factory_get_metadata (factory,
1720                   GST_ELEMENT_METADATA_KLASS), "Decoder")) {
1721
1722         GST_DEBUG ("Trying factory %s",
1723             gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
1724
1725         /* Check the source pad template caps to see if they match raw caps but don't match
1726          * our final caps*/
1727         for (tmps = gst_element_factory_get_static_pad_templates (factory);
1728             tmps && !dontuse; tmps = tmps->next) {
1729           GstStaticPadTemplate *st = (GstStaticPadTemplate *) tmps->data;
1730           if (st->direction != GST_PAD_SRC)
1731             continue;
1732           tcaps = gst_static_pad_template_get_caps (st);
1733
1734           apcontinue = TRUE;
1735
1736           /* Emit autoplug-continue to see if the caps are considered to be raw caps */
1737           g_signal_emit (G_OBJECT (dbin),
1738               gst_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE], 0, dpad, tcaps,
1739               &apcontinue);
1740
1741           /* If autoplug-continue returns TRUE and the caps are not final, don't use them */
1742           if (apcontinue && !are_final_caps (dbin, tcaps))
1743             dontuse = TRUE;
1744           gst_caps_unref (tcaps);
1745         }
1746       }
1747     }
1748
1749     if (dontuse) {
1750       gst_object_unref (dpad);
1751       g_value_array_free (factories);
1752       goto discarded_type;
1753     }
1754   }
1755
1756   /* 1.g now get the factory template caps and insert the capsfilter if this
1757    * is a parser/converter
1758    */
1759   if (is_parser_converter) {
1760     GstCaps *filter_caps;
1761     gint i;
1762     GstElement *capsfilter;
1763     GstPad *p;
1764     GstDecodeElement *delem;
1765
1766     filter_caps = gst_caps_new_empty ();
1767     for (i = 0; i < factories->n_values; i++) {
1768       GstElementFactory *factory =
1769           g_value_get_object (g_value_array_get_nth (factories, i));
1770       GstCaps *tcaps, *intersection;
1771       const GList *tmps;
1772
1773       GST_DEBUG ("Trying factory %s",
1774           gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
1775
1776       if (gst_element_get_factory (src) == factory ||
1777           gst_element_factory_list_is_type (factory,
1778               GST_ELEMENT_FACTORY_TYPE_PARSER)) {
1779         GST_DEBUG ("Skipping factory");
1780         continue;
1781       }
1782
1783       for (tmps = gst_element_factory_get_static_pad_templates (factory); tmps;
1784           tmps = tmps->next) {
1785         GstStaticPadTemplate *st = (GstStaticPadTemplate *) tmps->data;
1786         if (st->direction != GST_PAD_SINK || st->presence != GST_PAD_ALWAYS)
1787           continue;
1788         tcaps = gst_static_pad_template_get_caps (st);
1789         intersection =
1790             gst_caps_intersect_full (tcaps, caps, GST_CAPS_INTERSECT_FIRST);
1791         filter_caps = gst_caps_merge (filter_caps, intersection);
1792         gst_caps_unref (tcaps);
1793       }
1794     }
1795
1796     /* Append the parser caps to prevent any not-negotiated errors */
1797     filter_caps = gst_caps_merge (filter_caps, gst_caps_ref (caps));
1798
1799     if (chain->elements) {
1800       delem = (GstDecodeElement *) chain->elements->data;
1801       capsfilter = delem->capsfilter =
1802           gst_element_factory_make ("capsfilter", NULL);
1803     } else {
1804       delem = g_slice_new0 (GstDecodeElement);
1805       capsfilter = delem->element =
1806           gst_element_factory_make ("capsfilter", NULL);
1807       delem->capsfilter = NULL;
1808       chain->elements = g_list_prepend (chain->elements, delem);
1809     }
1810
1811     g_object_set (G_OBJECT (capsfilter), "caps", filter_caps, NULL);
1812     gst_caps_unref (filter_caps);
1813     gst_element_set_state (capsfilter, GST_STATE_PAUSED);
1814     gst_bin_add (GST_BIN_CAST (dbin), gst_object_ref (capsfilter));
1815
1816     decode_pad_set_target (dpad, NULL);
1817     p = gst_element_get_static_pad (capsfilter, "sink");
1818     gst_pad_link_full (pad, p, GST_PAD_LINK_CHECK_NOTHING);
1819     gst_object_unref (p);
1820     p = gst_element_get_static_pad (capsfilter, "src");
1821     decode_pad_set_target (dpad, p);
1822     pad = p;
1823
1824     gst_caps_unref (caps);
1825
1826     caps = gst_pad_get_current_caps (pad);
1827     if (!caps) {
1828       GST_DEBUG_OBJECT (dbin, "No final caps set yet, delaying autoplugging");
1829       gst_object_unref (dpad);
1830       g_value_array_free (factories);
1831       goto setup_caps_delay;
1832     }
1833   }
1834
1835   /* 1.h else continue autoplugging something from the list. */
1836   GST_LOG_OBJECT (pad, "Let's continue discovery on this pad");
1837   res =
1838       connect_pad (dbin, src, dpad, pad, caps, factories, chain,
1839       &deadend_details);
1840
1841   /* Need to unref the capsfilter srcpad here if
1842    * we inserted a capsfilter */
1843   if (is_parser_converter)
1844     gst_object_unref (pad);
1845
1846   gst_object_unref (dpad);
1847   g_value_array_free (factories);
1848
1849   if (!res)
1850     goto unknown_type;
1851
1852   gst_caps_unref (caps);
1853
1854   return FALSE;
1855
1856 expose_pad:
1857   {
1858     GST_LOG_OBJECT (dbin, "Pad is final and should expose the pad. "
1859         "autoplug-continue:%d", apcontinue);
1860     gst_object_unref (dpad);
1861     gst_caps_unref (caps);
1862     return TRUE;
1863   }
1864
1865 discarded_type:
1866   {
1867     GST_LOG_OBJECT (pad, "Known type, but discarded because not final caps");
1868     chain->deadend = TRUE;
1869     chain->endcaps = caps;
1870     gst_object_replace ((GstObject **) & chain->current_pad, NULL);
1871
1872     /* Try to expose anything */
1873     EXPOSE_LOCK (dbin);
1874     if (dbin->decode_chain) {
1875       if (gst_decode_chain_is_complete (dbin->decode_chain)) {
1876         gst_decode_bin_expose (dbin);
1877       }
1878     }
1879     EXPOSE_UNLOCK (dbin);
1880     do_async_done (dbin);
1881
1882     return FALSE;
1883   }
1884
1885 unknown_type:
1886   {
1887     GST_LOG_OBJECT (pad, "Unknown type, posting message and firing signal");
1888
1889     chain->deadend_details = deadend_details;
1890     chain->deadend = TRUE;
1891     chain->endcaps = caps;
1892     gst_object_replace ((GstObject **) & chain->current_pad, NULL);
1893
1894     gst_element_post_message (GST_ELEMENT_CAST (dbin),
1895         gst_missing_decoder_message_new (GST_ELEMENT_CAST (dbin), caps));
1896
1897     g_signal_emit (G_OBJECT (dbin),
1898         gst_decode_bin_signals[SIGNAL_UNKNOWN_TYPE], 0, pad, caps);
1899
1900     /* Try to expose anything */
1901     EXPOSE_LOCK (dbin);
1902     if (dbin->decode_chain) {
1903       if (gst_decode_chain_is_complete (dbin->decode_chain)) {
1904         gst_decode_bin_expose (dbin);
1905       }
1906     }
1907     EXPOSE_UNLOCK (dbin);
1908
1909     if (src == dbin->typefind) {
1910       if (!caps || gst_caps_is_empty (caps)) {
1911         GST_ELEMENT_ERROR (dbin, STREAM, TYPE_NOT_FOUND,
1912             (_("Could not determine type of stream")), (NULL));
1913       }
1914       do_async_done (dbin);
1915     }
1916     return FALSE;
1917   }
1918 non_fixed:
1919   {
1920     GST_DEBUG_OBJECT (pad, "pad has non-fixed caps delay autoplugging");
1921     gst_object_unref (dpad);
1922     goto setup_caps_delay;
1923   }
1924 any_caps:
1925   {
1926     GST_DEBUG_OBJECT (pad, "pad has ANY caps, delaying auto-pluggin");
1927     goto setup_caps_delay;
1928   }
1929 setup_caps_delay:
1930   {
1931     GstPendingPad *ppad;
1932
1933     /* connect to caps notification */
1934     CHAIN_MUTEX_LOCK (chain);
1935     GST_LOG_OBJECT (dbin, "Chain %p has now %d dynamic pads", chain,
1936         g_list_length (chain->pending_pads));
1937     ppad = g_slice_new0 (GstPendingPad);
1938     ppad->pad = gst_object_ref (pad);
1939     ppad->chain = chain;
1940     ppad->event_probe_id =
1941         gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
1942         pad_event_cb, ppad, NULL);
1943     chain->pending_pads = g_list_prepend (chain->pending_pads, ppad);
1944     ppad->notify_caps_id = g_signal_connect (pad, "notify::caps",
1945         G_CALLBACK (caps_notify_cb), chain);
1946     CHAIN_MUTEX_UNLOCK (chain);
1947
1948     /* If we're here because we have a Parser/Converter
1949      * we have to unref the pad */
1950     if (is_parser_converter)
1951       gst_object_unref (pad);
1952     if (caps)
1953       gst_caps_unref (caps);
1954
1955     return FALSE;
1956   }
1957 }
1958
1959 static void
1960 add_error_filter (GstDecodeBin * dbin, GstElement * element)
1961 {
1962   GST_OBJECT_LOCK (dbin);
1963   dbin->filtered = g_list_prepend (dbin->filtered, element);
1964   GST_OBJECT_UNLOCK (dbin);
1965 }
1966
1967 static void
1968 remove_error_filter (GstDecodeBin * dbin, GstElement * element,
1969     GstMessage ** error)
1970 {
1971   GList *l;
1972
1973   GST_OBJECT_LOCK (dbin);
1974   dbin->filtered = g_list_remove (dbin->filtered, element);
1975
1976   if (error)
1977     *error = NULL;
1978
1979   l = dbin->filtered_errors;
1980   while (l) {
1981     GstMessage *msg = l->data;
1982
1983     if (GST_MESSAGE_SRC (msg) == GST_OBJECT_CAST (element)) {
1984       /* Get the last error of this element, i.e. the earliest */
1985       if (error)
1986         gst_message_replace (error, msg);
1987       gst_message_unref (msg);
1988       l = dbin->filtered_errors = g_list_delete_link (dbin->filtered_errors, l);
1989     } else {
1990       l = l->next;
1991     }
1992   }
1993   GST_OBJECT_UNLOCK (dbin);
1994 }
1995
1996 typedef struct
1997 {
1998   gboolean ret;
1999   GstPad *peer;
2000 } SendStickyEventsData;
2001
2002 static gboolean
2003 send_sticky_event (GstPad * pad, GstEvent ** event, gpointer user_data)
2004 {
2005   SendStickyEventsData *data = user_data;
2006   gboolean ret;
2007
2008   ret = gst_pad_send_event (data->peer, gst_event_ref (*event));
2009   if (!ret)
2010     data->ret = FALSE;
2011
2012   return data->ret;
2013 }
2014
2015 static gboolean
2016 send_sticky_events (GstDecodeBin * dbin, GstPad * pad)
2017 {
2018   SendStickyEventsData data;
2019
2020   data.ret = TRUE;
2021   data.peer = gst_pad_get_peer (pad);
2022
2023   gst_pad_sticky_events_foreach (pad, send_sticky_event, &data);
2024
2025   gst_object_unref (data.peer);
2026
2027   return data.ret;
2028 }
2029
2030 static gchar *
2031 error_message_to_string (GstMessage * msg)
2032 {
2033   GError *err;
2034   gchar *debug, *message, *full_message;
2035
2036   gst_message_parse_error (msg, &err, &debug);
2037
2038   message = gst_error_get_message (err->domain, err->code);
2039
2040   if (debug)
2041     full_message = g_strdup_printf ("%s\n%s\n%s", message, err->message, debug);
2042   else
2043     full_message = g_strdup_printf ("%s\n%s", message, err->message);
2044
2045   g_free (message);
2046   g_free (debug);
2047   g_clear_error (&err);
2048
2049   return full_message;
2050 }
2051
2052 static GstPadProbeReturn
2053 demuxer_source_pad_probe (GstPad * pad, GstPadProbeInfo * info,
2054     gpointer user_data)
2055 {
2056   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
2057   GstDecodeGroup *group = (GstDecodeGroup *) user_data;
2058   GstDecodeChain *parent_chain = group->parent;
2059
2060   GST_DEBUG_OBJECT (pad, "Saw event %s", GST_EVENT_TYPE_NAME (event));
2061   /* Check if we are the active group, if not we need to proxy the flush
2062    * events to the other groups (of which at least one is exposed, ensuring
2063    * flushing properly propagates downstream of decodebin */
2064   if (parent_chain->active_group == group)
2065     return GST_PAD_PROBE_OK;
2066
2067   switch (GST_EVENT_TYPE (event)) {
2068     case GST_EVENT_FLUSH_START:
2069     case GST_EVENT_FLUSH_STOP:
2070     {
2071       GList *tmp;
2072       GST_DEBUG_OBJECT (pad, "Proxying flush events to inactive groups");
2073       /* Proxy to active group */
2074       for (tmp = parent_chain->active_group->reqpads; tmp; tmp = tmp->next) {
2075         GstPad *reqpad = (GstPad *) tmp->data;
2076         gst_pad_send_event (reqpad, gst_event_ref (event));
2077       }
2078       /* Proxy to other non-active groups (except ourself) */
2079       for (tmp = parent_chain->next_groups; tmp; tmp = tmp->next) {
2080         GList *tmp2;
2081         GstDecodeGroup *tmpgroup = (GstDecodeGroup *) tmp->data;
2082         if (tmpgroup != group) {
2083           for (tmp2 = tmpgroup->reqpads; tmp2; tmp2 = tmp2->next) {
2084             GstPad *reqpad = (GstPad *) tmp2->data;
2085             gst_pad_send_event (reqpad, gst_event_ref (event));
2086           }
2087         }
2088       }
2089       flush_chain (parent_chain,
2090           GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_START);
2091     }
2092       break;
2093     default:
2094       break;
2095   }
2096
2097   return GST_PAD_PROBE_OK;
2098 }
2099
2100 typedef struct
2101 {
2102   GstDecodeChain *chain;
2103   GstPad *pad;
2104 } PadExposeData;
2105
2106 /* connect_pad:
2107  *
2108  * Try to connect the given pad to an element created from one of the factories,
2109  * and recursively.
2110  *
2111  * Note that dpad is ghosting pad, and so pad is linked; be sure to unset dpad's
2112  * target before trying to link pad.
2113  *
2114  * Returns TRUE if an element was properly created and linked
2115  */
2116 static gboolean
2117 connect_pad (GstDecodeBin * dbin, GstElement * src, GstDecodePad * dpad,
2118     GstPad * pad, GstCaps * caps, GValueArray * factories,
2119     GstDecodeChain * chain, gchar ** deadend_details)
2120 {
2121   gboolean res = FALSE;
2122   GstPad *mqpad = NULL;
2123   gboolean is_demuxer = chain->parent && !chain->elements;      /* First pad after the demuxer */
2124   GString *error_details = NULL;
2125
2126   g_return_val_if_fail (factories != NULL, FALSE);
2127   g_return_val_if_fail (factories->n_values > 0, FALSE);
2128
2129   GST_DEBUG_OBJECT (dbin,
2130       "pad %s:%s , chain:%p, %d factories, caps %" GST_PTR_FORMAT,
2131       GST_DEBUG_PAD_NAME (pad), chain, factories->n_values, caps);
2132
2133   /* 1. is element demuxer or parser */
2134   if (is_demuxer) {
2135     GST_LOG_OBJECT (src,
2136         "is a demuxer, connecting the pad through multiqueue '%s'",
2137         GST_OBJECT_NAME (chain->parent->multiqueue));
2138
2139     /* Set a flush-start/-stop probe on the downstream events */
2140     chain->pad_probe_id =
2141         gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_FLUSH,
2142         demuxer_source_pad_probe, chain->parent, NULL);
2143
2144     decode_pad_set_target (dpad, NULL);
2145     if (!(mqpad = gst_decode_group_control_demuxer_pad (chain->parent, pad)))
2146       goto beach;
2147     src = chain->parent->multiqueue;
2148     /* Forward sticky events to mq src pad to allow factory initialization */
2149     gst_pad_sticky_events_foreach (pad, copy_sticky_events, mqpad);
2150     pad = mqpad;
2151     decode_pad_set_target (dpad, pad);
2152   }
2153
2154   error_details = g_string_new ("");
2155
2156   /* 2. Try to create an element and link to it */
2157   while (factories->n_values > 0) {
2158     GstAutoplugSelectResult ret;
2159     GstElementFactory *factory;
2160     GstDecodeElement *delem;
2161     GstElement *element;
2162     GstPad *sinkpad;
2163     GParamSpec *pspec;
2164     gboolean subtitle;
2165     GList *to_connect = NULL;
2166     GList *to_expose = NULL;
2167     gboolean is_parser = FALSE;
2168     gboolean is_decoder = FALSE;
2169
2170     /* Set dpad target to pad again, it might've been unset
2171      * below but we came back here because something failed
2172      */
2173     decode_pad_set_target (dpad, pad);
2174
2175     /* take first factory */
2176     factory = g_value_get_object (g_value_array_get_nth (factories, 0));
2177     /* Remove selected factory from the list. */
2178     g_value_array_remove (factories, 0);
2179
2180     GST_LOG_OBJECT (src, "trying factory %" GST_PTR_FORMAT, factory);
2181
2182     /* Check if the caps are really supported by the factory. The
2183      * factory list is non-empty-subset filtered while caps
2184      * are only accepted by a pad if they are a subset of the
2185      * pad caps.
2186      *
2187      * FIXME: Only do this for fixed caps here. Non-fixed caps
2188      * can happen if a Parser/Converter was autoplugged before
2189      * this. We then assume that it will be able to convert to
2190      * everything that the decoder would want.
2191      *
2192      * A subset check will fail here because the parser caps
2193      * will be generic and while the decoder will only
2194      * support a subset of the parser caps.
2195      */
2196     if (gst_caps_is_fixed (caps)) {
2197       const GList *templs;
2198       gboolean skip = FALSE;
2199
2200       templs = gst_element_factory_get_static_pad_templates (factory);
2201
2202       while (templs) {
2203         GstStaticPadTemplate *templ = (GstStaticPadTemplate *) templs->data;
2204
2205         if (templ->direction == GST_PAD_SINK) {
2206           GstCaps *templcaps = gst_static_caps_get (&templ->static_caps);
2207
2208           if (!gst_caps_is_subset (caps, templcaps)) {
2209             GST_DEBUG_OBJECT (src,
2210                 "caps %" GST_PTR_FORMAT " not subset of %" GST_PTR_FORMAT, caps,
2211                 templcaps);
2212             gst_caps_unref (templcaps);
2213             skip = TRUE;
2214             break;
2215           }
2216
2217           gst_caps_unref (templcaps);
2218         }
2219         templs = g_list_next (templs);
2220       }
2221       if (skip)
2222         continue;
2223     }
2224
2225     /* If the factory is for a parser we first check if the factory
2226      * was already used for the current chain. If it was used already
2227      * we would otherwise create an infinite loop here because the
2228      * parser apparently accepts its own output as input.
2229      * This is only done for parsers because it's perfectly valid
2230      * to have other element classes after each other because a
2231      * parser is the only one that does not change the data. A
2232      * valid example for this would be multiple id3demux in a row.
2233      */
2234     is_parser = strstr (gst_element_factory_get_metadata (factory,
2235             GST_ELEMENT_METADATA_KLASS), "Parser") != NULL;
2236
2237     if (is_parser) {
2238       gboolean skip = FALSE;
2239       GList *l;
2240
2241       CHAIN_MUTEX_LOCK (chain);
2242       for (l = chain->elements; l; l = l->next) {
2243         GstDecodeElement *delem = (GstDecodeElement *) l->data;
2244         GstElement *otherelement = delem->element;
2245
2246         if (gst_element_get_factory (otherelement) == factory) {
2247           skip = TRUE;
2248           break;
2249         }
2250       }
2251
2252       if (!skip && chain->parent && chain->parent->parent) {
2253         GstDecodeChain *parent_chain = chain->parent->parent;
2254         GstDecodeElement *pelem =
2255             parent_chain->elements ? parent_chain->elements->data : NULL;
2256
2257         if (pelem && gst_element_get_factory (pelem->element) == factory)
2258           skip = TRUE;
2259       }
2260       CHAIN_MUTEX_UNLOCK (chain);
2261       if (skip) {
2262         GST_DEBUG_OBJECT (dbin,
2263             "Skipping factory '%s' because it was already used in this chain",
2264             gst_plugin_feature_get_name (GST_PLUGIN_FEATURE_CAST (factory)));
2265         continue;
2266       }
2267
2268     }
2269
2270     /* emit autoplug-select to see what we should do with it. */
2271     g_signal_emit (G_OBJECT (dbin),
2272         gst_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT],
2273         0, dpad, caps, factory, &ret);
2274
2275     switch (ret) {
2276       case GST_AUTOPLUG_SELECT_TRY:
2277         GST_DEBUG_OBJECT (dbin, "autoplug select requested try");
2278         break;
2279       case GST_AUTOPLUG_SELECT_EXPOSE:
2280         GST_DEBUG_OBJECT (dbin, "autoplug select requested expose");
2281         /* expose the pad, we don't have the source element */
2282         expose_pad (dbin, src, dpad, pad, caps, chain);
2283         res = TRUE;
2284         goto beach;
2285       case GST_AUTOPLUG_SELECT_SKIP:
2286         GST_DEBUG_OBJECT (dbin, "autoplug select requested skip");
2287         continue;
2288       default:
2289         GST_WARNING_OBJECT (dbin, "autoplug select returned unhandled %d", ret);
2290         break;
2291     }
2292
2293     /* 2.0. Unlink pad */
2294     decode_pad_set_target (dpad, NULL);
2295
2296     /* 2.1. Try to create an element */
2297     if ((element = gst_element_factory_create (factory, NULL)) == NULL) {
2298       GST_WARNING_OBJECT (dbin, "Could not create an element from %s",
2299           gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
2300       g_string_append_printf (error_details,
2301           "Could not create an element from %s\n",
2302           gst_plugin_feature_get_name (GST_PLUGIN_FEATURE (factory)));
2303       continue;
2304     }
2305
2306     /* Filter errors, this will prevent the element from causing the pipeline
2307      * to error while we test it using READY state. */
2308     add_error_filter (dbin, element);
2309
2310     /* We don't yet want the bin to control the element's state */
2311     gst_element_set_locked_state (element, TRUE);
2312
2313     /* ... add it ... */
2314     if (!(gst_bin_add (GST_BIN_CAST (dbin), element))) {
2315       GST_WARNING_OBJECT (dbin, "Couldn't add %s to the bin",
2316           GST_ELEMENT_NAME (element));
2317       remove_error_filter (dbin, element, NULL);
2318       g_string_append_printf (error_details, "Couldn't add %s to the bin\n",
2319           GST_ELEMENT_NAME (element));
2320       gst_object_unref (element);
2321       continue;
2322     }
2323
2324     /* Find its sink pad. */
2325     if (!(sinkpad = find_sink_pad (element))) {
2326       GST_WARNING_OBJECT (dbin, "Element %s doesn't have a sink pad",
2327           GST_ELEMENT_NAME (element));
2328       remove_error_filter (dbin, element, NULL);
2329       g_string_append_printf (error_details,
2330           "Element %s doesn't have a sink pad", GST_ELEMENT_NAME (element));
2331       gst_bin_remove (GST_BIN (dbin), element);
2332       continue;
2333     }
2334
2335     /* ... and try to link */
2336     if ((gst_pad_link_full (pad, sinkpad,
2337                 GST_PAD_LINK_CHECK_NOTHING)) != GST_PAD_LINK_OK) {
2338       GST_WARNING_OBJECT (dbin, "Link failed on pad %s:%s",
2339           GST_DEBUG_PAD_NAME (sinkpad));
2340       remove_error_filter (dbin, element, NULL);
2341       g_string_append_printf (error_details, "Link failed on pad %s:%s",
2342           GST_DEBUG_PAD_NAME (sinkpad));
2343       gst_object_unref (sinkpad);
2344       gst_bin_remove (GST_BIN (dbin), element);
2345       continue;
2346     }
2347
2348     /* ... activate it ... */
2349     if ((gst_element_set_state (element,
2350                 GST_STATE_READY)) == GST_STATE_CHANGE_FAILURE) {
2351       GstMessage *error_msg;
2352
2353       GST_WARNING_OBJECT (dbin, "Couldn't set %s to READY",
2354           GST_ELEMENT_NAME (element));
2355       remove_error_filter (dbin, element, &error_msg);
2356
2357       if (error_msg) {
2358         gchar *error_string = error_message_to_string (error_msg);
2359         g_string_append_printf (error_details, "Couldn't set %s to READY:\n%s",
2360             GST_ELEMENT_NAME (element), error_string);
2361         gst_message_unref (error_msg);
2362         g_free (error_string);
2363       } else {
2364         g_string_append_printf (error_details, "Couldn't set %s to READY",
2365             GST_ELEMENT_NAME (element));
2366       }
2367       gst_object_unref (sinkpad);
2368       gst_bin_remove (GST_BIN (dbin), element);
2369       continue;
2370     }
2371
2372     /* check if we still accept the caps on the pad after setting
2373      * the element to READY */
2374     if (!gst_pad_query_accept_caps (sinkpad, caps)) {
2375       GstMessage *error_msg;
2376
2377       GST_WARNING_OBJECT (dbin, "Element %s does not accept caps",
2378           GST_ELEMENT_NAME (element));
2379
2380       remove_error_filter (dbin, element, &error_msg);
2381
2382       if (error_msg) {
2383         gchar *error_string = error_message_to_string (error_msg);
2384         g_string_append_printf (error_details,
2385             "Element %s does not accept caps:\n%s", GST_ELEMENT_NAME (element),
2386             error_string);
2387         gst_message_unref (error_msg);
2388         g_free (error_string);
2389       } else {
2390         g_string_append_printf (error_details,
2391             "Element %s does not accept caps", GST_ELEMENT_NAME (element));
2392       }
2393
2394       gst_element_set_state (element, GST_STATE_NULL);
2395       gst_object_unref (sinkpad);
2396       gst_bin_remove (GST_BIN (dbin), element);
2397       continue;
2398     }
2399
2400     gst_object_unref (sinkpad);
2401     GST_LOG_OBJECT (dbin, "linked on pad %s:%s", GST_DEBUG_PAD_NAME (pad));
2402
2403     CHAIN_MUTEX_LOCK (chain);
2404     delem = g_slice_new0 (GstDecodeElement);
2405     delem->element = gst_object_ref (element);
2406     delem->capsfilter = NULL;
2407     chain->elements = g_list_prepend (chain->elements, delem);
2408     chain->demuxer = is_demuxer_element (element);
2409     chain->adaptive_demuxer = is_adaptive_demuxer_element (element);
2410
2411     is_decoder = strstr (gst_element_factory_get_metadata (factory,
2412             GST_ELEMENT_METADATA_KLASS), "Decoder") != NULL;
2413
2414     /* For adaptive streaming demuxer we insert a multiqueue after
2415      * this demuxer.
2416      * Now for the case where we have a container stream inside these
2417      * buffers, another demuxer will be plugged and after this second
2418      * demuxer there will be a second multiqueue. This second multiqueue
2419      * will get smaller buffers and will be the one emitting buffering
2420      * messages.
2421      * If we don't have a container stream inside the fragment buffers,
2422      * we'll insert a multiqueue below right after the next element after
2423      * the adaptive streaming demuxer. This is going to be a parser or
2424      * decoder, and will output smaller buffers.
2425      */
2426     if (chain->parent && chain->parent->parent) {
2427       GstDecodeChain *parent_chain = chain->parent->parent;
2428
2429       if (parent_chain->adaptive_demuxer && (is_parser || is_decoder))
2430         chain->demuxer = TRUE;
2431     }
2432
2433     /* If we are configured to use buffering and there is no demuxer in the
2434      * chain, we still want a multiqueue, otherwise we will ignore the
2435      * use-buffering property. In that case, we will insert a multiqueue after
2436      * the parser or decoder - not elsewhere, otherwise we won't have
2437      * timestamps.
2438      */
2439
2440     if (!chain->parent && (is_parser || is_decoder) && dbin->use_buffering) {
2441       chain->demuxer = TRUE;
2442       if (is_decoder) {
2443         GST_WARNING_OBJECT (dbin,
2444             "Buffering messages used for decoded and non-parsed data");
2445       }
2446     }
2447
2448     CHAIN_MUTEX_UNLOCK (chain);
2449
2450     /* Set connection-speed property if needed */
2451     if (chain->demuxer) {
2452       GParamSpec *pspec;
2453
2454       if ((pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (element),
2455                   "connection-speed"))) {
2456         guint64 speed = dbin->connection_speed / 1000;
2457         gboolean wrong_type = FALSE;
2458
2459         if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_UINT) {
2460           GParamSpecUInt *pspecuint = G_PARAM_SPEC_UINT (pspec);
2461
2462           speed = CLAMP (speed, pspecuint->minimum, pspecuint->maximum);
2463         } else if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_INT) {
2464           GParamSpecInt *pspecint = G_PARAM_SPEC_INT (pspec);
2465
2466           speed = CLAMP (speed, pspecint->minimum, pspecint->maximum);
2467         } else if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_UINT64) {
2468           GParamSpecUInt64 *pspecuint = G_PARAM_SPEC_UINT64 (pspec);
2469
2470           speed = CLAMP (speed, pspecuint->minimum, pspecuint->maximum);
2471         } else if (G_PARAM_SPEC_TYPE (pspec) == G_TYPE_PARAM_INT64) {
2472           GParamSpecInt64 *pspecint = G_PARAM_SPEC_INT64 (pspec);
2473
2474           speed = CLAMP (speed, pspecint->minimum, pspecint->maximum);
2475         } else {
2476           GST_WARNING_OBJECT (dbin,
2477               "The connection speed property %" G_GUINT64_FORMAT " of type %s"
2478               " is not usefull not setting it", speed,
2479               g_type_name (G_PARAM_SPEC_TYPE (pspec)));
2480           wrong_type = TRUE;
2481         }
2482
2483         if (!wrong_type) {
2484           GST_DEBUG_OBJECT (dbin, "setting connection-speed=%" G_GUINT64_FORMAT
2485               " to demuxer element", speed);
2486
2487           g_object_set (element, "connection-speed", speed, NULL);
2488         }
2489       }
2490     }
2491
2492     /* try to configure the subtitle encoding property when we can */
2493     pspec = g_object_class_find_property (G_OBJECT_GET_CLASS (element),
2494         "subtitle-encoding");
2495     if (pspec && G_PARAM_SPEC_VALUE_TYPE (pspec) == G_TYPE_STRING) {
2496       SUBTITLE_LOCK (dbin);
2497       GST_DEBUG_OBJECT (dbin,
2498           "setting subtitle-encoding=%s to element", dbin->encoding);
2499       g_object_set (G_OBJECT (element), "subtitle-encoding", dbin->encoding,
2500           NULL);
2501       SUBTITLE_UNLOCK (dbin);
2502       subtitle = TRUE;
2503     } else {
2504       subtitle = FALSE;
2505     }
2506
2507     /* link this element further */
2508     to_connect = connect_element (dbin, delem, chain);
2509
2510     while (to_connect) {
2511       GstPad *opad = to_connect->data;
2512       gboolean expose_pad = FALSE;
2513       GstDecodeChain *new_chain;
2514       GstCaps *ocaps;
2515
2516       ocaps = get_pad_caps (opad);
2517       expose_pad =
2518           analyze_new_pad (dbin, delem->element, opad, ocaps, chain,
2519           &new_chain);
2520
2521       if (ocaps)
2522         gst_caps_unref (ocaps);
2523
2524       if (expose_pad) {
2525         PadExposeData *expose_data = g_new0 (PadExposeData, 1);
2526         expose_data->chain = new_chain;
2527         expose_data->pad = gst_object_ref (opad);
2528         to_expose = g_list_prepend (to_expose, expose_data);
2529       }
2530
2531       gst_object_unref (opad);
2532       to_connect = g_list_delete_link (to_connect, to_connect);
2533     }
2534     /* any pads left in to_expose are to be exposed */
2535
2536     /* Bring the element to the state of the parent */
2537
2538     /* First lock element's sinkpad stream lock so no data reaches
2539      * the possible new element added when caps are sent by element
2540      * while we're still sending sticky events */
2541     GST_PAD_STREAM_LOCK (sinkpad);
2542
2543     if ((gst_element_set_state (element,
2544                 GST_STATE_PAUSED)) == GST_STATE_CHANGE_FAILURE ||
2545         !send_sticky_events (dbin, pad)) {
2546       GstDecodeElement *dtmp = NULL;
2547       GstElement *tmp = NULL;
2548       GstMessage *error_msg;
2549
2550       GST_PAD_STREAM_UNLOCK (sinkpad);
2551
2552       GST_WARNING_OBJECT (dbin, "Couldn't set %s to PAUSED",
2553           GST_ELEMENT_NAME (element));
2554
2555       while (to_expose) {
2556         PadExposeData *expose_data = to_expose->data;
2557         gst_object_unref (expose_data->pad);
2558         g_free (expose_data);
2559         to_expose = g_list_delete_link (to_expose, to_expose);
2560       }
2561
2562       remove_error_filter (dbin, element, &error_msg);
2563
2564       if (error_msg) {
2565         gchar *error_string = error_message_to_string (error_msg);
2566         g_string_append_printf (error_details, "Couldn't set %s to PAUSED:\n%s",
2567             GST_ELEMENT_NAME (element), error_string);
2568         gst_message_unref (error_msg);
2569         g_free (error_string);
2570       } else {
2571         g_string_append_printf (error_details, "Couldn't set %s to PAUSED",
2572             GST_ELEMENT_NAME (element));
2573       }
2574
2575       /* Remove all elements in this chain that were just added. No
2576        * other thread could've added elements in the meantime */
2577       CHAIN_MUTEX_LOCK (chain);
2578       do {
2579         GList *l;
2580
2581         dtmp = chain->elements->data;
2582         tmp = dtmp->element;
2583
2584         /* Disconnect any signal handlers that might be connected
2585          * in connect_element() or analyze_pad() */
2586         if (dtmp->pad_added_id)
2587           g_signal_handler_disconnect (tmp, dtmp->pad_added_id);
2588         if (dtmp->pad_removed_id)
2589           g_signal_handler_disconnect (tmp, dtmp->pad_removed_id);
2590         if (dtmp->no_more_pads_id)
2591           g_signal_handler_disconnect (tmp, dtmp->no_more_pads_id);
2592
2593         for (l = chain->pending_pads; l;) {
2594           GstPendingPad *pp = l->data;
2595           GList *n;
2596
2597           if (GST_PAD_PARENT (pp->pad) != tmp) {
2598             l = l->next;
2599             continue;
2600           }
2601
2602           gst_pending_pad_free (pp);
2603
2604           /* Remove element from the list, update list head and go to the
2605            * next element in the list */
2606           n = l->next;
2607           chain->pending_pads = g_list_delete_link (chain->pending_pads, l);
2608           l = n;
2609         }
2610
2611         if (dtmp->capsfilter) {
2612           gst_bin_remove (GST_BIN (dbin), dtmp->capsfilter);
2613           gst_element_set_state (dtmp->capsfilter, GST_STATE_NULL);
2614           gst_object_unref (dtmp->capsfilter);
2615         }
2616
2617         gst_bin_remove (GST_BIN (dbin), tmp);
2618         gst_element_set_state (tmp, GST_STATE_NULL);
2619
2620         gst_object_unref (tmp);
2621         g_slice_free (GstDecodeElement, dtmp);
2622
2623         chain->elements = g_list_delete_link (chain->elements, chain->elements);
2624       } while (tmp != element);
2625       CHAIN_MUTEX_UNLOCK (chain);
2626
2627       continue;
2628     } else {
2629       /* Everything went well, the spice must flow now */
2630       GST_PAD_STREAM_UNLOCK (sinkpad);
2631     }
2632
2633     /* Remove error filter now, from now on we can't gracefully
2634      * handle errors of the element anymore */
2635     remove_error_filter (dbin, element, NULL);
2636
2637     /* Now let the bin handle the state */
2638     gst_element_set_locked_state (element, FALSE);
2639
2640     if (subtitle) {
2641       SUBTITLE_LOCK (dbin);
2642       /* we added the element now, add it to the list of subtitle-encoding
2643        * elements when we can set the property */
2644       dbin->subtitles = g_list_prepend (dbin->subtitles, element);
2645       SUBTITLE_UNLOCK (dbin);
2646     }
2647
2648     while (to_expose) {
2649       PadExposeData *expose_data = to_expose->data;
2650       GstCaps *ocaps;
2651
2652       ocaps = get_pad_caps (expose_data->pad);
2653       expose_pad (dbin, delem->element, expose_data->chain->current_pad,
2654           expose_data->pad, ocaps, expose_data->chain);
2655
2656       if (ocaps)
2657         gst_caps_unref (ocaps);
2658
2659       gst_object_unref (expose_data->pad);
2660       g_free (expose_data);
2661       to_expose = g_list_delete_link (to_expose, to_expose);
2662     }
2663
2664     res = TRUE;
2665     break;
2666   }
2667
2668 beach:
2669   if (mqpad)
2670     gst_object_unref (mqpad);
2671
2672   if (error_details)
2673     *deadend_details = g_string_free (error_details, (error_details->len == 0
2674             || res));
2675   else
2676     *deadend_details = NULL;
2677
2678   return res;
2679 }
2680
2681 static GstCaps *
2682 get_pad_caps (GstPad * pad)
2683 {
2684   GstCaps *caps;
2685
2686   /* first check the pad caps, if this is set, we are positively sure it is
2687    * fixed and exactly what the element will produce. */
2688   caps = gst_pad_get_current_caps (pad);
2689
2690   /* then use the getcaps function if we don't have caps. These caps might not
2691    * be fixed in some cases, in which case analyze_new_pad will set up a
2692    * notify::caps signal to continue autoplugging. */
2693   if (caps == NULL)
2694     caps = gst_pad_query_caps (pad, NULL);
2695
2696   return caps;
2697 }
2698
2699 /* Returns a list of pads that can be connected to already and
2700  * connects to pad-added and related signals */
2701 static GList *
2702 connect_element (GstDecodeBin * dbin, GstDecodeElement * delem,
2703     GstDecodeChain * chain)
2704 {
2705   GstElement *element = delem->element;
2706   GList *pads;
2707   gboolean dynamic = FALSE;
2708   GList *to_connect = NULL;
2709
2710   GST_DEBUG_OBJECT (dbin, "Attempting to connect element %s [chain:%p] further",
2711       GST_ELEMENT_NAME (element), chain);
2712
2713   /* 1. Loop over pad templates, grabbing existing pads along the way */
2714   for (pads = GST_ELEMENT_GET_CLASS (element)->padtemplates; pads;
2715       pads = g_list_next (pads)) {
2716     GstPadTemplate *templ = GST_PAD_TEMPLATE (pads->data);
2717     const gchar *templ_name;
2718
2719     /* we are only interested in source pads */
2720     if (GST_PAD_TEMPLATE_DIRECTION (templ) != GST_PAD_SRC)
2721       continue;
2722
2723     templ_name = GST_PAD_TEMPLATE_NAME_TEMPLATE (templ);
2724     GST_DEBUG_OBJECT (dbin, "got a source pad template %s", templ_name);
2725
2726     /* figure out what kind of pad this is */
2727     switch (GST_PAD_TEMPLATE_PRESENCE (templ)) {
2728       case GST_PAD_ALWAYS:
2729       {
2730         /* get the pad that we need to autoplug */
2731         GstPad *pad = gst_element_get_static_pad (element, templ_name);
2732
2733         if (pad) {
2734           GST_DEBUG_OBJECT (dbin, "got the pad for always template %s",
2735               templ_name);
2736           /* here is the pad, we need to autoplug it */
2737           to_connect = g_list_prepend (to_connect, pad);
2738         } else {
2739           /* strange, pad is marked as always but it's not
2740            * there. Fix the element */
2741           GST_WARNING_OBJECT (dbin,
2742               "could not get the pad for always template %s", templ_name);
2743         }
2744         break;
2745       }
2746       case GST_PAD_SOMETIMES:
2747       {
2748         /* try to get the pad to see if it is already created or
2749          * not */
2750         GstPad *pad = gst_element_get_static_pad (element, templ_name);
2751
2752         if (pad) {
2753           GST_DEBUG_OBJECT (dbin, "got the pad for sometimes template %s",
2754               templ_name);
2755           /* the pad is created, we need to autoplug it */
2756           to_connect = g_list_prepend (to_connect, pad);
2757         } else {
2758           GST_DEBUG_OBJECT (dbin,
2759               "did not get the sometimes pad of template %s", templ_name);
2760           /* we have an element that will create dynamic pads */
2761           dynamic = TRUE;
2762         }
2763         break;
2764       }
2765       case GST_PAD_REQUEST:
2766         /* ignore request pads */
2767         GST_DEBUG_OBJECT (dbin, "ignoring request padtemplate %s", templ_name);
2768         break;
2769     }
2770   }
2771
2772   /* 2. if there are more potential pads, connect to relevant signals */
2773   if (dynamic) {
2774     GST_LOG_OBJECT (dbin, "Adding signals to element %s in chain %p",
2775         GST_ELEMENT_NAME (element), chain);
2776     delem->pad_added_id = g_signal_connect (element, "pad-added",
2777         G_CALLBACK (pad_added_cb), chain);
2778     delem->pad_removed_id = g_signal_connect (element, "pad-removed",
2779         G_CALLBACK (pad_removed_cb), chain);
2780     delem->no_more_pads_id = g_signal_connect (element, "no-more-pads",
2781         G_CALLBACK (no_more_pads_cb), chain);
2782   }
2783
2784   /* 3. return all pads that can be connected to already */
2785
2786   return to_connect;
2787 }
2788
2789 /* expose_pad:
2790  *
2791  * Expose the given pad on the chain as a decoded pad.
2792  */
2793 static void
2794 expose_pad (GstDecodeBin * dbin, GstElement * src, GstDecodePad * dpad,
2795     GstPad * pad, GstCaps * caps, GstDecodeChain * chain)
2796 {
2797   GstPad *mqpad = NULL;
2798
2799   GST_DEBUG_OBJECT (dbin, "pad %s:%s, chain:%p",
2800       GST_DEBUG_PAD_NAME (pad), chain);
2801
2802   /* If this is the first pad for this chain, there are no other elements
2803    * and the source element is not the multiqueue we must link through the
2804    * multiqueue.
2805    *
2806    * This is the case if a demuxer directly exposed a raw pad.
2807    */
2808   if (chain->parent && !chain->elements && src != chain->parent->multiqueue) {
2809     GST_LOG_OBJECT (src, "connecting the pad through multiqueue");
2810
2811     decode_pad_set_target (dpad, NULL);
2812     if (!(mqpad = gst_decode_group_control_demuxer_pad (chain->parent, pad)))
2813       goto beach;
2814     pad = mqpad;
2815     decode_pad_set_target (dpad, pad);
2816   }
2817
2818   gst_decode_pad_activate (dpad, chain);
2819   chain->endpad = gst_object_ref (dpad);
2820   chain->endcaps = gst_caps_ref (caps);
2821
2822   EXPOSE_LOCK (dbin);
2823   if (dbin->decode_chain) {
2824     if (gst_decode_chain_is_complete (dbin->decode_chain)) {
2825       gst_decode_bin_expose (dbin);
2826     }
2827   }
2828   EXPOSE_UNLOCK (dbin);
2829
2830   if (mqpad)
2831     gst_object_unref (mqpad);
2832
2833 beach:
2834   return;
2835 }
2836
2837 /* check_upstream_seekable:
2838  *
2839  * Check if upstream is seekable.
2840  */
2841 static gboolean
2842 check_upstream_seekable (GstDecodeBin * dbin, GstPad * pad)
2843 {
2844   GstQuery *query;
2845   gint64 start = -1, stop = -1;
2846   gboolean seekable = FALSE;
2847
2848   query = gst_query_new_seeking (GST_FORMAT_BYTES);
2849   if (!gst_pad_peer_query (pad, query)) {
2850     GST_DEBUG_OBJECT (dbin, "seeking query failed");
2851     goto done;
2852   }
2853
2854   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
2855
2856   /* try harder to query upstream size if we didn't get it the first time */
2857   if (seekable && stop == -1) {
2858     GST_DEBUG_OBJECT (dbin, "doing duration query to fix up unset stop");
2859     gst_pad_peer_query_duration (pad, GST_FORMAT_BYTES, &stop);
2860   }
2861
2862   /* if upstream doesn't know the size, it's likely that it's not seekable in
2863    * practice even if it technically may be seekable */
2864   if (seekable && (start != 0 || stop <= start)) {
2865     GST_DEBUG_OBJECT (dbin, "seekable but unknown start/stop -> disable");
2866     seekable = FALSE;
2867   } else {
2868     GST_DEBUG_OBJECT (dbin, "upstream seekable: %d", seekable);
2869   }
2870
2871 done:
2872   gst_query_unref (query);
2873   return seekable;
2874 }
2875
2876 static void
2877 type_found (GstElement * typefind, guint probability,
2878     GstCaps * caps, GstDecodeBin * decode_bin)
2879 {
2880   GstPad *pad, *sink_pad;
2881   GstDecodeChain *chain;
2882
2883   GST_DEBUG_OBJECT (decode_bin, "typefind found caps %" GST_PTR_FORMAT, caps);
2884
2885   /* If the typefinder (but not something else) finds text/plain - i.e. that's
2886    * the top-level type of the file - then error out.
2887    */
2888   if (gst_structure_has_name (gst_caps_get_structure (caps, 0), "text/plain")) {
2889     GST_ELEMENT_ERROR (decode_bin, STREAM, WRONG_TYPE,
2890         (_("This appears to be a text file")),
2891         ("decodebin cannot decode plain text files"));
2892     goto exit;
2893   }
2894
2895   pad = gst_element_get_static_pad (typefind, "src");
2896   sink_pad = gst_element_get_static_pad (typefind, "sink");
2897
2898   /* need some lock here to prevent race with shutdown state change
2899    * which might yank away e.g. decode_chain while building stuff here.
2900    * In typical cases, STREAM_LOCK is held and handles that, it need not
2901    * be held (if called from a proxied setcaps), so grab it anyway */
2902   GST_PAD_STREAM_LOCK (sink_pad);
2903   /* FIXME: we can only deal with one type, we don't yet support dynamically changing
2904    * caps from the typefind element */
2905   if (decode_bin->have_type || decode_bin->decode_chain) {
2906   } else {
2907     decode_bin->have_type = TRUE;
2908
2909     decode_bin->decode_chain = gst_decode_chain_new (decode_bin, NULL, pad);
2910     chain = gst_decode_chain_ref (decode_bin->decode_chain);
2911
2912     if (analyze_new_pad (decode_bin, typefind, pad, caps,
2913             decode_bin->decode_chain, NULL))
2914       expose_pad (decode_bin, typefind, decode_bin->decode_chain->current_pad,
2915           pad, caps, decode_bin->decode_chain);
2916
2917     gst_decode_chain_unref (chain);
2918   }
2919
2920   GST_PAD_STREAM_UNLOCK (sink_pad);
2921   gst_object_unref (sink_pad);
2922   gst_object_unref (pad);
2923
2924 exit:
2925   return;
2926 }
2927
2928 static GstPadProbeReturn
2929 pad_event_cb (GstPad * pad, GstPadProbeInfo * info, gpointer data)
2930 {
2931   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
2932   GstPendingPad *ppad = (GstPendingPad *) data;
2933   GstDecodeChain *chain = ppad->chain;
2934   GstDecodeBin *dbin = chain->dbin;
2935
2936   g_assert (ppad);
2937   g_assert (chain);
2938   g_assert (dbin);
2939   switch (GST_EVENT_TYPE (event)) {
2940     case GST_EVENT_EOS:
2941       GST_DEBUG_OBJECT (pad, "Received EOS on a non final pad, this stream "
2942           "ended too early");
2943       chain->deadend = TRUE;
2944       chain->drained = TRUE;
2945       gst_object_replace ((GstObject **) & chain->current_pad, NULL);
2946       /* we don't set the endcaps because NULL endcaps means early EOS */
2947
2948       EXPOSE_LOCK (dbin);
2949       if (dbin->decode_chain)
2950         if (gst_decode_chain_is_complete (dbin->decode_chain))
2951           gst_decode_bin_expose (dbin);
2952       EXPOSE_UNLOCK (dbin);
2953       break;
2954     default:
2955       break;
2956   }
2957   return GST_PAD_PROBE_OK;
2958 }
2959
2960 static void
2961 pad_added_cb (GstElement * element, GstPad * pad, GstDecodeChain * chain)
2962 {
2963   GstCaps *caps;
2964   GstDecodeBin *dbin;
2965   GstDecodeChain *new_chain;
2966
2967   dbin = chain->dbin;
2968
2969   GST_DEBUG_OBJECT (pad, "pad added, chain:%p", chain);
2970   GST_PAD_STREAM_LOCK (pad);
2971   if (!gst_pad_is_active (pad)) {
2972     GST_PAD_STREAM_UNLOCK (pad);
2973     GST_DEBUG_OBJECT (pad, "Ignoring pad-added from a deactivated pad");
2974     return;
2975   }
2976
2977   caps = get_pad_caps (pad);
2978   if (analyze_new_pad (dbin, element, pad, caps, chain, &new_chain))
2979     expose_pad (dbin, element, new_chain->current_pad, pad, caps, new_chain);
2980   if (caps)
2981     gst_caps_unref (caps);
2982
2983   GST_PAD_STREAM_UNLOCK (pad);
2984 }
2985
2986 static GstPadProbeReturn
2987 sink_pad_event_probe (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
2988 {
2989   GstDecodeGroup *group = (GstDecodeGroup *) user_data;
2990   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
2991   GstPad *peer = gst_pad_get_peer (pad);
2992   GstPadProbeReturn proberet = GST_PAD_PROBE_OK;
2993
2994   GST_DEBUG_OBJECT (pad, "Got upstream event %s", GST_EVENT_TYPE_NAME (event));
2995
2996   if (peer == NULL) {
2997     GST_DEBUG_OBJECT (pad, "We are unlinked !");
2998     if (group->parent && group->parent->next_groups) {
2999       GstDecodeGroup *last_group =
3000           g_list_last (group->parent->next_groups)->data;
3001       GST_DEBUG_OBJECT (pad, "We could send the event to another group (%p)",
3002           last_group);
3003       /* Grab another sinkpad for that last group through which we will forward this event */
3004       if (last_group->reqpads) {
3005         GstPad *sinkpad = (GstPad *) last_group->reqpads->data;
3006         GstPad *otherpeer = gst_pad_get_peer (sinkpad);
3007         if (otherpeer) {
3008           GST_DEBUG_OBJECT (otherpeer, "Attempting to forward event");
3009           if (gst_pad_send_event (otherpeer, gst_event_ref (event))) {
3010             gst_event_unref (event);
3011             proberet = GST_PAD_PROBE_HANDLED;
3012           }
3013           gst_object_unref (otherpeer);
3014         }
3015       } else {
3016         GST_DEBUG_OBJECT (pad, "No request pads, can't forward event");
3017       }
3018     }
3019   } else {
3020     gst_object_unref (peer);
3021   }
3022
3023   return proberet;
3024 }
3025
3026 static GstPadProbeReturn
3027 sink_pad_query_probe (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
3028 {
3029   GstDecodeGroup *group = (GstDecodeGroup *) user_data;
3030   GstPad *peer = gst_pad_get_peer (pad);
3031   GstQuery *query = GST_PAD_PROBE_INFO_QUERY (info);
3032   GstPadProbeReturn proberet = GST_PAD_PROBE_OK;
3033
3034   GST_DEBUG_OBJECT (pad, "Got upstream query %s", GST_QUERY_TYPE_NAME (query));
3035
3036   if (peer == NULL) {
3037     GST_DEBUG_OBJECT (pad, "We are unlinked !");
3038     if (group->parent && group->parent->next_groups) {
3039       GstDecodeGroup *last_group =
3040           g_list_last (group->parent->next_groups)->data;
3041       GST_DEBUG_OBJECT (pad, "We could send the query to another group");
3042       /* Grab another sinkpad for that last group through which we will forward this event */
3043       if (last_group->reqpads) {
3044         GstPad *sinkpad = (GstPad *) last_group->reqpads->data;
3045         GstPad *otherpeer = gst_pad_get_peer (sinkpad);
3046         if (otherpeer) {
3047           GST_DEBUG_OBJECT (otherpeer, "Attempting to forward query");
3048           if (gst_pad_query (otherpeer, query)) {
3049             proberet = GST_PAD_PROBE_HANDLED;
3050           } else
3051             GST_DEBUG ("FAILURE");
3052           gst_object_unref (otherpeer);
3053         } else
3054           GST_DEBUG_OBJECT (sinkpad, "request pad not connected ??");
3055       } else
3056         GST_DEBUG_OBJECT (pad, "No request pads ???");
3057     }
3058   } else
3059     gst_object_unref (peer);
3060
3061   return proberet;
3062 }
3063
3064 static void
3065 pad_removed_cb (GstElement * element, GstPad * pad, GstDecodeChain * chain)
3066 {
3067   GList *l;
3068
3069   GST_LOG_OBJECT (pad, "pad removed, chain:%p", chain);
3070
3071   /* In fact, we don't have to do anything here, the active group will be
3072    * removed when the group's multiqueue is drained */
3073   CHAIN_MUTEX_LOCK (chain);
3074   for (l = chain->pending_pads; l; l = l->next) {
3075     GstPendingPad *ppad = l->data;
3076     GstPad *opad = ppad->pad;
3077
3078     if (pad == opad) {
3079       gst_pending_pad_free (ppad);
3080       chain->pending_pads = g_list_delete_link (chain->pending_pads, l);
3081       break;
3082     }
3083   }
3084   CHAIN_MUTEX_UNLOCK (chain);
3085 }
3086
3087 static void
3088 no_more_pads_cb (GstElement * element, GstDecodeChain * chain)
3089 {
3090   GstDecodeGroup *group = NULL;
3091
3092   GST_LOG_OBJECT (element, "got no more pads");
3093
3094   CHAIN_MUTEX_LOCK (chain);
3095   if (!chain->elements
3096       || ((GstDecodeElement *) chain->elements->data)->element != element) {
3097     GST_LOG_OBJECT (chain->dbin, "no-more-pads from old chain element '%s'",
3098         GST_OBJECT_NAME (element));
3099     CHAIN_MUTEX_UNLOCK (chain);
3100     return;
3101   } else if (!chain->demuxer) {
3102     GST_LOG_OBJECT (chain->dbin, "no-more-pads from a non-demuxer element '%s'",
3103         GST_OBJECT_NAME (element));
3104     CHAIN_MUTEX_UNLOCK (chain);
3105     return;
3106   }
3107
3108   /* when we received no_more_pads, we can complete the pads of the chain */
3109   if (!chain->next_groups && chain->active_group) {
3110     group = chain->active_group;
3111   } else if (chain->next_groups) {
3112     GList *iter;
3113     for (iter = chain->next_groups; iter; iter = g_list_next (iter)) {
3114       group = iter->data;
3115       if (!group->no_more_pads)
3116         break;
3117     }
3118   }
3119   if (!group) {
3120     GST_ERROR_OBJECT (chain->dbin, "can't find group for element");
3121     CHAIN_MUTEX_UNLOCK (chain);
3122     return;
3123   }
3124
3125   GST_DEBUG_OBJECT (element, "Setting group %p to complete", group);
3126
3127   group->no_more_pads = TRUE;
3128   /* this group has prerolled enough to not need more pads,
3129    * we can probably set its buffering state to playing now */
3130   GST_DEBUG_OBJECT (group->dbin, "Setting group %p multiqueue to "
3131       "'playing' buffering mode", group);
3132   decodebin_set_queue_size (group->dbin, group->multiqueue, FALSE,
3133       (group->parent ? group->parent->seekable : TRUE));
3134   CHAIN_MUTEX_UNLOCK (chain);
3135
3136   EXPOSE_LOCK (chain->dbin);
3137   if (chain->dbin->decode_chain) {
3138     if (gst_decode_chain_is_complete (chain->dbin->decode_chain)) {
3139       gst_decode_bin_expose (chain->dbin);
3140     }
3141   }
3142   EXPOSE_UNLOCK (chain->dbin);
3143 }
3144
3145 static void
3146 caps_notify_cb (GstPad * pad, GParamSpec * unused, GstDecodeChain * chain)
3147 {
3148   GstElement *element;
3149   GList *l;
3150
3151   GST_LOG_OBJECT (pad, "Notified caps for pad %s:%s", GST_DEBUG_PAD_NAME (pad));
3152
3153   /* Disconnect this; if we still need it, we'll reconnect to this in
3154    * analyze_new_pad */
3155   element = GST_ELEMENT_CAST (gst_pad_get_parent (pad));
3156
3157   CHAIN_MUTEX_LOCK (chain);
3158   for (l = chain->pending_pads; l; l = l->next) {
3159     GstPendingPad *ppad = l->data;
3160     if (ppad->pad == pad) {
3161       gst_pending_pad_free (ppad);
3162       chain->pending_pads = g_list_delete_link (chain->pending_pads, l);
3163       break;
3164     }
3165   }
3166   CHAIN_MUTEX_UNLOCK (chain);
3167
3168   pad_added_cb (element, pad, chain);
3169
3170   gst_object_unref (element);
3171 }
3172
3173 /* Decide whether an element is a demuxer based on the
3174  * klass and number/type of src pad templates it has */
3175 static gboolean
3176 is_demuxer_element (GstElement * srcelement)
3177 {
3178   GstElementFactory *srcfactory;
3179   GstElementClass *elemclass;
3180   GList *walk;
3181   const gchar *klass;
3182   gint potential_src_pads = 0;
3183
3184   srcfactory = gst_element_get_factory (srcelement);
3185   klass =
3186       gst_element_factory_get_metadata (srcfactory, GST_ELEMENT_METADATA_KLASS);
3187
3188   /* Can't be a demuxer unless it has Demux in the klass name */
3189   if (!strstr (klass, "Demux"))
3190     return FALSE;
3191
3192   /* Walk the src pad templates and count how many the element
3193    * might produce */
3194   elemclass = GST_ELEMENT_GET_CLASS (srcelement);
3195
3196   walk = gst_element_class_get_pad_template_list (elemclass);
3197   while (walk != NULL) {
3198     GstPadTemplate *templ;
3199
3200     templ = (GstPadTemplate *) walk->data;
3201     if (GST_PAD_TEMPLATE_DIRECTION (templ) == GST_PAD_SRC) {
3202       switch (GST_PAD_TEMPLATE_PRESENCE (templ)) {
3203         case GST_PAD_ALWAYS:
3204         case GST_PAD_SOMETIMES:
3205           if (strstr (GST_PAD_TEMPLATE_NAME_TEMPLATE (templ), "%"))
3206             potential_src_pads += 2;    /* Might make multiple pads */
3207           else
3208             potential_src_pads += 1;
3209           break;
3210         case GST_PAD_REQUEST:
3211           potential_src_pads += 2;
3212           break;
3213       }
3214     }
3215     walk = g_list_next (walk);
3216   }
3217
3218   if (potential_src_pads < 2)
3219     return FALSE;
3220
3221   return TRUE;
3222 }
3223
3224 static gboolean
3225 is_adaptive_demuxer_element (GstElement * srcelement)
3226 {
3227   GstElementFactory *srcfactory;
3228   const gchar *klass;
3229
3230   srcfactory = gst_element_get_factory (srcelement);
3231   klass =
3232       gst_element_factory_get_metadata (srcfactory, GST_ELEMENT_METADATA_KLASS);
3233
3234   /* Can't be a demuxer unless it has Demux in the klass name */
3235   if (!strstr (klass, "Demux") || !strstr (klass, "Adaptive"))
3236     return FALSE;
3237
3238   return TRUE;
3239 }
3240
3241 /* Returns TRUE if the caps are compatible with the caps specified in the 'caps'
3242  * property (which by default are the raw caps)
3243  *
3244  * The decodebin_lock should be taken !
3245  */
3246 static gboolean
3247 are_final_caps (GstDecodeBin * dbin, GstCaps * caps)
3248 {
3249   gboolean res;
3250
3251   GST_LOG_OBJECT (dbin, "Checking with caps %" GST_PTR_FORMAT, caps);
3252
3253   /* lock for getting the caps */
3254   GST_OBJECT_LOCK (dbin);
3255   res = gst_caps_is_subset (caps, dbin->caps);
3256   GST_OBJECT_UNLOCK (dbin);
3257
3258   GST_LOG_OBJECT (dbin, "Caps are %sfinal caps", res ? "" : "not ");
3259
3260   return res;
3261 }
3262
3263 /* gst_decode_bin_reset_buffering:
3264  *
3265  * Enables buffering on the last multiqueue of each group only,
3266  * disabling the rest
3267  *
3268  */
3269 static void
3270 gst_decode_bin_reset_buffering (GstDecodeBin * dbin)
3271 {
3272   if (!dbin->use_buffering)
3273     return;
3274
3275   GST_DEBUG_OBJECT (dbin, "Reseting multiqueues buffering");
3276   if (dbin->decode_chain) {
3277     CHAIN_MUTEX_LOCK (dbin->decode_chain);
3278     gst_decode_chain_reset_buffering (dbin->decode_chain);
3279     CHAIN_MUTEX_UNLOCK (dbin->decode_chain);
3280   }
3281 }
3282
3283 /****
3284  * GstDecodeChain functions
3285  ****/
3286
3287 static gboolean
3288 gst_decode_chain_reset_buffering (GstDecodeChain * chain)
3289 {
3290   GstDecodeGroup *group;
3291
3292   group = chain->active_group;
3293   GST_LOG_OBJECT (chain->dbin, "Resetting chain %p buffering, active group: %p",
3294       chain, group);
3295   if (group) {
3296     return gst_decode_group_reset_buffering (group);
3297   }
3298   return FALSE;
3299 }
3300
3301 /* gst_decode_chain_get_current_group:
3302  *
3303  * Returns the current group of this chain, to which
3304  * new chains should be attached or NULL if the last
3305  * group didn't have no-more-pads.
3306  *
3307  * Not MT-safe: Call with parent chain lock!
3308  */
3309 static GstDecodeGroup *
3310 gst_decode_chain_get_current_group (GstDecodeChain * chain)
3311 {
3312   GstDecodeGroup *group;
3313
3314   if (!chain->next_groups && chain->active_group
3315       && chain->active_group->overrun && !chain->active_group->no_more_pads) {
3316     GST_WARNING_OBJECT (chain->dbin,
3317         "Currently active group %p is exposed"
3318         " and wants to add a new pad without having signaled no-more-pads",
3319         chain->active_group);
3320     return NULL;
3321   }
3322
3323   if (chain->next_groups && (group = chain->next_groups->data) && group->overrun
3324       && !group->no_more_pads) {
3325     GST_WARNING_OBJECT (chain->dbin,
3326         "Currently newest pending group %p "
3327         "had overflow but didn't signal no-more-pads", group);
3328     return NULL;
3329   }
3330
3331   /* Now we know that we can really return something useful */
3332   if (!chain->active_group) {
3333     chain->active_group = group = gst_decode_group_new (chain->dbin, chain);
3334   } else if (!chain->active_group->overrun
3335       && !chain->active_group->no_more_pads) {
3336     group = chain->active_group;
3337   } else {
3338     GList *iter;
3339     group = NULL;
3340     for (iter = chain->next_groups; iter; iter = g_list_next (iter)) {
3341       GstDecodeGroup *next_group = iter->data;
3342
3343       if (!next_group->overrun && !next_group->no_more_pads) {
3344         group = next_group;
3345         break;
3346       }
3347     }
3348   }
3349   if (!group) {
3350     group = gst_decode_group_new (chain->dbin, chain);
3351     chain->next_groups = g_list_append (chain->next_groups, group);
3352   }
3353
3354   return group;
3355 }
3356
3357 static void gst_decode_group_free_internal (GstDecodeGroup * group,
3358     gboolean hide);
3359
3360 static void
3361 gst_decode_chain_unref (GstDecodeChain * chain)
3362 {
3363   if (g_atomic_int_dec_and_test (&chain->refs)) {
3364     g_mutex_clear (&chain->lock);
3365     g_slice_free (GstDecodeChain, chain);
3366   }
3367 }
3368
3369 static GstDecodeChain *
3370 gst_decode_chain_ref (GstDecodeChain * chain)
3371 {
3372   g_atomic_int_inc (&chain->refs);
3373   return chain;
3374 }
3375
3376 static void
3377 gst_decode_chain_free_internal (GstDecodeChain * chain, gboolean hide)
3378 {
3379   GList *l, *set_to_null = NULL;
3380
3381   CHAIN_MUTEX_LOCK (chain);
3382
3383   GST_DEBUG_OBJECT (chain->dbin, "%s chain %p", (hide ? "Hiding" : "Freeing"),
3384       chain);
3385
3386   if (chain->active_group) {
3387     gst_decode_group_free_internal (chain->active_group, hide);
3388     if (!hide)
3389       chain->active_group = NULL;
3390   }
3391
3392   for (l = chain->next_groups; l; l = l->next) {
3393     gst_decode_group_free_internal ((GstDecodeGroup *) l->data, hide);
3394     if (!hide)
3395       l->data = NULL;
3396   }
3397   if (!hide) {
3398     g_list_free (chain->next_groups);
3399     chain->next_groups = NULL;
3400   }
3401
3402   if (!hide) {
3403     for (l = chain->old_groups; l; l = l->next) {
3404       GstDecodeGroup *group = l->data;
3405
3406       gst_decode_group_free (group);
3407     }
3408     g_list_free (chain->old_groups);
3409     chain->old_groups = NULL;
3410   }
3411
3412   for (l = chain->pending_pads; l; l = l->next) {
3413     GstPendingPad *ppad = l->data;
3414     gst_pending_pad_free (ppad);
3415     l->data = NULL;
3416   }
3417   g_list_free (chain->pending_pads);
3418   chain->pending_pads = NULL;
3419
3420   for (l = chain->elements; l; l = l->next) {
3421     GstDecodeElement *delem = l->data;
3422     GstElement *element = delem->element;
3423
3424     if (delem->pad_added_id)
3425       g_signal_handler_disconnect (element, delem->pad_added_id);
3426     delem->pad_added_id = 0;
3427     if (delem->pad_removed_id)
3428       g_signal_handler_disconnect (element, delem->pad_removed_id);
3429     delem->pad_removed_id = 0;
3430     if (delem->no_more_pads_id)
3431       g_signal_handler_disconnect (element, delem->no_more_pads_id);
3432     delem->no_more_pads_id = 0;
3433
3434     if (delem->capsfilter) {
3435       if (GST_OBJECT_PARENT (delem->capsfilter) ==
3436           GST_OBJECT_CAST (chain->dbin))
3437         gst_bin_remove (GST_BIN_CAST (chain->dbin), delem->capsfilter);
3438       if (!hide) {
3439         set_to_null =
3440             g_list_append (set_to_null, gst_object_ref (delem->capsfilter));
3441       }
3442     }
3443
3444     if (GST_OBJECT_PARENT (element) == GST_OBJECT_CAST (chain->dbin))
3445       gst_bin_remove (GST_BIN_CAST (chain->dbin), element);
3446     if (!hide) {
3447       set_to_null = g_list_append (set_to_null, gst_object_ref (element));
3448     }
3449
3450     SUBTITLE_LOCK (chain->dbin);
3451     /* remove possible subtitle element */
3452     chain->dbin->subtitles = g_list_remove (chain->dbin->subtitles, element);
3453     SUBTITLE_UNLOCK (chain->dbin);
3454
3455     if (!hide) {
3456       if (delem->capsfilter) {
3457         gst_object_unref (delem->capsfilter);
3458         delem->capsfilter = NULL;
3459       }
3460
3461       gst_object_unref (element);
3462       l->data = NULL;
3463
3464       g_slice_free (GstDecodeElement, delem);
3465     }
3466   }
3467   if (!hide) {
3468     g_list_free (chain->elements);
3469     chain->elements = NULL;
3470   }
3471
3472   if (chain->endpad) {
3473     if (chain->endpad->exposed) {
3474       gst_element_remove_pad (GST_ELEMENT_CAST (chain->dbin),
3475           GST_PAD_CAST (chain->endpad));
3476     }
3477
3478     decode_pad_set_target (chain->endpad, NULL);
3479     chain->endpad->exposed = FALSE;
3480     if (!hide) {
3481       gst_object_unref (chain->endpad);
3482       chain->endpad = NULL;
3483     }
3484   }
3485
3486   if (!hide && chain->current_pad) {
3487     gst_object_unref (chain->current_pad);
3488     chain->current_pad = NULL;
3489   }
3490
3491   if (chain->pad) {
3492     gst_object_unref (chain->pad);
3493     chain->pad = NULL;
3494   }
3495
3496   if (chain->endcaps) {
3497     gst_caps_unref (chain->endcaps);
3498     chain->endcaps = NULL;
3499   }
3500   g_free (chain->deadend_details);
3501   chain->deadend_details = NULL;
3502
3503   GST_DEBUG_OBJECT (chain->dbin, "%s chain %p", (hide ? "Hidden" : "Freed"),
3504       chain);
3505   CHAIN_MUTEX_UNLOCK (chain);
3506
3507   while (set_to_null) {
3508     GstElement *element = set_to_null->data;
3509     set_to_null = g_list_delete_link (set_to_null, set_to_null);
3510     gst_element_set_state (element, GST_STATE_NULL);
3511     gst_object_unref (element);
3512   }
3513
3514   if (!hide)
3515     gst_decode_chain_unref (chain);
3516 }
3517
3518 /* gst_decode_chain_free:
3519  *
3520  * Completely frees and removes the chain and all
3521  * child groups from decodebin.
3522  *
3523  * MT-safe, don't hold the chain lock or any child chain's lock
3524  * when calling this!
3525  */
3526 static void
3527 gst_decode_chain_free (GstDecodeChain * chain)
3528 {
3529   gst_decode_chain_free_internal (chain, FALSE);
3530 }
3531
3532 /* gst_decode_chain_new:
3533  *
3534  * Creates a new decode chain and initializes it.
3535  *
3536  * It's up to the caller to add it to the list of child chains of
3537  * a group!
3538  */
3539 static GstDecodeChain *
3540 gst_decode_chain_new (GstDecodeBin * dbin, GstDecodeGroup * parent,
3541     GstPad * pad)
3542 {
3543   GstDecodeChain *chain = g_slice_new0 (GstDecodeChain);
3544
3545   GST_DEBUG_OBJECT (dbin, "Creating new chain %p with parent group %p", chain,
3546       parent);
3547
3548   chain->dbin = dbin;
3549   chain->parent = parent;
3550   chain->refs = 1;
3551   g_mutex_init (&chain->lock);
3552   chain->pad = gst_object_ref (pad);
3553
3554   return chain;
3555 }
3556
3557 /****
3558  * GstDecodeGroup functions
3559  ****/
3560
3561 /* The overrun callback is used to expose groups that have not yet had their
3562  * no_more_pads called while the (large) multiqueue overflowed. When this
3563  * happens we must assume that the no_more_pads will not arrive anymore and we
3564  * must expose the pads that we have.
3565  */
3566 static void
3567 multi_queue_overrun_cb (GstElement * queue, GstDecodeGroup * group)
3568 {
3569   GstDecodeBin *dbin;
3570
3571   dbin = group->dbin;
3572
3573   GST_LOG_OBJECT (dbin, "multiqueue '%s' (%p) is full", GST_OBJECT_NAME (queue),
3574       queue);
3575
3576   group->overrun = TRUE;
3577   /* this group has prerolled enough to not need more pads,
3578    * we can probably set its buffering state to playing now */
3579   GST_DEBUG_OBJECT (group->dbin, "Setting group %p multiqueue to "
3580       "'playing' buffering mode", group);
3581   decodebin_set_queue_size (group->dbin, group->multiqueue, FALSE,
3582       (group->parent ? group->parent->seekable : TRUE));
3583
3584   /* FIXME: We should make sure that everything gets exposed now
3585    * even if child chains are not complete because the will never
3586    * be complete! Ignore any non-complete chains when exposing
3587    * and never expose them later
3588    */
3589
3590   EXPOSE_LOCK (dbin);
3591   if (dbin->decode_chain) {
3592     if (gst_decode_chain_is_complete (dbin->decode_chain)) {
3593       if (!gst_decode_bin_expose (dbin))
3594         GST_WARNING_OBJECT (dbin, "Couldn't expose group");
3595     }
3596   }
3597   EXPOSE_UNLOCK (dbin);
3598 }
3599
3600 static void
3601 gst_decode_group_free_internal (GstDecodeGroup * group, gboolean hide)
3602 {
3603   GList *l;
3604
3605   GST_DEBUG_OBJECT (group->dbin, "%s group %p", (hide ? "Hiding" : "Freeing"),
3606       group);
3607
3608   if (!hide) {
3609     for (l = group->demuxer_pad_probe_ids; l != NULL; l = l->next) {
3610       GstDemuxerPad *demuxer_pad = l->data;
3611       GstPad *sinkpad = g_weak_ref_get (&demuxer_pad->weakPad);
3612
3613       if (sinkpad != NULL) {
3614         gst_pad_remove_probe (sinkpad, demuxer_pad->event_probe_id);
3615         gst_pad_remove_probe (sinkpad, demuxer_pad->query_probe_id);
3616         g_weak_ref_clear (&demuxer_pad->weakPad);
3617         gst_object_unref (sinkpad);
3618       }
3619       g_free (demuxer_pad);
3620     }
3621     g_list_free (group->demuxer_pad_probe_ids);
3622     group->demuxer_pad_probe_ids = NULL;
3623   }
3624
3625   for (l = group->children; l; l = l->next) {
3626     GstDecodeChain *chain = (GstDecodeChain *) l->data;
3627
3628     gst_decode_chain_free_internal (chain, hide);
3629     if (!hide)
3630       l->data = NULL;
3631   }
3632   if (!hide) {
3633     g_list_free (group->children);
3634     group->children = NULL;
3635   }
3636
3637   if (!hide) {
3638     for (l = group->reqpads; l; l = l->next) {
3639       GstPad *pad = l->data;
3640
3641       gst_element_release_request_pad (group->multiqueue, pad);
3642       gst_object_unref (pad);
3643       l->data = NULL;
3644     }
3645     g_list_free (group->reqpads);
3646     group->reqpads = NULL;
3647   }
3648
3649   if (group->multiqueue) {
3650     if (group->overrunsig) {
3651       g_signal_handler_disconnect (group->multiqueue, group->overrunsig);
3652       group->overrunsig = 0;
3653     }
3654
3655     if (GST_OBJECT_PARENT (group->multiqueue) == GST_OBJECT_CAST (group->dbin))
3656       gst_bin_remove (GST_BIN_CAST (group->dbin), group->multiqueue);
3657     if (!hide) {
3658       gst_element_set_state (group->multiqueue, GST_STATE_NULL);
3659       gst_object_unref (group->multiqueue);
3660       group->multiqueue = NULL;
3661     }
3662   }
3663
3664   GST_DEBUG_OBJECT (group->dbin, "%s group %p", (hide ? "Hid" : "Freed"),
3665       group);
3666   if (!hide)
3667     g_slice_free (GstDecodeGroup, group);
3668 }
3669
3670 /* gst_decode_group_free:
3671  *
3672  * Completely frees and removes the decode group and all
3673  * it's children.
3674  *
3675  * Never call this from any streaming thread!
3676  *
3677  * Not MT-safe, call with parent's chain lock!
3678  */
3679 static void
3680 gst_decode_group_free (GstDecodeGroup * group)
3681 {
3682   gst_decode_group_free_internal (group, FALSE);
3683 }
3684
3685 /* gst_decode_group_hide:
3686  *
3687  * Hide the decode group only, this means that
3688  * all child endpads are removed from decodebin
3689  * and all signals are unconnected.
3690  *
3691  * No element is set to NULL state and completely
3692  * unrefed here.
3693  *
3694  * Can be called from streaming threads.
3695  *
3696  * Not MT-safe, call with parent's chain lock!
3697  */
3698 static void
3699 gst_decode_group_hide (GstDecodeGroup * group)
3700 {
3701   gst_decode_group_free_internal (group, TRUE);
3702 }
3703
3704 /* gst_decode_chain_free_hidden_groups:
3705  *
3706  * Frees any decode groups that were hidden previously.
3707  * This allows keeping memory use from ballooning when
3708  * switching chains repeatedly.
3709  *
3710  * A new throwaway thread will be created to free the
3711  * groups, so any delay does not block the setup of a
3712  * new group.
3713  *
3714  * Not MT-safe, call with parent's chain lock!
3715  */
3716 static void
3717 gst_decode_chain_free_hidden_groups (GList * old_groups)
3718 {
3719   GList *l;
3720
3721   for (l = old_groups; l; l = l->next) {
3722     GstDecodeGroup *group = l->data;
3723
3724     gst_decode_group_free (group);
3725   }
3726   g_list_free (old_groups);
3727 }
3728
3729 static void
3730 gst_decode_chain_start_free_hidden_groups_thread (GstDecodeChain * chain)
3731 {
3732   GThread *thread;
3733   GError *error = NULL;
3734   GList *old_groups;
3735   GstDecodeBin *dbin = chain->dbin;
3736
3737   old_groups = chain->old_groups;
3738   if (!old_groups)
3739     return;
3740
3741   /* If we already have a thread running, wait for it to finish */
3742   g_mutex_lock (&dbin->cleanup_lock);
3743   if (dbin->cleanup_thread) {
3744     g_thread_join (dbin->cleanup_thread);
3745     dbin->cleanup_thread = NULL;
3746   }
3747
3748   chain->old_groups = NULL;
3749
3750   if (dbin->shutdown) {
3751     /* If we're shutting down, add the groups to be cleaned up in the
3752      * state change handler (which *is* another thread). Also avoids
3753      * playing racy games with the state change handler */
3754     dbin->cleanup_groups = g_list_concat (dbin->cleanup_groups, old_groups);
3755     g_mutex_unlock (&dbin->cleanup_lock);
3756     return;
3757   }
3758
3759   thread = g_thread_try_new ("free-hidden-groups",
3760       (GThreadFunc) gst_decode_chain_free_hidden_groups, old_groups, &error);
3761   if (!thread || error) {
3762     GST_ERROR ("Failed to start free-hidden-groups thread: %s",
3763         error ? error->message : "unknown reason");
3764     g_clear_error (&error);
3765     chain->old_groups = old_groups;
3766     g_mutex_unlock (&dbin->cleanup_lock);
3767     return;
3768   }
3769
3770   dbin->cleanup_thread = thread;
3771   g_mutex_unlock (&dbin->cleanup_lock);
3772
3773   GST_DEBUG_OBJECT (chain->dbin, "Started free-hidden-groups thread");
3774 }
3775
3776 static void
3777 decodebin_set_queue_size (GstDecodeBin * dbin, GstElement * multiqueue,
3778     gboolean preroll, gboolean seekable)
3779 {
3780   gboolean use_buffering;
3781
3782   /* get the current config from the multiqueue */
3783   g_object_get (multiqueue, "use-buffering", &use_buffering, NULL);
3784
3785   decodebin_set_queue_size_full (dbin, multiqueue, use_buffering, preroll,
3786       seekable);
3787 }
3788
3789 /* configure queue sizes, this depends on the buffering method and if we are
3790  * playing or prerolling. */
3791 static void
3792 decodebin_set_queue_size_full (GstDecodeBin * dbin, GstElement * multiqueue,
3793     gboolean use_buffering, gboolean preroll, gboolean seekable)
3794 {
3795   guint max_bytes, max_buffers;
3796   guint64 max_time;
3797
3798   GST_DEBUG_OBJECT (multiqueue, "use buffering %d", use_buffering);
3799
3800   if (preroll || use_buffering) {
3801     /* takes queue limits, initially we only queue up up to the max bytes limit,
3802      * with a default of 2MB. we use the same values for buffering mode. */
3803     if (preroll || (max_bytes = dbin->max_size_bytes) == 0)
3804       max_bytes = AUTO_PREROLL_SIZE_BYTES;
3805     if (preroll || (max_buffers = dbin->max_size_buffers) == 0)
3806       max_buffers = AUTO_PREROLL_SIZE_BUFFERS;
3807     if (preroll || (max_time = dbin->max_size_time) == 0) {
3808       if (dbin->use_buffering && !preroll)
3809         max_time = 5 * GST_SECOND;
3810       else
3811         max_time = seekable ? AUTO_PREROLL_SEEKABLE_SIZE_TIME :
3812             AUTO_PREROLL_NOT_SEEKABLE_SIZE_TIME;
3813     }
3814   } else {
3815     /* update runtime limits. At runtime, we try to keep the amount of buffers
3816      * in the queues as low as possible (but at least 5 buffers). */
3817     if (dbin->use_buffering)
3818       max_bytes = 0;
3819     else if ((max_bytes = dbin->max_size_bytes) == 0)
3820       max_bytes = AUTO_PLAY_SIZE_BYTES;
3821     if ((max_buffers = dbin->max_size_buffers) == 0)
3822       max_buffers = AUTO_PLAY_SIZE_BUFFERS;
3823     /* this is a multiqueue with disabled buffering, don't limit max_time */
3824     if (dbin->use_buffering)
3825       max_time = 0;
3826     else if ((max_time = dbin->max_size_time) == 0)
3827       max_time = AUTO_PLAY_SIZE_TIME;
3828   }
3829
3830   GST_DEBUG_OBJECT (multiqueue, "setting limits %u bytes, %u buffers, "
3831       "%" G_GUINT64_FORMAT " time", max_bytes, max_buffers, max_time);
3832   g_object_set (multiqueue,
3833       "max-size-bytes", max_bytes, "max-size-time", max_time,
3834       "max-size-buffers", max_buffers, NULL);
3835 }
3836
3837 /* gst_decode_group_new:
3838  * @dbin: Parent decodebin
3839  * @parent: Parent chain or %NULL
3840  *
3841  * Creates a new GstDecodeGroup. It is up to the caller to add it to the list
3842  * of groups.
3843  */
3844 static GstDecodeGroup *
3845 gst_decode_group_new (GstDecodeBin * dbin, GstDecodeChain * parent)
3846 {
3847   GstDecodeGroup *group = g_slice_new0 (GstDecodeGroup);
3848   GstElement *mq;
3849   gboolean seekable;
3850
3851   GST_DEBUG_OBJECT (dbin, "Creating new group %p with parent chain %p", group,
3852       parent);
3853
3854   group->dbin = dbin;
3855   group->parent = parent;
3856
3857 #ifdef TIZEN_FEATURE_TRUSTZONE
3858   /*tzmultiqueue patch : when this flag is set to TRUE, we will use tzmultiqueue instead of multiqueue element in pipeline*/
3859   if (dbin->use_trustzone) {
3860     GST_DEBUG_OBJECT (dbin, "decodebin2 use tzmultiqueue");
3861     mq = group->multiqueue = gst_element_factory_make ("tzmultiqueue", NULL);
3862   }
3863   else
3864 #endif
3865   mq = group->multiqueue = gst_element_factory_make ("multiqueue", NULL);
3866   if (G_UNLIKELY (!group->multiqueue))
3867     goto missing_multiqueue;
3868
3869   /* configure queue sizes for preroll */
3870   seekable = FALSE;
3871   if (parent && parent->demuxer) {
3872     GstElement *element =
3873         ((GstDecodeElement *) parent->elements->data)->element;
3874     GstPad *pad = gst_element_get_static_pad (element, "sink");
3875     if (pad) {
3876       seekable = parent->seekable = check_upstream_seekable (dbin, pad);
3877       gst_object_unref (pad);
3878     }
3879   }
3880   decodebin_set_queue_size_full (dbin, mq, FALSE, TRUE, seekable);
3881
3882   group->overrunsig = g_signal_connect (mq, "overrun",
3883       G_CALLBACK (multi_queue_overrun_cb), group);
3884   group->demuxer_pad_probe_ids = NULL;
3885
3886   gst_element_set_state (mq, GST_STATE_PAUSED);
3887   gst_bin_add (GST_BIN (dbin), gst_object_ref (mq));
3888
3889   return group;
3890
3891   /* ERRORS */
3892 missing_multiqueue:
3893   {
3894     gst_element_post_message (GST_ELEMENT_CAST (dbin),
3895         gst_missing_element_message_new (GST_ELEMENT_CAST (dbin),
3896             "multiqueue"));
3897     GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL), ("no multiqueue!"));
3898     g_slice_free (GstDecodeGroup, group);
3899     return NULL;
3900   }
3901 }
3902
3903 /* gst_decode_group_control_demuxer_pad
3904  *
3905  * Adds a new demuxer srcpad to the given group.
3906  *
3907  * Returns the srcpad of the multiqueue corresponding the given pad.
3908  * Returns NULL if there was an error.
3909  */
3910 static GstPad *
3911 gst_decode_group_control_demuxer_pad (GstDecodeGroup * group, GstPad * pad)
3912 {
3913   GstDecodeBin *dbin;
3914   GstDemuxerPad *demuxer_pad;
3915   GstPad *srcpad, *sinkpad;
3916   GstIterator *it = NULL;
3917   GValue item = { 0, };
3918
3919   dbin = group->dbin;
3920
3921   GST_LOG_OBJECT (dbin, "group:%p pad %s:%s", group, GST_DEBUG_PAD_NAME (pad));
3922
3923   srcpad = NULL;
3924
3925   if (G_UNLIKELY (!group->multiqueue))
3926     return NULL;
3927
3928   if (!(sinkpad = gst_element_get_request_pad (group->multiqueue, "sink_%u"))) {
3929     GST_ERROR_OBJECT (dbin, "Couldn't get sinkpad from multiqueue");
3930     return NULL;
3931   }
3932
3933   if ((gst_pad_link_full (pad, sinkpad,
3934               GST_PAD_LINK_CHECK_NOTHING) != GST_PAD_LINK_OK)) {
3935     GST_ERROR_OBJECT (dbin, "Couldn't link demuxer and multiqueue");
3936     goto error;
3937   }
3938
3939   it = gst_pad_iterate_internal_links (sinkpad);
3940
3941   if (!it || (gst_iterator_next (it, &item)) != GST_ITERATOR_OK
3942       || ((srcpad = g_value_dup_object (&item)) == NULL)) {
3943     GST_ERROR_OBJECT (dbin,
3944         "Couldn't get srcpad from multiqueue for sinkpad %" GST_PTR_FORMAT,
3945         sinkpad);
3946     goto error;
3947   }
3948
3949   CHAIN_MUTEX_LOCK (group->parent);
3950
3951   /* Note: GWeakRefs can't be moved in memory once they're in use, so do a
3952    * dedicated alloc for the GstDemuxerPad struct that contains it */
3953   demuxer_pad = g_new0 (GstDemuxerPad, 1);
3954   demuxer_pad->event_probe_id = gst_pad_add_probe (sinkpad,
3955       GST_PAD_PROBE_TYPE_EVENT_UPSTREAM, sink_pad_event_probe, group, NULL);
3956   demuxer_pad->query_probe_id = gst_pad_add_probe (sinkpad,
3957       GST_PAD_PROBE_TYPE_QUERY_UPSTREAM, sink_pad_query_probe, group, NULL);
3958
3959   g_weak_ref_set (&demuxer_pad->weakPad, sinkpad);
3960   group->demuxer_pad_probe_ids =
3961       g_list_prepend (group->demuxer_pad_probe_ids, demuxer_pad);
3962
3963   group->reqpads = g_list_prepend (group->reqpads, gst_object_ref (sinkpad));
3964   CHAIN_MUTEX_UNLOCK (group->parent);
3965
3966 beach:
3967   if (G_IS_VALUE (&item))
3968     g_value_unset (&item);
3969   if (it)
3970     gst_iterator_free (it);
3971   gst_object_unref (sinkpad);
3972   return srcpad;
3973
3974 error:
3975   gst_element_release_request_pad (group->multiqueue, sinkpad);
3976   goto beach;
3977 }
3978
3979 /* gst_decode_group_is_complete:
3980  *
3981  * Checks if the group is complete, this means that
3982  * a) overrun of the multiqueue or no-more-pads happened
3983  * b) all child chains are complete
3984  *
3985  * Not MT-safe, always call with decodebin expose lock
3986  */
3987 static gboolean
3988 gst_decode_group_is_complete (GstDecodeGroup * group)
3989 {
3990   GList *l;
3991   gboolean complete = TRUE;
3992
3993   if (!group->overrun && !group->no_more_pads) {
3994     complete = FALSE;
3995     goto out;
3996   }
3997
3998   for (l = group->children; l; l = l->next) {
3999     GstDecodeChain *chain = l->data;
4000
4001     if (!gst_decode_chain_is_complete (chain)) {
4002       complete = FALSE;
4003       goto out;
4004     }
4005   }
4006
4007 out:
4008   GST_DEBUG_OBJECT (group->dbin, "Group %p is complete: %d", group, complete);
4009   return complete;
4010 }
4011
4012 /* gst_decode_chain_is_complete:
4013  *
4014  * Returns TRUE if the chain is complete, this means either
4015  * a) This chain is a dead end, i.e. we have no suitable plugins
4016  * b) This chain ends in an endpad and this is blocked or exposed
4017  *
4018  * Not MT-safe, always call with decodebin expose lock
4019  */
4020 static gboolean
4021 gst_decode_chain_is_complete (GstDecodeChain * chain)
4022 {
4023   gboolean complete = FALSE;
4024
4025   CHAIN_MUTEX_LOCK (chain);
4026   if (chain->dbin->shutdown)
4027     goto out;
4028
4029   if (chain->deadend) {
4030     complete = TRUE;
4031     goto out;
4032   }
4033
4034   if (chain->endpad && gst_decode_pad_is_exposable (chain->endpad)) {
4035     complete = TRUE;
4036     goto out;
4037   }
4038
4039   if (chain->demuxer) {
4040     if (chain->active_group
4041         && gst_decode_group_is_complete (chain->active_group)) {
4042       complete = TRUE;
4043       goto out;
4044     }
4045   }
4046
4047 out:
4048   CHAIN_MUTEX_UNLOCK (chain);
4049   GST_DEBUG_OBJECT (chain->dbin, "Chain %p is complete: %d", chain, complete);
4050   return complete;
4051 }
4052
4053 /* Flushing group/chains */
4054 static void
4055 flush_group (GstDecodeGroup * group, gboolean flushing)
4056 {
4057   GList *tmp;
4058
4059   GST_DEBUG ("group %p flushing:%d", group, flushing);
4060
4061   if (group->drained == flushing)
4062     return;
4063   for (tmp = group->children; tmp; tmp = tmp->next) {
4064     GstDecodeChain *chain = (GstDecodeChain *) tmp->data;
4065     flush_chain (chain, flushing);
4066   }
4067   GST_DEBUG ("Setting group %p to drained:%d", group, flushing);
4068   group->drained = flushing;
4069 }
4070
4071 static void
4072 flush_chain (GstDecodeChain * chain, gboolean flushing)
4073 {
4074   GList *tmp;
4075   GstDecodeBin *dbin = chain->dbin;
4076
4077   GST_DEBUG_OBJECT (dbin, "chain %p (pad %s:%s) flushing:%d", chain,
4078       GST_DEBUG_PAD_NAME (chain->pad), flushing);
4079   if (chain->drained == flushing)
4080     return;
4081   /* if unflushing, check if we should switch to last group */
4082   if (flushing == FALSE && chain->next_groups) {
4083     GstDecodeGroup *target_group =
4084         (GstDecodeGroup *) g_list_last (chain->next_groups)->data;
4085     gst_decode_chain_start_free_hidden_groups_thread (chain);
4086     /* Hide active group (we're sure it's not that one we'll be using) */
4087     GST_DEBUG_OBJECT (dbin, "Switching from active group %p to group %p",
4088         chain->active_group, target_group);
4089     gst_decode_group_hide (chain->active_group);
4090     chain->old_groups = g_list_prepend (chain->old_groups, chain->active_group);
4091     chain->active_group = target_group;
4092     /* Hide all groups but the target_group */
4093     for (tmp = chain->next_groups; tmp; tmp = tmp->next) {
4094       GstDecodeGroup *group = (GstDecodeGroup *) tmp->data;
4095       if (group != target_group) {
4096         gst_decode_group_hide (group);
4097         chain->old_groups = g_list_prepend (chain->old_groups, group);
4098       }
4099     }
4100     /* Clear next groups */
4101     g_list_free (chain->next_groups);
4102     chain->next_groups = NULL;
4103   }
4104   /* Mark all groups as flushing */
4105   if (chain->active_group)
4106     flush_group (chain->active_group, flushing);
4107   for (tmp = chain->next_groups; tmp; tmp = tmp->next) {
4108     GstDecodeGroup *group = (GstDecodeGroup *) tmp->data;
4109     flush_group (group, flushing);
4110   }
4111   GST_DEBUG ("Setting chain %p to drained:%d", chain, flushing);
4112   chain->drained = flushing;
4113 }
4114
4115 static gboolean
4116 drain_and_switch_chains (GstDecodeChain * chain, GstDecodePad * drainpad,
4117     gboolean * last_group, gboolean * drained, gboolean * switched);
4118 /* drain_and_switch_chains/groups:
4119  *
4120  * CALL WITH CHAIN LOCK (or group parent) TAKEN !
4121  *
4122  * Goes down the chains/groups until it finds the chain
4123  * to which the drainpad belongs.
4124  *
4125  * It marks that pad/chain as drained and then will figure
4126  * out which group to switch to or not.
4127  *
4128  * last_chain will be set to TRUE if the group to which the
4129  * pad belongs is the last one.
4130  *
4131  * drained will be set to TRUE if the chain/group is drained.
4132  *
4133  * Returns: TRUE if the chain contained the target pad */
4134 static gboolean
4135 drain_and_switch_group (GstDecodeGroup * group, GstDecodePad * drainpad,
4136     gboolean * last_group, gboolean * drained, gboolean * switched)
4137 {
4138   gboolean handled = FALSE;
4139   GList *tmp;
4140
4141   GST_DEBUG ("Checking group %p (target pad %s:%s)",
4142       group, GST_DEBUG_PAD_NAME (drainpad));
4143
4144   /* Definitely can't be in drained groups */
4145   if (G_UNLIKELY (group->drained)) {
4146     goto beach;
4147   }
4148
4149   /* Figure out if all our chains are drained with the
4150    * new information */
4151   group->drained = TRUE;
4152   for (tmp = group->children; tmp; tmp = tmp->next) {
4153     GstDecodeChain *chain = (GstDecodeChain *) tmp->data;
4154     gboolean subdrained = FALSE;
4155
4156     handled |=
4157         drain_and_switch_chains (chain, drainpad, last_group, &subdrained,
4158         switched);
4159     if (!subdrained)
4160       group->drained = FALSE;
4161   }
4162
4163 beach:
4164   GST_DEBUG ("group %p (last_group:%d, drained:%d, switched:%d, handled:%d)",
4165       group, *last_group, group->drained, *switched, handled);
4166   *drained = group->drained;
4167   return handled;
4168 }
4169
4170 static gboolean
4171 drain_and_switch_chains (GstDecodeChain * chain, GstDecodePad * drainpad,
4172     gboolean * last_group, gboolean * drained, gboolean * switched)
4173 {
4174   gboolean handled = FALSE;
4175   GstDecodeBin *dbin = chain->dbin;
4176
4177   GST_DEBUG ("Checking chain %p %s:%s (target pad %s:%s)",
4178       chain, GST_DEBUG_PAD_NAME (chain->pad), GST_DEBUG_PAD_NAME (drainpad));
4179
4180   CHAIN_MUTEX_LOCK (chain);
4181
4182   if (chain->pad_probe_id) {
4183     gst_pad_remove_probe (chain->pad, chain->pad_probe_id);
4184     chain->pad_probe_id = 0;
4185   }
4186
4187   /* Definitely can't be in drained chains */
4188   if (G_UNLIKELY (chain->drained)) {
4189     goto beach;
4190   }
4191
4192   if (chain->endpad) {
4193     /* Check if we're reached the target endchain */
4194     if (drainpad != NULL && chain == drainpad->chain) {
4195       GST_DEBUG ("Found the target chain");
4196       drainpad->drained = TRUE;
4197       handled = TRUE;
4198     }
4199
4200     chain->drained = chain->endpad->drained;
4201     goto beach;
4202   }
4203
4204   /* We known there are groups to switch to */
4205   if (chain->next_groups)
4206     *last_group = FALSE;
4207
4208   /* Check the active group */
4209   if (chain->active_group) {
4210     gboolean subdrained = FALSE;
4211     handled = drain_and_switch_group (chain->active_group, drainpad,
4212         last_group, &subdrained, switched);
4213
4214     /* The group is drained, see if we can switch to another */
4215     if ((handled || drainpad == NULL) && subdrained && !*switched) {
4216       if (chain->next_groups) {
4217         /* Switch to next group */
4218         GST_DEBUG_OBJECT (dbin, "Hiding current group %p", chain->active_group);
4219         gst_decode_group_hide (chain->active_group);
4220         chain->old_groups =
4221             g_list_prepend (chain->old_groups, chain->active_group);
4222         GST_DEBUG_OBJECT (dbin, "Switching to next group %p",
4223             chain->next_groups->data);
4224         chain->active_group = chain->next_groups->data;
4225         chain->next_groups =
4226             g_list_delete_link (chain->next_groups, chain->next_groups);
4227         gst_decode_chain_start_free_hidden_groups_thread (chain);
4228         *switched = TRUE;
4229         chain->drained = FALSE;
4230       } else {
4231         GST_DEBUG ("Group %p was the last in chain %p", chain->active_group,
4232             chain);
4233         chain->drained = TRUE;
4234         /* We're drained ! */
4235       }
4236     } else {
4237       if (subdrained && !chain->next_groups)
4238         *drained = TRUE;
4239     }
4240   }
4241
4242 beach:
4243   CHAIN_MUTEX_UNLOCK (chain);
4244
4245   GST_DEBUG ("Chain %p (handled:%d, last_group:%d, drained:%d, switched:%d)",
4246       chain, handled, *last_group, chain->drained, *switched);
4247
4248   *drained = chain->drained;
4249
4250   if (*drained)
4251     g_signal_emit (dbin, gst_decode_bin_signals[SIGNAL_DRAINED], 0, NULL);
4252
4253   return handled;
4254 }
4255
4256 /* check if the group is drained, meaning all pads have seen an EOS
4257  * event.  */
4258 static gboolean
4259 gst_decode_pad_handle_eos (GstDecodePad * pad)
4260 {
4261   gboolean last_group = TRUE;
4262   gboolean switched = FALSE;
4263   gboolean drained = FALSE;
4264   GstDecodeChain *chain = pad->chain;
4265   GstDecodeBin *dbin = chain->dbin;
4266   GstEvent *tmp;
4267
4268   GST_LOG_OBJECT (dbin, "pad %p", pad);
4269
4270   /* Send a stream-group-done event in case downstream needs
4271    * to unblock before we can drain */
4272   tmp = gst_pad_get_sticky_event (GST_PAD (pad), GST_EVENT_STREAM_START, 0);
4273   if (tmp) {
4274     guint group_id;
4275     if (gst_event_parse_group_id (tmp, &group_id)) {
4276       GstPad *peer = gst_pad_get_peer (GST_PAD (pad));
4277
4278       if (peer) {
4279         GST_DEBUG_OBJECT (dbin,
4280             "Sending stream-group-done for group %u to pad %"
4281             GST_PTR_FORMAT, group_id, pad);
4282         gst_pad_send_event (peer, gst_event_new_stream_group_done (group_id));
4283         gst_object_unref (peer);
4284       }
4285     } else {
4286       GST_DEBUG_OBJECT (dbin,
4287           "No group ID to send stream-group-done on pad %" GST_PTR_FORMAT, pad);
4288     }
4289     gst_event_unref (tmp);
4290   }
4291
4292   EXPOSE_LOCK (dbin);
4293   if (dbin->decode_chain) {
4294     drain_and_switch_chains (dbin->decode_chain, pad, &last_group, &drained,
4295         &switched);
4296
4297     if (switched) {
4298       /* If we resulted in a group switch, expose what's needed */
4299       if (gst_decode_chain_is_complete (dbin->decode_chain))
4300         gst_decode_bin_expose (dbin);
4301     }
4302   }
4303   EXPOSE_UNLOCK (dbin);
4304
4305   return last_group;
4306 }
4307
4308 /* gst_decode_group_is_drained:
4309  *
4310  * Check is this group is drained and cache this result.
4311  * The group is drained if all child chains are drained.
4312  *
4313  * Not MT-safe, call with group->parent's lock */
4314 static gboolean
4315 gst_decode_group_is_drained (GstDecodeGroup * group)
4316 {
4317   GList *l;
4318   gboolean drained = TRUE;
4319
4320   if (group->drained) {
4321     drained = TRUE;
4322     goto out;
4323   }
4324
4325   for (l = group->children; l; l = l->next) {
4326     GstDecodeChain *chain = l->data;
4327
4328     CHAIN_MUTEX_LOCK (chain);
4329     if (!gst_decode_chain_is_drained (chain))
4330       drained = FALSE;
4331     CHAIN_MUTEX_UNLOCK (chain);
4332     if (!drained)
4333       goto out;
4334   }
4335   group->drained = drained;
4336
4337 out:
4338   GST_DEBUG_OBJECT (group->dbin, "Group %p is drained: %d", group, drained);
4339   return drained;
4340 }
4341
4342 /* gst_decode_chain_is_drained:
4343  *
4344  * Check is the chain is drained, which means that
4345  * either
4346  *
4347  * a) it's endpad is drained
4348  * b) there are no pending pads, the active group is drained
4349  *    and there are no next groups
4350  *
4351  * Not MT-safe, call with chain lock
4352  */
4353 static gboolean
4354 gst_decode_chain_is_drained (GstDecodeChain * chain)
4355 {
4356   gboolean drained = FALSE;
4357
4358   if (chain->endpad) {
4359     drained = chain->endpad->drained;
4360     goto out;
4361   }
4362
4363   if (chain->pending_pads) {
4364     drained = FALSE;
4365     goto out;
4366   }
4367
4368   if (chain->active_group && gst_decode_group_is_drained (chain->active_group)
4369       && !chain->next_groups) {
4370     drained = TRUE;
4371     goto out;
4372   }
4373
4374 out:
4375   GST_DEBUG_OBJECT (chain->dbin, "Chain %p is drained: %d", chain, drained);
4376   return drained;
4377 }
4378
4379 static gboolean
4380 gst_decode_group_reset_buffering (GstDecodeGroup * group)
4381 {
4382   GList *l;
4383   gboolean ret = TRUE;
4384
4385   GST_DEBUG_OBJECT (group->dbin, "Group reset buffering %p %s", group,
4386       GST_ELEMENT_NAME (group->multiqueue));
4387   for (l = group->children; l; l = l->next) {
4388     GstDecodeChain *chain = l->data;
4389
4390     CHAIN_MUTEX_LOCK (chain);
4391     if (!gst_decode_chain_reset_buffering (chain)) {
4392       ret = FALSE;
4393     }
4394     CHAIN_MUTEX_UNLOCK (chain);
4395   }
4396
4397   decodebin_set_queue_size_full (group->dbin, group->multiqueue, !ret,
4398       FALSE, (group->parent ? group->parent->seekable : TRUE));
4399
4400   if (ret) {
4401     /* all chains are buffering already, no need to do it here */
4402     g_object_set (group->multiqueue, "use-buffering", FALSE, NULL);
4403   } else {
4404     g_object_set (group->multiqueue, "use-buffering", TRUE,
4405         "low-percent", group->dbin->low_percent,
4406         "high-percent", group->dbin->high_percent, NULL);
4407   }
4408
4409   GST_DEBUG_OBJECT (group->dbin, "Setting %s buffering to %d",
4410       GST_ELEMENT_NAME (group->multiqueue), !ret);
4411   return TRUE;
4412 }
4413
4414
4415 /* sort_end_pads:
4416  * GCompareFunc to use with lists of GstPad.
4417  * Sorts pads by mime type.
4418  * First video (raw, then non-raw), then audio (raw, then non-raw),
4419  * then others.
4420  *
4421  * Return: negative if a<b, 0 if a==b, positive if a>b
4422  */
4423 static gint
4424 sort_end_pads (GstDecodePad * da, GstDecodePad * db)
4425 {
4426   gint va, vb;
4427   GstCaps *capsa, *capsb;
4428   GstStructure *sa, *sb;
4429   const gchar *namea, *nameb;
4430   gchar *ida, *idb;
4431   gint ret;
4432
4433   capsa = get_pad_caps (GST_PAD_CAST (da));
4434   capsb = get_pad_caps (GST_PAD_CAST (db));
4435
4436   sa = gst_caps_get_structure ((const GstCaps *) capsa, 0);
4437   sb = gst_caps_get_structure ((const GstCaps *) capsb, 0);
4438
4439   namea = gst_structure_get_name (sa);
4440   nameb = gst_structure_get_name (sb);
4441
4442   if (g_strrstr (namea, "video/x-raw"))
4443     va = 0;
4444   else if (g_strrstr (namea, "video/"))
4445     va = 1;
4446   else if (g_strrstr (namea, "audio/x-raw"))
4447     va = 2;
4448   else if (g_strrstr (namea, "audio/"))
4449     va = 3;
4450   else
4451     va = 4;
4452
4453   if (g_strrstr (nameb, "video/x-raw"))
4454     vb = 0;
4455   else if (g_strrstr (nameb, "video/"))
4456     vb = 1;
4457   else if (g_strrstr (nameb, "audio/x-raw"))
4458     vb = 2;
4459   else if (g_strrstr (nameb, "audio/"))
4460     vb = 3;
4461   else
4462     vb = 4;
4463
4464   gst_caps_unref (capsa);
4465   gst_caps_unref (capsb);
4466
4467   if (va != vb)
4468     return va - vb;
4469
4470   /* if otherwise the same, sort by stream-id */
4471   ida = gst_pad_get_stream_id (GST_PAD_CAST (da));
4472   idb = gst_pad_get_stream_id (GST_PAD_CAST (db));
4473   ret = (ida) ? ((idb) ? strcmp (ida, idb) : -1) : 1;
4474   g_free (ida);
4475   g_free (idb);
4476
4477   return ret;
4478 }
4479
4480 static GstCaps *
4481 _gst_element_get_linked_caps (GstElement * src, GstElement * sink,
4482     GstElement * capsfilter, GstPad ** srcpad)
4483 {
4484   GstIterator *it;
4485   GstElement *parent;
4486   GstPad *pad, *peer;
4487   gboolean done = FALSE;
4488   GstCaps *caps = NULL;
4489   GValue item = { 0, };
4490
4491   it = gst_element_iterate_src_pads (src);
4492   while (!done) {
4493     switch (gst_iterator_next (it, &item)) {
4494       case GST_ITERATOR_OK:
4495         pad = g_value_get_object (&item);
4496         peer = gst_pad_get_peer (pad);
4497         if (peer) {
4498           parent = gst_pad_get_parent_element (peer);
4499           if (parent == sink || (capsfilter != NULL && parent == capsfilter)) {
4500             caps = gst_pad_get_current_caps (pad);
4501             *srcpad = gst_object_ref (pad);
4502             done = TRUE;
4503           }
4504
4505           if (parent)
4506             gst_object_unref (parent);
4507           gst_object_unref (peer);
4508         }
4509         g_value_reset (&item);
4510         break;
4511       case GST_ITERATOR_RESYNC:
4512         gst_iterator_resync (it);
4513         break;
4514       case GST_ITERATOR_ERROR:
4515       case GST_ITERATOR_DONE:
4516         done = TRUE;
4517         break;
4518     }
4519   }
4520   g_value_unset (&item);
4521   gst_iterator_free (it);
4522
4523   return caps;
4524 }
4525
4526 static GQuark topology_structure_name = 0;
4527 static GQuark topology_caps = 0;
4528 static GQuark topology_next = 0;
4529 static GQuark topology_pad = 0;
4530 static GQuark topology_element_srcpad = 0;
4531
4532 /* FIXME: Invent gst_structure_take_structure() to prevent all the
4533  * structure copying for nothing
4534  */
4535 static GstStructure *
4536 gst_decode_chain_get_topology (GstDecodeChain * chain)
4537 {
4538   GstStructure *s, *u;
4539   GList *l;
4540   GstCaps *caps;
4541
4542   if (G_UNLIKELY ((chain->endpad || chain->deadend)
4543           && (chain->endcaps == NULL))) {
4544     GST_WARNING ("End chain without valid caps !");
4545     return NULL;
4546   }
4547
4548   u = gst_structure_new_id_empty (topology_structure_name);
4549
4550   /* Now at the last element */
4551   if ((chain->elements || !chain->active_group) &&
4552       (chain->endpad || chain->deadend)) {
4553     GstPad *srcpad;
4554
4555     s = gst_structure_new_id_empty (topology_structure_name);
4556     gst_structure_id_set (u, topology_caps, GST_TYPE_CAPS, chain->endcaps,
4557         NULL);
4558
4559     if (chain->endpad) {
4560       gst_structure_id_set (u, topology_pad, GST_TYPE_PAD, chain->endpad, NULL);
4561
4562       srcpad = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (chain->endpad));
4563       gst_structure_id_set (u, topology_element_srcpad, GST_TYPE_PAD,
4564           srcpad, NULL);
4565
4566       gst_object_unref (srcpad);
4567     }
4568
4569     gst_structure_id_set (s, topology_next, GST_TYPE_STRUCTURE, u, NULL);
4570     gst_structure_free (u);
4571     u = s;
4572   } else if (chain->active_group) {
4573     GValue list = { 0, };
4574     GValue item = { 0, };
4575
4576     g_value_init (&list, GST_TYPE_LIST);
4577     g_value_init (&item, GST_TYPE_STRUCTURE);
4578     for (l = chain->active_group->children; l; l = l->next) {
4579       s = gst_decode_chain_get_topology (l->data);
4580       if (s) {
4581         gst_value_set_structure (&item, s);
4582         gst_value_list_append_value (&list, &item);
4583         g_value_reset (&item);
4584         gst_structure_free (s);
4585       }
4586     }
4587     gst_structure_id_set_value (u, topology_next, &list);
4588     g_value_unset (&list);
4589     g_value_unset (&item);
4590   }
4591
4592   /* Get caps between all elements in this chain */
4593   l = (chain->elements && chain->elements->next) ? chain->elements : NULL;
4594   for (; l && l->next; l = l->next) {
4595     GstDecodeElement *delem, *delem_next;
4596     GstElement *elem, *capsfilter, *elem_next;
4597     GstCaps *caps;
4598     GstPad *srcpad;
4599
4600     delem = l->data;
4601     elem = delem->element;
4602     delem_next = l->next->data;
4603     elem_next = delem_next->element;
4604     capsfilter = delem_next->capsfilter;
4605     srcpad = NULL;
4606
4607     caps = _gst_element_get_linked_caps (elem_next, elem, capsfilter, &srcpad);
4608
4609     if (caps) {
4610       s = gst_structure_new_id_empty (topology_structure_name);
4611       gst_structure_id_set (u, topology_caps, GST_TYPE_CAPS, caps, NULL);
4612       gst_caps_unref (caps);
4613
4614       gst_structure_id_set (s, topology_next, GST_TYPE_STRUCTURE, u, NULL);
4615       gst_structure_free (u);
4616       u = s;
4617     }
4618
4619     if (srcpad) {
4620       gst_structure_id_set (u, topology_element_srcpad, GST_TYPE_PAD, srcpad,
4621           NULL);
4622       gst_object_unref (srcpad);
4623     }
4624   }
4625
4626   /* Caps that resulted in this chain */
4627   caps = get_pad_caps (chain->pad);
4628   if (G_UNLIKELY (!caps)) {
4629     GST_WARNING_OBJECT (chain->pad, "Couldn't get the caps of decode chain");
4630     return u;
4631   }
4632   gst_structure_id_set (u, topology_caps, GST_TYPE_CAPS, caps, NULL);
4633   gst_structure_id_set (u, topology_element_srcpad, GST_TYPE_PAD, chain->pad,
4634       NULL);
4635   gst_caps_unref (caps);
4636
4637   return u;
4638 }
4639
4640 static void
4641 gst_decode_bin_post_topology_message (GstDecodeBin * dbin)
4642 {
4643   GstStructure *s;
4644   GstMessage *msg;
4645
4646   s = gst_decode_chain_get_topology (dbin->decode_chain);
4647
4648   if (G_UNLIKELY (s == NULL))
4649     return;
4650   msg = gst_message_new_element (GST_OBJECT (dbin), s);
4651   gst_element_post_message (GST_ELEMENT (dbin), msg);
4652 }
4653
4654 static gboolean
4655 debug_sticky_event (GstPad * pad, GstEvent ** event, gpointer user_data)
4656 {
4657   GST_DEBUG_OBJECT (pad, "sticky event %s (%p)", GST_EVENT_TYPE_NAME (*event),
4658       *event);
4659   return TRUE;
4660 }
4661
4662
4663 /* Must only be called if the toplevel chain is complete and blocked! */
4664 /* Not MT-safe, call with decodebin expose lock! */
4665 static gboolean
4666 gst_decode_bin_expose (GstDecodeBin * dbin)
4667 {
4668   GList *tmp, *endpads;
4669   gboolean missing_plugin;
4670   GString *missing_plugin_details;
4671   gboolean already_exposed;
4672   gboolean last_group;
4673
4674 retry:
4675   endpads = NULL;
4676   missing_plugin = FALSE;
4677   already_exposed = TRUE;
4678   last_group = TRUE;
4679
4680   missing_plugin_details = g_string_new ("");
4681
4682   GST_DEBUG_OBJECT (dbin, "Exposing currently active chains/groups");
4683
4684   /* Don't expose if we're currently shutting down */
4685   DYN_LOCK (dbin);
4686   if (G_UNLIKELY (dbin->shutdown)) {
4687     GST_WARNING_OBJECT (dbin, "Currently, shutting down, aborting exposing");
4688     DYN_UNLOCK (dbin);
4689     return FALSE;
4690   }
4691   DYN_UNLOCK (dbin);
4692
4693   /* Get the pads that we're going to expose and mark things as exposed */
4694   if (!gst_decode_chain_expose (dbin->decode_chain, &endpads, &missing_plugin,
4695           missing_plugin_details, &last_group)) {
4696     g_list_foreach (endpads, (GFunc) gst_object_unref, NULL);
4697     g_list_free (endpads);
4698     g_string_free (missing_plugin_details, TRUE);
4699     /* Failures could be due to the fact that we are currently shutting down (recheck) */
4700     DYN_LOCK (dbin);
4701     if (G_UNLIKELY (dbin->shutdown)) {
4702       GST_WARNING_OBJECT (dbin, "Currently, shutting down, aborting exposing");
4703       DYN_UNLOCK (dbin);
4704       return FALSE;
4705     }
4706     DYN_UNLOCK (dbin);
4707     GST_ERROR_OBJECT (dbin, "Broken chain/group tree");
4708     g_return_val_if_reached (FALSE);
4709     return FALSE;
4710   }
4711   if (endpads == NULL) {
4712     if (missing_plugin) {
4713       if (missing_plugin_details->len > 0) {
4714         gchar *details = g_string_free (missing_plugin_details, FALSE);
4715         GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL),
4716             ("no suitable plugins found:\n%s", details));
4717         g_free (details);
4718       } else {
4719         g_string_free (missing_plugin_details, TRUE);
4720         GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL),
4721             ("no suitable plugins found"));
4722       }
4723     } else {
4724       /* in this case, the stream ended without buffers,
4725        * just post a warning */
4726       g_string_free (missing_plugin_details, TRUE);
4727
4728       GST_WARNING_OBJECT (dbin, "All streams finished without buffers. "
4729           "Last group: %d", last_group);
4730       if (last_group) {
4731         GST_ELEMENT_ERROR (dbin, STREAM, FAILED, (NULL),
4732             ("all streams without buffers"));
4733       } else {
4734         gboolean switched = FALSE;
4735         gboolean drained = FALSE;
4736
4737         drain_and_switch_chains (dbin->decode_chain, NULL, &last_group,
4738             &drained, &switched);
4739         GST_ELEMENT_WARNING (dbin, STREAM, FAILED, (NULL),
4740             ("all streams without buffers"));
4741         if (switched) {
4742           if (gst_decode_chain_is_complete (dbin->decode_chain))
4743             goto retry;
4744           else
4745             return FALSE;
4746         }
4747       }
4748     }
4749
4750     do_async_done (dbin);
4751     return FALSE;
4752   }
4753
4754   g_string_free (missing_plugin_details, TRUE);
4755
4756   /* Check if this was called when everything was exposed already */
4757   for (tmp = endpads; tmp && already_exposed; tmp = tmp->next) {
4758     GstDecodePad *dpad = tmp->data;
4759
4760     already_exposed &= dpad->exposed;
4761     if (!already_exposed)
4762       break;
4763   }
4764   if (already_exposed) {
4765     GST_DEBUG_OBJECT (dbin, "Everything was exposed already!");
4766     g_list_foreach (endpads, (GFunc) gst_object_unref, NULL);
4767     g_list_free (endpads);
4768     return TRUE;
4769   }
4770
4771   /* going to expose something, reset buffering */
4772   gst_decode_bin_reset_buffering (dbin);
4773
4774   /* Set all already exposed pads to blocked */
4775   for (tmp = endpads; tmp; tmp = tmp->next) {
4776     GstDecodePad *dpad = tmp->data;
4777
4778     if (dpad->exposed) {
4779       GST_DEBUG_OBJECT (dpad, "blocking exposed pad");
4780       gst_decode_pad_set_blocked (dpad, TRUE);
4781     }
4782   }
4783
4784   /* re-order pads : video, then audio, then others */
4785   endpads = g_list_sort (endpads, (GCompareFunc) sort_end_pads);
4786
4787   /* Don't add pads if we are shutting down */
4788   DYN_LOCK (dbin);
4789   if (G_UNLIKELY (dbin->shutdown)) {
4790     GST_WARNING_OBJECT (dbin, "Currently, shutting down, aborting exposing");
4791     DYN_UNLOCK (dbin);
4792     return FALSE;
4793   }
4794
4795   /* Expose pads */
4796   for (tmp = endpads; tmp; tmp = tmp->next) {
4797     GstDecodePad *dpad = (GstDecodePad *) tmp->data;
4798     gchar *padname;
4799
4800     /* 1. rewrite name */
4801     padname = g_strdup_printf ("src_%u", dbin->nbpads);
4802     dbin->nbpads++;
4803     GST_DEBUG_OBJECT (dbin, "About to expose dpad %s as %s",
4804         GST_OBJECT_NAME (dpad), padname);
4805     gst_object_set_name (GST_OBJECT (dpad), padname);
4806     g_free (padname);
4807
4808     gst_pad_sticky_events_foreach (GST_PAD_CAST (dpad), debug_sticky_event,
4809         dpad);
4810
4811     /* 2. activate and add */
4812     if (!dpad->exposed) {
4813       dpad->exposed = TRUE;
4814       if (!gst_element_add_pad (GST_ELEMENT (dbin), GST_PAD_CAST (dpad))) {
4815         /* not really fatal, we can try to add the other pads */
4816         g_warning ("error adding pad to decodebin");
4817         dpad->exposed = FALSE;
4818         continue;
4819       }
4820     }
4821
4822     /* 3. emit signal */
4823     GST_INFO_OBJECT (dpad, "added new decoded pad");
4824   }
4825   DYN_UNLOCK (dbin);
4826
4827   /* 4. Signal no-more-pads. This allows the application to hook stuff to the
4828    * exposed pads */
4829   GST_LOG_OBJECT (dbin, "signaling no-more-pads");
4830   gst_element_no_more_pads (GST_ELEMENT (dbin));
4831
4832   /* 5. Send a custom element message with the stream topology */
4833   if (dbin->post_stream_topology)
4834     gst_decode_bin_post_topology_message (dbin);
4835
4836   /* 6. Unblock internal pads. The application should have connected stuff now
4837    * so that streaming can continue. */
4838   for (tmp = endpads; tmp; tmp = tmp->next) {
4839     GstDecodePad *dpad = (GstDecodePad *) tmp->data;
4840
4841     GST_DEBUG_OBJECT (dpad, "unblocking");
4842     gst_decode_pad_unblock (dpad);
4843     GST_DEBUG_OBJECT (dpad, "unblocked");
4844     gst_object_unref (dpad);
4845   }
4846   g_list_free (endpads);
4847
4848   do_async_done (dbin);
4849   GST_DEBUG_OBJECT (dbin, "Exposed everything");
4850   return TRUE;
4851 }
4852
4853 /* gst_decode_chain_expose:
4854  *
4855  * Check if the chain can be exposed and add all endpads
4856  * to the endpads list.
4857  *
4858  * Also update the active group's multiqueue to the
4859  * runtime limits.
4860  *
4861  * Not MT-safe, call with decodebin expose lock! *
4862  */
4863 static gboolean
4864 gst_decode_chain_expose (GstDecodeChain * chain, GList ** endpads,
4865     gboolean * missing_plugin, GString * missing_plugin_details,
4866     gboolean * last_group)
4867 {
4868   GstDecodeGroup *group;
4869   GList *l;
4870   GstDecodeBin *dbin;
4871
4872   if (chain->deadend) {
4873     if (chain->endcaps) {
4874       if (chain->deadend_details) {
4875         g_string_append (missing_plugin_details, chain->deadend_details);
4876         g_string_append_c (missing_plugin_details, '\n');
4877       } else {
4878         gchar *desc = gst_pb_utils_get_codec_description (chain->endcaps);
4879         gchar *caps_str = gst_caps_to_string (chain->endcaps);
4880         g_string_append_printf (missing_plugin_details,
4881             "Missing decoder: %s (%s)\n", desc, caps_str);
4882         g_free (caps_str);
4883         g_free (desc);
4884       }
4885       *missing_plugin = TRUE;
4886     }
4887     return TRUE;
4888   }
4889
4890   if (chain->endpad) {
4891     if (!gst_decode_pad_is_exposable (chain->endpad) && !chain->endpad->exposed)
4892       return FALSE;
4893     *endpads = g_list_prepend (*endpads, gst_object_ref (chain->endpad));
4894     return TRUE;
4895   }
4896
4897   if (chain->next_groups)
4898     *last_group = FALSE;
4899
4900   group = chain->active_group;
4901   if (!group)
4902     return FALSE;
4903   if (!group->no_more_pads && !group->overrun)
4904     return FALSE;
4905
4906   dbin = group->dbin;
4907
4908   /* we can now disconnect any overrun signal, which is used to expose the
4909    * group. */
4910   if (group->overrunsig) {
4911     GST_LOG_OBJECT (dbin, "Disconnecting overrun");
4912     g_signal_handler_disconnect (group->multiqueue, group->overrunsig);
4913     group->overrunsig = 0;
4914   }
4915
4916   for (l = group->children; l; l = l->next) {
4917     GstDecodeChain *childchain = l->data;
4918
4919     if (!gst_decode_chain_expose (childchain, endpads, missing_plugin,
4920             missing_plugin_details, last_group))
4921       return FALSE;
4922   }
4923
4924   return TRUE;
4925 }
4926
4927 /*************************
4928  * GstDecodePad functions
4929  *************************/
4930
4931 static void
4932 gst_decode_pad_class_init (GstDecodePadClass * klass)
4933 {
4934 }
4935
4936 static void
4937 gst_decode_pad_init (GstDecodePad * pad)
4938 {
4939   pad->chain = NULL;
4940   pad->blocked = FALSE;
4941   pad->exposed = FALSE;
4942   pad->drained = FALSE;
4943   gst_object_ref_sink (pad);
4944 }
4945
4946 static GstPadProbeReturn
4947 source_pad_blocked_cb (GstPad * pad, GstPadProbeInfo * info, gpointer user_data)
4948 {
4949   GstDecodePad *dpad = user_data;
4950   GstDecodeChain *chain;
4951   GstDecodeBin *dbin;
4952   GstPadProbeReturn ret = GST_PAD_PROBE_OK;
4953
4954   if (GST_PAD_PROBE_INFO_TYPE (info) & GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM) {
4955     GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
4956
4957     GST_LOG_OBJECT (pad, "Seeing event '%s'", GST_EVENT_TYPE_NAME (event));
4958
4959     if (!GST_EVENT_IS_SERIALIZED (event)) {
4960       /* do not block on sticky or out of band events otherwise the allocation query
4961          from demuxer might block the loop thread */
4962       GST_LOG_OBJECT (pad, "Letting OOB event through");
4963       return GST_PAD_PROBE_PASS;
4964     }
4965
4966     if (GST_EVENT_IS_STICKY (event) && GST_EVENT_TYPE (event) != GST_EVENT_EOS) {
4967       /* manually push sticky events to ghost pad to avoid exposing pads
4968        * that don't have the sticky events. Handle EOS separately as we
4969        * want to block the pad on it if we didn't get any buffers before
4970        * EOS and expose the pad then. */
4971       gst_pad_push_event (GST_PAD_CAST (dpad), gst_event_ref (event));
4972
4973       /* let the sticky events pass */
4974       ret = GST_PAD_PROBE_PASS;
4975
4976       /* we only want to try to expose on CAPS events */
4977       if (GST_EVENT_TYPE (event) != GST_EVENT_CAPS) {
4978         GST_LOG_OBJECT (pad, "Letting sticky non-CAPS event through");
4979         goto done;
4980       }
4981     }
4982   } else if (GST_PAD_PROBE_INFO_TYPE (info) &
4983       GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM) {
4984     GstQuery *query = GST_PAD_PROBE_INFO_QUERY (info);
4985
4986     if (!GST_QUERY_IS_SERIALIZED (query)) {
4987       /* do not block on non-serialized queries */
4988       GST_LOG_OBJECT (pad, "Letting non-serialized query through");
4989       return GST_PAD_PROBE_PASS;
4990     }
4991     if (!gst_pad_has_current_caps (pad)) {
4992       /* do not block on allocation queries before we have caps,
4993        * this would deadlock because we are doing no autoplugging
4994        * without caps.
4995        * TODO: Try to do autoplugging based on the query caps
4996        */
4997       GST_LOG_OBJECT (pad, "Letting serialized query before caps through");
4998       return GST_PAD_PROBE_PASS;
4999     }
5000   }
5001   chain = dpad->chain;
5002   dbin = chain->dbin;
5003
5004   GST_LOG_OBJECT (dpad, "blocked: dpad->chain:%p", chain);
5005
5006   dpad->blocked = TRUE;
5007
5008   EXPOSE_LOCK (dbin);
5009   if (dbin->decode_chain) {
5010     if (gst_decode_chain_is_complete (dbin->decode_chain)) {
5011       if (!gst_decode_bin_expose (dbin))
5012         GST_WARNING_OBJECT (dbin, "Couldn't expose group");
5013     }
5014   }
5015   EXPOSE_UNLOCK (dbin);
5016
5017 done:
5018   return ret;
5019 }
5020
5021 static GstPadProbeReturn
5022 source_pad_event_probe (GstPad * pad, GstPadProbeInfo * info,
5023     gpointer user_data)
5024 {
5025   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
5026   GstDecodePad *dpad = user_data;
5027   gboolean res = TRUE;
5028
5029   GST_LOG_OBJECT (pad, "%s dpad:%p", GST_EVENT_TYPE_NAME (event), dpad);
5030
5031   if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
5032     GST_DEBUG_OBJECT (pad, "we received EOS");
5033
5034     /* Check if all pads are drained.
5035      * * If there is no next group, we will let the EOS go through.
5036      * * If there is a next group but the current group isn't completely
5037      *   drained, we will drop the EOS event.
5038      * * If there is a next group to expose and this was the last non-drained
5039      *   pad for that group, we will remove the ghostpad of the current group
5040      *   first, which unlinks the peer and so drops the EOS. */
5041     res = gst_decode_pad_handle_eos (dpad);
5042   }
5043   if (res)
5044     return GST_PAD_PROBE_OK;
5045   else
5046     return GST_PAD_PROBE_DROP;
5047 }
5048
5049 static void
5050 gst_decode_pad_set_blocked (GstDecodePad * dpad, gboolean blocked)
5051 {
5052   GstDecodeBin *dbin = dpad->dbin;
5053   GstPad *opad;
5054
5055   DYN_LOCK (dbin);
5056
5057   GST_DEBUG_OBJECT (dpad, "blocking pad: %d", blocked);
5058
5059   opad = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (dpad));
5060   if (!opad)
5061     goto out;
5062
5063   /* do not block if shutting down.
5064    * we do not consider/expect it blocked further below, but use other trick */
5065   if (!blocked || !dbin->shutdown) {
5066     if (blocked) {
5067       if (dpad->block_id == 0)
5068         dpad->block_id =
5069             gst_pad_add_probe (opad,
5070             GST_PAD_PROBE_TYPE_BLOCK_DOWNSTREAM |
5071             GST_PAD_PROBE_TYPE_QUERY_DOWNSTREAM, source_pad_blocked_cb,
5072             gst_object_ref (dpad), (GDestroyNotify) gst_object_unref);
5073     } else {
5074       if (dpad->block_id != 0) {
5075         gst_pad_remove_probe (opad, dpad->block_id);
5076         dpad->block_id = 0;
5077       }
5078       dpad->blocked = FALSE;
5079     }
5080   }
5081
5082   if (blocked) {
5083     if (dbin->shutdown) {
5084       /* deactivate to force flushing state to prevent NOT_LINKED errors */
5085       gst_pad_set_active (GST_PAD_CAST (dpad), FALSE);
5086       /* note that deactivating the target pad would have no effect here,
5087        * since elements are typically connected first (and pads exposed),
5088        * and only then brought to PAUSED state (so pads activated) */
5089     } else {
5090       gst_object_ref (dpad);
5091       dbin->blocked_pads = g_list_prepend (dbin->blocked_pads, dpad);
5092     }
5093   } else {
5094     GList *l;
5095
5096     if ((l = g_list_find (dbin->blocked_pads, dpad))) {
5097       gst_object_unref (dpad);
5098       dbin->blocked_pads = g_list_delete_link (dbin->blocked_pads, l);
5099     }
5100   }
5101   gst_object_unref (opad);
5102 out:
5103   DYN_UNLOCK (dbin);
5104 }
5105
5106 static void
5107 gst_decode_pad_add_drained_check (GstDecodePad * dpad)
5108 {
5109   gst_pad_add_probe (GST_PAD_CAST (dpad), GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
5110       source_pad_event_probe, dpad, NULL);
5111 }
5112
5113 static void
5114 gst_decode_pad_activate (GstDecodePad * dpad, GstDecodeChain * chain)
5115 {
5116   g_return_if_fail (chain != NULL);
5117
5118   dpad->chain = chain;
5119   gst_pad_set_active (GST_PAD_CAST (dpad), TRUE);
5120   gst_decode_pad_set_blocked (dpad, TRUE);
5121   gst_decode_pad_add_drained_check (dpad);
5122 }
5123
5124 static void
5125 gst_decode_pad_unblock (GstDecodePad * dpad)
5126 {
5127   gst_decode_pad_set_blocked (dpad, FALSE);
5128 }
5129
5130 static gboolean
5131 gst_decode_pad_event (GstPad * pad, GstObject * parent, GstEvent * event)
5132 {
5133   GstDecodeBin *dbin = GST_DECODE_BIN (parent);
5134
5135   if (GST_EVENT_TYPE (event) == GST_EVENT_SEEK && dbin && dbin->decode_chain) {
5136     GstElement *demuxer = NULL;
5137
5138     /* For adaptive demuxers we send the seek event directly to the demuxer.
5139      * See https://bugzilla.gnome.org/show_bug.cgi?id=606382
5140      */
5141     CHAIN_MUTEX_LOCK (dbin->decode_chain);
5142     if (dbin->decode_chain->adaptive_demuxer) {
5143       GstDecodeElement *delem = dbin->decode_chain->elements->data;
5144       demuxer = gst_object_ref (delem->element);
5145     }
5146     CHAIN_MUTEX_UNLOCK (dbin->decode_chain);
5147
5148     if (demuxer) {
5149       gboolean ret;
5150
5151       GST_DEBUG_OBJECT (dbin,
5152           "Sending SEEK event directly to adaptive streaming demuxer %s",
5153           GST_OBJECT_NAME (demuxer));
5154       ret = gst_element_send_event (demuxer, event);
5155       gst_object_unref (demuxer);
5156       return ret;
5157     }
5158   }
5159
5160   return gst_pad_event_default (pad, parent, event);
5161 }
5162
5163 static gboolean
5164 gst_decode_pad_query (GstPad * pad, GstObject * parent, GstQuery * query)
5165 {
5166   GstDecodePad *dpad = GST_DECODE_PAD (parent);
5167   gboolean ret = FALSE;
5168
5169   CHAIN_MUTEX_LOCK (dpad->chain);
5170   if (!dpad->exposed && !dpad->dbin->shutdown && !dpad->chain->deadend
5171       && dpad->chain->elements) {
5172     GstDecodeElement *delem = dpad->chain->elements->data;
5173
5174     ret = FALSE;
5175     GST_DEBUG_OBJECT (dpad->dbin,
5176         "calling autoplug-query for %s (element %s): %" GST_PTR_FORMAT,
5177         GST_PAD_NAME (dpad), GST_ELEMENT_NAME (delem->element), query);
5178     g_signal_emit (G_OBJECT (dpad->dbin),
5179         gst_decode_bin_signals[SIGNAL_AUTOPLUG_QUERY], 0, dpad, delem->element,
5180         query, &ret);
5181
5182     if (ret)
5183       GST_DEBUG_OBJECT (dpad->dbin,
5184           "autoplug-query returned %d: %" GST_PTR_FORMAT, ret, query);
5185     else
5186       GST_DEBUG_OBJECT (dpad->dbin, "autoplug-query returned %d", ret);
5187   }
5188   CHAIN_MUTEX_UNLOCK (dpad->chain);
5189
5190   /* If exposed or nothing handled the query use the default handler */
5191   if (!ret)
5192     ret = gst_pad_query_default (pad, parent, query);
5193
5194   return ret;
5195 }
5196
5197 static gboolean
5198 gst_decode_pad_is_exposable (GstDecodePad * endpad)
5199 {
5200   if (endpad->blocked || endpad->exposed)
5201     return TRUE;
5202
5203   return gst_pad_has_current_caps (GST_PAD_CAST (endpad));
5204 }
5205
5206 /*gst_decode_pad_new:
5207  *
5208  * Creates a new GstDecodePad for the given pad.
5209  */
5210 static GstDecodePad *
5211 gst_decode_pad_new (GstDecodeBin * dbin, GstDecodeChain * chain)
5212 {
5213   GstDecodePad *dpad;
5214   GstProxyPad *ppad;
5215   GstPadTemplate *pad_tmpl;
5216
5217   GST_DEBUG_OBJECT (dbin, "making new decodepad");
5218   pad_tmpl = gst_static_pad_template_get (&decoder_bin_src_template);
5219   dpad =
5220       g_object_new (GST_TYPE_DECODE_PAD, "direction", GST_PAD_SRC,
5221       "template", pad_tmpl, NULL);
5222   gst_ghost_pad_construct (GST_GHOST_PAD_CAST (dpad));
5223   dpad->chain = chain;
5224   dpad->dbin = dbin;
5225   gst_object_unref (pad_tmpl);
5226
5227   ppad = gst_proxy_pad_get_internal (GST_PROXY_PAD (dpad));
5228   gst_pad_set_query_function (GST_PAD_CAST (ppad), gst_decode_pad_query);
5229   gst_pad_set_event_function (GST_PAD_CAST (dpad), gst_decode_pad_event);
5230   gst_object_unref (ppad);
5231
5232   return dpad;
5233 }
5234
5235 static void
5236 gst_pending_pad_free (GstPendingPad * ppad)
5237 {
5238   g_assert (ppad);
5239   g_assert (ppad->pad);
5240
5241   if (ppad->event_probe_id != 0)
5242     gst_pad_remove_probe (ppad->pad, ppad->event_probe_id);
5243   if (ppad->notify_caps_id)
5244     g_signal_handler_disconnect (ppad->pad, ppad->notify_caps_id);
5245   gst_object_unref (ppad->pad);
5246   g_slice_free (GstPendingPad, ppad);
5247 }
5248
5249 /*****
5250  * Element add/remove
5251  *****/
5252
5253 static void
5254 do_async_start (GstDecodeBin * dbin)
5255 {
5256   GstMessage *message;
5257
5258   dbin->async_pending = TRUE;
5259
5260   message = gst_message_new_async_start (GST_OBJECT_CAST (dbin));
5261   parent_class->handle_message (GST_BIN_CAST (dbin), message);
5262 }
5263
5264 static void
5265 do_async_done (GstDecodeBin * dbin)
5266 {
5267   GstMessage *message;
5268
5269   if (dbin->async_pending) {
5270     message =
5271         gst_message_new_async_done (GST_OBJECT_CAST (dbin),
5272         GST_CLOCK_TIME_NONE);
5273     parent_class->handle_message (GST_BIN_CAST (dbin), message);
5274
5275     dbin->async_pending = FALSE;
5276   }
5277 }
5278
5279 /*****
5280  * convenience functions
5281  *****/
5282
5283 /* find_sink_pad
5284  *
5285  * Returns the first sink pad of the given element, or NULL if it doesn't have
5286  * any.
5287  */
5288
5289 static GstPad *
5290 find_sink_pad (GstElement * element)
5291 {
5292   GstIterator *it;
5293   GstPad *pad = NULL;
5294   GValue item = { 0, };
5295
5296   it = gst_element_iterate_sink_pads (element);
5297
5298   if ((gst_iterator_next (it, &item)) == GST_ITERATOR_OK)
5299     pad = g_value_dup_object (&item);
5300   g_value_unset (&item);
5301   gst_iterator_free (it);
5302
5303   return pad;
5304 }
5305
5306 /* call with dyn_lock held */
5307 static void
5308 unblock_pads (GstDecodeBin * dbin)
5309 {
5310   GST_LOG_OBJECT (dbin, "unblocking pads");
5311
5312   while (dbin->blocked_pads) {
5313     GList *tmp = dbin->blocked_pads;
5314     GstDecodePad *dpad = (GstDecodePad *) tmp->data;
5315     GstPad *opad;
5316
5317     dbin->blocked_pads = g_list_delete_link (dbin->blocked_pads, tmp);
5318     opad = gst_ghost_pad_get_target (GST_GHOST_PAD_CAST (dpad));
5319     if (opad) {
5320
5321       GST_DEBUG_OBJECT (dpad, "unblocking");
5322       if (dpad->block_id != 0) {
5323         gst_pad_remove_probe (opad, dpad->block_id);
5324         dpad->block_id = 0;
5325       }
5326       gst_object_unref (opad);
5327     }
5328
5329     dpad->blocked = FALSE;
5330
5331     /* We release the dyn lock since we want to allow the streaming threads
5332      * to properly stop and not be blocked in our various probes */
5333     DYN_UNLOCK (dbin);
5334     /* make flushing, prevent NOT_LINKED */
5335     gst_pad_set_active (GST_PAD_CAST (dpad), FALSE);
5336     DYN_LOCK (dbin);
5337
5338     GST_DEBUG_OBJECT (dpad, "unblocked");
5339     gst_object_unref (dpad);
5340   }
5341 }
5342
5343 static void
5344 gst_decode_chain_stop (GstDecodeBin * dbin, GstDecodeChain * chain,
5345     GQueue * elements)
5346 {
5347   GQueue *internal_elements, internal_elements_ = G_QUEUE_INIT;
5348   GList *l;
5349
5350   CHAIN_MUTEX_LOCK (chain);
5351   if (elements) {
5352     internal_elements = elements;
5353   } else {
5354     internal_elements = &internal_elements_;
5355   }
5356
5357   for (l = chain->next_groups; l; l = l->next) {
5358     GstDecodeGroup *group = l->data;
5359     GList *m;
5360
5361     for (m = group->children; m; m = m->next) {
5362       GstDecodeChain *chain2 = m->data;
5363       gst_decode_chain_stop (dbin, chain2, internal_elements);
5364     }
5365     if (group->multiqueue)
5366       g_queue_push_head (internal_elements, gst_object_ref (group->multiqueue));
5367   }
5368
5369   if (chain->active_group) {
5370     for (l = chain->active_group->children; l; l = l->next) {
5371       GstDecodeChain *chain2 = l->data;
5372       gst_decode_chain_stop (dbin, chain2, internal_elements);
5373     }
5374     if (chain->active_group->multiqueue)
5375       g_queue_push_head (internal_elements,
5376           gst_object_ref (chain->active_group->multiqueue));
5377   }
5378
5379   for (l = chain->old_groups; l; l = l->next) {
5380     GstDecodeGroup *group = l->data;
5381     GList *m;
5382
5383     for (m = group->children; m; m = m->next) {
5384       GstDecodeChain *chain2 = m->data;
5385       gst_decode_chain_stop (dbin, chain2, internal_elements);
5386     }
5387     if (group->multiqueue)
5388       g_queue_push_head (internal_elements, gst_object_ref (group->multiqueue));
5389   }
5390
5391   for (l = chain->elements; l; l = l->next) {
5392     GstDecodeElement *delem = l->data;
5393
5394     if (delem->capsfilter)
5395       g_queue_push_head (internal_elements, gst_object_ref (delem->capsfilter));
5396     g_queue_push_head (internal_elements, gst_object_ref (delem->element));
5397   }
5398
5399   CHAIN_MUTEX_UNLOCK (chain);
5400
5401   if (!elements) {
5402     GstElement *element;
5403
5404     EXPOSE_UNLOCK (dbin);
5405     /* Shut down from bottom to top */
5406     while ((element = g_queue_pop_tail (internal_elements))) {
5407       /* The bin must never ever change the state of this element anymore */
5408       gst_element_set_locked_state (element, TRUE);
5409       gst_element_set_state (element, GST_STATE_NULL);
5410       gst_object_unref (element);
5411     }
5412     g_queue_clear (internal_elements);
5413     EXPOSE_LOCK (dbin);
5414   }
5415 }
5416
5417 static GstStateChangeReturn
5418 gst_decode_bin_change_state (GstElement * element, GstStateChange transition)
5419 {
5420   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
5421   GstDecodeBin *dbin = GST_DECODE_BIN (element);
5422   GstDecodeChain *chain_to_free = NULL;
5423
5424   switch (transition) {
5425     case GST_STATE_CHANGE_NULL_TO_READY:
5426       if (dbin->typefind == NULL)
5427         goto missing_typefind;
5428       break;
5429     case GST_STATE_CHANGE_READY_TO_PAUSED:
5430       /* Make sure we've cleared all existing chains */
5431       EXPOSE_LOCK (dbin);
5432       if (dbin->decode_chain) {
5433         gst_decode_chain_free (dbin->decode_chain);
5434         dbin->decode_chain = NULL;
5435       }
5436       EXPOSE_UNLOCK (dbin);
5437       DYN_LOCK (dbin);
5438       GST_LOG_OBJECT (dbin, "clearing shutdown flag");
5439       dbin->shutdown = FALSE;
5440       DYN_UNLOCK (dbin);
5441       dbin->have_type = FALSE;
5442       ret = GST_STATE_CHANGE_ASYNC;
5443       do_async_start (dbin);
5444
5445
5446       /* connect a signal to find out when the typefind element found
5447        * a type */
5448       dbin->have_type_id =
5449           g_signal_connect (dbin->typefind, "have-type",
5450           G_CALLBACK (type_found), dbin);
5451       break;
5452     case GST_STATE_CHANGE_PAUSED_TO_READY:
5453     case GST_STATE_CHANGE_READY_TO_NULL:
5454       if (dbin->have_type_id)
5455         g_signal_handler_disconnect (dbin->typefind, dbin->have_type_id);
5456       dbin->have_type_id = 0;
5457       DYN_LOCK (dbin);
5458       GST_LOG_OBJECT (dbin, "setting shutdown flag");
5459       dbin->shutdown = TRUE;
5460       unblock_pads (dbin);
5461       DYN_UNLOCK (dbin);
5462
5463       /* Make sure we don't have cleanup races where
5464        * we might be trying to deactivate pads (in the cleanup thread)
5465        * at the same time as the default element deactivation
5466        * (in PAUSED=>READY)  */
5467       g_mutex_lock (&dbin->cleanup_lock);
5468       if (dbin->cleanup_thread) {
5469         g_thread_join (dbin->cleanup_thread);
5470         dbin->cleanup_thread = NULL;
5471       }
5472       g_mutex_unlock (&dbin->cleanup_lock);
5473     default:
5474       break;
5475   }
5476
5477   {
5478     GstStateChangeReturn bret;
5479
5480     bret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
5481     if (G_UNLIKELY (bret == GST_STATE_CHANGE_FAILURE))
5482       goto activate_failed;
5483     else if (G_UNLIKELY (bret == GST_STATE_CHANGE_NO_PREROLL)) {
5484       do_async_done (dbin);
5485       ret = bret;
5486     }
5487   }
5488   switch (transition) {
5489     case GST_STATE_CHANGE_PAUSED_TO_READY:
5490       do_async_done (dbin);
5491       EXPOSE_LOCK (dbin);
5492       if (dbin->decode_chain) {
5493         gst_decode_chain_stop (dbin, dbin->decode_chain, NULL);
5494         chain_to_free = dbin->decode_chain;
5495         gst_decode_chain_free_internal (dbin->decode_chain, TRUE);
5496         dbin->decode_chain = NULL;
5497       }
5498       EXPOSE_UNLOCK (dbin);
5499       if (chain_to_free)
5500         gst_decode_chain_free (chain_to_free);
5501       g_list_free_full (dbin->buffering_status,
5502           (GDestroyNotify) gst_message_unref);
5503       dbin->buffering_status = NULL;
5504       /* Let's do a final check of leftover groups to free */
5505       g_mutex_lock (&dbin->cleanup_lock);
5506       if (dbin->cleanup_groups) {
5507         gst_decode_chain_free_hidden_groups (dbin->cleanup_groups);
5508         dbin->cleanup_groups = NULL;
5509       }
5510       g_mutex_unlock (&dbin->cleanup_lock);
5511       break;
5512     case GST_STATE_CHANGE_READY_TO_NULL:
5513       /* Let's do a final check of leftover groups to free */
5514       g_mutex_lock (&dbin->cleanup_lock);
5515       if (dbin->cleanup_groups) {
5516         gst_decode_chain_free_hidden_groups (dbin->cleanup_groups);
5517         dbin->cleanup_groups = NULL;
5518       }
5519       g_mutex_unlock (&dbin->cleanup_lock);
5520       break;
5521     default:
5522       break;
5523   }
5524
5525   return ret;
5526
5527 /* ERRORS */
5528 missing_typefind:
5529   {
5530     gst_element_post_message (element,
5531         gst_missing_element_message_new (element, "typefind"));
5532     GST_ELEMENT_ERROR (dbin, CORE, MISSING_PLUGIN, (NULL), ("no typefind!"));
5533     return GST_STATE_CHANGE_FAILURE;
5534   }
5535 activate_failed:
5536   {
5537     GST_DEBUG_OBJECT (element,
5538         "element failed to change states -- activation problem?");
5539     do_async_done (dbin);
5540     return GST_STATE_CHANGE_FAILURE;
5541   }
5542 }
5543
5544 static void
5545 gst_decode_bin_handle_message (GstBin * bin, GstMessage * msg)
5546 {
5547   GstDecodeBin *dbin = GST_DECODE_BIN (bin);
5548   gboolean drop = FALSE;
5549
5550   if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_ERROR) {
5551     /* Don't pass errors when shutting down. Sometimes,
5552      * elements can generate spurious errors because we set the
5553      * output pads to flushing, and they can't detect that if they
5554      * send an event at exactly the wrong moment */
5555     DYN_LOCK (dbin);
5556     drop = dbin->shutdown;
5557     DYN_UNLOCK (dbin);
5558
5559     if (!drop) {
5560       GST_OBJECT_LOCK (dbin);
5561       drop = (g_list_find (dbin->filtered, GST_MESSAGE_SRC (msg)) != NULL);
5562       if (drop)
5563         dbin->filtered_errors =
5564             g_list_prepend (dbin->filtered_errors, gst_message_ref (msg));
5565       GST_OBJECT_UNLOCK (dbin);
5566     }
5567   } else if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_BUFFERING) {
5568     gint perc, msg_perc;
5569     gint smaller_perc = 100;
5570     GstMessage *smaller = NULL;
5571     GList *found = NULL;
5572     GList *iter;
5573
5574     /* buffering messages must be aggregated as there might be multiple
5575      * multiqueue in the pipeline and their independent buffering messages
5576      * will confuse the application
5577      *
5578      * decodebin keeps a list of messages received from elements that are
5579      * buffering.
5580      * Rules are:
5581      * 1) Always post the smaller buffering %
5582      * 2) If an element posts a 100% buffering message, remove it from the list
5583      * 3) When there are no more messages on the list, post 100% message
5584      * 4) When an element posts a new buffering message, update the one
5585      *    on the list to this new value
5586      */
5587
5588     BUFFERING_LOCK (dbin);
5589     gst_message_parse_buffering (msg, &msg_perc);
5590
5591     GST_DEBUG_OBJECT (dbin, "Got buffering msg %" GST_PTR_FORMAT, msg);
5592
5593     g_mutex_lock (&dbin->buffering_post_lock);
5594
5595     /*
5596      * Single loop for 2 things:
5597      * 1) Look for a message with the same source
5598      *   1.1) If the received message is 100%, remove it from the list
5599      * 2) Find the minimum buffering from the list
5600      */
5601     for (iter = dbin->buffering_status; iter;) {
5602       GstMessage *bufstats = iter->data;
5603       if (GST_MESSAGE_SRC (bufstats) == GST_MESSAGE_SRC (msg)) {
5604         found = iter;
5605         if (msg_perc < 100) {
5606           GST_DEBUG_OBJECT (dbin, "Replacing old buffering msg %"
5607               GST_PTR_FORMAT, iter->data);
5608           gst_message_unref (iter->data);
5609           bufstats = iter->data = gst_message_ref (msg);
5610         } else {
5611           GList *current = iter;
5612
5613           /* remove the element here and avoid confusing the loop */
5614           iter = g_list_next (iter);
5615
5616           GST_DEBUG_OBJECT (dbin, "Deleting old buffering msg %"
5617               GST_PTR_FORMAT, current->data);
5618
5619           gst_message_unref (current->data);
5620           dbin->buffering_status =
5621               g_list_delete_link (dbin->buffering_status, current);
5622
5623           continue;
5624         }
5625       }
5626
5627       gst_message_parse_buffering (bufstats, &perc);
5628       if (perc < smaller_perc) {
5629         smaller_perc = perc;
5630         smaller = bufstats;
5631       }
5632       iter = g_list_next (iter);
5633     }
5634
5635     if (found == NULL && msg_perc < 100) {
5636       if (msg_perc < smaller_perc) {
5637         smaller_perc = msg_perc;
5638         smaller = msg;
5639       }
5640       GST_DEBUG_OBJECT (dbin, "Storing buffering msg %" GST_PTR_FORMAT, msg);
5641       dbin->buffering_status =
5642           g_list_prepend (dbin->buffering_status, gst_message_ref (msg));
5643     }
5644
5645     /* now compute the buffering message that should be posted */
5646     if (smaller_perc == 100) {
5647       g_assert (dbin->buffering_status == NULL);
5648       /* we are posting the original received msg */
5649     } else {
5650       gst_message_replace (&msg, smaller);
5651     }
5652     BUFFERING_UNLOCK (dbin);
5653
5654     GST_DEBUG_OBJECT (dbin, "Forwarding buffering msg %" GST_PTR_FORMAT, msg);
5655     GST_BIN_CLASS (parent_class)->handle_message (bin, msg);
5656
5657     g_mutex_unlock (&dbin->buffering_post_lock);
5658     return;
5659   }
5660
5661   if (drop) {
5662     gst_message_unref (msg);
5663   } else {
5664     GST_DEBUG_OBJECT (dbin, "Forwarding msg %" GST_PTR_FORMAT, msg);
5665     GST_BIN_CLASS (parent_class)->handle_message (bin, msg);
5666   }
5667 }
5668
5669 static gboolean
5670 gst_decode_bin_remove_element (GstBin * bin, GstElement * element)
5671 {
5672   GstDecodeBin *dbin = GST_DECODE_BIN (bin);
5673   gboolean removed = FALSE, post = FALSE;
5674   GList *iter;
5675
5676   BUFFERING_LOCK (bin);
5677   g_mutex_lock (&dbin->buffering_post_lock);
5678   for (iter = dbin->buffering_status; iter; iter = iter->next) {
5679     GstMessage *bufstats = iter->data;
5680
5681     if (GST_MESSAGE_SRC (bufstats) == GST_OBJECT_CAST (element) ||
5682         gst_object_has_as_ancestor (GST_MESSAGE_SRC (bufstats),
5683             GST_OBJECT_CAST (element))) {
5684       gst_message_unref (bufstats);
5685       dbin->buffering_status =
5686           g_list_delete_link (dbin->buffering_status, iter);
5687       removed = TRUE;
5688       break;
5689     }
5690   }
5691
5692   if (removed && dbin->buffering_status == NULL)
5693     post = TRUE;
5694   BUFFERING_UNLOCK (bin);
5695
5696   if (post) {
5697     gst_element_post_message (GST_ELEMENT_CAST (bin),
5698         gst_message_new_buffering (GST_OBJECT_CAST (dbin), 100));
5699   }
5700   g_mutex_unlock (&dbin->buffering_post_lock);
5701
5702   return GST_BIN_CLASS (parent_class)->remove_element (bin, element);
5703 }
5704
5705 gboolean
5706 gst_decode_bin_plugin_init (GstPlugin * plugin)
5707 {
5708   GST_DEBUG_CATEGORY_INIT (gst_decode_bin_debug, "decodebin", 0, "decoder bin");
5709
5710   /* Register some quarks here for the stream topology message */
5711   topology_structure_name = g_quark_from_static_string ("stream-topology");
5712   topology_caps = g_quark_from_static_string ("caps");
5713   topology_next = g_quark_from_static_string ("next");
5714   topology_pad = g_quark_from_static_string ("pad");
5715   topology_element_srcpad = g_quark_from_static_string ("element-srcpad");
5716
5717   return gst_element_register (plugin, "decodebin", GST_RANK_NONE,
5718       GST_TYPE_DECODE_BIN);
5719 }