2 * Copyright (C) 2007-2008 Wouter Cloetens <wouter@mind.be>
3 * Copyright (C) 2021 Igalia S.L.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more
17 * SECTION:element-souphttpsrc
20 * This plugin reads data from a remote location specified by a URI.
21 * Supported protocols are 'http', 'https'.
23 * An HTTP proxy must be specified by its URL.
24 * If the "http_proxy" environment variable is set, its value is used.
25 * If built with libsoup's GNOME integration features, the GNOME proxy
26 * configuration will be used, or failing that, proxy autodetection.
27 * The #GstSoupHTTPSrc:proxy property can be used to override the default.
29 * In case the #GstSoupHTTPSrc:iradio-mode property is set and the location is
30 * an HTTP resource, souphttpsrc will send special Icecast HTTP headers to the
31 * server to request additional Icecast meta-information.
32 * If the server is not an Icecast server, it will behave as if the
33 * #GstSoupHTTPSrc:iradio-mode property were not set. If it is, souphttpsrc will
34 * output data with a media type of application/x-icy, in which case you will
35 * need to use the #GstICYDemux element as follow-up element to extract the Icecast
36 * metadata and to determine the underlying media type.
38 * ## Example launch line
40 * gst-launch-1.0 -v souphttpsrc location=https://some.server.org/index.html
41 * ! filesink location=/home/joe/server.html
42 * ]| The above pipeline reads a web page from a server using the HTTPS protocol
43 * and writes it to a local file.
45 * gst-launch-1.0 -v souphttpsrc user-agent="FooPlayer 0.99 beta"
46 * automatic-redirect=false proxy=http://proxy.intranet.local:8080
47 * location=http://music.foobar.com/demo.mp3 ! mpgaudioparse
48 * ! mpg123audiodec ! audioconvert ! audioresample ! autoaudiosink
49 * ]| The above pipeline will read and decode and play an mp3 file from a
50 * web server using the HTTP protocol. If the server sends redirects,
51 * the request fails instead of following the redirect. The specified
52 * HTTP proxy server is used. The User-Agent HTTP request header
53 * is set to a custom string instead of "GStreamer souphttpsrc."
55 * gst-launch-1.0 -v souphttpsrc location=http://10.11.12.13/mjpeg
56 * do-timestamp=true ! multipartdemux
57 * ! image/jpeg,width=640,height=480 ! matroskamux
58 * ! filesink location=mjpeg.mkv
59 * ]| The above pipeline reads a motion JPEG stream from an IP camera
60 * using the HTTP protocol, encoded as mime/multipart image/jpeg
61 * parts, and writes a Matroska motion JPEG file. The width and
62 * height properties are set in the caps to provide the Matroska
63 * multiplexer with the information to set this in the header.
64 * Timestamps are set on the buffers as they arrive from the camera.
65 * These are used by the mime/multipart demultiplexer to emit timestamps
66 * on the JPEG-encoded video frame buffers. This allows the Matroska
67 * multiplexer to timestamp the frames in the resulting file.
77 #include <stdlib.h> /* atoi() */
79 #include <gst/gstelement.h>
80 #include <glib/gi18n-lib.h>
81 #include "gstsoupelements.h"
82 #include "gstsouphttpsrc.h"
83 #include "gstsouputils.h"
85 #include <gst/tag/tag.h>
87 /* this is a simple wrapper class around SoupSession; it exists in order to
88 * have a refcountable owner for the actual SoupSession + the thread it runs
89 * in and its main loop (we cannot inverse the ownership hierarchy, because
90 * the thread + loop are actually longer lived than the session)
92 * it is entirely private to this implementation
95 #define GST_TYPE_SOUP_SESSION (gst_soup_session_get_type())
96 #define GST_SOUP_SESSION(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), GST_TYPE_SOUP_SESSION, GstSoupSession))
97 #define gst_soup_session_parent_class session_parent_class
99 GType gst_soup_session_get_type (void);
101 typedef struct _GstSoupSessionClass GstSoupSessionClass;
103 struct _GstSoupSession
105 GObject parent_instance;
107 SoupSession *session;
112 struct _GstSoupSessionClass
114 GObjectClass parent_class;
117 G_DEFINE_TYPE (GstSoupSession, gst_soup_session, G_TYPE_OBJECT);
120 gst_soup_session_init (GstSoupSession * sess)
125 _soup_session_finalize_cb (gpointer user_data)
127 GstSoupSession *sess = user_data;
129 g_main_loop_quit (sess->loop);
135 gst_soup_session_finalize (GObject * obj)
137 GstSoupSession *sess = GST_SOUP_SESSION (obj);
140 /* handle disposing of failure cases */
145 src = g_idle_source_new ();
147 g_source_set_callback (src, _soup_session_finalize_cb, sess, NULL);
148 g_source_attach (src, g_main_loop_get_context (sess->loop));
149 g_source_unref (src);
151 /* finish off thread and the loop; ensure it's not from the thread */
152 g_assert (!g_main_context_is_owner (g_main_loop_get_context (sess->loop)));
153 g_thread_join (sess->thread);
154 g_main_loop_unref (sess->loop);
156 G_OBJECT_CLASS (session_parent_class)->finalize (obj);
160 gst_soup_session_class_init (GstSoupSessionClass * klass)
162 GObjectClass *gclass = G_OBJECT_CLASS (klass);
164 gclass->finalize = gst_soup_session_finalize;
167 GST_DEBUG_CATEGORY_STATIC (souphttpsrc_debug);
168 #define GST_CAT_DEFAULT souphttpsrc_debug
170 #define GST_SOUP_SESSION_CONTEXT "gst.soup.session"
172 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
175 GST_STATIC_CAPS_ANY);
183 PROP_AUTOMATIC_REDIRECT,
198 PROP_SSL_USE_SYSTEM_CA_FILE,
202 PROP_TLS_INTERACTION,
205 #define DEFAULT_USER_AGENT "GStreamer souphttpsrc " PACKAGE_VERSION " "
206 #define DEFAULT_IRADIO_MODE TRUE
207 #define DEFAULT_SOUP_LOG_LEVEL SOUP_LOGGER_LOG_HEADERS
208 #define DEFAULT_COMPRESS FALSE
209 #define DEFAULT_KEEP_ALIVE TRUE
210 #define DEFAULT_SSL_STRICT TRUE
211 #define DEFAULT_SSL_CA_FILE NULL
212 #define DEFAULT_SSL_USE_SYSTEM_CA_FILE TRUE
213 #define DEFAULT_TLS_DATABASE NULL
214 #define DEFAULT_TLS_INTERACTION NULL
215 #define DEFAULT_TIMEOUT 15
216 #define DEFAULT_RETRIES 3
217 #define DEFAULT_SOUP_METHOD NULL
219 #define GROW_BLOCKSIZE_LIMIT 1
220 #define GROW_BLOCKSIZE_COUNT 1
221 #define GROW_BLOCKSIZE_FACTOR 2
222 #define REDUCE_BLOCKSIZE_LIMIT 0.20
223 #define REDUCE_BLOCKSIZE_COUNT 2
224 #define REDUCE_BLOCKSIZE_FACTOR 0.5
225 #define GROW_TIME_LIMIT (1 * GST_SECOND)
227 static void gst_soup_http_src_uri_handler_init (gpointer g_iface,
228 gpointer iface_data);
229 static void gst_soup_http_src_finalize (GObject * gobject);
230 static void gst_soup_http_src_dispose (GObject * gobject);
232 static void gst_soup_http_src_set_property (GObject * object, guint prop_id,
233 const GValue * value, GParamSpec * pspec);
234 static void gst_soup_http_src_get_property (GObject * object, guint prop_id,
235 GValue * value, GParamSpec * pspec);
237 static GstStateChangeReturn gst_soup_http_src_change_state (GstElement *
238 element, GstStateChange transition);
239 static void gst_soup_http_src_set_context (GstElement * element,
240 GstContext * context);
241 static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc,
242 GstBuffer ** outbuf);
243 static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc);
244 static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc);
245 static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size);
246 static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc);
247 static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc,
248 GstSegment * segment);
249 static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query);
250 static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc);
251 static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc);
252 static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src,
253 const gchar * uri, GError ** error);
254 static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src,
256 static char *gst_soup_http_src_unicodify (const char *str);
257 static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src,
258 const gchar * method);
259 static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src,
260 guint64 offset, guint64 stop_offset);
261 static gboolean gst_soup_http_src_session_open (GstSoupHTTPSrc * src);
262 static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src);
263 static GstFlowReturn gst_soup_http_src_parse_status (SoupMessage * msg,
264 GstSoupHTTPSrc * src);
265 static GstFlowReturn gst_soup_http_src_got_headers (GstSoupHTTPSrc * src,
267 static void gst_soup_http_src_authenticate_cb_2 (SoupSession *,
268 SoupMessage * msg, SoupAuth * auth, gboolean retrying, gpointer);
269 static gboolean gst_soup_http_src_authenticate_cb (SoupMessage * msg,
270 SoupAuth * auth, gboolean retrying, gpointer);
271 static gboolean gst_soup_http_src_accept_certificate_cb (SoupMessage * msg,
272 GTlsCertificate * tls_certificate, GTlsCertificateFlags tls_errors,
275 #define gst_soup_http_src_parent_class parent_class
276 G_DEFINE_TYPE_WITH_CODE (GstSoupHTTPSrc, gst_soup_http_src, GST_TYPE_PUSH_SRC,
277 G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
278 gst_soup_http_src_uri_handler_init));
280 static gboolean souphttpsrc_element_init (GstPlugin * plugin);
281 GST_ELEMENT_REGISTER_DEFINE_CUSTOM (souphttpsrc, souphttpsrc_element_init);
284 gst_soup_http_src_class_init (GstSoupHTTPSrcClass * klass)
286 GObjectClass *gobject_class;
287 GstElementClass *gstelement_class;
288 GstBaseSrcClass *gstbasesrc_class;
289 GstPushSrcClass *gstpushsrc_class;
291 gobject_class = (GObjectClass *) klass;
292 gstelement_class = (GstElementClass *) klass;
293 gstbasesrc_class = (GstBaseSrcClass *) klass;
294 gstpushsrc_class = (GstPushSrcClass *) klass;
296 gobject_class->set_property = gst_soup_http_src_set_property;
297 gobject_class->get_property = gst_soup_http_src_get_property;
298 gobject_class->finalize = gst_soup_http_src_finalize;
299 gobject_class->dispose = gst_soup_http_src_dispose;
301 g_object_class_install_property (gobject_class,
303 g_param_spec_string ("location", "Location",
304 "Location to read from", "",
305 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
306 g_object_class_install_property (gobject_class,
308 g_param_spec_string ("user-agent", "User-Agent",
309 "Value of the User-Agent HTTP request header field",
310 DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
311 g_object_class_install_property (gobject_class,
312 PROP_AUTOMATIC_REDIRECT,
313 g_param_spec_boolean ("automatic-redirect", "automatic-redirect",
314 "Automatically follow HTTP redirects (HTTP Status Code 3xx)",
315 TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
316 g_object_class_install_property (gobject_class,
318 g_param_spec_string ("proxy", "Proxy",
319 "HTTP proxy server URI", "",
320 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
321 g_object_class_install_property (gobject_class,
323 g_param_spec_string ("user-id", "user-id",
324 "HTTP location URI user id for authentication", "",
325 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
326 g_object_class_install_property (gobject_class, PROP_USER_PW,
327 g_param_spec_string ("user-pw", "user-pw",
328 "HTTP location URI user password for authentication", "",
329 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
330 g_object_class_install_property (gobject_class, PROP_PROXY_ID,
331 g_param_spec_string ("proxy-id", "proxy-id",
332 "HTTP proxy URI user id for authentication", "",
333 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
334 g_object_class_install_property (gobject_class, PROP_PROXY_PW,
335 g_param_spec_string ("proxy-pw", "proxy-pw",
336 "HTTP proxy URI user password for authentication", "",
337 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
338 g_object_class_install_property (gobject_class, PROP_COOKIES,
339 g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies",
340 G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
341 g_object_class_install_property (gobject_class, PROP_IS_LIVE,
342 g_param_spec_boolean ("is-live", "is-live", "Act like a live source",
343 FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
344 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
345 g_param_spec_uint ("timeout", "timeout",
346 "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0,
347 3600, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348 g_object_class_install_property (gobject_class, PROP_EXTRA_HEADERS,
349 g_param_spec_boxed ("extra-headers", "Extra Headers",
350 "Extra headers to append to the HTTP request",
351 GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
352 g_object_class_install_property (gobject_class, PROP_IRADIO_MODE,
353 g_param_spec_boolean ("iradio-mode", "iradio-mode",
354 "Enable internet radio mode (ask server to send shoutcast/icecast "
355 "metadata interleaved with the actual stream data)",
356 DEFAULT_IRADIO_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
359 * GstSoupHTTPSrc::http-log-level:
361 * If set and > 0, captures and dumps HTTP session data as
362 * log messages if log level >= GST_LEVEL_TRACE
366 g_object_class_install_property (gobject_class, PROP_SOUP_LOG_LEVEL,
367 g_param_spec_enum ("http-log-level", "HTTP log level",
368 "Set log level for soup's HTTP session log",
369 _soup_logger_log_level_get_type (),
370 DEFAULT_SOUP_LOG_LEVEL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
373 * GstSoupHTTPSrc::compress:
375 * If set to %TRUE, souphttpsrc will automatically handle gzip
376 * and deflate Content-Encodings. This does not make much difference
377 * and causes more load for normal media files, but makes a real
378 * difference in size for plaintext files.
382 g_object_class_install_property (gobject_class, PROP_COMPRESS,
383 g_param_spec_boolean ("compress", "Compress",
384 "Allow compressed content encodings",
385 DEFAULT_COMPRESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
388 * GstSoupHTTPSrc::keep-alive:
390 * If set to %TRUE, souphttpsrc will keep alive connections when being
391 * set to READY state and only will close connections when connecting
392 * to a different server or when going to NULL state..
396 g_object_class_install_property (gobject_class, PROP_KEEP_ALIVE,
397 g_param_spec_boolean ("keep-alive", "keep-alive",
398 "Use HTTP persistent connections", DEFAULT_KEEP_ALIVE,
399 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
402 * GstSoupHTTPSrc::ssl-strict:
404 * If set to %TRUE, souphttpsrc will reject all SSL certificates that
405 * are considered invalid.
409 g_object_class_install_property (gobject_class, PROP_SSL_STRICT,
410 g_param_spec_boolean ("ssl-strict", "SSL Strict",
411 "Strict SSL certificate checking", DEFAULT_SSL_STRICT,
412 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
415 * GstSoupHTTPSrc::ssl-ca-file:
417 * A SSL anchor CA file that should be used for checking certificates
418 * instead of the system CA file.
420 * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
421 * value will be ignored.
423 * Deprecated: Use #GstSoupHTTPSrc::tls-database property instead. This
424 * property is no-op when libsoup3 is being used at runtime.
428 g_object_class_install_property (gobject_class, PROP_SSL_CA_FILE,
429 g_param_spec_string ("ssl-ca-file", "SSL CA File",
430 "Location of a SSL anchor CA file to use", DEFAULT_SSL_CA_FILE,
431 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
434 * GstSoupHTTPSrc::ssl-use-system-ca-file:
436 * If set to %TRUE, souphttpsrc will use the system's CA file for
437 * checking certificates, unless #GstSoupHTTPSrc::ssl-ca-file or
438 * #GstSoupHTTPSrc::tls-database are non-%NULL.
440 * Deprecated: This property is no-op when libsoup3 is being used at runtime.
444 g_object_class_install_property (gobject_class, PROP_SSL_USE_SYSTEM_CA_FILE,
445 g_param_spec_boolean ("ssl-use-system-ca-file", "Use System CA File",
446 "Use system CA file", DEFAULT_SSL_USE_SYSTEM_CA_FILE,
447 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
450 * GstSoupHTTPSrc::tls-database:
452 * TLS database with anchor certificate authorities used to validate
453 * the server certificate.
455 * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
456 * and #GstSoupHTTPSrc::ssl-ca-file values will be ignored.
460 g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
461 g_param_spec_object ("tls-database", "TLS database",
462 "TLS database with anchor certificate authorities used to validate the server certificate",
463 G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
466 * GstSoupHTTPSrc::tls-interaction:
468 * A #GTlsInteraction object to be used when the connection or certificate
469 * database need to interact with the user. This will be used to prompt the
470 * user for passwords or certificate where necessary.
474 g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION,
475 g_param_spec_object ("tls-interaction", "TLS interaction",
476 "A GTlsInteraction object to be used when the connection or certificate database need to interact with the user.",
477 G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
480 * GstSoupHTTPSrc::retries:
482 * Maximum number of retries until giving up.
486 g_object_class_install_property (gobject_class, PROP_RETRIES,
487 g_param_spec_int ("retries", "Retries",
488 "Maximum number of retries until giving up (-1=infinite)", -1,
489 G_MAXINT, DEFAULT_RETRIES,
490 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
493 * GstSoupHTTPSrc::method
495 * The HTTP method to use when making a request
499 g_object_class_install_property (gobject_class, PROP_METHOD,
500 g_param_spec_string ("method", "HTTP method",
501 "The HTTP method to use (GET, HEAD, OPTIONS, etc)",
502 DEFAULT_SOUP_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
504 gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
506 gst_element_class_set_static_metadata (gstelement_class, "HTTP client source",
508 "Receive data as a client over the network via HTTP using SOUP",
509 "Wouter Cloetens <wouter@mind.be>");
510 gstelement_class->change_state =
511 GST_DEBUG_FUNCPTR (gst_soup_http_src_change_state);
512 gstelement_class->set_context =
513 GST_DEBUG_FUNCPTR (gst_soup_http_src_set_context);
515 gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start);
516 gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop);
517 gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock);
518 gstbasesrc_class->unlock_stop =
519 GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop);
520 gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size);
521 gstbasesrc_class->is_seekable =
522 GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable);
523 gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek);
524 gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query);
526 gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create);
530 gst_soup_http_src_reset (GstSoupHTTPSrc * src)
532 src->retry_count = 0;
533 src->have_size = FALSE;
534 src->got_headers = FALSE;
535 src->headers_ret = GST_FLOW_OK;
536 src->seekable = FALSE;
537 src->read_position = 0;
538 src->request_position = 0;
539 src->stop_position = -1;
540 src->content_size = 0;
541 src->have_body = FALSE;
543 src->reduce_blocksize_count = 0;
544 src->increase_blocksize_count = 0;
545 src->last_socket_read_time = 0;
547 g_cancellable_reset (src->cancellable);
549 gst_caps_replace (&src->src_caps, NULL);
550 g_free (src->iradio_name);
551 src->iradio_name = NULL;
552 g_free (src->iradio_genre);
553 src->iradio_genre = NULL;
554 g_free (src->iradio_url);
555 src->iradio_url = NULL;
559 gst_soup_http_src_init (GstSoupHTTPSrc * src)
563 g_mutex_init (&src->session_mutex);
564 g_cond_init (&src->session_cond);
565 src->cancellable = g_cancellable_new ();
566 src->location = NULL;
567 src->redirection_uri = NULL;
568 src->automatic_redirect = TRUE;
569 src->user_agent = g_strdup (DEFAULT_USER_AGENT);
572 src->proxy_id = NULL;
573 src->proxy_pw = NULL;
575 src->iradio_mode = DEFAULT_IRADIO_MODE;
577 src->external_session = NULL;
579 src->timeout = DEFAULT_TIMEOUT;
580 src->log_level = DEFAULT_SOUP_LOG_LEVEL;
581 src->compress = DEFAULT_COMPRESS;
582 src->keep_alive = DEFAULT_KEEP_ALIVE;
583 src->ssl_strict = DEFAULT_SSL_STRICT;
584 src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
585 src->tls_database = DEFAULT_TLS_DATABASE;
586 src->tls_interaction = DEFAULT_TLS_INTERACTION;
587 src->max_retries = DEFAULT_RETRIES;
588 src->method = DEFAULT_SOUP_METHOD;
589 src->minimum_blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
590 proxy = g_getenv ("http_proxy");
591 if (!gst_soup_http_src_set_proxy (src, proxy)) {
592 GST_WARNING_OBJECT (src,
593 "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
597 gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
599 gst_soup_http_src_reset (src);
603 gst_soup_http_src_dispose (GObject * gobject)
605 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
607 GST_DEBUG_OBJECT (src, "dispose");
609 gst_soup_http_src_session_close (src);
611 g_clear_object (&src->external_session);
613 G_OBJECT_CLASS (parent_class)->dispose (gobject);
617 gst_soup_http_src_finalize (GObject * gobject)
619 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
621 GST_DEBUG_OBJECT (src, "finalize");
623 g_mutex_clear (&src->session_mutex);
624 g_cond_clear (&src->session_cond);
625 g_object_unref (src->cancellable);
626 g_free (src->location);
627 g_free (src->redirection_uri);
628 g_free (src->user_agent);
629 if (src->proxy != NULL) {
630 gst_soup_uri_free (src->proxy);
632 g_free (src->user_id);
633 g_free (src->user_pw);
634 g_free (src->proxy_id);
635 g_free (src->proxy_pw);
636 g_strfreev (src->cookies);
638 if (src->extra_headers) {
639 gst_structure_free (src->extra_headers);
640 src->extra_headers = NULL;
643 g_free (src->ssl_ca_file);
645 if (src->tls_database)
646 g_object_unref (src->tls_database);
647 g_free (src->method);
649 if (src->tls_interaction)
650 g_object_unref (src->tls_interaction);
652 G_OBJECT_CLASS (parent_class)->finalize (gobject);
656 gst_soup_http_src_set_property (GObject * object, guint prop_id,
657 const GValue * value, GParamSpec * pspec)
659 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
664 const gchar *location;
666 location = g_value_get_string (value);
668 if (location == NULL) {
669 GST_WARNING ("location property cannot be NULL");
672 if (!gst_soup_http_src_set_location (src, location, NULL)) {
673 GST_WARNING ("badly formatted location");
678 case PROP_USER_AGENT:
679 g_free (src->user_agent);
680 src->user_agent = g_value_dup_string (value);
682 case PROP_IRADIO_MODE:
683 src->iradio_mode = g_value_get_boolean (value);
685 case PROP_AUTOMATIC_REDIRECT:
686 src->automatic_redirect = g_value_get_boolean (value);
692 proxy = g_value_get_string (value);
693 if (!gst_soup_http_src_set_proxy (src, proxy)) {
694 GST_WARNING ("badly formatted proxy URI");
700 g_strfreev (src->cookies);
701 src->cookies = g_strdupv (g_value_get_boxed (value));
704 gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
707 g_free (src->user_id);
708 src->user_id = g_value_dup_string (value);
711 g_free (src->user_pw);
712 src->user_pw = g_value_dup_string (value);
715 g_free (src->proxy_id);
716 src->proxy_id = g_value_dup_string (value);
719 g_free (src->proxy_pw);
720 src->proxy_pw = g_value_dup_string (value);
723 src->timeout = g_value_get_uint (value);
725 case PROP_EXTRA_HEADERS:{
726 const GstStructure *s = gst_value_get_structure (value);
728 if (src->extra_headers)
729 gst_structure_free (src->extra_headers);
731 src->extra_headers = s ? gst_structure_copy (s) : NULL;
734 case PROP_SOUP_LOG_LEVEL:
735 src->log_level = g_value_get_enum (value);
738 src->compress = g_value_get_boolean (value);
740 case PROP_KEEP_ALIVE:
741 src->keep_alive = g_value_get_boolean (value);
743 case PROP_SSL_STRICT:
744 src->ssl_strict = g_value_get_boolean (value);
746 case PROP_TLS_DATABASE:
747 g_clear_object (&src->tls_database);
748 src->tls_database = g_value_dup_object (value);
750 case PROP_TLS_INTERACTION:
751 g_clear_object (&src->tls_interaction);
752 src->tls_interaction = g_value_dup_object (value);
755 src->max_retries = g_value_get_int (value);
758 g_free (src->method);
759 src->method = g_value_dup_string (value);
761 case PROP_SSL_CA_FILE:
762 if (gst_soup_loader_get_api_version () == 2) {
763 g_free (src->ssl_ca_file);
764 src->ssl_ca_file = g_value_dup_string (value);
767 case PROP_SSL_USE_SYSTEM_CA_FILE:
768 if (gst_soup_loader_get_api_version () == 2) {
769 src->ssl_use_system_ca_file = g_value_get_boolean (value);
773 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
781 gst_soup_http_src_get_property (GObject * object, guint prop_id,
782 GValue * value, GParamSpec * pspec)
784 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
788 g_value_set_string (value, src->location);
790 case PROP_USER_AGENT:
791 g_value_set_string (value, src->user_agent);
793 case PROP_AUTOMATIC_REDIRECT:
794 g_value_set_boolean (value, src->automatic_redirect);
797 if (src->proxy == NULL)
798 g_value_set_static_string (value, "");
800 char *proxy = gst_soup_uri_to_string (src->proxy);
801 g_value_set_string (value, proxy);
806 g_value_set_boxed (value, g_strdupv (src->cookies));
809 g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
811 case PROP_IRADIO_MODE:
812 g_value_set_boolean (value, src->iradio_mode);
815 g_value_set_string (value, src->user_id);
818 g_value_set_string (value, src->user_pw);
821 g_value_set_string (value, src->proxy_id);
824 g_value_set_string (value, src->proxy_pw);
827 g_value_set_uint (value, src->timeout);
829 case PROP_EXTRA_HEADERS:
830 gst_value_set_structure (value, src->extra_headers);
832 case PROP_SOUP_LOG_LEVEL:
833 g_value_set_enum (value, src->log_level);
836 g_value_set_boolean (value, src->compress);
838 case PROP_KEEP_ALIVE:
839 g_value_set_boolean (value, src->keep_alive);
841 case PROP_SSL_STRICT:
842 g_value_set_boolean (value, src->ssl_strict);
844 case PROP_TLS_DATABASE:
845 g_value_set_object (value, src->tls_database);
847 case PROP_TLS_INTERACTION:
848 g_value_set_object (value, src->tls_interaction);
851 g_value_set_int (value, src->max_retries);
854 g_value_set_string (value, src->method);
856 case PROP_SSL_CA_FILE:
857 if (gst_soup_loader_get_api_version () == 2)
858 g_value_set_string (value, src->ssl_ca_file);
860 case PROP_SSL_USE_SYSTEM_CA_FILE:
861 if (gst_soup_loader_get_api_version () == 2)
862 g_value_set_boolean (value, src->ssl_use_system_ca_file);
865 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
871 gst_soup_http_src_unicodify (const gchar * str)
873 const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
874 "GST_TAG_ENCODING", NULL
877 return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
881 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
886 SoupMessageHeaders *request_headers =
887 _soup_message_get_request_headers (src->msg);
889 _soup_message_headers_remove (request_headers, "Range");
890 if (offset || stop_offset != -1) {
891 if (stop_offset != -1) {
892 g_assert (offset != stop_offset);
894 rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
895 G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 :
898 rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
901 if (rc > sizeof (buf) || rc < 0)
903 _soup_message_headers_append (request_headers, "Range", buf);
905 src->read_position = offset;
910 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
912 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (user_data);
913 const gchar *field_name = g_quark_to_string (field_id);
914 gchar *field_content = NULL;
915 SoupMessageHeaders *request_headers =
916 _soup_message_get_request_headers (src->msg);
918 if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
919 field_content = g_value_dup_string (value);
921 GValue dest = { 0, };
923 g_value_init (&dest, G_TYPE_STRING);
924 if (g_value_transform (value, &dest)) {
925 field_content = g_value_dup_string (&dest);
929 if (field_content == NULL) {
930 GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
931 "or can't be converted to a string", field_name);
935 GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
937 _soup_message_headers_append (request_headers, field_name, field_content);
939 g_free (field_content);
945 _append_extra_headers (GQuark field_id, const GValue * value,
948 if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
949 guint n = gst_value_array_get_size (value);
952 for (i = 0; i < n; i++) {
953 const GValue *v = gst_value_array_get_value (value, i);
955 if (!_append_extra_header (field_id, v, user_data))
958 } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
959 guint n = gst_value_list_get_size (value);
962 for (i = 0; i < n; i++) {
963 const GValue *v = gst_value_list_get_value (value, i);
965 if (!_append_extra_header (field_id, v, user_data))
969 return _append_extra_header (field_id, value, user_data);
977 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
979 if (!src->extra_headers)
982 return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
986 thread_func (gpointer user_data)
988 GstSoupHTTPSrc *src = user_data;
989 GstSoupSession *session = src->session;
992 GST_DEBUG_OBJECT (src, "thread start");
994 ctx = g_main_loop_get_context (session->loop);
996 g_main_context_push_thread_default (ctx);
998 /* We explicitly set User-Agent to NULL here and overwrite it per message
999 * to be able to have the same session with different User-Agents per
1002 _soup_session_new_with_options ("user-agent", NULL,
1003 "timeout", src->timeout, "tls-interaction", src->tls_interaction,
1004 /* Unset the limit the number of maximum allowed connections */
1005 "max-conns", src->session_is_shared ? G_MAXINT : 10,
1006 "max-conns-per-host", src->session_is_shared ? G_MAXINT : 2, NULL);
1007 g_assert (session->session);
1009 if (gst_soup_loader_get_api_version () == 3) {
1010 if (src->proxy != NULL) {
1011 GProxyResolver *proxy_resolver;
1012 char *proxy_string = gst_soup_uri_to_string (src->proxy);
1013 proxy_resolver = g_simple_proxy_resolver_new (proxy_string, NULL);
1014 g_free (proxy_string);
1015 g_object_set (src->session->session, "proxy-resolver", proxy_resolver,
1017 g_object_unref (proxy_resolver);
1019 #if !defined(STATIC_SOUP) || STATIC_SOUP == 2
1021 g_object_set (session->session, "ssl-strict", src->ssl_strict, NULL);
1022 if (src->proxy != NULL) {
1023 /* Need #if because there's no proxy->soup_uri when STATIC_SOUP == 3 */
1024 g_object_set (session->session, "proxy-uri", src->proxy->soup_uri, NULL);
1029 gst_soup_util_log_setup (session->session, src->log_level,
1030 G_OBJECT (session));
1031 if (gst_soup_loader_get_api_version () < 3) {
1032 _soup_session_add_feature_by_type (session->session,
1033 _soup_content_decoder_get_type ());
1035 _soup_session_add_feature_by_type (session->session,
1036 _soup_cookie_jar_get_type ());
1038 /* soup2: connect the authenticate handler for the src that spawned the
1039 * session (i.e. the first owner); other users of this session will connect
1040 * their own after fetching the external session; the callback will handle
1041 * this correctly (it checks if the message belongs to the current src
1042 * and exits early if it does not)
1044 if (gst_soup_loader_get_api_version () < 3) {
1045 g_signal_connect (session->session, "authenticate",
1046 G_CALLBACK (gst_soup_http_src_authenticate_cb_2), src);
1049 if (!src->session_is_shared) {
1050 if (src->tls_database)
1051 g_object_set (src->session->session, "tls-database", src->tls_database,
1053 else if (gst_soup_loader_get_api_version () == 2) {
1054 if (src->ssl_ca_file)
1055 g_object_set (src->session->session, "ssl-ca-file", src->ssl_ca_file,
1058 g_object_set (src->session->session, "ssl-use-system-ca-file",
1059 src->ssl_use_system_ca_file, NULL);
1063 /* Once the main loop is running, the source element that created this
1064 * session might disappear if the session is shared with other source
1069 g_main_loop_run (session->loop);
1071 /* Abort any pending operations on the session ... */
1072 _soup_session_abort (session->session);
1073 g_clear_object (&session->session);
1075 /* ... and iterate the main context until nothing is pending anymore */
1076 while (g_main_context_iteration (ctx, FALSE));
1078 g_main_context_pop_thread_default (ctx);
1080 GST_DEBUG_OBJECT (session, "thread stop");
1086 _session_ready_cb (gpointer user_data)
1088 GstSoupHTTPSrc *src = user_data;
1090 GST_DEBUG_OBJECT (src, "thread ready");
1092 g_mutex_lock (&src->session_mutex);
1093 g_cond_signal (&src->session_cond);
1094 g_mutex_unlock (&src->session_mutex);
1099 /* called with session_mutex taken */
1101 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
1107 GST_DEBUG_OBJECT (src, "Session is already open");
1111 if (!src->location) {
1112 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
1113 ("Missing location property"));
1117 can_share = (src->timeout == DEFAULT_TIMEOUT)
1118 && (src->cookies == NULL)
1119 && (src->ssl_strict == DEFAULT_SSL_STRICT)
1120 && (src->tls_interaction == NULL) && (src->proxy == NULL)
1121 && (src->tls_database == DEFAULT_TLS_DATABASE);
1123 if (gst_soup_loader_get_api_version () == 2)
1124 can_share = can_share && (src->ssl_ca_file == DEFAULT_SSL_CA_FILE) &&
1125 (src->ssl_use_system_ca_file == DEFAULT_SSL_USE_SYSTEM_CA_FILE);
1127 query = gst_query_new_context (GST_SOUP_SESSION_CONTEXT);
1128 if (gst_pad_peer_query (GST_BASE_SRC_PAD (src), query)) {
1129 GstContext *context;
1131 gst_query_parse_context (query, &context);
1132 gst_element_set_context (GST_ELEMENT_CAST (src), context);
1134 GstMessage *message;
1137 gst_message_new_need_context (GST_OBJECT_CAST (src),
1138 GST_SOUP_SESSION_CONTEXT);
1139 gst_element_post_message (GST_ELEMENT_CAST (src), message);
1141 gst_query_unref (query);
1143 GST_OBJECT_LOCK (src);
1145 src->session_is_shared = can_share;
1147 if (src->external_session && can_share) {
1148 GST_DEBUG_OBJECT (src, "Using external session %p", src->external_session);
1149 src->session = g_object_ref (src->external_session);
1150 /* for soup2, connect another authenticate handler; see thread_func */
1151 if (gst_soup_loader_get_api_version () < 3) {
1152 g_signal_connect (src->session->session, "authenticate",
1153 G_CALLBACK (gst_soup_http_src_authenticate_cb_2), src);
1159 GST_DEBUG_OBJECT (src, "Creating session (can share %d)", can_share);
1162 GST_SOUP_SESSION (g_object_new (GST_TYPE_SOUP_SESSION, NULL));
1164 GST_DEBUG_OBJECT (src, "Created session %p", src->session);
1166 ctx = g_main_context_new ();
1168 src->session->loop = g_main_loop_new (ctx, FALSE);
1169 /* now owned by the loop */
1170 g_main_context_unref (ctx);
1172 src->session->thread = g_thread_try_new ("souphttpsrc-thread",
1173 thread_func, src, NULL);
1175 if (!src->session->thread) {
1179 source = g_idle_source_new ();
1180 g_source_set_callback (source, _session_ready_cb, src, NULL);
1181 g_source_attach (source, ctx);
1182 g_source_unref (source);
1184 GST_DEBUG_OBJECT (src, "Waiting for thread to start...");
1185 while (!g_main_loop_is_running (src->session->loop))
1186 g_cond_wait (&src->session_cond, &src->session_mutex);
1187 GST_DEBUG_OBJECT (src, "Soup thread started");
1190 GST_OBJECT_UNLOCK (src);
1192 if (src->session_is_shared) {
1193 GstContext *context;
1194 GstMessage *message;
1197 GST_DEBUG_OBJECT (src->session, "Sharing session %p", src->session);
1199 context = gst_context_new (GST_SOUP_SESSION_CONTEXT, TRUE);
1200 s = gst_context_writable_structure (context);
1201 gst_structure_set (s, "session", GST_TYPE_SOUP_SESSION, src->session, NULL);
1203 gst_element_set_context (GST_ELEMENT_CAST (src), context);
1204 message = gst_message_new_have_context (GST_OBJECT_CAST (src), context);
1205 gst_element_post_message (GST_ELEMENT_CAST (src), message);
1211 g_clear_object (&src->session);
1212 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL), ("Failed to create session"));
1213 GST_OBJECT_UNLOCK (src);
1219 _session_close_cb (gpointer user_data)
1221 GstSoupHTTPSrc *src = user_data;
1224 gst_soup_session_cancel_message (src->session->session, src->msg,
1226 g_clear_object (&src->msg);
1229 /* there may be multiple of this callback attached to the session,
1230 * each with different data pointer; disconnect the one we are closing
1231 * the session for, leave the others alone
1233 g_signal_handlers_disconnect_by_func (src->session->session,
1234 G_CALLBACK (gst_soup_http_src_authenticate_cb_2), src);
1236 g_mutex_lock (&src->session_mutex);
1237 g_clear_object (&src->session);
1238 g_cond_signal (&src->session_cond);
1239 g_mutex_unlock (&src->session_mutex);
1245 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
1248 GstSoupSession *sess;
1250 GST_DEBUG_OBJECT (src, "Closing session");
1252 if (!src->session) {
1256 /* ensure _session_close_cb does not deadlock us */
1257 sess = g_object_ref (src->session);
1259 source = g_idle_source_new ();
1261 g_mutex_lock (&src->session_mutex);
1263 g_source_set_callback (source, _session_close_cb, src, NULL);
1264 g_source_attach (source, g_main_loop_get_context (src->session->loop));
1265 g_source_unref (source);
1267 while (src->session)
1268 g_cond_wait (&src->session_cond, &src->session_mutex);
1270 g_mutex_unlock (&src->session_mutex);
1272 /* finally dispose of our reference from the gst thread */
1273 g_object_unref (sess);
1277 gst_soup_http_src_authenticate_cb_2 (SoupSession * session, SoupMessage * msg,
1278 SoupAuth * auth, gboolean retrying, gpointer data)
1280 gst_soup_http_src_authenticate_cb (msg, auth, retrying, data);
1284 gst_soup_http_src_authenticate_cb (SoupMessage * msg, SoupAuth * auth,
1285 gboolean retrying, gpointer data)
1287 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (data);
1288 SoupStatus status_code;
1290 /* Might be from another user of the shared session */
1291 if (!GST_IS_SOUP_HTTP_SRC (src) || msg != src->msg)
1294 status_code = _soup_message_get_status (msg);
1297 /* First time authentication only, if we fail and are called again with
1298 * retry true fall through */
1299 if (status_code == SOUP_STATUS_UNAUTHORIZED) {
1300 if (src->user_id && src->user_pw) {
1301 _soup_auth_authenticate (auth, src->user_id, src->user_pw);
1303 } else if (status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1304 if (src->proxy_id && src->proxy_pw) {
1305 _soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
1314 gst_soup_http_src_accept_certificate_cb (SoupMessage * msg,
1315 GTlsCertificate * tls_certificate, GTlsCertificateFlags tls_errors,
1318 GstSoupHTTPSrc *src = user_data;
1320 /* Might be from another user of the shared session */
1321 if (!GST_IS_SOUP_HTTP_SRC (src) || msg != src->msg)
1324 /* Accept invalid certificates */
1325 if (!src->ssl_strict)
1332 insert_http_header (const gchar * name, const gchar * value, gpointer user_data)
1334 GstStructure *headers = user_data;
1337 if (!g_utf8_validate (name, -1, NULL) || !g_utf8_validate (value, -1, NULL))
1340 gv = gst_structure_get_value (headers, name);
1341 if (gv && GST_VALUE_HOLDS_ARRAY (gv)) {
1342 GValue v = G_VALUE_INIT;
1344 g_value_init (&v, G_TYPE_STRING);
1345 g_value_set_string (&v, value);
1346 gst_value_array_append_value ((GValue *) gv, &v);
1348 } else if (gv && G_VALUE_HOLDS_STRING (gv)) {
1349 GValue arr = G_VALUE_INIT;
1350 GValue v = G_VALUE_INIT;
1351 const gchar *old_value = g_value_get_string (gv);
1353 g_value_init (&arr, GST_TYPE_ARRAY);
1354 g_value_init (&v, G_TYPE_STRING);
1355 g_value_set_string (&v, old_value);
1356 gst_value_array_append_value (&arr, &v);
1357 g_value_set_string (&v, value);
1358 gst_value_array_append_value (&arr, &v);
1360 gst_structure_set_value (headers, name, &arr);
1362 g_value_unset (&arr);
1364 gst_structure_set (headers, name, G_TYPE_STRING, value, NULL);
1368 static GstFlowReturn
1369 gst_soup_http_src_got_headers (GstSoupHTTPSrc * src, SoupMessage * msg)
1372 GstTagList *tag_list;
1373 GstBaseSrc *basesrc;
1375 GHashTable *params = NULL;
1376 GstEvent *http_headers_event;
1377 GstStructure *http_headers, *headers;
1378 const gchar *accept_ranges;
1379 SoupMessageHeaders *request_headers = _soup_message_get_request_headers (msg);
1380 SoupMessageHeaders *response_headers =
1381 _soup_message_get_response_headers (msg);
1382 SoupStatus status_code = _soup_message_get_status (msg);
1384 GST_INFO_OBJECT (src, "got headers");
1386 if (status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
1387 src->proxy_id && src->proxy_pw) {
1388 /* wait for authenticate callback */
1392 http_headers = gst_structure_new_empty ("http-headers");
1393 gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location,
1394 "http-status-code", G_TYPE_UINT, status_code, NULL);
1395 if (src->redirection_uri)
1396 gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING,
1397 src->redirection_uri, NULL);
1398 headers = gst_structure_new_empty ("request-headers");
1399 _soup_message_headers_foreach (request_headers, insert_http_header, headers);
1400 gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
1402 gst_structure_free (headers);
1403 headers = gst_structure_new_empty ("response-headers");
1404 _soup_message_headers_foreach (response_headers, insert_http_header, headers);
1405 gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
1407 gst_structure_free (headers);
1409 gst_element_post_message (GST_ELEMENT_CAST (src),
1410 gst_message_new_element (GST_OBJECT_CAST (src),
1411 gst_structure_copy (http_headers)));
1413 if (status_code == SOUP_STATUS_UNAUTHORIZED) {
1414 /* force an error */
1415 gst_structure_free (http_headers);
1416 return gst_soup_http_src_parse_status (msg, src);
1419 src->got_headers = TRUE;
1421 http_headers_event =
1422 gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
1423 gst_event_replace (&src->http_headers_event, http_headers_event);
1424 gst_event_unref (http_headers_event);
1426 /* Parse Content-Length. */
1427 if (SOUP_STATUS_IS_SUCCESSFUL (status_code) &&
1428 (_soup_message_headers_get_encoding (response_headers) ==
1429 SOUP_ENCODING_CONTENT_LENGTH)) {
1430 newsize = src->request_position +
1431 _soup_message_headers_get_content_length (response_headers);
1432 if (!src->have_size || (src->content_size != newsize)) {
1433 src->content_size = newsize;
1434 src->have_size = TRUE;
1435 src->seekable = TRUE;
1436 GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
1438 basesrc = GST_BASE_SRC_CAST (src);
1439 basesrc->segment.duration = src->content_size;
1440 gst_element_post_message (GST_ELEMENT (src),
1441 gst_message_new_duration_changed (GST_OBJECT (src)));
1445 /* If the server reports Accept-Ranges: none we don't have to try
1446 * doing range requests at all
1448 if ((accept_ranges =
1449 _soup_message_headers_get_one (response_headers, "Accept-Ranges"))) {
1450 if (g_ascii_strcasecmp (accept_ranges, "none") == 0)
1451 src->seekable = FALSE;
1455 tag_list = gst_tag_list_new_empty ();
1458 _soup_message_headers_get_one (response_headers,
1459 "icy-metaint")) != NULL) {
1462 if (g_utf8_validate (value, -1, NULL)) {
1463 icy_metaint = atoi (value);
1465 GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value,
1467 if (icy_metaint > 0) {
1469 gst_caps_unref (src->src_caps);
1471 src->src_caps = gst_caps_new_simple ("application/x-icy",
1472 "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1474 gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1479 _soup_message_headers_get_content_type (response_headers,
1480 ¶ms)) != NULL) {
1481 if (!g_utf8_validate (value, -1, NULL)) {
1482 GST_WARNING_OBJECT (src, "Content-Type is invalid UTF-8");
1483 } else if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1488 GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1490 if (src->src_caps) {
1491 gst_caps_unref (src->src_caps);
1492 src->src_caps = NULL;
1495 param = g_hash_table_lookup (params, "channels");
1496 if (param != NULL) {
1497 guint64 val = g_ascii_strtoull (param, NULL, 10);
1504 param = g_hash_table_lookup (params, "rate");
1505 if (param != NULL) {
1506 guint64 val = g_ascii_strtoull (param, NULL, 10);
1513 if (rate > 0 && channels > 0) {
1514 src->src_caps = gst_caps_new_simple ("audio/x-unaligned-raw",
1515 "format", G_TYPE_STRING, "S16BE",
1516 "layout", G_TYPE_STRING, "interleaved",
1517 "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1519 gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1522 GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1524 /* Set the Content-Type field on the caps */
1525 if (src->src_caps) {
1526 src->src_caps = gst_caps_make_writable (src->src_caps);
1527 gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1529 gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1535 g_hash_table_destroy (params);
1538 _soup_message_headers_get_one (response_headers,
1539 "icy-name")) != NULL) {
1540 if (g_utf8_validate (value, -1, NULL)) {
1541 g_free (src->iradio_name);
1542 src->iradio_name = gst_soup_http_src_unicodify (value);
1543 if (src->iradio_name) {
1544 gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1545 src->iradio_name, NULL);
1550 _soup_message_headers_get_one (response_headers,
1551 "icy-genre")) != NULL) {
1552 if (g_utf8_validate (value, -1, NULL)) {
1553 g_free (src->iradio_genre);
1554 src->iradio_genre = gst_soup_http_src_unicodify (value);
1555 if (src->iradio_genre) {
1556 gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1557 src->iradio_genre, NULL);
1561 if ((value = _soup_message_headers_get_one (response_headers, "icy-url"))
1563 if (g_utf8_validate (value, -1, NULL)) {
1564 g_free (src->iradio_url);
1565 src->iradio_url = gst_soup_http_src_unicodify (value);
1566 if (src->iradio_url) {
1567 gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1568 src->iradio_url, NULL);
1572 if (!gst_tag_list_is_empty (tag_list)) {
1573 GST_DEBUG_OBJECT (src,
1574 "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1575 gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1577 gst_tag_list_unref (tag_list);
1580 /* Handle HTTP errors. */
1581 return gst_soup_http_src_parse_status (msg, src);
1585 gst_soup_http_src_alloc_buffer (GstSoupHTTPSrc * src)
1587 GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1591 rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1,
1592 basesrc->blocksize, &gstbuf);
1593 if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1600 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message) \
1602 GST_ELEMENT_ERROR_WITH_DETAILS ((src), cat, code, ("%s", error_message), \
1603 ("%s (%d), URL: %s, Redirect to: %s", _soup_message_get_reason_phrase (soup_msg), \
1604 _soup_message_get_status (soup_msg), (src)->location, GST_STR_NULL ((src)->redirection_uri)), \
1605 ("http-status-code", G_TYPE_UINT, _soup_message_get_status (soup_msg), \
1606 "http-redirect-uri", G_TYPE_STRING, GST_STR_NULL ((src)->redirection_uri), NULL)); \
1609 static GstFlowReturn
1610 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1612 SoupStatus status_code = _soup_message_get_status (msg);
1613 if (_soup_message_get_method (msg) == SOUP_METHOD_HEAD) {
1614 if (!SOUP_STATUS_IS_SUCCESSFUL (status_code))
1615 GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1620 /* SOUP_STATUS_IS_TRANSPORT_ERROR was replaced with GError in libsoup-3.0 */
1621 #if !defined(STATIC_SOUP) || STATIC_SOUP == 2
1622 if (SOUP_STATUS_IS_TRANSPORT_ERROR (status_code)) {
1623 switch (status_code) {
1624 case SOUP_STATUS_CANT_RESOLVE:
1625 case SOUP_STATUS_CANT_RESOLVE_PROXY:
1626 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1627 _("Could not resolve server name."));
1628 return GST_FLOW_ERROR;
1629 case SOUP_STATUS_CANT_CONNECT:
1630 case SOUP_STATUS_CANT_CONNECT_PROXY:
1631 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1632 _("Could not establish connection to server."));
1633 return GST_FLOW_ERROR;
1634 case SOUP_STATUS_SSL_FAILED:
1635 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1636 _("Secure connection setup failed."));
1637 return GST_FLOW_ERROR;
1638 case SOUP_STATUS_IO_ERROR:
1639 if (src->max_retries == -1 || src->retry_count < src->max_retries)
1640 return GST_FLOW_CUSTOM_ERROR;
1641 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1642 _("A network error occurred, or the server closed the connection "
1644 return GST_FLOW_ERROR;
1645 case SOUP_STATUS_MALFORMED:
1646 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1647 _("Server sent bad data."));
1648 return GST_FLOW_ERROR;
1649 case SOUP_STATUS_CANCELLED:
1650 /* No error message when interrupted by program. */
1659 if (SOUP_STATUS_IS_CLIENT_ERROR (status_code) ||
1660 SOUP_STATUS_IS_REDIRECTION (status_code) ||
1661 SOUP_STATUS_IS_SERVER_ERROR (status_code)) {
1662 const gchar *reason_phrase;
1664 reason_phrase = _soup_message_get_reason_phrase (msg);
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)";
1670 /* Report HTTP error. */
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 if (status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1676 src->have_body && (!src->have_size ||
1677 (src->request_position >= src->content_size))) {
1678 GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1679 "body, returning EOS");
1680 return GST_FLOW_EOS;
1683 /* FIXME: reason_phrase is not translated and not suitable for user
1684 * error dialog according to libsoup documentation.
1686 if (status_code == SOUP_STATUS_NOT_FOUND) {
1687 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND, (reason_phrase));
1688 } else if (status_code == SOUP_STATUS_UNAUTHORIZED
1689 || status_code == SOUP_STATUS_PAYMENT_REQUIRED
1690 || status_code == SOUP_STATUS_FORBIDDEN
1691 || status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1692 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_AUTHORIZED, (reason_phrase));
1694 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, (reason_phrase));
1696 return GST_FLOW_ERROR;
1703 gst_soup_http_src_restarted_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1705 SoupStatus status = _soup_message_get_status (msg);
1707 if (!SOUP_STATUS_IS_REDIRECTION (status))
1710 src->redirection_uri = gst_soup_message_uri_to_string (msg);
1711 src->redirection_permanent = (status == SOUP_STATUS_MOVED_PERMANENTLY);
1713 GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)",
1714 status, src->redirection_uri, src->redirection_permanent);
1718 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1720 SoupMessageHeaders *request_headers;
1722 g_return_val_if_fail (src->msg == NULL, FALSE);
1724 src->msg = _soup_message_new (method, src->location);
1726 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1727 ("Error parsing URL."), ("URL: %s", src->location));
1731 request_headers = _soup_message_get_request_headers (src->msg);
1733 /* Duplicating the defaults of libsoup here. We don't want to set a
1734 * User-Agent in the session as each source might have its own User-Agent
1736 if (!src->user_agent || !*src->user_agent) {
1738 g_strdup_printf ("libsoup/%u.%u.%u", _soup_get_major_version (),
1739 _soup_get_minor_version (), _soup_get_micro_version ());
1740 _soup_message_headers_append (request_headers, "User-Agent", user_agent);
1741 g_free (user_agent);
1742 } else if (g_str_has_suffix (src->user_agent, " ")) {
1743 gchar *user_agent = g_strdup_printf ("%slibsoup/%u.%u.%u", src->user_agent,
1744 _soup_get_major_version (),
1745 _soup_get_minor_version (), _soup_get_micro_version ());
1746 _soup_message_headers_append (request_headers, "User-Agent", user_agent);
1747 g_free (user_agent);
1749 _soup_message_headers_append (request_headers, "User-Agent",
1753 if (!src->keep_alive) {
1754 _soup_message_headers_append (request_headers, "Connection", "close");
1756 if (src->iradio_mode) {
1757 _soup_message_headers_append (request_headers, "icy-metadata", "1");
1762 for (cookie = src->cookies; *cookie != NULL; cookie++) {
1763 _soup_message_headers_append (request_headers, "Cookie", *cookie);
1766 _soup_message_disable_feature (src->msg, _soup_cookie_jar_get_type ());
1769 if (!src->compress) {
1770 _soup_message_headers_append (_soup_message_get_request_headers (src->msg),
1771 "Accept-Encoding", "identity");
1774 if (gst_soup_loader_get_api_version () == 3) {
1775 g_signal_connect (src->msg, "accept-certificate",
1776 G_CALLBACK (gst_soup_http_src_accept_certificate_cb), src);
1777 g_signal_connect (src->msg, "authenticate",
1778 G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
1782 SoupMessageFlags flags =
1783 src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT;
1785 /* SOUP_MESSAGE_OVERWRITE_CHUNKS is gone in libsoup-3.0, and
1786 * soup_message_body_set_accumulate() requires SoupMessageBody, which
1787 * can only be fetched from SoupServerMessage, not SoupMessage */
1788 #if !defined(STATIC_SOUP) || STATIC_SOUP == 2
1789 if (gst_soup_loader_get_api_version () == 2)
1790 flags |= SOUP_MESSAGE_OVERWRITE_CHUNKS;
1793 _soup_message_set_flags (src->msg, flags);
1796 if (src->automatic_redirect) {
1797 g_signal_connect (src->msg, "restarted",
1798 G_CALLBACK (gst_soup_http_src_restarted_cb), src);
1801 gst_soup_http_src_add_range_header (src, src->request_position,
1802 src->stop_position);
1804 gst_soup_http_src_add_extra_headers (src);
1809 struct GstSoupSendSrc
1811 GstSoupHTTPSrc *src;
1816 _session_send_cb (GObject * source, GAsyncResult * res, gpointer user_data)
1818 struct GstSoupSendSrc *msrc = user_data;
1819 GstSoupHTTPSrc *src = msrc->src;
1820 GError *error = NULL;
1822 g_mutex_lock (&src->session_mutex);
1824 src->input_stream = _soup_session_send_finish (src->session->session,
1827 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
1828 src->headers_ret = GST_FLOW_FLUSHING;
1830 src->headers_ret = gst_soup_http_src_got_headers (src, src->msg);
1833 if (!src->input_stream) {
1834 GST_DEBUG_OBJECT (src, "Sending message failed: %s", error->message);
1835 msrc->error = error;
1838 g_cond_broadcast (&src->session_cond);
1839 g_mutex_unlock (&src->session_mutex);
1843 _session_send_idle_cb (gpointer user_data)
1845 struct GstSoupSendSrc *msrc = user_data;
1846 GstSoupHTTPSrc *src = msrc->src;
1848 _soup_session_send_async (src->session->session, src->msg, src->cancellable,
1849 _session_send_cb, msrc);
1854 /* called with session lock taken */
1855 static GstFlowReturn
1856 gst_soup_http_src_send_message (GstSoupHTTPSrc * src)
1860 struct GstSoupSendSrc msrc;
1862 g_return_val_if_fail (src->msg != NULL, GST_FLOW_ERROR);
1863 g_assert (src->input_stream == NULL);
1868 source = g_idle_source_new ();
1870 src->headers_ret = GST_FLOW_OK;
1872 g_source_set_callback (source, _session_send_idle_cb, &msrc, NULL);
1873 g_source_attach (source, g_main_loop_get_context (src->session->loop));
1874 g_source_unref (source);
1876 while (!src->input_stream && !msrc.error)
1877 g_cond_wait (&src->session_cond, &src->session_mutex);
1879 ret = src->headers_ret;
1881 if (ret != GST_FLOW_OK) {
1885 if (!src->input_stream) {
1886 GST_DEBUG_OBJECT (src, "Didn't get an input stream: %s",
1887 msrc.error->message);
1888 ret = GST_FLOW_ERROR;
1892 /* if an input stream exists, it was always successful */
1893 GST_DEBUG_OBJECT (src, "Successfully got a reply");
1896 g_clear_error (&msrc.error);
1900 /* called with session lock taken */
1901 static GstFlowReturn
1902 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method)
1905 SoupMessageHeaders *request_headers;
1907 if (src->max_retries != -1 && src->retry_count > src->max_retries) {
1908 GST_DEBUG_OBJECT (src, "Max retries reached");
1909 return GST_FLOW_ERROR;
1913 /* EOS immediately if we have an empty segment */
1914 if (src->request_position == src->stop_position)
1915 return GST_FLOW_EOS;
1917 GST_LOG_OBJECT (src, "Running request for method: %s", method);
1920 request_headers = _soup_message_get_request_headers (src->msg);
1922 /* Update the position if we are retrying */
1923 if (src->msg && src->request_position > 0) {
1924 gst_soup_http_src_add_range_header (src, src->request_position,
1925 src->stop_position);
1926 } else if (src->msg && src->request_position == 0)
1927 _soup_message_headers_remove (request_headers, "Range");
1929 /* add_range_header() has the side effect of setting read_position to
1930 * the requested position. This *needs* to be set regardless of having
1931 * a message or not. Failure to do so would result in calculation being
1932 * done with stale/wrong read position */
1933 src->read_position = src->request_position;
1936 if (!gst_soup_http_src_build_message (src, method)) {
1937 return GST_FLOW_ERROR;
1941 if (g_cancellable_is_cancelled (src->cancellable)) {
1942 GST_INFO_OBJECT (src, "interrupted");
1943 return GST_FLOW_FLUSHING;
1946 ret = gst_soup_http_src_send_message (src);
1948 /* Check if Range header was respected. */
1949 if (ret == GST_FLOW_OK && src->request_position > 0 &&
1950 _soup_message_get_status (src->msg) != SOUP_STATUS_PARTIAL_CONTENT) {
1951 src->seekable = FALSE;
1952 GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, SEEK,
1953 (_("Server does not support seeking.")),
1954 ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s",
1955 src->location, GST_STR_NULL (src->redirection_uri)),
1956 ("http-status-code", G_TYPE_UINT, _soup_message_get_status (src->msg),
1957 "http-redirection-uri", G_TYPE_STRING,
1958 GST_STR_NULL (src->redirection_uri), NULL));
1959 ret = GST_FLOW_ERROR;
1966 * Check if the bytes_read is above a certain threshold of the blocksize, if
1967 * that happens a few times in a row, increase the blocksize; Do the same in
1968 * the opposite direction to reduce the blocksize.
1971 gst_soup_http_src_check_update_blocksize (GstSoupHTTPSrc * src,
1974 guint blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
1976 gint64 time_since_last_read =
1977 g_get_monotonic_time () * GST_USECOND - src->last_socket_read_time;
1979 GST_LOG_OBJECT (src, "Checking to update blocksize. Read: %" G_GINT64_FORMAT
1980 " bytes, blocksize: %u bytes, time since last read: %" GST_TIME_FORMAT,
1981 bytes_read, blocksize, GST_TIME_ARGS (time_since_last_read));
1983 if (bytes_read >= blocksize * GROW_BLOCKSIZE_LIMIT
1984 && time_since_last_read <= GROW_TIME_LIMIT) {
1985 src->reduce_blocksize_count = 0;
1986 src->increase_blocksize_count++;
1988 if (src->increase_blocksize_count >= GROW_BLOCKSIZE_COUNT) {
1989 blocksize *= GROW_BLOCKSIZE_FACTOR;
1990 GST_DEBUG_OBJECT (src, "Increased blocksize to %u", blocksize);
1991 gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
1992 src->increase_blocksize_count = 0;
1994 } else if (bytes_read < blocksize * REDUCE_BLOCKSIZE_LIMIT
1995 || time_since_last_read > GROW_TIME_LIMIT) {
1996 src->reduce_blocksize_count++;
1997 src->increase_blocksize_count = 0;
1999 if (src->reduce_blocksize_count >= REDUCE_BLOCKSIZE_COUNT) {
2000 blocksize *= REDUCE_BLOCKSIZE_FACTOR;
2001 blocksize = MAX (blocksize, src->minimum_blocksize);
2002 GST_DEBUG_OBJECT (src, "Decreased blocksize to %u", blocksize);
2003 gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
2004 src->reduce_blocksize_count = 0;
2007 src->reduce_blocksize_count = src->increase_blocksize_count = 0;
2012 gst_soup_http_src_update_position (GstSoupHTTPSrc * src, gint64 bytes_read)
2014 GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
2015 guint64 new_position;
2017 new_position = src->read_position + bytes_read;
2018 if (G_LIKELY (src->request_position == src->read_position))
2019 src->request_position = new_position;
2020 src->read_position = new_position;
2022 if (src->have_size) {
2023 if (new_position > src->content_size) {
2024 GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
2025 "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
2027 src->content_size = new_position;
2028 basesrc->segment.duration = src->content_size;
2029 gst_element_post_message (GST_ELEMENT (src),
2030 gst_message_new_duration_changed (GST_OBJECT (src)));
2031 } else if (new_position == src->content_size) {
2032 GST_DEBUG_OBJECT (src, "We're EOS now");
2037 struct GstSoupReadResult
2039 GstSoupHTTPSrc *src;
2047 _session_read_cb (GObject * source, GAsyncResult * ret, gpointer user_data)
2049 struct GstSoupReadResult *res = user_data;
2051 g_mutex_lock (&res->src->session_mutex);
2053 res->nbytes = g_input_stream_read_finish (G_INPUT_STREAM (source),
2056 g_cond_signal (&res->src->session_cond);
2057 g_mutex_unlock (&res->src->session_mutex);
2061 _session_read_idle_cb (gpointer user_data)
2063 struct GstSoupReadResult *res = user_data;
2065 g_input_stream_read_async (res->src->input_stream, res->buffer,
2066 res->bufsize, G_PRIORITY_DEFAULT, res->src->cancellable,
2067 _session_read_cb, res);
2072 static GstFlowReturn
2073 gst_soup_http_src_read_buffer (GstSoupHTTPSrc * src, GstBuffer ** outbuf)
2075 struct GstSoupReadResult res;
2081 bsrc = GST_BASE_SRC_CAST (src);
2083 *outbuf = gst_soup_http_src_alloc_buffer (src);
2085 GST_WARNING_OBJECT (src, "Failed to allocate buffer");
2086 return GST_FLOW_ERROR;
2089 if (!gst_buffer_map (*outbuf, &mapinfo, GST_MAP_WRITE)) {
2090 GST_WARNING_OBJECT (src, "Failed to map buffer");
2091 return GST_FLOW_ERROR;
2095 res.buffer = mapinfo.data;
2096 res.bufsize = mapinfo.size;
2100 source = g_idle_source_new ();
2102 g_mutex_lock (&src->session_mutex);
2104 g_source_set_callback (source, _session_read_idle_cb, &res, NULL);
2105 /* invoke on libsoup thread */
2106 g_source_attach (source, g_main_loop_get_context (src->session->loop));
2107 g_source_unref (source);
2110 while (!res.error && res.nbytes < 0)
2111 g_cond_wait (&src->session_cond, &src->session_mutex);
2112 g_mutex_unlock (&src->session_mutex);
2114 GST_DEBUG_OBJECT (src, "Read %" G_GSSIZE_FORMAT " bytes from http input",
2118 /* retry by default */
2119 GstFlowReturn ret = GST_FLOW_CUSTOM_ERROR;
2120 if (g_error_matches (res.error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
2121 ret = GST_FLOW_FLUSHING;
2123 GST_ERROR_OBJECT (src, "Got error from libsoup: %s", res.error->message);
2125 g_error_free (res.error);
2126 gst_buffer_unmap (*outbuf, &mapinfo);
2127 gst_buffer_unref (*outbuf);
2131 gst_buffer_unmap (*outbuf, &mapinfo);
2132 if (res.nbytes > 0) {
2133 gst_buffer_set_size (*outbuf, res.nbytes);
2134 GST_BUFFER_OFFSET (*outbuf) = bsrc->segment.position;
2136 gst_soup_http_src_update_position (src, res.nbytes);
2138 /* Got some data, reset retry counter */
2139 src->retry_count = 0;
2141 gst_soup_http_src_check_update_blocksize (src, res.nbytes);
2143 src->last_socket_read_time = g_get_monotonic_time () * GST_USECOND;
2145 /* If we're at the end of a range request, read again to let libsoup
2146 * finalize the request. This allows to reuse the connection again later,
2147 * otherwise we would have to cancel the message and close the connection
2149 if (bsrc->segment.stop != -1
2150 && bsrc->segment.position + res.nbytes >= bsrc->segment.stop) {
2151 SoupMessage *msg = src->msg;
2155 res.bufsize = sizeof (tmp);
2159 src->have_body = TRUE;
2161 g_mutex_lock (&src->session_mutex);
2163 source = g_idle_source_new ();
2165 g_source_set_callback (source, _session_read_idle_cb, &res, NULL);
2166 /* This should return immediately as we're at the end of the range */
2167 g_source_attach (source, g_main_loop_get_context (src->session->loop));
2168 g_source_unref (source);
2170 while (!res.error && res.nbytes < 0)
2171 g_cond_wait (&src->session_cond, &src->session_mutex);
2172 g_mutex_unlock (&src->session_mutex);
2174 g_clear_error (&res.error);
2175 g_object_unref (msg);
2178 GST_ERROR_OBJECT (src,
2179 "Read %" G_GSIZE_FORMAT " bytes after end of range", res.nbytes);
2182 gst_buffer_unref (*outbuf);
2183 if (src->have_size && src->read_position < src->content_size) {
2184 /* Maybe the server disconnected, retry */
2185 ret = GST_FLOW_CUSTOM_ERROR;
2187 g_clear_object (&src->msg);
2190 src->have_body = TRUE;
2194 g_clear_error (&res.error);
2200 _session_stream_clear_cb (gpointer user_data)
2202 GstSoupHTTPSrc *src = user_data;
2204 g_mutex_lock (&src->session_mutex);
2206 g_clear_object (&src->input_stream);
2208 g_cond_signal (&src->session_cond);
2209 g_mutex_unlock (&src->session_mutex);
2215 gst_soup_http_src_stream_clear (GstSoupHTTPSrc * src)
2219 if (!src->input_stream)
2222 g_mutex_lock (&src->session_mutex);
2224 source = g_idle_source_new ();
2226 g_source_set_callback (source, _session_stream_clear_cb, src, NULL);
2227 g_source_attach (source, g_main_loop_get_context (src->session->loop));
2228 g_source_unref (source);
2230 while (src->input_stream)
2231 g_cond_wait (&src->session_cond, &src->session_mutex);
2233 g_mutex_unlock (&src->session_mutex);
2236 static GstFlowReturn
2237 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
2239 GstSoupHTTPSrc *src;
2240 GstFlowReturn ret = GST_FLOW_OK;
2241 GstEvent *http_headers_event = NULL;
2243 src = GST_SOUP_HTTP_SRC (psrc);
2247 /* Check for pending position change */
2248 if (src->request_position != src->read_position && src->input_stream) {
2249 gst_soup_http_src_stream_clear (src);
2252 if (g_cancellable_is_cancelled (src->cancellable)) {
2253 ret = GST_FLOW_FLUSHING;
2257 /* If we have no open connection to the server, start one */
2258 if (!src->input_stream) {
2260 g_mutex_lock (&src->session_mutex);
2262 gst_soup_http_src_do_request (src,
2263 src->method ? src->method : SOUP_METHOD_GET);
2264 http_headers_event = src->http_headers_event;
2265 src->http_headers_event = NULL;
2266 g_mutex_unlock (&src->session_mutex);
2269 if (ret == GST_FLOW_OK || ret == GST_FLOW_CUSTOM_ERROR) {
2270 if (http_headers_event) {
2271 gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event);
2272 http_headers_event = NULL;
2276 if (ret == GST_FLOW_OK)
2277 ret = gst_soup_http_src_read_buffer (src, outbuf);
2280 GST_DEBUG_OBJECT (src, "Returning %d %s", ret, gst_flow_get_name (ret));
2281 if (ret != GST_FLOW_OK) {
2282 if (http_headers_event)
2283 gst_event_unref (http_headers_event);
2285 if (src->input_stream) {
2286 gst_soup_http_src_stream_clear (src);
2288 if (ret == GST_FLOW_CUSTOM_ERROR) {
2294 if (ret == GST_FLOW_FLUSHING) {
2295 src->retry_count = 0;
2302 gst_soup_http_src_start (GstBaseSrc * bsrc)
2304 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2307 GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
2309 g_mutex_lock (&src->session_mutex);
2310 ret = gst_soup_http_src_session_open (src);
2311 g_mutex_unlock (&src->session_mutex);
2316 gst_soup_http_src_stop (GstBaseSrc * bsrc)
2318 GstSoupHTTPSrc *src;
2320 src = GST_SOUP_HTTP_SRC (bsrc);
2321 GST_DEBUG_OBJECT (src, "stop()");
2323 gst_soup_http_src_stream_clear (src);
2325 if (src->keep_alive && !src->msg && !src->session_is_shared)
2326 g_cancellable_cancel (src->cancellable);
2328 gst_soup_http_src_session_close (src);
2330 gst_soup_http_src_reset (src);
2334 static GstStateChangeReturn
2335 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
2337 GstStateChangeReturn ret;
2338 GstSoupHTTPSrc *src;
2340 src = GST_SOUP_HTTP_SRC (element);
2342 switch (transition) {
2343 case GST_STATE_CHANGE_READY_TO_NULL:
2344 gst_soup_http_src_session_close (src);
2350 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2356 gst_soup_http_src_set_context (GstElement * element, GstContext * context)
2358 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (element);
2360 if (g_strcmp0 (gst_context_get_context_type (context),
2361 GST_SOUP_SESSION_CONTEXT) == 0) {
2362 const GstStructure *s = gst_context_get_structure (context);
2364 GST_OBJECT_LOCK (src);
2366 g_clear_object (&src->external_session);
2367 gst_structure_get (s, "session", GST_TYPE_SOUP_SESSION,
2368 &src->external_session, NULL);
2370 GST_DEBUG_OBJECT (src, "Setting external session %p",
2371 src->external_session);
2372 GST_OBJECT_UNLOCK (src);
2375 GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
2378 /* Interrupt a blocking request. */
2380 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
2382 GstSoupHTTPSrc *src;
2384 src = GST_SOUP_HTTP_SRC (bsrc);
2385 GST_DEBUG_OBJECT (src, "unlock()");
2387 g_cancellable_cancel (src->cancellable);
2391 /* Interrupt interrupt. */
2393 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
2395 GstSoupHTTPSrc *src;
2397 src = GST_SOUP_HTTP_SRC (bsrc);
2398 GST_DEBUG_OBJECT (src, "unlock_stop()");
2400 g_cancellable_reset (src->cancellable);
2405 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
2407 GstSoupHTTPSrc *src;
2409 src = GST_SOUP_HTTP_SRC (bsrc);
2411 if (src->have_size) {
2412 GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
2414 *size = src->content_size;
2417 GST_DEBUG_OBJECT (src, "get_size() = FALSE");
2422 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
2424 GstFlowReturn ret = GST_FLOW_OK;
2426 /* Special case to check if the server allows range requests
2427 * before really starting to get data in the buffer creation
2430 if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
2431 g_mutex_lock (&src->session_mutex);
2432 while (!src->got_headers && !g_cancellable_is_cancelled (src->cancellable)
2433 && ret == GST_FLOW_OK) {
2434 if ((src->msg && _soup_message_get_method (src->msg) != SOUP_METHOD_HEAD)) {
2435 /* wait for the current request to finish */
2436 g_cond_wait (&src->session_cond, &src->session_mutex);
2437 ret = src->headers_ret;
2439 if (gst_soup_http_src_session_open (src)) {
2440 ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD);
2444 g_mutex_unlock (&src->session_mutex);
2449 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
2451 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2453 gst_soup_http_src_check_seekable (src);
2455 return src->seekable;
2459 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
2461 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2463 GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
2464 ")", segment->start, segment->stop);
2465 if (src->read_position == segment->start &&
2466 src->request_position == src->read_position &&
2467 src->stop_position == segment->stop) {
2468 GST_DEBUG_OBJECT (src,
2469 "Seek to current read/end position and no seek pending");
2473 gst_soup_http_src_check_seekable (src);
2475 /* If we have no headers we don't know yet if it is seekable or not.
2476 * Store the start position and error out later if it isn't */
2477 if (src->got_headers && !src->seekable) {
2478 GST_WARNING_OBJECT (src, "Not seekable");
2482 if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
2483 GST_WARNING_OBJECT (src, "Invalid seek segment");
2487 if (src->have_size && segment->start >= src->content_size) {
2488 GST_WARNING_OBJECT (src,
2489 "Potentially seeking behind end of file, might EOS immediately");
2492 /* Wait for create() to handle the jump in offset. */
2493 src->request_position = segment->start;
2494 src->stop_position = segment->stop;
2500 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
2502 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2504 GstSchedulingFlags flags;
2505 gint minsize, maxsize, align;
2507 switch (GST_QUERY_TYPE (query)) {
2509 gst_query_set_uri (query, src->location);
2510 if (src->redirection_uri != NULL) {
2511 gst_query_set_uri_redirection (query, src->redirection_uri);
2512 gst_query_set_uri_redirection_permanent (query,
2513 src->redirection_permanent);
2523 ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
2525 switch (GST_QUERY_TYPE (query)) {
2526 case GST_QUERY_SCHEDULING:
2527 gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
2528 flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
2529 gst_query_set_scheduling (query, flags, minsize, maxsize, align);
2539 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
2542 const char *alt_schemes[] = { "icy://", "icyx://" };
2545 if (src->location) {
2546 g_free (src->location);
2547 src->location = NULL;
2553 for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
2554 if (g_str_has_prefix (uri, alt_schemes[i])) {
2556 g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
2561 if (src->redirection_uri) {
2562 g_free (src->redirection_uri);
2563 src->redirection_uri = NULL;
2566 src->location = g_strdup (uri);
2572 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
2575 gst_soup_uri_free (src->proxy);
2579 if (uri == NULL || *uri == '\0')
2582 if (g_strstr_len (uri, -1, "://")) {
2583 src->proxy = gst_soup_uri_new (uri);
2585 gchar *new_uri = g_strconcat ("http://", uri, NULL);
2587 src->proxy = gst_soup_uri_new (new_uri);
2591 return (src->proxy != NULL);
2595 gst_soup_http_src_uri_get_type (GType type)
2600 static const gchar *const *
2601 gst_soup_http_src_uri_get_protocols (GType type)
2603 static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
2609 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
2611 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2613 /* FIXME: make thread-safe */
2614 return g_strdup (src->location);
2618 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
2621 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2623 return gst_soup_http_src_set_location (src, uri, error);
2627 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
2629 GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
2631 iface->get_type = gst_soup_http_src_uri_get_type;
2632 iface->get_protocols = gst_soup_http_src_uri_get_protocols;
2633 iface->get_uri = gst_soup_http_src_uri_get_uri;
2634 iface->set_uri = gst_soup_http_src_uri_set_uri;
2638 souphttpsrc_element_init (GstPlugin * plugin)
2640 gboolean ret = TRUE;
2642 GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0,
2645 if (!soup_element_init (plugin))
2648 ret = gst_element_register (plugin, "souphttpsrc",
2649 GST_RANK_PRIMARY, GST_TYPE_SOUP_HTTP_SRC);