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