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