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