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