souphttpsrc: Only keep-alive the connection in stop() if we have finished all previou...
[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     GST_DEBUG_OBJECT (src, "Cancelling message");
713     src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED;
714     soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_CANCELLED);
715   }
716   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE;
717   src->msg = NULL;
718 }
719
720 static void
721 gst_soup_http_src_queue_message (GstSoupHTTPSrc * src)
722 {
723   soup_session_queue_message (src->session, src->msg,
724       (SoupSessionCallback) gst_soup_http_src_response_cb, src);
725   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED;
726 }
727
728 static gboolean
729 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
730     guint64 stop_offset)
731 {
732   gchar buf[64];
733
734   gint rc;
735
736   soup_message_headers_remove (src->msg->request_headers, "Range");
737   if (offset || stop_offset != -1) {
738     if (stop_offset != -1) {
739       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
740           G_GUINT64_FORMAT, offset, stop_offset);
741     } else {
742       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
743           offset);
744     }
745     if (rc > sizeof (buf) || rc < 0)
746       return FALSE;
747     soup_message_headers_append (src->msg->request_headers, "Range", buf);
748   }
749   src->read_position = offset;
750   return TRUE;
751 }
752
753 static gboolean
754 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
755 {
756   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
757   const gchar *field_name = g_quark_to_string (field_id);
758   gchar *field_content = NULL;
759
760   if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
761     field_content = g_value_dup_string (value);
762   } else {
763     GValue dest = { 0, };
764
765     g_value_init (&dest, G_TYPE_STRING);
766     if (g_value_transform (value, &dest)) {
767       field_content = g_value_dup_string (&dest);
768     }
769   }
770
771   if (field_content == NULL) {
772     GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
773         "or can't be converted to a string", field_name);
774     return FALSE;
775   }
776
777   GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
778       field_content);
779   soup_message_headers_append (src->msg->request_headers, field_name,
780       field_content);
781
782   g_free (field_content);
783
784   return TRUE;
785 }
786
787 static gboolean
788 _append_extra_headers (GQuark field_id, const GValue * value,
789     gpointer user_data)
790 {
791   if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
792     guint n = gst_value_array_get_size (value);
793     guint i;
794
795     for (i = 0; i < n; i++) {
796       const GValue *v = gst_value_array_get_value (value, i);
797
798       if (!_append_extra_header (field_id, v, user_data))
799         return FALSE;
800     }
801   } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
802     guint n = gst_value_list_get_size (value);
803     guint i;
804
805     for (i = 0; i < n; i++) {
806       const GValue *v = gst_value_list_get_value (value, i);
807
808       if (!_append_extra_header (field_id, v, user_data))
809         return FALSE;
810     }
811   } else {
812     return _append_extra_header (field_id, value, user_data);
813   }
814
815   return TRUE;
816 }
817
818
819 static gboolean
820 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
821 {
822   if (!src->extra_headers)
823     return TRUE;
824
825   return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
826 }
827
828
829 static void
830 gst_soup_http_src_session_unpause_message (GstSoupHTTPSrc * src)
831 {
832   soup_session_unpause_message (src->session, src->msg);
833 }
834
835 static void
836 gst_soup_http_src_session_pause_message (GstSoupHTTPSrc * src)
837 {
838   soup_session_pause_message (src->session, src->msg);
839 }
840
841 static gboolean
842 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
843 {
844   if (src->session) {
845     GST_DEBUG_OBJECT (src, "Session is already open");
846     return TRUE;
847   }
848
849   if (!src->location) {
850     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
851         ("Missing location property"));
852     return FALSE;
853   }
854
855   if (!src->context)
856     src->context = g_main_context_new ();
857
858   if (!src->loop)
859     src->loop = g_main_loop_new (src->context, TRUE);
860   if (!src->loop) {
861     GST_ELEMENT_ERROR (src, LIBRARY, INIT,
862         (NULL), ("Failed to start GMainLoop"));
863     g_main_context_unref (src->context);
864     return FALSE;
865   }
866
867   if (!src->session) {
868     GST_DEBUG_OBJECT (src, "Creating session");
869     if (src->proxy == NULL) {
870       src->session =
871           soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
872           src->context, SOUP_SESSION_USER_AGENT, src->user_agent,
873           SOUP_SESSION_TIMEOUT, src->timeout,
874           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
875           SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_DEFAULT,
876           NULL);
877     } else {
878       src->session =
879           soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
880           src->context, SOUP_SESSION_PROXY_URI, src->proxy,
881           SOUP_SESSION_TIMEOUT, src->timeout,
882           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
883           SOUP_SESSION_USER_AGENT, src->user_agent, NULL);
884     }
885
886     if (!src->session) {
887       GST_ELEMENT_ERROR (src, LIBRARY, INIT,
888           (NULL), ("Failed to create async session"));
889       return FALSE;
890     }
891
892     g_signal_connect (src->session, "authenticate",
893         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
894
895     /* Set up logging */
896     gst_soup_util_log_setup (src->session, src->log_level, GST_ELEMENT (src));
897     if (src->ssl_ca_file)
898       g_object_set (src->session, "ssl-ca-file", src->ssl_ca_file, NULL);
899     else
900       g_object_set (src->session, "ssl-use-system-ca-file",
901           src->ssl_use_system_ca_file, NULL);
902   } else {
903     GST_DEBUG_OBJECT (src, "Re-using session");
904   }
905
906   if (src->compress)
907     soup_session_add_feature_by_type (src->session, SOUP_TYPE_CONTENT_DECODER);
908   else
909     soup_session_remove_feature_by_type (src->session,
910         SOUP_TYPE_CONTENT_DECODER);
911
912   return TRUE;
913 }
914
915 static void
916 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
917 {
918   GST_DEBUG_OBJECT (src, "Closing session");
919
920   if (src->session) {
921     soup_session_abort (src->session);  /* This unrefs the message. */
922     g_object_unref (src->session);
923     src->session = NULL;
924     src->msg = NULL;
925   }
926   if (src->loop) {
927     g_main_loop_unref (src->loop);
928     g_main_context_unref (src->context);
929     src->loop = NULL;
930     src->context = NULL;
931   }
932 }
933
934 static void
935 gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg,
936     SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src)
937 {
938   if (!retrying) {
939     /* First time authentication only, if we fail and are called again with retry true fall through */
940     if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
941       if (src->user_id && src->user_pw)
942         soup_auth_authenticate (auth, src->user_id, src->user_pw);
943     } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
944       if (src->proxy_id && src->proxy_pw)
945         soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
946     }
947   }
948 }
949
950 static void
951 gst_soup_http_src_got_headers_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
952 {
953   const char *value;
954   GstTagList *tag_list;
955   GstBaseSrc *basesrc;
956   guint64 newsize;
957   GHashTable *params = NULL;
958
959   GST_INFO_OBJECT (src, "got headers");
960
961   if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
962       src->proxy_id && src->proxy_pw)
963     return;
964
965   if (src->automatic_redirect && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
966     src->redirection_uri = g_strdup (soup_message_headers_get_one
967         (msg->response_headers, "Location"));
968     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\"", msg->status_code,
969         src->redirection_uri);
970     return;
971   }
972
973   if (msg->status_code == SOUP_STATUS_UNAUTHORIZED)
974     return;
975
976   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING;
977   src->got_headers = TRUE;
978
979   /* Parse Content-Length. */
980   if (soup_message_headers_get_encoding (msg->response_headers) ==
981       SOUP_ENCODING_CONTENT_LENGTH) {
982     newsize = src->request_position +
983         soup_message_headers_get_content_length (msg->response_headers);
984     if (!src->have_size || (src->content_size != newsize)) {
985       src->content_size = newsize;
986       src->have_size = TRUE;
987       src->seekable = TRUE;
988       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
989
990       basesrc = GST_BASE_SRC_CAST (src);
991       basesrc->segment.duration = src->content_size;
992       gst_element_post_message (GST_ELEMENT (src),
993           gst_message_new_duration_changed (GST_OBJECT (src)));
994     }
995   }
996
997   /* Icecast stuff */
998   tag_list = gst_tag_list_new_empty ();
999
1000   if ((value =
1001           soup_message_headers_get_one (msg->response_headers,
1002               "icy-metaint")) != NULL) {
1003     gint icy_metaint = atoi (value);
1004
1005     GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value, icy_metaint);
1006     if (icy_metaint > 0) {
1007       if (src->src_caps)
1008         gst_caps_unref (src->src_caps);
1009
1010       src->src_caps = gst_caps_new_simple ("application/x-icy",
1011           "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1012
1013       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1014     }
1015   }
1016   if ((value =
1017           soup_message_headers_get_content_type (msg->response_headers,
1018               &params)) != NULL) {
1019     GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1020     if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1021       gint channels = 2;
1022       gint rate = 44100;
1023       char *param;
1024
1025       if (src->src_caps)
1026         gst_caps_unref (src->src_caps);
1027
1028       param = g_hash_table_lookup (params, "channels");
1029       if (param != NULL)
1030         channels = atol (param);
1031
1032       param = g_hash_table_lookup (params, "rate");
1033       if (param != NULL)
1034         rate = atol (param);
1035
1036       src->src_caps = gst_caps_new_simple ("audio/x-raw",
1037           "format", G_TYPE_STRING, "S16BE",
1038           "layout", G_TYPE_STRING, "interleaved",
1039           "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1040
1041       gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1042     } else {
1043       /* Set the Content-Type field on the caps */
1044       if (src->src_caps) {
1045         src->src_caps = gst_caps_make_writable (src->src_caps);
1046         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1047             value, NULL);
1048         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1049       }
1050     }
1051   }
1052
1053   if (params != NULL)
1054     g_hash_table_destroy (params);
1055
1056   if ((value =
1057           soup_message_headers_get_one (msg->response_headers,
1058               "icy-name")) != NULL) {
1059     g_free (src->iradio_name);
1060     src->iradio_name = gst_soup_http_src_unicodify (value);
1061     if (src->iradio_name) {
1062       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1063           src->iradio_name, NULL);
1064     }
1065   }
1066   if ((value =
1067           soup_message_headers_get_one (msg->response_headers,
1068               "icy-genre")) != NULL) {
1069     g_free (src->iradio_genre);
1070     src->iradio_genre = gst_soup_http_src_unicodify (value);
1071     if (src->iradio_genre) {
1072       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1073           src->iradio_genre, NULL);
1074     }
1075   }
1076   if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url"))
1077       != NULL) {
1078     g_free (src->iradio_url);
1079     src->iradio_url = gst_soup_http_src_unicodify (value);
1080     if (src->iradio_url) {
1081       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1082           src->iradio_url, NULL);
1083     }
1084   }
1085   if (!gst_tag_list_is_empty (tag_list)) {
1086     GST_DEBUG_OBJECT (src,
1087         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1088     gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1089   } else {
1090     gst_tag_list_unref (tag_list);
1091   }
1092
1093   /* Handle HTTP errors. */
1094   gst_soup_http_src_parse_status (msg, src);
1095
1096   /* Check if Range header was respected. */
1097   if (src->ret == GST_FLOW_CUSTOM_ERROR &&
1098       src->read_position && msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) {
1099     src->seekable = FALSE;
1100     GST_ELEMENT_ERROR (src, RESOURCE, SEEK,
1101         (_("Server does not support seeking.")),
1102         ("Server does not accept Range HTTP header, URL: %s", src->location));
1103     src->ret = GST_FLOW_ERROR;
1104   }
1105
1106   /* If we are going to error out, stop all processing right here, so we
1107    * don't output any data (such as an error html page), and return
1108    * GST_FLOW_ERROR from the create function instead of having
1109    * got_chunk_cb overwrite src->ret with FLOW_OK again. */
1110   if (src->ret == GST_FLOW_ERROR || src->ret == GST_FLOW_EOS) {
1111     gst_soup_http_src_session_pause_message (src);
1112
1113     if (src->loop)
1114       g_main_loop_quit (src->loop);
1115   }
1116   g_cond_signal (&src->request_finished_cond);
1117 }
1118
1119 /* Have body. Signal EOS. */
1120 static void
1121 gst_soup_http_src_got_body_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1122 {
1123   if (G_UNLIKELY (msg != src->msg)) {
1124     GST_DEBUG_OBJECT (src, "got body, but not for current message");
1125     return;
1126   }
1127   if (G_UNLIKELY (src->session_io_status !=
1128           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1129     /* Probably a redirect. */
1130     return;
1131   }
1132   GST_DEBUG_OBJECT (src, "got body");
1133   src->ret = GST_FLOW_EOS;
1134   src->have_body = TRUE;
1135
1136   /* no need to interrupt the message here, we do it on the
1137    * finished_cb anyway if needed. And getting the body might mean
1138    * that the connection was hang up before finished. This happens when
1139    * the pipeline is stalled for too long (long pauses during playback).
1140    * Best to let it continue from here and pause because it reached the
1141    * final bytes based on content_size or received an out of range error */
1142 }
1143
1144 /* Finished. Signal EOS. */
1145 static void
1146 gst_soup_http_src_finished_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1147 {
1148   if (G_UNLIKELY (msg != src->msg)) {
1149     GST_DEBUG_OBJECT (src, "finished, but not for current message");
1150     return;
1151   }
1152   GST_DEBUG_OBJECT (src, "finished");
1153   src->ret = GST_FLOW_EOS;
1154   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED) {
1155     /* gst_soup_http_src_cancel_message() triggered this; probably a seek
1156      * that occurred in the QUEUEING state; i.e. before the connection setup
1157      * was complete. Do nothing */
1158     GST_DEBUG_OBJECT (src, "cancelled");
1159   } else if (src->session_io_status ==
1160       GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING && src->read_position > 0 &&
1161       (src->have_size && src->read_position < src->content_size) &&
1162       (src->max_retries == -1 || src->retry_count < src->max_retries)) {
1163     /* The server disconnected while streaming. Reconnect and seeking to the
1164      * last location. */
1165     src->retry = TRUE;
1166     src->retry_count++;
1167     src->ret = GST_FLOW_CUSTOM_ERROR;
1168   } else if (G_UNLIKELY (src->session_io_status !=
1169           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1170     if (msg->method == SOUP_METHOD_HEAD) {
1171       GST_DEBUG_OBJECT (src, "Ignoring error %d:%s during HEAD request",
1172           msg->status_code, msg->reason_phrase);
1173     } else {
1174       gst_soup_http_src_parse_status (msg, src);
1175     }
1176   }
1177   if (src->loop)
1178     g_main_loop_quit (src->loop);
1179   g_cond_signal (&src->request_finished_cond);
1180 }
1181
1182 /* Buffer lifecycle management.
1183  *
1184  * gst_soup_http_src_create() runs the GMainLoop for this element, to let
1185  * Soup take control.
1186  * A GstBuffer is allocated in gst_soup_http_src_chunk_allocator() and
1187  * associated with a SoupBuffer.
1188  * Soup reads HTTP data in the GstBuffer's data buffer.
1189  * The gst_soup_http_src_got_chunk_cb() is then called with the SoupBuffer.
1190  * That sets gst_soup_http_src_create()'s return argument to the GstBuffer,
1191  * increments its refcount (to 2), pauses the flow of data from the HTTP
1192  * source to prevent gst_soup_http_src_got_chunk_cb() from being called
1193  * again and breaks out of the GMainLoop.
1194  * Because the SOUP_MESSAGE_OVERWRITE_CHUNKS flag is set, Soup frees the
1195  * SoupBuffer and calls gst_soup_http_src_chunk_free(), which decrements the
1196  * refcount (to 1).
1197  * gst_soup_http_src_create() returns the GstBuffer. It will be freed by a
1198  * downstream element.
1199  * If Soup fails to read HTTP data, it does not call
1200  * gst_soup_http_src_got_chunk_cb(), but still frees the SoupBuffer and
1201  * calls gst_soup_http_src_chunk_free(), which decrements the GstBuffer's
1202  * refcount to 0, freeing it.
1203  */
1204
1205 typedef struct
1206 {
1207   GstBuffer *buffer;
1208   GstMapInfo map;
1209 } SoupGstChunk;
1210
1211 static void
1212 gst_soup_http_src_chunk_free (gpointer user_data)
1213 {
1214   SoupGstChunk *chunk = (SoupGstChunk *) user_data;
1215
1216   gst_buffer_unmap (chunk->buffer, &chunk->map);
1217   gst_buffer_unref (chunk->buffer);
1218   g_slice_free (SoupGstChunk, chunk);
1219 }
1220
1221 static SoupBuffer *
1222 gst_soup_http_src_chunk_allocator (SoupMessage * msg, gsize max_len,
1223     gpointer user_data)
1224 {
1225   GstSoupHTTPSrc *src = (GstSoupHTTPSrc *) user_data;
1226   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1227   GstBuffer *gstbuf;
1228   SoupBuffer *soupbuf;
1229   gsize length;
1230   GstFlowReturn rc;
1231   SoupGstChunk *chunk;
1232
1233   if (max_len)
1234     length = MIN (basesrc->blocksize, max_len);
1235   else
1236     length = basesrc->blocksize;
1237   GST_DEBUG_OBJECT (src, "alloc %" G_GSIZE_FORMAT " bytes <= %" G_GSIZE_FORMAT,
1238       length, max_len);
1239
1240   rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1, length, &gstbuf);
1241   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1242     /* Failed to allocate buffer. Stall SoupSession and return error code
1243      * to create(). */
1244     src->ret = rc;
1245     g_main_loop_quit (src->loop);
1246     return NULL;
1247   }
1248
1249   chunk = g_slice_new0 (SoupGstChunk);
1250   chunk->buffer = gstbuf;
1251   gst_buffer_map (gstbuf, &chunk->map, GST_MAP_READWRITE);
1252
1253   soupbuf = soup_buffer_new_with_owner (chunk->map.data, chunk->map.size,
1254       chunk, gst_soup_http_src_chunk_free);
1255
1256   return soupbuf;
1257 }
1258
1259 static void
1260 gst_soup_http_src_got_chunk_cb (SoupMessage * msg, SoupBuffer * chunk,
1261     GstSoupHTTPSrc * src)
1262 {
1263   GstBaseSrc *basesrc;
1264   guint64 new_position;
1265   SoupGstChunk *gchunk;
1266
1267   if (G_UNLIKELY (msg != src->msg)) {
1268     GST_DEBUG_OBJECT (src, "got chunk, but not for current message");
1269     return;
1270   }
1271   if (G_UNLIKELY (!src->outbuf)) {
1272     GST_DEBUG_OBJECT (src, "got chunk but we're not expecting one");
1273     src->ret = GST_FLOW_OK;
1274     gst_soup_http_src_cancel_message (src);
1275     g_main_loop_quit (src->loop);
1276     return;
1277   }
1278
1279   /* We got data, reset the retry counter */
1280   src->retry_count = 0;
1281
1282   src->have_body = FALSE;
1283   if (G_UNLIKELY (src->session_io_status !=
1284           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1285     /* Probably a redirect. */
1286     return;
1287   }
1288   basesrc = GST_BASE_SRC_CAST (src);
1289   GST_DEBUG_OBJECT (src, "got chunk of %" G_GSIZE_FORMAT " bytes",
1290       chunk->length);
1291
1292   /* Extract the GstBuffer from the SoupBuffer and set its fields. */
1293   gchunk = (SoupGstChunk *) soup_buffer_get_owner (chunk);
1294   *src->outbuf = gchunk->buffer;
1295
1296   gst_buffer_resize (*src->outbuf, 0, chunk->length);
1297   GST_BUFFER_OFFSET (*src->outbuf) = basesrc->segment.position;
1298
1299   gst_buffer_ref (*src->outbuf);
1300
1301   new_position = src->read_position + chunk->length;
1302   if (G_LIKELY (src->request_position == src->read_position))
1303     src->request_position = new_position;
1304   src->read_position = new_position;
1305
1306   if (src->have_size) {
1307     if (new_position > src->content_size) {
1308       GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
1309           "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
1310           src->content_size);
1311       src->content_size = new_position;
1312       basesrc->segment.duration = src->content_size;
1313       gst_element_post_message (GST_ELEMENT (src),
1314           gst_message_new_duration_changed (GST_OBJECT (src)));
1315     } else if (new_position == src->content_size) {
1316       GST_DEBUG_OBJECT (src, "We're EOS now");
1317     }
1318   }
1319
1320   src->ret = GST_FLOW_OK;
1321   g_main_loop_quit (src->loop);
1322   gst_soup_http_src_session_pause_message (src);
1323 }
1324
1325 static void
1326 gst_soup_http_src_response_cb (SoupSession * session, SoupMessage * msg,
1327     GstSoupHTTPSrc * src)
1328 {
1329   if (G_UNLIKELY (msg != src->msg)) {
1330     GST_DEBUG_OBJECT (src, "got response %d: %s, but not for current message",
1331         msg->status_code, msg->reason_phrase);
1332     return;
1333   }
1334   if (G_UNLIKELY (src->session_io_status !=
1335           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)
1336       && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
1337     /* Ignore redirections. */
1338     return;
1339   }
1340   GST_DEBUG_OBJECT (src, "got response %d: %s", msg->status_code,
1341       msg->reason_phrase);
1342   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING &&
1343       src->read_position > 0 && (src->have_size
1344           && src->read_position < src->content_size) &&
1345       (src->max_retries == -1 || src->retry_count < src->max_retries)) {
1346     /* The server disconnected while streaming. Reconnect and seeking to the
1347      * last location. */
1348     src->retry = TRUE;
1349     src->retry_count++;
1350   } else {
1351     gst_soup_http_src_parse_status (msg, src);
1352   }
1353   /* The session's SoupMessage object expires after this callback returns. */
1354   src->msg = NULL;
1355   g_main_loop_quit (src->loop);
1356 }
1357
1358 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1359   GST_ELEMENT_ERROR ((src), cat, code, ("%s", error_message),        \
1360       ("%s (%d), URL: %s", (soup_msg)->reason_phrase,                \
1361           (soup_msg)->status_code, (src)->location));
1362
1363 static void
1364 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1365 {
1366   if (msg->method == SOUP_METHOD_HEAD) {
1367     if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
1368       GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1369           msg->status_code);
1370   } else if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
1371     switch (msg->status_code) {
1372       case SOUP_STATUS_CANT_RESOLVE:
1373       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1374         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1375             _("Could not resolve server name."));
1376         src->ret = GST_FLOW_ERROR;
1377         break;
1378       case SOUP_STATUS_CANT_CONNECT:
1379       case SOUP_STATUS_CANT_CONNECT_PROXY:
1380         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1381             _("Could not establish connection to server."));
1382         src->ret = GST_FLOW_ERROR;
1383         break;
1384       case SOUP_STATUS_SSL_FAILED:
1385         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1386             _("Secure connection setup failed."));
1387         src->ret = GST_FLOW_ERROR;
1388         break;
1389       case SOUP_STATUS_IO_ERROR:
1390         if (src->max_retries == -1 || src->retry_count < src->max_retries) {
1391           src->retry = TRUE;
1392           src->retry_count++;
1393           src->ret = GST_FLOW_CUSTOM_ERROR;
1394         } else {
1395           SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1396               _("A network error occured, or the server closed the connection "
1397                   "unexpectedly."));
1398           src->ret = GST_FLOW_ERROR;
1399         }
1400         break;
1401       case SOUP_STATUS_MALFORMED:
1402         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1403             _("Server sent bad data."));
1404         src->ret = GST_FLOW_ERROR;
1405         break;
1406       case SOUP_STATUS_CANCELLED:
1407         /* No error message when interrupted by program. */
1408         break;
1409     }
1410   } else if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) ||
1411       SOUP_STATUS_IS_REDIRECTION (msg->status_code) ||
1412       SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) {
1413     /* Report HTTP error. */
1414
1415     /* when content_size is unknown and we have just finished receiving
1416      * a body message, requests that go beyond the content limits will result
1417      * in an error. Here we convert those to EOS */
1418     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1419         src->have_body && !src->have_size) {
1420       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1421           "body, returning EOS");
1422       src->ret = GST_FLOW_EOS;
1423       return;
1424     }
1425
1426     /* FIXME: reason_phrase is not translated and not suitable for user
1427      * error dialog according to libsoup documentation.
1428      */
1429     if (msg->status_code == SOUP_STATUS_NOT_FOUND) {
1430       GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,
1431           ("%s", msg->reason_phrase),
1432           ("%s (%d), URL: %s", msg->reason_phrase, msg->status_code,
1433               src->location));
1434     } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED ||
1435         msg->status_code == SOUP_STATUS_PAYMENT_REQUIRED ||
1436         msg->status_code == SOUP_STATUS_FORBIDDEN ||
1437         msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1438       GST_ELEMENT_ERROR (src, RESOURCE, NOT_AUTHORIZED,
1439           ("%s", msg->reason_phrase),
1440           ("%s (%d), URL: %s", msg->reason_phrase, msg->status_code,
1441               src->location));
1442     } else {
1443       GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1444           ("%s", msg->reason_phrase),
1445           ("%s (%d), URL: %s", msg->reason_phrase, msg->status_code,
1446               src->location));
1447     }
1448     src->ret = GST_FLOW_ERROR;
1449   }
1450 }
1451
1452 static gboolean
1453 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1454 {
1455   g_return_val_if_fail (src->msg == NULL, FALSE);
1456
1457   src->msg = soup_message_new (method, src->location);
1458   if (!src->msg) {
1459     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1460         ("Error parsing URL."), ("URL: %s", src->location));
1461     return FALSE;
1462   }
1463   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE;
1464   if (!src->keep_alive) {
1465     soup_message_headers_append (src->msg->request_headers, "Connection",
1466         "close");
1467   }
1468   if (src->iradio_mode) {
1469     soup_message_headers_append (src->msg->request_headers, "icy-metadata",
1470         "1");
1471   }
1472   if (src->cookies) {
1473     gchar **cookie;
1474
1475     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1476       soup_message_headers_append (src->msg->request_headers, "Cookie",
1477           *cookie);
1478     }
1479   }
1480   src->retry = FALSE;
1481
1482   g_signal_connect (src->msg, "got_headers",
1483       G_CALLBACK (gst_soup_http_src_got_headers_cb), src);
1484   g_signal_connect (src->msg, "got_body",
1485       G_CALLBACK (gst_soup_http_src_got_body_cb), src);
1486   g_signal_connect (src->msg, "finished",
1487       G_CALLBACK (gst_soup_http_src_finished_cb), src);
1488   g_signal_connect (src->msg, "got_chunk",
1489       G_CALLBACK (gst_soup_http_src_got_chunk_cb), src);
1490   soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS |
1491       (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT));
1492   soup_message_set_chunk_allocator (src->msg,
1493       gst_soup_http_src_chunk_allocator, src, NULL);
1494   gst_soup_http_src_add_range_header (src, src->request_position,
1495       src->stop_position);
1496
1497   gst_soup_http_src_add_extra_headers (src);
1498
1499   return TRUE;
1500 }
1501
1502 static GstFlowReturn
1503 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method,
1504     GstBuffer ** outbuf)
1505 {
1506   /* If we're not OK, just go out of here */
1507   if (src->ret != GST_FLOW_OK) {
1508     GST_DEBUG_OBJECT (src, "Previous flow return not OK: %s",
1509         gst_flow_get_name (src->ret));
1510     return src->ret;
1511   }
1512
1513   GST_LOG_OBJECT (src, "Running request for method: %s", method);
1514   if (src->msg && (src->request_position != src->read_position)) {
1515     if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) {
1516       gst_soup_http_src_add_range_header (src, src->request_position,
1517           src->stop_position);
1518     } else {
1519       GST_DEBUG_OBJECT (src, "Seek from position %" G_GUINT64_FORMAT
1520           " to %" G_GUINT64_FORMAT ": requeueing connection request",
1521           src->read_position, src->request_position);
1522       gst_soup_http_src_cancel_message (src);
1523     }
1524   }
1525   if (!src->msg)
1526     if (!gst_soup_http_src_build_message (src, method)) {
1527       return GST_FLOW_ERROR;
1528     }
1529
1530   src->ret = GST_FLOW_CUSTOM_ERROR;
1531   src->outbuf = outbuf;
1532   do {
1533     if (src->interrupted) {
1534       GST_DEBUG_OBJECT (src, "interrupted");
1535       src->ret = GST_FLOW_FLUSHING;
1536       break;
1537     }
1538     if (src->retry) {
1539       GST_DEBUG_OBJECT (src, "Reconnecting");
1540       if (!gst_soup_http_src_build_message (src, method)) {
1541         return GST_FLOW_ERROR;
1542       }
1543       src->retry = FALSE;
1544       continue;
1545     }
1546     if (!src->msg) {
1547       GST_DEBUG_OBJECT (src, "EOS reached");
1548       break;
1549     }
1550
1551     switch (src->session_io_status) {
1552       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE:
1553         GST_DEBUG_OBJECT (src, "Queueing connection request");
1554         gst_soup_http_src_queue_message (src);
1555         break;
1556       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED:
1557         break;
1558       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING:
1559         gst_soup_http_src_session_unpause_message (src);
1560         break;
1561       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED:
1562         /* Impossible. */
1563         break;
1564     }
1565
1566     if (src->ret == GST_FLOW_CUSTOM_ERROR)
1567       g_main_loop_run (src->loop);
1568
1569   } while (src->ret == GST_FLOW_CUSTOM_ERROR);
1570
1571   /* Let the request finish if we had a stop position and are there */
1572   if (src->ret == GST_FLOW_OK && src->stop_position != -1
1573       && src->read_position >= src->stop_position) {
1574     src->outbuf = NULL;
1575     gst_soup_http_src_session_unpause_message (src);
1576     g_main_loop_run (src->loop);
1577
1578     g_cond_signal (&src->request_finished_cond);
1579     /* Return OK unconditionally here, src->ret will
1580      * be most likely be EOS now but we want to
1581      * consume the buffer we got above */
1582     return GST_FLOW_OK;
1583   }
1584
1585   if (src->ret == GST_FLOW_CUSTOM_ERROR)
1586     src->ret = GST_FLOW_EOS;
1587   g_cond_signal (&src->request_finished_cond);
1588
1589   return src->ret;
1590 }
1591
1592 static GstFlowReturn
1593 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
1594 {
1595   GstSoupHTTPSrc *src;
1596   GstFlowReturn ret;
1597
1598   src = GST_SOUP_HTTP_SRC (psrc);
1599
1600   g_mutex_lock (&src->mutex);
1601   *outbuf = NULL;
1602   ret = gst_soup_http_src_do_request (src, SOUP_METHOD_GET, outbuf);
1603   g_mutex_unlock (&src->mutex);
1604   return ret;
1605 }
1606
1607 static gboolean
1608 gst_soup_http_src_start (GstBaseSrc * bsrc)
1609 {
1610   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1611
1612   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
1613
1614   return gst_soup_http_src_session_open (src);
1615 }
1616
1617 static gboolean
1618 gst_soup_http_src_stop (GstBaseSrc * bsrc)
1619 {
1620   GstSoupHTTPSrc *src;
1621
1622   src = GST_SOUP_HTTP_SRC (bsrc);
1623   GST_DEBUG_OBJECT (src, "stop()");
1624   if (src->keep_alive && !src->msg)
1625     gst_soup_http_src_cancel_message (src);
1626   else
1627     gst_soup_http_src_session_close (src);
1628
1629   gst_soup_http_src_reset (src);
1630   return TRUE;
1631 }
1632
1633 static GstStateChangeReturn
1634 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
1635 {
1636   GstStateChangeReturn ret;
1637   GstSoupHTTPSrc *src;
1638
1639   src = GST_SOUP_HTTP_SRC (element);
1640
1641   switch (transition) {
1642     case GST_STATE_CHANGE_READY_TO_NULL:
1643       gst_soup_http_src_session_close (src);
1644       break;
1645     default:
1646       break;
1647   }
1648
1649   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1650
1651   return ret;
1652 }
1653
1654 /* Interrupt a blocking request. */
1655 static gboolean
1656 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
1657 {
1658   GstSoupHTTPSrc *src;
1659
1660   src = GST_SOUP_HTTP_SRC (bsrc);
1661   GST_DEBUG_OBJECT (src, "unlock()");
1662
1663   src->interrupted = TRUE;
1664   src->ret = GST_FLOW_FLUSHING;
1665   if (src->loop)
1666     g_main_loop_quit (src->loop);
1667   g_cond_signal (&src->request_finished_cond);
1668   return TRUE;
1669 }
1670
1671 /* Interrupt interrupt. */
1672 static gboolean
1673 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
1674 {
1675   GstSoupHTTPSrc *src;
1676
1677   src = GST_SOUP_HTTP_SRC (bsrc);
1678   GST_DEBUG_OBJECT (src, "unlock_stop()");
1679
1680   src->interrupted = FALSE;
1681   src->ret = GST_FLOW_OK;
1682   return TRUE;
1683 }
1684
1685 static gboolean
1686 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
1687 {
1688   GstSoupHTTPSrc *src;
1689
1690   src = GST_SOUP_HTTP_SRC (bsrc);
1691
1692   if (src->have_size) {
1693     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
1694         src->content_size);
1695     *size = src->content_size;
1696     return TRUE;
1697   }
1698   GST_DEBUG_OBJECT (src, "get_size() = FALSE");
1699   return FALSE;
1700 }
1701
1702 static void
1703 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
1704 {
1705   GstFlowReturn ret = GST_FLOW_OK;
1706
1707   /* Special case to check if the server allows range requests
1708    * before really starting to get data in the buffer creation
1709    * loops.
1710    */
1711   if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
1712     g_mutex_lock (&src->mutex);
1713     while (!src->got_headers && !src->interrupted && ret == GST_FLOW_OK) {
1714       if ((src->msg && src->msg->method != SOUP_METHOD_HEAD) &&
1715           src->session_io_status != GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) {
1716         /* wait for the current request to finish */
1717         g_cond_wait (&src->request_finished_cond, &src->mutex);
1718       } else {
1719         if (gst_soup_http_src_session_open (src)) {
1720           ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD, NULL);
1721         }
1722       }
1723     }
1724     if (src->ret == GST_FLOW_EOS) {
1725       /* A HEAD request shouldn't lead to EOS */
1726       src->ret = GST_FLOW_OK;
1727     }
1728     /* resets status to idle */
1729     gst_soup_http_src_cancel_message (src);
1730     g_mutex_unlock (&src->mutex);
1731   }
1732 }
1733
1734 static gboolean
1735 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
1736 {
1737   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1738
1739   gst_soup_http_src_check_seekable (src);
1740
1741   return src->seekable;
1742 }
1743
1744 static gboolean
1745 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
1746 {
1747   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1748
1749   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1750       ")", segment->start, segment->stop);
1751   if (src->read_position == segment->start &&
1752       src->request_position == src->read_position &&
1753       src->stop_position == segment->stop) {
1754     GST_DEBUG_OBJECT (src,
1755         "Seek to current read/end position and no seek pending");
1756     return TRUE;
1757   }
1758
1759   gst_soup_http_src_check_seekable (src);
1760
1761   /* If we have no headers we don't know yet if it is seekable or not.
1762    * Store the start position and error out later if it isn't */
1763   if (src->got_headers && !src->seekable) {
1764     GST_WARNING_OBJECT (src, "Not seekable");
1765     return FALSE;
1766   }
1767
1768   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
1769     GST_WARNING_OBJECT (src, "Invalid seek segment");
1770     return FALSE;
1771   }
1772
1773   if (src->have_size && segment->start >= src->content_size) {
1774     GST_WARNING_OBJECT (src,
1775         "Potentially seeking behind end of file, might EOS immediately");
1776   }
1777
1778   /* Wait for create() to handle the jump in offset. */
1779   src->request_position = segment->start;
1780   src->stop_position = segment->stop;
1781
1782   return TRUE;
1783 }
1784
1785 static gboolean
1786 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
1787 {
1788   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1789   gboolean ret;
1790   GstSchedulingFlags flags;
1791   gint minsize, maxsize, align;
1792
1793   switch (GST_QUERY_TYPE (query)) {
1794     case GST_QUERY_URI:
1795       gst_query_set_uri (query, src->location);
1796       if (src->redirection_uri != NULL)
1797         gst_query_set_uri_redirection (query, src->redirection_uri);
1798       ret = TRUE;
1799       break;
1800     default:
1801       ret = FALSE;
1802       break;
1803   }
1804
1805   if (!ret)
1806     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
1807
1808   switch (GST_QUERY_TYPE (query)) {
1809     case GST_QUERY_SCHEDULING:
1810       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
1811       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
1812       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
1813       break;
1814     default:
1815       break;
1816   }
1817
1818   return ret;
1819 }
1820
1821 static gboolean
1822 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
1823     GError ** error)
1824 {
1825   const char *alt_schemes[] = { "icy://", "icyx://" };
1826   guint i;
1827
1828   if (src->location) {
1829     g_free (src->location);
1830     src->location = NULL;
1831   }
1832
1833   if (uri == NULL)
1834     return FALSE;
1835
1836   for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
1837     if (g_str_has_prefix (uri, alt_schemes[i])) {
1838       src->location =
1839           g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
1840       return TRUE;
1841     }
1842   }
1843
1844   if (src->redirection_uri) {
1845     g_free (src->redirection_uri);
1846     src->redirection_uri = NULL;
1847   }
1848
1849   src->location = g_strdup (uri);
1850
1851   return TRUE;
1852 }
1853
1854 static gboolean
1855 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
1856 {
1857   if (src->proxy) {
1858     soup_uri_free (src->proxy);
1859     src->proxy = NULL;
1860   }
1861   if (g_str_has_prefix (uri, "http://")) {
1862     src->proxy = soup_uri_new (uri);
1863   } else {
1864     gchar *new_uri = g_strconcat ("http://", uri, NULL);
1865
1866     src->proxy = soup_uri_new (new_uri);
1867     g_free (new_uri);
1868   }
1869
1870   return TRUE;
1871 }
1872
1873 static guint
1874 gst_soup_http_src_uri_get_type (GType type)
1875 {
1876   return GST_URI_SRC;
1877 }
1878
1879 static const gchar *const *
1880 gst_soup_http_src_uri_get_protocols (GType type)
1881 {
1882   static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
1883
1884   return protocols;
1885 }
1886
1887 static gchar *
1888 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
1889 {
1890   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
1891
1892   /* FIXME: make thread-safe */
1893   return g_strdup (src->location);
1894 }
1895
1896 static gboolean
1897 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
1898     GError ** error)
1899 {
1900   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
1901
1902   return gst_soup_http_src_set_location (src, uri, error);
1903 }
1904
1905 static void
1906 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1907 {
1908   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1909
1910   iface->get_type = gst_soup_http_src_uri_get_type;
1911   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
1912   iface->get_uri = gst_soup_http_src_uri_get_uri;
1913   iface->set_uri = gst_soup_http_src_uri_set_uri;
1914 }