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