tizen 2.0 init
[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
807   GST_DEBUG_OBJECT (src, "got headers:");
808   soup_message_headers_foreach (msg->response_headers,
809       gst_soup_http_src_headers_foreach, src);
810
811   if (msg->status_code == 407 && src->proxy_id && src->proxy_pw)
812     return;
813
814   if (src->automatic_redirect && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
815 #ifdef GST_EXT_SOUP_MODIFICATION
816     value = soup_message_headers_get (msg->response_headers, "Location");
817     gst_soup_http_src_set_location (src, value);
818     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\"", msg->status_code, value);
819 #else
820     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\"", msg->status_code,
821         soup_message_headers_get (msg->response_headers, "Location"));
822 #endif
823     return;
824   }
825
826   if (msg->status_code == SOUP_STATUS_UNAUTHORIZED)
827     return;
828
829   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING;
830
831   /* Parse Content-Length. */
832   if (soup_message_headers_get_encoding (msg->response_headers) ==
833       SOUP_ENCODING_CONTENT_LENGTH) {
834     newsize = src->request_position +
835         soup_message_headers_get_content_length (msg->response_headers);
836     if (!src->have_size || (src->content_size != newsize)) {
837       src->content_size = newsize;
838 #ifdef SEEK_CHANGES
839     if(!src->file_size)
840       src->file_size = newsize;
841 #endif
842       src->have_size = TRUE;
843       src->seekable = TRUE;
844       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
845
846       basesrc = GST_BASE_SRC_CAST (src);
847       gst_segment_set_duration (&basesrc->segment, GST_FORMAT_BYTES,
848           src->content_size);
849       gst_element_post_message (GST_ELEMENT (src),
850           gst_message_new_duration (GST_OBJECT (src), GST_FORMAT_BYTES,
851               src->content_size));
852     }
853 #ifdef SEEK_CHANGES
854     soup_message_headers_get_content_range(msg->response_headers, &start, &end, &total_length);
855     if(total_length > 0)
856     {
857       src->file_size = total_length;
858       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->file_size);
859       basesrc = GST_BASE_SRC_CAST (src);
860       gst_segment_set_duration (&basesrc->segment, GST_FORMAT_BYTES,
861           src->file_size);
862       gst_element_post_message (GST_ELEMENT (src),
863           gst_message_new_duration (GST_OBJECT (src), GST_FORMAT_BYTES,
864               src->file_size));
865     }
866 #endif
867   }
868
869   /* Icecast stuff */
870   tag_list = gst_tag_list_new ();
871
872   if ((value =
873           soup_message_headers_get (msg->response_headers,
874               "icy-metaint")) != NULL) {
875     gint icy_metaint = atoi (value);
876
877     GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value, icy_metaint);
878     if (icy_metaint > 0) {
879       if (src->src_caps)
880         gst_caps_unref (src->src_caps);
881
882       src->src_caps = gst_caps_new_simple ("application/x-icy",
883           "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
884     }
885   }
886   if ((value =
887           soup_message_headers_get_content_type (msg->response_headers,
888               &params)) != NULL) {
889     GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
890     if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
891       gint channels = 2;
892       gint rate = 44100;
893       char *param;
894
895       if (src->src_caps)
896         gst_caps_unref (src->src_caps);
897
898       param = g_hash_table_lookup (params, "channels");
899       if (param != NULL)
900         channels = atol (param);
901
902       param = g_hash_table_lookup (params, "rate");
903       if (param != NULL)
904         rate = atol (param);
905
906       src->src_caps = gst_caps_new_simple ("audio/x-raw-int",
907           "channels", G_TYPE_INT, channels,
908           "rate", G_TYPE_INT, rate,
909           "width", G_TYPE_INT, 16,
910           "depth", G_TYPE_INT, 16,
911           "signed", G_TYPE_BOOLEAN, TRUE,
912           "endianness", G_TYPE_INT, G_BIG_ENDIAN, NULL);
913     } else {
914       /* Set the Content-Type field on the caps */
915       if (src->src_caps)
916         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
917             value, NULL);
918     }
919   }
920
921   if (params != NULL)
922     g_hash_table_destroy (params);
923
924   if ((value =
925           soup_message_headers_get (msg->response_headers,
926               "icy-name")) != NULL) {
927     g_free (src->iradio_name);
928     src->iradio_name = gst_soup_http_src_unicodify (value);
929     if (src->iradio_name) {
930       g_object_notify (G_OBJECT (src), "iradio-name");
931       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
932           src->iradio_name, NULL);
933     }
934   }
935   if ((value =
936           soup_message_headers_get (msg->response_headers,
937               "icy-genre")) != NULL) {
938     g_free (src->iradio_genre);
939     src->iradio_genre = gst_soup_http_src_unicodify (value);
940     if (src->iradio_genre) {
941       g_object_notify (G_OBJECT (src), "iradio-genre");
942       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
943           src->iradio_genre, NULL);
944     }
945   }
946   if ((value = soup_message_headers_get (msg->response_headers, "icy-url"))
947       != NULL) {
948     g_free (src->iradio_url);
949     src->iradio_url = gst_soup_http_src_unicodify (value);
950     if (src->iradio_url) {
951       g_object_notify (G_OBJECT (src), "iradio-url");
952       gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
953           src->iradio_url, NULL);
954     }
955   }
956   if (!gst_tag_list_is_empty (tag_list)) {
957     GST_DEBUG_OBJECT (src,
958         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
959     gst_element_found_tags (GST_ELEMENT_CAST (src), tag_list);
960   } else {
961     gst_tag_list_free (tag_list);
962   }
963
964   /* Handle HTTP errors. */
965   gst_soup_http_src_parse_status (msg, src);
966
967   /* Check if Range header was respected. */
968   if (src->ret == GST_FLOW_CUSTOM_ERROR &&
969       src->read_position && msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) {
970     src->seekable = FALSE;
971     GST_ELEMENT_ERROR (src, RESOURCE, SEEK,
972         (_("Server does not support seeking.")),
973         ("Server does not accept Range HTTP header, URL: %s", src->location));
974     src->ret = GST_FLOW_ERROR;
975   }
976 }
977
978 /* Have body. Signal EOS. */
979 static void
980 gst_soup_http_src_got_body_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
981 {
982   if (G_UNLIKELY (msg != src->msg)) {
983     GST_DEBUG_OBJECT (src, "got body, but not for current message");
984     return;
985   }
986   if (G_UNLIKELY (src->session_io_status !=
987           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
988     /* Probably a redirect. */
989     return;
990   }
991   GST_DEBUG_OBJECT (src, "got body");
992   src->ret = GST_FLOW_UNEXPECTED;
993   if (src->loop)
994     g_main_loop_quit (src->loop);
995   gst_soup_http_src_session_pause_message (src);
996 }
997
998 /* Finished. Signal EOS. */
999 static void
1000 gst_soup_http_src_finished_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1001 {
1002   if (G_UNLIKELY (msg != src->msg)) {
1003     GST_DEBUG_OBJECT (src, "finished, but not for current message");
1004     return;
1005   }
1006   GST_DEBUG_OBJECT (src, "finished");
1007   src->ret = GST_FLOW_UNEXPECTED;
1008   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED) {
1009     /* gst_soup_http_src_cancel_message() triggered this; probably a seek
1010      * that occurred in the QUEUEING state; i.e. before the connection setup
1011      * was complete. Do nothing */
1012   } else if (src->session_io_status ==
1013       GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING && src->read_position > 0) {
1014     /* The server disconnected while streaming. Reconnect and seeking to the
1015      * last location. */
1016     src->retry = TRUE;
1017     src->ret = GST_FLOW_CUSTOM_ERROR;
1018   } else if (G_UNLIKELY (src->session_io_status !=
1019           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1020     /* FIXME: reason_phrase is not translated, add proper error message */
1021     GST_ELEMENT_ERROR (src, RESOURCE, NOT_FOUND,
1022         ("%s", msg->reason_phrase),
1023         ("libsoup status code %d", msg->status_code));
1024   }
1025   if (src->loop)
1026     g_main_loop_quit (src->loop);
1027 }
1028
1029 /* Buffer lifecycle management.
1030  *
1031  * gst_soup_http_src_create() runs the GMainLoop for this element, to let
1032  * Soup take control.
1033  * A GstBuffer is allocated in gst_soup_http_src_chunk_allocator() and
1034  * associated with a SoupBuffer.
1035  * Soup reads HTTP data in the GstBuffer's data buffer.
1036  * The gst_soup_http_src_got_chunk_cb() is then called with the SoupBuffer.
1037  * That sets gst_soup_http_src_create()'s return argument to the GstBuffer,
1038  * increments its refcount (to 2), pauses the flow of data from the HTTP
1039  * source to prevent gst_soup_http_src_got_chunk_cb() from being called
1040  * again and breaks out of the GMainLoop.
1041  * Because the SOUP_MESSAGE_OVERWRITE_CHUNKS flag is set, Soup frees the
1042  * SoupBuffer and calls gst_soup_http_src_chunk_free(), which decrements the
1043  * refcount (to 1).
1044  * gst_soup_http_src_create() returns the GstBuffer. It will be freed by a
1045  * downstream element.
1046  * If Soup fails to read HTTP data, it does not call
1047  * gst_soup_http_src_got_chunk_cb(), but still frees the SoupBuffer and
1048  * calls gst_soup_http_src_chunk_free(), which decrements the GstBuffer's
1049  * refcount to 0, freeing it.
1050  */
1051
1052 static void
1053 gst_soup_http_src_chunk_free (gpointer gstbuf)
1054 {
1055   gst_buffer_unref (GST_BUFFER_CAST (gstbuf));
1056 }
1057
1058 static SoupBuffer *
1059 gst_soup_http_src_chunk_allocator (SoupMessage * msg, gsize max_len,
1060     gpointer user_data)
1061 {
1062   GstSoupHTTPSrc *src = (GstSoupHTTPSrc *) user_data;
1063   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1064   GstBuffer *gstbuf;
1065   SoupBuffer *soupbuf;
1066   gsize length;
1067   GstFlowReturn rc;
1068
1069   if (max_len)
1070     length = MIN (basesrc->blocksize, max_len);
1071   else
1072     length = basesrc->blocksize;
1073   GST_DEBUG_OBJECT (src, "alloc %" G_GSIZE_FORMAT " bytes <= %" G_GSIZE_FORMAT,
1074       length, max_len);
1075
1076
1077   rc = gst_pad_alloc_buffer (GST_BASE_SRC_PAD (basesrc),
1078       GST_BUFFER_OFFSET_NONE, length,
1079       src->src_caps ? src->src_caps :
1080       GST_PAD_CAPS (GST_BASE_SRC_PAD (basesrc)), &gstbuf);
1081   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1082     /* Failed to allocate buffer. Stall SoupSession and return error code
1083      * to create(). */
1084     src->ret = rc;
1085     g_main_loop_quit (src->loop);
1086     return NULL;
1087   }
1088
1089   soupbuf = soup_buffer_new_with_owner (GST_BUFFER_DATA (gstbuf), length,
1090       gstbuf, gst_soup_http_src_chunk_free);
1091
1092   return soupbuf;
1093 }
1094
1095 static void
1096 gst_soup_http_src_got_chunk_cb (SoupMessage * msg, SoupBuffer * chunk,
1097     GstSoupHTTPSrc * src)
1098 {
1099   GstBaseSrc *basesrc;
1100   guint64 new_position;
1101
1102   if (G_UNLIKELY (msg != src->msg)) {
1103     GST_DEBUG_OBJECT (src, "got chunk, but not for current message");
1104     return;
1105   }
1106   if (G_UNLIKELY (src->session_io_status !=
1107           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)) {
1108     /* Probably a redirect. */
1109     return;
1110   }
1111   basesrc = GST_BASE_SRC_CAST (src);
1112   GST_DEBUG_OBJECT (src, "got chunk of %" G_GSIZE_FORMAT " bytes",
1113       chunk->length);
1114
1115   /* Extract the GstBuffer from the SoupBuffer and set its fields. */
1116   *src->outbuf = GST_BUFFER_CAST (soup_buffer_get_owner (chunk));
1117
1118   GST_BUFFER_SIZE (*src->outbuf) = chunk->length;
1119   GST_BUFFER_OFFSET (*src->outbuf) = basesrc->segment.last_stop;
1120
1121   gst_buffer_set_caps (*src->outbuf,
1122       (src->src_caps) ? src->src_caps :
1123       GST_PAD_CAPS (GST_BASE_SRC_PAD (basesrc)));
1124
1125   gst_buffer_ref (*src->outbuf);
1126
1127   new_position = src->read_position + chunk->length;
1128   if (G_LIKELY (src->request_position == src->read_position))
1129     src->request_position = new_position;
1130   src->read_position = new_position;
1131
1132   src->ret = GST_FLOW_OK;
1133   g_main_loop_quit (src->loop);
1134   gst_soup_http_src_session_pause_message (src);
1135 }
1136
1137 static void
1138 gst_soup_http_src_response_cb (SoupSession * session, SoupMessage * msg,
1139     GstSoupHTTPSrc * src)
1140 {
1141   if (G_UNLIKELY (msg != src->msg)) {
1142     GST_DEBUG_OBJECT (src, "got response %d: %s, but not for current message",
1143         msg->status_code, msg->reason_phrase);
1144     return;
1145   }
1146   if (G_UNLIKELY (src->session_io_status !=
1147           GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING)
1148       && SOUP_STATUS_IS_REDIRECTION (msg->status_code)) {
1149     /* Ignore redirections. */
1150     return;
1151   }
1152   GST_DEBUG_OBJECT (src, "got response %d: %s", msg->status_code,
1153       msg->reason_phrase);
1154   if (src->session_io_status == GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING &&
1155       src->read_position > 0) {
1156     /* The server disconnected while streaming. Reconnect and seeking to the
1157      * last location. */
1158     src->retry = TRUE;
1159   } else
1160     gst_soup_http_src_parse_status (msg, src);
1161   /* The session's SoupMessage object expires after this callback returns. */
1162   src->msg = NULL;
1163   g_main_loop_quit (src->loop);
1164 }
1165
1166 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1167   GST_ELEMENT_ERROR ((src), cat, code, ("%s", error_message),        \
1168       ("%s (%d), URL: %s", (soup_msg)->reason_phrase,                \
1169           (soup_msg)->status_code, (src)->location));
1170
1171 static void
1172 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1173 {
1174   if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
1175     switch (msg->status_code) {
1176       case SOUP_STATUS_CANT_RESOLVE:
1177       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1178         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1179             _("Could not resolve server name."));
1180         src->ret = GST_FLOW_ERROR;
1181         break;
1182       case SOUP_STATUS_CANT_CONNECT:
1183       case SOUP_STATUS_CANT_CONNECT_PROXY:
1184         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1185             _("Could not establish connection to server."));
1186         src->ret = GST_FLOW_ERROR;
1187         break;
1188       case SOUP_STATUS_SSL_FAILED:
1189         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1190             _("Secure connection setup failed."));
1191         src->ret = GST_FLOW_ERROR;
1192         break;
1193       case SOUP_STATUS_IO_ERROR:
1194         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1195             _("A network error occured, or the server closed the connection "
1196                 "unexpectedly."));
1197         src->ret = GST_FLOW_ERROR;
1198         break;
1199       case SOUP_STATUS_MALFORMED:
1200         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1201             _("Server sent bad data."));
1202         src->ret = GST_FLOW_ERROR;
1203         break;
1204       case SOUP_STATUS_CANCELLED:
1205         /* No error message when interrupted by program. */
1206         break;
1207     }
1208   } else if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) ||
1209       SOUP_STATUS_IS_REDIRECTION (msg->status_code) ||
1210       SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) {
1211     /* Report HTTP error. */
1212     /* FIXME: reason_phrase is not translated and not suitable for user
1213      * error dialog according to libsoup documentation.
1214      * FIXME: error code (OPEN_READ vs. READ) should depend on http status? */
1215     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1216         ("%s", msg->reason_phrase),
1217         ("%s (%d), URL: %s", msg->reason_phrase, msg->status_code,
1218             src->location));
1219     src->ret = GST_FLOW_ERROR;
1220   }
1221 }
1222
1223 static gboolean
1224 gst_soup_http_src_build_message (GstSoupHTTPSrc * src)
1225 {
1226   src->msg = soup_message_new (SOUP_METHOD_GET, src->location);
1227   if (!src->msg) {
1228     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1229         ("Error parsing URL."), ("URL: %s", src->location));
1230     return FALSE;
1231   }
1232   src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE;
1233   soup_message_headers_append (src->msg->request_headers, "Connection",
1234       "close");
1235   if (src->iradio_mode) {
1236     soup_message_headers_append (src->msg->request_headers, "icy-metadata",
1237         "1");
1238   }
1239   if (src->cookies) {
1240     gchar **cookie;
1241 #ifdef GST_EXT_SOUP_MODIFICATION
1242     SoupURI *uri;
1243     SoupCookie *cookie_parsed;
1244     gchar *header;
1245
1246     uri = soup_uri_new (src->location);
1247     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1248       if ((cookie_parsed = soup_cookie_parse (*cookie, uri)) != NULL) {
1249         header = soup_cookie_to_cookie_header (cookie_parsed);
1250         soup_message_headers_append (src->msg->request_headers, "Cookie",
1251           header);
1252         g_free (header);
1253         soup_cookie_free (cookie_parsed);
1254       }
1255     }
1256     soup_uri_free (uri);
1257 #else
1258     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1259       soup_message_headers_append (src->msg->request_headers, "Cookie",
1260           *cookie);
1261     }
1262 #endif
1263   }
1264   soup_message_headers_append (src->msg->request_headers,
1265       "transferMode.dlna.org", "Streaming");
1266   src->retry = FALSE;
1267
1268   g_signal_connect (src->msg, "got_headers",
1269       G_CALLBACK (gst_soup_http_src_got_headers_cb), src);
1270   g_signal_connect (src->msg, "got_body",
1271       G_CALLBACK (gst_soup_http_src_got_body_cb), src);
1272   g_signal_connect (src->msg, "finished",
1273       G_CALLBACK (gst_soup_http_src_finished_cb), src);
1274   g_signal_connect (src->msg, "got_chunk",
1275       G_CALLBACK (gst_soup_http_src_got_chunk_cb), src);
1276   soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS |
1277       (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT));
1278   soup_message_set_chunk_allocator (src->msg,
1279       gst_soup_http_src_chunk_allocator, src, NULL);
1280 #ifdef SEEK_CHANGES
1281   //gst_soup_http_src_add_range_header (src, src->request_position);
1282   if(src->range_size > 0)
1283     soup_message_headers_set_range(src->msg->request_headers, src->request_position, (src->request_position+src->range_size-1));
1284   else {
1285     gst_soup_http_src_add_range_header (src, src->request_position);
1286     gst_soup_http_src_add_extra_headers (src);
1287     GST_DEBUG_OBJECT (src, "request headers:");
1288     soup_message_headers_foreach (src->msg->request_headers,gst_soup_http_src_headers_foreach, src);
1289   }
1290 #else
1291   gst_soup_http_src_add_range_header (src, src->request_position);
1292
1293   gst_soup_http_src_add_extra_headers (src);
1294
1295   GST_DEBUG_OBJECT (src, "request headers:");
1296   soup_message_headers_foreach (src->msg->request_headers,
1297       gst_soup_http_src_headers_foreach, src);
1298 #endif
1299
1300   return TRUE;
1301 }
1302
1303 static GstFlowReturn
1304 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
1305 {
1306   GstSoupHTTPSrc *src;
1307
1308   src = GST_SOUP_HTTP_SRC (psrc);
1309
1310   if (src->msg && (src->request_position != src->read_position)) {
1311 #ifdef SEEK_CHANGES
1312     if (src->file_size != 0 && src->request_position >= src->file_size) {
1313 #else
1314     if (src->content_size != 0 && src->request_position >= src->content_size) {
1315 #endif
1316       GST_WARNING_OBJECT (src, "Seeking behind the end of file -- EOS");
1317       return GST_FLOW_UNEXPECTED;
1318     } else if (src->session_io_status ==
1319         GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE) {
1320       gst_soup_http_src_add_range_header (src, src->request_position);
1321     } else {
1322       GST_DEBUG_OBJECT (src, "Seek from position %" G_GUINT64_FORMAT
1323           " to %" G_GUINT64_FORMAT ": requeueing connection request",
1324           src->read_position, src->request_position);
1325 #ifndef SEEK_CHANGES
1326       gst_soup_http_src_cancel_message (src);
1327 #endif
1328     }
1329   }
1330 #ifdef SEEK_CHANGES
1331   if(src->msg  && src->seeked) {
1332     GST_DEBUG_OBJECT (src, "seeking to offset start %llu end %llu", src->request_position, (src->request_position+src->range_size-1));
1333     if(src->msg) {
1334       soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_OK);
1335       src->msg = NULL;
1336       if (!gst_soup_http_src_build_message (src))
1337         return GST_FLOW_ERROR;
1338     }
1339     soup_session_queue_message (src->session, src->msg, (SoupSessionCallback) gst_soup_http_src_response_cb, src);
1340     src->session_io_status = GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED;
1341     src->read_position = src->request_position;
1342     if(src->range_size > 0) src->content_size = src->request_position+src->range_size-1;
1343     else src->content_size = src->file_size;
1344   }
1345   src->seeked = FALSE;
1346 #endif
1347   if (!src->msg)
1348     if (!gst_soup_http_src_build_message (src))
1349       return GST_FLOW_ERROR;
1350
1351   src->ret = GST_FLOW_CUSTOM_ERROR;
1352   src->outbuf = outbuf;
1353   do {
1354     if (src->interrupted) {
1355       GST_DEBUG_OBJECT (src, "interrupted");
1356       break;
1357     }
1358     if (src->retry) {
1359       GST_DEBUG_OBJECT (src, "Reconnecting");
1360       if (!gst_soup_http_src_build_message (src))
1361         return GST_FLOW_ERROR;
1362       src->retry = FALSE;
1363       continue;
1364     }
1365     if (!src->msg) {
1366       GST_DEBUG_OBJECT (src, "EOS reached");
1367       break;
1368     }
1369
1370     switch (src->session_io_status) {
1371       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_IDLE:
1372         GST_DEBUG_OBJECT (src, "Queueing connection request");
1373         gst_soup_http_src_queue_message (src);
1374         break;
1375       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_QUEUED:
1376         break;
1377       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_RUNNING:
1378         gst_soup_http_src_session_unpause_message (src);
1379         break;
1380       case GST_SOUP_HTTP_SRC_SESSION_IO_STATUS_CANCELLED:
1381         /* Impossible. */
1382         break;
1383     }
1384
1385     if (src->ret == GST_FLOW_CUSTOM_ERROR)
1386       g_main_loop_run (src->loop);
1387   } while (src->ret == GST_FLOW_CUSTOM_ERROR);
1388
1389   if (src->ret == GST_FLOW_CUSTOM_ERROR)
1390     src->ret = GST_FLOW_UNEXPECTED;
1391   return src->ret;
1392 }
1393
1394 static gboolean
1395 gst_soup_http_src_start (GstBaseSrc * bsrc)
1396 {
1397   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1398
1399   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
1400
1401   if (!src->location) {
1402     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
1403         ("Missing location property"));
1404     return FALSE;
1405   }
1406
1407   src->context = g_main_context_new ();
1408
1409   src->loop = g_main_loop_new (src->context, TRUE);
1410   if (!src->loop) {
1411     GST_ELEMENT_ERROR (src, LIBRARY, INIT,
1412         (NULL), ("Failed to start GMainLoop"));
1413     g_main_context_unref (src->context);
1414     return FALSE;
1415   }
1416
1417   if (src->proxy == NULL) {
1418     src->session =
1419         soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
1420         src->context, SOUP_SESSION_USER_AGENT, src->user_agent,
1421         SOUP_SESSION_TIMEOUT, src->timeout,
1422 #ifdef HAVE_LIBSOUP_GNOME
1423         SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_PROXY_RESOLVER_GNOME,
1424 #endif
1425         NULL);
1426   } else {
1427     src->session =
1428         soup_session_async_new_with_options (SOUP_SESSION_ASYNC_CONTEXT,
1429         src->context, SOUP_SESSION_PROXY_URI, src->proxy,
1430         SOUP_SESSION_TIMEOUT, src->timeout,
1431         SOUP_SESSION_USER_AGENT, src->user_agent, NULL);
1432   }
1433
1434   if (!src->session) {
1435     GST_ELEMENT_ERROR (src, LIBRARY, INIT,
1436         (NULL), ("Failed to create async session"));
1437     return FALSE;
1438   }
1439
1440 #ifdef GST_EXT_SOUP_MODIFICATION
1441   soup_session_add_feature_by_type (src->session, SOUP_TYPE_COOKIE_JAR);
1442   src->cookie_jar = SOUP_COOKIE_JAR (soup_session_get_feature (src->session, SOUP_TYPE_COOKIE_JAR));
1443 #endif
1444
1445   g_signal_connect (src->session, "authenticate",
1446       G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
1447   return TRUE;
1448 }
1449
1450 static gboolean
1451 gst_soup_http_src_stop (GstBaseSrc * bsrc)
1452 {
1453   GstSoupHTTPSrc *src;
1454
1455   src = GST_SOUP_HTTP_SRC (bsrc);
1456   GST_DEBUG_OBJECT (src, "stop()");
1457   gst_soup_http_src_session_close (src);
1458   if (src->loop) {
1459     g_main_loop_unref (src->loop);
1460     g_main_context_unref (src->context);
1461     src->loop = NULL;
1462     src->context = NULL;
1463   }
1464   if (src->extra_headers) {
1465     gst_structure_free (src->extra_headers);
1466     src->extra_headers = NULL;
1467   }
1468
1469   gst_soup_http_src_reset (src);
1470   return TRUE;
1471 }
1472
1473 /* Interrupt a blocking request. */
1474 static gboolean
1475 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
1476 {
1477   GstSoupHTTPSrc *src;
1478
1479   src = GST_SOUP_HTTP_SRC (bsrc);
1480   GST_DEBUG_OBJECT (src, "unlock()");
1481
1482   src->interrupted = TRUE;
1483   if (src->loop)
1484     g_main_loop_quit (src->loop);
1485   return TRUE;
1486 }
1487
1488 /* Interrupt interrupt. */
1489 static gboolean
1490 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
1491 {
1492   GstSoupHTTPSrc *src;
1493
1494   src = GST_SOUP_HTTP_SRC (bsrc);
1495   GST_DEBUG_OBJECT (src, "unlock_stop()");
1496
1497   src->interrupted = FALSE;
1498   return TRUE;
1499 }
1500
1501 static gboolean
1502 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
1503 {
1504   GstSoupHTTPSrc *src;
1505
1506   src = GST_SOUP_HTTP_SRC (bsrc);
1507
1508   if (src->have_size) {
1509 #ifdef SEEK_CHANGES
1510     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
1511         src->file_size);
1512     *size = src->file_size;
1513 #else
1514     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
1515         src->content_size);
1516     *size = src->content_size;
1517 #endif
1518     return TRUE;
1519   }
1520   GST_DEBUG_OBJECT (src, "get_size() = FALSE");
1521   return FALSE;
1522 }
1523
1524 static gboolean
1525 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
1526 {
1527   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1528
1529   return src->seekable;
1530 }
1531
1532 static gboolean
1533 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
1534 {
1535   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1536
1537   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT ")", segment->start);
1538
1539 #ifdef SEEK_CHANGES
1540   src->seeked = TRUE;
1541 #endif
1542   if (src->read_position == segment->start) {
1543     GST_DEBUG_OBJECT (src, "Seeking to current read position");
1544     return TRUE;
1545   }
1546
1547   if (!src->seekable) {
1548     GST_WARNING_OBJECT (src, "Not seekable");
1549     return FALSE;
1550   }
1551
1552   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
1553     GST_WARNING_OBJECT (src, "Invalid seek segment");
1554     return FALSE;
1555   }
1556
1557 #ifdef SEEK_CHANGES
1558   if (src->content_size != 0 && segment->start >= src->file_size) {
1559 #else
1560   if (src->content_size != 0 && segment->start >= src->content_size) {
1561 #endif
1562     GST_WARNING_OBJECT (src, "Seeking behind end of file, will go to EOS soon");
1563   }
1564
1565   /* Wait for create() to handle the jump in offset. */
1566   src->request_position = segment->start;
1567   return TRUE;
1568 }
1569
1570 static gboolean
1571 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
1572 {
1573   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
1574   gboolean ret;
1575
1576   switch (GST_QUERY_TYPE (query)) {
1577     case GST_QUERY_URI:
1578       gst_query_set_uri (query, src->location);
1579       ret = TRUE;
1580       break;
1581     default:
1582       ret = FALSE;
1583       break;
1584   }
1585
1586   if (!ret)
1587     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
1588
1589   return ret;
1590 }
1591
1592 static gboolean
1593 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri)
1594 {
1595   if (src->location) {
1596     g_free (src->location);
1597     src->location = NULL;
1598   }
1599   src->location = g_strdup (uri);
1600
1601   return TRUE;
1602 }
1603
1604 static gboolean
1605 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
1606 {
1607   if (src->proxy) {
1608     soup_uri_free (src->proxy);
1609     src->proxy = NULL;
1610   }
1611   if (g_str_has_prefix (uri, "http://")) {
1612     src->proxy = soup_uri_new (uri);
1613   } else {
1614     gchar *new_uri = g_strconcat ("http://", uri, NULL);
1615
1616     src->proxy = soup_uri_new (new_uri);
1617     g_free (new_uri);
1618   }
1619
1620   return TRUE;
1621 }
1622
1623 static guint
1624 gst_soup_http_src_uri_get_type (void)
1625 {
1626   return GST_URI_SRC;
1627 }
1628
1629 static gchar **
1630 gst_soup_http_src_uri_get_protocols (void)
1631 {
1632   static const gchar *protocols[] = { "http", "https", NULL };
1633   return (gchar **) protocols;
1634 }
1635
1636 static const gchar *
1637 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
1638 {
1639   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
1640
1641   return src->location;
1642 }
1643
1644 static gboolean
1645 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri)
1646 {
1647   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
1648
1649   return gst_soup_http_src_set_location (src, uri);
1650 }
1651
1652 static void
1653 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
1654 {
1655   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
1656
1657   iface->get_type = gst_soup_http_src_uri_get_type;
1658   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
1659   iface->get_uri = gst_soup_http_src_uri_get_uri;
1660   iface->set_uri = gst_soup_http_src_uri_set_uri;
1661 }