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