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