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