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