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