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