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