souphttpsrc: Also retry on unexpected network failures
[platform/upstream/gst-plugins-good.git] / ext / soup / gstsouphttpsrc.c
1 /* GStreamer
2  * Copyright (C) 2007-2008 Wouter Cloetens <wouter@mind.be>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more
13  */
14
15 /**
16  * SECTION:element-souphttpsrc
17  *
18  * This plugin reads data from a remote location specified by a URI.
19  * Supported protocols are 'http', 'https'.
20  *
21  * An HTTP proxy must be specified by its URL.
22  * If the "http_proxy" environment variable is set, its value is used.
23  * If built with libsoup's GNOME integration features, the GNOME proxy
24  * configuration will be used, or failing that, proxy autodetection.
25  * The #GstSoupHTTPSrc:proxy property can be used to override the default.
26  *
27  * In case the #GstSoupHTTPSrc:iradio-mode property is set and the location is
28  * an HTTP resource, souphttpsrc will send special Icecast HTTP headers to the
29  * server to request additional Icecast meta-information.
30  * If the server is not an Icecast server, it will behave as if the
31  * #GstSoupHTTPSrc:iradio-mode property were not set. If it is, souphttpsrc will
32  * output data with a media type of application/x-icy, in which case you will
33  * need to use the #ICYDemux element as follow-up element to extract the Icecast
34  * metadata and to determine the underlying media type.
35  *
36  * <refsect2>
37  * <title>Example launch line</title>
38  * |[
39  * gst-launch-1.0 -v souphttpsrc location=https://some.server.org/index.html
40  *     ! filesink location=/home/joe/server.html
41  * ]| The above pipeline reads a web page from a server using the HTTPS protocol
42  * and writes it to a local file.
43  * |[
44  * gst-launch-1.0 -v souphttpsrc user-agent="FooPlayer 0.99 beta"
45  *     automatic-redirect=false proxy=http://proxy.intranet.local:8080
46  *     location=http://music.foobar.com/demo.mp3 ! mad ! audioconvert
47  *     ! audioresample ! alsasink
48  * ]| The above pipeline will read and decode and play an mp3 file from a
49  * web server using the HTTP protocol. If the server sends redirects,
50  * the request fails instead of following the redirect. The specified
51  * HTTP proxy server is used. The User-Agent HTTP request header
52  * is set to a custom string instead of "GStreamer souphttpsrc."
53  * |[
54  * gst-launch-1.0 -v souphttpsrc location=http://10.11.12.13/mjpeg
55  *     do-timestamp=true ! multipartdemux
56  *     ! image/jpeg,width=640,height=480 ! matroskamux
57  *     ! filesink location=mjpeg.mkv
58  * ]| The above pipeline reads a motion JPEG stream from an IP camera
59  * using the HTTP protocol, encoded as mime/multipart image/jpeg
60  * parts, and writes a Matroska motion JPEG file. The width and
61  * height properties are set in the caps to provide the Matroska
62  * multiplexer with the information to set this in the header.
63  * Timestamps are set on the buffers as they arrive from the camera.
64  * These are used by the mime/multipart demultiplexer to emit timestamps
65  * on the JPEG-encoded video frame buffers. This allows the Matroska
66  * multiplexer to timestamp the frames in the resulting file.
67  * </refsect2>
68  */
69
70 #ifdef HAVE_CONFIG_H
71 #include "config.h"
72 #endif
73
74 #include <string.h>
75 #ifdef HAVE_STDLIB_H
76 #include <stdlib.h>             /* atoi() */
77 #endif
78 #include <gst/gstelement.h>
79 #include <gst/gst-i18n-plugin.h>
80 #include <libsoup/soup.h>
81 #include "gstsouphttpsrc.h"
82 #include "gstsouputils.h"
83
84 #include <gst/tag/tag.h>
85
86 GST_DEBUG_CATEGORY_STATIC (souphttpsrc_debug);
87 #define GST_CAT_DEFAULT souphttpsrc_debug
88
89 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
90     GST_PAD_SRC,
91     GST_PAD_ALWAYS,
92     GST_STATIC_CAPS_ANY);
93
94 enum
95 {
96   PROP_0,
97   PROP_LOCATION,
98   PROP_IS_LIVE,
99   PROP_USER_AGENT,
100   PROP_AUTOMATIC_REDIRECT,
101   PROP_PROXY,
102   PROP_USER_ID,
103   PROP_USER_PW,
104   PROP_PROXY_ID,
105   PROP_PROXY_PW,
106   PROP_COOKIES,
107   PROP_IRADIO_MODE,
108   PROP_TIMEOUT,
109   PROP_EXTRA_HEADERS,
110   PROP_SOUP_LOG_LEVEL,
111   PROP_COMPRESS,
112   PROP_KEEP_ALIVE,
113   PROP_SSL_STRICT,
114   PROP_SSL_CA_FILE,
115   PROP_SSL_USE_SYSTEM_CA_FILE,
116   PROP_RETRIES
117 };
118
119 #define DEFAULT_USER_AGENT           "GStreamer souphttpsrc "
120 #define DEFAULT_IRADIO_MODE          TRUE
121 #define DEFAULT_SOUP_LOG_LEVEL       SOUP_LOGGER_LOG_HEADERS
122 #define DEFAULT_COMPRESS             FALSE
123 #define DEFAULT_KEEP_ALIVE           FALSE
124 #define DEFAULT_SSL_STRICT           TRUE
125 #define DEFAULT_SSL_CA_FILE          NULL
126 #define DEFAULT_SSL_USE_SYSTEM_CA_FILE TRUE
127 #define DEFAULT_TIMEOUT              15
128 #define DEFAULT_RETRIES              3
129
130 static void gst_soup_http_src_uri_handler_init (gpointer g_iface,
131     gpointer iface_data);
132 static void gst_soup_http_src_finalize (GObject * gobject);
133 static void gst_soup_http_src_dispose (GObject * gobject);
134
135 static void gst_soup_http_src_set_property (GObject * object, guint prop_id,
136     const GValue * value, GParamSpec * pspec);
137 static void gst_soup_http_src_get_property (GObject * object, guint prop_id,
138     GValue * value, GParamSpec * pspec);
139
140 static GstStateChangeReturn gst_soup_http_src_change_state (GstElement *
141     element, GstStateChange transition);
142 static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc,
143     GstBuffer ** outbuf);
144 static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc);
145 static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc);
146 static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size);
147 static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc);
148 static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc,
149     GstSegment * segment);
150 static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query);
151 static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc);
152 static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc);
153 static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src,
154     const gchar * uri, GError ** error);
155 static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src,
156     const gchar * uri);
157 static char *gst_soup_http_src_unicodify (const char *str);
158 static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src,
159     const gchar * method);
160 static void gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src);
161 static void gst_soup_http_src_queue_message (GstSoupHTTPSrc * src);
162 static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src,
163     guint64 offset, guint64 stop_offset);
164 static void gst_soup_http_src_session_unpause_message (GstSoupHTTPSrc * src);
165 static void gst_soup_http_src_session_pause_message (GstSoupHTTPSrc * src);
166 static gboolean gst_soup_http_src_session_open (GstSoupHTTPSrc * src);
167 static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src);
168 static void gst_soup_http_src_parse_status (SoupMessage * msg,
169     GstSoupHTTPSrc * src);
170 static void gst_soup_http_src_chunk_free (gpointer gstbuf);
171 static SoupBuffer *gst_soup_http_src_chunk_allocator (SoupMessage * msg,
172     gsize max_len, gpointer user_data);
173 static void gst_soup_http_src_got_chunk_cb (SoupMessage * msg,
174     SoupBuffer * chunk, GstSoupHTTPSrc * src);
175 static void gst_soup_http_src_response_cb (SoupSession * session,
176     SoupMessage * msg, GstSoupHTTPSrc * src);
177 static void gst_soup_http_src_got_headers_cb (SoupMessage * msg,
178     GstSoupHTTPSrc * src);
179 static void gst_soup_http_src_got_body_cb (SoupMessage * msg,
180     GstSoupHTTPSrc * src);
181 static void gst_soup_http_src_finished_cb (SoupMessage * msg,
182     GstSoupHTTPSrc * src);
183 static void gst_soup_http_src_authenticate_cb (SoupSession * session,
184     SoupMessage * msg, SoupAuth * auth, gboolean retrying,
185     GstSoupHTTPSrc * src);
186
187 #define gst_soup_http_src_parent_class parent_class
188 G_DEFINE_TYPE_WITH_CODE (GstSoupHTTPSrc, gst_soup_http_src, GST_TYPE_PUSH_SRC,
189     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
190         gst_soup_http_src_uri_handler_init));
191
192 static void
193 gst_soup_http_src_class_init (GstSoupHTTPSrcClass * klass)
194 {
195   GObjectClass *gobject_class;
196   GstElementClass *gstelement_class;
197   GstBaseSrcClass *gstbasesrc_class;
198   GstPushSrcClass *gstpushsrc_class;
199
200   gobject_class = (GObjectClass *) klass;
201   gstelement_class = (GstElementClass *) klass;
202   gstbasesrc_class = (GstBaseSrcClass *) klass;
203   gstpushsrc_class = (GstPushSrcClass *) klass;
204
205   gobject_class->set_property = gst_soup_http_src_set_property;
206   gobject_class->get_property = gst_soup_http_src_get_property;
207   gobject_class->finalize = gst_soup_http_src_finalize;
208   gobject_class->dispose = gst_soup_http_src_dispose;
209
210   g_object_class_install_property (gobject_class,
211       PROP_LOCATION,
212       g_param_spec_string ("location", "Location",
213           "Location to read from", "",
214           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
215   g_object_class_install_property (gobject_class,
216       PROP_USER_AGENT,
217       g_param_spec_string ("user-agent", "User-Agent",
218           "Value of the User-Agent HTTP request header field",
219           DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
220   g_object_class_install_property (gobject_class,
221       PROP_AUTOMATIC_REDIRECT,
222       g_param_spec_boolean ("automatic-redirect", "automatic-redirect",
223           "Automatically follow HTTP redirects (HTTP Status Code 3xx)",
224           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
225   g_object_class_install_property (gobject_class,
226       PROP_PROXY,
227       g_param_spec_string ("proxy", "Proxy",
228           "HTTP proxy server URI", "",
229           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
230   g_object_class_install_property (gobject_class,
231       PROP_USER_ID,
232       g_param_spec_string ("user-id", "user-id",
233           "HTTP location URI user id for authentication", "",
234           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
235   g_object_class_install_property (gobject_class, PROP_USER_PW,
236       g_param_spec_string ("user-pw", "user-pw",
237           "HTTP location URI user password for authentication", "",
238           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
239   g_object_class_install_property (gobject_class, PROP_PROXY_ID,
240       g_param_spec_string ("proxy-id", "proxy-id",
241           "HTTP proxy URI user id for authentication", "",
242           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
243   g_object_class_install_property (gobject_class, PROP_PROXY_PW,
244       g_param_spec_string ("proxy-pw", "proxy-pw",
245           "HTTP proxy URI user password for authentication", "",
246           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
247   g_object_class_install_property (gobject_class, PROP_COOKIES,
248       g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies",
249           G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
250   g_object_class_install_property (gobject_class, PROP_IS_LIVE,
251       g_param_spec_boolean ("is-live", "is-live", "Act like a live source",
252           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
253   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
254       g_param_spec_uint ("timeout", "timeout",
255           "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0,
256           3600, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
257   g_object_class_install_property (gobject_class, PROP_EXTRA_HEADERS,
258       g_param_spec_boxed ("extra-headers", "Extra Headers",
259           "Extra headers to append to the HTTP request",
260           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
261   g_object_class_install_property (gobject_class, PROP_IRADIO_MODE,
262       g_param_spec_boolean ("iradio-mode", "iradio-mode",
263           "Enable internet radio mode (ask server to send shoutcast/icecast "
264           "metadata interleaved with the actual stream data)",
265           DEFAULT_IRADIO_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
266
267  /**
268    * GstSoupHTTPSrc::http-log-level:
269    *
270    * If set and > 0, captures and dumps HTTP session data as
271    * log messages if log level >= GST_LEVEL_TRACE
272    *
273    * Since: 1.4
274    */
275   g_object_class_install_property (gobject_class, PROP_SOUP_LOG_LEVEL,
276       g_param_spec_enum ("http-log-level", "HTTP log level",
277           "Set log level for soup's HTTP session log",
278           SOUP_TYPE_LOGGER_LOG_LEVEL, DEFAULT_SOUP_LOG_LEVEL,
279           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
280
281  /**
282    * GstSoupHTTPSrc::compress:
283    *
284    * If set to %TRUE, souphttpsrc will automatically handle gzip
285    * and deflate Content-Encodings. This does not make much difference
286    * and causes more load for normal media files, but makes a real
287    * difference in size for plaintext files.
288    *
289    * Since: 1.4
290    */
291   g_object_class_install_property (gobject_class, PROP_COMPRESS,
292       g_param_spec_boolean ("compress", "Compress",
293           "Allow compressed content encodings",
294           DEFAULT_COMPRESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
295
296  /**
297    * GstSoupHTTPSrc::keep-alive:
298    *
299    * If set to %TRUE, souphttpsrc will keep alive connections when being
300    * set to READY state and only will close connections when connecting
301    * to a different server or when going to NULL state..
302    *
303    * Since: 1.4
304    */
305   g_object_class_install_property (gobject_class, PROP_KEEP_ALIVE,
306       g_param_spec_boolean ("keep-alive", "keep-alive",
307           "Use HTTP persistent connections", DEFAULT_KEEP_ALIVE,
308           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
309
310  /**
311    * GstSoupHTTPSrc::ssl-strict:
312    *
313    * If set to %TRUE, souphttpsrc will reject all SSL certificates that
314    * are considered invalid.
315    *
316    * Since: 1.4
317    */
318   g_object_class_install_property (gobject_class, PROP_SSL_STRICT,
319       g_param_spec_boolean ("ssl-strict", "SSL Strict",
320           "Strict SSL certificate checking", DEFAULT_SSL_STRICT,
321           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
322
323  /**
324    * GstSoupHTTPSrc::ssl-ca-file:
325    *
326    * A SSL anchor CA file that should be used for checking certificates
327    * instead of the system CA file.
328    *
329    * Since: 1.4
330    */
331   g_object_class_install_property (gobject_class, PROP_SSL_CA_FILE,
332       g_param_spec_string ("ssl-ca-file", "SSL CA File",
333           "Location of a SSL anchor CA file to use", DEFAULT_SSL_CA_FILE,
334           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
335
336  /**
337    * GstSoupHTTPSrc::ssl-use-system-ca-file:
338    *
339    * If set to %TRUE, souphttpsrc will use the system's CA file for
340    * checking certificates.
341    *
342    * Since: 1.4
343    */
344   g_object_class_install_property (gobject_class, PROP_SSL_USE_SYSTEM_CA_FILE,
345       g_param_spec_boolean ("ssl-use-system-ca-file", "Use System CA File",
346           "Use system CA file", DEFAULT_SSL_USE_SYSTEM_CA_FILE,
347           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348
349  /**
350    * GstSoupHTTPSrc::retries:
351    *
352    * Maximum number of retries until giving up.
353    *
354    * Since: 1.4
355    */
356   g_object_class_install_property (gobject_class, PROP_RETRIES,
357       g_param_spec_int ("retries", "Retries",
358           "Maximum number of retries until giving up (-1=infinite)", -1,
359           G_MAXINT, DEFAULT_RETRIES,
360           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
361
362   gst_element_class_add_pad_template (gstelement_class,
363       gst_static_pad_template_get (&srctemplate));
364
365   gst_element_class_set_static_metadata (gstelement_class, "HTTP client source",
366       "Source/Network",
367       "Receive data as a client over the network via HTTP using SOUP",
368       "Wouter Cloetens <wouter@mind.be>");
369   gstelement_class->change_state =
370       GST_DEBUG_FUNCPTR (gst_soup_http_src_change_state);
371
372   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start);
373   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop);
374   gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock);
375   gstbasesrc_class->unlock_stop =
376       GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop);
377   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size);
378   gstbasesrc_class->is_seekable =
379       GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable);
380   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek);
381   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query);
382
383   gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create);
384
385   GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0,
386       "SOUP HTTP src");
387 }
388
389 static void
390 gst_soup_http_src_reset (GstSoupHTTPSrc * src)
391 {
392   src->interrupted = FALSE;
393   src->retry = FALSE;
394   src->retry_count = 0;
395   src->have_size = FALSE;
396   src->got_headers = FALSE;
397   src->seekable = FALSE;
398   src->read_position = 0;
399   src->request_position = 0;
400   src->stop_position = -1;
401   src->content_size = 0;
402   src->have_body = FALSE;
403
404   src->ret = GST_FLOW_OK;
405
406   gst_caps_replace (&src->src_caps, NULL);
407   g_free (src->iradio_name);
408   src->iradio_name = NULL;
409   g_free (src->iradio_genre);
410   src->iradio_genre = NULL;
411   g_free (src->iradio_url);
412   src->iradio_url = NULL;
413 }
414
415 static void
416 gst_soup_http_src_init (GstSoupHTTPSrc * src)
417 {
418   const gchar *proxy;
419
420   g_mutex_init (&src->mutex);
421   g_cond_init (&src->request_finished_cond);
422   src->location = NULL;
423   src->redirection_uri = NULL;
424   src->automatic_redirect = TRUE;
425   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
426   src->user_id = NULL;
427   src->user_pw = NULL;
428   src->proxy_id = NULL;
429   src->proxy_pw = NULL;
430   src->cookies = NULL;
431   src->iradio_mode = DEFAULT_IRADIO_MODE;
432   src->loop = NULL;
433   src->context = NULL;
434   src->session = NULL;
435   src->msg = NULL;
436   src->timeout = DEFAULT_TIMEOUT;
437   src->log_level = DEFAULT_SOUP_LOG_LEVEL;
438   src->ssl_strict = DEFAULT_SSL_STRICT;
439   src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
440   src->max_retries = DEFAULT_RETRIES;
441   proxy = g_getenv ("http_proxy");
442   if (proxy && !gst_soup_http_src_set_proxy (src, proxy)) {
443     GST_WARNING_OBJECT (src,
444         "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
445         proxy);
446   }
447
448   gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
449
450   gst_soup_http_src_reset (src);
451 }
452
453 static void
454 gst_soup_http_src_dispose (GObject * gobject)
455 {
456   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
457
458   GST_DEBUG_OBJECT (src, "dispose");
459
460   gst_soup_http_src_session_close (src);
461
462   G_OBJECT_CLASS (parent_class)->dispose (gobject);
463 }
464
465 static void
466 gst_soup_http_src_finalize (GObject * gobject)
467 {
468   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
469
470   GST_DEBUG_OBJECT (src, "finalize");
471
472   g_mutex_clear (&src->mutex);
473   g_cond_clear (&src->request_finished_cond);
474   g_free (src->location);
475   if (src->redirection_uri) {
476     g_free (src->redirection_uri);
477   }
478   g_free (src->user_agent);
479   if (src->proxy != NULL) {
480     soup_uri_free (src->proxy);
481   }
482   g_free (src->user_id);
483   g_free (src->user_pw);
484   g_free (src->proxy_id);
485   g_free (src->proxy_pw);
486   g_strfreev (src->cookies);
487
488   if (src->extra_headers) {
489     gst_structure_free (src->extra_headers);
490     src->extra_headers = NULL;
491   }
492
493   g_free (src->ssl_ca_file);
494
495   G_OBJECT_CLASS (parent_class)->finalize (gobject);
496 }
497
498 static void
499 gst_soup_http_src_set_property (GObject * object, guint prop_id,
500     const GValue * value, GParamSpec * pspec)
501 {
502   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
503
504   switch (prop_id) {
505     case PROP_LOCATION:
506     {
507       const gchar *location;
508
509       location = g_value_get_string (value);
510
511       if (location == NULL) {
512         GST_WARNING ("location property cannot be NULL");
513         goto done;
514       }
515       if (!gst_soup_http_src_set_location (src, location, NULL)) {
516         GST_WARNING ("badly formatted location");
517         goto done;
518       }
519       break;
520     }
521     case PROP_USER_AGENT:
522       if (src->user_agent)
523         g_free (src->user_agent);
524       src->user_agent = g_value_dup_string (value);
525       break;
526     case PROP_IRADIO_MODE:
527       src->iradio_mode = g_value_get_boolean (value);
528       break;
529     case PROP_AUTOMATIC_REDIRECT:
530       src->automatic_redirect = g_value_get_boolean (value);
531       break;
532     case PROP_PROXY:
533     {
534       const gchar *proxy;
535
536       proxy = g_value_get_string (value);
537
538       if (proxy == NULL) {
539         GST_WARNING ("proxy property cannot be NULL");
540         goto done;
541       }
542       if (!gst_soup_http_src_set_proxy (src, proxy)) {
543         GST_WARNING ("badly formatted proxy URI");
544         goto done;
545       }
546       break;
547     }
548     case PROP_COOKIES:
549       g_strfreev (src->cookies);
550       src->cookies = g_strdupv (g_value_get_boxed (value));
551       break;
552     case PROP_IS_LIVE:
553       gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
554       break;
555     case PROP_USER_ID:
556       if (src->user_id)
557         g_free (src->user_id);
558       src->user_id = g_value_dup_string (value);
559       break;
560     case PROP_USER_PW:
561       if (src->user_pw)
562         g_free (src->user_pw);
563       src->user_pw = g_value_dup_string (value);
564       break;
565     case PROP_PROXY_ID:
566       if (src->proxy_id)
567         g_free (src->proxy_id);
568       src->proxy_id = g_value_dup_string (value);
569       break;
570     case PROP_PROXY_PW:
571       if (src->proxy_pw)
572         g_free (src->proxy_pw);
573       src->proxy_pw = g_value_dup_string (value);
574       break;
575     case PROP_TIMEOUT:
576       src->timeout = g_value_get_uint (value);
577       break;
578     case PROP_EXTRA_HEADERS:{
579       const GstStructure *s = gst_value_get_structure (value);
580
581       if (src->extra_headers)
582         gst_structure_free (src->extra_headers);
583
584       src->extra_headers = s ? gst_structure_copy (s) : NULL;
585       break;
586     }
587     case PROP_SOUP_LOG_LEVEL:
588       src->log_level = g_value_get_enum (value);
589       break;
590     case PROP_COMPRESS:
591       src->compress = g_value_get_boolean (value);
592       break;
593     case PROP_KEEP_ALIVE:
594       src->keep_alive = g_value_get_boolean (value);
595       break;
596     case PROP_SSL_STRICT:
597       src->ssl_strict = g_value_get_boolean (value);
598       break;
599     case PROP_SSL_CA_FILE:
600       if (src->ssl_ca_file)
601         g_free (src->ssl_ca_file);
602       src->ssl_ca_file = g_value_dup_string (value);
603       break;
604     case PROP_SSL_USE_SYSTEM_CA_FILE:
605       src->ssl_use_system_ca_file = g_value_get_boolean (value);
606       break;
607     case PROP_RETRIES:
608       src->max_retries = g_value_get_int (value);
609       break;
610     default:
611       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
612       break;
613   }
614 done:
615   return;
616 }
617
618 static void
619 gst_soup_http_src_get_property (GObject * object, guint prop_id,
620     GValue * value, GParamSpec * pspec)
621 {
622   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
623
624   switch (prop_id) {
625     case PROP_LOCATION:
626       g_value_set_string (value, src->location);
627       break;
628     case PROP_USER_AGENT:
629       g_value_set_string (value, src->user_agent);
630       break;
631     case PROP_AUTOMATIC_REDIRECT:
632       g_value_set_boolean (value, src->automatic_redirect);
633       break;
634     case PROP_PROXY:
635       if (src->proxy == NULL)
636         g_value_set_static_string (value, "");
637       else {
638         char *proxy = soup_uri_to_string (src->proxy, FALSE);
639
640         g_value_set_string (value, proxy);
641         g_free (proxy);
642       }
643       break;
644     case PROP_COOKIES:
645       g_value_set_boxed (value, g_strdupv (src->cookies));
646       break;
647     case PROP_IS_LIVE:
648       g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
649       break;
650     case PROP_IRADIO_MODE:
651       g_value_set_boolean (value, src->iradio_mode);
652       break;
653     case PROP_USER_ID:
654       g_value_set_string (value, src->user_id);
655       break;
656     case PROP_USER_PW:
657       g_value_set_string (value, src->user_pw);
658       break;
659     case PROP_PROXY_ID:
660       g_value_set_string (value, src->proxy_id);
661       break;
662     case PROP_PROXY_PW:
663       g_value_set_string (value, src->proxy_pw);
664       break;
665     case PROP_TIMEOUT:
666       g_value_set_uint (value, src->timeout);
667       break;
668     case PROP_EXTRA_HEADERS:
669       gst_value_set_structure (value, src->extra_headers);
670       break;
671     case PROP_SOUP_LOG_LEVEL:
672       g_value_set_enum (value, src->log_level);
673       break;
674     case PROP_COMPRESS:
675       g_value_set_boolean (value, src->compress);
676       break;
677     case PROP_KEEP_ALIVE:
678       g_value_set_boolean (value, src->keep_alive);
679       break;
680     case PROP_SSL_STRICT:
681       g_value_set_boolean (value, src->ssl_strict);
682       break;
683     case PROP_SSL_CA_FILE:
684       g_value_set_string (value, src->ssl_ca_file);
685       break;
686     case PROP_SSL_USE_SYSTEM_CA_FILE:
687       g_value_set_boolean (value, src->ssl_strict);
688       break;
689     case PROP_RETRIES:
690       g_value_set_int (value, src->max_retries);
691       break;
692     default:
693       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
694       break;
695   }
696 }
697
698 static gchar *
699 gst_soup_http_src_unicodify (const gchar * str)
700 {
701   const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
702     "GST_TAG_ENCODING", NULL
703   };
704
705   return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
706 }
707
708 static void
709 gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src)
710 {
711   if (src->msg != NULL) {
712     src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED;
713     soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_CANCELLED);
714   }
715   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE;
716   src->msg = NULL;
717 }
718
719 static void
720 gst_soup_http_src_queue_message (GstSoupHTTPSrc * src)
721 {
722   soup_session_queue_message (src->session, src->msg,
723       (SoupSessionCallback) gst_soup_http_src_response_cb, src);
724   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED;
725 }
726
727 static gboolean
728 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
729     guint64 stop_offset)
730 {
731   gchar buf[64];
732
733   gint rc;
734
735   soup_message_headers_remove (src->msg->request_headers, "Range");
736   if (offset || stop_offset != -1) {
737     if (stop_offset != -1) {
738       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
739           G_GUINT64_FORMAT, offset, stop_offset);
740     } else {
741       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
742           offset);
743     }
744     if (rc > sizeof (buf) || rc < 0)
745       return FALSE;
746     soup_message_headers_append (src->msg->request_headers, "Range", buf);
747   }
748   src->read_position = offset;
749   return TRUE;
750 }
751
752 static gboolean
753 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
754 {
755   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
756   const gchar *field_name = g_quark_to_string (field_id);
757   gchar *field_content = NULL;
758
759   if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
760     field_content = g_value_dup_string (value);
761   } else {
762     GValue dest = { 0, };
763
764     g_value_init (&dest, G_TYPE_STRING);
765     if (g_value_transform (value, &dest)) {
766       field_content = g_value_dup_string (&dest);
767     }
768   }
769
770   if (field_content == NULL) {
771     GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
772         "or can't be converted to a string", field_name);
773     return FALSE;
774   }
775
776   GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
777       field_content);
778   soup_message_headers_append (src->msg->request_headers, field_name,
779       field_content);
780
781   g_free (field_content);
782
783   return TRUE;
784 }
785
786 static gboolean
787 _append_extra_headers (GQuark field_id, const GValue * value,
788     gpointer user_data)
789 {
790   if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
791     guint n = gst_value_array_get_size (value);
792     guint i;
793
794     for (i = 0; i < n; i++) {
795       const GValue *v = gst_value_array_get_value (value, i);
796
797       if (!_append_extra_header (field_id, v, user_data))
798         return FALSE;
799     }
800   } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
801     guint n = gst_value_list_get_size (value);
802     guint i;
803
804     for (i = 0; i < n; i++) {
805       const GValue *v = gst_value_list_get_value (value, i);
806
807       if (!_append_extra_header (field_id, v, user_data))
808         return FALSE;
809     }
810   } else {
811     return _append_extra_header (field_id, value, user_data);
812   }
813
814   return TRUE;
815 }
816
817
818 static gboolean
819 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
820 {
821   if (!src->extra_headers)
822     return TRUE;
823
824   return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
825 }
826
827
828 static void
829 gst_soup_http_src_session_unpause_message (GstSoupHTTPSrc * src)
830 {
831   soup_session_unpause_message (src->session, src->msg);
832 }
833
834 static void
835 gst_soup_http_src_session_pause_message (GstSoupHTTPSrc * src)
836 {
837   soup_session_pause_message (src->session, src->msg);
838 }
839
840 static gboolean
841 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
842 {
843   if (src->session) {
844     GST_DEBUG_OBJECT (src, "Session is already open");
845     return TRUE;
846   }
847
848   if (!src->location) {
849     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
850         ("Missing location property"));
851     return FALSE;
852   }
853
854   if (!src->context)
855     src->context = g_main_context_new ();
856
857   if (!src->loop)
858     src->loop = g_main_loop_new (src->context, TRUE);
859   if (!src->loop) {
860     GST_ELEMENT_ERROR (src, LIBRARY, INIT,
861         (NULL), ("Failed to start GMainLoop"));
862     g_main_context_unref (src->context);
863     return FALSE;
864   }
865
866   if (!src->session) {
867     GST_DEBUG_OBJECT (src, "Creating session");
868     if (src->proxy == NULL) {
869       src->session =
870           soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
871           src->context, SOUP_SESSION_USER_AGENT, src->user_agent,
872           SOUP_SESSION_TIMEOUT, src->timeout,
873           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
874           SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_DEFAULT,
875           NULL);
876     } else {
877       src->session =
878           soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
879           src->context, SOUP_SESSION_PROXY_URI, src->proxy,
880           SOUP_SESSION_TIMEOUT, src->timeout,
881           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
882           SOUP_SESSION_USER_AGENT, src->user_agent, NULL);
883     }
884
885     if (!src->session) {
886       GST_ELEMENT_ERROR (src, LIBRARY, INIT,
887           (NULL), ("Failed to create async session"));
888       return FALSE;
889     }
890
891     g_signal_connect (src->session, "authenticate",
892         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
893
894     /* Set up logging */
895     gst_soup_util_log_setup (src->session, src->log_level, GST_ELEMENT (src));
896     if (src->ssl_ca_file)
897       g_object_set (src->session, "ssl-ca-file", src->ssl_ca_file, NULL);
898     else
899       g_object_set (src->session, "ssl-use-system-ca-file",
900           src->ssl_use_system_ca_file, NULL);
901   } else {
902     GST_DEBUG_OBJECT (src, "Re-using session");
903   }
904
905   if (src->compress)
906     soup_session_add_feature_by_type (src->session, SOUP_TYPE_CONTENT_DECODER);
907   else
908     soup_session_remove_feature_by_type (src->session,
909         SOUP_TYPE_CONTENT_DECODER);
910
911   return TRUE;
912 }
913
914 static void
915 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
916 {
917   if (src->session) {
918     soup_session_abort (src->session);  /* This unrefs the message. */
919     g_object_unref (src->session);
920     src->session = NULL;
921     src->msg = NULL;
922   }
923   if (src->loop) {
924     g_main_loop_unref (src->loop);
925     g_main_context_unref (src->context);
926     src->loop = NULL;
927     src->context = NULL;
928   }
929 }
930
931 static void
932 gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg,
933     SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src)
934 {
935   if (!retrying) {
936     /* First time authentication only, if we fail and are called again with retry true fall through */
937     if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
938       if (src->user_id && src->user_pw)
939         soup_auth_authenticate (auth, src->user_id, src->user_pw);
940     } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
941       if (src->proxy_id && src->proxy_pw)
942         soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
943     }
944   }
945 }
946
947 static void
948 gst_soup_http_src_got_headers_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
949 {
950   const char *value;
951   GstTagList *tag_list;
952   GstBaseSrc *basesrc;
953   guint64 newsize;
954   GHashTable *params = NULL;
955
956   GST_INFO_OBJECT (src, "got headers");
957
958   if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
959       src->proxy_id && src->proxy_pw)
960     return;
961
962   if (src->automatic_redirect && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
963     src->redirection_uri = g_strdup (soup_message_headers_get_one
964         (msg->response_headers, "Location"));
965     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\"", msg->status_code,
966         src->redirection_uri);
967     return;
968   }
969
970   if (msg->status_code == SOUP_STATUS_UNAUTHORIZED)
971     return;
972
973   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING;
974   src->got_headers = TRUE;
975
976   /* Parse Content-Length. */
977   if (soup_message_headers_get_encoding (msg->response_headers) ==
978       SOUP_ENCODING_CONTENT_LENGTH) {
979     newsize = src->request_position +
980         soup_message_headers_get_content_length (msg->response_headers);
981     if (!src->have_size || (src->content_size != newsize)) {
982       src->content_size = newsize;
983       src->have_size = TRUE;
984       src->seekable = TRUE;
985       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
986
987       basesrc = GST_BASE_SRC_CAST (src);
988       basesrc->segment.duration = src->content_size;
989       gst_element_post_message (GST_ELEMENT (src),
990           gst_message_new_duration_changed (GST_OBJECT (src)));
991     }
992   }
993
994   /* Icecast stuff */
995   tag_list = gst_tag_list_new_empty ();
996
997   if ((value =
998           soup_message_headers_get_one (msg->response_headers,
999               "icy-metaint")) != NULL) {
1000     gint icy_metaint = atoi (value);
1001
1002     GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value, icy_metaint);
1003     if (icy_metaint > 0) {
1004       if (src->src_caps)
1005         gst_caps_unref (src->src_caps);
1006
1007       src->src_caps = gst_caps_new_simple ("application/x-icy",
1008           "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1009
1010       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1011     }
1012   }
1013   if ((value =
1014           soup_message_headers_get_content_type (msg->response_headers,
1015               &params)) != NULL) {
1016     GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1017     if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1018       gint channels = 2;
1019       gint rate = 44100;
1020       char *param;
1021
1022       if (src->src_caps)
1023         gst_caps_unref (src->src_caps);
1024
1025       param = g_hash_table_lookup (params, "channels");
1026       if (param != NULL)
1027         channels = atol (param);
1028
1029       param = g_hash_table_lookup (params, "rate");
1030       if (param != NULL)
1031         rate = atol (param);
1032
1033       src->src_caps = gst_caps_new_simple ("audio/x-raw",
1034           "format", G_TYPE_STRING, "S16BE",
1035           "layout", G_TYPE_STRING, "interleaved",
1036           "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1037
1038       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1039     } else {
1040       /* Set the Content-Type field on the caps */
1041       if (src->src_caps) {
1042         src->src_caps = gst_caps_make_writable (src->src_caps);
1043         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1044             value, NULL);
1045         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1046       }
1047     }
1048   }
1049
1050   if (params != NULL)
1051     g_hash_table_destroy (params);
1052
1053   if ((value =
1054           soup_message_headers_get_one (msg->response_headers,
1055               "icy-name")) != NULL) {
1056     g_free (src->iradio_name);
1057     src->iradio_name = gst_soup_http_src_unicodify (value);
1058     if (src->iradio_name) {
1059       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1060           src->iradio_name, NULL);
1061     }
1062   }
1063   if ((value =
1064           soup_message_headers_get_one (msg->response_headers,
1065               "icy-genre")) != NULL) {
1066     g_free (src->iradio_genre);
1067     src->iradio_genre = gst_soup_http_src_unicodify (value);
1068     if (src->iradio_genre) {
1069       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1070           src->iradio_genre, NULL);
1071     }
1072   }
1073   if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url"))
1074       != NULL) {
1075     g_free (src->iradio_url);
1076     src->iradio_url = gst_soup_http_src_unicodify (value);
1077     if (src->iradio_url) {
1078       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1079           src->iradio_url, NULL);
1080     }
1081   }
1082   if (!gst_tag_list_is_empty (tag_list)) {
1083     GST_DEBUG_OBJECT (src,
1084         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1085     gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1086   } else {
1087     gst_tag_list_unref (tag_list);
1088   }
1089
1090   /* Handle HTTP errors. */
1091   gst_soup_http_src_parse_status (msg, src);
1092
1093   /* Check if Range header was respected. */
1094   if (src->ret == GST_FLOW_CUSTOM_ERROR &&
1095       src->read_position && msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) {
1096     src->seekable = FALSE;
1097     GST_ELEMENT_ERROR (src, RESOURCE, SEEK,
1098         (_("Server does not support seeking.")),
1099         ("Server does not accept Range HTTP header, URL: %s", src->location));
1100     src->ret = GST_FLOW_ERROR;
1101   }
1102
1103   /* If we are going to error out, stop all processing right here, so we
1104    * don't output any data (such as an error html page), and return
1105    * GST_FLOW_ERROR from the create function instead of having
1106    * got_chunk_cb overwrite src->ret with FLOW_OK again. */
1107   if (src->ret == GST_FLOW_ERROR || src->ret == GST_FLOW_EOS) {
1108     gst_soup_http_src_session_pause_message (src);
1109
1110     if (src->loop)
1111       g_main_loop_quit (src->loop);
1112   }
1113   g_cond_signal (&src->request_finished_cond);
1114 }
1115
1116 /* Have body. Signal EOS. */
1117 static void
1118 gst_soup_http_src_got_body_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1119 {
1120   if (G_UNLIKELY (msg != src->msg)) {
1121     GST_DEBUG_OBJECT (src, "got body, but not for current message");
1122     return;
1123   }
1124   if (G_UNLIKELY (src->session_io_status !=
1125           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1126     /* Probably a redirect. */
1127     return;
1128   }
1129   GST_DEBUG_OBJECT (src, "got body");
1130   src->ret = GST_FLOW_EOS;
1131   src->have_body = TRUE;
1132
1133   /* no need to interrupt the message here, we do it on the
1134    * finished_cb anyway if needed. And getting the body might mean
1135    * that the connection was hang up before finished. This happens when
1136    * the pipeline is stalled for too long (long pauses during playback).
1137    * Best to let it continue from here and pause because it reached the
1138    * final bytes based on content_size or received an out of range error */
1139 }
1140
1141 /* Finished. Signal EOS. */
1142 static void
1143 gst_soup_http_src_finished_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1144 {
1145   if (G_UNLIKELY (msg != src->msg)) {
1146     GST_DEBUG_OBJECT (src, "finished, but not for current message");
1147     return;
1148   }
1149   GST_DEBUG_OBJECT (src, "finished");
1150   src->ret = GST_FLOW_EOS;
1151   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED) {
1152     /* gst_soup_http_src_cancel_message() triggered this; probably a seek
1153      * that occurred in the QUEUEING state; i.e. before the connection setup
1154      * was complete. Do nothing */
1155   } else if (src->session_io_status ==
1156       GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING && src->read_position > 0 &&
1157       (src->have_size && src->read_position < src->content_size) &&
1158       (src->max_retries == -1 || src->retry_count < src->max_retries)) {
1159     /* The server disconnected while streaming. Reconnect and seeking to the
1160      * last location. */
1161     src->retry = TRUE;
1162     src->retry_count++;
1163     src->ret = GST_FLOW_CUSTOM_ERROR;
1164   } else if (G_UNLIKELY (src->session_io_status !=
1165           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1166     if (msg->method == SOUP_METHOD_HEAD) {
1167       GST_DEBUG_OBJECT (src, "Ignoring error %d:%s during HEAD request",
1168           msg->status_code, msg->reason_phrase);
1169     } else {
1170       gst_soup_http_src_parse_status (msg, src);
1171     }
1172   }
1173   if (src->loop)
1174     g_main_loop_quit (src->loop);
1175   g_cond_signal (&src->request_finished_cond);
1176 }
1177
1178 /* Buffer lifecycle management.
1179  *
1180  * gst_soup_http_src_create() runs the GMainLoop for this element, to let
1181  * Soup take control.
1182  * A GstBuffer is allocated in gst_soup_http_src_chunk_allocator() and
1183  * associated with a SoupBuffer.
1184  * Soup reads HTTP data in the GstBuffer's data buffer.
1185  * The gst_soup_http_src_got_chunk_cb() is then called with the SoupBuffer.
1186  * That sets gst_soup_http_src_create()'s return argument to the GstBuffer,
1187  * increments its refcount (to 2), pauses the flow of data from the HTTP
1188  * source to prevent gst_soup_http_src_got_chunk_cb() from being called
1189  * again and breaks out of the GMainLoop.
1190  * Because the SOUP_MESSAGE_OVERWRITE_CHUNKS flag is set, Soup frees the
1191  * SoupBuffer and calls gst_soup_http_src_chunk_free(), which decrements the
1192  * refcount (to 1).
1193  * gst_soup_http_src_create() returns the GstBuffer. It will be freed by a
1194  * downstream element.
1195  * If Soup fails to read HTTP data, it does not call
1196  * gst_soup_http_src_got_chunk_cb(), but still frees the SoupBuffer and
1197  * calls gst_soup_http_src_chunk_free(), which decrements the GstBuffer's
1198  * refcount to 0, freeing it.
1199  */
1200
1201 typedef struct
1202 {
1203   GstBuffer *buffer;
1204   GstMapInfo map;
1205 } SoupGstChunk;
1206
1207 static void
1208 gst_soup_http_src_chunk_free (gpointer user_data)
1209 {
1210   SoupGstChunk *chunk = (SoupGstChunk *) user_data;
1211
1212   gst_buffer_unmap (chunk->buffer, &chunk->map);
1213   gst_buffer_unref (chunk->buffer);
1214   g_slice_free (SoupGstChunk, chunk);
1215 }
1216
1217 static SoupBuffer *
1218 gst_soup_http_src_chunk_allocator (SoupMessage * msg, gsize max_len,
1219     gpointer user_data)
1220 {
1221   GstSoupHTTPSrc *src = (GstSoupHTTPSrc *) user_data;
1222   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1223   GstBuffer *gstbuf;
1224   SoupBuffer *soupbuf;
1225   gsize length;
1226   GstFlowReturn rc;
1227   SoupGstChunk *chunk;
1228
1229   if (max_len)
1230     length = MIN (basesrc->blocksize, max_len);
1231   else
1232     length = basesrc->blocksize;
1233   GST_DEBUG_OBJECT (src, "alloc %" G_GSIZE_FORMAT " bytes <= %" G_GSIZE_FORMAT,
1234       length, max_len);
1235
1236   rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1, length, &gstbuf);
1237   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1238     /* Failed to allocate buffer. Stall SoupSession and return error code
1239      * to create(). */
1240     src->ret = rc;
1241     g_main_loop_quit (src->loop);
1242     return NULL;
1243   }
1244
1245   chunk = g_slice_new0 (SoupGstChunk);
1246   chunk->buffer = gstbuf;
1247   gst_buffer_map (gstbuf, &chunk->map, GST_MAP_READWRITE);
1248
1249   soupbuf = soup_buffer_new_with_owner (chunk->map.data, chunk->map.size,
1250       chunk, gst_soup_http_src_chunk_free);
1251
1252   return soupbuf;
1253 }
1254
1255 static void
1256 gst_soup_http_src_got_chunk_cb (SoupMessage * msg, SoupBuffer * chunk,
1257     GstSoupHTTPSrc * src)
1258 {
1259   GstBaseSrc *basesrc;
1260   guint64 new_position;
1261   SoupGstChunk *gchunk;
1262
1263   if (G_UNLIKELY (msg != src->msg)) {
1264     GST_DEBUG_OBJECT (src, "got chunk, but not for current message");
1265     return;
1266   }
1267   if (G_UNLIKELY (!src->outbuf)) {
1268     GST_DEBUG_OBJECT (src, "got chunk but we're not expecting one");
1269     src->ret = GST_FLOW_OK;
1270     gst_soup_http_src_cancel_message (src);
1271     g_main_loop_quit (src->loop);
1272     return;
1273   }
1274
1275   /* We got data, reset the retry counter */
1276   src->retry_count = 0;
1277
1278   src->have_body = FALSE;
1279   if (G_UNLIKELY (src->session_io_status !=
1280           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1281     /* Probably a redirect. */
1282     return;
1283   }
1284   basesrc = GST_BASE_SRC_CAST (src);
1285   GST_DEBUG_OBJECT (src, "got chunk of %" G_GSIZE_FORMAT " bytes",
1286       chunk->length);
1287
1288   /* Extract the GstBuffer from the SoupBuffer and set its fields. */
1289   gchunk = (SoupGstChunk *) soup_buffer_get_owner (chunk);
1290   *src->outbuf = gchunk->buffer;
1291
1292   gst_buffer_resize (*src->outbuf, 0, chunk->length);
1293   GST_BUFFER_OFFSET (*src->outbuf) = basesrc->segment.position;
1294
1295   gst_buffer_ref (*src->outbuf);
1296
1297   new_position = src->read_position + chunk->length;
1298   if (G_LIKELY (src->request_position == src->read_position))
1299     src->request_position = new_position;
1300   src->read_position = new_position;
1301
1302   if (src->have_size) {
1303     if (new_position > src->content_size) {
1304       GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
1305           "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
1306           src->content_size);
1307       src->content_size = new_position;
1308       basesrc->segment.duration = src->content_size;
1309       gst_element_post_message (GST_ELEMENT (src),
1310           gst_message_new_duration_changed (GST_OBJECT (src)));
1311     } else if (new_position == src->content_size) {
1312       GST_DEBUG_OBJECT (src, "We're EOS now");
1313     }
1314   }
1315
1316   src->ret = GST_FLOW_OK;
1317   g_main_loop_quit (src->loop);
1318   gst_soup_http_src_session_pause_message (src);
1319 }
1320
1321 static void
1322 gst_soup_http_src_response_cb (SoupSession * session, SoupMessage * msg,
1323     GstSoupHTTPSrc * src)
1324 {
1325   if (G_UNLIKELY (msg != src->msg)) {
1326     GST_DEBUG_OBJECT (src, "got response %d: %s, but not for current message",
1327         msg->status_code, msg->reason_phrase);
1328     return;
1329   }
1330   if (G_UNLIKELY (src->session_io_status !=
1331           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)
1332       && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
1333     /* Ignore redirections. */
1334     return;
1335   }
1336   GST_DEBUG_OBJECT (src, "got response %d: %s", msg->status_code,
1337       msg->reason_phrase);
1338   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING &&
1339       src->read_position > 0 && (src->have_size
1340           && src->read_position < src->content_size) &&
1341       (src->max_retries == -1 || src->retry_count < src->max_retries)) {
1342     /* The server disconnected while streaming. Reconnect and seeking to the
1343      * last location. */
1344     src->retry = TRUE;
1345     src->retry_count++;
1346   } else {
1347     gst_soup_http_src_parse_status (msg, src);
1348   }
1349   /* The session's SoupMessage object expires after this callback returns. */
1350   src->msg = NULL;
1351   g_main_loop_quit (src->loop);
1352 }
1353
1354 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1355   GST_ELEMENT_ERROR ((src), cat, code, ("%s", error_message),        \
1356       ("%s (%d), URL: %s", (soup_msg)->reason_phrase,                \
1357           (soup_msg)->status_code, (src)->location));
1358
1359 static void
1360 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1361 {
1362   if (msg->method == SOUP_METHOD_HEAD) {
1363     if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
1364       GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1365           msg->status_code);
1366   } else if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
1367     switch (msg->status_code) {
1368       case SOUP_STATUS_CANT_RESOLVE:
1369       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1370         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1371             _("Could not resolve server name."));
1372         src->ret = GST_FLOW_ERROR;
1373         break;
1374       case SOUP_STATUS_CANT_CONNECT:
1375       case SOUP_STATUS_CANT_CONNECT_PROXY:
1376         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1377             _("Could not establish connection to server."));
1378         src->ret = GST_FLOW_ERROR;
1379         break;
1380       case SOUP_STATUS_SSL_FAILED:
1381         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1382             _("Secure connection setup failed."));
1383         src->ret = GST_FLOW_ERROR;
1384         break;
1385       case SOUP_STATUS_IO_ERROR:
1386         if (src->max_retries == -1 || src->retry_count < src->max_retries) {
1387           src->retry = TRUE;
1388           src->retry_count++;
1389           src->ret = GST_FLOW_CUSTOM_ERROR;
1390         } else {
1391           SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1392               _("A network error occured, or the server closed the connection "
1393                   "unexpectedly."));
1394           src->ret = GST_FLOW_ERROR;
1395         }
1396         break;
1397       case SOUP_STATUS_MALFORMED:
1398         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1399             _("Server sent bad data."));
1400         src->ret = GST_FLOW_ERROR;
1401         break;
1402       case SOUP_STATUS_CANCELLED:
1403         /* No error message when interrupted by program. */
1404         break;
1405     }
1406   } else if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) ||
1407       SOUP_STATUS_IS_REDIRECTION (msg->status_code) ||
1408       SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) {
1409     /* Report HTTP error. */
1410
1411     /* when content_size is unknown and we have just finished receiving
1412      * a body message, requests that go beyond the content limits will result
1413      * in an error. Here we convert those to EOS */
1414     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1415         src->have_body && !src->have_size) {
1416       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1417           "body, returning EOS");
1418       src->ret = GST_FLOW_EOS;
1419       return;
1420     }
1421
1422     /* FIXME: reason_phrase is not translated and not suitable for user
1423      * error dialog according to libsoup documentation.
1424      */
1425     if (msg->status_code == SOUP_STATUS_NOT_FOUND) {
1426       GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,
1427           ("%s", msg->reason_phrase),
1428           ("%s (%d), URL: %s", msg->reason_phrase, msg->status_code,
1429               src->location));
1430     } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED ||
1431         msg->status_code == SOUP_STATUS_PAYMENT_REQUIRED ||
1432         msg->status_code == SOUP_STATUS_FORBIDDEN ||
1433         msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1434       GST_ELEMENT_ERROR (src, RESOURCE, NOT_AUTHORIZED,
1435           ("%s", msg->reason_phrase),
1436           ("%s (%d), URL: %s", msg->reason_phrase, msg->status_code,
1437               src->location));
1438     } else {
1439       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1440           ("%s", msg->reason_phrase),
1441           ("%s (%d), URL: %s", msg->reason_phrase, msg->status_code,
1442               src->location));
1443     }
1444     src->ret = GST_FLOW_ERROR;
1445   }
1446 }
1447
1448 static gboolean
1449 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1450 {
1451   src->msg = soup_message_new (method, src->location);
1452   if (!src->msg) {
1453     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1454         ("Error parsing URL."), ("URL: %s", src->location));
1455     return FALSE;
1456   }
1457   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE;
1458   if (!src->keep_alive) {
1459     soup_message_headers_append (src->msg->request_headers, "Connection",
1460         "close");
1461   }
1462   if (src->iradio_mode) {
1463     soup_message_headers_append (src->msg->request_headers, "icy-metadata",
1464         "1");
1465   }
1466   if (src->cookies) {
1467     gchar **cookie;
1468
1469     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1470       soup_message_headers_append (src->msg->request_headers, "Cookie",
1471           *cookie);
1472     }
1473   }
1474   src->retry = FALSE;
1475
1476   g_signal_connect (src->msg, "got_headers",
1477       G_CALLBACK (gst_soup_http_src_got_headers_cb), src);
1478   g_signal_connect (src->msg, "got_body",
1479       G_CALLBACK (gst_soup_http_src_got_body_cb), src);
1480   g_signal_connect (src->msg, "finished",
1481       G_CALLBACK (gst_soup_http_src_finished_cb), src);
1482   g_signal_connect (src->msg, "got_chunk",
1483       G_CALLBACK (gst_soup_http_src_got_chunk_cb), src);
1484   soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS |
1485       (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT));
1486   soup_message_set_chunk_allocator (src->msg,
1487       gst_soup_http_src_chunk_allocator, src, NULL);
1488   gst_soup_http_src_add_range_header (src, src->request_position,
1489       src->stop_position);
1490
1491   gst_soup_http_src_add_extra_headers (src);
1492
1493   return TRUE;
1494 }
1495
1496 static GstFlowReturn
1497 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method,
1498     GstBuffer ** outbuf)
1499 {
1500   /* If we're not OK, just go out of here */
1501   if (src->ret != GST_FLOW_OK) {
1502     GST_DEBUG_OBJECT (src, "Previous flow return not OK: %s",
1503         gst_flow_get_name (src->ret));
1504     return src->ret;
1505   }
1506
1507   GST_LOG_OBJECT (src, "Running request for method: %s", method);
1508   if (src->msg && (src->request_position != src->read_position)) {
1509     if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) {
1510       gst_soup_http_src_add_range_header (src, src->request_position,
1511           src->stop_position);
1512     } else {
1513       GST_DEBUG_OBJECT (src, "Seek from position %" G_GUINT64_FORMAT
1514           " to %" G_GUINT64_FORMAT ": requeueing connection request",
1515           src->read_position, src->request_position);
1516       gst_soup_http_src_cancel_message (src);
1517     }
1518   }
1519   if (!src->msg)
1520     if (!gst_soup_http_src_build_message (src, method)) {
1521       return GST_FLOW_ERROR;
1522     }
1523
1524   src->ret = GST_FLOW_CUSTOM_ERROR;
1525   src->outbuf = outbuf;
1526   do {
1527     if (src->interrupted) {
1528       GST_DEBUG_OBJECT (src, "interrupted");
1529       src->ret = GST_FLOW_FLUSHING;
1530       break;
1531     }
1532     if (src->retry) {
1533       GST_DEBUG_OBJECT (src, "Reconnecting");
1534       if (!gst_soup_http_src_build_message (src, method)) {
1535         return GST_FLOW_ERROR;
1536       }
1537       src->retry = FALSE;
1538       continue;
1539     }
1540     if (!src->msg) {
1541       GST_DEBUG_OBJECT (src, "EOS reached");
1542       break;
1543     }
1544
1545     switch (src->session_io_status) {
1546       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE:
1547         GST_DEBUG_OBJECT (src, "Queueing connection request");
1548         gst_soup_http_src_queue_message (src);
1549         break;
1550       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED:
1551         break;
1552       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING:
1553         gst_soup_http_src_session_unpause_message (src);
1554         break;
1555       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED:
1556         /* Impossible. */
1557         break;
1558     }
1559
1560     if (src->ret == GST_FLOW_CUSTOM_ERROR)
1561       g_main_loop_run (src->loop);
1562
1563   } while (src->ret == GST_FLOW_CUSTOM_ERROR);
1564
1565   /* Let the request finish if we had a stop position and are there */
1566   if (src->ret == GST_FLOW_OK && src->stop_position != -1
1567       && src->read_position >= src->stop_position) {
1568     src->outbuf = NULL;
1569     gst_soup_http_src_session_unpause_message (src);
1570     g_main_loop_run (src->loop);
1571
1572     g_cond_signal (&src->request_finished_cond);
1573     /* Return OK unconditionally here, src->ret will
1574      * be most likely be EOS now but we want to
1575      * consume the buffer we got above */
1576     return GST_FLOW_OK;
1577   }
1578
1579   if (src->ret == GST_FLOW_CUSTOM_ERROR)
1580     src->ret = GST_FLOW_EOS;
1581   g_cond_signal (&src->request_finished_cond);
1582
1583   return src->ret;
1584 }
1585
1586 static GstFlowReturn
1587 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
1588 {
1589   GstSoupHTTPSrc *src;
1590   GstFlowReturn ret;
1591
1592   src = GST_SOUP_HTTP_SRC (psrc);
1593
1594   g_mutex_lock (&src->mutex);
1595   *outbuf = NULL;
1596   ret = gst_soup_http_src_do_request (src, SOUP_METHOD_GET, outbuf);
1597   g_mutex_unlock (&src->mutex);
1598   return ret;
1599 }
1600
1601 static gboolean
1602 gst_soup_http_src_start (GstBaseSrc * bsrc)
1603 {
1604   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1605
1606   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
1607
1608   return gst_soup_http_src_session_open (src);
1609 }
1610
1611 static gboolean
1612 gst_soup_http_src_stop (GstBaseSrc * bsrc)
1613 {
1614   GstSoupHTTPSrc *src;
1615
1616   src = GST_SOUP_HTTP_SRC (bsrc);
1617   GST_DEBUG_OBJECT (src, "stop()");
1618   if (src->keep_alive)
1619     gst_soup_http_src_cancel_message (src);
1620   else
1621     gst_soup_http_src_session_close (src);
1622
1623   gst_soup_http_src_reset (src);
1624   return TRUE;
1625 }
1626
1627 static GstStateChangeReturn
1628 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
1629 {
1630   GstStateChangeReturn ret;
1631   GstSoupHTTPSrc *src;
1632
1633   src = GST_SOUP_HTTP_SRC (element);
1634
1635   switch (transition) {
1636     case GST_STATE_CHANGE_READY_TO_NULL:
1637       gst_soup_http_src_session_close (src);
1638       break;
1639     default:
1640       break;
1641   }
1642
1643   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1644
1645   return ret;
1646 }
1647
1648 /* Interrupt a blocking request. */
1649 static gboolean
1650 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
1651 {
1652   GstSoupHTTPSrc *src;
1653
1654   src = GST_SOUP_HTTP_SRC (bsrc);
1655   GST_DEBUG_OBJECT (src, "unlock()");
1656
1657   src->interrupted = TRUE;
1658   src->ret = GST_FLOW_FLUSHING;
1659   if (src->loop)
1660     g_main_loop_quit (src->loop);
1661   g_cond_signal (&src->request_finished_cond);
1662   return TRUE;
1663 }
1664
1665 /* Interrupt interrupt. */
1666 static gboolean
1667 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
1668 {
1669   GstSoupHTTPSrc *src;
1670
1671   src = GST_SOUP_HTTP_SRC (bsrc);
1672   GST_DEBUG_OBJECT (src, "unlock_stop()");
1673
1674   src->interrupted = FALSE;
1675   src->ret = GST_FLOW_OK;
1676   return TRUE;
1677 }
1678
1679 static gboolean
1680 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
1681 {
1682   GstSoupHTTPSrc *src;
1683
1684   src = GST_SOUP_HTTP_SRC (bsrc);
1685
1686   if (src->have_size) {
1687     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
1688         src->content_size);
1689     *size = src->content_size;
1690     return TRUE;
1691   }
1692   GST_DEBUG_OBJECT (src, "get_size() = FALSE");
1693   return FALSE;
1694 }
1695
1696 static void
1697 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
1698 {
1699   GstFlowReturn ret = GST_FLOW_OK;
1700
1701   /* Special case to check if the server allows range requests
1702    * before really starting to get data in the buffer creation
1703    * loops.
1704    */
1705   if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
1706     g_mutex_lock (&src->mutex);
1707     while (!src->got_headers && !src->interrupted && ret == GST_FLOW_OK) {
1708       if ((src->msg && src->msg->method != SOUP_METHOD_HEAD) &&
1709           src->session_io_status != GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) {
1710         /* wait for the current request to finish */
1711         g_cond_wait (&src->request_finished_cond, &src->mutex);
1712       } else {
1713         if (gst_soup_http_src_session_open (src)) {
1714           ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD, NULL);
1715         }
1716       }
1717     }
1718     if (src->ret == GST_FLOW_EOS) {
1719       /* A HEAD request shouldn't lead to EOS */
1720       src->ret = GST_FLOW_OK;
1721     }
1722     /* resets status to idle */
1723     gst_soup_http_src_cancel_message (src);
1724     g_mutex_unlock (&src->mutex);
1725   }
1726
1727 }
1728
1729 static gboolean
1730 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
1731 {
1732   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1733
1734   gst_soup_http_src_check_seekable (src);
1735
1736   return src->seekable;
1737 }
1738
1739 static gboolean
1740 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
1741 {
1742   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1743
1744   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1745       ")", segment->start, segment->stop);
1746   if (src->read_position == segment->start &&
1747       src->request_position == src->read_position &&
1748       src->stop_position == segment->stop) {
1749     GST_DEBUG_OBJECT (src,
1750         "Seek to current read/end position and no seek pending");
1751     return TRUE;
1752   }
1753
1754   gst_soup_http_src_check_seekable (src);
1755
1756   /* If we have no headers we don't know yet if it is seekable or not.
1757    * Store the start position and error out later if it isn't */
1758   if (src->got_headers && !src->seekable) {
1759     GST_WARNING_OBJECT (src, "Not seekable");
1760     return FALSE;
1761   }
1762
1763   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
1764     GST_WARNING_OBJECT (src, "Invalid seek segment");
1765     return FALSE;
1766   }
1767
1768   if (src->have_size && segment->start >= src->content_size) {
1769     GST_WARNING_OBJECT (src,
1770         "Potentially seeking behind end of file, might EOS immediately");
1771   }
1772
1773   /* Wait for create() to handle the jump in offset. */
1774   src->request_position = segment->start;
1775   src->stop_position = segment->stop;
1776
1777   return TRUE;
1778 }
1779
1780 static gboolean
1781 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
1782 {
1783   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1784   gboolean ret;
1785   GstSchedulingFlags flags;
1786   gint minsize, maxsize, align;
1787
1788   switch (GST_QUERY_TYPE (query)) {
1789     case GST_QUERY_URI:
1790       gst_query_set_uri (query, src->location);
1791       if (src->redirection_uri != NULL)
1792         gst_query_set_uri_redirection (query, src->redirection_uri);
1793       ret = TRUE;
1794       break;
1795     default:
1796       ret = FALSE;
1797       break;
1798   }
1799
1800   if (!ret)
1801     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
1802
1803   switch (GST_QUERY_TYPE (query)) {
1804     case GST_QUERY_SCHEDULING:
1805       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
1806       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
1807       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
1808       break;
1809     default:
1810       break;
1811   }
1812
1813   return ret;
1814 }
1815
1816 static gboolean
1817 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
1818     GError ** error)
1819 {
1820   const char *alt_schemes[] = { "icy://", "icyx://" };
1821   guint i;
1822
1823   if (src->location) {
1824     g_free (src->location);
1825     src->location = NULL;
1826   }
1827
1828   if (uri == NULL)
1829     return FALSE;
1830
1831   for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
1832     if (g_str_has_prefix (uri, alt_schemes[i])) {
1833       src->location =
1834           g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
1835       return TRUE;
1836     }
1837   }
1838
1839   if (src->redirection_uri) {
1840     g_free (src->redirection_uri);
1841     src->redirection_uri = NULL;
1842   }
1843
1844   src->location = g_strdup (uri);
1845
1846   return TRUE;
1847 }
1848
1849 static gboolean
1850 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
1851 {
1852   if (src->proxy) {
1853     soup_uri_free (src->proxy);
1854     src->proxy = NULL;
1855   }
1856   if (g_str_has_prefix (uri, "http://")) {
1857     src->proxy = soup_uri_new (uri);
1858   } else {
1859     gchar *new_uri = g_strconcat ("http://", uri, NULL);
1860
1861     src->proxy = soup_uri_new (new_uri);
1862     g_free (new_uri);
1863   }
1864
1865   return TRUE;
1866 }
1867
1868 static guint
1869 gst_soup_http_src_uri_get_type (GType type)
1870 {
1871   return GST_URI_SRC;
1872 }
1873
1874 static const gchar *const *
1875 gst_soup_http_src_uri_get_protocols (GType type)
1876 {
1877   static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
1878
1879   return protocols;
1880 }
1881
1882 static gchar *
1883 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
1884 {
1885   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
1886
1887   /* FIXME: make thread-safe */
1888   return g_strdup (src->location);
1889 }
1890
1891 static gboolean
1892 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1893     GError ** error)
1894 {
1895   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
1896
1897   return gst_soup_http_src_set_location (src, uri, error);
1898 }
1899
1900 static void
1901 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1902 {
1903   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1904
1905   iface->get_type = gst_soup_http_src_uri_get_type;
1906   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
1907   iface->get_uri = gst_soup_http_src_uri_get_uri;
1908   iface->set_uri = gst_soup_http_src_uri_set_uri;
1909 }