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