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