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