[GStreamer] Use smart pointers and modernize code in WebKitWebAudioSourceGStreamer
[WebKit-https.git] / Source / WebCore / platform / graphics / gstreamer / WebKitWebSourceGStreamer.cpp
index af9d6e2..2a7f89e 100644 (file)
 
 #if ENABLE(VIDEO) && USE(GSTREAMER)
 
-#include "Document.h"
-#include "Frame.h"
 #include "GRefPtrGStreamer.h"
-#include "GStreamerVersioning.h"
+#include "GStreamerUtilities.h"
+#include "GUniquePtrGStreamer.h"
+#include "HTTPHeaderNames.h"
+#include "MainThreadNotifier.h"
 #include "MediaPlayer.h"
-#include "NetworkingContext.h"
 #include "NotImplemented.h"
+#include "PlatformMediaResourceLoader.h"
+#include "ResourceError.h"
+#include "ResourceHandle.h"
 #include "ResourceHandleClient.h"
-#include "ResourceHandleInternal.h"
 #include "ResourceRequest.h"
 #include "ResourceResponse.h"
+#include "SharedBuffer.h"
 #include <gst/app/gstappsrc.h>
 #include <gst/gst.h>
 #include <gst/pbutils/missing-plugins.h>
+#include <wtf/MainThread.h>
 #include <wtf/Noncopyable.h>
-#include <wtf/gobject/GOwnPtr.h>
-#include <wtf/gobject/GRefPtr.h>
+#include <wtf/glib/GMutexLocker.h>
+#include <wtf/glib/GRefPtr.h>
+#include <wtf/glib/GUniquePtr.h>
 #include <wtf/text/CString.h>
 
 using namespace WebCore;
 
-class StreamingClient : public ResourceHandleClient {
-    WTF_MAKE_NONCOPYABLE(StreamingClient); WTF_MAKE_FAST_ALLOCATED;
+class StreamingClient {
     public:
         StreamingClient(WebKitWebSrc*);
         virtual ~StreamingClient();
 
-        virtual void willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&);
-        virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
+    protected:
+        char* createReadBuffer(size_t requestedSize, size_t& actualSize);
+        void handleResponseReceived(const ResourceResponse&);
+        void handleDataReceived(const char*, int);
+        void handleNotifyFinished();
 
-        virtual char* getBuffer(int, int*);
+        GstElement* m_src;
+};
+
+class CachedResourceStreamingClient final : public PlatformMediaResourceClient, public StreamingClient {
+    WTF_MAKE_NONCOPYABLE(CachedResourceStreamingClient);
+    public:
+        CachedResourceStreamingClient(WebKitWebSrc*);
+        virtual ~CachedResourceStreamingClient();
+
+    private:
+        // PlatformMediaResourceClient virtual methods.
+#if USE(SOUP)
+        char* getOrCreateReadBuffer(PlatformMediaResource&, size_t requestedSize, size_t& actualSize) override;
+#endif
+        void responseReceived(PlatformMediaResource&, const ResourceResponse&) override;
+        void dataReceived(PlatformMediaResource&, const char*, int) override;
+        void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) override;
+        void loadFailed(PlatformMediaResource&, const ResourceError&) override;
+        void loadFinished(PlatformMediaResource&) override;
+};
 
-        virtual void didReceiveData(ResourceHandle*, const char*, int, int);
-        virtual void didFinishLoading(ResourceHandle*, double /*finishTime*/);
-        virtual void didFail(ResourceHandle*, const ResourceError&);
-        virtual void wasBlocked(ResourceHandle*);
-        virtual void cannotShowURL(ResourceHandle*);
+class ResourceHandleStreamingClient : public ResourceHandleClient, public StreamingClient {
+    WTF_MAKE_NONCOPYABLE(ResourceHandleStreamingClient); WTF_MAKE_FAST_ALLOCATED;
+    public:
+        ResourceHandleStreamingClient(WebKitWebSrc*, ResourceRequest&&);
+        virtual ~ResourceHandleStreamingClient();
+
+        // StreamingClient virtual methods.
+        bool loadFailed() const;
+        void setDefersLoading(bool);
 
     private:
-        WebKitWebSrc* m_src;
+        // ResourceHandleClient virtual methods.
+#if USE(SOUP)
+        char* getOrCreateReadBuffer(size_t requestedSize, size_t& actualSize) override;
+#endif
+        ResourceRequest willSendRequest(ResourceHandle*, ResourceRequest&&, ResourceResponse&&) override;
+        void didReceiveResponse(ResourceHandle*, ResourceResponse&&) override;
+        void didReceiveData(ResourceHandle*, const char*, unsigned, int) override;
+        void didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&&, int encodedLength) override;
+        void didFinishLoading(ResourceHandle*, double /*finishTime*/) override;
+        void didFail(ResourceHandle*, const ResourceError&) override;
+        void wasBlocked(ResourceHandle*) override;
+        void cannotShowURL(ResourceHandle*) override;
+
+        ThreadIdentifier m_thread { 0 };
+        Lock m_initializeRunLoopConditionMutex;
+        Condition m_initializeRunLoopCondition;
+        RunLoop* m_runLoop { nullptr };
+        Lock m_terminateRunLoopConditionMutex;
+        Condition m_terminateRunLoopCondition;
+        RefPtr<ResourceHandle> m_resource;
+};
+
+enum MainThreadSourceNotification {
+    Start = 1 << 0,
+    Stop = 1 << 1,
+    NeedData = 1 << 2,
+    EnoughData = 1 << 3,
+    Seek = 1 << 4
 };
 
 #define WEBKIT_WEB_SRC_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE((obj), WEBKIT_TYPE_WEB_SRC, WebKitWebSrcPrivate))
