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