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