gst-libs: Remove interfaces libs and mixer/tuner interfaces
[platform/upstream/gstreamer.git] / gst / playback / gsturidecodebin.c
1 /* GStreamer
2  * Copyright (C) <2007> Wim Taymans <wim.taymans@gmail.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:element-uridecodebin
22  *
23  * Decodes data from a URI into raw media. It selects a source element that can
24  * handle the given #GstURIDecodeBin:uri scheme and connects it to a decodebin.
25  */
26
27 /* FIXME 0.11: suppress warnings for deprecated API such as GValueArray
28  * with newer GLib versions (>= 2.31.0) */
29 #define GLIB_DISABLE_DEPRECATION_WARNINGS
30
31 #ifdef HAVE_CONFIG_H
32 #  include "config.h"
33 #endif
34
35 #include <string.h>
36
37 #include <gst/gst.h>
38 #include <gst/gst-i18n-plugin.h>
39 #include <gst/pbutils/missing-plugins.h>
40
41 #include "gstplay-enum.h"
42 #include "gstrawcaps.h"
43 #include "gstplayback.h"
44
45 #include "gst/glib-compat-private.h"
46
47 #define GST_TYPE_URI_DECODE_BIN \
48   (gst_uri_decode_bin_get_type())
49 #define GST_URI_DECODE_BIN(obj) \
50   (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_URI_DECODE_BIN,GstURIDecodeBin))
51 #define GST_URI_DECODE_BIN_CLASS(klass) \
52   (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_URI_DECODE_BIN,GstURIDecodeBinClass))
53 #define GST_IS_URI_DECODE_BIN(obj) \
54   (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_URI_DECODE_BIN))
55 #define GST_IS_URI_DECODE_BIN_CLASS(klass) \
56   (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_URI_DECODE_BIN))
57 #define GST_URI_DECODE_BIN_CAST(obj) ((GstURIDecodeBin *) (obj))
58
59 typedef struct _GstURIDecodeBin GstURIDecodeBin;
60 typedef struct _GstURIDecodeBinClass GstURIDecodeBinClass;
61
62 #define GST_URI_DECODE_BIN_GET_LOCK(dec) (((GstURIDecodeBin*)(dec))->lock)
63 #define GST_URI_DECODE_BIN_LOCK(dec) (g_mutex_lock(GST_URI_DECODE_BIN_GET_LOCK(dec)))
64 #define GST_URI_DECODE_BIN_UNLOCK(dec) (g_mutex_unlock(GST_URI_DECODE_BIN_GET_LOCK(dec)))
65
66 typedef struct _GstURIDecodeBinStream
67 {
68   gulong probe_id;
69   guint bitrate;
70 } GstURIDecodeBinStream;
71
72 /**
73  * GstURIDecodeBin
74  *
75  * uridecodebin element struct
76  */
77 struct _GstURIDecodeBin
78 {
79   GstBin parent_instance;
80
81   GMutex *lock;                 /* lock for constructing */
82
83   GMutex *factories_lock;
84   guint32 factories_cookie;
85   GList *factories;             /* factories we can use for selecting elements */
86
87   gchar *uri;
88   guint64 connection_speed;
89   GstCaps *caps;
90   gchar *encoding;
91
92   gboolean is_stream;
93   gboolean is_download;
94   gboolean need_queue;
95   guint64 buffer_duration;      /* When buffering, buffer duration (ns) */
96   guint buffer_size;            /* When buffering, buffer size (bytes) */
97   gboolean download;
98   gboolean use_buffering;
99
100   GstElement *source;
101   GstElement *queue;
102   GstElement *typefind;
103   guint have_type_id;           /* have-type signal id from typefind */
104   GSList *decodebins;
105   GSList *pending_decodebins;
106   GHashTable *streams;
107   guint numpads;
108
109   /* for dynamic sources */
110   guint src_np_sig_id;          /* new-pad signal id */
111   guint src_nmp_sig_id;         /* no-more-pads signal id */
112   gint pending;
113
114   gboolean async_pending;       /* async-start has been emitted */
115
116   gboolean expose_allstreams;   /* Whether to expose unknow type streams or not */
117
118   guint64 ring_buffer_max_size; /* 0 means disabled */
119 };
120
121 struct _GstURIDecodeBinClass
122 {
123   GstBinClass parent_class;
124
125   /* signal fired when we found a pad that we cannot decode */
126   void (*unknown_type) (GstElement * element, GstPad * pad, GstCaps * caps);
127
128   /* signal fired to know if we continue trying to decode the given caps */
129     gboolean (*autoplug_continue) (GstElement * element, GstPad * pad,
130       GstCaps * caps);
131   /* signal fired to get a list of factories to try to autoplug */
132   GValueArray *(*autoplug_factories) (GstElement * element, GstPad * pad,
133       GstCaps * caps);
134   /* signal fired to sort the factories */
135   GValueArray *(*autoplug_sort) (GstElement * element, GstPad * pad,
136       GstCaps * caps, GValueArray * factories);
137   /* signal fired to select from the proposed list of factories */
138     GstAutoplugSelectResult (*autoplug_select) (GstElement * element,
139       GstPad * pad, GstCaps * caps, GstElementFactory * factory);
140
141   /* emitted when all data is decoded */
142   void (*drained) (GstElement * element);
143 };
144
145 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src_%u",
146     GST_PAD_SRC,
147     GST_PAD_SOMETIMES,
148     GST_STATIC_CAPS_ANY);
149
150 static GstStaticCaps default_raw_caps = GST_STATIC_CAPS (DEFAULT_RAW_CAPS);
151
152 GST_DEBUG_CATEGORY_STATIC (gst_uri_decode_bin_debug);
153 #define GST_CAT_DEFAULT gst_uri_decode_bin_debug
154
155 /* signals */
156 enum
157 {
158   SIGNAL_UNKNOWN_TYPE,
159   SIGNAL_AUTOPLUG_CONTINUE,
160   SIGNAL_AUTOPLUG_FACTORIES,
161   SIGNAL_AUTOPLUG_SELECT,
162   SIGNAL_DRAINED,
163   SIGNAL_AUTOPLUG_SORT,
164   SIGNAL_SOURCE_SETUP,
165   LAST_SIGNAL
166 };
167
168 /* properties */
169 #define DEFAULT_PROP_URI            NULL
170 #define DEFAULT_PROP_SOURCE         NULL
171 #define DEFAULT_CONNECTION_SPEED    0
172 #define DEFAULT_CAPS                (gst_static_caps_get (&default_raw_caps))
173 #define DEFAULT_SUBTITLE_ENCODING   NULL
174 #define DEFAULT_BUFFER_DURATION     -1
175 #define DEFAULT_BUFFER_SIZE         -1
176 #define DEFAULT_DOWNLOAD            FALSE
177 #define DEFAULT_USE_BUFFERING       FALSE
178 #define DEFAULT_EXPOSE_ALL_STREAMS  TRUE
179 #define DEFAULT_RING_BUFFER_MAX_SIZE 0
180
181 enum
182 {
183   PROP_0,
184   PROP_URI,
185   PROP_SOURCE,
186   PROP_CONNECTION_SPEED,
187   PROP_CAPS,
188   PROP_SUBTITLE_ENCODING,
189   PROP_BUFFER_SIZE,
190   PROP_BUFFER_DURATION,
191   PROP_DOWNLOAD,
192   PROP_USE_BUFFERING,
193   PROP_EXPOSE_ALL_STREAMS,
194   PROP_RING_BUFFER_MAX_SIZE,
195   PROP_LAST
196 };
197
198 static guint gst_uri_decode_bin_signals[LAST_SIGNAL] = { 0 };
199
200 GType gst_uri_decode_bin_get_type (void);
201 #define gst_uri_decode_bin_parent_class parent_class
202 G_DEFINE_TYPE (GstURIDecodeBin, gst_uri_decode_bin, GST_TYPE_BIN);
203
204 static void remove_decoders (GstURIDecodeBin * bin, gboolean force);
205 static void gst_uri_decode_bin_set_property (GObject * object, guint prop_id,
206     const GValue * value, GParamSpec * pspec);
207 static void gst_uri_decode_bin_get_property (GObject * object, guint prop_id,
208     GValue * value, GParamSpec * pspec);
209 static void gst_uri_decode_bin_finalize (GObject * obj);
210
211 static void handle_message (GstBin * bin, GstMessage * msg);
212
213 static gboolean gst_uri_decode_bin_query (GstElement * element,
214     GstQuery * query);
215 static GstStateChangeReturn gst_uri_decode_bin_change_state (GstElement *
216     element, GstStateChange transition);
217
218 static gboolean
219 _gst_boolean_accumulator (GSignalInvocationHint * ihint,
220     GValue * return_accu, const GValue * handler_return, gpointer dummy)
221 {
222   gboolean myboolean;
223
224   myboolean = g_value_get_boolean (handler_return);
225   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
226     g_value_set_boolean (return_accu, myboolean);
227
228   /* stop emission if FALSE */
229   return myboolean;
230 }
231
232 static gboolean
233 _gst_array_accumulator (GSignalInvocationHint * ihint,
234     GValue * return_accu, const GValue * handler_return, gpointer dummy)
235 {
236   gpointer array;
237
238   array = g_value_get_boxed (handler_return);
239   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
240     g_value_set_boxed (return_accu, array);
241
242   return FALSE;
243 }
244
245 static gboolean
246 _gst_select_accumulator (GSignalInvocationHint * ihint,
247     GValue * return_accu, const GValue * handler_return, gpointer dummy)
248 {
249   GstAutoplugSelectResult res;
250
251   res = g_value_get_enum (handler_return);
252   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
253     g_value_set_enum (return_accu, res);
254
255   return FALSE;
256 }
257
258 static gboolean
259 _gst_array_hasvalue_accumulator (GSignalInvocationHint * ihint,
260     GValue * return_accu, const GValue * handler_return, gpointer dummy)
261 {
262   gpointer array;
263
264   array = g_value_get_boxed (handler_return);
265   if (!(ihint->run_type & G_SIGNAL_RUN_CLEANUP))
266     g_value_set_boxed (return_accu, array);
267
268   if (array != NULL)
269     return FALSE;
270
271   return TRUE;
272 }
273
274 static gboolean
275 gst_uri_decode_bin_autoplug_continue (GstElement * element, GstPad * pad,
276     GstCaps * caps)
277 {
278   /* by default we always continue */
279   return TRUE;
280 }
281
282 /* Must be called with factories lock! */
283 static void
284 gst_uri_decode_bin_update_factories_list (GstURIDecodeBin * dec)
285 {
286   guint32 cookie;
287
288   cookie = gst_registry_get_feature_list_cookie (gst_registry_get ());
289   if (!dec->factories || dec->factories_cookie != cookie) {
290     if (dec->factories)
291       gst_plugin_feature_list_free (dec->factories);
292     dec->factories =
293         gst_element_factory_list_get_elements
294         (GST_ELEMENT_FACTORY_TYPE_DECODABLE, GST_RANK_MARGINAL);
295     dec->factories_cookie = cookie;
296   }
297 }
298
299 static GValueArray *
300 gst_uri_decode_bin_autoplug_factories (GstElement * element, GstPad * pad,
301     GstCaps * caps)
302 {
303   GList *list, *tmp;
304   GValueArray *result;
305   GstURIDecodeBin *dec = GST_URI_DECODE_BIN_CAST (element);
306
307   GST_DEBUG_OBJECT (element, "finding factories");
308
309   /* return all compatible factories for caps */
310   g_mutex_lock (dec->factories_lock);
311   gst_uri_decode_bin_update_factories_list (dec);
312   list =
313       gst_element_factory_list_filter (dec->factories, caps, GST_PAD_SINK,
314       FALSE);
315   g_mutex_unlock (dec->factories_lock);
316
317   result = g_value_array_new (g_list_length (list));
318   for (tmp = list; tmp; tmp = tmp->next) {
319     GstElementFactory *factory = GST_ELEMENT_FACTORY_CAST (tmp->data);
320     GValue val = { 0, };
321
322     g_value_init (&val, G_TYPE_OBJECT);
323     g_value_set_object (&val, factory);
324     g_value_array_append (result, &val);
325     g_value_unset (&val);
326   }
327   gst_plugin_feature_list_free (list);
328
329   GST_DEBUG_OBJECT (element, "autoplug-factories returns %p", result);
330
331   return result;
332 }
333
334 static GValueArray *
335 gst_uri_decode_bin_autoplug_sort (GstElement * element, GstPad * pad,
336     GstCaps * caps, GValueArray * factories)
337 {
338   return NULL;
339 }
340
341 static GstAutoplugSelectResult
342 gst_uri_decode_bin_autoplug_select (GstElement * element, GstPad * pad,
343     GstCaps * caps, GstElementFactory * factory)
344 {
345   GST_DEBUG_OBJECT (element, "default autoplug-select returns TRY");
346
347   /* Try factory. */
348   return GST_AUTOPLUG_SELECT_TRY;
349 }
350
351 static void
352 gst_uri_decode_bin_class_init (GstURIDecodeBinClass * klass)
353 {
354   GObjectClass *gobject_class;
355   GstElementClass *gstelement_class;
356   GstBinClass *gstbin_class;
357
358   gobject_class = G_OBJECT_CLASS (klass);
359   gstelement_class = GST_ELEMENT_CLASS (klass);
360   gstbin_class = GST_BIN_CLASS (klass);
361
362   gobject_class->set_property = gst_uri_decode_bin_set_property;
363   gobject_class->get_property = gst_uri_decode_bin_get_property;
364   gobject_class->finalize = gst_uri_decode_bin_finalize;
365
366   g_object_class_install_property (gobject_class, PROP_URI,
367       g_param_spec_string ("uri", "URI", "URI to decode",
368           DEFAULT_PROP_URI, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
369
370   g_object_class_install_property (gobject_class, PROP_SOURCE,
371       g_param_spec_object ("source", "Source", "Source object used",
372           GST_TYPE_ELEMENT, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
373
374   g_object_class_install_property (gobject_class, PROP_CONNECTION_SPEED,
375       g_param_spec_uint64 ("connection-speed", "Connection Speed",
376           "Network connection speed in kbps (0 = unknown)",
377           0, G_MAXUINT64 / 1000, DEFAULT_CONNECTION_SPEED,
378           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
379
380   g_object_class_install_property (gobject_class, PROP_CAPS,
381       g_param_spec_boxed ("caps", "Caps",
382           "The caps on which to stop decoding. (NULL = default)",
383           GST_TYPE_CAPS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
384
385   g_object_class_install_property (gobject_class, PROP_SUBTITLE_ENCODING,
386       g_param_spec_string ("subtitle-encoding", "subtitle encoding",
387           "Encoding to assume if input subtitles are not in UTF-8 encoding. "
388           "If not set, the GST_SUBTITLE_ENCODING environment variable will "
389           "be checked for an encoding to use. If that is not set either, "
390           "ISO-8859-15 will be assumed.", NULL,
391           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
392
393   g_object_class_install_property (gobject_class, PROP_BUFFER_SIZE,
394       g_param_spec_int ("buffer-size", "Buffer size (bytes)",
395           "Buffer size when buffering streams (-1 default value)",
396           -1, G_MAXINT, DEFAULT_BUFFER_SIZE,
397           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
398   g_object_class_install_property (gobject_class, PROP_BUFFER_DURATION,
399       g_param_spec_int64 ("buffer-duration", "Buffer duration (ns)",
400           "Buffer duration when buffering streams (-1 default value)",
401           -1, G_MAXINT64, DEFAULT_BUFFER_DURATION,
402           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
403
404   /**
405    * GstURIDecodeBin::download:
406    *
407    * For certain media type, enable download buffering.
408    */
409   g_object_class_install_property (gobject_class, PROP_DOWNLOAD,
410       g_param_spec_boolean ("download", "Download",
411           "Attempt download buffering when buffering network streams",
412           DEFAULT_DOWNLOAD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
413   /**
414    * GstURIDecodeBin::use-buffering:
415    *
416    * Emit BUFFERING messages based on low-/high-percent thresholds of the
417    * demuxed or parsed data.
418    * When download buffering is activated and used for the current media
419    * type, this property does nothing. Otherwise perform buffering on the
420    * demuxed or parsed media.
421    *
422    * Since: 0.10.26
423    */
424   g_object_class_install_property (gobject_class, PROP_USE_BUFFERING,
425       g_param_spec_boolean ("use-buffering", "Use Buffering",
426           "Perform buffering on demuxed/parsed media",
427           DEFAULT_USE_BUFFERING, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
428
429   /**
430    * GstURIDecodeBin::expose-all-streams
431    *
432    * Expose streams of unknown type.
433    *
434    * If set to %FALSE, then only the streams that can be decoded to the final
435    * caps (see 'caps' property) will have a pad exposed. Streams that do not
436    * match those caps but could have been decoded will not have decoder plugged
437    * in internally and will not have a pad exposed. 
438    *
439    * Since: 0.10.30
440    */
441   g_object_class_install_property (gobject_class, PROP_EXPOSE_ALL_STREAMS,
442       g_param_spec_boolean ("expose-all-streams", "Expose All Streams",
443           "Expose all streams, including those of unknown type or that don't match the 'caps' property",
444           DEFAULT_EXPOSE_ALL_STREAMS,
445           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
446
447   /**
448    * GstURIDecodeBin::ring-buffer-max-size
449    *
450    * The maximum size of the ring buffer in kilobytes. If set to 0, the ring
451    * buffer is disabled. Default is 0.
452    *
453    * Since: 0.10.31
454    */
455   g_object_class_install_property (gobject_class, PROP_RING_BUFFER_MAX_SIZE,
456       g_param_spec_uint64 ("ring-buffer-max-size",
457           "Max. ring buffer size (bytes)",
458           "Max. amount of data in the ring buffer (bytes, 0 = ring buffer disabled)",
459           0, G_MAXUINT, DEFAULT_RING_BUFFER_MAX_SIZE,
460           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
461
462   /**
463    * GstURIDecodeBin::unknown-type:
464    * @bin: The uridecodebin.
465    * @pad: the new pad containing caps that cannot be resolved to a 'final'.
466    * stream type.
467    * @caps: the #GstCaps of the pad that cannot be resolved.
468    *
469    * This signal is emitted when a pad for which there is no further possible
470    * decoding is added to the uridecodebin.
471    */
472   gst_uri_decode_bin_signals[SIGNAL_UNKNOWN_TYPE] =
473       g_signal_new ("unknown-type", G_TYPE_FROM_CLASS (klass),
474       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass, unknown_type),
475       NULL, NULL, g_cclosure_marshal_generic, G_TYPE_NONE, 2,
476       GST_TYPE_PAD, GST_TYPE_CAPS);
477
478   /**
479    * GstURIDecodeBin::autoplug-continue:
480    * @bin: The uridecodebin.
481    * @pad: The #GstPad.
482    * @caps: The #GstCaps found.
483    *
484    * This signal is emitted whenever uridecodebin finds a new stream. It is
485    * emitted before looking for any elements that can handle that stream.
486    *
487    * <note>
488    *   Invocation of signal handlers stops after the first signal handler
489    *   returns #FALSE. Signal handlers are invoked in the order they were
490    *   connected in.
491    * </note>
492    *
493    * Returns: #TRUE if you wish uridecodebin to look for elements that can
494    * handle the given @caps. If #FALSE, those caps will be considered as
495    * final and the pad will be exposed as such (see 'pad-added' signal of
496    * #GstElement).
497    */
498   gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE] =
499       g_signal_new ("autoplug-continue", G_TYPE_FROM_CLASS (klass),
500       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass,
501           autoplug_continue), _gst_boolean_accumulator, NULL,
502       g_cclosure_marshal_generic, G_TYPE_BOOLEAN, 2, GST_TYPE_PAD,
503       GST_TYPE_CAPS);
504
505   /**
506    * GstURIDecodeBin::autoplug-factories:
507    * @bin: The uridecodebin.
508    * @pad: The #GstPad.
509    * @caps: The #GstCaps found.
510    *
511    * This function is emitted when an array of possible factories for @caps on
512    * @pad is needed. Uridecodebin will by default return an array with all
513    * compatible factories, sorted by rank.
514    *
515    * If this function returns NULL, @pad will be exposed as a final caps.
516    *
517    * If this function returns an empty array, the pad will be considered as
518    * having an unhandled type media type.
519    *
520    * <note>
521    *   Only the signal handler that is connected first will ever by invoked.
522    *   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
523    *   signal, they will never be invoked!
524    * </note>
525    *
526    * Returns: a #GValueArray* with a list of factories to try. The factories are
527    * by default tried in the returned order or based on the index returned by
528    * "autoplug-select".
529    */
530   gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES] =
531       g_signal_new ("autoplug-factories", G_TYPE_FROM_CLASS (klass),
532       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass,
533           autoplug_factories), _gst_array_accumulator, NULL,
534       g_cclosure_marshal_generic, G_TYPE_VALUE_ARRAY, 2,
535       GST_TYPE_PAD, GST_TYPE_CAPS);
536
537   /**
538    * GstURIDecodeBin::autoplug-sort:
539    * @bin: The uridecodebin.
540    * @pad: The #GstPad.
541    * @caps: The #GstCaps.
542    * @factories: A #GValueArray of possible #GstElementFactory to use.
543    *
544    * Once decodebin has found the possible #GstElementFactory objects to try
545    * for @caps on @pad, this signal is emited. The purpose of the signal is for
546    * the application to perform additional sorting or filtering on the element
547    * factory array.
548    *
549    * The callee should copy and modify @factories or return #NULL if the
550    * order should not change.
551    *
552    * <note>
553    *   Invocation of signal handlers stops after one signal handler has
554    *   returned something else than #NULL. Signal handlers are invoked in
555    *   the order they were connected in.
556    *   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
557    *   signal, they will never be invoked!
558    * </note>
559    *
560    * Returns: A new sorted array of #GstElementFactory objects.
561    *
562    * Since: 0.10.33
563    */
564   gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_SORT] =
565       g_signal_new ("autoplug-sort", G_TYPE_FROM_CLASS (klass),
566       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass, autoplug_sort),
567       _gst_array_hasvalue_accumulator, NULL,
568       g_cclosure_marshal_generic, G_TYPE_VALUE_ARRAY, 3,
569       GST_TYPE_PAD, GST_TYPE_CAPS, G_TYPE_VALUE_ARRAY);
570
571   /**
572    * GstURIDecodeBin::autoplug-select:
573    * @bin: The uridecodebin.
574    * @pad: The #GstPad.
575    * @caps: The #GstCaps.
576    * @factory: A #GstElementFactory to use.
577    *
578    * This signal is emitted once uridecodebin has found all the possible
579    * #GstElementFactory that can be used to handle the given @caps. For each of
580    * those factories, this signal is emitted.
581    *
582    * The signal handler should return a #GST_TYPE_AUTOPLUG_SELECT_RESULT enum
583    * value indicating what decodebin should do next.
584    *
585    * A value of #GST_AUTOPLUG_SELECT_TRY will try to autoplug an element from
586    * @factory.
587    *
588    * A value of #GST_AUTOPLUG_SELECT_EXPOSE will expose @pad without plugging
589    * any element to it.
590    *
591    * A value of #GST_AUTOPLUG_SELECT_SKIP will skip @factory and move to the
592    * next factory.
593    *
594    * <note>
595    *   Only the signal handler that is connected first will ever by invoked.
596    *   Don't connect signal handlers with the #G_CONNECT_AFTER flag to this
597    *   signal, they will never be invoked!
598    * </note>
599    *
600    * Returns: a #GST_TYPE_AUTOPLUG_SELECT_RESULT that indicates the required
601    * operation. The default handler will always return
602    * #GST_AUTOPLUG_SELECT_TRY.
603    */
604   gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT] =
605       g_signal_new ("autoplug-select", G_TYPE_FROM_CLASS (klass),
606       G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstURIDecodeBinClass,
607           autoplug_select), _gst_select_accumulator, NULL,
608       g_cclosure_marshal_generic,
609       GST_TYPE_AUTOPLUG_SELECT_RESULT, 3, GST_TYPE_PAD, GST_TYPE_CAPS,
610       GST_TYPE_ELEMENT_FACTORY);
611
612   /**
613    * GstURIDecodeBin::drained:
614    *
615    * This signal is emitted when the data for the current uri is played.
616    */
617   gst_uri_decode_bin_signals[SIGNAL_DRAINED] =
618       g_signal_new ("drained", G_TYPE_FROM_CLASS (klass),
619       G_SIGNAL_RUN_LAST,
620       G_STRUCT_OFFSET (GstURIDecodeBinClass, drained), NULL, NULL,
621       g_cclosure_marshal_generic, G_TYPE_NONE, 0, G_TYPE_NONE);
622
623   /**
624    * GstURIDecodeBin::source-setup:
625    * @bin: the uridecodebin.
626    * @source: source element
627    *
628    * This signal is emitted after the source element has been created, so
629    * it can be configured by setting additional properties (e.g. set a
630    * proxy server for an http source, or set the device and read speed for
631    * an audio cd source). This is functionally equivalent to connecting to
632    * the notify::source signal, but more convenient.
633    *
634    * Since: 0.10.33
635    */
636   gst_uri_decode_bin_signals[SIGNAL_SOURCE_SETUP] =
637       g_signal_new ("source-setup", G_TYPE_FROM_CLASS (klass),
638       G_SIGNAL_RUN_LAST, 0, NULL, NULL,
639       g_cclosure_marshal_generic, G_TYPE_NONE, 1, GST_TYPE_ELEMENT);
640
641   gst_element_class_add_pad_template (gstelement_class,
642       gst_static_pad_template_get (&srctemplate));
643   gst_element_class_set_static_metadata (gstelement_class,
644       "URI Decoder", "Generic/Bin/Decoder",
645       "Autoplug and decode an URI to raw media",
646       "Wim Taymans <wim.taymans@gmail.com>");
647
648   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_uri_decode_bin_query);
649   gstelement_class->change_state =
650       GST_DEBUG_FUNCPTR (gst_uri_decode_bin_change_state);
651
652   gstbin_class->handle_message = GST_DEBUG_FUNCPTR (handle_message);
653
654   klass->autoplug_continue =
655       GST_DEBUG_FUNCPTR (gst_uri_decode_bin_autoplug_continue);
656   klass->autoplug_factories =
657       GST_DEBUG_FUNCPTR (gst_uri_decode_bin_autoplug_factories);
658   klass->autoplug_sort = GST_DEBUG_FUNCPTR (gst_uri_decode_bin_autoplug_sort);
659   klass->autoplug_select =
660       GST_DEBUG_FUNCPTR (gst_uri_decode_bin_autoplug_select);
661 }
662
663 static void
664 gst_uri_decode_bin_init (GstURIDecodeBin * dec)
665 {
666   /* first filter out the interesting element factories */
667   dec->factories_lock = g_mutex_new ();
668
669   dec->lock = g_mutex_new ();
670
671   dec->uri = g_strdup (DEFAULT_PROP_URI);
672   dec->connection_speed = DEFAULT_CONNECTION_SPEED;
673   dec->caps = DEFAULT_CAPS;
674   dec->encoding = g_strdup (DEFAULT_SUBTITLE_ENCODING);
675
676   dec->buffer_duration = DEFAULT_BUFFER_DURATION;
677   dec->buffer_size = DEFAULT_BUFFER_SIZE;
678   dec->download = DEFAULT_DOWNLOAD;
679   dec->use_buffering = DEFAULT_USE_BUFFERING;
680   dec->expose_allstreams = DEFAULT_EXPOSE_ALL_STREAMS;
681   dec->ring_buffer_max_size = DEFAULT_RING_BUFFER_MAX_SIZE;
682
683   GST_OBJECT_FLAG_SET (dec, GST_ELEMENT_FLAG_SOURCE);
684 }
685
686 static void
687 gst_uri_decode_bin_finalize (GObject * obj)
688 {
689   GstURIDecodeBin *dec = GST_URI_DECODE_BIN (obj);
690
691   remove_decoders (dec, TRUE);
692   g_mutex_free (dec->lock);
693   g_mutex_free (dec->factories_lock);
694   g_free (dec->uri);
695   g_free (dec->encoding);
696   if (dec->factories)
697     gst_plugin_feature_list_free (dec->factories);
698   if (dec->caps)
699     gst_caps_unref (dec->caps);
700
701   G_OBJECT_CLASS (parent_class)->finalize (obj);
702 }
703
704 static void
705 gst_uri_decode_bin_set_encoding (GstURIDecodeBin * dec, const gchar * encoding)
706 {
707   GSList *walk;
708
709   GST_URI_DECODE_BIN_LOCK (dec);
710
711   /* set property first */
712   GST_OBJECT_LOCK (dec);
713   g_free (dec->encoding);
714   dec->encoding = g_strdup (encoding);
715   GST_OBJECT_UNLOCK (dec);
716
717   /* set the property on all decodebins now */
718   for (walk = dec->decodebins; walk; walk = g_slist_next (walk)) {
719     GObject *decodebin = G_OBJECT (walk->data);
720
721     g_object_set (decodebin, "subtitle-encoding", encoding, NULL);
722   }
723   GST_URI_DECODE_BIN_UNLOCK (dec);
724 }
725
726 static void
727 gst_uri_decode_bin_set_property (GObject * object, guint prop_id,
728     const GValue * value, GParamSpec * pspec)
729 {
730   GstURIDecodeBin *dec = GST_URI_DECODE_BIN (object);
731
732   switch (prop_id) {
733     case PROP_URI:
734       GST_OBJECT_LOCK (dec);
735       g_free (dec->uri);
736       dec->uri = g_value_dup_string (value);
737       GST_OBJECT_UNLOCK (dec);
738       break;
739     case PROP_CONNECTION_SPEED:
740       GST_OBJECT_LOCK (dec);
741       dec->connection_speed = g_value_get_uint64 (value) * 1000;
742       GST_OBJECT_UNLOCK (dec);
743       break;
744     case PROP_CAPS:
745       GST_OBJECT_LOCK (dec);
746       if (dec->caps)
747         gst_caps_unref (dec->caps);
748       dec->caps = g_value_dup_boxed (value);
749       GST_OBJECT_UNLOCK (dec);
750       break;
751     case PROP_SUBTITLE_ENCODING:
752       gst_uri_decode_bin_set_encoding (dec, g_value_get_string (value));
753       break;
754     case PROP_BUFFER_SIZE:
755       dec->buffer_size = g_value_get_int (value);
756       break;
757     case PROP_BUFFER_DURATION:
758       dec->buffer_duration = g_value_get_int64 (value);
759       break;
760     case PROP_DOWNLOAD:
761       dec->download = g_value_get_boolean (value);
762       break;
763     case PROP_USE_BUFFERING:
764       dec->use_buffering = g_value_get_boolean (value);
765       break;
766     case PROP_EXPOSE_ALL_STREAMS:
767       dec->expose_allstreams = g_value_get_boolean (value);
768       break;
769     case PROP_RING_BUFFER_MAX_SIZE:
770       dec->ring_buffer_max_size = g_value_get_uint64 (value);
771       break;
772     default:
773       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
774       break;
775   }
776 }
777
778 static void
779 gst_uri_decode_bin_get_property (GObject * object, guint prop_id,
780     GValue * value, GParamSpec * pspec)
781 {
782   GstURIDecodeBin *dec = GST_URI_DECODE_BIN (object);
783
784   switch (prop_id) {
785     case PROP_URI:
786       GST_OBJECT_LOCK (dec);
787       g_value_set_string (value, dec->uri);
788       GST_OBJECT_UNLOCK (dec);
789       break;
790     case PROP_SOURCE:
791       GST_OBJECT_LOCK (dec);
792       g_value_set_object (value, dec->source);
793       GST_OBJECT_UNLOCK (dec);
794       break;
795     case PROP_CONNECTION_SPEED:
796       GST_OBJECT_LOCK (dec);
797       g_value_set_uint64 (value, dec->connection_speed / 1000);
798       GST_OBJECT_UNLOCK (dec);
799       break;
800     case PROP_CAPS:
801       GST_OBJECT_LOCK (dec);
802       g_value_set_boxed (value, dec->caps);
803       GST_OBJECT_UNLOCK (dec);
804       break;
805     case PROP_SUBTITLE_ENCODING:
806       GST_OBJECT_LOCK (dec);
807       g_value_set_string (value, dec->encoding);
808       GST_OBJECT_UNLOCK (dec);
809       break;
810     case PROP_BUFFER_SIZE:
811       GST_OBJECT_LOCK (dec);
812       g_value_set_int (value, dec->buffer_size);
813       GST_OBJECT_UNLOCK (dec);
814       break;
815     case PROP_BUFFER_DURATION:
816       GST_OBJECT_LOCK (dec);
817       g_value_set_int64 (value, dec->buffer_duration);
818       GST_OBJECT_UNLOCK (dec);
819       break;
820     case PROP_DOWNLOAD:
821       g_value_set_boolean (value, dec->download);
822       break;
823     case PROP_USE_BUFFERING:
824       g_value_set_boolean (value, dec->use_buffering);
825       break;
826     case PROP_EXPOSE_ALL_STREAMS:
827       g_value_set_boolean (value, dec->expose_allstreams);
828       break;
829     case PROP_RING_BUFFER_MAX_SIZE:
830       g_value_set_uint64 (value, dec->ring_buffer_max_size);
831       break;
832     default:
833       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
834       break;
835   }
836 }
837
838 static void
839 do_async_start (GstURIDecodeBin * dbin)
840 {
841   GstMessage *message;
842
843   dbin->async_pending = TRUE;
844
845   message = gst_message_new_async_start (GST_OBJECT_CAST (dbin));
846   GST_BIN_CLASS (parent_class)->handle_message (GST_BIN_CAST (dbin), message);
847 }
848
849 static void
850 do_async_done (GstURIDecodeBin * dbin)
851 {
852   GstMessage *message;
853
854   if (dbin->async_pending) {
855     GST_DEBUG_OBJECT (dbin, "posting ASYNC_DONE");
856     message = gst_message_new_async_done (GST_OBJECT_CAST (dbin), FALSE);
857     GST_BIN_CLASS (parent_class)->handle_message (GST_BIN_CAST (dbin), message);
858
859     dbin->async_pending = FALSE;
860   }
861 }
862
863 #define DEFAULT_QUEUE_SIZE          (3 * GST_SECOND)
864 #define DEFAULT_QUEUE_MIN_THRESHOLD ((DEFAULT_QUEUE_SIZE * 30) / 100)
865 #define DEFAULT_QUEUE_THRESHOLD     ((DEFAULT_QUEUE_SIZE * 95) / 100)
866
867 static void
868 unknown_type_cb (GstElement * element, GstPad * pad, GstCaps * caps,
869     GstURIDecodeBin * decoder)
870 {
871   gchar *capsstr;
872
873   capsstr = gst_caps_to_string (caps);
874   GST_ELEMENT_WARNING (decoder, STREAM, CODEC_NOT_FOUND,
875       (_("No decoder available for type \'%s\'."), capsstr), (NULL));
876   g_free (capsstr);
877 }
878
879 /* add a streaminfo that indicates that the stream is handled by the
880  * given element. This usually means that a stream without actual data is
881  * produced but one that is sunken by an element. Examples of this are:
882  * cdaudio, a hardware decoder/sink, dvd meta bins etc...
883  */
884 static void
885 add_element_stream (GstElement * element, GstURIDecodeBin * decoder)
886 {
887   g_warning ("add element stream");
888 }
889
890 /* when the decoder element signals that no more pads will be generated, we
891  * can commit the current group.
892  */
893 static void
894 no_more_pads_full (GstElement * element, gboolean subs,
895     GstURIDecodeBin * decoder)
896 {
897   gboolean final;
898
899   /* setup phase */
900   GST_DEBUG_OBJECT (element, "no more pads, %d pending", decoder->pending);
901
902   GST_URI_DECODE_BIN_LOCK (decoder);
903   final = (decoder->pending == 0);
904
905   /* nothing pending, we can exit */
906   if (final)
907     goto done;
908
909   /* the object has no pending no_more_pads */
910   if (!g_object_get_data (G_OBJECT (element), "pending"))
911     goto done;
912   g_object_set_data (G_OBJECT (element), "pending", NULL);
913
914   decoder->pending--;
915   final = (decoder->pending == 0);
916
917 done:
918   GST_URI_DECODE_BIN_UNLOCK (decoder);
919
920   if (final)
921     gst_element_no_more_pads (GST_ELEMENT_CAST (decoder));
922
923   return;
924 }
925
926 static void
927 no_more_pads (GstElement * element, GstURIDecodeBin * decoder)
928 {
929   no_more_pads_full (element, FALSE, decoder);
930 }
931
932 static void
933 source_no_more_pads (GstElement * element, GstURIDecodeBin * bin)
934 {
935   GST_DEBUG_OBJECT (bin, "No more pads in source element %s.",
936       GST_ELEMENT_NAME (element));
937
938   g_signal_handler_disconnect (element, bin->src_np_sig_id);
939   bin->src_np_sig_id = 0;
940   g_signal_handler_disconnect (element, bin->src_nmp_sig_id);
941   bin->src_nmp_sig_id = 0;
942
943   no_more_pads_full (element, FALSE, bin);
944 }
945
946 static void
947 configure_stream_buffering (GstURIDecodeBin * decoder)
948 {
949   GstElement *queue = NULL;
950   GHashTableIter iter;
951   gpointer key, value;
952   gint bitrate = 0;
953
954   /* automatic configuration enabled ? */
955   if (decoder->buffer_size != -1)
956     return;
957
958   GST_URI_DECODE_BIN_LOCK (decoder);
959   if (decoder->queue)
960     queue = gst_object_ref (decoder->queue);
961
962   g_hash_table_iter_init (&iter, decoder->streams);
963   while (g_hash_table_iter_next (&iter, &key, &value)) {
964     GstURIDecodeBinStream *stream = value;
965
966     if (stream->bitrate && bitrate >= 0)
967       bitrate += stream->bitrate;
968     else
969       bitrate = -1;
970   }
971   GST_URI_DECODE_BIN_UNLOCK (decoder);
972
973   GST_DEBUG_OBJECT (decoder, "overall bitrate %d", bitrate);
974   if (!queue)
975     return;
976
977   if (bitrate > 0) {
978     guint64 time;
979     guint bytes;
980
981     /* all streams have a bitrate;
982      * configure queue size based on queue duration using combined bitrate */
983     g_object_get (queue, "max-size-time", &time, NULL);
984     GST_DEBUG_OBJECT (decoder, "queue buffering time %" GST_TIME_FORMAT,
985         GST_TIME_ARGS (time));
986     if (time > 0) {
987       bytes = gst_util_uint64_scale (time, bitrate, 8 * GST_SECOND);
988       GST_DEBUG_OBJECT (decoder, "corresponds to buffer size %d", bytes);
989       g_object_set (queue, "max-size-bytes", bytes, NULL);
990     }
991   }
992
993   gst_object_unref (queue);
994 }
995
996 static GstPadProbeReturn
997 decoded_pad_event_probe (GstPad * pad, GstPadProbeInfo * info,
998     gpointer user_data)
999 {
1000   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
1001   GstURIDecodeBin *decoder = user_data;
1002
1003   GST_LOG_OBJECT (pad, "%s, decoder %p", GST_EVENT_TYPE_NAME (event), decoder);
1004
1005   /* look for a bitrate tag */
1006   switch (GST_EVENT_TYPE (event)) {
1007     case GST_EVENT_TAG:
1008     {
1009       GstTagList *list;
1010       guint bitrate = 0;
1011       GstURIDecodeBinStream *stream;
1012
1013       gst_event_parse_tag (event, &list);
1014       if (!gst_tag_list_get_uint_index (list, GST_TAG_NOMINAL_BITRATE, 0,
1015               &bitrate)) {
1016         gst_tag_list_get_uint_index (list, GST_TAG_BITRATE, 0, &bitrate);
1017       }
1018       GST_DEBUG_OBJECT (pad, "found bitrate %u", bitrate);
1019       if (bitrate) {
1020         GST_URI_DECODE_BIN_LOCK (decoder);
1021         stream = g_hash_table_lookup (decoder->streams, pad);
1022         GST_URI_DECODE_BIN_UNLOCK (decoder);
1023         if (stream) {
1024           stream->bitrate = bitrate;
1025           /* no longer need this probe now */
1026           gst_pad_remove_probe (pad, stream->probe_id);
1027           /* configure buffer if possible */
1028           configure_stream_buffering (decoder);
1029         }
1030       }
1031       break;
1032     }
1033     default:
1034       break;
1035   }
1036
1037   /* never drop */
1038   return GST_PAD_PROBE_OK;
1039 }
1040
1041 /* Called by the signal handlers when a decodebin has found a new raw pad */
1042 static void
1043 new_decoded_pad_added_cb (GstElement * element, GstPad * pad,
1044     GstURIDecodeBin * decoder)
1045 {
1046   GstPad *newpad;
1047   GstPadTemplate *pad_tmpl;
1048   gchar *padname;
1049   GstURIDecodeBinStream *stream;
1050
1051   GST_DEBUG_OBJECT (element, "new decoded pad, name: <%s>", GST_PAD_NAME (pad));
1052
1053   GST_URI_DECODE_BIN_LOCK (decoder);
1054   padname = g_strdup_printf ("src_%u", decoder->numpads);
1055   decoder->numpads++;
1056   GST_URI_DECODE_BIN_UNLOCK (decoder);
1057
1058   pad_tmpl = gst_static_pad_template_get (&srctemplate);
1059   newpad = gst_ghost_pad_new_from_template (padname, pad, pad_tmpl);
1060   gst_object_unref (pad_tmpl);
1061   g_free (padname);
1062
1063   /* store ref to the ghostpad so we can remove it */
1064   g_object_set_data (G_OBJECT (pad), "uridecodebin.ghostpad", newpad);
1065
1066   /* add event probe to monitor tags */
1067   stream = g_slice_alloc0 (sizeof (GstURIDecodeBinStream));
1068   stream->probe_id =
1069       gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
1070       decoded_pad_event_probe, decoder, NULL);
1071   GST_URI_DECODE_BIN_LOCK (decoder);
1072   g_hash_table_insert (decoder->streams, pad, stream);
1073   GST_URI_DECODE_BIN_UNLOCK (decoder);
1074
1075   gst_pad_set_active (newpad, TRUE);
1076   gst_element_add_pad (GST_ELEMENT_CAST (decoder), newpad);
1077 }
1078
1079 static GstPadProbeReturn
1080 source_pad_event_probe (GstPad * pad, GstPadProbeInfo * info,
1081     gpointer user_data)
1082 {
1083   GstEvent *event = GST_PAD_PROBE_INFO_EVENT (info);
1084   GstURIDecodeBin *decoder = user_data;
1085
1086   GST_LOG_OBJECT (pad, "%s, decoder %p", GST_EVENT_TYPE_NAME (event), decoder);
1087
1088   if (GST_EVENT_TYPE (event) == GST_EVENT_EOS) {
1089     GST_DEBUG_OBJECT (pad, "we received EOS");
1090
1091     g_signal_emit (decoder,
1092         gst_uri_decode_bin_signals[SIGNAL_DRAINED], 0, NULL);
1093   }
1094   /* never drop events */
1095   return GST_PAD_PROBE_OK;
1096 }
1097
1098 /* called when we found a raw pad on the source element. We need to set up a
1099  * padprobe to detect EOS before exposing the pad. */
1100 static void
1101 expose_decoded_pad (GstElement * element, GstPad * pad,
1102     GstURIDecodeBin * decoder)
1103 {
1104   gst_pad_add_probe (pad, GST_PAD_PROBE_TYPE_EVENT_DOWNSTREAM,
1105       source_pad_event_probe, decoder, NULL);
1106
1107   new_decoded_pad_added_cb (element, pad, decoder);
1108 }
1109
1110 static void
1111 pad_removed_cb (GstElement * element, GstPad * pad, GstURIDecodeBin * decoder)
1112 {
1113   GstPad *ghost;
1114
1115   GST_DEBUG_OBJECT (element, "pad removed name: <%s:%s>",
1116       GST_DEBUG_PAD_NAME (pad));
1117
1118   /* we only care about srcpads */
1119   if (!GST_PAD_IS_SRC (pad))
1120     return;
1121
1122   if (!(ghost = g_object_get_data (G_OBJECT (pad), "uridecodebin.ghostpad")))
1123     goto no_ghost;
1124
1125   /* unghost the pad */
1126   gst_ghost_pad_set_target (GST_GHOST_PAD_CAST (ghost), NULL);
1127
1128   /* deactivate and remove */
1129   gst_pad_set_active (pad, FALSE);
1130   gst_element_remove_pad (GST_ELEMENT_CAST (decoder), ghost);
1131
1132   return;
1133
1134   /* ERRORS */
1135 no_ghost:
1136   {
1137     GST_WARNING_OBJECT (element, "no ghost pad found");
1138     return;
1139   }
1140 }
1141
1142 /* helper function to lookup stuff in lists */
1143 static gboolean
1144 array_has_value (const gchar * values[], const gchar * value)
1145 {
1146   gint i;
1147
1148   for (i = 0; values[i]; i++) {
1149     if (g_str_has_prefix (value, values[i]))
1150       return TRUE;
1151   }
1152   return FALSE;
1153 }
1154
1155 static gboolean
1156 array_has_uri_value (const gchar * values[], const gchar * value)
1157 {
1158   gint i;
1159
1160   for (i = 0; values[i]; i++) {
1161     if (!g_ascii_strncasecmp (value, values[i], strlen (values[i])))
1162       return TRUE;
1163   }
1164   return FALSE;
1165 }
1166
1167 /* list of URIs that we consider to be streams and that need buffering.
1168  * We have no mechanism yet to figure this out with a query. */
1169 static const gchar *stream_uris[] = { "http://", "https://", "mms://",
1170   "mmsh://", "mmsu://", "mmst://", "fd://", "myth://", "ssh://",
1171   "ftp://", "sftp://",
1172   NULL
1173 };
1174
1175 /* list of URIs that need a queue because they are pretty bursty */
1176 static const gchar *queue_uris[] = { "cdda://", NULL };
1177
1178 /* blacklisted URIs, we know they will always fail. */
1179 static const gchar *blacklisted_uris[] = { NULL };
1180
1181 /* mime types that we don't consider to be media types */
1182 #if 0
1183 static const gchar *no_media_mimes[] = {
1184   "application/x-executable", "application/x-bzip", "application/x-gzip",
1185   "application/zip", "application/x-compress", NULL
1186 };
1187 #endif
1188
1189 /* media types we can download */
1190 static const gchar *download_media[] = {
1191   "video/quicktime", "video/mj2", "audio/x-m4a", "application/x-3gp",
1192   "video/x-flv", "video/x-msvideo", "video/webm", NULL
1193 };
1194
1195 #define IS_STREAM_URI(uri)          (array_has_uri_value (stream_uris, uri))
1196 #define IS_QUEUE_URI(uri)           (array_has_uri_value (queue_uris, uri))
1197 #define IS_BLACKLISTED_URI(uri)     (array_has_uri_value (blacklisted_uris, uri))
1198 #define IS_NO_MEDIA_MIME(mime)      (array_has_value (no_media_mimes, mime))
1199 #define IS_DOWNLOAD_MEDIA(media)    (array_has_value (download_media, media))
1200
1201 /*
1202  * Generate and configure a source element.
1203  */
1204 static GstElement *
1205 gen_source_element (GstURIDecodeBin * decoder)
1206 {
1207   GObjectClass *source_class;
1208   GstElement *source;
1209   GParamSpec *pspec;
1210
1211   if (!decoder->uri)
1212     goto no_uri;
1213
1214   GST_LOG_OBJECT (decoder, "finding source for %s", decoder->uri);
1215
1216   if (!gst_uri_is_valid (decoder->uri))
1217     goto invalid_uri;
1218
1219   if (IS_BLACKLISTED_URI (decoder->uri))
1220     goto uri_blacklisted;
1221
1222   source = gst_element_make_from_uri (GST_URI_SRC, decoder->uri, "source");
1223   if (!source)
1224     goto no_source;
1225
1226   GST_LOG_OBJECT (decoder, "found source type %s", G_OBJECT_TYPE_NAME (source));
1227
1228   decoder->is_stream = IS_STREAM_URI (decoder->uri);
1229   GST_LOG_OBJECT (decoder, "source is stream: %d", decoder->is_stream);
1230
1231   decoder->need_queue = IS_QUEUE_URI (decoder->uri);
1232   GST_LOG_OBJECT (decoder, "source needs queue: %d", decoder->need_queue);
1233
1234   source_class = G_OBJECT_GET_CLASS (source);
1235
1236   /* make HTTP sources send extra headers so we get icecast
1237    * metadata in case the stream is an icecast stream */
1238   if (!strncmp (decoder->uri, "http://", 7) &&
1239       g_object_class_find_property (source_class, "iradio-mode")) {
1240     GST_LOG_OBJECT (decoder, "configuring iradio-mode");
1241     g_object_set (source, "iradio-mode", TRUE, NULL);
1242   }
1243
1244   pspec = g_object_class_find_property (source_class, "connection-speed");
1245   if (pspec != NULL) {
1246     if (G_PARAM_SPEC_VALUE_TYPE (pspec) == G_TYPE_UINT64 ||
1247         G_PARAM_SPEC_VALUE_TYPE (pspec) == G_TYPE_INT64) {
1248       GST_DEBUG_OBJECT (decoder,
1249           "setting connection-speed=%" G_GUINT64_FORMAT " on source element %s",
1250           decoder->connection_speed / 1000, G_OBJECT_TYPE_NAME (source));
1251
1252       g_object_set (source, "connection-speed",
1253           decoder->connection_speed / 1000, NULL);
1254     } else {
1255       g_warning ("connection-speed property of '%s' is not a 64-bit int type",
1256           G_OBJECT_TYPE_NAME (source));
1257     }
1258   }
1259
1260   pspec = g_object_class_find_property (source_class, "subtitle-encoding");
1261   if (pspec != NULL && G_PARAM_SPEC_VALUE_TYPE (pspec) == G_TYPE_STRING) {
1262     GST_DEBUG_OBJECT (decoder,
1263         "setting subtitle-encoding=%s to source element", decoder->encoding);
1264     g_object_set (source, "subtitle-encoding", decoder->encoding, NULL);
1265   }
1266   return source;
1267
1268   /* ERRORS */
1269 no_uri:
1270   {
1271     GST_ELEMENT_ERROR (decoder, RESOURCE, NOT_FOUND,
1272         (_("No URI specified to play from.")), (NULL));
1273     return NULL;
1274   }
1275 invalid_uri:
1276   {
1277     GST_ELEMENT_ERROR (decoder, RESOURCE, NOT_FOUND,
1278         (_("Invalid URI \"%s\"."), decoder->uri), (NULL));
1279     return NULL;
1280   }
1281 uri_blacklisted:
1282   {
1283     GST_ELEMENT_ERROR (decoder, RESOURCE, FAILED,
1284         (_("This stream type cannot be played yet.")), (NULL));
1285     return NULL;
1286   }
1287 no_source:
1288   {
1289     gchar *prot = gst_uri_get_protocol (decoder->uri);
1290
1291     /* whoops, could not create the source element, dig a little deeper to
1292      * figure out what might be wrong. */
1293     if (prot) {
1294       GstMessage *msg;
1295
1296       msg =
1297           gst_missing_uri_source_message_new (GST_ELEMENT_CAST (decoder), prot);
1298       gst_element_post_message (GST_ELEMENT_CAST (decoder), msg);
1299
1300       GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN,
1301           (_("No URI handler implemented for \"%s\"."), prot), (NULL));
1302       g_free (prot);
1303     } else
1304       goto invalid_uri;
1305
1306     return NULL;
1307   }
1308 }
1309
1310 /**
1311  * has_all_raw_caps:
1312  * @pad: a #GstPad
1313  * @all_raw: pointer to hold the result
1314  *
1315  * check if the caps of the pad are all raw. The caps are all raw if
1316  * all of its structures contain audio/x-raw or video/x-raw.
1317  *
1318  * Returns: %FALSE @pad has no caps. Else TRUE and @all_raw set t the result.
1319  */
1320 static gboolean
1321 has_all_raw_caps (GstPad * pad, GstCaps * rawcaps, gboolean * all_raw)
1322 {
1323   GstCaps *caps, *intersection;
1324   gint capssize;
1325   gboolean res = FALSE;
1326
1327   caps = gst_pad_query_caps (pad, NULL);
1328   if (caps == NULL)
1329     return FALSE;
1330
1331   GST_DEBUG_OBJECT (pad, "have caps %" GST_PTR_FORMAT, caps);
1332
1333   capssize = gst_caps_get_size (caps);
1334   /* no caps, skip and move to the next pad */
1335   if (capssize == 0 || gst_caps_is_empty (caps) || gst_caps_is_any (caps))
1336     goto done;
1337
1338   intersection = gst_caps_intersect (caps, rawcaps);
1339   *all_raw = !gst_caps_is_empty (intersection)
1340       && (gst_caps_get_size (intersection) == capssize);
1341   gst_caps_unref (intersection);
1342
1343   res = TRUE;
1344
1345 done:
1346   gst_caps_unref (caps);
1347   return res;
1348 }
1349
1350 static void
1351 post_missing_plugin_error (GstElement * dec, const gchar * element_name)
1352 {
1353   GstMessage *msg;
1354
1355   msg = gst_missing_element_message_new (dec, element_name);
1356   gst_element_post_message (dec, msg);
1357
1358   GST_ELEMENT_ERROR (dec, CORE, MISSING_PLUGIN,
1359       (_("Missing element '%s' - check your GStreamer installation."),
1360           element_name), (NULL));
1361 }
1362
1363 /**
1364  * analyse_source:
1365  * @decoder: a #GstURIDecodeBin
1366  * @is_raw: are all pads raw data
1367  * @have_out: does the source have output
1368  * @is_dynamic: is this a dynamic source
1369  * @use_queue: put a queue before raw output pads
1370  *
1371  * Check the source of @decoder and collect information about it.
1372  *
1373  * @is_raw will be set to TRUE if the source only produces raw pads. When this
1374  * function returns, all of the raw pad of the source will be added
1375  * to @decoder.
1376  *
1377  * @have_out: will be set to TRUE if the source has output pads.
1378  *
1379  * @is_dynamic: TRUE if the element will create (more) pads dynamically later
1380  * on.
1381  *
1382  * Returns: FALSE if a fatal error occured while scanning.
1383  */
1384 static gboolean
1385 analyse_source (GstURIDecodeBin * decoder, gboolean * is_raw,
1386     gboolean * have_out, gboolean * is_dynamic, gboolean use_queue)
1387 {
1388   GstIterator *pads_iter;
1389   gboolean done = FALSE;
1390   gboolean res = TRUE;
1391   GstCaps *rawcaps;
1392   GstPad *pad;
1393   GValue item = { 0, };
1394
1395   *have_out = FALSE;
1396   *is_raw = FALSE;
1397   *is_dynamic = FALSE;
1398
1399   g_object_get (decoder, "caps", &rawcaps, NULL);
1400   if (!rawcaps)
1401     rawcaps = DEFAULT_CAPS;
1402
1403   pads_iter = gst_element_iterate_src_pads (decoder->source);
1404   while (!done) {
1405     switch (gst_iterator_next (pads_iter, &item)) {
1406       case GST_ITERATOR_ERROR:
1407         res = FALSE;
1408         /* FALLTROUGH */
1409       case GST_ITERATOR_DONE:
1410         done = TRUE;
1411         break;
1412       case GST_ITERATOR_RESYNC:
1413         /* reset results and resync */
1414         *have_out = FALSE;
1415         *is_raw = FALSE;
1416         *is_dynamic = FALSE;
1417         gst_iterator_resync (pads_iter);
1418         break;
1419       case GST_ITERATOR_OK:
1420         pad = g_value_get_object (&item);
1421         /* we now officially have an ouput pad */
1422         *have_out = TRUE;
1423
1424         /* if FALSE, this pad has no caps and we continue with the next pad. */
1425         if (!has_all_raw_caps (pad, rawcaps, is_raw)) {
1426           g_value_reset (&item);
1427           break;
1428         }
1429
1430         /* caps on source pad are all raw, we can add the pad */
1431         if (*is_raw) {
1432           GstElement *outelem;
1433
1434           if (use_queue) {
1435             GstPad *sinkpad;
1436
1437             /* insert a queue element right before the raw pad */
1438             outelem = gst_element_factory_make ("queue2", NULL);
1439             if (!outelem)
1440               goto no_queue2;
1441
1442             gst_bin_add (GST_BIN_CAST (decoder), outelem);
1443
1444             sinkpad = gst_element_get_static_pad (outelem, "sink");
1445             gst_pad_link (pad, sinkpad);
1446             gst_object_unref (sinkpad);
1447             gst_object_unref (pad);
1448
1449             /* save queue pointer so we can remove it later */
1450             decoder->queue = outelem;
1451
1452             /* get the new raw srcpad */
1453             pad = gst_element_get_static_pad (outelem, "src");
1454           } else {
1455             outelem = decoder->source;
1456           }
1457           expose_decoded_pad (outelem, pad, decoder);
1458         }
1459         g_value_reset (&item);
1460         break;
1461     }
1462   }
1463   g_value_unset (&item);
1464   gst_iterator_free (pads_iter);
1465   gst_caps_unref (rawcaps);
1466
1467   if (!*have_out) {
1468     GstElementClass *elemclass;
1469     GList *walk;
1470
1471     /* element has no output pads, check for padtemplates that list SOMETIMES
1472      * pads. */
1473     elemclass = GST_ELEMENT_GET_CLASS (decoder->source);
1474
1475     walk = gst_element_class_get_pad_template_list (elemclass);
1476     while (walk != NULL) {
1477       GstPadTemplate *templ;
1478
1479       templ = (GstPadTemplate *) walk->data;
1480       if (GST_PAD_TEMPLATE_DIRECTION (templ) == GST_PAD_SRC) {
1481         if (GST_PAD_TEMPLATE_PRESENCE (templ) == GST_PAD_SOMETIMES)
1482           *is_dynamic = TRUE;
1483         break;
1484       }
1485       walk = g_list_next (walk);
1486     }
1487   }
1488
1489   return res;
1490 no_queue2:
1491   {
1492     post_missing_plugin_error (GST_ELEMENT_CAST (decoder), "queue2");
1493
1494     g_value_unset (&item);
1495     gst_iterator_free (pads_iter);
1496     gst_caps_unref (rawcaps);
1497
1498     return FALSE;
1499   }
1500 }
1501
1502 /* Remove all decodebin from ourself
1503  * If force is FALSE, then the decodebin instances will be stored in
1504  * pending_decodebins for re-use later on.
1505  * If force is TRUE, then all decodebin instances will be unreferenced
1506  * and cleared, including the pending ones. */
1507 static void
1508 remove_decoders (GstURIDecodeBin * bin, gboolean force)
1509 {
1510   GSList *walk;
1511
1512   for (walk = bin->decodebins; walk; walk = g_slist_next (walk)) {
1513     GstElement *decoder = GST_ELEMENT_CAST (walk->data);
1514
1515     GST_DEBUG_OBJECT (bin, "removing old decoder element");
1516     if (force) {
1517       gst_element_set_state (decoder, GST_STATE_NULL);
1518       gst_bin_remove (GST_BIN_CAST (bin), decoder);
1519     } else {
1520       GstCaps *caps;
1521
1522       gst_element_set_state (decoder, GST_STATE_READY);
1523       /* add it to our list of pending decodebins */
1524       g_object_ref (decoder);
1525       gst_bin_remove (GST_BIN_CAST (bin), decoder);
1526       /* restore some properties we might have changed */
1527       g_object_set (decoder, "sink-caps", NULL, NULL);
1528       caps = DEFAULT_CAPS;
1529       g_object_set (decoder, "caps", caps, NULL);
1530       gst_caps_unref (caps);
1531       /* make it freshly floating again */
1532       g_object_force_floating (G_OBJECT (decoder));
1533
1534       bin->pending_decodebins =
1535           g_slist_prepend (bin->pending_decodebins, decoder);
1536     }
1537   }
1538   g_slist_free (bin->decodebins);
1539   bin->decodebins = NULL;
1540   if (force) {
1541     GSList *tmp;
1542
1543     for (tmp = bin->pending_decodebins; tmp; tmp = tmp->next) {
1544       gst_element_set_state ((GstElement *) tmp->data, GST_STATE_NULL);
1545       gst_object_unref ((GstElement *) tmp->data);
1546     }
1547     g_slist_free (bin->pending_decodebins);
1548     bin->pending_decodebins = NULL;
1549
1550   }
1551
1552   /* Don't loose the SOURCE flag */
1553   GST_OBJECT_FLAG_SET (bin, GST_ELEMENT_FLAG_SOURCE);
1554 }
1555
1556 static void
1557 proxy_unknown_type_signal (GstElement * element, GstPad * pad, GstCaps * caps,
1558     GstURIDecodeBin * dec)
1559 {
1560   GST_DEBUG_OBJECT (dec, "unknown-type signaled");
1561
1562   g_signal_emit (dec,
1563       gst_uri_decode_bin_signals[SIGNAL_UNKNOWN_TYPE], 0, pad, caps);
1564 }
1565
1566 static gboolean
1567 proxy_autoplug_continue_signal (GstElement * element, GstPad * pad,
1568     GstCaps * caps, GstURIDecodeBin * dec)
1569 {
1570   gboolean result;
1571
1572   g_signal_emit (dec,
1573       gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_CONTINUE], 0, pad, caps,
1574       &result);
1575
1576   GST_DEBUG_OBJECT (dec, "autoplug-continue returned %d", result);
1577
1578   return result;
1579 }
1580
1581 static GValueArray *
1582 proxy_autoplug_factories_signal (GstElement * element, GstPad * pad,
1583     GstCaps * caps, GstURIDecodeBin * dec)
1584 {
1585   GValueArray *result;
1586
1587   g_signal_emit (dec,
1588       gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_FACTORIES], 0, pad, caps,
1589       &result);
1590
1591   GST_DEBUG_OBJECT (dec, "autoplug-factories returned %p", result);
1592
1593   return result;
1594 }
1595
1596 static GValueArray *
1597 proxy_autoplug_sort_signal (GstElement * element, GstPad * pad,
1598     GstCaps * caps, GValueArray * factories, GstURIDecodeBin * dec)
1599 {
1600   GValueArray *result;
1601
1602   g_signal_emit (dec,
1603       gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_SORT], 0, pad, caps,
1604       factories, &result);
1605
1606   GST_DEBUG_OBJECT (dec, "autoplug-sort returned %p", result);
1607
1608   return result;
1609 }
1610
1611 static GstAutoplugSelectResult
1612 proxy_autoplug_select_signal (GstElement * element, GstPad * pad,
1613     GstCaps * caps, GstElementFactory * factory, GstURIDecodeBin * dec)
1614 {
1615   GstAutoplugSelectResult result;
1616
1617   g_signal_emit (dec,
1618       gst_uri_decode_bin_signals[SIGNAL_AUTOPLUG_SELECT], 0, pad, caps, factory,
1619       &result);
1620
1621   GST_DEBUG_OBJECT (dec, "autoplug-select returned %d", result);
1622
1623   return result;
1624 }
1625
1626 static void
1627 proxy_drained_signal (GstElement * element, GstURIDecodeBin * dec)
1628 {
1629   GST_DEBUG_OBJECT (dec, "drained signaled");
1630
1631   g_signal_emit (dec, gst_uri_decode_bin_signals[SIGNAL_DRAINED], 0, NULL);
1632 }
1633
1634 /* make a decodebin and connect to all the signals */
1635 static GstElement *
1636 make_decoder (GstURIDecodeBin * decoder)
1637 {
1638   GstElement *decodebin;
1639
1640   /* re-use pending decodebin */
1641   if (decoder->pending_decodebins) {
1642     GSList *first = decoder->pending_decodebins;
1643     GST_LOG_OBJECT (decoder, "re-using pending decodebin");
1644     decodebin = (GstElement *) first->data;
1645     decoder->pending_decodebins =
1646         g_slist_delete_link (decoder->pending_decodebins, first);
1647   } else {
1648     GST_LOG_OBJECT (decoder, "making new decodebin");
1649
1650     /* now create the decoder element */
1651     decodebin = gst_element_factory_make ("decodebin", NULL);
1652
1653     if (!decodebin)
1654       goto no_decodebin;
1655
1656     /* sanity check */
1657     if (decodebin->numsinkpads == 0)
1658       goto no_typefind;
1659
1660     /* connect signals to proxy */
1661     g_signal_connect (decodebin, "unknown-type",
1662         G_CALLBACK (proxy_unknown_type_signal), decoder);
1663     g_signal_connect (decodebin, "autoplug-continue",
1664         G_CALLBACK (proxy_autoplug_continue_signal), decoder);
1665     g_signal_connect (decodebin, "autoplug-factories",
1666         G_CALLBACK (proxy_autoplug_factories_signal), decoder);
1667     g_signal_connect (decodebin, "autoplug-sort",
1668         G_CALLBACK (proxy_autoplug_sort_signal), decoder);
1669     g_signal_connect (decodebin, "autoplug-select",
1670         G_CALLBACK (proxy_autoplug_select_signal), decoder);
1671     g_signal_connect (decodebin, "drained",
1672         G_CALLBACK (proxy_drained_signal), decoder);
1673
1674     /* set up callbacks to create the links between decoded data
1675      * and video/audio/subtitle rendering/output. */
1676     g_signal_connect (decodebin,
1677         "pad-added", G_CALLBACK (new_decoded_pad_added_cb), decoder);
1678     g_signal_connect (decodebin,
1679         "pad-removed", G_CALLBACK (pad_removed_cb), decoder);
1680     g_signal_connect (decodebin, "no-more-pads",
1681         G_CALLBACK (no_more_pads), decoder);
1682     g_signal_connect (decodebin,
1683         "unknown-type", G_CALLBACK (unknown_type_cb), decoder);
1684   }
1685
1686   /* configure caps if we have any */
1687   if (decoder->caps)
1688     g_object_set (decodebin, "caps", decoder->caps, NULL);
1689
1690   /* Propagate expose-all-streams property */
1691   g_object_set (decodebin, "expose-all-streams", decoder->expose_allstreams,
1692       NULL);
1693
1694   if (!decoder->is_stream) {
1695     /* propagate the use-buffering property but only when we are not already
1696      * doing stream buffering with queue2. FIXME, we might want to do stream
1697      * buffering with the multiqueue buffering instead of queue2. */
1698     g_object_set (decodebin, "use-buffering", decoder->use_buffering, NULL);
1699
1700     if (decoder->use_buffering) {
1701       guint max_bytes;
1702       guint64 max_time;
1703
1704       /* configure sizes when buffering */
1705       if ((max_bytes = decoder->buffer_size) == -1)
1706         max_bytes = 2 * 1024 * 1024;
1707       if ((max_time = decoder->buffer_duration) == -1)
1708         max_time = 2 * GST_SECOND;
1709
1710       g_object_set (decodebin, "max-size-bytes", max_bytes, "max-size-buffers",
1711           (guint) 0, "max-size-time", max_time, NULL);
1712     }
1713   }
1714
1715   g_object_set_data (G_OBJECT (decodebin), "pending", GINT_TO_POINTER (1));
1716   g_object_set (decodebin, "subtitle-encoding", decoder->encoding, NULL);
1717   decoder->pending++;
1718   GST_LOG_OBJECT (decoder, "have %d pending dynamic objects", decoder->pending);
1719
1720   gst_bin_add (GST_BIN_CAST (decoder), decodebin);
1721
1722   decoder->decodebins = g_slist_prepend (decoder->decodebins, decodebin);
1723
1724   return decodebin;
1725
1726   /* ERRORS */
1727 no_decodebin:
1728   {
1729     post_missing_plugin_error (GST_ELEMENT_CAST (decoder), "decodebin");
1730     GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN, (NULL),
1731         ("No decodebin element, check your installation"));
1732     return NULL;
1733   }
1734 no_typefind:
1735   {
1736     gst_object_unref (decodebin);
1737     GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN, (NULL),
1738         ("No typefind element, decodebin is unusable, check your installation"));
1739     return NULL;
1740   }
1741 }
1742
1743 /* signaled when we have a stream and we need to configure the download
1744  * buffering or regular buffering */
1745 static void
1746 type_found (GstElement * typefind, guint probability,
1747     GstCaps * caps, GstURIDecodeBin * decoder)
1748 {
1749   GstElement *dec_elem, *queue;
1750   GstStructure *s;
1751   const gchar *media_type;
1752
1753   GST_DEBUG_OBJECT (decoder, "typefind found caps %" GST_PTR_FORMAT, caps);
1754
1755   s = gst_caps_get_structure (caps, 0);
1756   media_type = gst_structure_get_name (s);
1757
1758   /* remember if we need download buffering */
1759   decoder->is_download = IS_DOWNLOAD_MEDIA (media_type) && decoder->download;
1760   /* only enable download buffering if the upstream duration is known */
1761   if (decoder->is_download) {
1762     gint64 dur;
1763
1764     decoder->is_download =
1765         (gst_element_query_duration (typefind, GST_FORMAT_BYTES, &dur)
1766         && dur != -1);
1767   }
1768
1769   dec_elem = make_decoder (decoder);
1770   if (!dec_elem)
1771     goto no_decodebin;
1772
1773   queue = gst_element_factory_make ("queue2", NULL);
1774   if (!queue)
1775     goto no_queue2;
1776
1777   g_object_set (queue, "use-buffering", TRUE, NULL);
1778   g_object_set (queue, "ring-buffer-max-size", decoder->ring_buffer_max_size,
1779       NULL);
1780
1781   GST_DEBUG_OBJECT (decoder, "check media-type %s, %d", media_type,
1782       decoder->download);
1783
1784   if (decoder->is_download) {
1785     gchar *temp_template, *filename;
1786     const gchar *tmp_dir, *prgname;
1787
1788     tmp_dir = g_get_tmp_dir ();
1789     prgname = g_get_prgname ();
1790     if (prgname == NULL)
1791       prgname = "GStreamer";
1792
1793     filename = g_strdup_printf ("%s-XXXXXX", prgname);
1794
1795     /* build our filename */
1796     temp_template = g_build_filename (tmp_dir, filename, NULL);
1797
1798     GST_DEBUG_OBJECT (decoder, "enable download buffering in %s (%s, %s, %s)",
1799         temp_template, tmp_dir, prgname, filename);
1800
1801     /* configure progressive download for selected media types */
1802     g_object_set (queue, "temp-template", temp_template, NULL);
1803
1804     g_free (filename);
1805     g_free (temp_template);
1806   }
1807
1808   /* Disable max-size-buffers */
1809   g_object_set (queue, "max-size-buffers", 0, NULL);
1810
1811   /* If buffer size or duration are set, set them on the queue2 element */
1812   if (decoder->buffer_size != -1)
1813     g_object_set (queue, "max-size-bytes", decoder->buffer_size, NULL);
1814   if (decoder->buffer_duration != -1)
1815     g_object_set (queue, "max-size-time", decoder->buffer_duration, NULL);
1816
1817   gst_bin_add (GST_BIN_CAST (decoder), queue);
1818
1819   if (!gst_element_link_pads (typefind, "src", queue, "sink"))
1820     goto could_not_link;
1821
1822   /* to force caps on the decodebin element and avoid reparsing stuff by
1823    * typefind. It also avoids a deadlock in the way typefind activates pads in
1824    * the state change */
1825   g_object_set (dec_elem, "sink-caps", caps, NULL);
1826
1827   if (!gst_element_link_pads (queue, "src", dec_elem, "sink"))
1828     goto could_not_link;
1829
1830   /* PLAYING in one go might fail (see bug #632782) */
1831   gst_element_set_state (dec_elem, GST_STATE_PAUSED);
1832   gst_element_set_state (dec_elem, GST_STATE_PLAYING);
1833   gst_element_set_state (queue, GST_STATE_PLAYING);
1834
1835   do_async_done (decoder);
1836
1837   return;
1838
1839   /* ERRORS */
1840 no_decodebin:
1841   {
1842     /* error was posted */
1843     return;
1844   }
1845 could_not_link:
1846   {
1847     GST_ELEMENT_ERROR (decoder, CORE, NEGOTIATION,
1848         (NULL), ("Can't link typefind to decodebin element"));
1849     return;
1850   }
1851 no_queue2:
1852   {
1853     post_missing_plugin_error (GST_ELEMENT_CAST (decoder), "queue2");
1854     return;
1855   }
1856 }
1857
1858 /* setup a streaming source. This will first plug a typefind element to the
1859  * source. After we find the type, we decide to plug a queue2 and continue to
1860  * plug a decodebin starting from the found caps */
1861 static gboolean
1862 setup_streaming (GstURIDecodeBin * decoder)
1863 {
1864   GstElement *typefind;
1865
1866   /* now create the decoder element */
1867   typefind = gst_element_factory_make ("typefind", NULL);
1868   if (!typefind)
1869     goto no_typefind;
1870
1871   gst_bin_add (GST_BIN_CAST (decoder), typefind);
1872
1873   if (!gst_element_link_pads (decoder->source, NULL, typefind, "sink"))
1874     goto could_not_link;
1875
1876   decoder->typefind = typefind;
1877
1878   /* connect a signal to find out when the typefind element found
1879    * a type */
1880   decoder->have_type_id =
1881       g_signal_connect (decoder->typefind, "have-type",
1882       G_CALLBACK (type_found), decoder);
1883
1884   do_async_start (decoder);
1885
1886   return TRUE;
1887
1888   /* ERRORS */
1889 no_typefind:
1890   {
1891     post_missing_plugin_error (GST_ELEMENT_CAST (decoder), "typefind");
1892     GST_ELEMENT_ERROR (decoder, CORE, MISSING_PLUGIN, (NULL),
1893         ("No typefind element, check your installation"));
1894     return FALSE;
1895   }
1896 could_not_link:
1897   {
1898     GST_ELEMENT_ERROR (decoder, CORE, NEGOTIATION,
1899         (NULL), ("Can't link source to typefind element"));
1900     gst_bin_remove (GST_BIN_CAST (decoder), typefind);
1901     /* Don't loose the SOURCE flag */
1902     GST_OBJECT_FLAG_SET (decoder, GST_ELEMENT_FLAG_SOURCE);
1903     return FALSE;
1904   }
1905 }
1906
1907 static void
1908 free_stream (gpointer value)
1909 {
1910   g_slice_free (GstURIDecodeBinStream, value);
1911 }
1912
1913 /* remove source and all related elements */
1914 static void
1915 remove_source (GstURIDecodeBin * bin)
1916 {
1917   GstElement *source = bin->source;
1918
1919   if (source) {
1920     GST_DEBUG_OBJECT (bin, "removing old src element");
1921     gst_element_set_state (source, GST_STATE_NULL);
1922
1923     if (bin->src_np_sig_id) {
1924       g_signal_handler_disconnect (source, bin->src_np_sig_id);
1925       bin->src_np_sig_id = 0;
1926     }
1927     if (bin->src_nmp_sig_id) {
1928       g_signal_handler_disconnect (source, bin->src_nmp_sig_id);
1929       bin->src_nmp_sig_id = 0;
1930     }
1931     gst_bin_remove (GST_BIN_CAST (bin), source);
1932     bin->source = NULL;
1933   }
1934   if (bin->queue) {
1935     GST_DEBUG_OBJECT (bin, "removing old queue element");
1936     gst_element_set_state (bin->queue, GST_STATE_NULL);
1937     gst_bin_remove (GST_BIN_CAST (bin), bin->queue);
1938     bin->queue = NULL;
1939   }
1940   if (bin->typefind) {
1941     GST_DEBUG_OBJECT (bin, "removing old typefind element");
1942     gst_element_set_state (bin->typefind, GST_STATE_NULL);
1943     gst_bin_remove (GST_BIN_CAST (bin), bin->typefind);
1944     bin->typefind = NULL;
1945   }
1946   if (bin->streams) {
1947     g_hash_table_destroy (bin->streams);
1948     bin->streams = NULL;
1949   }
1950   /* Don't loose the SOURCE flag */
1951   GST_OBJECT_FLAG_SET (bin, GST_ELEMENT_FLAG_SOURCE);
1952 }
1953
1954 /* is called when a dynamic source element created a new pad. */
1955 static void
1956 source_new_pad (GstElement * element, GstPad * pad, GstURIDecodeBin * bin)
1957 {
1958   GstElement *decoder;
1959   gboolean is_raw;
1960   GstCaps *rawcaps;
1961
1962   GST_URI_DECODE_BIN_LOCK (bin);
1963   GST_DEBUG_OBJECT (bin, "Found new pad %s.%s in source element %s",
1964       GST_DEBUG_PAD_NAME (pad), GST_ELEMENT_NAME (element));
1965
1966   g_object_get (bin, "caps", &rawcaps, NULL);
1967   if (!rawcaps)
1968     rawcaps = DEFAULT_CAPS;
1969
1970   /* if this is a pad with all raw caps, we can expose it */
1971   if (has_all_raw_caps (pad, rawcaps, &is_raw) && is_raw) {
1972     /* it's all raw, create output pads. */
1973     GST_URI_DECODE_BIN_UNLOCK (bin);
1974     gst_caps_unref (rawcaps);
1975     expose_decoded_pad (element, pad, bin);
1976     return;
1977   }
1978   gst_caps_unref (rawcaps);
1979
1980   /* not raw, create decoder */
1981   decoder = make_decoder (bin);
1982   if (!decoder)
1983     goto no_decodebin;
1984
1985   /* and link to decoder */
1986   if (!gst_element_link_pads (bin->source, NULL, decoder, "sink"))
1987     goto could_not_link;
1988
1989   GST_DEBUG_OBJECT (bin, "linked decoder to new pad");
1990
1991   gst_element_set_state (decoder, GST_STATE_PLAYING);
1992   GST_URI_DECODE_BIN_UNLOCK (bin);
1993
1994   return;
1995
1996   /* ERRORS */
1997 no_decodebin:
1998   {
1999     /* error was posted */
2000     GST_URI_DECODE_BIN_UNLOCK (bin);
2001     return;
2002   }
2003 could_not_link:
2004   {
2005     GST_ELEMENT_ERROR (bin, CORE, NEGOTIATION,
2006         (NULL), ("Can't link source to decoder element"));
2007     GST_URI_DECODE_BIN_UNLOCK (bin);
2008     return;
2009   }
2010 }
2011
2012 /* construct and run the source and decoder elements until we found
2013  * all the streams or until a preroll queue has been filled.
2014 */
2015 static gboolean
2016 setup_source (GstURIDecodeBin * decoder)
2017 {
2018   gboolean is_raw, have_out, is_dynamic;
2019
2020   GST_DEBUG_OBJECT (decoder, "setup source");
2021
2022   /* delete old src */
2023   remove_source (decoder);
2024
2025   decoder->pending = 0;
2026
2027   /* create and configure an element that can handle the uri */
2028   if (!(decoder->source = gen_source_element (decoder)))
2029     goto no_source;
2030
2031   /* state will be merged later - if file is not found, error will be
2032    * handled by the application right after. */
2033   gst_bin_add (GST_BIN_CAST (decoder), decoder->source);
2034
2035   /* notify of the new source used */
2036   g_object_notify (G_OBJECT (decoder), "source");
2037
2038   g_signal_emit (decoder, gst_uri_decode_bin_signals[SIGNAL_SOURCE_SETUP],
2039       0, decoder->source);
2040
2041   /* remove the old decoders now, if any */
2042   remove_decoders (decoder, FALSE);
2043
2044   /* stream admin setup */
2045   decoder->streams = g_hash_table_new_full (NULL, NULL, NULL, free_stream);
2046
2047   /* see if the source element emits raw audio/video all by itself,
2048    * if so, we can create streams for the pads and be done with it.
2049    * Also check that is has source pads, if not, we assume it will
2050    * do everything itself.  */
2051   if (!analyse_source (decoder, &is_raw, &have_out, &is_dynamic,
2052           decoder->need_queue))
2053     goto invalid_source;
2054
2055   if (is_raw) {
2056     GST_DEBUG_OBJECT (decoder, "Source provides all raw data");
2057     /* source provides raw data, we added the pads and we can now signal a
2058      * no_more pads because we are done. */
2059     gst_element_no_more_pads (GST_ELEMENT_CAST (decoder));
2060     return TRUE;
2061   }
2062   if (!have_out && !is_dynamic) {
2063     GST_DEBUG_OBJECT (decoder, "Source has no output pads");
2064     /* create a stream to indicate that this uri is handled by a self
2065      * contained element. We are now done. */
2066     add_element_stream (decoder->source, decoder);
2067     return TRUE;
2068   }
2069   if (is_dynamic) {
2070     GST_DEBUG_OBJECT (decoder, "Source has dynamic output pads");
2071     /* connect a handler for the new-pad signal */
2072     decoder->src_np_sig_id =
2073         g_signal_connect (decoder->source, "pad-added",
2074         G_CALLBACK (source_new_pad), decoder);
2075     decoder->src_nmp_sig_id =
2076         g_signal_connect (decoder->source, "no-more-pads",
2077         G_CALLBACK (source_no_more_pads), decoder);
2078     g_object_set_data (G_OBJECT (decoder->source), "pending",
2079         GINT_TO_POINTER (1));
2080     decoder->pending++;
2081   } else {
2082     if (decoder->is_stream) {
2083       GST_DEBUG_OBJECT (decoder, "Setting up streaming");
2084       /* do the stream things here */
2085       if (!setup_streaming (decoder))
2086         goto streaming_failed;
2087     } else {
2088       GstElement *dec_elem;
2089
2090       /* no streaming source, we can link now */
2091       GST_DEBUG_OBJECT (decoder, "Plugging decodebin to source");
2092
2093       dec_elem = make_decoder (decoder);
2094       if (!dec_elem)
2095         goto no_decoder;
2096
2097       if (!gst_element_link_pads (decoder->source, NULL, dec_elem, "sink"))
2098         goto could_not_link;
2099     }
2100   }
2101   return TRUE;
2102
2103   /* ERRORS */
2104 no_source:
2105   {
2106     /* error message was already posted */
2107     return FALSE;
2108   }
2109 invalid_source:
2110   {
2111     GST_ELEMENT_ERROR (decoder, CORE, FAILED,
2112         (_("Source element is invalid.")), (NULL));
2113     return FALSE;
2114   }
2115 no_decoder:
2116   {
2117     /* message was posted */
2118     return FALSE;
2119   }
2120 streaming_failed:
2121   {
2122     /* message was posted */
2123     return FALSE;
2124   }
2125 could_not_link:
2126   {
2127     GST_ELEMENT_ERROR (decoder, CORE, NEGOTIATION,
2128         (NULL), ("Can't link source to decoder element"));
2129     return FALSE;
2130   }
2131 }
2132
2133 static void
2134 value_list_append_structure_list (GValue * list_val, GstStructure ** first,
2135     GList * structure_list)
2136 {
2137   GList *l;
2138
2139   for (l = structure_list; l != NULL; l = l->next) {
2140     GValue val = { 0, };
2141
2142     if (*first == NULL)
2143       *first = gst_structure_copy ((GstStructure *) l->data);
2144
2145     g_value_init (&val, GST_TYPE_STRUCTURE);
2146     g_value_take_boxed (&val, gst_structure_copy ((GstStructure *) l->data));
2147     gst_value_list_append_value (list_val, &val);
2148     g_value_unset (&val);
2149   }
2150 }
2151
2152 /* if it's a redirect message with multiple redirect locations we might
2153  * want to pick a different 'best' location depending on the required
2154  * bitrates and the connection speed */
2155 static GstMessage *
2156 handle_redirect_message (GstURIDecodeBin * dec, GstMessage * msg)
2157 {
2158   const GValue *locations_list, *location_val;
2159   GstMessage *new_msg;
2160   GstStructure *new_structure = NULL;
2161   GList *l_good = NULL, *l_neutral = NULL, *l_bad = NULL;
2162   GValue new_list = { 0, };
2163   guint size, i;
2164   const GstStructure *structure;
2165
2166   GST_DEBUG_OBJECT (dec, "redirect message: %" GST_PTR_FORMAT, msg);
2167   GST_DEBUG_OBJECT (dec, "connection speed: %" G_GUINT64_FORMAT,
2168       dec->connection_speed);
2169
2170   structure = gst_message_get_structure (msg);
2171   if (dec->connection_speed == 0 || structure == NULL)
2172     return msg;
2173
2174   locations_list = gst_structure_get_value (structure, "locations");
2175   if (locations_list == NULL)
2176     return msg;
2177
2178   size = gst_value_list_get_size (locations_list);
2179   if (size < 2)
2180     return msg;
2181
2182   /* maintain existing order as much as possible, just sort references
2183    * with too high a bitrate to the end (the assumption being that if
2184    * bitrates are given they are given for all interesting streams and
2185    * that the you-need-at-least-version-xyz redirect has the same bitrate
2186    * as the lowest referenced redirect alternative) */
2187   for (i = 0; i < size; ++i) {
2188     const GstStructure *s;
2189     gint bitrate = 0;
2190
2191     location_val = gst_value_list_get_value (locations_list, i);
2192     s = (const GstStructure *) g_value_get_boxed (location_val);
2193     if (!gst_structure_get_int (s, "minimum-bitrate", &bitrate) || bitrate <= 0) {
2194       GST_DEBUG_OBJECT (dec, "no bitrate: %" GST_PTR_FORMAT, s);
2195       l_neutral = g_list_append (l_neutral, (gpointer) s);
2196     } else if (bitrate > dec->connection_speed) {
2197       GST_DEBUG_OBJECT (dec, "bitrate too high: %" GST_PTR_FORMAT, s);
2198       l_bad = g_list_append (l_bad, (gpointer) s);
2199     } else if (bitrate <= dec->connection_speed) {
2200       GST_DEBUG_OBJECT (dec, "bitrate OK: %" GST_PTR_FORMAT, s);
2201       l_good = g_list_append (l_good, (gpointer) s);
2202     }
2203   }
2204
2205   g_value_init (&new_list, GST_TYPE_LIST);
2206   value_list_append_structure_list (&new_list, &new_structure, l_good);
2207   value_list_append_structure_list (&new_list, &new_structure, l_neutral);
2208   value_list_append_structure_list (&new_list, &new_structure, l_bad);
2209   gst_structure_set_value (new_structure, "locations", &new_list);
2210   g_value_unset (&new_list);
2211
2212   g_list_free (l_good);
2213   g_list_free (l_neutral);
2214   g_list_free (l_bad);
2215
2216   new_msg = gst_message_new_element (msg->src, new_structure);
2217   gst_message_unref (msg);
2218
2219   GST_DEBUG_OBJECT (dec, "new redirect message: %" GST_PTR_FORMAT, new_msg);
2220   return new_msg;
2221 }
2222
2223 static void
2224 handle_message (GstBin * bin, GstMessage * msg)
2225 {
2226   if (GST_MESSAGE_TYPE (msg) == GST_MESSAGE_ELEMENT
2227       && gst_message_has_name (msg, "redirect")) {
2228     /* sort redirect messages based on the connection speed. This simplifies
2229      * the user of this element as it can in most cases just pick the first item
2230      * of the sorted list as a good redirection candidate. It can of course
2231      * choose something else from the list if it has a better way. */
2232     msg = handle_redirect_message (GST_URI_DECODE_BIN (bin), msg);
2233   }
2234   GST_BIN_CLASS (parent_class)->handle_message (bin, msg);
2235 }
2236
2237 /* generic struct passed to all query fold methods
2238  * FIXME, move to core.
2239  */
2240 typedef struct
2241 {
2242   GstQuery *query;
2243   gint64 min;
2244   gint64 max;
2245   gboolean seekable;
2246   gboolean live;
2247 } QueryFold;
2248
2249 typedef void (*QueryInitFunction) (GstURIDecodeBin * dec, QueryFold * fold);
2250 typedef void (*QueryDoneFunction) (GstURIDecodeBin * dec, QueryFold * fold);
2251
2252 /* for duration/position we collect all durations/positions and take
2253  * the MAX of all valid results */
2254 static void
2255 decoder_query_init (GstURIDecodeBin * dec, QueryFold * fold)
2256 {
2257   fold->min = 0;
2258   fold->max = -1;
2259   fold->seekable = TRUE;
2260   fold->live = 0;
2261 }
2262
2263 static gboolean
2264 decoder_query_duration_fold (const GValue * item, GValue * ret,
2265     QueryFold * fold)
2266 {
2267   GstPad *pad = g_value_get_object (item);
2268
2269   if (gst_pad_query (pad, fold->query)) {
2270     gint64 duration;
2271
2272     g_value_set_boolean (ret, TRUE);
2273
2274     gst_query_parse_duration (fold->query, NULL, &duration);
2275
2276     GST_DEBUG_OBJECT (item, "got duration %" G_GINT64_FORMAT, duration);
2277
2278     if (duration > fold->max)
2279       fold->max = duration;
2280   }
2281   return TRUE;
2282 }
2283
2284 static void
2285 decoder_query_duration_done (GstURIDecodeBin * dec, QueryFold * fold)
2286 {
2287   GstFormat format;
2288
2289   gst_query_parse_duration (fold->query, &format, NULL);
2290   /* store max in query result */
2291   gst_query_set_duration (fold->query, format, fold->max);
2292
2293   GST_DEBUG ("max duration %" G_GINT64_FORMAT, fold->max);
2294 }
2295
2296 static gboolean
2297 decoder_query_position_fold (const GValue * item, GValue * ret,
2298     QueryFold * fold)
2299 {
2300   GstPad *pad = g_value_get_object (item);
2301
2302   if (gst_pad_query (pad, fold->query)) {
2303     gint64 position;
2304
2305     g_value_set_boolean (ret, TRUE);
2306
2307     gst_query_parse_position (fold->query, NULL, &position);
2308
2309     GST_DEBUG_OBJECT (item, "got position %" G_GINT64_FORMAT, position);
2310
2311     if (position > fold->max)
2312       fold->max = position;
2313   }
2314
2315   return TRUE;
2316 }
2317
2318 static void
2319 decoder_query_position_done (GstURIDecodeBin * dec, QueryFold * fold)
2320 {
2321   GstFormat format;
2322
2323   gst_query_parse_position (fold->query, &format, NULL);
2324   /* store max in query result */
2325   gst_query_set_position (fold->query, format, fold->max);
2326
2327   GST_DEBUG_OBJECT (dec, "max position %" G_GINT64_FORMAT, fold->max);
2328 }
2329
2330 static gboolean
2331 decoder_query_latency_fold (const GValue * item, GValue * ret, QueryFold * fold)
2332 {
2333   GstPad *pad = g_value_get_object (item);
2334
2335   if (gst_pad_query (pad, fold->query)) {
2336     GstClockTime min, max;
2337     gboolean live;
2338
2339     g_value_set_boolean (ret, TRUE);
2340
2341     gst_query_parse_latency (fold->query, &live, &min, &max);
2342
2343     GST_DEBUG_OBJECT (item,
2344         "got latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
2345         ", live %d", GST_TIME_ARGS (min), GST_TIME_ARGS (max), live);
2346
2347     /* for the combined latency we collect the MAX of all min latencies and
2348      * the MIN of all max latencies */
2349     if (min > fold->min)
2350       fold->min = min;
2351     if (fold->max == -1)
2352       fold->max = max;
2353     else if (max < fold->max)
2354       fold->max = max;
2355     if (fold->live == FALSE)
2356       fold->live = live;
2357   }
2358
2359   return TRUE;
2360 }
2361
2362 static void
2363 decoder_query_latency_done (GstURIDecodeBin * dec, QueryFold * fold)
2364 {
2365   /* store max in query result */
2366   gst_query_set_latency (fold->query, fold->live, fold->min, fold->max);
2367
2368   GST_DEBUG_OBJECT (dec,
2369       "latency min %" GST_TIME_FORMAT ", max %" GST_TIME_FORMAT
2370       ", live %d", GST_TIME_ARGS (fold->min), GST_TIME_ARGS (fold->max),
2371       fold->live);
2372 }
2373
2374 /* we are seekable if all srcpads are seekable */
2375 static gboolean
2376 decoder_query_seeking_fold (const GValue * item, GValue * ret, QueryFold * fold)
2377 {
2378   GstPad *pad = g_value_get_object (item);
2379
2380   if (gst_pad_query (pad, fold->query)) {
2381     gboolean seekable;
2382
2383     g_value_set_boolean (ret, TRUE);
2384     gst_query_parse_seeking (fold->query, NULL, &seekable, NULL, NULL);
2385
2386     GST_DEBUG_OBJECT (item, "got seekable %d", seekable);
2387
2388     if (fold->seekable == TRUE)
2389       fold->seekable = seekable;
2390   }
2391
2392   return TRUE;
2393 }
2394
2395 static void
2396 decoder_query_seeking_done (GstURIDecodeBin * dec, QueryFold * fold)
2397 {
2398   GstFormat format;
2399
2400   gst_query_parse_seeking (fold->query, &format, NULL, NULL, NULL);
2401   gst_query_set_seeking (fold->query, format, fold->seekable, 0, -1);
2402
2403   GST_DEBUG_OBJECT (dec, "seekable %d", fold->seekable);
2404 }
2405
2406 /* generic fold, return first valid result */
2407 static gboolean
2408 decoder_query_generic_fold (const GValue * item, GValue * ret, QueryFold * fold)
2409 {
2410   GstPad *pad = g_value_get_object (item);
2411   gboolean res;
2412
2413   if ((res = gst_pad_query (pad, fold->query))) {
2414     g_value_set_boolean (ret, TRUE);
2415     GST_DEBUG_OBJECT (item, "answered query %p", fold->query);
2416   }
2417
2418   /* and stop as soon as we have a valid result */
2419   return !res;
2420 }
2421
2422
2423 /* we're a bin, the default query handler iterates sink elements, which we don't
2424  * have normally. We should just query all source pads.
2425  */
2426 static gboolean
2427 gst_uri_decode_bin_query (GstElement * element, GstQuery * query)
2428 {
2429   GstURIDecodeBin *decoder;
2430   gboolean res = FALSE;
2431   GstIterator *iter;
2432   GstIteratorFoldFunction fold_func;
2433   QueryInitFunction fold_init = NULL;
2434   QueryDoneFunction fold_done = NULL;
2435   QueryFold fold_data;
2436   GValue ret = { 0 };
2437
2438   decoder = GST_URI_DECODE_BIN (element);
2439
2440   switch (GST_QUERY_TYPE (query)) {
2441     case GST_QUERY_DURATION:
2442       /* iterate and collect durations */
2443       fold_func = (GstIteratorFoldFunction) decoder_query_duration_fold;
2444       fold_init = decoder_query_init;
2445       fold_done = decoder_query_duration_done;
2446       break;
2447     case GST_QUERY_POSITION:
2448       /* iterate and collect durations */
2449       fold_func = (GstIteratorFoldFunction) decoder_query_position_fold;
2450       fold_init = decoder_query_init;
2451       fold_done = decoder_query_position_done;
2452       break;
2453     case GST_QUERY_LATENCY:
2454       /* iterate and collect durations */
2455       fold_func = (GstIteratorFoldFunction) decoder_query_latency_fold;
2456       fold_init = decoder_query_init;
2457       fold_done = decoder_query_latency_done;
2458       break;
2459     case GST_QUERY_SEEKING:
2460       /* iterate and collect durations */
2461       fold_func = (GstIteratorFoldFunction) decoder_query_seeking_fold;
2462       fold_init = decoder_query_init;
2463       fold_done = decoder_query_seeking_done;
2464       break;
2465     default:
2466       fold_func = (GstIteratorFoldFunction) decoder_query_generic_fold;
2467       break;
2468   }
2469
2470   fold_data.query = query;
2471
2472   g_value_init (&ret, G_TYPE_BOOLEAN);
2473   g_value_set_boolean (&ret, FALSE);
2474
2475   iter = gst_element_iterate_src_pads (element);
2476   GST_DEBUG_OBJECT (element, "Sending query %p (type %d) to src pads",
2477       query, GST_QUERY_TYPE (query));
2478
2479   if (fold_init)
2480     fold_init (decoder, &fold_data);
2481
2482   while (TRUE) {
2483     GstIteratorResult ires;
2484
2485     ires = gst_iterator_fold (iter, fold_func, &ret, &fold_data);
2486
2487     switch (ires) {
2488       case GST_ITERATOR_RESYNC:
2489         gst_iterator_resync (iter);
2490         if (fold_init)
2491           fold_init (decoder, &fold_data);
2492         g_value_set_boolean (&ret, FALSE);
2493         break;
2494       case GST_ITERATOR_OK:
2495       case GST_ITERATOR_DONE:
2496         res = g_value_get_boolean (&ret);
2497         if (fold_done != NULL && res)
2498           fold_done (decoder, &fold_data);
2499         goto done;
2500       default:
2501         res = FALSE;
2502         goto done;
2503     }
2504   }
2505 done:
2506   gst_iterator_free (iter);
2507
2508   return res;
2509 }
2510
2511 static GstStateChangeReturn
2512 gst_uri_decode_bin_change_state (GstElement * element,
2513     GstStateChange transition)
2514 {
2515   GstStateChangeReturn ret;
2516   GstURIDecodeBin *decoder;
2517
2518   decoder = GST_URI_DECODE_BIN (element);
2519
2520   switch (transition) {
2521     case GST_STATE_CHANGE_READY_TO_PAUSED:
2522       if (!setup_source (decoder))
2523         goto source_failed;
2524       break;
2525     default:
2526       break;
2527   }
2528
2529   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2530
2531   switch (transition) {
2532     case GST_STATE_CHANGE_READY_TO_PAUSED:
2533       GST_DEBUG ("ready to paused");
2534       if (ret == GST_STATE_CHANGE_FAILURE)
2535         goto setup_failed;
2536       break;
2537     case GST_STATE_CHANGE_PAUSED_TO_READY:
2538       GST_DEBUG ("paused to ready");
2539       remove_decoders (decoder, FALSE);
2540       remove_source (decoder);
2541       do_async_done (decoder);
2542       break;
2543     case GST_STATE_CHANGE_READY_TO_NULL:
2544       GST_DEBUG ("ready to null");
2545       remove_decoders (decoder, TRUE);
2546       remove_source (decoder);
2547       break;
2548     default:
2549       break;
2550   }
2551   return ret;
2552
2553   /* ERRORS */
2554 source_failed:
2555   {
2556     return GST_STATE_CHANGE_FAILURE;
2557   }
2558 setup_failed:
2559   {
2560     /* clean up leftover groups */
2561     return GST_STATE_CHANGE_FAILURE;
2562   }
2563 }
2564
2565 gboolean
2566 gst_uri_decode_bin_plugin_init (GstPlugin * plugin)
2567 {
2568   GST_DEBUG_CATEGORY_INIT (gst_uri_decode_bin_debug, "uridecodebin", 0,
2569       "URI decoder element");
2570
2571   return gst_element_register (plugin, "uridecodebin", GST_RANK_NONE,
2572       GST_TYPE_URI_DECODE_BIN);
2573 }