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