26daa83ab37be0824c80f507fb71526c5896b57b
[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 ! mpgaudioparse
47  *     ! mpg123audiodec ! audioconvert ! audioresample ! autoaudiosink
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 #define GST_SOUP_SESSION_CONTEXT "gst.soup.session"
90
91 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
92     GST_PAD_SRC,
93     GST_PAD_ALWAYS,
94     GST_STATIC_CAPS_ANY);
95
96 enum
97 {
98   PROP_0,
99   PROP_LOCATION,
100   PROP_IS_LIVE,
101   PROP_USER_AGENT,
102   PROP_AUTOMATIC_REDIRECT,
103   PROP_PROXY,
104   PROP_USER_ID,
105   PROP_USER_PW,
106   PROP_PROXY_ID,
107   PROP_PROXY_PW,
108   PROP_COOKIES,
109   PROP_IRADIO_MODE,
110   PROP_TIMEOUT,
111   PROP_EXTRA_HEADERS,
112   PROP_SOUP_LOG_LEVEL,
113   PROP_COMPRESS,
114   PROP_KEEP_ALIVE,
115   PROP_SSL_STRICT,
116   PROP_SSL_CA_FILE,
117   PROP_SSL_USE_SYSTEM_CA_FILE,
118   PROP_TLS_DATABASE,
119   PROP_RETRIES,
120   PROP_METHOD,
121   PROP_TLS_INTERACTION,
122 };
123
124 #define DEFAULT_USER_AGENT           "GStreamer souphttpsrc " PACKAGE_VERSION " "
125 #define DEFAULT_IRADIO_MODE          TRUE
126 #define DEFAULT_SOUP_LOG_LEVEL       SOUP_LOGGER_LOG_HEADERS
127 #define DEFAULT_COMPRESS             FALSE
128 #define DEFAULT_KEEP_ALIVE           TRUE
129 #define DEFAULT_SSL_STRICT           TRUE
130 #define DEFAULT_SSL_CA_FILE          NULL
131 #define DEFAULT_SSL_USE_SYSTEM_CA_FILE TRUE
132 #define DEFAULT_TLS_DATABASE         NULL
133 #define DEFAULT_TLS_INTERACTION      NULL
134 #define DEFAULT_TIMEOUT              15
135 #define DEFAULT_RETRIES              3
136 #define DEFAULT_SOUP_METHOD          NULL
137
138 #define GROW_BLOCKSIZE_LIMIT 1
139 #define GROW_BLOCKSIZE_COUNT 1
140 #define GROW_BLOCKSIZE_FACTOR 2
141 #define REDUCE_BLOCKSIZE_LIMIT 0.20
142 #define REDUCE_BLOCKSIZE_COUNT 2
143 #define REDUCE_BLOCKSIZE_FACTOR 0.5
144 #define GROW_TIME_LIMIT (1 * GST_SECOND)
145
146 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
147 #define DLNA_OP_TIMED_SEEK  0x02
148 #define DLNA_OP_BYTE_SEEK   0x01
149 #endif
150
151 static void gst_soup_http_src_uri_handler_init (gpointer g_iface,
152     gpointer iface_data);
153 static void gst_soup_http_src_finalize (GObject * gobject);
154 static void gst_soup_http_src_dispose (GObject * gobject);
155
156 static void gst_soup_http_src_set_property (GObject * object, guint prop_id,
157     const GValue * value, GParamSpec * pspec);
158 static void gst_soup_http_src_get_property (GObject * object, guint prop_id,
159     GValue * value, GParamSpec * pspec);
160
161 static GstStateChangeReturn gst_soup_http_src_change_state (GstElement *
162     element, GstStateChange transition);
163 static void gst_soup_http_src_set_context (GstElement * element,
164     GstContext * context);
165 static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc,
166     GstBuffer ** outbuf);
167 static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc);
168 static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc);
169 static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size);
170 static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc);
171 static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc,
172     GstSegment * segment);
173 static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query);
174 static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc);
175 static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc);
176 static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src,
177     const gchar * uri, GError ** error);
178 static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src,
179     const gchar * uri);
180 static char *gst_soup_http_src_unicodify (const char *str);
181 static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src,
182     const gchar * method);
183 static void gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src);
184 static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src,
185     guint64 offset, guint64 stop_offset);
186 static gboolean gst_soup_http_src_session_open (GstSoupHTTPSrc * src);
187 static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src);
188 static GstFlowReturn gst_soup_http_src_parse_status (SoupMessage * msg,
189     GstSoupHTTPSrc * src);
190 static GstFlowReturn gst_soup_http_src_got_headers (GstSoupHTTPSrc * src,
191     SoupMessage * msg);
192 static void gst_soup_http_src_authenticate_cb (SoupSession * session,
193     SoupMessage * msg, SoupAuth * auth, gboolean retrying,
194     GstSoupHTTPSrc * src);
195
196 #define gst_soup_http_src_parent_class parent_class
197 G_DEFINE_TYPE_WITH_CODE (GstSoupHTTPSrc, gst_soup_http_src, GST_TYPE_PUSH_SRC,
198     G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
199         gst_soup_http_src_uri_handler_init));
200
201 static void
202 gst_soup_http_src_class_init (GstSoupHTTPSrcClass * klass)
203 {
204   GObjectClass *gobject_class;
205   GstElementClass *gstelement_class;
206   GstBaseSrcClass *gstbasesrc_class;
207   GstPushSrcClass *gstpushsrc_class;
208
209   gobject_class = (GObjectClass *) klass;
210   gstelement_class = (GstElementClass *) klass;
211   gstbasesrc_class = (GstBaseSrcClass *) klass;
212   gstpushsrc_class = (GstPushSrcClass *) klass;
213
214   gobject_class->set_property = gst_soup_http_src_set_property;
215   gobject_class->get_property = gst_soup_http_src_get_property;
216   gobject_class->finalize = gst_soup_http_src_finalize;
217   gobject_class->dispose = gst_soup_http_src_dispose;
218
219   g_object_class_install_property (gobject_class,
220       PROP_LOCATION,
221       g_param_spec_string ("location", "Location",
222           "Location to read from", "",
223           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
224   g_object_class_install_property (gobject_class,
225       PROP_USER_AGENT,
226       g_param_spec_string ("user-agent", "User-Agent",
227           "Value of the User-Agent HTTP request header field",
228           DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
229   g_object_class_install_property (gobject_class,
230       PROP_AUTOMATIC_REDIRECT,
231       g_param_spec_boolean ("automatic-redirect", "automatic-redirect",
232           "Automatically follow HTTP redirects (HTTP Status Code 3xx)",
233           TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
234   g_object_class_install_property (gobject_class,
235       PROP_PROXY,
236       g_param_spec_string ("proxy", "Proxy",
237           "HTTP proxy server URI", "",
238           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
239   g_object_class_install_property (gobject_class,
240       PROP_USER_ID,
241       g_param_spec_string ("user-id", "user-id",
242           "HTTP location URI user id for authentication", "",
243           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
244   g_object_class_install_property (gobject_class, PROP_USER_PW,
245       g_param_spec_string ("user-pw", "user-pw",
246           "HTTP location URI user password for authentication", "",
247           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
248   g_object_class_install_property (gobject_class, PROP_PROXY_ID,
249       g_param_spec_string ("proxy-id", "proxy-id",
250           "HTTP proxy URI user id for authentication", "",
251           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
252   g_object_class_install_property (gobject_class, PROP_PROXY_PW,
253       g_param_spec_string ("proxy-pw", "proxy-pw",
254           "HTTP proxy URI user password for authentication", "",
255           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
256   g_object_class_install_property (gobject_class, PROP_COOKIES,
257       g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies",
258           G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
259   g_object_class_install_property (gobject_class, PROP_IS_LIVE,
260       g_param_spec_boolean ("is-live", "is-live", "Act like a live source",
261           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
262   g_object_class_install_property (gobject_class, PROP_TIMEOUT,
263       g_param_spec_uint ("timeout", "timeout",
264           "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0,
265           3600, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
266   g_object_class_install_property (gobject_class, PROP_EXTRA_HEADERS,
267       g_param_spec_boxed ("extra-headers", "Extra Headers",
268           "Extra headers to append to the HTTP request",
269           GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
270   g_object_class_install_property (gobject_class, PROP_IRADIO_MODE,
271       g_param_spec_boolean ("iradio-mode", "iradio-mode",
272           "Enable internet radio mode (ask server to send shoutcast/icecast "
273           "metadata interleaved with the actual stream data)",
274           DEFAULT_IRADIO_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
275
276  /**
277    * GstSoupHTTPSrc::http-log-level:
278    *
279    * If set and > 0, captures and dumps HTTP session data as
280    * log messages if log level >= GST_LEVEL_TRACE
281    *
282    * Since: 1.4
283    */
284   g_object_class_install_property (gobject_class, PROP_SOUP_LOG_LEVEL,
285       g_param_spec_enum ("http-log-level", "HTTP log level",
286           "Set log level for soup's HTTP session log",
287           SOUP_TYPE_LOGGER_LOG_LEVEL, DEFAULT_SOUP_LOG_LEVEL,
288           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
289
290  /**
291    * GstSoupHTTPSrc::compress:
292    *
293    * If set to %TRUE, souphttpsrc will automatically handle gzip
294    * and deflate Content-Encodings. This does not make much difference
295    * and causes more load for normal media files, but makes a real
296    * difference in size for plaintext files.
297    *
298    * Since: 1.4
299    */
300   g_object_class_install_property (gobject_class, PROP_COMPRESS,
301       g_param_spec_boolean ("compress", "Compress",
302           "Allow compressed content encodings",
303           DEFAULT_COMPRESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
304
305  /**
306    * GstSoupHTTPSrc::keep-alive:
307    *
308    * If set to %TRUE, souphttpsrc will keep alive connections when being
309    * set to READY state and only will close connections when connecting
310    * to a different server or when going to NULL state..
311    *
312    * Since: 1.4
313    */
314   g_object_class_install_property (gobject_class, PROP_KEEP_ALIVE,
315       g_param_spec_boolean ("keep-alive", "keep-alive",
316           "Use HTTP persistent connections", DEFAULT_KEEP_ALIVE,
317           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
318
319  /**
320    * GstSoupHTTPSrc::ssl-strict:
321    *
322    * If set to %TRUE, souphttpsrc will reject all SSL certificates that
323    * are considered invalid.
324    *
325    * Since: 1.4
326    */
327   g_object_class_install_property (gobject_class, PROP_SSL_STRICT,
328       g_param_spec_boolean ("ssl-strict", "SSL Strict",
329           "Strict SSL certificate checking", DEFAULT_SSL_STRICT,
330           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
331
332  /**
333    * GstSoupHTTPSrc::ssl-ca-file:
334    *
335    * A SSL anchor CA file that should be used for checking certificates
336    * instead of the system CA file.
337    *
338    * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
339    * value will be ignored.
340    *
341    * Deprecated: Use #GstSoupHTTPSrc::tls-database property instead.
342    * Since: 1.4
343    */
344   g_object_class_install_property (gobject_class, PROP_SSL_CA_FILE,
345       g_param_spec_string ("ssl-ca-file", "SSL CA File",
346           "Location of a SSL anchor CA file to use", DEFAULT_SSL_CA_FILE,
347           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348
349  /**
350    * GstSoupHTTPSrc::ssl-use-system-ca-file:
351    *
352    * If set to %TRUE, souphttpsrc will use the system's CA file for
353    * checking certificates, unless #GstSoupHTTPSrc::ssl-ca-file or
354    * #GstSoupHTTPSrc::tls-database are non-%NULL.
355    *
356    * Since: 1.4
357    */
358   g_object_class_install_property (gobject_class, PROP_SSL_USE_SYSTEM_CA_FILE,
359       g_param_spec_boolean ("ssl-use-system-ca-file", "Use System CA File",
360           "Use system CA file", DEFAULT_SSL_USE_SYSTEM_CA_FILE,
361           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
362
363   /**
364    * GstSoupHTTPSrc::tls-database:
365    *
366    * TLS database with anchor certificate authorities used to validate
367    * the server certificate.
368    *
369    * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
370    * and #GstSoupHTTPSrc::ssl-ca-file values will be ignored.
371    *
372    * Since: 1.6
373    */
374   g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
375       g_param_spec_object ("tls-database", "TLS database",
376           "TLS database with anchor certificate authorities used to validate the server certificate",
377           G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
378
379   /**
380    * GstSoupHTTPSrc::tls-interaction:
381    *
382    * A #GTlsInteraction object to be used when the connection or certificate
383    * database need to interact with the user. This will be used to prompt the
384    * user for passwords or certificate where necessary.
385    *
386    * Since: 1.8
387    */
388   g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION,
389       g_param_spec_object ("tls-interaction", "TLS interaction",
390           "A GTlsInteraction object to be used when the connection or certificate database need to interact with the user.",
391           G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
392
393  /**
394    * GstSoupHTTPSrc::retries:
395    *
396    * Maximum number of retries until giving up.
397    *
398    * Since: 1.4
399    */
400   g_object_class_install_property (gobject_class, PROP_RETRIES,
401       g_param_spec_int ("retries", "Retries",
402           "Maximum number of retries until giving up (-1=infinite)", -1,
403           G_MAXINT, DEFAULT_RETRIES,
404           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
405
406  /**
407    * GstSoupHTTPSrc::method
408    *
409    * The HTTP method to use when making a request
410    *
411    * Since: 1.6
412    */
413   g_object_class_install_property (gobject_class, PROP_METHOD,
414       g_param_spec_string ("method", "HTTP method",
415           "The HTTP method to use (GET, HEAD, OPTIONS, etc)",
416           DEFAULT_SOUP_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
417
418   gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
419
420   gst_element_class_set_static_metadata (gstelement_class, "HTTP client source",
421       "Source/Network",
422       "Receive data as a client over the network via HTTP using SOUP",
423       "Wouter Cloetens <wouter@mind.be>");
424   gstelement_class->change_state =
425       GST_DEBUG_FUNCPTR (gst_soup_http_src_change_state);
426   gstelement_class->set_context =
427       GST_DEBUG_FUNCPTR (gst_soup_http_src_set_context);
428
429   gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start);
430   gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop);
431   gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock);
432   gstbasesrc_class->unlock_stop =
433       GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop);
434   gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size);
435   gstbasesrc_class->is_seekable =
436       GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable);
437   gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek);
438   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query);
439
440   gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create);
441
442   GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0,
443       "SOUP HTTP src");
444 }
445
446 static void
447 gst_soup_http_src_reset (GstSoupHTTPSrc * src)
448 {
449   src->retry_count = 0;
450   src->have_size = FALSE;
451   src->got_headers = FALSE;
452   src->seekable = FALSE;
453   src->read_position = 0;
454   src->request_position = 0;
455   src->stop_position = -1;
456   src->content_size = 0;
457   src->have_body = FALSE;
458
459   src->reduce_blocksize_count = 0;
460   src->increase_blocksize_count = 0;
461   src->last_socket_read_time = 0;
462
463 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
464   if (src->dash_oldest_segment) {
465     g_free (src->dash_oldest_segment);
466     src->dash_oldest_segment = NULL;
467   }
468   if (src->dash_newest_segment) {
469     g_free (src->dash_newest_segment);
470     src->dash_newest_segment = NULL;
471   }
472   src->dlna_opt = 0;
473 #endif
474
475   g_cancellable_reset (src->cancellable);
476   g_mutex_lock (&src->mutex);
477   if (src->input_stream) {
478     g_object_unref (src->input_stream);
479     src->input_stream = NULL;
480   }
481   g_mutex_unlock (&src->mutex);
482
483   gst_caps_replace (&src->src_caps, NULL);
484   g_free (src->iradio_name);
485   src->iradio_name = NULL;
486   g_free (src->iradio_genre);
487   src->iradio_genre = NULL;
488   g_free (src->iradio_url);
489   src->iradio_url = NULL;
490 }
491
492 static void
493 gst_soup_http_src_init (GstSoupHTTPSrc * src)
494 {
495   const gchar *proxy;
496
497   g_mutex_init (&src->mutex);
498   g_cond_init (&src->have_headers_cond);
499   src->cancellable = g_cancellable_new ();
500   src->location = NULL;
501   src->redirection_uri = NULL;
502   src->automatic_redirect = TRUE;
503   src->user_agent = g_strdup (DEFAULT_USER_AGENT);
504   src->user_id = NULL;
505   src->user_pw = NULL;
506   src->proxy_id = NULL;
507   src->proxy_pw = NULL;
508   src->cookies = NULL;
509   src->iradio_mode = DEFAULT_IRADIO_MODE;
510   src->session = NULL;
511   src->external_session = NULL;
512   src->forced_external_session = FALSE;
513   src->msg = NULL;
514   src->timeout = DEFAULT_TIMEOUT;
515   src->log_level = DEFAULT_SOUP_LOG_LEVEL;
516   src->compress = DEFAULT_COMPRESS;
517   src->keep_alive = DEFAULT_KEEP_ALIVE;
518   src->ssl_strict = DEFAULT_SSL_STRICT;
519   src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
520   src->tls_database = DEFAULT_TLS_DATABASE;
521   src->tls_interaction = DEFAULT_TLS_INTERACTION;
522   src->max_retries = DEFAULT_RETRIES;
523   src->method = DEFAULT_SOUP_METHOD;
524   src->minimum_blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
525 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
526   src->dash_oldest_segment = NULL;
527   src->dash_newest_segment = NULL;
528   src->received_total = 0;
529   src->dlna_opt = 0;
530 #endif
531   proxy = g_getenv ("http_proxy");
532   if (!gst_soup_http_src_set_proxy (src, proxy)) {
533     GST_WARNING_OBJECT (src,
534         "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
535         proxy);
536   }
537 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
538   src->cookie_jar  = NULL;
539 #endif
540   gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
541
542   gst_soup_http_src_reset (src);
543 }
544
545 static void
546 gst_soup_http_src_dispose (GObject * gobject)
547 {
548   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
549
550   GST_DEBUG_OBJECT (src, "dispose");
551
552   gst_soup_http_src_session_close (src);
553
554   if (src->external_session) {
555     g_object_unref (src->external_session);
556     src->external_session = NULL;
557   }
558
559   G_OBJECT_CLASS (parent_class)->dispose (gobject);
560 }
561
562 static void
563 gst_soup_http_src_finalize (GObject * gobject)
564 {
565   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
566
567   GST_DEBUG_OBJECT (src, "finalize");
568
569   g_mutex_clear (&src->mutex);
570   g_cond_clear (&src->have_headers_cond);
571   g_object_unref (src->cancellable);
572   g_free (src->location);
573   g_free (src->redirection_uri);
574   g_free (src->user_agent);
575   if (src->proxy != NULL) {
576     soup_uri_free (src->proxy);
577   }
578   g_free (src->user_id);
579   g_free (src->user_pw);
580   g_free (src->proxy_id);
581   g_free (src->proxy_pw);
582   g_strfreev (src->cookies);
583
584   if (src->extra_headers) {
585     gst_structure_free (src->extra_headers);
586     src->extra_headers = NULL;
587   }
588
589   g_free (src->ssl_ca_file);
590
591   if (src->tls_database)
592     g_object_unref (src->tls_database);
593   g_free (src->method);
594
595   if (src->tls_interaction)
596     g_object_unref (src->tls_interaction);
597
598   G_OBJECT_CLASS (parent_class)->finalize (gobject);
599 }
600
601 static void
602 gst_soup_http_src_set_property (GObject * object, guint prop_id,
603     const GValue * value, GParamSpec * pspec)
604 {
605   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
606
607   switch (prop_id) {
608     case PROP_LOCATION:
609     {
610       const gchar *location;
611
612       location = g_value_get_string (value);
613
614       if (location == NULL) {
615         GST_WARNING ("location property cannot be NULL");
616         goto done;
617       }
618       if (!gst_soup_http_src_set_location (src, location, NULL)) {
619         GST_WARNING ("badly formatted location");
620         goto done;
621       }
622       break;
623     }
624     case PROP_USER_AGENT:
625       g_free (src->user_agent);
626       src->user_agent = g_value_dup_string (value);
627       break;
628     case PROP_IRADIO_MODE:
629       src->iradio_mode = g_value_get_boolean (value);
630       break;
631     case PROP_AUTOMATIC_REDIRECT:
632       src->automatic_redirect = g_value_get_boolean (value);
633       break;
634     case PROP_PROXY:
635     {
636       const gchar *proxy;
637
638       proxy = g_value_get_string (value);
639       if (!gst_soup_http_src_set_proxy (src, proxy)) {
640         GST_WARNING ("badly formatted proxy URI");
641         goto done;
642       }
643       break;
644     }
645     case PROP_COOKIES:
646 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
647     {
648       char **array;
649       SoupURI *base_uri;
650       SoupCookie *cookie_parsed = NULL;
651
652       g_strfreev (src->cookies);
653       src->cookies = g_strdupv (g_value_get_boxed (value));
654
655       if (src->cookie_jar && ((array = src->cookies) != NULL)) {
656         base_uri = soup_uri_new (src->location);
657         GST_INFO_OBJECT (src, "request to set cookies...");
658         while (*array != NULL) {
659           cookie_parsed = soup_cookie_parse (*array++, base_uri);
660           if (cookie_parsed && cookie_parsed->domain)
661             soup_cookie_jar_add_cookie (src->cookie_jar, cookie_parsed);
662         }
663         soup_uri_free (base_uri);
664       } else {
665         GST_INFO_OBJECT (src, "set cookies after session creation");
666       }
667     }
668 #else
669       g_strfreev (src->cookies);
670       src->cookies = g_strdupv (g_value_get_boxed (value));
671 #endif
672       break;
673     case PROP_IS_LIVE:
674       gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
675       break;
676     case PROP_USER_ID:
677       g_free (src->user_id);
678       src->user_id = g_value_dup_string (value);
679       break;
680     case PROP_USER_PW:
681       g_free (src->user_pw);
682       src->user_pw = g_value_dup_string (value);
683       break;
684     case PROP_PROXY_ID:
685       g_free (src->proxy_id);
686       src->proxy_id = g_value_dup_string (value);
687       break;
688     case PROP_PROXY_PW:
689       g_free (src->proxy_pw);
690       src->proxy_pw = g_value_dup_string (value);
691       break;
692     case PROP_TIMEOUT:
693       src->timeout = g_value_get_uint (value);
694       break;
695     case PROP_EXTRA_HEADERS:{
696       const GstStructure *s = gst_value_get_structure (value);
697
698       if (src->extra_headers)
699         gst_structure_free (src->extra_headers);
700
701       src->extra_headers = s ? gst_structure_copy (s) : NULL;
702       break;
703     }
704     case PROP_SOUP_LOG_LEVEL:
705       src->log_level = g_value_get_enum (value);
706       break;
707     case PROP_COMPRESS:
708       src->compress = g_value_get_boolean (value);
709       break;
710     case PROP_KEEP_ALIVE:
711       src->keep_alive = g_value_get_boolean (value);
712       break;
713     case PROP_SSL_STRICT:
714       src->ssl_strict = g_value_get_boolean (value);
715       break;
716     case PROP_SSL_CA_FILE:
717       g_free (src->ssl_ca_file);
718       src->ssl_ca_file = g_value_dup_string (value);
719       break;
720     case PROP_SSL_USE_SYSTEM_CA_FILE:
721       src->ssl_use_system_ca_file = g_value_get_boolean (value);
722       break;
723     case PROP_TLS_DATABASE:
724       g_clear_object (&src->tls_database);
725       src->tls_database = g_value_dup_object (value);
726       break;
727     case PROP_TLS_INTERACTION:
728       g_clear_object (&src->tls_interaction);
729       src->tls_interaction = g_value_dup_object (value);
730       break;
731     case PROP_RETRIES:
732       src->max_retries = g_value_get_int (value);
733       break;
734     case PROP_METHOD:
735       g_free (src->method);
736       src->method = g_value_dup_string (value);
737       break;
738     default:
739       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
740       break;
741   }
742 done:
743   return;
744 }
745
746 static void
747 gst_soup_http_src_get_property (GObject * object, guint prop_id,
748     GValue * value, GParamSpec * pspec)
749 {
750   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
751
752   switch (prop_id) {
753     case PROP_LOCATION:
754       g_value_set_string (value, src->location);
755       break;
756     case PROP_USER_AGENT:
757       g_value_set_string (value, src->user_agent);
758       break;
759     case PROP_AUTOMATIC_REDIRECT:
760       g_value_set_boolean (value, src->automatic_redirect);
761       break;
762     case PROP_PROXY:
763       if (src->proxy == NULL)
764         g_value_set_static_string (value, "");
765       else {
766         char *proxy = soup_uri_to_string (src->proxy, FALSE);
767
768         g_value_set_string (value, proxy);
769         g_free (proxy);
770       }
771       break;
772     case PROP_COOKIES:
773 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
774     {
775         GSList *cookie_list, *c;
776         gchar **cookies, **array;
777
778         cookies = NULL;
779         if ((src->cookie_jar) &&
780             ((cookie_list = soup_cookie_jar_all_cookies (src->cookie_jar)) != NULL)) {
781           cookies = g_new0 (gchar *, g_slist_length(cookie_list) + 1);
782           array = cookies;
783           for (c = cookie_list; c; c = c->next) {
784             *array++ = soup_cookie_to_set_cookie_header ((SoupCookie *)(c->data));
785           }
786           soup_cookies_free (cookie_list);
787         }
788         g_value_set_boxed (value, cookies);
789     }
790 #else
791         g_value_set_boxed (value, g_strdupv (src->cookies));
792 #endif
793       break;
794     case PROP_IS_LIVE:
795       g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
796       break;
797     case PROP_IRADIO_MODE:
798       g_value_set_boolean (value, src->iradio_mode);
799       break;
800     case PROP_USER_ID:
801       g_value_set_string (value, src->user_id);
802       break;
803     case PROP_USER_PW:
804       g_value_set_string (value, src->user_pw);
805       break;
806     case PROP_PROXY_ID:
807       g_value_set_string (value, src->proxy_id);
808       break;
809     case PROP_PROXY_PW:
810       g_value_set_string (value, src->proxy_pw);
811       break;
812     case PROP_TIMEOUT:
813       g_value_set_uint (value, src->timeout);
814       break;
815     case PROP_EXTRA_HEADERS:
816       gst_value_set_structure (value, src->extra_headers);
817       break;
818     case PROP_SOUP_LOG_LEVEL:
819       g_value_set_enum (value, src->log_level);
820       break;
821     case PROP_COMPRESS:
822       g_value_set_boolean (value, src->compress);
823       break;
824     case PROP_KEEP_ALIVE:
825       g_value_set_boolean (value, src->keep_alive);
826       break;
827     case PROP_SSL_STRICT:
828       g_value_set_boolean (value, src->ssl_strict);
829       break;
830     case PROP_SSL_CA_FILE:
831       g_value_set_string (value, src->ssl_ca_file);
832       break;
833     case PROP_SSL_USE_SYSTEM_CA_FILE:
834       g_value_set_boolean (value, src->ssl_use_system_ca_file);
835       break;
836     case PROP_TLS_DATABASE:
837       g_value_set_object (value, src->tls_database);
838       break;
839     case PROP_TLS_INTERACTION:
840       g_value_set_object (value, src->tls_interaction);
841       break;
842     case PROP_RETRIES:
843       g_value_set_int (value, src->max_retries);
844       break;
845     case PROP_METHOD:
846       g_value_set_string (value, src->method);
847       break;
848     default:
849       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
850       break;
851   }
852 }
853
854 static gchar *
855 gst_soup_http_src_unicodify (const gchar * str)
856 {
857   const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
858     "GST_TAG_ENCODING", NULL
859   };
860
861   return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
862 }
863
864 static void
865 gst_soup_http_src_cancel_message (GstSoupHTTPSrc * src)
866 {
867   g_cancellable_cancel (src->cancellable);
868   g_cond_signal (&src->have_headers_cond);
869 }
870
871 static gboolean
872 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
873     guint64 stop_offset)
874 {
875   gchar buf[64];
876   gint rc;
877
878   soup_message_headers_remove (src->msg->request_headers, "Range");
879
880 /* This changes are needed to enable Seekable Contents from server.
881    We have observed that , for few specific networks ( VODAFONE ) , without theabove headers ,
882    Youtube is sending non-seekable contents to the Client. */
883 #ifndef TIZEN_FEATURE_SOUP_MODIFICATION
884   if (offset || stop_offset != -1)
885 #endif
886   {
887     if (stop_offset != -1) {
888       g_assert (offset != stop_offset);
889
890       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
891           G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 :
892           stop_offset);
893     } else {
894       rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
895           offset);
896     }
897     if (rc > sizeof (buf) || rc < 0)
898       return FALSE;
899     soup_message_headers_append (src->msg->request_headers, "Range", buf);
900   }
901   src->read_position = offset;
902   return TRUE;
903 }
904
905 static gboolean
906 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
907 {
908   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
909   const gchar *field_name = g_quark_to_string (field_id);
910   gchar *field_content = NULL;
911
912   if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
913     field_content = g_value_dup_string (value);
914   } else {
915     GValue dest = { 0, };
916
917     g_value_init (&dest, G_TYPE_STRING);
918     if (g_value_transform (value, &dest)) {
919       field_content = g_value_dup_string (&dest);
920     }
921   }
922
923   if (field_content == NULL) {
924     GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
925         "or can't be converted to a string", field_name);
926     return FALSE;
927   }
928
929   GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
930       field_content);
931   soup_message_headers_append (src->msg->request_headers, field_name,
932       field_content);
933
934 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
935   if (!g_ascii_strcasecmp(field_name, "Cookie")) {
936     SoupURI *uri = NULL;
937     SoupCookie *cookie_parsed = NULL;
938     gchar *saveptr = NULL;
939
940     if (strlen(field_content) > 0) {
941       gchar *tmp_field = NULL;
942
943       uri = soup_uri_new (src->location);
944
945       tmp_field = strtok_r (field_content, ";", &saveptr);
946
947       while (tmp_field != NULL) {
948         GST_DEBUG_OBJECT (src, "field_content = %s", tmp_field);
949
950         cookie_parsed = soup_cookie_parse(tmp_field, uri);
951         GST_DEBUG_OBJECT (src, "cookie parsed = %p", cookie_parsed);
952
953         if (src->cookie_jar && cookie_parsed && cookie_parsed->domain)
954           soup_cookie_jar_add_cookie (src->cookie_jar, cookie_parsed);
955
956         tmp_field = strtok_r (NULL, ";", &saveptr);
957       }
958       soup_uri_free (uri);
959     }
960   }
961 #endif
962
963   g_free (field_content);
964
965   return TRUE;
966 }
967
968 static gboolean
969 _append_extra_headers (GQuark field_id, const GValue * value,
970     gpointer user_data)
971 {
972   if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
973     guint n = gst_value_array_get_size (value);
974     guint i;
975
976     for (i = 0; i < n; i++) {
977       const GValue *v = gst_value_array_get_value (value, i);
978
979       if (!_append_extra_header (field_id, v, user_data))
980         return FALSE;
981     }
982   } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
983     guint n = gst_value_list_get_size (value);
984     guint i;
985
986     for (i = 0; i < n; i++) {
987       const GValue *v = gst_value_list_get_value (value, i);
988
989       if (!_append_extra_header (field_id, v, user_data))
990         return FALSE;
991     }
992   } else {
993     return _append_extra_header (field_id, value, user_data);
994   }
995
996   return TRUE;
997 }
998
999
1000 static gboolean
1001 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
1002 {
1003   if (!src->extra_headers)
1004     return TRUE;
1005
1006   return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
1007 }
1008
1009 static gboolean
1010 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
1011 {
1012   if (src->session) {
1013     GST_DEBUG_OBJECT (src, "Session is already open");
1014     return TRUE;
1015   }
1016
1017   if (!src->location) {
1018     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
1019         ("Missing location property"));
1020     return FALSE;
1021   }
1022
1023   if (!src->session) {
1024     GstQuery *query;
1025     gboolean can_share = (src->timeout == DEFAULT_TIMEOUT)
1026         && (src->ssl_strict == DEFAULT_SSL_STRICT)
1027         && (src->tls_interaction == NULL) && (src->proxy == NULL)
1028         && (src->tls_database == DEFAULT_TLS_DATABASE)
1029         && (src->ssl_ca_file == DEFAULT_SSL_CA_FILE)
1030         && (src->ssl_use_system_ca_file == DEFAULT_SSL_USE_SYSTEM_CA_FILE);
1031
1032     query = gst_query_new_context (GST_SOUP_SESSION_CONTEXT);
1033     if (gst_pad_peer_query (GST_BASE_SRC_PAD (src), query)) {
1034       GstContext *context;
1035
1036       gst_query_parse_context (query, &context);
1037       gst_element_set_context (GST_ELEMENT_CAST (src), context);
1038     } else {
1039       GstMessage *message;
1040
1041       message =
1042           gst_message_new_need_context (GST_OBJECT_CAST (src),
1043           GST_SOUP_SESSION_CONTEXT);
1044       gst_element_post_message (GST_ELEMENT_CAST (src), message);
1045     }
1046     gst_query_unref (query);
1047
1048     GST_OBJECT_LOCK (src);
1049     if (src->external_session && (can_share || src->forced_external_session)) {
1050       GST_DEBUG_OBJECT (src, "Using external session %p",
1051           src->external_session);
1052       src->session = g_object_ref (src->external_session);
1053       src->session_is_shared = TRUE;
1054     } else {
1055       GST_DEBUG_OBJECT (src, "Creating session (can share %d)", can_share);
1056
1057       /* We explicitly set User-Agent to NULL here and overwrite it per message
1058        * to be able to have the same session with different User-Agents per
1059        * source */
1060       if (src->proxy == NULL) {
1061         src->session =
1062             soup_session_new_with_options (SOUP_SESSION_USER_AGENT,
1063             NULL, SOUP_SESSION_TIMEOUT, src->timeout,
1064             SOUP_SESSION_SSL_STRICT, src->ssl_strict,
1065             SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
1066       } else {
1067         src->session =
1068             soup_session_new_with_options (SOUP_SESSION_PROXY_URI, src->proxy,
1069             SOUP_SESSION_TIMEOUT, src->timeout,
1070             SOUP_SESSION_SSL_STRICT, src->ssl_strict,
1071             SOUP_SESSION_USER_AGENT, NULL,
1072             SOUP_SESSION_TLS_INTERACTION, src->tls_interaction, NULL);
1073       }
1074
1075       if (src->session) {
1076         gst_soup_util_log_setup (src->session, src->log_level,
1077             GST_ELEMENT (src));
1078         soup_session_add_feature_by_type (src->session,
1079             SOUP_TYPE_CONTENT_DECODER);
1080         soup_session_add_feature_by_type (src->session, SOUP_TYPE_COOKIE_JAR);
1081
1082         if (can_share) {
1083           GstContext *context;
1084           GstMessage *message;
1085           GstStructure *s;
1086
1087           GST_DEBUG_OBJECT (src, "Sharing session %p", src->session);
1088           src->session_is_shared = TRUE;
1089
1090           /* Unset the limit the number of maximum allowed connection */
1091           g_object_set (src->session, SOUP_SESSION_MAX_CONNS, G_MAXINT,
1092               SOUP_SESSION_MAX_CONNS_PER_HOST, G_MAXINT, NULL);
1093
1094           context = gst_context_new (GST_SOUP_SESSION_CONTEXT, TRUE);
1095           s = gst_context_writable_structure (context);
1096           gst_structure_set (s, "session", SOUP_TYPE_SESSION, src->session,
1097               "force", G_TYPE_BOOLEAN, FALSE, NULL);
1098
1099           gst_object_ref (src->session);
1100           GST_OBJECT_UNLOCK (src);
1101           gst_element_set_context (GST_ELEMENT_CAST (src), context);
1102           message =
1103               gst_message_new_have_context (GST_OBJECT_CAST (src), context);
1104           gst_element_post_message (GST_ELEMENT_CAST (src), message);
1105           GST_OBJECT_LOCK (src);
1106           gst_object_unref (src->session);
1107         } else {
1108           src->session_is_shared = FALSE;
1109         }
1110       }
1111     }
1112
1113     if (!src->session) {
1114       GST_ELEMENT_ERROR (src, LIBRARY, INIT,
1115           (NULL), ("Failed to create session"));
1116       GST_OBJECT_UNLOCK (src);
1117       return FALSE;
1118     }
1119
1120 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1121     {
1122       char **array = NULL;
1123       SoupURI *base_uri;
1124       SoupCookie *soup_cookie = NULL;
1125
1126       soup_session_add_feature_by_type (src->session, SOUP_TYPE_COOKIE_JAR);
1127       src->cookie_jar = SOUP_COOKIE_JAR (soup_session_get_feature (src->session, SOUP_TYPE_COOKIE_JAR));
1128       if ((array = src->cookies) != NULL) {
1129         base_uri = soup_uri_new (src->location);
1130         while (*array != NULL) {
1131           soup_cookie = soup_cookie_parse (*array++, base_uri);
1132           if (soup_cookie && soup_cookie->domain) {
1133             GST_INFO_OBJECT (src, "adding cookies..");
1134             soup_cookie_jar_add_cookie (src->cookie_jar, soup_cookie);
1135           }
1136         }
1137         soup_uri_free (base_uri);
1138       }
1139     }
1140 #endif
1141
1142     g_signal_connect (src->session, "authenticate",
1143         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
1144
1145     if (!src->session_is_shared) {
1146       if (src->tls_database)
1147         g_object_set (src->session, "tls-database", src->tls_database, NULL);
1148       else if (src->ssl_ca_file)
1149         g_object_set (src->session, "ssl-ca-file", src->ssl_ca_file, NULL);
1150       else
1151         g_object_set (src->session, "ssl-use-system-ca-file",
1152             src->ssl_use_system_ca_file, NULL);
1153     }
1154     GST_OBJECT_UNLOCK (src);
1155   } else {
1156     GST_DEBUG_OBJECT (src, "Re-using session");
1157   }
1158
1159   return TRUE;
1160 }
1161
1162 static void
1163 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
1164 {
1165   GST_DEBUG_OBJECT (src, "Closing session");
1166
1167   g_mutex_lock (&src->mutex);
1168   if (src->msg) {
1169     soup_session_cancel_message (src->session, src->msg, SOUP_STATUS_CANCELLED);
1170     g_object_unref (src->msg);
1171     src->msg = NULL;
1172   }
1173
1174   if (src->session) {
1175     if (!src->session_is_shared)
1176 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1177 /* When Playback is ongoing and Browser is moved to background ( Pressing Menu or Home Key ), The Session gets destroyed.
1178    But the cookie_jar property remains unfreed. This results in garbage pointer and causes crash.
1179    Removing the cookie_jar feature during close session of browser to handle the issue. */
1180     {
1181       GST_DEBUG_OBJECT (src, "Removing Cookie Jar instance");
1182       soup_session_remove_feature_by_type(src->session, SOUP_TYPE_COOKIE_JAR);
1183       src->cookie_jar = NULL;
1184           soup_session_abort (src->session);
1185     }
1186 #else
1187       soup_session_abort (src->session);
1188 #endif
1189     g_signal_handlers_disconnect_by_func (src->session,
1190         G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
1191     g_object_unref (src->session);
1192     src->session = NULL;
1193   }
1194
1195   g_mutex_unlock (&src->mutex);
1196 }
1197
1198 static void
1199 gst_soup_http_src_authenticate_cb (SoupSession * session, SoupMessage * msg,
1200     SoupAuth * auth, gboolean retrying, GstSoupHTTPSrc * src)
1201 {
1202   /* Might be from another user of the shared session */
1203   if (!GST_IS_SOUP_HTTP_SRC (src) || msg != src->msg)
1204     return;
1205
1206   if (!retrying) {
1207     /* First time authentication only, if we fail and are called again with retry true fall through */
1208     if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
1209       if (src->user_id && src->user_pw)
1210         soup_auth_authenticate (auth, src->user_id, src->user_pw);
1211     } else if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1212       if (src->proxy_id && src->proxy_pw)
1213         soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
1214     }
1215   }
1216 }
1217
1218 static void
1219 insert_http_header (const gchar * name, const gchar * value, gpointer user_data)
1220 {
1221   GstStructure *headers = user_data;
1222   const GValue *gv;
1223
1224   if (!g_utf8_validate (name, -1, NULL) || !g_utf8_validate (value, -1, NULL))
1225     return;
1226
1227   gv = gst_structure_get_value (headers, name);
1228   if (gv && GST_VALUE_HOLDS_ARRAY (gv)) {
1229     GValue v = G_VALUE_INIT;
1230
1231     g_value_init (&v, G_TYPE_STRING);
1232     g_value_set_string (&v, value);
1233     gst_value_array_append_value ((GValue *) gv, &v);
1234     g_value_unset (&v);
1235   } else if (gv && G_VALUE_HOLDS_STRING (gv)) {
1236     GValue arr = G_VALUE_INIT;
1237     GValue v = G_VALUE_INIT;
1238     const gchar *old_value = g_value_get_string (gv);
1239
1240     g_value_init (&arr, GST_TYPE_ARRAY);
1241     g_value_init (&v, G_TYPE_STRING);
1242     g_value_set_string (&v, old_value);
1243     gst_value_array_append_value (&arr, &v);
1244     g_value_set_string (&v, value);
1245     gst_value_array_append_value (&arr, &v);
1246
1247     gst_structure_set_value (headers, name, &arr);
1248     g_value_unset (&v);
1249     g_value_unset (&arr);
1250   } else {
1251     gst_structure_set (headers, name, G_TYPE_STRING, value, NULL);
1252   }
1253 }
1254
1255 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1256 static void
1257 gst_soup_http_src_headers_foreach (const gchar * name, const gchar * val,
1258     gpointer src)
1259 {
1260   GST_INFO_OBJECT (src, " %s: %s", name, val);
1261
1262   if (g_ascii_strcasecmp (name, "Set-Cookie") == 0) {
1263     if (val) {
1264       gboolean bret = FALSE;
1265       GstStructure *s = NULL;
1266       GstSoupHTTPSrc * tmp = src;
1267       SoupURI *uri;
1268
1269       uri =  soup_uri_new (tmp->location);
1270
1271       /* post current bandwith & uri to application */
1272       s = gst_structure_new ("cookies",
1273             "updated-cookie", G_TYPE_STRING, val,
1274             "updated-url", G_TYPE_STRING, tmp->location, NULL);
1275       bret = gst_element_post_message (GST_ELEMENT_CAST (src), gst_message_new_element (GST_OBJECT_CAST (src), s));
1276       soup_cookie_jar_set_cookie (tmp->cookie_jar,  uri, val);
1277       soup_uri_free (uri);
1278
1279       GST_INFO_OBJECT (src, "request url [%s], posted cookies [%s] msg and returned = %d", tmp->location, val, bret);
1280     }
1281   } else if (g_ascii_strcasecmp (name, "Dash-Oldest-Segment") == 0) {
1282     if (val) {
1283       GstSoupHTTPSrc * tmp = src;
1284       tmp->dash_oldest_segment = g_strdup (val);
1285       GST_INFO_OBJECT (src, "Dash-Oldest-Segment set as %s ", tmp->dash_oldest_segment);
1286     }
1287   } else if (g_ascii_strcasecmp (name, "Dash-Newest-Segment") == 0) {
1288     if (val) {
1289       GstSoupHTTPSrc * tmp = src;
1290       tmp->dash_newest_segment = g_strdup (val);
1291       GST_INFO_OBJECT (src, "Dash-Newest-Segment set as %s ", tmp->dash_newest_segment);
1292     }
1293   }
1294 }
1295 #endif
1296
1297 static GstFlowReturn
1298 gst_soup_http_src_got_headers (GstSoupHTTPSrc * src, SoupMessage * msg)
1299 {
1300   const char *value;
1301   GstTagList *tag_list;
1302   GstBaseSrc *basesrc;
1303   guint64 newsize;
1304   GHashTable *params = NULL;
1305   GstEvent *http_headers_event;
1306   GstStructure *http_headers, *headers;
1307   const gchar *accept_ranges;
1308 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1309   gint64 start = 0, stop = 0, total = 0;
1310 #endif
1311
1312   GST_INFO_OBJECT (src, "got headers : %d", msg->status_code);
1313 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1314   soup_message_headers_foreach (msg->response_headers,
1315       gst_soup_http_src_headers_foreach, src);
1316 #endif
1317   if (msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
1318       src->proxy_id && src->proxy_pw) {
1319     /* wait for authenticate callback */
1320     return GST_FLOW_OK;
1321   }
1322
1323   http_headers = gst_structure_new_empty ("http-headers");
1324   gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location,
1325       "http-status-code", G_TYPE_UINT, msg->status_code, NULL);
1326   if (src->redirection_uri)
1327     gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING,
1328         src->redirection_uri, NULL);
1329   headers = gst_structure_new_empty ("request-headers");
1330   soup_message_headers_foreach (msg->request_headers, insert_http_header,
1331       headers);
1332   gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
1333       headers, NULL);
1334   gst_structure_free (headers);
1335   headers = gst_structure_new_empty ("response-headers");
1336   soup_message_headers_foreach (msg->response_headers, insert_http_header,
1337       headers);
1338   gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
1339       headers, NULL);
1340   gst_structure_free (headers);
1341
1342   gst_element_post_message (GST_ELEMENT_CAST (src),
1343       gst_message_new_element (GST_OBJECT_CAST (src),
1344           gst_structure_copy (http_headers)));
1345
1346   if (msg->status_code == SOUP_STATUS_UNAUTHORIZED) {
1347     /* force an error */
1348     gst_structure_free (http_headers);
1349     return gst_soup_http_src_parse_status (msg, src);
1350   }
1351
1352   src->got_headers = TRUE;
1353   g_cond_broadcast (&src->have_headers_cond);
1354
1355   http_headers_event =
1356       gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
1357   gst_event_replace (&src->http_headers_event, http_headers_event);
1358   gst_event_unref (http_headers_event);
1359
1360 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1361   /* Parse DLNA OP CODE */
1362   if ((value = soup_message_headers_get_one
1363         (msg->response_headers, "contentFeatures.dlna.org")) != NULL) {
1364     gchar **token = NULL;
1365     gchar **ptr = NULL;
1366
1367     GST_DEBUG_OBJECT (src, "DLNA server response");
1368
1369     token = g_strsplit (value, ";", 0);
1370     for (ptr = token ; *ptr ; ptr++) {
1371       gchar *tmp = NULL;
1372       gchar *op_code = NULL;
1373
1374       if (!strlen (*ptr))
1375         continue;
1376
1377       tmp = g_ascii_strup (*ptr, strlen (*ptr));
1378       if (!strstr (tmp, "DLNA.ORG_OP")) {
1379         g_free (tmp);
1380         continue;
1381       }
1382
1383       g_free (tmp);
1384
1385       op_code = strchr (*ptr, '=');
1386       if (op_code) {
1387         op_code++;
1388
1389         src->dlna_opt = (atoi (op_code) / 10 << 1) | (atoi (op_code) % 10);
1390         GST_DEBUG_OBJECT (src, "dlna op code: %s (0x%X)", op_code, src->dlna_opt);
1391         break;
1392       }
1393     }
1394     g_strfreev (token);
1395   }
1396 #endif
1397
1398   /* Parse Content-Length. */
1399   if (soup_message_headers_get_encoding (msg->response_headers) ==
1400       SOUP_ENCODING_CONTENT_LENGTH) {
1401 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1402       if (msg->status_code == SOUP_STATUS_PARTIAL_CONTENT) {
1403         newsize = src->request_position +
1404             soup_message_headers_get_content_length (msg->response_headers);
1405       } else {
1406         if (soup_message_headers_get_content_range(msg->response_headers, &start, &stop, &total) && (total > 0)) {
1407           GST_DEBUG_OBJECT (src, "get range header : %" G_GINT64_FORMAT
1408                                   "~%" G_GINT64_FORMAT"/%"G_GINT64_FORMAT, start, stop, total);
1409           newsize = (guint64)total;
1410         } else {
1411           if ((src->have_size) && (src->content_size <= src->request_position)) {
1412             newsize = src->content_size;
1413           } else {
1414             newsize = soup_message_headers_get_content_length (msg->response_headers);
1415           }
1416         }
1417       }
1418 #else
1419       newsize = src->request_position +
1420           soup_message_headers_get_content_length (msg->response_headers);
1421 #endif
1422     if (!src->have_size || (src->content_size != newsize)) {
1423       src->content_size = newsize;
1424       src->have_size = TRUE;
1425       src->seekable = TRUE;
1426       GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
1427
1428       basesrc = GST_BASE_SRC_CAST (src);
1429       basesrc->segment.duration = src->content_size;
1430       gst_element_post_message (GST_ELEMENT (src),
1431           gst_message_new_duration_changed (GST_OBJECT (src)));
1432     }
1433   }
1434
1435   /* If the server reports Accept-Ranges: none we don't have to try
1436    * doing range requests at all
1437    */
1438   if ((accept_ranges =
1439           soup_message_headers_get_one (msg->response_headers,
1440               "Accept-Ranges"))) {
1441     if (g_ascii_strcasecmp (accept_ranges, "none") == 0)
1442       src->seekable = FALSE;
1443   }
1444 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1445   else if (src->dlna_opt & DLNA_OP_BYTE_SEEK) {
1446     if (src->have_size) {
1447       GST_DEBUG_OBJECT (src, "DLNA server is seekable");
1448       src->seekable = TRUE;
1449     }
1450   }
1451   /* The Range request header is always included.
1452    * @ref gst_soup_http_src_add_range_header() */
1453   else if ((msg->status_code == SOUP_STATUS_OK) &&
1454     (soup_message_headers_get_content_range (msg->response_headers, &start, &stop, &total) == FALSE)) {
1455     GST_DEBUG_OBJECT (src, "there is no accept range header");
1456     src->seekable = FALSE;
1457   }
1458 #endif
1459
1460   /* Icecast stuff */
1461   tag_list = gst_tag_list_new_empty ();
1462
1463   if ((value =
1464           soup_message_headers_get_one (msg->response_headers,
1465               "icy-metaint")) != NULL) {
1466     gint icy_metaint;
1467
1468     if (g_utf8_validate (value, -1, NULL)) {
1469       icy_metaint = atoi (value);
1470
1471       GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value,
1472           icy_metaint);
1473       if (icy_metaint > 0) {
1474         if (src->src_caps)
1475           gst_caps_unref (src->src_caps);
1476
1477         src->src_caps = gst_caps_new_simple ("application/x-icy",
1478             "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1479
1480         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1481       }
1482     }
1483   }
1484   if ((value =
1485           soup_message_headers_get_content_type (msg->response_headers,
1486               &params)) != NULL) {
1487     if (!g_utf8_validate (value, -1, NULL)) {
1488       GST_WARNING_OBJECT (src, "Content-Type is invalid UTF-8");
1489     } else if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1490       gint channels = 2;
1491       gint rate = 44100;
1492       char *param;
1493
1494       GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1495
1496       if (src->src_caps) {
1497         gst_caps_unref (src->src_caps);
1498         src->src_caps = NULL;
1499       }
1500
1501       param = g_hash_table_lookup (params, "channels");
1502       if (param != NULL) {
1503         guint64 val = g_ascii_strtoull (param, NULL, 10);
1504         if (val < 64)
1505           channels = val;
1506         else
1507           channels = 0;
1508       }
1509
1510       param = g_hash_table_lookup (params, "rate");
1511       if (param != NULL) {
1512         guint64 val = g_ascii_strtoull (param, NULL, 10);
1513         if (val < G_MAXINT)
1514           rate = val;
1515         else
1516           rate = 0;
1517       }
1518
1519       if (rate > 0 && channels > 0) {
1520         src->src_caps = gst_caps_new_simple ("audio/x-unaligned-raw",
1521             "format", G_TYPE_STRING, "S16BE",
1522             "layout", G_TYPE_STRING, "interleaved",
1523             "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1524
1525         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1526       }
1527     } else {
1528       GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1529
1530       /* Set the Content-Type field on the caps */
1531       if (src->src_caps) {
1532         src->src_caps = gst_caps_make_writable (src->src_caps);
1533         gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1534             value, NULL);
1535         gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1536       }
1537     }
1538   }
1539
1540   if (params != NULL)
1541     g_hash_table_destroy (params);
1542
1543   if ((value =
1544           soup_message_headers_get_one (msg->response_headers,
1545               "icy-name")) != NULL) {
1546     if (g_utf8_validate (value, -1, NULL)) {
1547       g_free (src->iradio_name);
1548       src->iradio_name = gst_soup_http_src_unicodify (value);
1549       if (src->iradio_name) {
1550         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1551             src->iradio_name, NULL);
1552       }
1553     }
1554   }
1555   if ((value =
1556           soup_message_headers_get_one (msg->response_headers,
1557               "icy-genre")) != NULL) {
1558     if (g_utf8_validate (value, -1, NULL)) {
1559       g_free (src->iradio_genre);
1560       src->iradio_genre = gst_soup_http_src_unicodify (value);
1561       if (src->iradio_genre) {
1562         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1563             src->iradio_genre, NULL);
1564       }
1565     }
1566   }
1567   if ((value = soup_message_headers_get_one (msg->response_headers, "icy-url"))
1568       != NULL) {
1569     if (g_utf8_validate (value, -1, NULL)) {
1570       g_free (src->iradio_url);
1571       src->iradio_url = gst_soup_http_src_unicodify (value);
1572       if (src->iradio_url) {
1573         gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1574             src->iradio_url, NULL);
1575       }
1576     }
1577   }
1578   if (!gst_tag_list_is_empty (tag_list)) {
1579     GST_DEBUG_OBJECT (src,
1580         "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1581     gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1582   } else {
1583     gst_tag_list_unref (tag_list);
1584   }
1585
1586   /* Handle HTTP errors. */
1587   return gst_soup_http_src_parse_status (msg, src);
1588 }
1589
1590 static GstBuffer *
1591 gst_soup_http_src_alloc_buffer (GstSoupHTTPSrc * src)
1592 {
1593   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1594   GstFlowReturn rc;
1595   GstBuffer *gstbuf;
1596
1597   rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1,
1598       basesrc->blocksize, &gstbuf);
1599   if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1600     return NULL;
1601   }
1602
1603   return gstbuf;
1604 }
1605
1606 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message)     \
1607   do { \
1608     GST_ELEMENT_ERROR_WITH_DETAILS ((src), cat, code, ("%s", error_message), \
1609         ("%s (%d), URL: %s, Redirect to: %s", (soup_msg)->reason_phrase, \
1610             (soup_msg)->status_code, (src)->location, GST_STR_NULL ((src)->redirection_uri)), \
1611             ("http-status-code", G_TYPE_UINT, (soup_msg)->status_code, \
1612              "http-redirect-uri", G_TYPE_STRING, GST_STR_NULL ((src)->redirection_uri), NULL)); \
1613   } while(0)
1614
1615 static GstFlowReturn
1616 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1617 {
1618   if (msg->method == SOUP_METHOD_HEAD) {
1619     if (!SOUP_STATUS_IS_SUCCESSFUL (msg->status_code))
1620       GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1621           msg->status_code);
1622     return GST_FLOW_OK;
1623   }
1624
1625   if (SOUP_STATUS_IS_TRANSPORT_ERROR (msg->status_code)) {
1626     switch (msg->status_code) {
1627       case SOUP_STATUS_CANT_RESOLVE:
1628       case SOUP_STATUS_CANT_RESOLVE_PROXY:
1629         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1630             _("Could not resolve server name."));
1631         return GST_FLOW_ERROR;
1632       case SOUP_STATUS_CANT_CONNECT:
1633       case SOUP_STATUS_CANT_CONNECT_PROXY:
1634         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1635             _("Could not establish connection to server."));
1636         return GST_FLOW_ERROR;
1637       case SOUP_STATUS_SSL_FAILED:
1638         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1639             _("Secure connection setup failed."));
1640         return GST_FLOW_ERROR;
1641       case SOUP_STATUS_IO_ERROR:
1642         if (src->max_retries == -1 || src->retry_count < src->max_retries)
1643           return GST_FLOW_CUSTOM_ERROR;
1644         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1645             _("A network error occurred, or the server closed the connection "
1646                 "unexpectedly."));
1647         return GST_FLOW_ERROR;
1648       case SOUP_STATUS_MALFORMED:
1649         SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1650             _("Server sent bad data."));
1651         return GST_FLOW_ERROR;
1652       case SOUP_STATUS_CANCELLED:
1653         /* No error message when interrupted by program. */
1654         break;
1655     }
1656     return GST_FLOW_OK;
1657   }
1658
1659   if (SOUP_STATUS_IS_CLIENT_ERROR (msg->status_code) ||
1660       SOUP_STATUS_IS_REDIRECTION (msg->status_code) ||
1661       SOUP_STATUS_IS_SERVER_ERROR (msg->status_code)) {
1662     const gchar *reason_phrase;
1663
1664     reason_phrase = msg->reason_phrase;
1665     if (reason_phrase && !g_utf8_validate (reason_phrase, -1, NULL)) {
1666       GST_ERROR_OBJECT (src, "Invalid UTF-8 in reason");
1667       reason_phrase = "(invalid)";
1668     }
1669
1670     /* Report HTTP error. */
1671
1672     /* when content_size is unknown and we have just finished receiving
1673      * a body message, requests that go beyond the content limits will result
1674      * in an error. Here we convert those to EOS */
1675 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1676     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1677         ((src->have_body && !src->have_size) ||
1678          (src->have_size && src->request_position >= src->content_size))) {
1679       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1680           "body, returning EOS");
1681       return GST_FLOW_EOS;
1682     }
1683 #else
1684     if (msg->status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1685         src->have_body && !src->have_size) {
1686       GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1687           "body, returning EOS");
1688       return GST_FLOW_EOS;
1689     }
1690 #endif
1691
1692     /* FIXME: reason_phrase is not translated and not suitable for user
1693      * error dialog according to libsoup documentation.
1694      */
1695     if (msg->status_code == SOUP_STATUS_NOT_FOUND) {
1696       SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND, (reason_phrase));
1697     } else if (msg->status_code == SOUP_STATUS_UNAUTHORIZED
1698         || msg->status_code == SOUP_STATUS_PAYMENT_REQUIRED
1699         || msg->status_code == SOUP_STATUS_FORBIDDEN
1700         || msg->status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1701       SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_AUTHORIZED, (reason_phrase));
1702     } else {
1703       SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, (reason_phrase));
1704     }
1705     return GST_FLOW_ERROR;
1706   }
1707
1708   return GST_FLOW_OK;
1709 }
1710
1711 static void
1712 gst_soup_http_src_restarted_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1713 {
1714   if (soup_session_would_redirect (src->session, msg)) {
1715     src->redirection_uri =
1716         soup_uri_to_string (soup_message_get_uri (msg), FALSE);
1717     src->redirection_permanent =
1718         (msg->status_code == SOUP_STATUS_MOVED_PERMANENTLY);
1719     GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)",
1720         msg->status_code, src->redirection_uri, src->redirection_permanent);
1721   }
1722 }
1723
1724 static gboolean
1725 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1726 {
1727   g_return_val_if_fail (src->msg == NULL, FALSE);
1728
1729   src->msg = soup_message_new (method, src->location);
1730   if (!src->msg) {
1731     GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1732         ("Error parsing URL."), ("URL: %s", src->location));
1733     return FALSE;
1734   }
1735
1736   /* Duplicating the defaults of libsoup here. We don't want to set a
1737    * User-Agent in the session as each source might have its own User-Agent
1738    * set */
1739   if (!src->user_agent || !*src->user_agent) {
1740     gchar *user_agent =
1741         g_strdup_printf ("libsoup/%u.%u.%u", soup_get_major_version (),
1742         soup_get_minor_version (), soup_get_micro_version ());
1743     soup_message_headers_append (src->msg->request_headers, "User-Agent",
1744         user_agent);
1745     g_free (user_agent);
1746   } else if (g_str_has_suffix (src->user_agent, " ")) {
1747     gchar *user_agent = g_strdup_printf ("%slibsoup/%u.%u.%u", src->user_agent,
1748         soup_get_major_version (),
1749         soup_get_minor_version (), soup_get_micro_version ());
1750     soup_message_headers_append (src->msg->request_headers, "User-Agent",
1751         user_agent);
1752     g_free (user_agent);
1753   } else {
1754     soup_message_headers_append (src->msg->request_headers, "User-Agent",
1755         src->user_agent);
1756   }
1757
1758   if (!src->keep_alive) {
1759     soup_message_headers_append (src->msg->request_headers, "Connection",
1760         "close");
1761   }
1762   if (src->iradio_mode) {
1763     soup_message_headers_append (src->msg->request_headers, "icy-metadata",
1764         "1");
1765   }
1766
1767 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1768 /* This changes are needed to enable Seekable Contents from server.
1769    We have observed that , for few specific networks ( VODAFONE ) , without theabove headers ,
1770    Youtube is sending non-seekable contents to the Client. */
1771   soup_message_headers_append (src->msg->request_headers, "Accept-Ranges","bytes");
1772
1773   if (src->cookie_jar) {
1774     GSList *cookie_list, *c;
1775     gchar *header;
1776
1777     SoupURI *uri = NULL;
1778     SoupCookie *cookie;
1779     uri = soup_uri_new (src->location);
1780
1781     if ((cookie_list = soup_cookie_jar_all_cookies (src->cookie_jar)) != NULL) {
1782       for (c = cookie_list; c; c = c->next) {
1783         cookie = (SoupCookie *)c->data;
1784         if (soup_cookie_applies_to_uri(cookie, uri)) {
1785           header = soup_cookie_to_cookie_header (cookie);
1786           soup_message_headers_append (src->msg->request_headers, "Cookie", header);
1787           g_free (header);
1788         }
1789       }
1790     }
1791     soup_cookies_free (cookie_list);
1792     soup_uri_free (uri);
1793   }
1794 #else
1795   if (src->cookies) {
1796     gchar **cookie;
1797
1798     for (cookie = src->cookies; *cookie != NULL; cookie++) {
1799       soup_message_headers_append (src->msg->request_headers, "Cookie",
1800           *cookie);
1801     }
1802   }
1803 #endif
1804
1805   if (!src->compress)
1806     soup_message_disable_feature (src->msg, SOUP_TYPE_CONTENT_DECODER);
1807
1808   soup_message_set_flags (src->msg, SOUP_MESSAGE_OVERWRITE_CHUNKS |
1809       (src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT));
1810
1811   if (src->automatic_redirect) {
1812     g_signal_connect (src->msg, "restarted",
1813         G_CALLBACK (gst_soup_http_src_restarted_cb), src);
1814   }
1815
1816   gst_soup_http_src_add_range_header (src, src->request_position,
1817       src->stop_position);
1818
1819   gst_soup_http_src_add_extra_headers (src);
1820
1821 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1822   soup_message_headers_foreach (src->msg->request_headers,
1823       gst_soup_http_src_headers_foreach, src);
1824 #endif
1825
1826   return TRUE;
1827 }
1828
1829 /* Lock taken */
1830 static GstFlowReturn
1831 gst_soup_http_src_send_message (GstSoupHTTPSrc * src)
1832 {
1833   GstFlowReturn ret;
1834   GError *error = NULL;
1835
1836   g_return_val_if_fail (src->msg != NULL, GST_FLOW_ERROR);
1837   g_assert (src->input_stream == NULL);
1838
1839   src->input_stream =
1840       soup_session_send (src->session, src->msg, src->cancellable, &error);
1841
1842   if (g_cancellable_is_cancelled (src->cancellable)) {
1843     ret = GST_FLOW_FLUSHING;
1844     goto done;
1845   }
1846
1847   ret = gst_soup_http_src_got_headers (src, src->msg);
1848   if (ret != GST_FLOW_OK) {
1849     goto done;
1850   }
1851
1852   if (!src->input_stream) {
1853     GST_DEBUG_OBJECT (src, "Didn't get an input stream: %s", error->message);
1854     ret = GST_FLOW_ERROR;
1855     goto done;
1856   }
1857
1858   if (SOUP_STATUS_IS_SUCCESSFUL (src->msg->status_code)) {
1859     GST_DEBUG_OBJECT (src, "Successfully got a reply");
1860   } else {
1861     /* FIXME - be more helpful to people debugging */
1862     ret = GST_FLOW_ERROR;
1863   }
1864
1865 done:
1866   if (error)
1867     g_error_free (error);
1868   return ret;
1869 }
1870
1871 static GstFlowReturn
1872 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method)
1873 {
1874   GstFlowReturn ret;
1875
1876   if (src->max_retries != -1 && src->retry_count > src->max_retries) {
1877     GST_DEBUG_OBJECT (src, "Max retries reached");
1878     return GST_FLOW_ERROR;
1879   }
1880
1881   src->retry_count++;
1882   /* EOS immediately if we have an empty segment */
1883   if (src->request_position == src->stop_position)
1884     return GST_FLOW_EOS;
1885
1886   GST_LOG_OBJECT (src, "Running request for method: %s", method);
1887
1888   /* Update the position if we are retrying */
1889   if (src->msg && src->request_position > 0) {
1890     gst_soup_http_src_add_range_header (src, src->request_position,
1891         src->stop_position);
1892   } else if (src->msg && src->request_position == 0)
1893     soup_message_headers_remove (src->msg->request_headers, "Range");
1894
1895   /* add_range_header() has the side effect of setting read_position to
1896    * the requested position. This *needs* to be set regardless of having
1897    * a message or not. Failure to do so would result in calculation being
1898    * done with stale/wrong read position */
1899   src->read_position = src->request_position;
1900
1901   if (!src->msg) {
1902     if (!gst_soup_http_src_build_message (src, method)) {
1903       return GST_FLOW_ERROR;
1904     }
1905   }
1906
1907   if (g_cancellable_is_cancelled (src->cancellable)) {
1908     GST_INFO_OBJECT (src, "interrupted");
1909     return GST_FLOW_FLUSHING;
1910   }
1911
1912   ret = gst_soup_http_src_send_message (src);
1913
1914   /* Check if Range header was respected. */
1915 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
1916   if (ret == GST_FLOW_OK && src->request_position > 0 &&
1917       (src->msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) &&
1918           (src->request_position < src->content_size)) {
1919 #else
1920   if (ret == GST_FLOW_OK && src->request_position > 0 &&
1921       src->msg->status_code != SOUP_STATUS_PARTIAL_CONTENT) {
1922 #endif
1923     src->seekable = FALSE;
1924     GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, SEEK,
1925         (_("Server does not support seeking.")),
1926         ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s",
1927             src->location, GST_STR_NULL (src->redirection_uri)),
1928         ("http-status-code", G_TYPE_UINT, src->msg->status_code,
1929             "http-redirection-uri", G_TYPE_STRING,
1930             GST_STR_NULL (src->redirection_uri), NULL));
1931     ret = GST_FLOW_ERROR;
1932   }
1933
1934   return ret;
1935 }
1936
1937 /*
1938  * Check if the bytes_read is above a certain threshold of the blocksize, if
1939  * that happens a few times in a row, increase the blocksize; Do the same in
1940  * the opposite direction to reduce the blocksize.
1941  */
1942 static void
1943 gst_soup_http_src_check_update_blocksize (GstSoupHTTPSrc * src,
1944     gint64 bytes_read)
1945 {
1946   guint blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
1947
1948   gint64 time_since_last_read =
1949       g_get_monotonic_time () * GST_USECOND - src->last_socket_read_time;
1950
1951   GST_LOG_OBJECT (src, "Checking to update blocksize. Read: %" G_GINT64_FORMAT
1952       " bytes, blocksize: %u bytes, time since last read: %" GST_TIME_FORMAT,
1953       bytes_read, blocksize, GST_TIME_ARGS (time_since_last_read));
1954
1955   if (bytes_read >= blocksize * GROW_BLOCKSIZE_LIMIT
1956       && time_since_last_read <= GROW_TIME_LIMIT) {
1957     src->reduce_blocksize_count = 0;
1958     src->increase_blocksize_count++;
1959
1960     if (src->increase_blocksize_count >= GROW_BLOCKSIZE_COUNT) {
1961       blocksize *= GROW_BLOCKSIZE_FACTOR;
1962       GST_DEBUG_OBJECT (src, "Increased blocksize to %u", blocksize);
1963       gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
1964       src->increase_blocksize_count = 0;
1965     }
1966   } else if (bytes_read < blocksize * REDUCE_BLOCKSIZE_LIMIT
1967       || time_since_last_read > GROW_TIME_LIMIT) {
1968     src->reduce_blocksize_count++;
1969     src->increase_blocksize_count = 0;
1970
1971     if (src->reduce_blocksize_count >= REDUCE_BLOCKSIZE_COUNT) {
1972       blocksize *= REDUCE_BLOCKSIZE_FACTOR;
1973       blocksize = MAX (blocksize, src->minimum_blocksize);
1974       GST_DEBUG_OBJECT (src, "Decreased blocksize to %u", blocksize);
1975       gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
1976       src->reduce_blocksize_count = 0;
1977     }
1978   } else {
1979     src->reduce_blocksize_count = src->increase_blocksize_count = 0;
1980   }
1981 }
1982
1983 static void
1984 gst_soup_http_src_update_position (GstSoupHTTPSrc * src, gint64 bytes_read)
1985 {
1986   GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1987   guint64 new_position;
1988
1989   new_position = src->read_position + bytes_read;
1990   if (G_LIKELY (src->request_position == src->read_position))
1991     src->request_position = new_position;
1992   src->read_position = new_position;
1993
1994   if (src->have_size) {
1995     if (new_position > src->content_size) {
1996       GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
1997           "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
1998           src->content_size);
1999       src->content_size = new_position;
2000       basesrc->segment.duration = src->content_size;
2001       gst_element_post_message (GST_ELEMENT (src),
2002           gst_message_new_duration_changed (GST_OBJECT (src)));
2003     } else if (new_position == src->content_size) {
2004       GST_DEBUG_OBJECT (src, "We're EOS now");
2005     }
2006   }
2007 }
2008
2009 static GstFlowReturn
2010 gst_soup_http_src_read_buffer (GstSoupHTTPSrc * src, GstBuffer ** outbuf)
2011 {
2012   gssize read_bytes;
2013   GstMapInfo mapinfo;
2014   GstBaseSrc *bsrc;
2015   GstFlowReturn ret;
2016
2017   bsrc = GST_BASE_SRC_CAST (src);
2018
2019   *outbuf = gst_soup_http_src_alloc_buffer (src);
2020   if (!*outbuf) {
2021     GST_WARNING_OBJECT (src, "Failed to allocate buffer");
2022     return GST_FLOW_ERROR;
2023   }
2024
2025   if (!gst_buffer_map (*outbuf, &mapinfo, GST_MAP_WRITE)) {
2026     GST_WARNING_OBJECT (src, "Failed to map buffer");
2027     return GST_FLOW_ERROR;
2028   }
2029
2030   read_bytes =
2031       g_input_stream_read (src->input_stream, mapinfo.data, mapinfo.size,
2032       src->cancellable, NULL);
2033   GST_DEBUG_OBJECT (src, "Read %" G_GSSIZE_FORMAT " bytes from http input",
2034       read_bytes);
2035
2036   g_mutex_lock (&src->mutex);
2037   if (g_cancellable_is_cancelled (src->cancellable)) {
2038     gst_buffer_unmap (*outbuf, &mapinfo);
2039     gst_buffer_unref (*outbuf);
2040     g_mutex_unlock (&src->mutex);
2041     return GST_FLOW_FLUSHING;
2042   }
2043
2044   gst_buffer_unmap (*outbuf, &mapinfo);
2045   if (read_bytes > 0) {
2046     gst_buffer_set_size (*outbuf, read_bytes);
2047     GST_BUFFER_OFFSET (*outbuf) = bsrc->segment.position;
2048     ret = GST_FLOW_OK;
2049     gst_soup_http_src_update_position (src, read_bytes);
2050 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
2051     src->received_total += read_bytes;
2052 #endif
2053
2054     /* Got some data, reset retry counter */
2055     src->retry_count = 0;
2056
2057     gst_soup_http_src_check_update_blocksize (src, read_bytes);
2058
2059     src->last_socket_read_time = g_get_monotonic_time () * GST_USECOND;
2060
2061     /* If we're at the end of a range request, read again to let libsoup
2062      * finalize the request. This allows to reuse the connection again later,
2063      * otherwise we would have to cancel the message and close the connection
2064      */
2065     if (bsrc->segment.stop != -1
2066         && bsrc->segment.position + read_bytes >= bsrc->segment.stop) {
2067       guint8 tmp[128];
2068
2069       g_object_unref (src->msg);
2070       src->msg = NULL;
2071       src->have_body = TRUE;
2072
2073       /* This should return immediately as we're at the end of the range */
2074       read_bytes =
2075           g_input_stream_read (src->input_stream, tmp, sizeof (tmp),
2076           src->cancellable, NULL);
2077       if (read_bytes > 0)
2078         GST_ERROR_OBJECT (src,
2079             "Read %" G_GSIZE_FORMAT " bytes after end of range", read_bytes);
2080     }
2081   } else {
2082     gst_buffer_unref (*outbuf);
2083     if (read_bytes < 0 ||
2084         (src->have_size && src->read_position < src->content_size)) {
2085       /* Maybe the server disconnected, retry */
2086       ret = GST_FLOW_CUSTOM_ERROR;
2087     } else {
2088       g_object_unref (src->msg);
2089       src->msg = NULL;
2090       ret = GST_FLOW_EOS;
2091       src->have_body = TRUE;
2092     }
2093   }
2094   g_mutex_unlock (&src->mutex);
2095
2096   return ret;
2097 }
2098
2099 static GstFlowReturn
2100 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
2101 {
2102   GstSoupHTTPSrc *src;
2103   GstFlowReturn ret = GST_FLOW_OK;
2104   GstEvent *http_headers_event = NULL;
2105
2106   src = GST_SOUP_HTTP_SRC (psrc);
2107
2108 retry:
2109   g_mutex_lock (&src->mutex);
2110
2111   /* Check for pending position change */
2112   if (src->request_position != src->read_position) {
2113     if (src->input_stream) {
2114       g_input_stream_close (src->input_stream, src->cancellable, NULL);
2115       g_object_unref (src->input_stream);
2116       src->input_stream = NULL;
2117     }
2118   }
2119
2120   if (g_cancellable_is_cancelled (src->cancellable)) {
2121     ret = GST_FLOW_FLUSHING;
2122     g_mutex_unlock (&src->mutex);
2123     goto done;
2124   }
2125
2126   /* If we have no open connection to the server, start one */
2127   if (!src->input_stream) {
2128     *outbuf = NULL;
2129     ret =
2130         gst_soup_http_src_do_request (src,
2131         src->method ? src->method : SOUP_METHOD_GET);
2132     http_headers_event = src->http_headers_event;
2133     src->http_headers_event = NULL;
2134   }
2135   g_mutex_unlock (&src->mutex);
2136
2137   if (ret == GST_FLOW_OK || ret == GST_FLOW_CUSTOM_ERROR) {
2138     if (http_headers_event) {
2139       gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event);
2140       http_headers_event = NULL;
2141     }
2142   }
2143
2144   if (ret == GST_FLOW_OK)
2145     ret = gst_soup_http_src_read_buffer (src, outbuf);
2146
2147 done:
2148   GST_DEBUG_OBJECT (src, "Returning %d %s", ret, gst_flow_get_name (ret));
2149   if (ret != GST_FLOW_OK) {
2150     if (http_headers_event)
2151       gst_event_unref (http_headers_event);
2152
2153     g_mutex_lock (&src->mutex);
2154     if (src->input_stream) {
2155       g_object_unref (src->input_stream);
2156       src->input_stream = NULL;
2157     }
2158     g_mutex_unlock (&src->mutex);
2159     if (ret == GST_FLOW_CUSTOM_ERROR) {
2160       ret = GST_FLOW_OK;
2161       goto retry;
2162     }
2163   }
2164
2165   if (ret == GST_FLOW_FLUSHING) {
2166     g_mutex_lock (&src->mutex);
2167     src->retry_count = 0;
2168     g_mutex_unlock (&src->mutex);
2169   }
2170
2171   return ret;
2172 }
2173
2174 static gboolean
2175 gst_soup_http_src_start (GstBaseSrc * bsrc)
2176 {
2177   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2178
2179   GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
2180
2181 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
2182   if (src->dash_oldest_segment) {
2183     g_free (src->dash_oldest_segment);
2184     src->dash_oldest_segment = NULL;
2185   }
2186   if (src->dash_newest_segment) {
2187     g_free (src->dash_newest_segment);
2188     src->dash_newest_segment = NULL;
2189   }
2190 #endif
2191   return gst_soup_http_src_session_open (src);
2192 }
2193
2194 static gboolean
2195 gst_soup_http_src_stop (GstBaseSrc * bsrc)
2196 {
2197   GstSoupHTTPSrc *src;
2198
2199   src = GST_SOUP_HTTP_SRC (bsrc);
2200   GST_DEBUG_OBJECT (src, "stop()");
2201   if (src->keep_alive && !src->msg && !src->session_is_shared)
2202     gst_soup_http_src_cancel_message (src);
2203   else
2204     gst_soup_http_src_session_close (src);
2205
2206   gst_soup_http_src_reset (src);
2207   return TRUE;
2208 }
2209
2210 static GstStateChangeReturn
2211 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
2212 {
2213   GstStateChangeReturn ret;
2214   GstSoupHTTPSrc *src;
2215
2216   src = GST_SOUP_HTTP_SRC (element);
2217
2218   switch (transition) {
2219 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
2220     case GST_STATE_CHANGE_PAUSED_TO_READY:
2221       GST_WARNING_OBJECT (src, "Last read pos"
2222             ": %" G_GINT64_FORMAT ", received total : %" G_GINT64_FORMAT,
2223             src->read_position, src->received_total);
2224       break;
2225 #endif
2226     case GST_STATE_CHANGE_READY_TO_NULL:
2227       gst_soup_http_src_session_close (src);
2228       break;
2229     default:
2230       break;
2231   }
2232
2233   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2234
2235   return ret;
2236 }
2237
2238 static void
2239 gst_soup_http_src_set_context (GstElement * element, GstContext * context)
2240 {
2241   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (element);
2242
2243   if (g_strcmp0 (gst_context_get_context_type (context),
2244           GST_SOUP_SESSION_CONTEXT) == 0) {
2245     const GstStructure *s = gst_context_get_structure (context);
2246
2247     GST_OBJECT_LOCK (src);
2248     if (src->external_session)
2249       g_object_unref (src->external_session);
2250     src->external_session = NULL;
2251     gst_structure_get (s, "session", SOUP_TYPE_SESSION, &src->external_session,
2252         NULL);
2253     src->forced_external_session = FALSE;
2254     gst_structure_get (s, "force", G_TYPE_BOOLEAN,
2255         &src->forced_external_session, NULL);
2256
2257     GST_DEBUG_OBJECT (src, "Setting external session %p (force: %d)",
2258         src->external_session, src->forced_external_session);
2259     GST_OBJECT_UNLOCK (src);
2260   }
2261
2262   GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
2263 }
2264
2265 /* Interrupt a blocking request. */
2266 static gboolean
2267 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
2268 {
2269   GstSoupHTTPSrc *src;
2270
2271   src = GST_SOUP_HTTP_SRC (bsrc);
2272   GST_DEBUG_OBJECT (src, "unlock()");
2273
2274   gst_soup_http_src_cancel_message (src);
2275   return TRUE;
2276 }
2277
2278 /* Interrupt interrupt. */
2279 static gboolean
2280 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
2281 {
2282   GstSoupHTTPSrc *src;
2283
2284   src = GST_SOUP_HTTP_SRC (bsrc);
2285   GST_DEBUG_OBJECT (src, "unlock_stop()");
2286
2287   g_cancellable_reset (src->cancellable);
2288   return TRUE;
2289 }
2290
2291 static gboolean
2292 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
2293 {
2294   GstSoupHTTPSrc *src;
2295
2296   src = GST_SOUP_HTTP_SRC (bsrc);
2297
2298   if (src->have_size) {
2299     GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
2300         src->content_size);
2301     *size = src->content_size;
2302     return TRUE;
2303   }
2304   GST_DEBUG_OBJECT (src, "get_size() = FALSE");
2305   return FALSE;
2306 }
2307
2308 static void
2309 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
2310 {
2311   GstFlowReturn ret = GST_FLOW_OK;
2312
2313   /* Special case to check if the server allows range requests
2314    * before really starting to get data in the buffer creation
2315    * loops.
2316    */
2317   if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
2318     g_mutex_lock (&src->mutex);
2319     while (!src->got_headers && !g_cancellable_is_cancelled (src->cancellable)
2320         && ret == GST_FLOW_OK) {
2321       if ((src->msg && src->msg->method != SOUP_METHOD_HEAD)) {
2322         /* wait for the current request to finish */
2323         g_cond_wait (&src->have_headers_cond, &src->mutex);
2324       } else {
2325         if (gst_soup_http_src_session_open (src)) {
2326           ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD);
2327         }
2328       }
2329     }
2330     g_mutex_unlock (&src->mutex);
2331   }
2332 }
2333
2334 static gboolean
2335 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
2336 {
2337   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2338
2339   gst_soup_http_src_check_seekable (src);
2340
2341   return src->seekable;
2342 }
2343
2344 static gboolean
2345 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
2346 {
2347   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2348
2349   GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
2350       ")", segment->start, segment->stop);
2351   if (src->read_position == segment->start &&
2352       src->request_position == src->read_position &&
2353       src->stop_position == segment->stop) {
2354     GST_DEBUG_OBJECT (src,
2355         "Seek to current read/end position and no seek pending");
2356     return TRUE;
2357   }
2358
2359   gst_soup_http_src_check_seekable (src);
2360
2361   /* If we have no headers we don't know yet if it is seekable or not.
2362    * Store the start position and error out later if it isn't */
2363   if (src->got_headers && !src->seekable) {
2364     GST_WARNING_OBJECT (src, "Not seekable");
2365     return FALSE;
2366   }
2367
2368   if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
2369     GST_WARNING_OBJECT (src, "Invalid seek segment");
2370     return FALSE;
2371   }
2372
2373   if (src->have_size && segment->start >= src->content_size) {
2374     GST_WARNING_OBJECT (src,
2375         "Potentially seeking behind end of file, might EOS immediately");
2376   }
2377
2378   /* Wait for create() to handle the jump in offset. */
2379   src->request_position = segment->start;
2380   src->stop_position = segment->stop;
2381
2382   return TRUE;
2383 }
2384
2385 static gboolean
2386 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
2387 {
2388   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2389   gboolean ret;
2390   GstSchedulingFlags flags;
2391   gint minsize, maxsize, align;
2392
2393   switch (GST_QUERY_TYPE (query)) {
2394     case GST_QUERY_URI:
2395       gst_query_set_uri (query, src->location);
2396       if (src->redirection_uri != NULL) {
2397         gst_query_set_uri_redirection (query, src->redirection_uri);
2398         gst_query_set_uri_redirection_permanent (query,
2399             src->redirection_permanent);
2400       }
2401       ret = TRUE;
2402       break;
2403     default:
2404       ret = FALSE;
2405       break;
2406   }
2407
2408   if (!ret)
2409     ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
2410
2411   switch (GST_QUERY_TYPE (query)) {
2412     case GST_QUERY_SCHEDULING:
2413       gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
2414       flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
2415
2416 #ifdef TIZEN_FEATURE_SOUP_MODIFICATION
2417       if (gst_soup_http_src_is_seekable(bsrc)) {
2418           GST_DEBUG_OBJECT (src, "set seekable flag");
2419           flags |= GST_SCHEDULING_FLAG_SEEKABLE;
2420       }
2421 #endif
2422       gst_query_set_scheduling (query, flags, minsize, maxsize, align);
2423       break;
2424     default:
2425       break;
2426   }
2427
2428   return ret;
2429 }
2430
2431 static gboolean
2432 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
2433     GError ** error)
2434 {
2435   const char *alt_schemes[] = { "icy://", "icyx://" };
2436   guint i;
2437
2438   if (src->location) {
2439     g_free (src->location);
2440     src->location = NULL;
2441   }
2442
2443   if (uri == NULL)
2444     return FALSE;
2445
2446   for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
2447     if (g_str_has_prefix (uri, alt_schemes[i])) {
2448       src->location =
2449           g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
2450       return TRUE;
2451     }
2452   }
2453
2454   if (src->redirection_uri) {
2455     g_free (src->redirection_uri);
2456     src->redirection_uri = NULL;
2457   }
2458
2459   src->location = g_strdup (uri);
2460
2461   return TRUE;
2462 }
2463
2464 static gboolean
2465 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
2466 {
2467   if (src->proxy) {
2468     soup_uri_free (src->proxy);
2469     src->proxy = NULL;
2470   }
2471
2472   if (uri == NULL || *uri == '\0')
2473     return TRUE;
2474
2475   if (g_strstr_len (uri, -1, "://")) {
2476     src->proxy = soup_uri_new (uri);
2477   } else {
2478     gchar *new_uri = g_strconcat ("http://", uri, NULL);
2479
2480     src->proxy = soup_uri_new (new_uri);
2481     g_free (new_uri);
2482   }
2483
2484   return (src->proxy != NULL);
2485 }
2486
2487 static GstURIType
2488 gst_soup_http_src_uri_get_type (GType type)
2489 {
2490   return GST_URI_SRC;
2491 }
2492
2493 static const gchar *const *
2494 gst_soup_http_src_uri_get_protocols (GType type)
2495 {
2496   static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
2497
2498   return protocols;
2499 }
2500
2501 static gchar *
2502 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
2503 {
2504   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2505
2506   /* FIXME: make thread-safe */
2507   return g_strdup (src->location);
2508 }
2509
2510 static gboolean
2511 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
2512     GError ** error)
2513 {
2514   GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2515
2516   return gst_soup_http_src_set_location (src, uri, error);
2517 }
2518
2519 static void
2520 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
2521 {
2522   GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
2523
2524   iface->get_type = gst_soup_http_src_uri_get_type;
2525   iface->get_protocols = gst_soup_http_src_uri_get_protocols;
2526   iface->get_uri = gst_soup_http_src_uri_get_uri;
2527   iface->set_uri = gst_soup_http_src_uri_set_uri;
2528 }