@@ -69,45 +126,39 @@ struct _WebKitWebSrcPrivate {
     GstAppSrc* appsrc;
     GstPad* srcpad;
     gchar* uri;
+    bool keepAlive;
+    GUniquePtr<GstStructure> extraHeaders;
+    bool compress;
+    GUniquePtr<gchar> httpMethod;
 
-    RefPtr<WebCore::Frame> frame;
     WebCore::MediaPlayer* player;
 
-    StreamingClient* client;
-    RefPtr<ResourceHandle> resourceHandle;
+    RefPtr<PlatformMediaResourceLoader> loader;
+    RefPtr<PlatformMediaResource> resource;
+    std::unique_ptr<ResourceHandleStreamingClient> client;
+
+    bool didPassAccessControlCheck;
 
     guint64 offset;
     guint64 size;
     gboolean seekable;
-    gboolean paused;
+    bool paused;
+    bool isSeeking;
 
     guint64 requestedOffset;
 
-    guint needDataID;
-    guint enoughDataID;
-    guint seekID;
-
+    bool createdInMainThread;
+    MainThreadNotifier<MainThreadSourceNotification> notifier;
     GRefPtr<GstBuffer> buffer;
-
-    // icecast stuff
-    gboolean iradioMode;
-    gchar* iradioName;
-    gchar* iradioGenre;
-    gchar* iradioUrl;
-    gchar* iradioTitle;
-
-    // TRUE if appsrc's version is >= 0.10.27, see
-    // https://bugzilla.gnome.org/show_bug.cgi?id=609423
-    gboolean haveAppSrc27;
 };
 
 enum {
-    PROP_IRADIO_MODE = 1,
-    PROP_IRADIO_NAME,
-    PROP_IRADIO_GENRE,
-    PROP_IRADIO_URL,
-    PROP_IRADIO_TITLE,
-    PROP_LOCATION
+    PROP_0,
+    PROP_LOCATION,
+    PROP_KEEP_ALIVE,
+    PROP_EXTRA_HEADERS,
+    PROP_COMPRESS,
+    PROP_METHOD
 };
 
 static GstStaticPadTemplate srcTemplate = GST_STATIC_PAD_TEMPLATE("src",
@@ -127,21 +178,25 @@ static void webKitWebSrcGetProperty(GObject*, guint propertyID, GValue*, GParamS
 static GstStateChangeReturn webKitWebSrcChangeState(GstElement*, GstStateChange);
 
 static gboolean webKitWebSrcQueryWithParent(GstPad*, GstObject*, GstQuery*);
-#ifndef GST_API_VERSION_1
-static gboolean webKitWebSrcQuery(GstPad*, GstQuery*);
-#endif
-
-static void webKitWebSrcNeedDataCb(GstAppSrc*, guint length, gpointer userData);
-static void webKitWebSrcEnoughDataCb(GstAppSrc*, gpointer userData);
-static gboolean webKitWebSrcSeekDataCb(GstAppSrc*, guint64 offset, gpointer userData);
 
-static void webKitWebSrcStop(WebKitWebSrc*, bool);
+static void webKitWebSrcNeedData(WebKitWebSrc*);
+static void webKitWebSrcEnoughData(WebKitWebSrc*);
+static gboolean webKitWebSrcSeek(WebKitWebSrc*, guint64);
 
 static GstAppSrcCallbacks appsrcCallbacks = {
-    webKitWebSrcNeedDataCb,
-    webKitWebSrcEnoughDataCb,
-    webKitWebSrcSeekDataCb,
-    { 0 }
+    // need_data
+    [](GstAppSrc*, guint, gpointer userData) {
+        webKitWebSrcNeedData(WEBKIT_WEB_SRC(userData));
+    },
+    // enough_data
+    [](GstAppSrc*, gpointer userData) {
+        webKitWebSrcEnoughData(WEBKIT_WEB_SRC(userData));
+    },
+    // seek_data
+    [](GstAppSrc*, guint64 offset, gpointer userData) -> gboolean {
+        return webKitWebSrcSeek(WEBKIT_WEB_SRC(userData), offset);
+    },
+    { nullptr }
 };
 
 #define webkit_web_src_parent_class parent_class
@@ -163,51 +218,9 @@ static void webkit_web_src_class_init(WebKitWebSrcClass* klass)
 
     gst_element_class_add_pad_template(eklass,
                                        gst_static_pad_template_get(&srcTemplate));
-    setGstElementClassMetadata(eklass, "WebKit Web source element", "Source", "Handles HTTP/HTTPS uris",
+    gst_element_class_set_metadata(eklass, "WebKit Web source element", "Source", "Handles HTTP/HTTPS uris",
                                "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
 
-    // icecast stuff
-    g_object_class_install_property(oklass,
-                                    PROP_IRADIO_MODE,
-                                    g_param_spec_boolean("iradio-mode",
-                                                         "iradio-mode",
-                                                         "Enable internet radio mode (extraction of shoutcast/icecast metadata)",
-                                                         FALSE,
-                                                         (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
-
-    g_object_class_install_property(oklass,
-                                    PROP_IRADIO_NAME,
-                                    g_param_spec_string("iradio-name",
-                                                        "iradio-name",
-                                                        "Name of the stream",
-                                                        0,
-                                                        (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
-
-    g_object_class_install_property(oklass,
-                                    PROP_IRADIO_GENRE,
-                                    g_param_spec_string("iradio-genre",
-                                                        "iradio-genre",
-                                                        "Genre of the stream",
-                                                        0,
-                                                        (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
-                                                        
-    g_object_class_install_property(oklass,
-                                    PROP_IRADIO_URL,
-                                    g_param_spec_string("iradio-url",
-                                                        "iradio-url",
-                                                        "Homepage URL for radio stream",
-                                                        0,
-                                                        (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
-
-    g_object_class_install_property(oklass,
-                                    PROP_IRADIO_TITLE,
-                                    g_param_spec_string("iradio-title",
-                                                        "iradio-title",
-                                                        "Name of currently playing song",
-                                                        0,
-                                                        (GParamFlags) (G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)));
-
-
     /* Allows setting the uri using the 'location' property, which is used
      * for example by gst_element_make_from_uri() */
     g_object_class_install_property(oklass,
@@ -217,6 +230,23 @@ static void webkit_web_src_class_init(WebKitWebSrcClass* klass)
                                                         "Location to read from",
                                                         0,
                                                         (GParamFlags) (G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
+
+    g_object_class_install_property(oklass, PROP_KEEP_ALIVE,
+        g_param_spec_boolean("keep-alive", "keep-alive", "Use HTTP persistent connections",
+            FALSE, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
+
+    g_object_class_install_property(oklass, PROP_EXTRA_HEADERS,
+        g_param_spec_boxed("extra-headers", "Extra Headers", "Extra headers to append to the HTTP request",
+            GST_TYPE_STRUCTURE, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
+
+    g_object_class_install_property(oklass, PROP_COMPRESS,
+        g_param_spec_boolean("compress", "Compress", "Allow compressed content encodings",
+            FALSE, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
+
+    g_object_class_install_property(oklass, PROP_METHOD,
+        g_param_spec_string("method", "method", "The HTTP method to use (default: GET)",
+            nullptr, static_cast<GParamFlags>(G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)));
+
     eklass->change_state = webKitWebSrcChangeState;
 
     g_type_class_add_private(klass, sizeof(WebKitWebSrcPrivate));
@@ -227,8 +257,9 @@ static void webkit_web_src_init(WebKitWebSrc* src)
     WebKitWebSrcPrivate* priv = WEBKIT_WEB_SRC_GET_PRIVATE(src);
 
     src->priv = priv;
+    new (priv) WebKitWebSrcPrivate();
 
-    priv->client = new StreamingClient(src);
+    priv->createdInMainThread = isMainThread();
 
     priv->appsrc = GST_APP_SRC(gst_element_factory_make("appsrc", 0));
     if (!priv->appsrc) {
@@ -236,9 +267,6 @@ static void webkit_web_src_init(WebKitWebSrc* src)
         return;
     }
 
-    GstElementFactory* factory = GST_ELEMENT_FACTORY(GST_ELEMENT_GET_CLASS(priv->appsrc)->elementfactory);
-    priv->haveAppSrc27 = gst_plugin_feature_check_version(GST_PLUGIN_FEATURE(factory), 0, 10, 27);
-
     gst_bin_add(GST_BIN(src), GST_ELEMENT(priv->appsrc));
 
 
@@ -247,12 +275,8 @@ static void webkit_web_src_init(WebKitWebSrc* src)
 
     gst_element_add_pad(GST_ELEMENT(src), priv->srcpad);
 
-#ifdef GST_API_VERSION_1
     GST_OBJECT_FLAG_SET(priv->srcpad, GST_PAD_FLAG_NEED_PARENT);
     gst_pad_set_query_function(priv->srcpad, webKitWebSrcQueryWithParent);
-#else
-    gst_pad_set_query_function(priv->srcpad, webKitWebSrcQuery);
-#endif
 
     gst_app_src_set_callbacks(priv->appsrc, &appsrcCallbacks, src, 0);
     gst_app_src_set_emit_signals(priv->appsrc, FALSE);
@@ -275,10 +299,10 @@ static void webkit_web_src_init(WebKitWebSrc* src)
     // likely that libsoup already provides new data before
     // the queue is really empty.
     // This might need tweaking for ports not using libsoup.
-    if (priv->haveAppSrc27)
-        g_object_set(priv->appsrc, "min-percent", 20, NULL);
+    g_object_set(priv->appsrc, "min-percent", 20, NULL);
 
-    webKitWebSrcStop(src, false);
+    gst_app_src_set_caps(priv->appsrc, 0);
+    gst_app_src_set_size(priv->appsrc, -1);
 }
 
 static void webKitWebSrcDispose(GObject* object)
@@ -286,12 +310,7 @@ static void webKitWebSrcDispose(GObject* object)
     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
     WebKitWebSrcPrivate* priv = src->priv;
 
-    if (priv->buffer) {
-#ifdef GST_API_VERSION_1
-        unmapGstBuffer(priv->buffer.get());
-#endif
-        priv->buffer.clear();
-    }
+    priv->player = 0;
 
     GST_CALL_PARENT(G_OBJECT_CLASS, dispose, (object));
 }
@@ -301,9 +320,8 @@ static void webKitWebSrcFinalize(GObject* object)
     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
     WebKitWebSrcPrivate* priv = src->priv;
 
-    delete priv->client;
-
     g_free(priv->uri);
+    priv->~WebKitWebSrcPrivate();
 
     GST_CALL_PARENT(G_OBJECT_CLASS, finalize, (object));
 }
@@ -311,18 +329,24 @@ static void webKitWebSrcFinalize(GObject* object)
 static void webKitWebSrcSetProperty(GObject* object, guint propID, const GValue* value, GParamSpec* pspec)
 {
     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
-    WebKitWebSrcPrivate* priv = src->priv;
 
     switch (propID) {
-    case PROP_IRADIO_MODE:
-        priv->iradioMode = g_value_get_boolean(value);
-        break;
     case PROP_LOCATION:
-#ifdef GST_API_VERSION_1
         gst_uri_handler_set_uri(reinterpret_cast<GstURIHandler*>(src), g_value_get_string(value), 0);
-#else
-        gst_uri_handler_set_uri(reinterpret_cast<GstURIHandler*>(src), g_value_get_string(value));
-#endif
+        break;
+    case PROP_KEEP_ALIVE:
+        src->priv->keepAlive = g_value_get_boolean(value);
+        break;
+    case PROP_EXTRA_HEADERS: {
+        const GstStructure* s = gst_value_get_structure(value);
+        src->priv->extraHeaders.reset(s ? gst_structure_copy(s) : nullptr);
+        break;
+    }
+    case PROP_COMPRESS:
+        src->priv->compress = g_value_get_boolean(value);
+        break;
+    case PROP_METHOD:
+        src->priv->httpMethod.reset(g_value_dup_string(value));
         break;
     default:
         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
@@ -335,24 +359,22 @@ static void webKitWebSrcGetProperty(GObject* object, guint propID, GValue* value
     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
     WebKitWebSrcPrivate* priv = src->priv;
 
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
     switch (propID) {
-    case PROP_IRADIO_MODE:
-        g_value_set_boolean(value, priv->iradioMode);
-        break;
-    case PROP_IRADIO_NAME:
-        g_value_set_string(value, priv->iradioName);
+    case PROP_LOCATION:
+        g_value_set_string(value, priv->uri);
         break;
-    case PROP_IRADIO_GENRE:
-        g_value_set_string(value, priv->iradioGenre);
+    case PROP_KEEP_ALIVE:
+        g_value_set_boolean(value, priv->keepAlive);
         break;
-    case PROP_IRADIO_URL:
-        g_value_set_string(value, priv->iradioUrl);
+    case PROP_EXTRA_HEADERS:
+        gst_value_set_structure(value, priv->extraHeaders.get());
         break;
-    case PROP_IRADIO_TITLE:
-        g_value_set_string(value, priv->iradioTitle);
+    case PROP_COMPRESS:
+        g_value_set_boolean(value, priv->compress);
         break;
-    case PROP_LOCATION:
-        g_value_set_string(value, priv->uri);
+    case PROP_METHOD:
+        g_value_set_string(value, priv->httpMethod.get());
         break;
     default:
         G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propID, pspec);
@@ -360,125 +382,216 @@ static void webKitWebSrcGetProperty(GObject* object, guint propID, GValue* value
     }
 }
 
-
-static void webKitWebSrcStop(WebKitWebSrc* src, bool seeking)
+static void webKitWebSrcStop(WebKitWebSrc* src)
 {
     WebKitWebSrcPrivate* priv = src->priv;
 
-    if (priv->resourceHandle) {
-        priv->resourceHandle->cancel();
-        priv->resourceHandle.release();
+    if (priv->resource || (priv->loader && !priv->keepAlive)) {
+        GRefPtr<WebKitWebSrc> protector = WTF::ensureGRef(src);
+        priv->notifier.cancelPendingNotifications(MainThreadSourceNotification::NeedData | MainThreadSourceNotification::EnoughData | MainThreadSourceNotification::Seek);
+        priv->notifier.notify(MainThreadSourceNotification::Stop, [protector, keepAlive = priv->keepAlive] {
+            WebKitWebSrcPrivate* priv = protector->priv;
+
+            WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(protector.get()));
+            if (priv->resource) {
+                priv->resource->stop();
+                priv->resource->setClient(nullptr);
+                priv->resource = nullptr;
+            }
+
+            if (!keepAlive)
+                priv->loader = nullptr;
+        });
     }
-    priv->resourceHandle = 0;
 
-    if (priv->frame && !seeking)
-        priv->frame.clear();
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
 
-    priv->player = 0;
+    bool wasSeeking = std::exchange(priv->isSeeking, false);
+
+    priv->client = nullptr;
 
     if (priv->buffer) {
-#ifdef GST_API_VERSION_1
         unmapGstBuffer(priv->buffer.get());
-#endif
         priv->buffer.clear();
     }
 
-    GST_OBJECT_LOCK(src);
-    if (priv->needDataID)
-        g_source_remove(priv->needDataID);
-    priv->needDataID = 0;
+    priv->paused = false;
 
-    if (priv->enoughDataID)
-        g_source_remove(priv->enoughDataID);
-    priv->enoughDataID = 0;
+    priv->offset = 0;
+    priv->seekable = FALSE;
 
-    if (priv->seekID)
-        g_source_remove(priv->seekID);
-    priv->seekID = 0;
+    if (!wasSeeking) {
+        priv->size = 0;
+        priv->requestedOffset = 0;
+        priv->player = 0;
+    }
 
-    priv->paused = FALSE;
-    GST_OBJECT_UNLOCK(src);
+    locker.unlock();
 
-    g_free(priv->iradioName);
-    priv->iradioName = 0;
+    if (priv->appsrc) {
+        gst_app_src_set_caps(priv->appsrc, 0);
+        if (!wasSeeking)
+            gst_app_src_set_size(priv->appsrc, -1);
+    }
 
-    g_free(priv->iradioGenre);
-    priv->iradioGenre = 0;
+    GST_DEBUG_OBJECT(src, "Stopped request");
+}
 
-    g_free(priv->iradioUrl);
-    priv->iradioUrl = 0;
+static bool webKitWebSrcSetExtraHeader(GQuark fieldId, const GValue* value, gpointer userData)
+{
+    GUniquePtr<gchar> fieldContent;
 
-    g_free(priv->iradioTitle);
-    priv->iradioTitle = 0;
+    if (G_VALUE_HOLDS_STRING(value))
+        fieldContent.reset(g_value_dup_string(value));
+    else {
+        GValue dest = G_VALUE_INIT;
 
-    if (priv->appsrc) {
-        gst_app_src_set_caps(priv->appsrc, 0);
-        if (!seeking)
-            gst_app_src_set_size(priv->appsrc, -1);
+        g_value_init(&dest, G_TYPE_STRING);
+        if (g_value_transform(value, &dest))
+            fieldContent.reset(g_value_dup_string(&dest));
     }
 
-    priv->offset = 0;
-    priv->seekable = FALSE;
+    const gchar* fieldName = g_quark_to_string(fieldId);
+    if (!fieldContent.get()) {
+        GST_ERROR("extra-headers field '%s' contains no value or can't be converted to a string", fieldName);
+        return false;
+    }
 
-    if (!seeking) {
-        priv->size = 0;
-        priv->requestedOffset = 0;
+    GST_DEBUG("Appending extra header: \"%s: %s\"", fieldName, fieldContent.get());
+    ResourceRequest* request = static_cast<ResourceRequest*>(userData);
+    request->setHTTPHeaderField(fieldName, fieldContent.get());
+    return true;
+}
+
+static gboolean webKitWebSrcProcessExtraHeaders(GQuark fieldId, const GValue* value, gpointer userData)
+{
+    if (G_VALUE_TYPE(value) == GST_TYPE_ARRAY) {
+        unsigned size = gst_value_array_get_size(value);
+
+        for (unsigned i = 0; i < size; i++) {
+            if (!webKitWebSrcSetExtraHeader(fieldId, gst_value_array_get_value(value, i), userData))
+                return FALSE;
+        }
+        return TRUE;
     }
 
-    GST_DEBUG_OBJECT(src, "Stopped request");
+    if (G_VALUE_TYPE(value) == GST_TYPE_LIST) {
+        unsigned size = gst_value_list_get_size(value);
+
+        for (unsigned i = 0; i < size; i++) {
+            if (!webKitWebSrcSetExtraHeader(fieldId, gst_value_list_get_value(value, i), userData))
+                return FALSE;
+        }
+        return TRUE;
+    }
+
+    return webKitWebSrcSetExtraHeader(fieldId, value, userData);
 }
 
-static bool webKitWebSrcStart(WebKitWebSrc* src)
+static void webKitWebSrcStart(WebKitWebSrc* src)
 {
     WebKitWebSrcPrivate* priv = src->priv;
 
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+
+    priv->didPassAccessControlCheck = false;
+
     if (!priv->uri) {
         GST_ERROR_OBJECT(src, "No URI provided");
-        return false;
+        locker.unlock();
+        webKitWebSrcStop(src);
+        return;
     }
-    
-    KURL url = KURL(KURL(), priv->uri);
+
+    ASSERT(!priv->client);
+
+    GST_DEBUG_OBJECT(src, "Fetching %s", priv->uri);
+    URL url = URL(URL(), priv->uri);
 
     ResourceRequest request(url);
     request.setAllowCookies(true);
+    request.setFirstPartyForCookies(url);
 
-    NetworkingContext* context = 0;
-    FrameLoader* loader = priv->frame ? priv->frame->loader() : 0;
-    if (loader) {
-        loader->addExtraFieldsToSubresourceRequest(request);
-        context = loader->networkingContext();
-    }
+    priv->size = 0;
 
     if (priv->player)
         request.setHTTPReferrer(priv->player->referrer());
 
+    if (priv->httpMethod.get())
+        request.setHTTPMethod(priv->httpMethod.get());
+
+#if USE(SOUP)
+    // By default, HTTP Accept-Encoding is disabled here as we don't
+    // want the received response to be encoded in any way as we need
+    // to rely on the proper size of the returned data on
+    // didReceiveResponse.
+    // If Accept-Encoding is used, the server may send the data in encoded format and
+    // request.expectedContentLength() will have the "wrong" size (the size of the
+    // compressed data), even though the data received in didReceiveData is uncompressed.
+    // This is however useful to enable for adaptive streaming
+    // scenarios, when the demuxer needs to download playlists.
+    if (!priv->compress)
+        request.setAcceptEncoding(false);
+#endif
+
     // Let Apple web servers know we want to access their nice movie trailers.
     if (!g_ascii_strcasecmp("movies.apple.com", url.host().utf8().data())
         || !g_ascii_strcasecmp("trailers.apple.com", url.host().utf8().data()))
         request.setHTTPUserAgent("Quicktime/7.6.6");
 
     if (priv->requestedOffset) {
-        GOwnPtr<gchar> val;
-
-        val.set(g_strdup_printf("bytes=%" G_GUINT64_FORMAT "-", priv->requestedOffset));
-        request.setHTTPHeaderField("Range", val.get());
+        GUniquePtr<gchar> val(g_strdup_printf("bytes=%" G_GUINT64_FORMAT "-", priv->requestedOffset));
+        request.setHTTPHeaderField(HTTPHeaderName::Range, val.get());
     }
+    priv->offset = priv->requestedOffset;
 
-    if (priv->iradioMode)
-        request.setHTTPHeaderField("icy-metadata", "1");
-
-    // Needed to use DLNA streaming servers
-    request.setHTTPHeaderField("transferMode.dlna", "Streaming");
-
-    priv->resourceHandle = ResourceHandle::create(context, request, priv->client, false, false);
-    if (!priv->resourceHandle) {
-        GST_ERROR_OBJECT(src, "Failed to create ResourceHandle");
-        return false;
+    if (!priv->keepAlive) {
+        GST_DEBUG_OBJECT(src, "Persistent connection support disabled");
+        request.setHTTPHeaderField(HTTPHeaderName::Connection, "close");
     }
 
-    GST_DEBUG_OBJECT(src, "Started request");
+    if (priv->extraHeaders)
+        gst_structure_foreach(priv->extraHeaders.get(), webKitWebSrcProcessExtraHeaders, &request);
+
+    // We always request Icecast/Shoutcast metadata, just in case ...
+    request.setHTTPHeaderField(HTTPHeaderName::IcyMetadata, "1");
+
+    if (!priv->player || !priv->createdInMainThread) {
+        priv->client = std::make_unique<ResourceHandleStreamingClient>(src, WTFMove(request));
+        if (priv->client->loadFailed()) {
+            GST_ERROR_OBJECT(src, "Failed to setup streaming client");
+            priv->client = nullptr;
+            locker.unlock();
+            webKitWebSrcStop(src);
+        } else
+            GST_DEBUG_OBJECT(src, "Started request");
+        return;
+    }
 
-    return true;
+    locker.unlock();
+    GRefPtr<WebKitWebSrc> protector = WTF::ensureGRef(src);
+    priv->notifier.notify(MainThreadSourceNotification::Start, [protector, request = WTFMove(request)] {
+        WebKitWebSrcPrivate* priv = protector->priv;
+
+        WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(protector.get()));
+        if (!priv->loader)
+            priv->loader = priv->player->createResourceLoader();
+
+        PlatformMediaResourceLoader::LoadOptions loadOptions = 0;
+        if (request.url().protocolIsBlob())
+            loadOptions |= PlatformMediaResourceLoader::LoadOption::BufferData;
+        // FIXME: request should be moved for efficiency
+        priv->resource = priv->loader->requestResource(ResourceRequest(request), loadOptions);
+        if (priv->resource) {
+            priv->resource->setClient(std::make_unique<CachedResourceStreamingClient>(protector.get()));
+            GST_DEBUG_OBJECT(protector.get(), "Started request");
+        } else {
+            GST_ERROR_OBJECT(protector.get(), "Failed to setup streaming client");
+            priv->loader = nullptr;
+            locker.unlock();
+            webKitWebSrcStop(protector.get());
+        }
+    });
 }
 
 static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStateChange transition)
@@ -508,14 +621,17 @@ static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStat
 
     switch (transition) {
     case GST_STATE_CHANGE_READY_TO_PAUSED:
+    {
         GST_DEBUG_OBJECT(src, "READY->PAUSED");
-        if (!webKitWebSrcStart(src))
-            ret = GST_STATE_CHANGE_FAILURE;
+        webKitWebSrcStart(src);
         break;
+    }
     case GST_STATE_CHANGE_PAUSED_TO_READY:
+    {
         GST_DEBUG_OBJECT(src, "PAUSED->READY");
-        webKitWebSrcStop(src, false);
+        webKitWebSrcStop(src);
         break;
+    }
     default:
         break;
     }
@@ -525,7 +641,7 @@ static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStat
 
 static gboolean webKitWebSrcQueryWithParent(GstPad* pad, GstObject* parent, GstQuery* query)
 {
-    WebKitWebSrc* webkitSrc = WEBKIT_WEB_SRC(GST_ELEMENT(parent));
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(GST_ELEMENT(parent));
     gboolean result = FALSE;
 
     switch (GST_QUERY_TYPE(query)) {
@@ -534,15 +650,26 @@ static gboolean webKitWebSrcQueryWithParent(GstPad* pad, GstObject* parent, GstQ
 
         gst_query_parse_duration(query, &format, NULL);
 
-        GST_DEBUG_OBJECT(webkitSrc, "duration query in format %s", gst_format_get_name(format));
-        if ((format == GST_FORMAT_BYTES) && (webkitSrc->priv->size > 0)) {
-            gst_query_set_duration(query, format, webkitSrc->priv->size);
+        GST_DEBUG_OBJECT(src, "duration query in format %s", gst_format_get_name(format));
+        WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+        if (format == GST_FORMAT_BYTES && src->priv->size > 0) {
+            gst_query_set_duration(query, format, src->priv->size);
             result = TRUE;
         }
         break;
     }
     case GST_QUERY_URI: {
-        gst_query_set_uri(query, webkitSrc->priv->uri);
+        WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+        gst_query_set_uri(query, src->priv->uri);
+        result = TRUE;
+        break;
+    }
+    case GST_QUERY_SCHEDULING: {
+        GstSchedulingFlags flags;
+        int minSize, maxSize, align;
+
+        gst_query_parse_scheduling(query, &flags, &minSize, &maxSize, &align);
+        gst_query_set_scheduling(query, static_cast<GstSchedulingFlags>(flags | GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED), minSize, maxSize, align);
         result = TRUE;
         break;
     }
@@ -559,17 +686,13 @@ static gboolean webKitWebSrcQueryWithParent(GstPad* pad, GstObject* parent, GstQ
     return result;
 }
 
-#ifndef GST_API_VERSION_1
-static gboolean webKitWebSrcQuery(GstPad* pad, GstQuery* query)
+static bool urlHasSupportedProtocol(const URL& url)
 {
-    GRefPtr<GstElement> src = adoptGRef(gst_pad_get_parent_element(pad));
-    return webKitWebSrcQueryWithParent(pad, GST_OBJECT(src.get()), query);
+    return url.isValid() && (url.protocolIsInHTTPFamily() || url.protocolIsBlob());
 }
-#endif
 
 // uri handler interface
 
-#ifdef GST_API_VERSION_1
 static GstURIType webKitWebSrcUriGetType(GType)
 {
     return GST_URI_SRC;
@@ -577,60 +700,21 @@ static GstURIType webKitWebSrcUriGetType(GType)
 
 const gchar* const* webKitWebSrcGetProtocols(GType)
 {
-    static const char* protocols[] = {"http", "https", 0 };
+    static const char* protocols[] = {"http", "https", "blob", 0 };
     return protocols;
 }
 
 static gchar* webKitWebSrcGetUri(GstURIHandler* handler)
 {
-    return g_strdup(WEBKIT_WEB_SRC(handler)->priv->uri);
-}
-
-static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri, GError** error)
-{
     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
-    WebKitWebSrcPrivate* priv = src->priv;
-
-    if (GST_STATE(src) >= GST_STATE_PAUSED) {
-        GST_ERROR_OBJECT(src, "URI can only be set in states < PAUSED");
-        return FALSE;
-    }
-
-    g_free(priv->uri);
-    priv->uri = 0;
-
-    if (!uri)
-        return TRUE;
-
-    KURL url(KURL(), uri);
-
-    if (!url.isValid() || !url.protocolIsInHTTPFamily()) {
-        g_set_error(error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI, "Invalid URI '%s'", uri);
-        return FALSE;
-    }
-
-    priv->uri = g_strdup(url.string().utf8().data());
-    return TRUE;
-}
+    gchar* ret;
 
-#else
-static GstURIType webKitWebSrcUriGetType(void)
-{
-    return GST_URI_SRC;
-}
-
-static gchar** webKitWebSrcGetProtocols(void)
-{
-    static gchar* protocols[] = {(gchar*) "http", (gchar*) "https", 0 };
-    return protocols;
-}
-
-static const gchar* webKitWebSrcGetUri(GstURIHandler* handler)
-{
-    return g_strdup(WEBKIT_WEB_SRC(handler)->priv->uri);
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+    ret = g_strdup(src->priv->uri);
+    return ret;
 }
 
-static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri)
+static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri, GError** error)
 {
     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
     WebKitWebSrcPrivate* priv = src->priv;
@@ -640,23 +724,23 @@ static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri)
         return FALSE;
     }
 
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+
     g_free(priv->uri);
     priv->uri = 0;
 
     if (!uri)
         return TRUE;
 
-    KURL url(KURL(), uri);
-
-    if (!url.isValid() || !url.protocolIsInHTTPFamily()) {
-        GST_ERROR_OBJECT(src, "Invalid URI '%s'", uri);
+    URL url(URL(), uri);
+    if (!urlHasSupportedProtocol(url)) {
+        g_set_error(error, GST_URI_ERROR, GST_URI_ERROR_BAD_URI, "Invalid URI '%s'", uri);
         return FALSE;
     }
 
     priv->uri = g_strdup(url.string().utf8().data());
     return TRUE;
 }
-#endif
 
 static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer)
 {
@@ -668,303 +752,447 @@ static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer)
     iface->set_uri = webKitWebSrcSetUri;
 }
 
-// appsrc callbacks
-
-static gboolean webKitWebSrcNeedDataMainCb(WebKitWebSrc* src)
-{
-    WebKitWebSrcPrivate* priv = src->priv;
-
-    priv->resourceHandle->setDefersLoading(false);
-
-    GST_OBJECT_LOCK(src);
-    priv->paused = FALSE;
-    priv->needDataID = 0;
-    GST_OBJECT_UNLOCK(src);
-    return FALSE;
-}
-
-static void webKitWebSrcNeedDataCb(GstAppSrc*, guint length, gpointer userData)
+static void webKitWebSrcNeedData(WebKitWebSrc* src)
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
     WebKitWebSrcPrivate* priv = src->priv;
 
-    GST_DEBUG_OBJECT(src, "Need more data: %u", length);
+    GST_DEBUG_OBJECT(src, "Need more data");
 
-    GST_OBJECT_LOCK(src);
-    if (priv->needDataID || !priv->paused) {
-        GST_OBJECT_UNLOCK(src);
-        return;
+    {
+        WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+        if (!priv->paused)
+            return;
+        priv->paused = false;
+        if (priv->client) {
+            priv->client->setDefersLoading(false);
+            return;
+        }
     }
 
-    priv->needDataID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcNeedDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
-    GST_OBJECT_UNLOCK(src);
+    GRefPtr<WebKitWebSrc> protector = WTF::ensureGRef(src);
+    priv->notifier.notify(MainThreadSourceNotification::NeedData, [protector] {
+        WebKitWebSrcPrivate* priv = protector->priv;
+        if (priv->resource)
+            priv->resource->setDefersLoading(false);
+    });
 }
 
-static gboolean webKitWebSrcEnoughDataMainCb(WebKitWebSrc* src)
+static void webKitWebSrcEnoughData(WebKitWebSrc* src)
 {
     WebKitWebSrcPrivate* priv = src->priv;
 
-    priv->resourceHandle->setDefersLoading(true);
-
-    GST_OBJECT_LOCK(src);
-    priv->paused = TRUE;
-    priv->enoughDataID = 0;
-    GST_OBJECT_UNLOCK(src);
-
-    return FALSE;
-}
-
-static void webKitWebSrcEnoughDataCb(GstAppSrc*, gpointer userData)
-{
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
-    WebKitWebSrcPrivate* priv = src->priv;
-
     GST_DEBUG_OBJECT(src, "Have enough data");
 
-    GST_OBJECT_LOCK(src);
-    if (priv->enoughDataID || priv->paused) {
-        GST_OBJECT_UNLOCK(src);
-        return;
+    {
+        WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+        if (priv->paused)
+            return;
+        priv->paused = true;
+        if (priv->client) {
+            priv->client->setDefersLoading(true);
+            return;
+        }
     }
 
-    priv->enoughDataID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcEnoughDataMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
-    GST_OBJECT_UNLOCK(src);
-}
-
-static gboolean webKitWebSrcSeekMainCb(WebKitWebSrc* src)
-{
-    webKitWebSrcStop(src, true);
-    webKitWebSrcStart(src);
-
-    return FALSE;
+    GRefPtr<WebKitWebSrc> protector = WTF::ensureGRef(src);
+    priv->notifier.notify(MainThreadSourceNotification::EnoughData, [protector] {
+        WebKitWebSrcPrivate* priv = protector->priv;
+        if (priv->resource)
+            priv->resource->setDefersLoading(true);
+    });
 }
 
-static gboolean webKitWebSrcSeekDataCb(GstAppSrc*, guint64 offset, gpointer userData)
+static gboolean webKitWebSrcSeek(WebKitWebSrc* src, guint64 offset)
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
     WebKitWebSrcPrivate* priv = src->priv;
 
-    GST_DEBUG_OBJECT(src, "Seeking to offset: %" G_GUINT64_FORMAT, offset);
-    if (offset == priv->offset)
-        return TRUE;
+    {
+        WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+        if (offset == priv->offset && priv->requestedOffset == priv->offset)
+            return TRUE;
 
-    if (!priv->seekable)
-        return FALSE;
-    if (offset > priv->size)
-        return FALSE;
+        if (!priv->seekable)
+            return FALSE;
+
+        priv->isSeeking = true;
+        priv->requestedOffset = offset;
+    }
 
-    GST_DEBUG_OBJECT(src, "Doing range-request seek");
-    priv->requestedOffset = offset;
+    GST_DEBUG_OBJECT(src, "Seeking to offset: %" G_GUINT64_FORMAT, src->priv->requestedOffset);
+    if (priv->client) {
+        webKitWebSrcStop(src);
+        webKitWebSrcStart(src);
+        return TRUE;
+    }
 
-    GST_OBJECT_LOCK(src);
-    if (priv->seekID)
-        g_source_remove(priv->seekID);
-    priv->seekID = g_timeout_add_full(G_PRIORITY_DEFAULT, 0, (GSourceFunc) webKitWebSrcSeekMainCb, gst_object_ref(src), (GDestroyNotify) gst_object_unref);
-    GST_OBJECT_UNLOCK(src);
-    
+    GRefPtr<WebKitWebSrc> protector = WTF::ensureGRef(src);
+    priv->notifier.notify(MainThreadSourceNotification::Seek, [protector] {
+        webKitWebSrcStop(protector.get());
+        webKitWebSrcStart(protector.get());
+    });
     return TRUE;
 }
 
 void webKitWebSrcSetMediaPlayer(WebKitWebSrc* src, WebCore::MediaPlayer* player)
 {
-    WebKitWebSrcPrivate* priv = src->priv;
-    WebCore::Frame* frame = 0;
-
-    WebCore::Document* document = player->mediaPlayerClient()->mediaPlayerOwningDocument();
-    if (document)
-        frame = document->frame();
-
-    priv->frame = frame;
-    priv->player = player;
+    ASSERT(player);
+    ASSERT(src->priv->createdInMainThread);
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+    src->priv->player = player;
 }
 
-StreamingClient::StreamingClient(WebKitWebSrc* src) : m_src(src)
+bool webKitSrcPassedCORSAccessCheck(WebKitWebSrc* src)
 {
+    return src->priv->didPassAccessControlCheck;
+}
 
+StreamingClient::StreamingClient(WebKitWebSrc* src)
+    : m_src(static_cast<GstElement*>(gst_object_ref(src)))
+{
 }
 
 StreamingClient::~StreamingClient()
 {
-
+    gst_object_unref(m_src);
 }
 
-void StreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&)
+char* StreamingClient::createReadBuffer(size_t requestedSize, size_t& actualSize)
 {
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
+    WebKitWebSrcPrivate* priv = src->priv;
+
+    ASSERT(!priv->buffer);
+
+    GstBuffer* buffer = gst_buffer_new_and_alloc(requestedSize);
+
+    mapGstBuffer(buffer, GST_MAP_WRITE);
+
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+    priv->buffer = adoptGRef(buffer);
+    locker.unlock();
+
+    actualSize = gst_buffer_get_size(buffer);
+    return getGstBufferDataPointer(buffer);
 }
 
-void StreamingClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
+void StreamingClient::handleResponseReceived(const ResourceResponse& response)
 {
-    WebKitWebSrcPrivate* priv = m_src->priv;
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
+    WebKitWebSrcPrivate* priv = src->priv;
 
-    GST_DEBUG_OBJECT(m_src, "Received response: %d", response.httpStatusCode());
+    GST_DEBUG_OBJECT(src, "Received response: %d", response.httpStatusCode());
 
-    // If we seeked we need 206 == PARTIAL_CONTENT
-    if (priv->requestedOffset && response.httpStatusCode() != 206) {
-        GST_ELEMENT_ERROR(m_src, RESOURCE, READ, (0), (0));
+    if (response.httpStatusCode() >= 400) {
+        GST_ELEMENT_ERROR(src, RESOURCE, READ, ("Received %d HTTP error code", response.httpStatusCode()), (nullptr));
         gst_app_src_end_of_stream(priv->appsrc);
-        webKitWebSrcStop(m_src, false);
+        webKitWebSrcStop(src);
         return;
     }
 
-    long long length = response.expectedContentLength();
-    if (length > 0) {
-        length += priv->requestedOffset;
-        gst_app_src_set_size(priv->appsrc, length);
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
 
-#ifndef GST_API_VERSION_1
-        if (!priv->haveAppSrc27) {
-            gst_segment_set_duration(&GST_BASE_SRC(priv->appsrc)->segment, GST_FORMAT_BYTES, length);
-            gst_element_post_message(GST_ELEMENT(priv->appsrc),
-                                     gst_message_new_duration(GST_OBJECT(priv->appsrc),
-                                                              GST_FORMAT_BYTES, length));
-        }
-#endif
+    if (priv->isSeeking) {
+        GST_DEBUG_OBJECT(src, "Seek in progress, ignoring response");
+        return;
     }
 
-    priv->size = length >= 0 ? length : 0;
-    priv->seekable = length > 0 && g_ascii_strcasecmp("none", response.httpHeaderField("Accept-Ranges").utf8().data());
-
-    // icecast stuff
-    String value = response.httpHeaderField("icy-metaint");
-    if (!value.isEmpty()) {
-        gchar* endptr = 0;
-        gint64 icyMetaInt = g_ascii_strtoll(value.utf8().data(), &endptr, 10);
-            
-        if (endptr && *endptr == '\0' && icyMetaInt > 0) {
-            GRefPtr<GstCaps> caps = adoptGRef(gst_caps_new_simple("application/x-icy", "metadata-interval", G_TYPE_INT, (gint) icyMetaInt, NULL));
-
-            gst_app_src_set_caps(priv->appsrc, caps.get());
+    if (priv->requestedOffset) {
+        // Seeking ... we expect a 206 == PARTIAL_CONTENT
+        if (response.httpStatusCode() == 200) {
+            // Range request didn't have a ranged response; resetting offset.
+            priv->offset = 0;
+        } else if (response.httpStatusCode() != 206) {
+            // Range request completely failed.
+            locker.unlock();
+            GST_ELEMENT_ERROR(src, RESOURCE, READ, ("Received unexpected %d HTTP status code", response.httpStatusCode()), (nullptr));
+            gst_app_src_end_of_stream(priv->appsrc);
+            webKitWebSrcStop(src);
+            return;
         }
     }
 
-#ifdef GST_API_VERSION_1
-    GstTagList* tags = gst_tag_list_new_empty();
-#else
-    GstTagList* tags = gst_tag_list_new();
-#endif
-    value = response.httpHeaderField("icy-name");
-    if (!value.isEmpty()) {
-        g_free(priv->iradioName);
-        priv->iradioName = g_strdup(value.utf8().data());
-        g_object_notify(G_OBJECT(m_src), "iradio-name");
-        gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, priv->iradioName, NULL);
-    }
-    value = response.httpHeaderField("icy-genre");
-    if (!value.isEmpty()) {
-        g_free(priv->iradioGenre);
-        priv->iradioGenre = g_strdup(value.utf8().data());
-        g_object_notify(G_OBJECT(m_src), "iradio-genre");
-        gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, priv->iradioGenre, NULL);
-    }
-    value = response.httpHeaderField("icy-url");
-    if (!value.isEmpty()) {
-        g_free(priv->iradioUrl);
-        priv->iradioUrl = g_strdup(value.utf8().data());
-        g_object_notify(G_OBJECT(m_src), "iradio-url");
-        gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, priv->iradioUrl, NULL);
-    }
-    value = response.httpHeaderField("icy-title");
-    if (!value.isEmpty()) {
-        g_free(priv->iradioTitle);
-        priv->iradioTitle = g_strdup(value.utf8().data());
-        g_object_notify(G_OBJECT(m_src), "iradio-title");
-        gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_TITLE, priv->iradioTitle, NULL);
-    }
-
-    if (gst_tag_list_is_empty(tags))
-#ifdef GST_API_VERSION_1
-        gst_tag_list_unref(tags);
-#else
-        gst_tag_list_free(tags);
-#endif
-    else
-        notifyGstTagsOnPad(GST_ELEMENT(m_src), m_src->priv->srcpad, tags);
+    long long length = response.expectedContentLength();
+    if (length > 0 && priv->requestedOffset && response.httpStatusCode() == 206)
+        length += priv->requestedOffset;
+
+    priv->size = length >= 0 ? length : 0;
+    priv->seekable = length > 0 && g_ascii_strcasecmp("none", response.httpHeaderField(HTTPHeaderName::AcceptRanges).utf8().data());
+
+    locker.unlock();
+
+    // notify size/duration
+    if (length > 0) {
+        gst_app_src_set_size(priv->appsrc, length);
+    } else
+        gst_app_src_set_size(priv->appsrc, -1);
+
+    gst_app_src_set_caps(priv->appsrc, 0);
 }
 
-void StreamingClient::didReceiveData(ResourceHandle* handle, const char* data, int length, int)
+void StreamingClient::handleDataReceived(const char* data, int length)
 {
-    WebKitWebSrcPrivate* priv = m_src->priv;
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
+    WebKitWebSrcPrivate* priv = src->priv;
+
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
 
-    GST_LOG_OBJECT(m_src, "Have %d bytes of data", priv->buffer ? getGstBufferSize(priv->buffer.get()) : length);
+    GST_LOG_OBJECT(src, "Have %lld bytes of data", priv->buffer ? static_cast<long long>(gst_buffer_get_size(priv->buffer.get())) : length);
 
     ASSERT(!priv->buffer || data == getGstBufferDataPointer(priv->buffer.get()));
 
-#ifdef GST_API_VERSION_1
     if (priv->buffer)
         unmapGstBuffer(priv->buffer.get());
-#endif
 
-    if (priv->seekID || handle != priv->resourceHandle) {
-        GST_DEBUG_OBJECT(m_src, "Seek in progress, ignoring data");
+    if (priv->isSeeking) {
+        GST_DEBUG_OBJECT(src, "Seek in progress, ignoring data");
         priv->buffer.clear();
         return;
     }
 
+    if (priv->offset < priv->requestedOffset) {
+        // Range request failed; seeking manually.
+        if (priv->offset + length <= priv->requestedOffset) {
+            // Discard all the buffers coming before the requested seek position.
+            priv->offset += length;
+            priv->buffer.clear();
+            return;
+        }
+
+        if (priv->offset + length > priv->requestedOffset) {
+            guint64 offset = priv->requestedOffset - priv->offset;
+            data += offset;
+            length -= offset;
+            if (priv->buffer)
+                gst_buffer_resize(priv->buffer.get(), offset, -1);
+            priv->offset = priv->requestedOffset;
+        }
+
+        priv->requestedOffset = 0;
+    }
+
     // Ports using the GStreamer backend but not the soup implementation of ResourceHandle
     // won't be using buffers provided by this client, the buffer is created here in that case.
     if (!priv->buffer)
         priv->buffer = adoptGRef(createGstBufferForData(data, length));
     else
-        setGstBufferSize(priv->buffer.get(), length);
+        gst_buffer_set_size(priv->buffer.get(), static_cast<gssize>(length));
 
     GST_BUFFER_OFFSET(priv->buffer.get()) = priv->offset;
+    if (priv->requestedOffset == priv->offset)
+        priv->requestedOffset += length;
     priv->offset += length;
+    // priv->size == 0 if received length on didReceiveResponse < 0.
+    if (priv->size > 0 && priv->offset > priv->size) {
+        GST_DEBUG_OBJECT(src, "Updating internal size from %" G_GUINT64_FORMAT " to %" G_GUINT64_FORMAT, priv->size, priv->offset);
+        gst_app_src_set_size(priv->appsrc, priv->offset);
+        priv->size = priv->offset;
+    }
     GST_BUFFER_OFFSET_END(priv->buffer.get()) = priv->offset;
 
+    locker.unlock();
+
     GstFlowReturn ret = gst_app_src_push_buffer(priv->appsrc, priv->buffer.leakRef());
-#ifdef GST_API_VERSION_1
     if (ret != GST_FLOW_OK && ret != GST_FLOW_EOS)
-#else
-    if (ret != GST_FLOW_OK && ret != GST_FLOW_UNEXPECTED)
+        GST_ELEMENT_ERROR(src, CORE, FAILED, (0), (0));
+}
+
+void StreamingClient::handleNotifyFinished()
+{
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
+    WebKitWebSrcPrivate* priv = src->priv;
+
+    GST_DEBUG_OBJECT(src, "Have EOS");
+
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+    if (!priv->isSeeking) {
+        locker.unlock();
+        gst_app_src_end_of_stream(priv->appsrc);
+    }
+}
+
+CachedResourceStreamingClient::CachedResourceStreamingClient(WebKitWebSrc* src)
+    : StreamingClient(src)
+{
+}
+
+CachedResourceStreamingClient::~CachedResourceStreamingClient()
+{
+}
+
+#if USE(SOUP)
+char* CachedResourceStreamingClient::getOrCreateReadBuffer(PlatformMediaResource&, size_t requestedSize, size_t& actualSize)
+{
+    return createReadBuffer(requestedSize, actualSize);
+}
 #endif
-        GST_ELEMENT_ERROR(m_src, CORE, FAILED, (0), (0));
+
+void CachedResourceStreamingClient::responseReceived(PlatformMediaResource&, const ResourceResponse& response)
+{
+    WebKitWebSrcPrivate* priv = WEBKIT_WEB_SRC(m_src)->priv;
+    priv->didPassAccessControlCheck = priv->resource->didPassAccessControlCheck();
+    handleResponseReceived(response);
 }
 
-char* StreamingClient::getBuffer(int requestedSize, int* actualSize)
+void CachedResourceStreamingClient::dataReceived(PlatformMediaResource&, const char* data, int length)
 {
-    WebKitWebSrcPrivate* priv = m_src->priv;
+    handleDataReceived(data, length);
+}
 
-    ASSERT(!priv->buffer);
+void CachedResourceStreamingClient::accessControlCheckFailed(PlatformMediaResource&, const ResourceError& error)
+{
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
+    GST_ELEMENT_ERROR(src, RESOURCE, READ, ("%s", error.localizedDescription().utf8().data()), (nullptr));
+    gst_app_src_end_of_stream(src->priv->appsrc);
+    webKitWebSrcStop(src);
+}
 
-    GstBuffer* buffer = gst_buffer_new_and_alloc(requestedSize);
+void CachedResourceStreamingClient::loadFailed(PlatformMediaResource&, const ResourceError& error)
+{
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
 
-#ifdef GST_API_VERSION_1
-    mapGstBuffer(buffer);
+    if (!error.isCancellation()) {
+        GST_ERROR_OBJECT(src, "Have failure: %s", error.localizedDescription().utf8().data());
+        GST_ELEMENT_ERROR(src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (nullptr));
+    }
+
+    gst_app_src_end_of_stream(src->priv->appsrc);
+}
+
+void CachedResourceStreamingClient::loadFinished(PlatformMediaResource&)
+{
+    handleNotifyFinished();
+}
+
+ResourceHandleStreamingClient::ResourceHandleStreamingClient(WebKitWebSrc* src, ResourceRequest&& request)
+    : StreamingClient(src)
+{
+    LockHolder locker(m_initializeRunLoopConditionMutex);
+    m_thread = createThread("ResourceHandleStreamingClient", [this, request = WTFMove(request)] {
+        {
+            LockHolder locker(m_initializeRunLoopConditionMutex);
+            m_runLoop = &RunLoop::current();
+            m_resource = ResourceHandle::create(nullptr /*context*/, request, this, true, false);
+            m_initializeRunLoopCondition.notifyOne();
+        }
+        if (!m_resource)
+            return;
+
+        m_runLoop->dispatch([this] { m_resource->setDefersLoading(false); });
+        m_runLoop->run();
+        {
+            LockHolder locker(m_terminateRunLoopConditionMutex);
+            m_runLoop = nullptr;
+            m_resource->clearClient();
+            m_resource->cancel();
+            m_resource = nullptr;
+            m_terminateRunLoopCondition.notifyOne();
+        }
+    });
+    m_initializeRunLoopCondition.wait(m_initializeRunLoopConditionMutex);
+}
+
+ResourceHandleStreamingClient::~ResourceHandleStreamingClient()
+{
+    if (m_thread) {
+        detachThread(m_thread);
+        m_thread = 0;
+    }
+
+    if (m_runLoop == &RunLoop::current())
+        m_runLoop->stop();
+    else {
+        LockHolder locker(m_terminateRunLoopConditionMutex);
+        m_runLoop->stop();
+        m_terminateRunLoopCondition.wait(m_terminateRunLoopConditionMutex);
+    }
+}
+
+bool ResourceHandleStreamingClient::loadFailed() const
+{
+    return !m_resource;
+}
+
+void ResourceHandleStreamingClient::setDefersLoading(bool defers)
+{
+    m_runLoop->dispatch([this, defers] {
+        if (m_resource)
+            m_resource->setDefersLoading(defers);
+    });
+}
+
+#if USE(SOUP)
+char* ResourceHandleStreamingClient::getOrCreateReadBuffer(size_t requestedSize, size_t& actualSize)
+{
+    return createReadBuffer(requestedSize, actualSize);
+}
 #endif
 
-    priv->buffer = adoptGRef(buffer);
+ResourceRequest ResourceHandleStreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&& request, ResourceResponse&&)
+{
+    return WTFMove(request);
+}
 
-    *actualSize = getGstBufferSize(buffer);
-    return getGstBufferDataPointer(buffer);
+void ResourceHandleStreamingClient::didReceiveResponse(ResourceHandle*, ResourceResponse&& response)
+{
+    handleResponseReceived(response);
 }
 
-void StreamingClient::didFinishLoading(ResourceHandle*, double)
+void ResourceHandleStreamingClient::didReceiveData(ResourceHandle*, const char* /* data */, unsigned /* length */, int)
 {
-    WebKitWebSrcPrivate* priv = m_src->priv;
+    ASSERT_NOT_REACHED();
+}
 
-    GST_DEBUG_OBJECT(m_src, "Have EOS");
+void ResourceHandleStreamingClient::didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&& buffer, int /* encodedLength */)
+{
+    // This pattern is suggested by SharedBuffer.h.
+    const char* segment;
+    unsigned position = 0;
+    while (unsigned length = buffer->getSomeData(segment, position)) {
+        handleDataReceived(segment, length);
+        position += length;
+    }
+}
 
-    if (!priv->seekID)
-        gst_app_src_end_of_stream(m_src->priv->appsrc);
+void ResourceHandleStreamingClient::didFinishLoading(ResourceHandle*, double)
+{
+    handleNotifyFinished();
 }
 
-void StreamingClient::didFail(ResourceHandle*, const ResourceError& error)
+void ResourceHandleStreamingClient::didFail(ResourceHandle*, const ResourceError& error)
 {
-    GST_ERROR_OBJECT(m_src, "Have failure: %s", error.localizedDescription().utf8().data());
-    GST_ELEMENT_ERROR(m_src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
-    gst_app_src_end_of_stream(m_src->priv->appsrc);
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
+
+    GST_ERROR_OBJECT(src, "Have failure: %s", error.localizedDescription().utf8().data());
+    GST_ELEMENT_ERROR(src, RESOURCE, FAILED, ("%s", error.localizedDescription().utf8().data()), (0));
+    gst_app_src_end_of_stream(src->priv->appsrc);
 }
 
-void StreamingClient::wasBlocked(ResourceHandle*)
+void ResourceHandleStreamingClient::wasBlocked(ResourceHandle*)
 {
-    GST_ERROR_OBJECT(m_src, "Request was blocked");
-    GST_ELEMENT_ERROR(m_src, RESOURCE, OPEN_READ, ("Access to \"%s\" was blocked", m_src->priv->uri), (0));
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
+    GUniquePtr<gchar> uri;
+
+    GST_ERROR_OBJECT(src, "Request was blocked");
+
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+    uri.reset(g_strdup(src->priv->uri));
+    locker.unlock();
+
+    GST_ELEMENT_ERROR(src, RESOURCE, OPEN_READ, ("Access to \"%s\" was blocked", uri.get()), (0));
 }
 
-void StreamingClient::cannotShowURL(ResourceHandle*)
+void ResourceHandleStreamingClient::cannotShowURL(ResourceHandle*)
 {
-    GST_ERROR_OBJECT(m_src, "Cannot show URL");
-    GST_ELEMENT_ERROR(m_src, RESOURCE, OPEN_READ, ("Can't show \"%s\"", m_src->priv->uri), (0));
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
+    GUniquePtr<gchar> uri;
+
+    GST_ERROR_OBJECT(src, "Cannot show URL");
+
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+    uri.reset(g_strdup(src->priv->uri));
+    locker.unlock();
+
+    GST_ELEMENT_ERROR(src, RESOURCE, OPEN_READ, ("Can't show \"%s\"", uri.get()), (0));
 }
 
 #endif // USE(GSTREAMER)