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