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