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