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))
98 GType gst_soup_session_get_type (void);
100 typedef struct _GstSoupSessionClass GstSoupSessionClass;
102 struct _GstSoupSession
104 GObject parent_instance;
106 SoupSession *session;
111 struct _GstSoupSessionClass
113 GObjectClass parent_class;
116 G_DEFINE_TYPE (GstSoupSession, gst_soup_session, G_TYPE_OBJECT);
119 gst_soup_session_init (GstSoupSession * sess)
124 _soup_session_finalize_cb (gpointer user_data)
126 GstSoupSession *sess = user_data;
128 g_main_loop_quit (sess->loop);
134 gst_soup_session_finalize (GObject * obj)
136 GstSoupSession *sess = GST_SOUP_SESSION (obj);
139 /* handle disposing of failure cases */
143 src = g_idle_source_new ();
145 g_source_set_callback (src, _soup_session_finalize_cb, sess, NULL);
146 g_source_attach (src, g_main_loop_get_context (sess->loop));
147 g_source_unref (src);
149 /* finish off thread and the loop; ensure it's not from the thread */
150 g_assert (!g_main_context_is_owner (g_main_loop_get_context (sess->loop)));
151 g_thread_join (sess->thread);
152 g_main_loop_unref (sess->loop);
156 gst_soup_session_class_init (GstSoupSessionClass * klass)
158 GObjectClass *gclass = G_OBJECT_CLASS (klass);
160 gclass->finalize = gst_soup_session_finalize;
163 GST_DEBUG_CATEGORY_STATIC (souphttpsrc_debug);
164 #define GST_CAT_DEFAULT souphttpsrc_debug
166 #define GST_SOUP_SESSION_CONTEXT "gst.soup.session"
168 static GstStaticPadTemplate srctemplate = GST_STATIC_PAD_TEMPLATE ("src",
171 GST_STATIC_CAPS_ANY);
179 PROP_AUTOMATIC_REDIRECT,
194 PROP_SSL_USE_SYSTEM_CA_FILE,
198 PROP_TLS_INTERACTION,
201 #define DEFAULT_USER_AGENT "GStreamer souphttpsrc " PACKAGE_VERSION " "
202 #define DEFAULT_IRADIO_MODE TRUE
203 #define DEFAULT_SOUP_LOG_LEVEL SOUP_LOGGER_LOG_HEADERS
204 #define DEFAULT_COMPRESS FALSE
205 #define DEFAULT_KEEP_ALIVE TRUE
206 #define DEFAULT_SSL_STRICT TRUE
207 #define DEFAULT_SSL_CA_FILE NULL
208 #define DEFAULT_SSL_USE_SYSTEM_CA_FILE TRUE
209 #define DEFAULT_TLS_DATABASE NULL
210 #define DEFAULT_TLS_INTERACTION NULL
211 #define DEFAULT_TIMEOUT 15
212 #define DEFAULT_RETRIES 3
213 #define DEFAULT_SOUP_METHOD NULL
215 #define GROW_BLOCKSIZE_LIMIT 1
216 #define GROW_BLOCKSIZE_COUNT 1
217 #define GROW_BLOCKSIZE_FACTOR 2
218 #define REDUCE_BLOCKSIZE_LIMIT 0.20
219 #define REDUCE_BLOCKSIZE_COUNT 2
220 #define REDUCE_BLOCKSIZE_FACTOR 0.5
221 #define GROW_TIME_LIMIT (1 * GST_SECOND)
223 static void gst_soup_http_src_uri_handler_init (gpointer g_iface,
224 gpointer iface_data);
225 static void gst_soup_http_src_finalize (GObject * gobject);
226 static void gst_soup_http_src_dispose (GObject * gobject);
228 static void gst_soup_http_src_set_property (GObject * object, guint prop_id,
229 const GValue * value, GParamSpec * pspec);
230 static void gst_soup_http_src_get_property (GObject * object, guint prop_id,
231 GValue * value, GParamSpec * pspec);
233 static GstStateChangeReturn gst_soup_http_src_change_state (GstElement *
234 element, GstStateChange transition);
235 static void gst_soup_http_src_set_context (GstElement * element,
236 GstContext * context);
237 static GstFlowReturn gst_soup_http_src_create (GstPushSrc * psrc,
238 GstBuffer ** outbuf);
239 static gboolean gst_soup_http_src_start (GstBaseSrc * bsrc);
240 static gboolean gst_soup_http_src_stop (GstBaseSrc * bsrc);
241 static gboolean gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size);
242 static gboolean gst_soup_http_src_is_seekable (GstBaseSrc * bsrc);
243 static gboolean gst_soup_http_src_do_seek (GstBaseSrc * bsrc,
244 GstSegment * segment);
245 static gboolean gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query);
246 static gboolean gst_soup_http_src_unlock (GstBaseSrc * bsrc);
247 static gboolean gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc);
248 static gboolean gst_soup_http_src_set_location (GstSoupHTTPSrc * src,
249 const gchar * uri, GError ** error);
250 static gboolean gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src,
252 static char *gst_soup_http_src_unicodify (const char *str);
253 static gboolean gst_soup_http_src_build_message (GstSoupHTTPSrc * src,
254 const gchar * method);
255 static gboolean gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src,
256 guint64 offset, guint64 stop_offset);
257 static gboolean gst_soup_http_src_session_open (GstSoupHTTPSrc * src);
258 static void gst_soup_http_src_session_close (GstSoupHTTPSrc * src);
259 static GstFlowReturn gst_soup_http_src_parse_status (SoupMessage * msg,
260 GstSoupHTTPSrc * src);
261 static GstFlowReturn gst_soup_http_src_got_headers (GstSoupHTTPSrc * src,
263 static void gst_soup_http_src_authenticate_cb_2 (SoupSession *,
264 SoupMessage * msg, SoupAuth * auth, gboolean retrying, gpointer);
265 static gboolean gst_soup_http_src_authenticate_cb (SoupMessage * msg,
266 SoupAuth * auth, gboolean retrying, gpointer);
267 static gboolean gst_soup_http_src_accept_certificate_cb (SoupMessage * msg,
268 GTlsCertificate * tls_certificate, GTlsCertificateFlags tls_errors,
271 #define gst_soup_http_src_parent_class parent_class
272 G_DEFINE_TYPE_WITH_CODE (GstSoupHTTPSrc, gst_soup_http_src, GST_TYPE_PUSH_SRC,
273 G_IMPLEMENT_INTERFACE (GST_TYPE_URI_HANDLER,
274 gst_soup_http_src_uri_handler_init));
276 static gboolean souphttpsrc_element_init (GstPlugin * plugin);
277 GST_ELEMENT_REGISTER_DEFINE_CUSTOM (souphttpsrc, souphttpsrc_element_init);
280 gst_soup_http_src_class_init (GstSoupHTTPSrcClass * klass)
282 GObjectClass *gobject_class;
283 GstElementClass *gstelement_class;
284 GstBaseSrcClass *gstbasesrc_class;
285 GstPushSrcClass *gstpushsrc_class;
287 gobject_class = (GObjectClass *) klass;
288 gstelement_class = (GstElementClass *) klass;
289 gstbasesrc_class = (GstBaseSrcClass *) klass;
290 gstpushsrc_class = (GstPushSrcClass *) klass;
292 gobject_class->set_property = gst_soup_http_src_set_property;
293 gobject_class->get_property = gst_soup_http_src_get_property;
294 gobject_class->finalize = gst_soup_http_src_finalize;
295 gobject_class->dispose = gst_soup_http_src_dispose;
297 g_object_class_install_property (gobject_class,
299 g_param_spec_string ("location", "Location",
300 "Location to read from", "",
301 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
302 g_object_class_install_property (gobject_class,
304 g_param_spec_string ("user-agent", "User-Agent",
305 "Value of the User-Agent HTTP request header field",
306 DEFAULT_USER_AGENT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
307 g_object_class_install_property (gobject_class,
308 PROP_AUTOMATIC_REDIRECT,
309 g_param_spec_boolean ("automatic-redirect", "automatic-redirect",
310 "Automatically follow HTTP redirects (HTTP Status Code 3xx)",
311 TRUE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
312 g_object_class_install_property (gobject_class,
314 g_param_spec_string ("proxy", "Proxy",
315 "HTTP proxy server URI", "",
316 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
317 g_object_class_install_property (gobject_class,
319 g_param_spec_string ("user-id", "user-id",
320 "HTTP location URI user id for authentication", "",
321 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
322 g_object_class_install_property (gobject_class, PROP_USER_PW,
323 g_param_spec_string ("user-pw", "user-pw",
324 "HTTP location URI user password for authentication", "",
325 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
326 g_object_class_install_property (gobject_class, PROP_PROXY_ID,
327 g_param_spec_string ("proxy-id", "proxy-id",
328 "HTTP proxy URI user id for authentication", "",
329 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
330 g_object_class_install_property (gobject_class, PROP_PROXY_PW,
331 g_param_spec_string ("proxy-pw", "proxy-pw",
332 "HTTP proxy URI user password for authentication", "",
333 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
334 g_object_class_install_property (gobject_class, PROP_COOKIES,
335 g_param_spec_boxed ("cookies", "Cookies", "HTTP request cookies",
336 G_TYPE_STRV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
337 g_object_class_install_property (gobject_class, PROP_IS_LIVE,
338 g_param_spec_boolean ("is-live", "is-live", "Act like a live source",
339 FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
340 g_object_class_install_property (gobject_class, PROP_TIMEOUT,
341 g_param_spec_uint ("timeout", "timeout",
342 "Value in seconds to timeout a blocking I/O (0 = No timeout).", 0,
343 3600, DEFAULT_TIMEOUT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
344 g_object_class_install_property (gobject_class, PROP_EXTRA_HEADERS,
345 g_param_spec_boxed ("extra-headers", "Extra Headers",
346 "Extra headers to append to the HTTP request",
347 GST_TYPE_STRUCTURE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
348 g_object_class_install_property (gobject_class, PROP_IRADIO_MODE,
349 g_param_spec_boolean ("iradio-mode", "iradio-mode",
350 "Enable internet radio mode (ask server to send shoutcast/icecast "
351 "metadata interleaved with the actual stream data)",
352 DEFAULT_IRADIO_MODE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
355 * GstSoupHTTPSrc::http-log-level:
357 * If set and > 0, captures and dumps HTTP session data as
358 * log messages if log level >= GST_LEVEL_TRACE
362 g_object_class_install_property (gobject_class, PROP_SOUP_LOG_LEVEL,
363 g_param_spec_enum ("http-log-level", "HTTP log level",
364 "Set log level for soup's HTTP session log",
365 _soup_logger_log_level_get_type (),
366 DEFAULT_SOUP_LOG_LEVEL, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
369 * GstSoupHTTPSrc::compress:
371 * If set to %TRUE, souphttpsrc will automatically handle gzip
372 * and deflate Content-Encodings. This does not make much difference
373 * and causes more load for normal media files, but makes a real
374 * difference in size for plaintext files.
378 g_object_class_install_property (gobject_class, PROP_COMPRESS,
379 g_param_spec_boolean ("compress", "Compress",
380 "Allow compressed content encodings",
381 DEFAULT_COMPRESS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
384 * GstSoupHTTPSrc::keep-alive:
386 * If set to %TRUE, souphttpsrc will keep alive connections when being
387 * set to READY state and only will close connections when connecting
388 * to a different server or when going to NULL state..
392 g_object_class_install_property (gobject_class, PROP_KEEP_ALIVE,
393 g_param_spec_boolean ("keep-alive", "keep-alive",
394 "Use HTTP persistent connections", DEFAULT_KEEP_ALIVE,
395 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
398 * GstSoupHTTPSrc::ssl-strict:
400 * If set to %TRUE, souphttpsrc will reject all SSL certificates that
401 * are considered invalid.
405 g_object_class_install_property (gobject_class, PROP_SSL_STRICT,
406 g_param_spec_boolean ("ssl-strict", "SSL Strict",
407 "Strict SSL certificate checking", DEFAULT_SSL_STRICT,
408 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
411 * GstSoupHTTPSrc::ssl-ca-file:
413 * A SSL anchor CA file that should be used for checking certificates
414 * instead of the system CA file.
416 * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
417 * value will be ignored.
419 * Deprecated: Use #GstSoupHTTPSrc::tls-database property instead. This
420 * property is no-op when libsoup3 is being used at runtime.
424 g_object_class_install_property (gobject_class, PROP_SSL_CA_FILE,
425 g_param_spec_string ("ssl-ca-file", "SSL CA File",
426 "Location of a SSL anchor CA file to use", DEFAULT_SSL_CA_FILE,
427 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
430 * GstSoupHTTPSrc::ssl-use-system-ca-file:
432 * If set to %TRUE, souphttpsrc will use the system's CA file for
433 * checking certificates, unless #GstSoupHTTPSrc::ssl-ca-file or
434 * #GstSoupHTTPSrc::tls-database are non-%NULL.
436 * Deprecated: This property is no-op when libsoup3 is being used at runtime.
440 g_object_class_install_property (gobject_class, PROP_SSL_USE_SYSTEM_CA_FILE,
441 g_param_spec_boolean ("ssl-use-system-ca-file", "Use System CA File",
442 "Use system CA file", DEFAULT_SSL_USE_SYSTEM_CA_FILE,
443 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
446 * GstSoupHTTPSrc::tls-database:
448 * TLS database with anchor certificate authorities used to validate
449 * the server certificate.
451 * If this property is non-%NULL, #GstSoupHTTPSrc::ssl-use-system-ca-file
452 * and #GstSoupHTTPSrc::ssl-ca-file values will be ignored.
456 g_object_class_install_property (gobject_class, PROP_TLS_DATABASE,
457 g_param_spec_object ("tls-database", "TLS database",
458 "TLS database with anchor certificate authorities used to validate the server certificate",
459 G_TYPE_TLS_DATABASE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
462 * GstSoupHTTPSrc::tls-interaction:
464 * A #GTlsInteraction object to be used when the connection or certificate
465 * database need to interact with the user. This will be used to prompt the
466 * user for passwords or certificate where necessary.
470 g_object_class_install_property (gobject_class, PROP_TLS_INTERACTION,
471 g_param_spec_object ("tls-interaction", "TLS interaction",
472 "A GTlsInteraction object to be used when the connection or certificate database need to interact with the user.",
473 G_TYPE_TLS_INTERACTION, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
476 * GstSoupHTTPSrc::retries:
478 * Maximum number of retries until giving up.
482 g_object_class_install_property (gobject_class, PROP_RETRIES,
483 g_param_spec_int ("retries", "Retries",
484 "Maximum number of retries until giving up (-1=infinite)", -1,
485 G_MAXINT, DEFAULT_RETRIES,
486 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
489 * GstSoupHTTPSrc::method
491 * The HTTP method to use when making a request
495 g_object_class_install_property (gobject_class, PROP_METHOD,
496 g_param_spec_string ("method", "HTTP method",
497 "The HTTP method to use (GET, HEAD, OPTIONS, etc)",
498 DEFAULT_SOUP_METHOD, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
500 gst_element_class_add_static_pad_template (gstelement_class, &srctemplate);
502 gst_element_class_set_static_metadata (gstelement_class, "HTTP client source",
504 "Receive data as a client over the network via HTTP using SOUP",
505 "Wouter Cloetens <wouter@mind.be>");
506 gstelement_class->change_state =
507 GST_DEBUG_FUNCPTR (gst_soup_http_src_change_state);
508 gstelement_class->set_context =
509 GST_DEBUG_FUNCPTR (gst_soup_http_src_set_context);
511 gstbasesrc_class->start = GST_DEBUG_FUNCPTR (gst_soup_http_src_start);
512 gstbasesrc_class->stop = GST_DEBUG_FUNCPTR (gst_soup_http_src_stop);
513 gstbasesrc_class->unlock = GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock);
514 gstbasesrc_class->unlock_stop =
515 GST_DEBUG_FUNCPTR (gst_soup_http_src_unlock_stop);
516 gstbasesrc_class->get_size = GST_DEBUG_FUNCPTR (gst_soup_http_src_get_size);
517 gstbasesrc_class->is_seekable =
518 GST_DEBUG_FUNCPTR (gst_soup_http_src_is_seekable);
519 gstbasesrc_class->do_seek = GST_DEBUG_FUNCPTR (gst_soup_http_src_do_seek);
520 gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_soup_http_src_query);
522 gstpushsrc_class->create = GST_DEBUG_FUNCPTR (gst_soup_http_src_create);
526 gst_soup_http_src_reset (GstSoupHTTPSrc * src)
528 src->retry_count = 0;
529 src->have_size = FALSE;
530 src->got_headers = FALSE;
531 src->headers_ret = GST_FLOW_OK;
532 src->seekable = FALSE;
533 src->read_position = 0;
534 src->request_position = 0;
535 src->stop_position = -1;
536 src->content_size = 0;
537 src->have_body = FALSE;
539 src->reduce_blocksize_count = 0;
540 src->increase_blocksize_count = 0;
541 src->last_socket_read_time = 0;
543 g_cancellable_reset (src->cancellable);
545 gst_caps_replace (&src->src_caps, NULL);
546 g_free (src->iradio_name);
547 src->iradio_name = NULL;
548 g_free (src->iradio_genre);
549 src->iradio_genre = NULL;
550 g_free (src->iradio_url);
551 src->iradio_url = NULL;
555 gst_soup_http_src_init (GstSoupHTTPSrc * src)
559 g_mutex_init (&src->session_mutex);
560 g_cond_init (&src->session_cond);
561 src->cancellable = g_cancellable_new ();
562 src->location = NULL;
563 src->redirection_uri = NULL;
564 src->automatic_redirect = TRUE;
565 src->user_agent = g_strdup (DEFAULT_USER_AGENT);
568 src->proxy_id = NULL;
569 src->proxy_pw = NULL;
571 src->iradio_mode = DEFAULT_IRADIO_MODE;
573 src->external_session = NULL;
575 src->timeout = DEFAULT_TIMEOUT;
576 src->log_level = DEFAULT_SOUP_LOG_LEVEL;
577 src->compress = DEFAULT_COMPRESS;
578 src->keep_alive = DEFAULT_KEEP_ALIVE;
579 src->ssl_strict = DEFAULT_SSL_STRICT;
580 src->ssl_use_system_ca_file = DEFAULT_SSL_USE_SYSTEM_CA_FILE;
581 src->tls_database = DEFAULT_TLS_DATABASE;
582 src->tls_interaction = DEFAULT_TLS_INTERACTION;
583 src->max_retries = DEFAULT_RETRIES;
584 src->method = DEFAULT_SOUP_METHOD;
585 src->minimum_blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
586 proxy = g_getenv ("http_proxy");
587 if (!gst_soup_http_src_set_proxy (src, proxy)) {
588 GST_WARNING_OBJECT (src,
589 "The proxy in the http_proxy env var (\"%s\") cannot be parsed.",
593 gst_base_src_set_automatic_eos (GST_BASE_SRC (src), FALSE);
595 gst_soup_http_src_reset (src);
599 gst_soup_http_src_dispose (GObject * gobject)
601 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
603 GST_DEBUG_OBJECT (src, "dispose");
605 gst_soup_http_src_session_close (src);
607 g_clear_object (&src->external_session);
609 G_OBJECT_CLASS (parent_class)->dispose (gobject);
613 gst_soup_http_src_finalize (GObject * gobject)
615 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (gobject);
617 GST_DEBUG_OBJECT (src, "finalize");
619 g_mutex_clear (&src->session_mutex);
620 g_cond_clear (&src->session_cond);
621 g_object_unref (src->cancellable);
622 g_free (src->location);
623 g_free (src->redirection_uri);
624 g_free (src->user_agent);
625 if (src->proxy != NULL) {
626 gst_soup_uri_free (src->proxy);
628 g_free (src->user_id);
629 g_free (src->user_pw);
630 g_free (src->proxy_id);
631 g_free (src->proxy_pw);
632 g_strfreev (src->cookies);
634 if (src->extra_headers) {
635 gst_structure_free (src->extra_headers);
636 src->extra_headers = NULL;
639 g_free (src->ssl_ca_file);
641 if (src->tls_database)
642 g_object_unref (src->tls_database);
643 g_free (src->method);
645 if (src->tls_interaction)
646 g_object_unref (src->tls_interaction);
648 G_OBJECT_CLASS (parent_class)->finalize (gobject);
652 gst_soup_http_src_set_property (GObject * object, guint prop_id,
653 const GValue * value, GParamSpec * pspec)
655 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
660 const gchar *location;
662 location = g_value_get_string (value);
664 if (location == NULL) {
665 GST_WARNING ("location property cannot be NULL");
668 if (!gst_soup_http_src_set_location (src, location, NULL)) {
669 GST_WARNING ("badly formatted location");
674 case PROP_USER_AGENT:
675 g_free (src->user_agent);
676 src->user_agent = g_value_dup_string (value);
678 case PROP_IRADIO_MODE:
679 src->iradio_mode = g_value_get_boolean (value);
681 case PROP_AUTOMATIC_REDIRECT:
682 src->automatic_redirect = g_value_get_boolean (value);
688 proxy = g_value_get_string (value);
689 if (!gst_soup_http_src_set_proxy (src, proxy)) {
690 GST_WARNING ("badly formatted proxy URI");
696 g_strfreev (src->cookies);
697 src->cookies = g_strdupv (g_value_get_boxed (value));
700 gst_base_src_set_live (GST_BASE_SRC (src), g_value_get_boolean (value));
703 g_free (src->user_id);
704 src->user_id = g_value_dup_string (value);
707 g_free (src->user_pw);
708 src->user_pw = g_value_dup_string (value);
711 g_free (src->proxy_id);
712 src->proxy_id = g_value_dup_string (value);
715 g_free (src->proxy_pw);
716 src->proxy_pw = g_value_dup_string (value);
719 src->timeout = g_value_get_uint (value);
721 case PROP_EXTRA_HEADERS:{
722 const GstStructure *s = gst_value_get_structure (value);
724 if (src->extra_headers)
725 gst_structure_free (src->extra_headers);
727 src->extra_headers = s ? gst_structure_copy (s) : NULL;
730 case PROP_SOUP_LOG_LEVEL:
731 src->log_level = g_value_get_enum (value);
734 src->compress = g_value_get_boolean (value);
736 case PROP_KEEP_ALIVE:
737 src->keep_alive = g_value_get_boolean (value);
739 case PROP_SSL_STRICT:
740 src->ssl_strict = g_value_get_boolean (value);
742 case PROP_TLS_DATABASE:
743 g_clear_object (&src->tls_database);
744 src->tls_database = g_value_dup_object (value);
746 case PROP_TLS_INTERACTION:
747 g_clear_object (&src->tls_interaction);
748 src->tls_interaction = g_value_dup_object (value);
751 src->max_retries = g_value_get_int (value);
754 g_free (src->method);
755 src->method = g_value_dup_string (value);
757 case PROP_SSL_CA_FILE:
758 if (gst_soup_loader_get_api_version () == 2) {
759 g_free (src->ssl_ca_file);
760 src->ssl_ca_file = g_value_dup_string (value);
763 case PROP_SSL_USE_SYSTEM_CA_FILE:
764 if (gst_soup_loader_get_api_version () == 2) {
765 src->ssl_use_system_ca_file = g_value_get_boolean (value);
769 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
777 gst_soup_http_src_get_property (GObject * object, guint prop_id,
778 GValue * value, GParamSpec * pspec)
780 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (object);
784 g_value_set_string (value, src->location);
786 case PROP_USER_AGENT:
787 g_value_set_string (value, src->user_agent);
789 case PROP_AUTOMATIC_REDIRECT:
790 g_value_set_boolean (value, src->automatic_redirect);
793 if (src->proxy == NULL)
794 g_value_set_static_string (value, "");
796 char *proxy = gst_soup_uri_to_string (src->proxy);
797 g_value_set_string (value, proxy);
802 g_value_set_boxed (value, g_strdupv (src->cookies));
805 g_value_set_boolean (value, gst_base_src_is_live (GST_BASE_SRC (src)));
807 case PROP_IRADIO_MODE:
808 g_value_set_boolean (value, src->iradio_mode);
811 g_value_set_string (value, src->user_id);
814 g_value_set_string (value, src->user_pw);
817 g_value_set_string (value, src->proxy_id);
820 g_value_set_string (value, src->proxy_pw);
823 g_value_set_uint (value, src->timeout);
825 case PROP_EXTRA_HEADERS:
826 gst_value_set_structure (value, src->extra_headers);
828 case PROP_SOUP_LOG_LEVEL:
829 g_value_set_enum (value, src->log_level);
832 g_value_set_boolean (value, src->compress);
834 case PROP_KEEP_ALIVE:
835 g_value_set_boolean (value, src->keep_alive);
837 case PROP_SSL_STRICT:
838 g_value_set_boolean (value, src->ssl_strict);
840 case PROP_TLS_DATABASE:
841 g_value_set_object (value, src->tls_database);
843 case PROP_TLS_INTERACTION:
844 g_value_set_object (value, src->tls_interaction);
847 g_value_set_int (value, src->max_retries);
850 g_value_set_string (value, src->method);
852 case PROP_SSL_CA_FILE:
853 if (gst_soup_loader_get_api_version () == 2)
854 g_value_set_string (value, src->ssl_ca_file);
856 case PROP_SSL_USE_SYSTEM_CA_FILE:
857 if (gst_soup_loader_get_api_version () == 2)
858 g_value_set_boolean (value, src->ssl_use_system_ca_file);
861 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
867 gst_soup_http_src_unicodify (const gchar * str)
869 const gchar *env_vars[] = { "GST_ICY_TAG_ENCODING",
870 "GST_TAG_ENCODING", NULL
873 return gst_tag_freeform_string_to_utf8 (str, -1, env_vars);
877 gst_soup_http_src_add_range_header (GstSoupHTTPSrc * src, guint64 offset,
882 SoupMessageHeaders *request_headers =
883 _soup_message_get_request_headers (src->msg);
885 _soup_message_headers_remove (request_headers, "Range");
886 if (offset || stop_offset != -1) {
887 if (stop_offset != -1) {
888 g_assert (offset != stop_offset);
890 rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-%"
891 G_GUINT64_FORMAT, offset, (stop_offset > 0) ? stop_offset - 1 :
894 rc = g_snprintf (buf, sizeof (buf), "bytes=%" G_GUINT64_FORMAT "-",
897 if (rc > sizeof (buf) || rc < 0)
899 _soup_message_headers_append (request_headers, "Range", buf);
901 src->read_position = offset;
906 _append_extra_header (GQuark field_id, const GValue * value, gpointer user_data)
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 SoupMessageHeaders *request_headers =
912 _soup_message_get_request_headers (src->msg);
914 if (G_VALUE_TYPE (value) == G_TYPE_STRING) {
915 field_content = g_value_dup_string (value);
917 GValue dest = { 0, };
919 g_value_init (&dest, G_TYPE_STRING);
920 if (g_value_transform (value, &dest)) {
921 field_content = g_value_dup_string (&dest);
925 if (field_content == NULL) {
926 GST_ERROR_OBJECT (src, "extra-headers field '%s' contains no value "
927 "or can't be converted to a string", field_name);
931 GST_DEBUG_OBJECT (src, "Appending extra header: \"%s: %s\"", field_name,
933 _soup_message_headers_append (request_headers, field_name, field_content);
935 g_free (field_content);
941 _append_extra_headers (GQuark field_id, const GValue * value,
944 if (G_VALUE_TYPE (value) == GST_TYPE_ARRAY) {
945 guint n = gst_value_array_get_size (value);
948 for (i = 0; i < n; i++) {
949 const GValue *v = gst_value_array_get_value (value, i);
951 if (!_append_extra_header (field_id, v, user_data))
954 } else if (G_VALUE_TYPE (value) == GST_TYPE_LIST) {
955 guint n = gst_value_list_get_size (value);
958 for (i = 0; i < n; i++) {
959 const GValue *v = gst_value_list_get_value (value, i);
961 if (!_append_extra_header (field_id, v, user_data))
965 return _append_extra_header (field_id, value, user_data);
973 gst_soup_http_src_add_extra_headers (GstSoupHTTPSrc * src)
975 if (!src->extra_headers)
978 return gst_structure_foreach (src->extra_headers, _append_extra_headers, src);
982 thread_func (gpointer user_data)
984 GstSoupHTTPSrc *src = user_data;
985 GstSoupSession *session = src->session;
988 GST_DEBUG_OBJECT (src, "thread start");
990 ctx = g_main_loop_get_context (session->loop);
992 g_main_context_push_thread_default (ctx);
994 /* We explicitly set User-Agent to NULL here and overwrite it per message
995 * to be able to have the same session with different User-Agents per
998 _soup_session_new_with_options ("user-agent", NULL,
999 "timeout", src->timeout, "tls-interaction", src->tls_interaction,
1000 /* Unset the limit the number of maximum allowed connections */
1001 "max-conns", src->session_is_shared ? G_MAXINT : 10,
1002 "max-conns-per-host", src->session_is_shared ? G_MAXINT : 2, NULL);
1003 g_assert (session->session);
1005 if (gst_soup_loader_get_api_version () == 3) {
1006 if (src->proxy != NULL) {
1007 GProxyResolver *proxy_resolver;
1008 char *proxy_string = gst_soup_uri_to_string (src->proxy);
1009 proxy_resolver = g_simple_proxy_resolver_new (proxy_string, NULL);
1010 g_free (proxy_string);
1011 g_object_set (src->session->session, "proxy-resolver", proxy_resolver,
1013 g_object_unref (proxy_resolver);
1015 #if !defined(STATIC_SOUP) || STATIC_SOUP == 2
1017 g_object_set (session->session, "ssl-strict", src->ssl_strict, NULL);
1018 if (src->proxy != NULL) {
1019 /* Need #if because there's no proxy->soup_uri when STATIC_SOUP == 3 */
1020 g_object_set (session->session, "proxy-uri", src->proxy->soup_uri, NULL);
1025 gst_soup_util_log_setup (session->session, src->log_level,
1026 G_OBJECT (session));
1027 if (gst_soup_loader_get_api_version () < 3) {
1028 _soup_session_add_feature_by_type (session->session,
1029 _soup_content_decoder_get_type ());
1031 _soup_session_add_feature_by_type (session->session,
1032 _soup_cookie_jar_get_type ());
1034 /* soup2: connect the authenticate handler for the src that spawned the
1035 * session (i.e. the first owner); other users of this session will connect
1036 * their own after fetching the external session; the callback will handle
1037 * this correctly (it checks if the message belongs to the current src
1038 * and exits early if it does not)
1040 if (gst_soup_loader_get_api_version () < 3) {
1041 g_signal_connect (session->session, "authenticate",
1042 G_CALLBACK (gst_soup_http_src_authenticate_cb_2), src);
1045 if (!src->session_is_shared) {
1046 if (src->tls_database)
1047 g_object_set (src->session->session, "tls-database", src->tls_database,
1049 else if (gst_soup_loader_get_api_version () == 2) {
1050 if (src->ssl_ca_file)
1051 g_object_set (src->session->session, "ssl-ca-file", src->ssl_ca_file,
1054 g_object_set (src->session->session, "ssl-use-system-ca-file",
1055 src->ssl_use_system_ca_file, NULL);
1059 /* Once the main loop is running, the source element that created this
1060 * session might disappear if the session is shared with other source
1065 g_main_loop_run (session->loop);
1067 /* Abort any pending operations on the session ... */
1068 _soup_session_abort (session->session);
1069 g_clear_object (&session->session);
1071 /* ... and iterate the main context until nothing is pending anymore */
1072 while (g_main_context_iteration (ctx, FALSE));
1074 g_main_context_pop_thread_default (ctx);
1076 GST_DEBUG_OBJECT (session, "thread stop");
1082 _session_ready_cb (gpointer user_data)
1084 GstSoupHTTPSrc *src = user_data;
1086 GST_DEBUG_OBJECT (src, "thread ready");
1088 g_mutex_lock (&src->session_mutex);
1089 g_cond_signal (&src->session_cond);
1090 g_mutex_unlock (&src->session_mutex);
1095 /* called with session_mutex taken */
1097 gst_soup_http_src_session_open (GstSoupHTTPSrc * src)
1103 GST_DEBUG_OBJECT (src, "Session is already open");
1107 if (!src->location) {
1108 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ, (_("No URL set.")),
1109 ("Missing location property"));
1113 can_share = (src->timeout == DEFAULT_TIMEOUT)
1114 && (src->cookies == NULL)
1115 && (src->ssl_strict == DEFAULT_SSL_STRICT)
1116 && (src->tls_interaction == NULL) && (src->proxy == NULL)
1117 && (src->tls_database == DEFAULT_TLS_DATABASE);
1119 if (gst_soup_loader_get_api_version () == 2)
1120 can_share = can_share && (src->ssl_ca_file == DEFAULT_SSL_CA_FILE) &&
1121 (src->ssl_use_system_ca_file == DEFAULT_SSL_USE_SYSTEM_CA_FILE);
1123 query = gst_query_new_context (GST_SOUP_SESSION_CONTEXT);
1124 if (gst_pad_peer_query (GST_BASE_SRC_PAD (src), query)) {
1125 GstContext *context;
1127 gst_query_parse_context (query, &context);
1128 gst_element_set_context (GST_ELEMENT_CAST (src), context);
1130 GstMessage *message;
1133 gst_message_new_need_context (GST_OBJECT_CAST (src),
1134 GST_SOUP_SESSION_CONTEXT);
1135 gst_element_post_message (GST_ELEMENT_CAST (src), message);
1137 gst_query_unref (query);
1139 GST_OBJECT_LOCK (src);
1141 src->session_is_shared = can_share;
1143 if (src->external_session && can_share) {
1144 GST_DEBUG_OBJECT (src, "Using external session %p", src->external_session);
1145 src->session = g_object_ref (src->external_session);
1146 /* for soup2, connect another authenticate handler; see thread_func */
1147 if (gst_soup_loader_get_api_version () < 3) {
1148 g_signal_connect (src->session->session, "authenticate",
1149 G_CALLBACK (gst_soup_http_src_authenticate_cb_2), src);
1155 GST_DEBUG_OBJECT (src, "Creating session (can share %d)", can_share);
1158 GST_SOUP_SESSION (g_object_new (GST_TYPE_SOUP_SESSION, NULL));
1160 GST_DEBUG_OBJECT (src, "Created session %p", src->session);
1162 ctx = g_main_context_new ();
1164 src->session->loop = g_main_loop_new (ctx, FALSE);
1165 /* now owned by the loop */
1166 g_main_context_unref (ctx);
1168 src->session->thread = g_thread_try_new ("souphttpsrc-thread",
1169 thread_func, src, NULL);
1171 if (!src->session->thread) {
1175 source = g_idle_source_new ();
1176 g_source_set_callback (source, _session_ready_cb, src, NULL);
1177 g_source_attach (source, ctx);
1178 g_source_unref (source);
1180 GST_DEBUG_OBJECT (src, "Waiting for thread to start...");
1181 while (!g_main_loop_is_running (src->session->loop))
1182 g_cond_wait (&src->session_cond, &src->session_mutex);
1183 GST_DEBUG_OBJECT (src, "Soup thread started");
1186 GST_OBJECT_UNLOCK (src);
1188 if (src->session_is_shared) {
1189 GstContext *context;
1190 GstMessage *message;
1193 GST_DEBUG_OBJECT (src->session, "Sharing session %p", src->session);
1195 context = gst_context_new (GST_SOUP_SESSION_CONTEXT, TRUE);
1196 s = gst_context_writable_structure (context);
1197 gst_structure_set (s, "session", GST_TYPE_SOUP_SESSION, src->session, NULL);
1199 gst_element_set_context (GST_ELEMENT_CAST (src), context);
1200 message = gst_message_new_have_context (GST_OBJECT_CAST (src), context);
1201 gst_element_post_message (GST_ELEMENT_CAST (src), message);
1207 g_clear_object (&src->session);
1208 GST_ELEMENT_ERROR (src, LIBRARY, INIT, (NULL), ("Failed to create session"));
1209 GST_OBJECT_UNLOCK (src);
1215 _session_close_cb (gpointer user_data)
1217 GstSoupHTTPSrc *src = user_data;
1220 gst_soup_session_cancel_message (src->session->session, src->msg,
1222 g_clear_object (&src->msg);
1225 /* there may be multiple of this callback attached to the session,
1226 * each with different data pointer; disconnect the one we are closing
1227 * the session for, leave the others alone
1229 g_signal_handlers_disconnect_by_func (src->session->session,
1230 G_CALLBACK (gst_soup_http_src_authenticate_cb_2), src);
1232 g_mutex_lock (&src->session_mutex);
1233 g_clear_object (&src->session);
1234 g_cond_signal (&src->session_cond);
1235 g_mutex_unlock (&src->session_mutex);
1241 gst_soup_http_src_session_close (GstSoupHTTPSrc * src)
1244 GstSoupSession *sess;
1246 GST_DEBUG_OBJECT (src, "Closing session");
1248 if (!src->session) {
1252 /* ensure _session_close_cb does not deadlock us */
1253 sess = g_object_ref (src->session);
1255 source = g_idle_source_new ();
1257 g_mutex_lock (&src->session_mutex);
1259 g_source_set_callback (source, _session_close_cb, src, NULL);
1260 g_source_attach (source, g_main_loop_get_context (src->session->loop));
1261 g_source_unref (source);
1263 while (src->session)
1264 g_cond_wait (&src->session_cond, &src->session_mutex);
1266 g_mutex_unlock (&src->session_mutex);
1268 /* finally dispose of our reference from the gst thread */
1269 g_object_unref (sess);
1273 gst_soup_http_src_authenticate_cb_2 (SoupSession * session, SoupMessage * msg,
1274 SoupAuth * auth, gboolean retrying, gpointer data)
1276 gst_soup_http_src_authenticate_cb (msg, auth, retrying, data);
1280 gst_soup_http_src_authenticate_cb (SoupMessage * msg, SoupAuth * auth,
1281 gboolean retrying, gpointer data)
1283 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (data);
1284 SoupStatus status_code;
1286 /* Might be from another user of the shared session */
1287 if (!GST_IS_SOUP_HTTP_SRC (src) || msg != src->msg)
1290 status_code = _soup_message_get_status (msg);
1293 /* First time authentication only, if we fail and are called again with
1294 * retry true fall through */
1295 if (status_code == SOUP_STATUS_UNAUTHORIZED) {
1296 if (src->user_id && src->user_pw) {
1297 _soup_auth_authenticate (auth, src->user_id, src->user_pw);
1299 } else if (status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1300 if (src->proxy_id && src->proxy_pw) {
1301 _soup_auth_authenticate (auth, src->proxy_id, src->proxy_pw);
1310 gst_soup_http_src_accept_certificate_cb (SoupMessage * msg,
1311 GTlsCertificate * tls_certificate, GTlsCertificateFlags tls_errors,
1314 GstSoupHTTPSrc *src = user_data;
1316 /* Might be from another user of the shared session */
1317 if (!GST_IS_SOUP_HTTP_SRC (src) || msg != src->msg)
1320 /* Accept invalid certificates */
1321 if (!src->ssl_strict)
1328 insert_http_header (const gchar * name, const gchar * value, gpointer user_data)
1330 GstStructure *headers = user_data;
1333 if (!g_utf8_validate (name, -1, NULL) || !g_utf8_validate (value, -1, NULL))
1336 gv = gst_structure_get_value (headers, name);
1337 if (gv && GST_VALUE_HOLDS_ARRAY (gv)) {
1338 GValue v = G_VALUE_INIT;
1340 g_value_init (&v, G_TYPE_STRING);
1341 g_value_set_string (&v, value);
1342 gst_value_array_append_value ((GValue *) gv, &v);
1344 } else if (gv && G_VALUE_HOLDS_STRING (gv)) {
1345 GValue arr = G_VALUE_INIT;
1346 GValue v = G_VALUE_INIT;
1347 const gchar *old_value = g_value_get_string (gv);
1349 g_value_init (&arr, GST_TYPE_ARRAY);
1350 g_value_init (&v, G_TYPE_STRING);
1351 g_value_set_string (&v, old_value);
1352 gst_value_array_append_value (&arr, &v);
1353 g_value_set_string (&v, value);
1354 gst_value_array_append_value (&arr, &v);
1356 gst_structure_set_value (headers, name, &arr);
1358 g_value_unset (&arr);
1360 gst_structure_set (headers, name, G_TYPE_STRING, value, NULL);
1364 static GstFlowReturn
1365 gst_soup_http_src_got_headers (GstSoupHTTPSrc * src, SoupMessage * msg)
1368 GstTagList *tag_list;
1369 GstBaseSrc *basesrc;
1371 GHashTable *params = NULL;
1372 GstEvent *http_headers_event;
1373 GstStructure *http_headers, *headers;
1374 const gchar *accept_ranges;
1375 SoupMessageHeaders *request_headers = _soup_message_get_request_headers (msg);
1376 SoupMessageHeaders *response_headers =
1377 _soup_message_get_response_headers (msg);
1378 SoupStatus status_code = _soup_message_get_status (msg);
1380 GST_INFO_OBJECT (src, "got headers");
1382 if (status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED &&
1383 src->proxy_id && src->proxy_pw) {
1384 /* wait for authenticate callback */
1388 http_headers = gst_structure_new_empty ("http-headers");
1389 gst_structure_set (http_headers, "uri", G_TYPE_STRING, src->location,
1390 "http-status-code", G_TYPE_UINT, status_code, NULL);
1391 if (src->redirection_uri)
1392 gst_structure_set (http_headers, "redirection-uri", G_TYPE_STRING,
1393 src->redirection_uri, NULL);
1394 headers = gst_structure_new_empty ("request-headers");
1395 _soup_message_headers_foreach (request_headers, insert_http_header, headers);
1396 gst_structure_set (http_headers, "request-headers", GST_TYPE_STRUCTURE,
1398 gst_structure_free (headers);
1399 headers = gst_structure_new_empty ("response-headers");
1400 _soup_message_headers_foreach (response_headers, insert_http_header, headers);
1401 gst_structure_set (http_headers, "response-headers", GST_TYPE_STRUCTURE,
1403 gst_structure_free (headers);
1405 gst_element_post_message (GST_ELEMENT_CAST (src),
1406 gst_message_new_element (GST_OBJECT_CAST (src),
1407 gst_structure_copy (http_headers)));
1409 if (status_code == SOUP_STATUS_UNAUTHORIZED) {
1410 /* force an error */
1411 gst_structure_free (http_headers);
1412 return gst_soup_http_src_parse_status (msg, src);
1415 src->got_headers = TRUE;
1417 http_headers_event =
1418 gst_event_new_custom (GST_EVENT_CUSTOM_DOWNSTREAM_STICKY, http_headers);
1419 gst_event_replace (&src->http_headers_event, http_headers_event);
1420 gst_event_unref (http_headers_event);
1422 /* Parse Content-Length. */
1423 if (SOUP_STATUS_IS_SUCCESSFUL (status_code) &&
1424 (_soup_message_headers_get_encoding (response_headers) ==
1425 SOUP_ENCODING_CONTENT_LENGTH)) {
1426 newsize = src->request_position +
1427 _soup_message_headers_get_content_length (response_headers);
1428 if (!src->have_size || (src->content_size != newsize)) {
1429 src->content_size = newsize;
1430 src->have_size = TRUE;
1431 src->seekable = TRUE;
1432 GST_DEBUG_OBJECT (src, "size = %" G_GUINT64_FORMAT, src->content_size);
1434 basesrc = GST_BASE_SRC_CAST (src);
1435 basesrc->segment.duration = src->content_size;
1436 gst_element_post_message (GST_ELEMENT (src),
1437 gst_message_new_duration_changed (GST_OBJECT (src)));
1441 /* If the server reports Accept-Ranges: none we don't have to try
1442 * doing range requests at all
1444 if ((accept_ranges =
1445 _soup_message_headers_get_one (response_headers, "Accept-Ranges"))) {
1446 if (g_ascii_strcasecmp (accept_ranges, "none") == 0)
1447 src->seekable = FALSE;
1451 tag_list = gst_tag_list_new_empty ();
1454 _soup_message_headers_get_one (response_headers,
1455 "icy-metaint")) != NULL) {
1458 if (g_utf8_validate (value, -1, NULL)) {
1459 icy_metaint = atoi (value);
1461 GST_DEBUG_OBJECT (src, "icy-metaint: %s (parsed: %d)", value,
1463 if (icy_metaint > 0) {
1465 gst_caps_unref (src->src_caps);
1467 src->src_caps = gst_caps_new_simple ("application/x-icy",
1468 "metadata-interval", G_TYPE_INT, icy_metaint, NULL);
1470 gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1475 _soup_message_headers_get_content_type (response_headers,
1476 ¶ms)) != NULL) {
1477 if (!g_utf8_validate (value, -1, NULL)) {
1478 GST_WARNING_OBJECT (src, "Content-Type is invalid UTF-8");
1479 } else if (g_ascii_strcasecmp (value, "audio/L16") == 0) {
1484 GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1486 if (src->src_caps) {
1487 gst_caps_unref (src->src_caps);
1488 src->src_caps = NULL;
1491 param = g_hash_table_lookup (params, "channels");
1492 if (param != NULL) {
1493 guint64 val = g_ascii_strtoull (param, NULL, 10);
1500 param = g_hash_table_lookup (params, "rate");
1501 if (param != NULL) {
1502 guint64 val = g_ascii_strtoull (param, NULL, 10);
1509 if (rate > 0 && channels > 0) {
1510 src->src_caps = gst_caps_new_simple ("audio/x-unaligned-raw",
1511 "format", G_TYPE_STRING, "S16BE",
1512 "layout", G_TYPE_STRING, "interleaved",
1513 "channels", G_TYPE_INT, channels, "rate", G_TYPE_INT, rate, NULL);
1515 gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1518 GST_DEBUG_OBJECT (src, "Content-Type: %s", value);
1520 /* Set the Content-Type field on the caps */
1521 if (src->src_caps) {
1522 src->src_caps = gst_caps_make_writable (src->src_caps);
1523 gst_caps_set_simple (src->src_caps, "content-type", G_TYPE_STRING,
1525 gst_base_src_set_caps (GST_BASE_SRC (src), src->src_caps);
1531 g_hash_table_destroy (params);
1534 _soup_message_headers_get_one (response_headers,
1535 "icy-name")) != NULL) {
1536 if (g_utf8_validate (value, -1, NULL)) {
1537 g_free (src->iradio_name);
1538 src->iradio_name = gst_soup_http_src_unicodify (value);
1539 if (src->iradio_name) {
1540 gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION,
1541 src->iradio_name, NULL);
1546 _soup_message_headers_get_one (response_headers,
1547 "icy-genre")) != NULL) {
1548 if (g_utf8_validate (value, -1, NULL)) {
1549 g_free (src->iradio_genre);
1550 src->iradio_genre = gst_soup_http_src_unicodify (value);
1551 if (src->iradio_genre) {
1552 gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE,
1553 src->iradio_genre, NULL);
1557 if ((value = _soup_message_headers_get_one (response_headers, "icy-url"))
1559 if (g_utf8_validate (value, -1, NULL)) {
1560 g_free (src->iradio_url);
1561 src->iradio_url = gst_soup_http_src_unicodify (value);
1562 if (src->iradio_url) {
1563 gst_tag_list_add (tag_list, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION,
1564 src->iradio_url, NULL);
1568 if (!gst_tag_list_is_empty (tag_list)) {
1569 GST_DEBUG_OBJECT (src,
1570 "calling gst_element_found_tags with %" GST_PTR_FORMAT, tag_list);
1571 gst_pad_push_event (GST_BASE_SRC_PAD (src), gst_event_new_tag (tag_list));
1573 gst_tag_list_unref (tag_list);
1576 /* Handle HTTP errors. */
1577 return gst_soup_http_src_parse_status (msg, src);
1581 gst_soup_http_src_alloc_buffer (GstSoupHTTPSrc * src)
1583 GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
1587 rc = GST_BASE_SRC_CLASS (parent_class)->alloc (basesrc, -1,
1588 basesrc->blocksize, &gstbuf);
1589 if (G_UNLIKELY (rc != GST_FLOW_OK)) {
1596 #define SOUP_HTTP_SRC_ERROR(src,soup_msg,cat,code,error_message) \
1598 GST_ELEMENT_ERROR_WITH_DETAILS ((src), cat, code, ("%s", error_message), \
1599 ("%s (%d), URL: %s, Redirect to: %s", _soup_message_get_reason_phrase (soup_msg), \
1600 _soup_message_get_status (soup_msg), (src)->location, GST_STR_NULL ((src)->redirection_uri)), \
1601 ("http-status-code", G_TYPE_UINT, _soup_message_get_status (soup_msg), \
1602 "http-redirect-uri", G_TYPE_STRING, GST_STR_NULL ((src)->redirection_uri), NULL)); \
1605 static GstFlowReturn
1606 gst_soup_http_src_parse_status (SoupMessage * msg, GstSoupHTTPSrc * src)
1608 SoupStatus status_code = _soup_message_get_status (msg);
1609 if (_soup_message_get_method (msg) == SOUP_METHOD_HEAD) {
1610 if (!SOUP_STATUS_IS_SUCCESSFUL (status_code))
1611 GST_DEBUG_OBJECT (src, "Ignoring error %d during HEAD request",
1616 /* SOUP_STATUS_IS_TRANSPORT_ERROR was replaced with GError in libsoup-3.0 */
1617 #if !defined(STATIC_SOUP) || STATIC_SOUP == 2
1618 if (SOUP_STATUS_IS_TRANSPORT_ERROR (status_code)) {
1619 switch (status_code) {
1620 case SOUP_STATUS_CANT_RESOLVE:
1621 case SOUP_STATUS_CANT_RESOLVE_PROXY:
1622 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND,
1623 _("Could not resolve server name."));
1624 return GST_FLOW_ERROR;
1625 case SOUP_STATUS_CANT_CONNECT:
1626 case SOUP_STATUS_CANT_CONNECT_PROXY:
1627 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1628 _("Could not establish connection to server."));
1629 return GST_FLOW_ERROR;
1630 case SOUP_STATUS_SSL_FAILED:
1631 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ,
1632 _("Secure connection setup failed."));
1633 return GST_FLOW_ERROR;
1634 case SOUP_STATUS_IO_ERROR:
1635 if (src->max_retries == -1 || src->retry_count < src->max_retries)
1636 return GST_FLOW_CUSTOM_ERROR;
1637 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1638 _("A network error occurred, or the server closed the connection "
1640 return GST_FLOW_ERROR;
1641 case SOUP_STATUS_MALFORMED:
1642 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, READ,
1643 _("Server sent bad data."));
1644 return GST_FLOW_ERROR;
1645 case SOUP_STATUS_CANCELLED:
1646 /* No error message when interrupted by program. */
1655 if (SOUP_STATUS_IS_CLIENT_ERROR (status_code) ||
1656 SOUP_STATUS_IS_REDIRECTION (status_code) ||
1657 SOUP_STATUS_IS_SERVER_ERROR (status_code)) {
1658 const gchar *reason_phrase;
1660 reason_phrase = _soup_message_get_reason_phrase (msg);
1661 if (reason_phrase && !g_utf8_validate (reason_phrase, -1, NULL)) {
1662 GST_ERROR_OBJECT (src, "Invalid UTF-8 in reason");
1663 reason_phrase = "(invalid)";
1666 /* Report HTTP error. */
1668 /* when content_size is unknown and we have just finished receiving
1669 * a body message, requests that go beyond the content limits will result
1670 * in an error. Here we convert those to EOS */
1671 if (status_code == SOUP_STATUS_REQUESTED_RANGE_NOT_SATISFIABLE &&
1672 src->have_body && (!src->have_size ||
1673 (src->request_position >= src->content_size))) {
1674 GST_DEBUG_OBJECT (src, "Requested range out of limits and received full "
1675 "body, returning EOS");
1676 return GST_FLOW_EOS;
1679 /* FIXME: reason_phrase is not translated and not suitable for user
1680 * error dialog according to libsoup documentation.
1682 if (status_code == SOUP_STATUS_NOT_FOUND) {
1683 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_FOUND, (reason_phrase));
1684 } else if (status_code == SOUP_STATUS_UNAUTHORIZED
1685 || status_code == SOUP_STATUS_PAYMENT_REQUIRED
1686 || status_code == SOUP_STATUS_FORBIDDEN
1687 || status_code == SOUP_STATUS_PROXY_AUTHENTICATION_REQUIRED) {
1688 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, NOT_AUTHORIZED, (reason_phrase));
1690 SOUP_HTTP_SRC_ERROR (src, msg, RESOURCE, OPEN_READ, (reason_phrase));
1692 return GST_FLOW_ERROR;
1699 gst_soup_http_src_restarted_cb (SoupMessage * msg, GstSoupHTTPSrc * src)
1701 SoupStatus status = _soup_message_get_status (msg);
1703 if (!SOUP_STATUS_IS_REDIRECTION (status))
1706 src->redirection_uri = gst_soup_message_uri_to_string (msg);
1707 src->redirection_permanent = (status == SOUP_STATUS_MOVED_PERMANENTLY);
1709 GST_DEBUG_OBJECT (src, "%u redirect to \"%s\" (permanent %d)",
1710 status, src->redirection_uri, src->redirection_permanent);
1714 gst_soup_http_src_build_message (GstSoupHTTPSrc * src, const gchar * method)
1716 SoupMessageHeaders *request_headers;
1718 g_return_val_if_fail (src->msg == NULL, FALSE);
1720 src->msg = _soup_message_new (method, src->location);
1722 GST_ELEMENT_ERROR (src, RESOURCE, OPEN_READ,
1723 ("Error parsing URL."), ("URL: %s", src->location));
1727 request_headers = _soup_message_get_request_headers (src->msg);
1729 /* Duplicating the defaults of libsoup here. We don't want to set a
1730 * User-Agent in the session as each source might have its own User-Agent
1732 if (!src->user_agent || !*src->user_agent) {
1734 g_strdup_printf ("libsoup/%u.%u.%u", _soup_get_major_version (),
1735 _soup_get_minor_version (), _soup_get_micro_version ());
1736 _soup_message_headers_append (request_headers, "User-Agent", user_agent);
1737 g_free (user_agent);
1738 } else if (g_str_has_suffix (src->user_agent, " ")) {
1739 gchar *user_agent = g_strdup_printf ("%slibsoup/%u.%u.%u", src->user_agent,
1740 _soup_get_major_version (),
1741 _soup_get_minor_version (), _soup_get_micro_version ());
1742 _soup_message_headers_append (request_headers, "User-Agent", user_agent);
1743 g_free (user_agent);
1745 _soup_message_headers_append (request_headers, "User-Agent",
1749 if (!src->keep_alive) {
1750 _soup_message_headers_append (request_headers, "Connection", "close");
1752 if (src->iradio_mode) {
1753 _soup_message_headers_append (request_headers, "icy-metadata", "1");
1758 for (cookie = src->cookies; *cookie != NULL; cookie++) {
1759 _soup_message_headers_append (request_headers, "Cookie", *cookie);
1762 _soup_message_disable_feature (src->msg, _soup_cookie_jar_get_type ());
1765 if (!src->compress) {
1766 _soup_message_headers_append (_soup_message_get_request_headers (src->msg),
1767 "Accept-Encoding", "identity");
1770 if (gst_soup_loader_get_api_version () == 3) {
1771 g_signal_connect (src->msg, "accept-certificate",
1772 G_CALLBACK (gst_soup_http_src_accept_certificate_cb), src);
1773 g_signal_connect (src->msg, "authenticate",
1774 G_CALLBACK (gst_soup_http_src_authenticate_cb), src);
1778 SoupMessageFlags flags =
1779 src->automatic_redirect ? 0 : SOUP_MESSAGE_NO_REDIRECT;
1781 /* SOUP_MESSAGE_OVERWRITE_CHUNKS is gone in libsoup-3.0, and
1782 * soup_message_body_set_accumulate() requires SoupMessageBody, which
1783 * can only be fetched from SoupServerMessage, not SoupMessage */
1784 #if !defined(STATIC_SOUP) || STATIC_SOUP == 2
1785 if (gst_soup_loader_get_api_version () == 2)
1786 flags |= SOUP_MESSAGE_OVERWRITE_CHUNKS;
1789 _soup_message_set_flags (src->msg, flags);
1792 if (src->automatic_redirect) {
1793 g_signal_connect (src->msg, "restarted",
1794 G_CALLBACK (gst_soup_http_src_restarted_cb), src);
1797 gst_soup_http_src_add_range_header (src, src->request_position,
1798 src->stop_position);
1800 gst_soup_http_src_add_extra_headers (src);
1805 struct GstSoupSendSrc
1807 GstSoupHTTPSrc *src;
1812 _session_send_cb (GObject * source, GAsyncResult * res, gpointer user_data)
1814 struct GstSoupSendSrc *msrc = user_data;
1815 GstSoupHTTPSrc *src = msrc->src;
1816 GError *error = NULL;
1818 g_mutex_lock (&src->session_mutex);
1820 src->input_stream = _soup_session_send_finish (src->session->session,
1823 if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
1824 src->headers_ret = GST_FLOW_FLUSHING;
1826 src->headers_ret = gst_soup_http_src_got_headers (src, src->msg);
1829 if (!src->input_stream) {
1830 GST_DEBUG_OBJECT (src, "Sending message failed: %s", error->message);
1831 msrc->error = error;
1834 g_cond_broadcast (&src->session_cond);
1835 g_mutex_unlock (&src->session_mutex);
1839 _session_send_idle_cb (gpointer user_data)
1841 struct GstSoupSendSrc *msrc = user_data;
1842 GstSoupHTTPSrc *src = msrc->src;
1844 _soup_session_send_async (src->session->session, src->msg, src->cancellable,
1845 _session_send_cb, msrc);
1850 /* called with session lock taken */
1851 static GstFlowReturn
1852 gst_soup_http_src_send_message (GstSoupHTTPSrc * src)
1856 struct GstSoupSendSrc msrc;
1858 g_return_val_if_fail (src->msg != NULL, GST_FLOW_ERROR);
1859 g_assert (src->input_stream == NULL);
1864 source = g_idle_source_new ();
1866 src->headers_ret = GST_FLOW_OK;
1868 g_source_set_callback (source, _session_send_idle_cb, &msrc, NULL);
1869 g_source_attach (source, g_main_loop_get_context (src->session->loop));
1870 g_source_unref (source);
1872 while (!src->input_stream && !msrc.error)
1873 g_cond_wait (&src->session_cond, &src->session_mutex);
1875 ret = src->headers_ret;
1877 if (ret != GST_FLOW_OK) {
1881 if (!src->input_stream) {
1882 GST_DEBUG_OBJECT (src, "Didn't get an input stream: %s",
1883 msrc.error->message);
1884 ret = GST_FLOW_ERROR;
1888 /* if an input stream exists, it was always successful */
1889 GST_DEBUG_OBJECT (src, "Successfully got a reply");
1892 g_clear_error (&msrc.error);
1896 /* called with session lock taken */
1897 static GstFlowReturn
1898 gst_soup_http_src_do_request (GstSoupHTTPSrc * src, const gchar * method)
1901 SoupMessageHeaders *request_headers;
1903 if (src->max_retries != -1 && src->retry_count > src->max_retries) {
1904 GST_DEBUG_OBJECT (src, "Max retries reached");
1905 return GST_FLOW_ERROR;
1909 /* EOS immediately if we have an empty segment */
1910 if (src->request_position == src->stop_position)
1911 return GST_FLOW_EOS;
1913 GST_LOG_OBJECT (src, "Running request for method: %s", method);
1916 request_headers = _soup_message_get_request_headers (src->msg);
1918 /* Update the position if we are retrying */
1919 if (src->msg && src->request_position > 0) {
1920 gst_soup_http_src_add_range_header (src, src->request_position,
1921 src->stop_position);
1922 } else if (src->msg && src->request_position == 0)
1923 _soup_message_headers_remove (request_headers, "Range");
1925 /* add_range_header() has the side effect of setting read_position to
1926 * the requested position. This *needs* to be set regardless of having
1927 * a message or not. Failure to do so would result in calculation being
1928 * done with stale/wrong read position */
1929 src->read_position = src->request_position;
1932 if (!gst_soup_http_src_build_message (src, method)) {
1933 return GST_FLOW_ERROR;
1937 if (g_cancellable_is_cancelled (src->cancellable)) {
1938 GST_INFO_OBJECT (src, "interrupted");
1939 return GST_FLOW_FLUSHING;
1942 ret = gst_soup_http_src_send_message (src);
1944 /* Check if Range header was respected. */
1945 if (ret == GST_FLOW_OK && src->request_position > 0 &&
1946 _soup_message_get_status (src->msg) != SOUP_STATUS_PARTIAL_CONTENT) {
1947 src->seekable = FALSE;
1948 GST_ELEMENT_ERROR_WITH_DETAILS (src, RESOURCE, SEEK,
1949 (_("Server does not support seeking.")),
1950 ("Server does not accept Range HTTP header, URL: %s, Redirect to: %s",
1951 src->location, GST_STR_NULL (src->redirection_uri)),
1952 ("http-status-code", G_TYPE_UINT, _soup_message_get_status (src->msg),
1953 "http-redirection-uri", G_TYPE_STRING,
1954 GST_STR_NULL (src->redirection_uri), NULL));
1955 ret = GST_FLOW_ERROR;
1962 * Check if the bytes_read is above a certain threshold of the blocksize, if
1963 * that happens a few times in a row, increase the blocksize; Do the same in
1964 * the opposite direction to reduce the blocksize.
1967 gst_soup_http_src_check_update_blocksize (GstSoupHTTPSrc * src,
1970 guint blocksize = gst_base_src_get_blocksize (GST_BASE_SRC_CAST (src));
1972 gint64 time_since_last_read =
1973 g_get_monotonic_time () * GST_USECOND - src->last_socket_read_time;
1975 GST_LOG_OBJECT (src, "Checking to update blocksize. Read: %" G_GINT64_FORMAT
1976 " bytes, blocksize: %u bytes, time since last read: %" GST_TIME_FORMAT,
1977 bytes_read, blocksize, GST_TIME_ARGS (time_since_last_read));
1979 if (bytes_read >= blocksize * GROW_BLOCKSIZE_LIMIT
1980 && time_since_last_read <= GROW_TIME_LIMIT) {
1981 src->reduce_blocksize_count = 0;
1982 src->increase_blocksize_count++;
1984 if (src->increase_blocksize_count >= GROW_BLOCKSIZE_COUNT) {
1985 blocksize *= GROW_BLOCKSIZE_FACTOR;
1986 GST_DEBUG_OBJECT (src, "Increased blocksize to %u", blocksize);
1987 gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
1988 src->increase_blocksize_count = 0;
1990 } else if (bytes_read < blocksize * REDUCE_BLOCKSIZE_LIMIT
1991 || time_since_last_read > GROW_TIME_LIMIT) {
1992 src->reduce_blocksize_count++;
1993 src->increase_blocksize_count = 0;
1995 if (src->reduce_blocksize_count >= REDUCE_BLOCKSIZE_COUNT) {
1996 blocksize *= REDUCE_BLOCKSIZE_FACTOR;
1997 blocksize = MAX (blocksize, src->minimum_blocksize);
1998 GST_DEBUG_OBJECT (src, "Decreased blocksize to %u", blocksize);
1999 gst_base_src_set_blocksize (GST_BASE_SRC_CAST (src), blocksize);
2000 src->reduce_blocksize_count = 0;
2003 src->reduce_blocksize_count = src->increase_blocksize_count = 0;
2008 gst_soup_http_src_update_position (GstSoupHTTPSrc * src, gint64 bytes_read)
2010 GstBaseSrc *basesrc = GST_BASE_SRC_CAST (src);
2011 guint64 new_position;
2013 new_position = src->read_position + bytes_read;
2014 if (G_LIKELY (src->request_position == src->read_position))
2015 src->request_position = new_position;
2016 src->read_position = new_position;
2018 if (src->have_size) {
2019 if (new_position > src->content_size) {
2020 GST_DEBUG_OBJECT (src, "Got position previous estimated content size "
2021 "(%" G_GINT64_FORMAT " > %" G_GINT64_FORMAT ")", new_position,
2023 src->content_size = new_position;
2024 basesrc->segment.duration = src->content_size;
2025 gst_element_post_message (GST_ELEMENT (src),
2026 gst_message_new_duration_changed (GST_OBJECT (src)));
2027 } else if (new_position == src->content_size) {
2028 GST_DEBUG_OBJECT (src, "We're EOS now");
2033 struct GstSoupReadResult
2035 GstSoupHTTPSrc *src;
2043 _session_read_cb (GObject * source, GAsyncResult * ret, gpointer user_data)
2045 struct GstSoupReadResult *res = user_data;
2047 g_mutex_lock (&res->src->session_mutex);
2049 res->nbytes = g_input_stream_read_finish (G_INPUT_STREAM (source),
2052 g_cond_signal (&res->src->session_cond);
2053 g_mutex_unlock (&res->src->session_mutex);
2057 _session_read_idle_cb (gpointer user_data)
2059 struct GstSoupReadResult *res = user_data;
2061 g_input_stream_read_async (res->src->input_stream, res->buffer,
2062 res->bufsize, G_PRIORITY_DEFAULT, res->src->cancellable,
2063 _session_read_cb, res);
2068 static GstFlowReturn
2069 gst_soup_http_src_read_buffer (GstSoupHTTPSrc * src, GstBuffer ** outbuf)
2071 struct GstSoupReadResult res;
2077 bsrc = GST_BASE_SRC_CAST (src);
2079 *outbuf = gst_soup_http_src_alloc_buffer (src);
2081 GST_WARNING_OBJECT (src, "Failed to allocate buffer");
2082 return GST_FLOW_ERROR;
2085 if (!gst_buffer_map (*outbuf, &mapinfo, GST_MAP_WRITE)) {
2086 GST_WARNING_OBJECT (src, "Failed to map buffer");
2087 return GST_FLOW_ERROR;
2091 res.buffer = mapinfo.data;
2092 res.bufsize = mapinfo.size;
2096 source = g_idle_source_new ();
2098 g_mutex_lock (&src->session_mutex);
2100 g_source_set_callback (source, _session_read_idle_cb, &res, NULL);
2101 /* invoke on libsoup thread */
2102 g_source_attach (source, g_main_loop_get_context (src->session->loop));
2103 g_source_unref (source);
2106 while (!res.error && res.nbytes < 0)
2107 g_cond_wait (&src->session_cond, &src->session_mutex);
2108 g_mutex_unlock (&src->session_mutex);
2110 GST_DEBUG_OBJECT (src, "Read %" G_GSSIZE_FORMAT " bytes from http input",
2114 /* retry by default */
2115 GstFlowReturn ret = GST_FLOW_CUSTOM_ERROR;
2116 if (g_error_matches (res.error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
2117 ret = GST_FLOW_FLUSHING;
2119 GST_ERROR_OBJECT (src, "Got error from libsoup: %s", res.error->message);
2121 g_error_free (res.error);
2122 gst_buffer_unmap (*outbuf, &mapinfo);
2123 gst_buffer_unref (*outbuf);
2127 gst_buffer_unmap (*outbuf, &mapinfo);
2128 if (res.nbytes > 0) {
2129 gst_buffer_set_size (*outbuf, res.nbytes);
2130 GST_BUFFER_OFFSET (*outbuf) = bsrc->segment.position;
2132 gst_soup_http_src_update_position (src, res.nbytes);
2134 /* Got some data, reset retry counter */
2135 src->retry_count = 0;
2137 gst_soup_http_src_check_update_blocksize (src, res.nbytes);
2139 src->last_socket_read_time = g_get_monotonic_time () * GST_USECOND;
2141 /* If we're at the end of a range request, read again to let libsoup
2142 * finalize the request. This allows to reuse the connection again later,
2143 * otherwise we would have to cancel the message and close the connection
2145 if (bsrc->segment.stop != -1
2146 && bsrc->segment.position + res.nbytes >= bsrc->segment.stop) {
2147 SoupMessage *msg = src->msg;
2151 res.bufsize = sizeof (tmp);
2155 src->have_body = TRUE;
2157 g_mutex_lock (&src->session_mutex);
2159 source = g_idle_source_new ();
2161 g_source_set_callback (source, _session_read_idle_cb, &res, NULL);
2162 /* This should return immediately as we're at the end of the range */
2163 g_source_attach (source, g_main_loop_get_context (src->session->loop));
2164 g_source_unref (source);
2166 while (!res.error && res.nbytes < 0)
2167 g_cond_wait (&src->session_cond, &src->session_mutex);
2168 g_mutex_unlock (&src->session_mutex);
2170 g_clear_error (&res.error);
2171 g_object_unref (msg);
2174 GST_ERROR_OBJECT (src,
2175 "Read %" G_GSIZE_FORMAT " bytes after end of range", res.nbytes);
2178 gst_buffer_unref (*outbuf);
2179 if (src->have_size && src->read_position < src->content_size) {
2180 /* Maybe the server disconnected, retry */
2181 ret = GST_FLOW_CUSTOM_ERROR;
2183 g_clear_object (&src->msg);
2186 src->have_body = TRUE;
2190 g_clear_error (&res.error);
2196 _session_stream_clear_cb (gpointer user_data)
2198 GstSoupHTTPSrc *src = user_data;
2200 g_mutex_lock (&src->session_mutex);
2202 g_clear_object (&src->input_stream);
2204 g_cond_signal (&src->session_cond);
2205 g_mutex_unlock (&src->session_mutex);
2211 gst_soup_http_src_stream_clear (GstSoupHTTPSrc * src)
2215 if (!src->input_stream)
2218 g_mutex_lock (&src->session_mutex);
2220 source = g_idle_source_new ();
2222 g_source_set_callback (source, _session_stream_clear_cb, src, NULL);
2223 g_source_attach (source, g_main_loop_get_context (src->session->loop));
2224 g_source_unref (source);
2226 while (src->input_stream)
2227 g_cond_wait (&src->session_cond, &src->session_mutex);
2229 g_mutex_unlock (&src->session_mutex);
2232 static GstFlowReturn
2233 gst_soup_http_src_create (GstPushSrc * psrc, GstBuffer ** outbuf)
2235 GstSoupHTTPSrc *src;
2236 GstFlowReturn ret = GST_FLOW_OK;
2237 GstEvent *http_headers_event = NULL;
2239 src = GST_SOUP_HTTP_SRC (psrc);
2243 /* Check for pending position change */
2244 if (src->request_position != src->read_position && src->input_stream) {
2245 gst_soup_http_src_stream_clear (src);
2248 if (g_cancellable_is_cancelled (src->cancellable)) {
2249 ret = GST_FLOW_FLUSHING;
2253 /* If we have no open connection to the server, start one */
2254 if (!src->input_stream) {
2256 g_mutex_lock (&src->session_mutex);
2258 gst_soup_http_src_do_request (src,
2259 src->method ? src->method : SOUP_METHOD_GET);
2260 http_headers_event = src->http_headers_event;
2261 src->http_headers_event = NULL;
2262 g_mutex_unlock (&src->session_mutex);
2265 if (ret == GST_FLOW_OK || ret == GST_FLOW_CUSTOM_ERROR) {
2266 if (http_headers_event) {
2267 gst_pad_push_event (GST_BASE_SRC_PAD (src), http_headers_event);
2268 http_headers_event = NULL;
2272 if (ret == GST_FLOW_OK)
2273 ret = gst_soup_http_src_read_buffer (src, outbuf);
2276 GST_DEBUG_OBJECT (src, "Returning %d %s", ret, gst_flow_get_name (ret));
2277 if (ret != GST_FLOW_OK) {
2278 if (http_headers_event)
2279 gst_event_unref (http_headers_event);
2281 if (src->input_stream) {
2282 gst_soup_http_src_stream_clear (src);
2284 if (ret == GST_FLOW_CUSTOM_ERROR) {
2290 if (ret == GST_FLOW_FLUSHING) {
2291 src->retry_count = 0;
2298 gst_soup_http_src_start (GstBaseSrc * bsrc)
2300 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2303 GST_DEBUG_OBJECT (src, "start(\"%s\")", src->location);
2305 g_mutex_lock (&src->session_mutex);
2306 ret = gst_soup_http_src_session_open (src);
2307 g_mutex_unlock (&src->session_mutex);
2312 gst_soup_http_src_stop (GstBaseSrc * bsrc)
2314 GstSoupHTTPSrc *src;
2316 src = GST_SOUP_HTTP_SRC (bsrc);
2317 GST_DEBUG_OBJECT (src, "stop()");
2319 gst_soup_http_src_stream_clear (src);
2321 if (src->keep_alive && !src->msg && !src->session_is_shared)
2322 g_cancellable_cancel (src->cancellable);
2324 gst_soup_http_src_session_close (src);
2326 gst_soup_http_src_reset (src);
2330 static GstStateChangeReturn
2331 gst_soup_http_src_change_state (GstElement * element, GstStateChange transition)
2333 GstStateChangeReturn ret;
2334 GstSoupHTTPSrc *src;
2336 src = GST_SOUP_HTTP_SRC (element);
2338 switch (transition) {
2339 case GST_STATE_CHANGE_READY_TO_NULL:
2340 gst_soup_http_src_session_close (src);
2346 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2352 gst_soup_http_src_set_context (GstElement * element, GstContext * context)
2354 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (element);
2356 if (g_strcmp0 (gst_context_get_context_type (context),
2357 GST_SOUP_SESSION_CONTEXT) == 0) {
2358 const GstStructure *s = gst_context_get_structure (context);
2360 GST_OBJECT_LOCK (src);
2362 g_clear_object (&src->external_session);
2363 gst_structure_get (s, "session", GST_TYPE_SOUP_SESSION,
2364 &src->external_session, NULL);
2366 GST_DEBUG_OBJECT (src, "Setting external session %p",
2367 src->external_session);
2368 GST_OBJECT_UNLOCK (src);
2371 GST_ELEMENT_CLASS (parent_class)->set_context (element, context);
2374 /* Interrupt a blocking request. */
2376 gst_soup_http_src_unlock (GstBaseSrc * bsrc)
2378 GstSoupHTTPSrc *src;
2380 src = GST_SOUP_HTTP_SRC (bsrc);
2381 GST_DEBUG_OBJECT (src, "unlock()");
2383 g_cancellable_cancel (src->cancellable);
2387 /* Interrupt interrupt. */
2389 gst_soup_http_src_unlock_stop (GstBaseSrc * bsrc)
2391 GstSoupHTTPSrc *src;
2393 src = GST_SOUP_HTTP_SRC (bsrc);
2394 GST_DEBUG_OBJECT (src, "unlock_stop()");
2396 g_cancellable_reset (src->cancellable);
2401 gst_soup_http_src_get_size (GstBaseSrc * bsrc, guint64 * size)
2403 GstSoupHTTPSrc *src;
2405 src = GST_SOUP_HTTP_SRC (bsrc);
2407 if (src->have_size) {
2408 GST_DEBUG_OBJECT (src, "get_size() = %" G_GUINT64_FORMAT,
2410 *size = src->content_size;
2413 GST_DEBUG_OBJECT (src, "get_size() = FALSE");
2418 gst_soup_http_src_check_seekable (GstSoupHTTPSrc * src)
2420 GstFlowReturn ret = GST_FLOW_OK;
2422 /* Special case to check if the server allows range requests
2423 * before really starting to get data in the buffer creation
2426 if (!src->got_headers && GST_STATE (src) >= GST_STATE_PAUSED) {
2427 g_mutex_lock (&src->session_mutex);
2428 while (!src->got_headers && !g_cancellable_is_cancelled (src->cancellable)
2429 && ret == GST_FLOW_OK) {
2430 if ((src->msg && _soup_message_get_method (src->msg) != SOUP_METHOD_HEAD)) {
2431 /* wait for the current request to finish */
2432 g_cond_wait (&src->session_cond, &src->session_mutex);
2433 ret = src->headers_ret;
2435 if (gst_soup_http_src_session_open (src)) {
2436 ret = gst_soup_http_src_do_request (src, SOUP_METHOD_HEAD);
2440 g_mutex_unlock (&src->session_mutex);
2445 gst_soup_http_src_is_seekable (GstBaseSrc * bsrc)
2447 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2449 gst_soup_http_src_check_seekable (src);
2451 return src->seekable;
2455 gst_soup_http_src_do_seek (GstBaseSrc * bsrc, GstSegment * segment)
2457 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2459 GST_DEBUG_OBJECT (src, "do_seek(%" G_GUINT64_FORMAT "-%" G_GUINT64_FORMAT
2460 ")", segment->start, segment->stop);
2461 if (src->read_position == segment->start &&
2462 src->request_position == src->read_position &&
2463 src->stop_position == segment->stop) {
2464 GST_DEBUG_OBJECT (src,
2465 "Seek to current read/end position and no seek pending");
2469 gst_soup_http_src_check_seekable (src);
2471 /* If we have no headers we don't know yet if it is seekable or not.
2472 * Store the start position and error out later if it isn't */
2473 if (src->got_headers && !src->seekable) {
2474 GST_WARNING_OBJECT (src, "Not seekable");
2478 if (segment->rate < 0.0 || segment->format != GST_FORMAT_BYTES) {
2479 GST_WARNING_OBJECT (src, "Invalid seek segment");
2483 if (src->have_size && segment->start >= src->content_size) {
2484 GST_WARNING_OBJECT (src,
2485 "Potentially seeking behind end of file, might EOS immediately");
2488 /* Wait for create() to handle the jump in offset. */
2489 src->request_position = segment->start;
2490 src->stop_position = segment->stop;
2496 gst_soup_http_src_query (GstBaseSrc * bsrc, GstQuery * query)
2498 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (bsrc);
2500 GstSchedulingFlags flags;
2501 gint minsize, maxsize, align;
2503 switch (GST_QUERY_TYPE (query)) {
2505 gst_query_set_uri (query, src->location);
2506 if (src->redirection_uri != NULL) {
2507 gst_query_set_uri_redirection (query, src->redirection_uri);
2508 gst_query_set_uri_redirection_permanent (query,
2509 src->redirection_permanent);
2519 ret = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
2521 switch (GST_QUERY_TYPE (query)) {
2522 case GST_QUERY_SCHEDULING:
2523 gst_query_parse_scheduling (query, &flags, &minsize, &maxsize, &align);
2524 flags |= GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED;
2525 gst_query_set_scheduling (query, flags, minsize, maxsize, align);
2535 gst_soup_http_src_set_location (GstSoupHTTPSrc * src, const gchar * uri,
2538 const char *alt_schemes[] = { "icy://", "icyx://" };
2541 if (src->location) {
2542 g_free (src->location);
2543 src->location = NULL;
2549 for (i = 0; i < G_N_ELEMENTS (alt_schemes); i++) {
2550 if (g_str_has_prefix (uri, alt_schemes[i])) {
2552 g_strdup_printf ("http://%s", uri + strlen (alt_schemes[i]));
2557 if (src->redirection_uri) {
2558 g_free (src->redirection_uri);
2559 src->redirection_uri = NULL;
2562 src->location = g_strdup (uri);
2568 gst_soup_http_src_set_proxy (GstSoupHTTPSrc * src, const gchar * uri)
2571 gst_soup_uri_free (src->proxy);
2575 if (uri == NULL || *uri == '\0')
2578 if (g_strstr_len (uri, -1, "://")) {
2579 src->proxy = gst_soup_uri_new (uri);
2581 gchar *new_uri = g_strconcat ("http://", uri, NULL);
2583 src->proxy = gst_soup_uri_new (new_uri);
2587 return (src->proxy != NULL);
2591 gst_soup_http_src_uri_get_type (GType type)
2596 static const gchar *const *
2597 gst_soup_http_src_uri_get_protocols (GType type)
2599 static const gchar *protocols[] = { "http", "https", "icy", "icyx", NULL };
2605 gst_soup_http_src_uri_get_uri (GstURIHandler * handler)
2607 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2609 /* FIXME: make thread-safe */
2610 return g_strdup (src->location);
2614 gst_soup_http_src_uri_set_uri (GstURIHandler * handler, const gchar * uri,
2617 GstSoupHTTPSrc *src = GST_SOUP_HTTP_SRC (handler);
2619 return gst_soup_http_src_set_location (src, uri, error);
2623 gst_soup_http_src_uri_handler_init (gpointer g_iface, gpointer iface_data)
2625 GstURIHandlerInterface *iface = (GstURIHandlerInterface *) g_iface;
2627 iface->get_type = gst_soup_http_src_uri_get_type;
2628 iface->get_protocols = gst_soup_http_src_uri_get_protocols;
2629 iface->get_uri = gst_soup_http_src_uri_get_uri;
2630 iface->set_uri = gst_soup_http_src_uri_set_uri;
2634 souphttpsrc_element_init (GstPlugin * plugin)
2636 gboolean ret = TRUE;
2638 GST_DEBUG_CATEGORY_INIT (souphttpsrc_debug, "souphttpsrc", 0,
2641 if (!soup_element_init (plugin))
2644 ret = gst_element_register (plugin, "souphttpsrc",
2645 GST_RANK_PRIMARY, GST_TYPE_SOUP_HTTP_SRC);