souphttpsrc: retry request on early termination from the server
[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 GstFlowReturn gst_soup_http_src_parse_status (SoupMessage * msg,
179     GstSoupHTTPSrc * src);
180 static GstFlowReturn 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   g_cancellable_reset (src->cancellable);
451   if (src->input_stream) {
452     g_object_unref (src->input_stream);
453     src->input_stream = NULL;
454   }
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->location = NULL;
474   src->redirection_uri = NULL;
475   src->automatic_redirect = TRUE;
476   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
477   src->user_id = NULL;
478   src->user_pw = NULL;
479   src->proxy_id = NULL;
480   src->proxy_pw = NULL;
481   src->cookies = NULL;
482   src->iradio_mode = DEFAULT_IRADIO_MODE;
483   src->session = NULL;
484   src->msg = NULL;
485   src->timeout = DEFAULT_TIMEOUT;
486   src->log_level = DEFAULT_SOUP_LOG_LEVEL;
487   src->ssl_strict = DEFAULT_SSL_STRICT;
488   src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
489   src->tls_database = DEFAULT_TLS_DATABASE;
490   src->tls_interaction = DEFAULT_TLS_INTERACTION;
491   src->max_retries = DEFAULT_RETRIES;
492   src->method = DEFAULT_SOUP_METHOD;
493   src->minimum_blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
494   proxy = g_getenv ("http_proxy");
495   if (!gst_soup_http_src_set_proxy (src, proxy)) {
496     GST_WARNING_OBJECT (src,
497         "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
498         proxy);
499   }
500
501   gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
502
503   gst_soup_http_src_reset (src);
504 }
505
506 static void
507 gst_soup_http_src_dispose (GObject * gobject)
508 {
509   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
510
511   GST_DEBUG_OBJECT (src, "dispose");
512
513   gst_soup_http_src_session_close (src);
514
515   G_OBJECT_CLASS (parent_class)->dispose (gobject);
516 }
517
518 static void
519 gst_soup_http_src_finalize (GObject * gobject)
520 {
521   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
522
523   GST_DEBUG_OBJECT (src, "finalize");
524
525   g_mutex_clear (&src->mutex);
526   g_cond_clear (&src->have_headers_cond);
527   g_object_unref (src->cancellable);
528   g_free (src->location);
529   g_free (src->redirection_uri);
530   g_free (src->user_agent);
531   if (src->proxy != NULL) {
532     soup_uri_free (src->proxy);
533   }
534   g_free (src->user_id);
535   g_free (src->user_pw);
536   g_free (src->proxy_id);
537   g_free (src->proxy_pw);
538   g_strfreev (src->cookies);
539
540   if (src->extra_headers) {
541     gst_structure_free (src->extra_headers);
542     src->extra_headers = NULL;
543   }
544
545   g_free (src->ssl_ca_file);
546
547   if (src->tls_database)
548     g_object_unref (src->tls_database);
549   g_free (src->method);
550
551   if (src->tls_interaction)
552     g_object_unref (src->tls_interaction);
553
554   G_OBJECT_CLASS (parent_class)->finalize (gobject);
555 }
556
557 static void
558 gst_soup_http_src_set_property (GObject * object, guint prop_id,
559     const GValue * value, GParamSpec * pspec)
560 {
561   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
562
563   switch (prop_id) {
564     case PROP_LOCATION:
565     {
566       const gchar *location;
567
568       location = g_value_get_string (value);
569
570       if (location == NULL) {
571         GST_WARNING ("location property cannot be NULL");
572         goto done;
573       }
574       if (!gst_soup_http_src_set_location (src, location, NULL)) {
575         GST_WARNING ("badly formatted location");
576         goto done;
577       }
578       break;
579     }
580     case PROP_USER_AGENT:
581       g_free (src->user_agent);
582       src->user_agent = g_value_dup_string (value);
583       break;
584     case PROP_IRADIO_MODE:
585       src->iradio_mode = g_value_get_boolean (value);
586       break;
587     case PROP_AUTOMATIC_REDIRECT:
588       src->automatic_redirect = g_value_get_boolean (value);
589       break;
590     case PROP_PROXY:
591     {
592       const gchar *proxy;
593
594       proxy = g_value_get_string (value);
595       if (!gst_soup_http_src_set_proxy (src, proxy)) {
596         GST_WARNING ("badly formatted proxy URI");
597         goto done;
598       }
599       break;
600     }
601     case PROP_COOKIES:
602       g_strfreev (src->cookies);
603       src->cookies = g_strdupv (g_value_get_boxed (value));
604       break;
605     case PROP_IS_LIVE:
606       gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
607       break;
608     case PROP_USER_ID:
609       g_free (src->user_id);
610       src->user_id = g_value_dup_string (value);
611       break;
612     case PROP_USER_PW:
613       g_free (src->user_pw);
614       src->user_pw = g_value_dup_string (value);
615       break;
616     case PROP_PROXY_ID:
617       g_free (src->proxy_id);
618       src->proxy_id = g_value_dup_string (value);
619       break;
620     case PROP_PROXY_PW:
621       g_free (src->proxy_pw);
622       src->proxy_pw = g_value_dup_string (value);
623       break;
624     case PROP_TIMEOUT:
625       src->timeout = g_value_get_uint (value);
626       break;
627     case PROP_EXTRA_HEADERS:{
628       const GstStructure *s = gst_value_get_structure (value);
629
630       if (src->extra_headers)
631         gst_structure_free (src->extra_headers);
632
633       src->extra_headers = s ? gst_structure_copy (s) : NULL;
634       break;
635     }
636     case PROP_SOUP_LOG_LEVEL:
637       src->log_level = g_value_get_enum (value);
638       break;
639     case PROP_COMPRESS:
640       src->compress = g_value_get_boolean (value);
641       break;
642     case PROP_KEEP_ALIVE:
643       src->keep_alive = g_value_get_boolean (value);
644       break;
645     case PROP_SSL_STRICT:
646       src->ssl_strict = g_value_get_boolean (value);
647       break;
648     case PROP_SSL_CA_FILE:
649       g_free (src->ssl_ca_file);
650       src->ssl_ca_file = g_value_dup_string (value);
651       break;
652     case PROP_SSL_USE_SYSTEM_CA_FILE:
653       src->ssl_use_system_ca_file = g_value_get_boolean (value);
654       break;
655     case PROP_TLS_DATABASE:
656       g_clear_object (&src->tls_database);
657       src->tls_database = g_value_dup_object (value);
658       break;
659     case PROP_TLS_INTERACTION:
660       g_clear_object (&src->tls_interaction);
661       src->tls_interaction = g_value_dup_object (value);
662       break;
663     case PROP_RETRIES:
664       src->max_retries = g_value_get_int (value);
665       break;
666     case PROP_METHOD:
667       g_free (src->method);
668       src->method = g_value_dup_string (value);
669       break;
670     default:
671       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
672       break;
673   }
674 done:
675   return;
676 }
677
678 static void
679 gst_soup_http_src_get_property (GObject * object, guint prop_id,
680     GValue * value, GParamSpec * pspec)
681 {
682   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
683
684   switch (prop_id) {
685     case PROP_LOCATION:
686       g_value_set_string (value, src->location);
687       break;
688     case PROP_USER_AGENT:
689       g_value_set_string (value, src->user_agent);
690       break;
691     case PROP_AUTOMATIC_REDIRECT:
692       g_value_set_boolean (value, src->automatic_redirect);
693       break;
694     case PROP_PROXY:
695       if (src->proxy == NULL)
696         g_value_set_static_string (value, "");
697       else {
698         char *proxy = soup_uri_to_string (src->proxy, FALSE);
699
700         g_value_set_string (value, proxy);
701         g_free (proxy);
702       }
703       break;
704     case PROP_COOKIES:
705       g_value_set_boxed (value, g_strdupv (src->cookies));
706       break;
707     case PROP_IS_LIVE:
708       g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
709       break;
710     case PROP_IRADIO_MODE:
711       g_value_set_boolean (value, src->iradio_mode);
712       break;
713     case PROP_USER_ID:
714       g_value_set_string (value, src->user_id);
715       break;
716     case PROP_USER_PW:
717       g_value_set_string (value, src->user_pw);
718       break;
719     case PROP_PROXY_ID:
720       g_value_set_string (value, src->proxy_id);
721       break;
722     case PROP_PROXY_PW:
723       g_value_set_string (value, src->proxy_pw);
724       break;
725     case PROP_TIMEOUT:
726       g_value_set_uint (value, src->timeout);
727       break;
728     case PROP_EXTRA_HEADERS:
729       gst_value_set_structure (value, src->extra_headers);
730       break;
731     case PROP_SOUP_LOG_LEVEL:
732       g_value_set_enum (value, src->log_level);
733       break;
734     case PROP_COMPRESS:
735       g_value_set_boolean (value, src->compress);
736       break;
737     case PROP_KEEP_ALIVE:
738       g_value_set_boolean (value, src->keep_alive);
739       break;
740     case PROP_SSL_STRICT:
741       g_value_set_boolean (value, src->ssl_strict);
742       break;
743     case PROP_SSL_CA_FILE:
744       g_value_set_string (value, src->ssl_ca_file);
745       break;
746     case PROP_SSL_USE_SYSTEM_CA_FILE:
747       g_value_set_boolean (value, src->ssl_use_system_ca_file);
748       break;
749     case PROP_TLS_DATABASE:
750       g_value_set_object (value, src->tls_database);
751       break;
752     case PROP_TLS_INTERACTION:
753       g_value_set_object (value, src->tls_interaction);
754       break;
755     case PROP_RETRIES:
756       g_value_set_int (value, src->max_retries);
757       break;
758     case PROP_METHOD:
759       g_value_set_string (value, src->method);
760       break;
761     default:
762       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
763       break;
764   }
765 }
766
767 static gchar *
768 gst_soup_http_src_unicodify (const gchar * str)
769 {
770   const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
771     "GST_TAG_ENCODING", NULL
772   };
773
774   return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
775 }
776
777 static void
778 gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src)
779 {
780   g_cancellable_cancel (src->cancellable);
781   g_cond_signal (&src->have_headers_cond);
782 }
783
784 static gboolean
785 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
786     guint64 stop_offset)
787 {
788   gchar buf[64];
789   gint rc;
790
791   soup_message_headers_remove (src->msg->request_headers, "Range");
792   if (offset || stop_offset != -1) {
793     if (stop_offset != -1) {
794       g_assert (offset != stop_offset);
795
796       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
797           G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 :
798           stop_offset);
799     } else {
800       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
801           offset);
802     }
803     if (rc > sizeof (buf) || rc < 0)
804       return FALSE;
805     soup_message_headers_append (src->msg->request_headers, "Range", buf);
806   }
807   src->read_position = offset;
808   return TRUE;
809 }
810
811 static gboolean
812 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
813 {
814   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
815   const gchar *field_name = g_quark_to_string (field_id);
816   gchar *field_content = NULL;
817
818   if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
819     field_content = g_value_dup_string (value);
820   } else {
821     GValue dest = { 0, };
822
823     g_value_init (&dest, G_TYPE_STRING);
824     if (g_value_transform (value, &dest)) {
825       field_content = g_value_dup_string (&dest);
826     }
827   }
828
829   if (field_content == NULL) {
830     GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
831         "or can't be converted to a string", field_name);
832     return FALSE;
833   }
834
835   GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
836       field_content);
837   soup_message_headers_append (src->msg->request_headers, field_name,
838       field_content);
839
840   g_free (field_content);
841
842   return TRUE;
843 }
844
845 static gboolean
846 _append_extra_headers (GQuark field_id, const GValue * value,
847     gpointer user_data)
848 {
849   if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
850     guint n = gst_value_array_get_size (value);
851     guint i;
852
853     for (i = 0; i < n; i++) {
854       const GValue *v = gst_value_array_get_value (value, i);
855
856       if (!_append_extra_header (field_id, v, user_data))
857         return FALSE;
858     }
859   } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
860     guint n = gst_value_list_get_size (value);
861     guint i;
862
863     for (i = 0; i < n; i++) {
864       const GValue *v = gst_value_list_get_value (value, i);
865
866       if (!_append_extra_header (field_id, v, user_data))
867         return FALSE;
868     }
869   } else {
870     return _append_extra_header (field_id, value, user_data);
871   }
872
873   return TRUE;
874 }
875
876
877 static gboolean
878 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
879 {
880   if (!src->extra_headers)
881     return TRUE;
882
883   return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
884 }
885
886 static gboolean
887 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
888 {
889   if (src->session) {
890     GST_DEBUG_OBJECT (src, "Session is already open");
891     return TRUE;
892   }
893
894   if (!src->location) {
895     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
896         ("Missing location property"));
897     return FALSE;
898   }
899
900   if (!src->session) {
901     GST_DEBUG_OBJECT (src, "Creating session");
902     if (src->proxy == NULL) {
903       src->session =
904           soup_session_new_with_options (SOUP_SESSION_USER_AGENT,
905           src->user_agent, SOUP_SESSION_TIMEOUT, src->timeout,
906           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
907           SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
908     } else {
909       src->session =
910           soup_session_new_with_options (SOUP_SESSION_PROXY_URI, src->proxy,
911           SOUP_SESSION_TIMEOUT, src->timeout,
912           SOUP_SESSION_SSL_STRICT, src->ssl_strict,
913           SOUP_SESSION_USER_AGENT, src->user_agent,
914           SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
915     }
916
917     if (!src->session) {
918       GST_ELEMENT_ERROR (src, LIBRARY, INIT,
919           (NULL), ("Failed to create async session"));
920       return FALSE;
921     }
922
923     g_signal_connect (src->session, "authenticate",
924         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
925
926     /* Set up logging */
927     gst_soup_util_log_setup (src->session, src->log_level, GST_ELEMENT (src));
928     if (src->tls_database)
929       g_object_set (src->session, "tls-database", src->tls_database, NULL);
930     else if (src->ssl_ca_file)
931       g_object_set (src->session, "ssl-ca-file", src->ssl_ca_file, NULL);
932     else
933       g_object_set (src->session, "ssl-use-system-ca-file",
934           src->ssl_use_system_ca_file, NULL);
935   } else {
936     GST_DEBUG_OBJECT (src, "Re-using session");
937   }
938
939   if (src->compress)
940     soup_session_add_feature_by_type (src->session, SOUP_TYPE_CONTENT_DECODER);
941   else
942     soup_session_remove_feature_by_type (src->session,
943         SOUP_TYPE_CONTENT_DECODER);
944
945   return TRUE;
946 }
947
948 static void
949 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
950 {
951   GST_DEBUG_OBJECT (src, "Closing session");
952
953   g_mutex_lock (&src->mutex);
954   if (src->msg) {
955     soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_CANCELLED);
956     g_object_unref (src->msg);
957     src->msg = NULL;
958   }
959
960   if (src->session) {
961     soup_session_abort (src->session);
962     g_object_unref (src->session);
963     src->session = NULL;
964   }
965   g_mutex_unlock (&src->mutex);
966 }
967
968 static void
969 gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg,
970     SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src)
971 {
972   if (!retrying) {
973     /* First time authentication only, if we fail and are called again with retry true fall through */
974     if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
975       if (src->user_id && src->user_pw)
976         soup_auth_authenticate (auth, src->user_id, src->user_pw);
977     } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
978       if (src->proxy_id && src->proxy_pw)
979         soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
980     }
981   }
982 }
983
984 static void
985 insert_http_header (const gchar * name, const gchar * value, gpointer user_data)
986 {
987   GstStructure *headers = user_data;
988   const GValue *gv;
989
990   if (!g_utf8_validate (name, -1, NULL) || !g_utf8_validate (value, -1, NULL))
991     return;
992
993   gv = gst_structure_get_value (headers, name);
994   if (gv && GST_VALUE_HOLDS_ARRAY (gv)) {
995     GValue v = G_VALUE_INIT;
996
997     g_value_init (&v, G_TYPE_STRING);
998     g_value_set_string (&v, value);
999     gst_value_array_append_value ((GValue *) gv, &v);
1000     g_value_unset (&v);
1001   } else if (gv && G_VALUE_HOLDS_STRING (gv)) {
1002     GValue arr = G_VALUE_INIT;
1003     GValue v = G_VALUE_INIT;
1004     const gchar *old_value = g_value_get_string (gv);
1005
1006     g_value_init (&arr, GST_TYPE_ARRAY);
1007     g_value_init (&v, G_TYPE_STRING);
1008     g_value_set_string (&v, old_value);
1009     gst_value_array_append_value (&arr, &v);
1010     g_value_set_string (&v, value);
1011     gst_value_array_append_value (&arr, &v);
1012
1013     gst_structure_set_value (headers, name, &arr);
1014     g_value_unset (&v);
1015     g_value_unset (&arr);
1016   } else {
1017     gst_structure_set (headers, name, G_TYPE_STRING, value, NULL);
1018   }
1019 }
1020
1021 static GstFlowReturn
1022 gst_soup_http_src_got_headers (GstSoupHTTPSrc * src, SoupMessage * msg)
1023 {
1024   const char *value;
1025   GstTagList *tag_list;
1026   GstBaseSrc *basesrc;
1027   guint64 newsize;
1028   GHashTable *params = NULL;
1029   GstEvent *http_headers_event;
1030   GstStructure *http_headers, *headers;
1031   const gchar *accept_ranges;
1032
1033   GST_INFO_OBJECT (src, "got headers");
1034
1035   if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
1036       src->proxy_id && src->proxy_pw) {
1037     /* wait for authenticate callback */
1038     return GST_FLOW_OK;
1039   }
1040
1041   if (src->automatic_redirect &&
1042       soup_session_would_redirect (src->session, msg) &&
1043       soup_session_redirect_message (src->session, msg)) {
1044     src->redirection_uri =
1045         soup_uri_to_string (soup_message_get_uri (msg), FALSE);
1046     src->redirection_permanent =
1047         (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY);
1048     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)",
1049         msg->status_code, src->redirection_uri, src->redirection_permanent);
1050
1051     /* force a retry with the updated message */
1052     return GST_FLOW_CUSTOM_ERROR;
1053   }
1054
1055   if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
1056     /* force an error */
1057     return gst_soup_http_src_parse_status (msg, src);
1058   }
1059
1060   src->got_headers = TRUE;
1061   g_cond_broadcast (&src->have_headers_cond);
1062
1063   http_headers = gst_structure_new_empty ("http-headers");
1064   gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location, NULL);
1065   if (src->redirection_uri)
1066     gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING,
1067         src->redirection_uri, NULL);
1068   headers = gst_structure_new_empty ("request-headers");
1069   soup_message_headers_foreach (msg->request_headers, insert_http_header,
1070       headers);
1071   gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
1072       headers, NULL);
1073   gst_structure_free (headers);
1074   headers = gst_structure_new_empty ("response-headers");
1075   soup_message_headers_foreach (msg->response_headers, insert_http_header,
1076       headers);
1077   gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
1078       headers, NULL);
1079   gst_structure_free (headers);
1080
1081   http_headers_event =
1082       gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
1083   gst_event_replace (&src->http_headers_event, http_headers_event);
1084   gst_event_unref (http_headers_event);
1085
1086   /* Parse Content-Length. */
1087   if (soup_message_headers_get_encoding (msg->response_headers) ==
1088       SOUP_ENCODING_CONTENT_LENGTH) {
1089     newsize = src->request_position +
1090         soup_message_headers_get_content_length (msg->response_headers);
1091     if (!src->have_size || (src->content_size != newsize)) {
1092       src->content_size = newsize;
1093       src->have_size = TRUE;
1094       src->seekable = TRUE;
1095       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
1096
1097       basesrc = GST_BASE_SRC_CAST (src);
1098       basesrc->segment.duration = src->content_size;
1099       gst_element_post_message (GST_ELEMENT (src),
1100           gst_message_new_duration_changed (GST_OBJECT (src)));
1101     }
1102   }
1103
1104   /* If the server reports Accept-Ranges: none we don't have to try
1105    * doing range requests at all
1106    */
1107   if ((accept_ranges =
1108           soup_message_headers_get_one (msg->response_headers,
1109               "Accept-Ranges"))) {
1110     if (g_ascii_strcasecmp (accept_ranges, "none") == 0)
1111       src->seekable = FALSE;
1112   }
1113
1114   /* Icecast stuff */
1115   tag_list = gst_tag_list_new_empty ();
1116
1117   if ((value =
1118           soup_message_headers_get_one (msg->response_headers,
1119               "icy-metaint")) != NULL) {
1120     gint icy_metaint;
1121
1122     if (g_utf8_validate (value, -1, NULL)) {
1123       icy_metaint = atoi (value);
1124
1125       GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value,
1126           icy_metaint);
1127       if (icy_metaint > 0) {
1128         if (src->src_caps)
1129           gst_caps_unref (src->src_caps);
1130
1131         src->src_caps = gst_caps_new_simple ("application/x-icy",
1132             "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1133
1134         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1135       }
1136     }
1137   }
1138   if ((value =
1139           soup_message_headers_get_content_type (msg->response_headers,
1140               &params)) != NULL) {
1141     if (!g_utf8_validate (value, -1, NULL)) {
1142       GST_WARNING_OBJECT (src, "Content-Type is invalid UTF-8");
1143     } else if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1144       gint channels = 2;
1145       gint rate = 44100;
1146       char *param;
1147
1148       GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1149
1150       if (src->src_caps) {
1151         gst_caps_unref (src->src_caps);
1152         src->src_caps = NULL;
1153       }
1154
1155       param = g_hash_table_lookup (params, "channels");
1156       if (param != NULL) {
1157         guint64 val = g_ascii_strtoull (param, NULL, 10);
1158         if (val < 64)
1159           channels = val;
1160         else
1161           channels = 0;
1162       }
1163
1164       param = g_hash_table_lookup (params, "rate");
1165       if (param != NULL) {
1166         guint64 val = g_ascii_strtoull (param, NULL, 10);
1167         if (val < G_MAXINT)
1168           rate = val;
1169         else
1170           rate = 0;
1171       }
1172
1173       if (rate > 0 && channels > 0) {
1174         src->src_caps = gst_caps_new_simple ("audio/x-unaligned-raw",
1175             "format", G_TYPE_STRING, "S16BE",
1176             "layout", G_TYPE_STRING, "interleaved",
1177             "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1178
1179         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1180       }
1181     } else {
1182       GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1183
1184       /* Set the Content-Type field on the caps */
1185       if (src->src_caps) {
1186         src->src_caps = gst_caps_make_writable (src->src_caps);
1187         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1188             value, NULL);
1189         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1190       }
1191     }
1192   }
1193
1194   if (params != NULL)
1195     g_hash_table_destroy (params);
1196
1197   if ((value =
1198           soup_message_headers_get_one (msg->response_headers,
1199               "icy-name")) != NULL) {
1200     if (g_utf8_validate (value, -1, NULL)) {
1201       g_free (src->iradio_name);
1202       src->iradio_name = gst_soup_http_src_unicodify (value);
1203       if (src->iradio_name) {
1204         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1205             src->iradio_name, NULL);
1206       }
1207     }
1208   }
1209   if ((value =
1210           soup_message_headers_get_one (msg->response_headers,
1211               "icy-genre")) != NULL) {
1212     if (g_utf8_validate (value, -1, NULL)) {
1213       g_free (src->iradio_genre);
1214       src->iradio_genre = gst_soup_http_src_unicodify (value);
1215       if (src->iradio_genre) {
1216         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1217             src->iradio_genre, NULL);
1218       }
1219     }
1220   }
1221   if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url"))
1222       != NULL) {
1223     if (g_utf8_validate (value, -1, NULL)) {
1224       g_free (src->iradio_url);
1225       src->iradio_url = gst_soup_http_src_unicodify (value);
1226       if (src->iradio_url) {
1227         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1228             src->iradio_url, NULL);
1229       }
1230     }
1231   }
1232   if (!gst_tag_list_is_empty (tag_list)) {
1233     GST_DEBUG_OBJECT (src,
1234         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1235     gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1236   } else {
1237     gst_tag_list_unref (tag_list);
1238   }
1239
1240   /* Handle HTTP errors. */
1241   return gst_soup_http_src_parse_status (msg, src);
1242 }
1243
1244 static GstBuffer *
1245 gst_soup_http_src_alloc_buffer (GstSoupHTTPSrc * src)
1246 {
1247   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1248   GstFlowReturn rc;
1249   GstBuffer *gstbuf;
1250
1251   rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1,
1252       basesrc->blocksize, &gstbuf);
1253   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1254     return NULL;
1255   }
1256
1257   return gstbuf;
1258 }
1259
1260 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1261   do { \
1262     GST_ELEMENT_ERROR_WITH_DETAILS ((src), cat, code, ("%s", error_message), \
1263         ("%s (%d), URL: %s, Redirect to: %s", (soup_msg)->reason_phrase, \
1264             (soup_msg)->status_code, (src)->location, GST_STR_NULL ((src)->redirection_uri)), \
1265             ("http-status-code", G_TYPE_UINT, msg->status_code, \
1266              "http-redirect-uri", G_TYPE_STRING, GST_STR_NULL ((src)->redirection_uri), NULL)); \
1267   } while(0)
1268
1269 static GstFlowReturn
1270 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1271 {
1272   if (msg->method == SOUP_METHOD_HEAD) {
1273     if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
1274       GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1275           msg->status_code);
1276     return GST_FLOW_OK;
1277   }
1278
1279   if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
1280     switch (msg->status_code) {
1281       case SOUP_STATUS_CANT_RESOLVE:
1282       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1283         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1284             _("Could not resolve server name."));
1285         return GST_FLOW_ERROR;
1286       case SOUP_STATUS_CANT_CONNECT:
1287       case SOUP_STATUS_CANT_CONNECT_PROXY:
1288         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1289             _("Could not establish connection to server."));
1290         return GST_FLOW_ERROR;
1291       case SOUP_STATUS_SSL_FAILED:
1292         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1293             _("Secure connection setup failed."));
1294         return GST_FLOW_ERROR;
1295       case SOUP_STATUS_IO_ERROR:
1296         if (src->max_retries == -1 || src->retry_count < src->max_retries)
1297           return GST_FLOW_CUSTOM_ERROR;
1298         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1299             _("A network error occurred, or the server closed the connection "
1300                 "unexpectedly."));
1301         return GST_FLOW_ERROR;
1302       case SOUP_STATUS_MALFORMED:
1303         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1304             _("Server sent bad data."));
1305         return GST_FLOW_ERROR;
1306       case SOUP_STATUS_CANCELLED:
1307         /* No error message when interrupted by program. */
1308         break;
1309     }
1310     return GST_FLOW_OK;
1311   }
1312
1313   if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) ||
1314       SOUP_STATUS_IS_REDIRECTION (msg->status_code) ||
1315       SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) {
1316     const gchar *reason_phrase;
1317
1318     reason_phrase = msg->reason_phrase;
1319     if (reason_phrase && !g_utf8_validate (reason_phrase, -1, NULL)) {
1320       GST_ERROR_OBJECT (src, "Invalid UTF-8 in reason");
1321       reason_phrase = "(invalid)";
1322     }
1323
1324     /* Report HTTP error. */
1325
1326     /* when content_size is unknown and we have just finished receiving
1327      * a body message, requests that go beyond the content limits will result
1328      * in an error. Here we convert those to EOS */
1329     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1330         src->have_body && !src->have_size) {
1331       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1332           "body, returning EOS");
1333       return GST_FLOW_EOS;
1334     }
1335
1336     /* FIXME: reason_phrase is not translated and not suitable for user
1337      * error dialog according to libsoup documentation.
1338      */
1339     if (msg->status_code == SOUP_STATUS_NOT_FOUND) {
1340       GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, NOT_FOUND,
1341           ("%s", reason_phrase),
1342           ("%s (%d), URL: %s, Redirect to: %s", reason_phrase,
1343               msg->status_code, src->location,
1344               GST_STR_NULL (src->redirection_uri)),
1345           ("http-status-code", G_TYPE_UINT, msg->status_code,
1346               "http-redirect-uri", G_TYPE_STRING,
1347               GST_STR_NULL (src->redirection_uri), NULL));
1348     } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED
1349         || msg->status_code == SOUP_STATUS_PAYMENT_REQUIRED
1350         || msg->status_code == SOUP_STATUS_FORBIDDEN
1351         || msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1352       GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, NOT_AUTHORIZED, ("%s",
1353               reason_phrase), ("%s (%d), URL: %s, Redirect to: %s",
1354               reason_phrase, msg->status_code, src->location,
1355               GST_STR_NULL (src->redirection_uri)), ("http-status-code",
1356               G_TYPE_UINT, msg->status_code, "http-redirect-uri", G_TYPE_STRING,
1357               GST_STR_NULL (src->redirection_uri), NULL));
1358     } else {
1359       GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, OPEN_READ,
1360           ("%s", reason_phrase),
1361           ("%s (%d), URL: %s, Redirect to: %s", reason_phrase,
1362               msg->status_code, src->location,
1363               GST_STR_NULL (src->redirection_uri)),
1364           ("http-status-code", G_TYPE_UINT, msg->status_code,
1365               "http-redirect-uri", G_TYPE_STRING,
1366               GST_STR_NULL (src->redirection_uri), NULL));
1367     }
1368     return GST_FLOW_ERROR;
1369   }
1370
1371   return GST_FLOW_OK;
1372 }
1373
1374 static gboolean
1375 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1376 {
1377   g_return_val_if_fail (src->msg == NULL, FALSE);
1378
1379   src->msg = soup_message_new (method, src->location);
1380   if (!src->msg) {
1381     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1382         ("Error parsing URL."), ("URL: %s", src->location));
1383     return FALSE;
1384   }
1385   if (!src->keep_alive) {
1386     soup_message_headers_append (src->msg->request_headers, "Connection",
1387         "close");
1388   }
1389   if (src->iradio_mode) {
1390     soup_message_headers_append (src->msg->request_headers, "icy-metadata",
1391         "1");
1392   }
1393   if (src->cookies) {
1394     gchar **cookie;
1395
1396     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1397       soup_message_headers_append (src->msg->request_headers, "Cookie",
1398           *cookie);
1399     }
1400   }
1401
1402   soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS |
1403       SOUP_MESSAGE_NO_REDIRECT);
1404   gst_soup_http_src_add_range_header (src, src->request_position,
1405       src->stop_position);
1406
1407   gst_soup_http_src_add_extra_headers (src);
1408
1409   return TRUE;
1410 }
1411
1412 static GstFlowReturn
1413 gst_soup_http_src_send_message (GstSoupHTTPSrc * src)
1414 {
1415   GstFlowReturn ret;
1416   GError *error = NULL;
1417
1418   g_return_val_if_fail (src->msg != NULL, GST_FLOW_ERROR);
1419
1420   src->input_stream =
1421       soup_session_send (src->session, src->msg, src->cancellable, &error);
1422
1423   if (g_cancellable_is_cancelled (src->cancellable)) {
1424     ret = GST_FLOW_FLUSHING;
1425     goto done;
1426   }
1427
1428   ret = gst_soup_http_src_got_headers (src, src->msg);
1429   if (ret != GST_FLOW_OK) {
1430     goto done;
1431   }
1432
1433   if (!src->input_stream) {
1434     GST_DEBUG_OBJECT (src, "Didn't get an input stream: %s", error->message);
1435     ret = GST_FLOW_ERROR;
1436     goto done;
1437   }
1438
1439   if (SOUP_STATUS_IS_SUCCESSFUL (src->msg->status_code)) {
1440     GST_DEBUG_OBJECT (src, "Successfully got a reply");
1441   } else {
1442     /* FIXME - be more helpful to people debugging */
1443     ret = GST_FLOW_ERROR;
1444   }
1445
1446 done:
1447   if (error)
1448     g_error_free (error);
1449   return ret;
1450 }
1451
1452 static GstFlowReturn
1453 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method)
1454 {
1455   GstFlowReturn ret;
1456
1457   if (src->max_retries != -1 && src->retry_count > src->max_retries) {
1458     GST_DEBUG_OBJECT (src, "Max retries reached");
1459     return GST_FLOW_ERROR;
1460   }
1461
1462   src->retry_count++;
1463   /* EOS immediately if we have an empty segment */
1464   if (src->request_position == src->stop_position)
1465     return GST_FLOW_EOS;
1466
1467   GST_LOG_OBJECT (src, "Running request for method: %s", method);
1468
1469   /* Update the position if we are retrying */
1470   if (src->msg && src->request_position > 0) {
1471     gst_soup_http_src_add_range_header (src, src->request_position,
1472         src->stop_position);
1473   }
1474
1475   if (!src->msg) {
1476     if (!gst_soup_http_src_build_message (src, method)) {
1477       return GST_FLOW_ERROR;
1478     }
1479   }
1480
1481   if (g_cancellable_is_cancelled (src->cancellable)) {
1482     GST_INFO_OBJECT (src, "interrupted");
1483     return GST_FLOW_FLUSHING;
1484   }
1485
1486   ret = gst_soup_http_src_send_message (src);
1487
1488   /* Check if Range header was respected. */
1489   if (ret == GST_FLOW_OK && src->request_position > 0 &&
1490       src->msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) {
1491     src->seekable = FALSE;
1492     GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, SEEK,
1493         (_("Server does not support seeking.")),
1494         ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s",
1495             src->location, GST_STR_NULL (src->redirection_uri)),
1496         ("http-status-code", G_TYPE_UINT, src->msg->status_code,
1497             "http-redirection-uri", G_TYPE_STRING,
1498             GST_STR_NULL (src->redirection_uri), NULL));
1499     ret = GST_FLOW_ERROR;
1500   }
1501
1502   return ret;
1503 }
1504
1505 /*
1506  * Check if the bytes_read is above a certain threshold of the blocksize, if
1507  * that happens a few times in a row, increase the blocksize; Do the same in
1508  * the opposite direction to reduce the blocksize.
1509  */
1510 static void
1511 gst_soup_http_src_check_update_blocksize (GstSoupHTTPSrc * src,
1512     gint64 bytes_read)
1513 {
1514   guint blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
1515
1516   GST_LOG_OBJECT (src, "Checking to update blocksize. Read:%" G_GINT64_FORMAT
1517       " blocksize:%u", bytes_read, blocksize);
1518
1519   if (bytes_read >= blocksize * GROW_BLOCKSIZE_LIMIT) {
1520     src->reduce_blocksize_count = 0;
1521     src->increase_blocksize_count++;
1522
1523     if (src->increase_blocksize_count >= GROW_BLOCKSIZE_COUNT) {
1524       blocksize *= GROW_BLOCKSIZE_FACTOR;
1525       GST_DEBUG_OBJECT (src, "Increased blocksize to %u", blocksize);
1526       gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
1527       src->increase_blocksize_count = 0;
1528     }
1529   } else if (bytes_read < blocksize * REDUCE_BLOCKSIZE_LIMIT) {
1530     src->reduce_blocksize_count++;
1531     src->increase_blocksize_count = 0;
1532
1533     if (src->reduce_blocksize_count >= REDUCE_BLOCKSIZE_COUNT) {
1534       blocksize *= REDUCE_BLOCKSIZE_FACTOR;
1535       blocksize = MAX (blocksize, src->minimum_blocksize);
1536       GST_DEBUG_OBJECT (src, "Decreased blocksize to %u", blocksize);
1537       gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
1538       src->reduce_blocksize_count = 0;
1539     }
1540   } else {
1541     src->reduce_blocksize_count = src->increase_blocksize_count = 0;
1542   }
1543 }
1544
1545 static void
1546 gst_soup_http_src_update_position (GstSoupHTTPSrc * src, gint64 bytes_read)
1547 {
1548   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1549   guint64 new_position;
1550
1551   new_position = src->read_position + bytes_read;
1552   if (G_LIKELY (src->request_position == src->read_position))
1553     src->request_position = new_position;
1554   src->read_position = new_position;
1555
1556   if (src->have_size) {
1557     if (new_position > src->content_size) {
1558       GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
1559           "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
1560           src->content_size);
1561       src->content_size = new_position;
1562       basesrc->segment.duration = src->content_size;
1563       gst_element_post_message (GST_ELEMENT (src),
1564           gst_message_new_duration_changed (GST_OBJECT (src)));
1565     } else if (new_position == src->content_size) {
1566       GST_DEBUG_OBJECT (src, "We're EOS now");
1567     }
1568   }
1569 }
1570
1571 static GstFlowReturn
1572 gst_soup_http_src_read_buffer (GstSoupHTTPSrc * src, GstBuffer ** outbuf)
1573 {
1574   gssize read_bytes;
1575   GstMapInfo mapinfo;
1576   GstBaseSrc *bsrc;
1577   GstFlowReturn ret;
1578
1579   bsrc = GST_BASE_SRC_CAST (src);
1580
1581   *outbuf = gst_soup_http_src_alloc_buffer (src);
1582   if (!*outbuf) {
1583     GST_WARNING_OBJECT (src, "Failed to allocate buffer");
1584     return GST_FLOW_ERROR;
1585   }
1586
1587   if (!gst_buffer_map (*outbuf, &mapinfo, GST_MAP_WRITE)) {
1588     GST_WARNING_OBJECT (src, "Failed to map buffer");
1589     return GST_FLOW_ERROR;
1590   }
1591
1592   read_bytes =
1593       g_input_stream_read (src->input_stream, mapinfo.data, mapinfo.size,
1594       src->cancellable, NULL);
1595   GST_DEBUG_OBJECT (src, "Read %" G_GSSIZE_FORMAT " bytes from http input",
1596       read_bytes);
1597
1598   g_mutex_lock (&src->mutex);
1599   if (g_cancellable_is_cancelled (src->cancellable)) {
1600     gst_buffer_unmap (*outbuf, &mapinfo);
1601     gst_buffer_unref (*outbuf);
1602     g_mutex_unlock (&src->mutex);
1603     return GST_FLOW_FLUSHING;
1604   }
1605
1606   gst_buffer_unmap (*outbuf, &mapinfo);
1607   if (read_bytes > 0) {
1608     gst_buffer_set_size (*outbuf, read_bytes);
1609     GST_BUFFER_OFFSET (*outbuf) = bsrc->segment.position;
1610     ret = GST_FLOW_OK;
1611     gst_soup_http_src_update_position (src, read_bytes);
1612
1613     /* Got some data, reset retry counter */
1614     src->retry_count = 0;
1615
1616     gst_soup_http_src_check_update_blocksize (src, read_bytes);
1617
1618     /* If we're at the end of a range request, read again to let libsoup
1619      * finalize the request. This allows to reuse the connection again later,
1620      * otherwise we would have to cancel the message and close the connection
1621      */
1622     if (bsrc->segment.stop != -1
1623         && bsrc->segment.position + read_bytes >= bsrc->segment.stop) {
1624       guint8 tmp[128];
1625
1626       g_object_unref (src->msg);
1627       src->msg = NULL;
1628       src->have_body = TRUE;
1629
1630       /* This should return immediately as we're at the end of the range */
1631       read_bytes =
1632           g_input_stream_read (src->input_stream, tmp, sizeof (tmp),
1633           src->cancellable, NULL);
1634       if (read_bytes > 0)
1635         GST_ERROR_OBJECT (src,
1636             "Read %" G_GSIZE_FORMAT " bytes after end of range", read_bytes);
1637     }
1638   } else {
1639     gst_buffer_unref (*outbuf);
1640     if (read_bytes < 0 ||
1641         (src->have_size && src->read_position < src->content_size)) {
1642       /* Maybe the server disconnected, retry */
1643       ret = GST_FLOW_CUSTOM_ERROR;
1644     } else {
1645       g_object_unref (src->msg);
1646       src->msg = NULL;
1647       ret = GST_FLOW_EOS;
1648       src->have_body = TRUE;
1649     }
1650   }
1651   g_mutex_unlock (&src->mutex);
1652
1653   return ret;
1654 }
1655
1656 static GstFlowReturn
1657 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
1658 {
1659   GstSoupHTTPSrc *src;
1660   GstFlowReturn ret = GST_FLOW_OK;
1661   GstEvent *http_headers_event = NULL;
1662
1663   src = GST_SOUP_HTTP_SRC (psrc);
1664
1665 retry:
1666   g_mutex_lock (&src->mutex);
1667
1668   /* Check for pending position change */
1669   if (src->request_position != src->read_position) {
1670     if (src->input_stream) {
1671       g_input_stream_close (src->input_stream, src->cancellable, NULL);
1672       g_object_unref (src->input_stream);
1673       src->input_stream = NULL;
1674     }
1675   }
1676
1677   if (g_cancellable_is_cancelled (src->cancellable)) {
1678     ret = GST_FLOW_FLUSHING;
1679     g_mutex_unlock (&src->mutex);
1680     goto done;
1681   }
1682
1683   /* If we have no open connection to the server, start one */
1684   if (!src->input_stream) {
1685     *outbuf = NULL;
1686     ret =
1687         gst_soup_http_src_do_request (src,
1688         src->method ? src->method : SOUP_METHOD_GET);
1689     http_headers_event = src->http_headers_event;
1690     src->http_headers_event = NULL;
1691   }
1692   g_mutex_unlock (&src->mutex);
1693
1694   if (ret == GST_FLOW_OK || ret == GST_FLOW_CUSTOM_ERROR) {
1695     if (http_headers_event) {
1696       gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event);
1697       http_headers_event = NULL;
1698     }
1699   }
1700
1701   if (ret == GST_FLOW_OK)
1702     ret = gst_soup_http_src_read_buffer (src, outbuf);
1703
1704 done:
1705   GST_DEBUG_OBJECT (src, "Returning %d %s", ret, gst_flow_get_name (ret));
1706   if (ret != GST_FLOW_OK) {
1707     if (http_headers_event)
1708       gst_event_unref (http_headers_event);
1709
1710     g_mutex_lock (&src->mutex);
1711     if (src->input_stream) {
1712       g_object_unref (src->input_stream);
1713       src->input_stream = NULL;
1714     }
1715     g_mutex_unlock (&src->mutex);
1716     if (ret == GST_FLOW_CUSTOM_ERROR) {
1717       ret = GST_FLOW_OK;
1718       goto retry;
1719     }
1720   }
1721   return ret;
1722 }
1723
1724 static gboolean
1725 gst_soup_http_src_start (GstBaseSrc * bsrc)
1726 {
1727   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1728
1729   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
1730
1731   return gst_soup_http_src_session_open (src);
1732 }
1733
1734 static gboolean
1735 gst_soup_http_src_stop (GstBaseSrc * bsrc)
1736 {
1737   GstSoupHTTPSrc *src;
1738
1739   src = GST_SOUP_HTTP_SRC (bsrc);
1740   GST_DEBUG_OBJECT (src, "stop()");
1741   if (src->keep_alive && !src->msg)
1742     gst_soup_http_src_cancel_message (src);
1743   else
1744     gst_soup_http_src_session_close (src);
1745
1746   gst_soup_http_src_reset (src);
1747   return TRUE;
1748 }
1749
1750 static GstStateChangeReturn
1751 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
1752 {
1753   GstStateChangeReturn ret;
1754   GstSoupHTTPSrc *src;
1755
1756   src = GST_SOUP_HTTP_SRC (element);
1757
1758   switch (transition) {
1759     case GST_STATE_CHANGE_READY_TO_NULL:
1760       gst_soup_http_src_session_close (src);
1761       break;
1762     default:
1763       break;
1764   }
1765
1766   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1767
1768   return ret;
1769 }
1770
1771 /* Interrupt a blocking request. */
1772 static gboolean
1773 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
1774 {
1775   GstSoupHTTPSrc *src;
1776
1777   src = GST_SOUP_HTTP_SRC (bsrc);
1778   GST_DEBUG_OBJECT (src, "unlock()");
1779
1780   gst_soup_http_src_cancel_message (src);
1781   return TRUE;
1782 }
1783
1784 /* Interrupt interrupt. */
1785 static gboolean
1786 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
1787 {
1788   GstSoupHTTPSrc *src;
1789
1790   src = GST_SOUP_HTTP_SRC (bsrc);
1791   GST_DEBUG_OBJECT (src, "unlock_stop()");
1792
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     g_mutex_unlock (&src->mutex);
1837   }
1838 }
1839
1840 static gboolean
1841 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
1842 {
1843   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1844
1845   gst_soup_http_src_check_seekable (src);
1846
1847   return src->seekable;
1848 }
1849
1850 static gboolean
1851 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
1852 {
1853   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1854
1855   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
1856       ")", segment->start, segment->stop);
1857   if (src->read_position == segment->start &&
1858       src->request_position == src->read_position &&
1859       src->stop_position == segment->stop) {
1860     GST_DEBUG_OBJECT (src,
1861         "Seek to current read/end position and no seek pending");
1862     return TRUE;
1863   }
1864
1865   gst_soup_http_src_check_seekable (src);
1866
1867   /* If we have no headers we don't know yet if it is seekable or not.
1868    * Store the start position and error out later if it isn't */
1869   if (src->got_headers && !src->seekable) {
1870     GST_WARNING_OBJECT (src, "Not seekable");
1871     return FALSE;
1872   }
1873
1874   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
1875     GST_WARNING_OBJECT (src, "Invalid seek segment");
1876     return FALSE;
1877   }
1878
1879   if (src->have_size && segment->start >= src->content_size) {
1880     GST_WARNING_OBJECT (src,
1881         "Potentially seeking behind end of file, might EOS immediately");
1882   }
1883
1884   /* Wait for create() to handle the jump in offset. */
1885   src->request_position = segment->start;
1886   src->stop_position = segment->stop;
1887
1888   return TRUE;
1889 }
1890
1891 static gboolean
1892 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
1893 {
1894   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1895   gboolean ret;
1896   GstSchedulingFlags flags;
1897   gint minsize, maxsize, align;
1898
1899   switch (GST_QUERY_TYPE (query)) {
1900     case GST_QUERY_URI:
1901       gst_query_set_uri (query, src->location);
1902       if (src->redirection_uri != NULL) {
1903         gst_query_set_uri_redirection (query, src->redirection_uri);
1904         gst_query_set_uri_redirection_permanent (query,
1905             src->redirection_permanent);
1906       }
1907       ret = TRUE;
1908       break;
1909     default:
1910       ret = FALSE;
1911       break;
1912   }
1913
1914   if (!ret)
1915     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
1916
1917   switch (GST_QUERY_TYPE (query)) {
1918     case GST_QUERY_SCHEDULING:
1919       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
1920       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
1921       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
1922       break;
1923     default:
1924       break;
1925   }
1926
1927   return ret;
1928 }
1929
1930 static gboolean
1931 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
1932     GError ** error)
1933 {
1934   const char *alt_schemes[] = { "icy://", "icyx://" };
1935   guint i;
1936
1937   if (src->location) {
1938     g_free (src->location);
1939     src->location = NULL;
1940   }
1941
1942   if (uri == NULL)
1943     return FALSE;
1944
1945   for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
1946     if (g_str_has_prefix (uri, alt_schemes[i])) {
1947       src->location =
1948           g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
1949       return TRUE;
1950     }
1951   }
1952
1953   if (src->redirection_uri) {
1954     g_free (src->redirection_uri);
1955     src->redirection_uri = NULL;
1956   }
1957
1958   src->location = g_strdup (uri);
1959
1960   return TRUE;
1961 }
1962
1963 static gboolean
1964 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
1965 {
1966   if (src->proxy) {
1967     soup_uri_free (src->proxy);
1968     src->proxy = NULL;
1969   }
1970
1971   if (uri == NULL || *uri == '\0')
1972     return TRUE;
1973
1974   if (g_str_has_prefix (uri, "http://")) {
1975     src->proxy = soup_uri_new (uri);
1976   } else {
1977     gchar *new_uri = g_strconcat ("http://", uri, NULL);
1978
1979     src->proxy = soup_uri_new (new_uri);
1980     g_free (new_uri);
1981   }
1982
1983   return (src->proxy != NULL);
1984 }
1985
1986 static guint
1987 gst_soup_http_src_uri_get_type (GType type)
1988 {
1989   return GST_URI_SRC;
1990 }
1991
1992 static const gchar *const *
1993 gst_soup_http_src_uri_get_protocols (GType type)
1994 {
1995   static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
1996
1997   return protocols;
1998 }
1999
2000 static gchar *
2001 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
2002 {
2003   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2004
2005   /* FIXME: make thread-safe */
2006   return g_strdup (src->location);
2007 }
2008
2009 static gboolean
2010 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
2011     GError ** error)
2012 {
2013   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2014
2015   return gst_soup_http_src_set_location (src, uri, error);
2016 }
2017
2018 static void
2019 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
2020 {
2021   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
2022
2023   iface->get_type = gst_soup_http_src_uri_get_type;
2024   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
2025   iface->get_uri = gst_soup_http_src_uri_get_uri;
2026   iface->set_uri = gst_soup_http_src_uri_set_uri;
2027 }