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