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