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