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