[GStreamer] Use smart pointers and modernize code in WebKitWebAudioSourceGStreamer
[WebKit-https.git] / Source / WebCore / platform / graphics / gstreamer / WebKitWebSourceGStreamer.cpp
index 506e1d3..2a7f89e 100644 (file)
 
 #if ENABLE(VIDEO) && USE(GSTREAMER)
 
-#include "CachedRawResource.h"
-#include "CachedRawResourceClient.h"
-#include "CachedResourceHandle.h"
-#include "CachedResourceLoader.h"
-#include "CachedResourceRequest.h"
-#include "CrossOriginAccessControl.h"
 #include "GRefPtrGStreamer.h"
 #include "GStreamerUtilities.h"
+#include "GUniquePtrGStreamer.h"
 #include "HTTPHeaderNames.h"
+#include "MainThreadNotifier.h"
 #include "MediaPlayer.h"
 #include "NotImplemented.h"
+#include "PlatformMediaResourceLoader.h"
+#include "ResourceError.h"
 #include "ResourceHandle.h"
 #include "ResourceHandleClient.h"
 #include "ResourceRequest.h"
 #include "ResourceResponse.h"
-#include "SecurityOrigin.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/GMainLoopSource.h>
-#include <wtf/gobject/GMutexLocker.h>
-#include <wtf/gobject/GRefPtr.h>
-#include <wtf/gobject/GUniquePtr.h>
+#include <wtf/glib/GMutexLocker.h>
+#include <wtf/glib/GRefPtr.h>
+#include <wtf/glib/GUniquePtr.h>
 #include <wtf/text/CString.h>
 
 using namespace WebCore;
 
-enum CORSAccessCheckResult {
-    CORSNoCheck,
-    CORSSuccess,
-    CORSFailure
-};
-
 class StreamingClient {
     public:
         StreamingClient(WebKitWebSrc*);
         virtual ~StreamingClient();
 
-        virtual bool loadFailed() const = 0;
-        virtual void setDefersLoading(bool) = 0;
-
     protected:
         char* createReadBuffer(size_t requestedSize, size_t& actualSize);
-        void handleResponseReceived(const ResourceResponse&, CORSAccessCheckResult);
+        void handleResponseReceived(const ResourceResponse&);
         void handleDataReceived(const char*, int);
         void handleNotifyFinished();
 
-        GRefPtr<GstElement> m_src;
+        GstElement* m_src;
 };
 
-class CachedResourceStreamingClient : public CachedRawResourceClient, public StreamingClient {
-    WTF_MAKE_NONCOPYABLE(CachedResourceStreamingClient); WTF_MAKE_FAST_ALLOCATED;
+class CachedResourceStreamingClient final : public PlatformMediaResourceClient, public StreamingClient {
+    WTF_MAKE_NONCOPYABLE(CachedResourceStreamingClient);
     public:
-        CachedResourceStreamingClient(WebKitWebSrc*, CachedResourceLoader*, const ResourceRequest&, MediaPlayerClient::CORSMode);
+        CachedResourceStreamingClient(WebKitWebSrc*);
         virtual ~CachedResourceStreamingClient();
 
-        // StreamingClient virtual methods.
-        virtual bool loadFailed() const;
-        virtual void setDefersLoading(bool);
-
     private:
-        // CachedResourceClient virtual methods.
-        virtual char* getOrCreateReadBuffer(CachedResource*, size_t requestedSize, size_t& actualSize);
-        virtual void responseReceived(CachedResource*, const ResourceResponse&);
-        virtual void dataReceived(CachedResource*, const char*, int);
-        virtual void notifyFinished(CachedResource*);
-
-        CachedResourceHandle<CachedRawResource> m_resource;
-        RefPtr<SecurityOrigin> m_origin;
+        // 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;
 };
 
 class ResourceHandleStreamingClient : public ResourceHandleClient, public StreamingClient {
     WTF_MAKE_NONCOPYABLE(ResourceHandleStreamingClient); WTF_MAKE_FAST_ALLOCATED;
     public:
-        ResourceHandleStreamingClient(WebKitWebSrc*, const ResourceRequest&);
+        ResourceHandleStreamingClient(WebKitWebSrc*, ResourceRequest&&);
         virtual ~ResourceHandleStreamingClient();
 
         // StreamingClient virtual methods.
-        virtual bool loadFailed() const;
-        virtual void setDefersLoading(bool);
+        bool loadFailed() const;
+        void setDefersLoading(bool);
 
     private:
         // ResourceHandleClient virtual methods.
-        virtual char* getOrCreateReadBuffer(size_t requestedSize, size_t& actualSize);
-        virtual void willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&);
-        virtual void didReceiveResponse(ResourceHandle*, const ResourceResponse&);
-        virtual void didReceiveData(ResourceHandle*, const char*, unsigned, int);
-        virtual void didReceiveBuffer(ResourceHandle*, PassRefPtr<SharedBuffer>, int encodedLength);
-        virtual void didFinishLoading(ResourceHandle*, double /*finishTime*/);
-        virtual void didFail(ResourceHandle*, const ResourceError&);
-        virtual void wasBlocked(ResourceHandle*);
-        virtual void cannotShowURL(ResourceHandle*);
-
+#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))
 struct _WebKitWebSrcPrivate {
     GstAppSrc* appsrc;
     GstPad* srcpad;
     gchar* uri;
+    bool keepAlive;
+    GUniquePtr<GstStructure> extraHeaders;
+    bool compress;
+    GUniquePtr<gchar> httpMethod;
 
     WebCore::MediaPlayer* player;
 
-    StreamingClient* client;
+    RefPtr<PlatformMediaResourceLoader> loader;
+    RefPtr<PlatformMediaResource> resource;
+    std::unique_ptr<ResourceHandleStreamingClient> client;
 
-    CORSAccessCheckResult corsAccessCheck;
+    bool didPassAccessControlCheck;
 
     guint64 offset;
     guint64 size;
     gboolean seekable;
-    gboolean paused;
+    bool paused;
+    bool isSeeking;
 
     guint64 requestedOffset;
 
-    GMainLoopSource startSource;
-    GMainLoopSource stopSource;
-    GMainLoopSource needDataSource;
-    GMainLoopSource enoughDataSource;
-    GMainLoopSource seekSource;
-
+    bool createdInMainThread;
+    MainThreadNotifier<MainThreadSourceNotification> notifier;
     GRefPtr<GstBuffer> buffer;
-
-    // icecast stuff
-    gchar* iradioName;
-    gchar* iradioGenre;
-    gchar* iradioUrl;
-    gchar* iradioTitle;
 };
 
 enum {
-    PROP_IRADIO_NAME = 1,
-    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",
@@ -180,15 +179,24 @@ static GstStateChangeReturn webKitWebSrcChangeState(GstElement*, GstStateChange)
 
 static gboolean webKitWebSrcQueryWithParent(GstPad*, GstObject*, GstQuery*);
 
-static void webKitWebSrcNeedDataCb(GstAppSrc*, guint length, gpointer userData);
-static void webKitWebSrcEnoughDataCb(GstAppSrc*, gpointer userData);
-static gboolean webKitWebSrcSeekDataCb(GstAppSrc*, guint64 offset, gpointer userData);
+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
@@ -213,40 +221,6 @@ static void webkit_web_src_class_init(WebKitWebSrcClass* klass)
     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_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,
@@ -256,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));
@@ -268,6 +259,8 @@ static void webkit_web_src_init(WebKitWebSrc* src)
     src->priv = priv;
     new (priv) WebKitWebSrcPrivate();
 
+    priv->createdInMainThread = isMainThread();
+
     priv->appsrc = GST_APP_SRC(gst_element_factory_make("appsrc", 0));
     if (!priv->appsrc) {
         GST_ERROR_OBJECT(src, "Failed to create appsrc");
@@ -341,6 +334,20 @@ static void webKitWebSrcSetProperty(GObject* object, guint propID, const GValue*
     case PROP_LOCATION:
         gst_uri_handler_set_uri(reinterpret_cast<GstURIHandler*>(src), g_value_get_string(value), 0);
         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);
         break;
@@ -352,22 +359,22 @@ static void webKitWebSrcGetProperty(GObject* object, guint propID, GValue* value
     WebKitWebSrc* src = WEBKIT_WEB_SRC(object);
     WebKitWebSrcPrivate* priv = src->priv;
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
     switch (propID) {
-    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);
@@ -375,56 +382,45 @@ static void webKitWebSrcGetProperty(GObject* object, guint propID, GValue* value
     }
 }
 
-static void removeTimeoutSources(WebKitWebSrc* src)
-{
-    WebKitWebSrcPrivate* priv = src->priv;
-
-    priv->startSource.cancel();
-    priv->needDataSource.cancel();
-    priv->enoughDataSource.cancel();
-    priv->seekSource.cancel();
-}
-
 static void webKitWebSrcStop(WebKitWebSrc* src)
 {
     WebKitWebSrcPrivate* priv = src->priv;
 
-    ASSERT(isMainThread());
-
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+    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;
+        });
+    }
 
-    bool seeking = priv->seekSource.isActive();
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
 
-    removeTimeoutSources(src);
+    bool wasSeeking = std::exchange(priv->isSeeking, false);
 
-    if (priv->client) {
-        delete priv->client;
-        priv->client = 0;
-    }
+    priv->client = nullptr;
 
     if (priv->buffer) {
         unmapGstBuffer(priv->buffer.get());
         priv->buffer.clear();
     }
 
-    priv->paused = FALSE;
-
-    g_free(priv->iradioName);
-    priv->iradioName = 0;
-
-    g_free(priv->iradioGenre);
-    priv->iradioGenre = 0;
-
-    g_free(priv->iradioUrl);
-    priv->iradioUrl = 0;
-
-    g_free(priv->iradioTitle);
-    priv->iradioTitle = 0;
+    priv->paused = false;
 
     priv->offset = 0;
     priv->seekable = FALSE;
 
-    if (!seeking) {
+    if (!wasSeeking) {
         priv->size = 0;
         priv->requestedOffset = 0;
         priv->player = 0;
@@ -434,22 +430,71 @@ static void webKitWebSrcStop(WebKitWebSrc* src)
 
     if (priv->appsrc) {
         gst_app_src_set_caps(priv->appsrc, 0);
-        if (!seeking)
+        if (!wasSeeking)
             gst_app_src_set_size(priv->appsrc, -1);
     }
 
     GST_DEBUG_OBJECT(src, "Stopped request");
 }
 
+static bool webKitWebSrcSetExtraHeader(GQuark fieldId, const GValue* value, gpointer userData)
+{
+    GUniquePtr<gchar> fieldContent;
+
+    if (G_VALUE_HOLDS_STRING(value))
+        fieldContent.reset(g_value_dup_string(value));
+    else {
+        GValue dest = G_VALUE_INIT;
+
+        g_value_init(&dest, G_TYPE_STRING);
+        if (g_value_transform(value, &dest))
+            fieldContent.reset(g_value_dup_string(&dest));
+    }
+
+    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;
+    }
+
+    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;
+    }
+
+    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 void webKitWebSrcStart(WebKitWebSrc* src)
 {
     WebKitWebSrcPrivate* priv = src->priv;
 
-    ASSERT(isMainThread());
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
-
-    priv->corsAccessCheck = CORSNoCheck;
+    priv->didPassAccessControlCheck = false;
 
     if (!priv->uri) {
         GST_ERROR_OBJECT(src, "No URI provided");
@@ -460,22 +505,33 @@ static void webKitWebSrcStart(WebKitWebSrc* src)
 
     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);
+
+    priv->size = 0;
 
     if (priv->player)
         request.setHTTPReferrer(priv->player->referrer());
 
+    if (priv->httpMethod.get())
+        request.setHTTPMethod(priv->httpMethod.get());
+
 #if USE(SOUP)
-    // Let's disable HTTP Accept-Encoding 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
+    // 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.
-    request.setAcceptEncoding(false);
+    // 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.
@@ -489,31 +545,53 @@ static void webKitWebSrcStart(WebKitWebSrc* src)
     }
     priv->offset = priv->requestedOffset;
 
+    if (!priv->keepAlive) {
+        GST_DEBUG_OBJECT(src, "Persistent connection support disabled");
+        request.setHTTPHeaderField(HTTPHeaderName::Connection, "close");
+    }
+
+    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");
 
-    // Needed to use DLNA streaming servers
-    request.setHTTPHeaderField(HTTPHeaderName::TransferModeDLNA, "Streaming");
-
-    if (priv->player) {
-        if (CachedResourceLoader* loader = priv->player->cachedResourceLoader())
-            priv->client = new CachedResourceStreamingClient(src, loader, request, priv->player->mediaPlayerClient()->mediaPlayerCORSMode());
+    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;
     }
 
-    if (!priv->client)
-        priv->client = new ResourceHandleStreamingClient(src, request);
-
-    if (!priv->client || priv->client->loadFailed()) {
-        GST_ERROR_OBJECT(src, "Failed to setup streaming client");
-        if (priv->client) {
-            delete priv->client;
-            priv->client = 0;
+    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());
         }
-        locker.unlock();
-        webKitWebSrcStop(src);
-        return;
-    }
-    GST_DEBUG_OBJECT(src, "Started request");
+    });
 }
 
 static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStateChange transition)
@@ -541,22 +619,19 @@ static GstStateChangeReturn webKitWebSrcChangeState(GstElement* element, GstStat
         return ret;
     }
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
     switch (transition) {
     case GST_STATE_CHANGE_READY_TO_PAUSED:
+    {
         GST_DEBUG_OBJECT(src, "READY->PAUSED");
-        gst_object_ref(src);
-        priv->startSource.schedule("[WebKit] webKitWebSrcStart", std::function<void()>(std::bind(webKitWebSrcStart, src)), G_PRIORITY_DEFAULT,
-            [src] { gst_object_unref(src); });
+        webKitWebSrcStart(src);
         break;
+    }
     case GST_STATE_CHANGE_PAUSED_TO_READY:
+    {
         GST_DEBUG_OBJECT(src, "PAUSED->READY");
-        // cancel pending sources
-        removeTimeoutSources(src);
-        gst_object_ref(src);
-        priv->stopSource.schedule("[WebKit] webKitWebSrcStop", std::function<void()>(std::bind(webKitWebSrcStop, src)), G_PRIORITY_DEFAULT,
-            [src] { gst_object_unref(src); });
+        webKitWebSrcStop(src);
         break;
+    }
     default:
         break;
     }
@@ -576,7 +651,7 @@ static gboolean webKitWebSrcQueryWithParent(GstPad* pad, GstObject* parent, GstQ
         gst_query_parse_duration(query, &format, NULL);
 
         GST_DEBUG_OBJECT(src, "duration query in format %s", gst_format_get_name(format));
-        GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+        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;
@@ -584,11 +659,20 @@ static gboolean webKitWebSrcQueryWithParent(GstPad* pad, GstObject* parent, GstQ
         break;
     }
     case GST_QUERY_URI: {
-        GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+        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;
+    }
     default: {
         GRefPtr<GstPad> target = adoptGRef(gst_ghost_pad_get_target(GST_GHOST_PAD_CAST(pad)));
 
@@ -604,7 +688,7 @@ static gboolean webKitWebSrcQueryWithParent(GstPad* pad, GstObject* parent, GstQ
 
 static bool urlHasSupportedProtocol(const URL& url)
 {
-    return url.isValid() && (url.protocolIsInHTTPFamily() || url.protocolIs("blob"));
+    return url.isValid() && (url.protocolIsInHTTPFamily() || url.protocolIsBlob());
 }
 
 // uri handler interface
@@ -625,7 +709,7 @@ static gchar* webKitWebSrcGetUri(GstURIHandler* handler)
     WebKitWebSrc* src = WEBKIT_WEB_SRC(handler);
     gchar* ret;
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
     ret = g_strdup(src->priv->uri);
     return ret;
 }
@@ -640,7 +724,7 @@ static gboolean webKitWebSrcSetUri(GstURIHandler* handler, const gchar* uri, GEr
         return FALSE;
     }
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
 
     g_free(priv->uri);
     priv->uri = 0;
@@ -668,131 +752,122 @@ static void webKitWebSrcUriHandlerInit(gpointer gIface, gpointer)
     iface->set_uri = webKitWebSrcSetUri;
 }
 
-// appsrc callbacks
-
-static void webKitWebSrcNeedDataMainCb(WebKitWebSrc* src)
-{
-    WebKitWebSrcPrivate* priv = src->priv;
-
-    ASSERT(isMainThread());
-
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
-    priv->paused = FALSE;
-    locker.unlock();
-
-    if (priv->client)
-        priv->client->setDefersLoading(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");
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
-    if (priv->needDataSource.isScheduled() || !priv->paused)
-        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;
+        }
+    }
 
-    gst_object_ref(src);
-    priv->needDataSource.schedule("[WebKit] webKitWebSrcNeedDataMainCb", std::function<void()>(std::bind(webKitWebSrcNeedDataMainCb, src)), G_PRIORITY_DEFAULT,
-        [src] { gst_object_unref(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 void webKitWebSrcEnoughDataMainCb(WebKitWebSrc* src)
+static void webKitWebSrcEnoughData(WebKitWebSrc* src)
 {
     WebKitWebSrcPrivate* priv = src->priv;
 
-    ASSERT(isMainThread());
+    GST_DEBUG_OBJECT(src, "Have enough data");
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
-    priv->paused = TRUE;
-    locker.unlock();
+    {
+        WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+        if (priv->paused)
+            return;
+        priv->paused = true;
+        if (priv->client) {
+            priv->client->setDefersLoading(true);
+            return;
+        }
+    }
 
-    if (priv->client)
-        priv->client->setDefersLoading(true);
+    GRefPtr<WebKitWebSrc> protector = WTF::ensureGRef(src);
+    priv->notifier.notify(MainThreadSourceNotification::EnoughData, [protector] {
+        WebKitWebSrcPrivate* priv = protector->priv;
+        if (priv->resource)
+            priv->resource->setDefersLoading(true);
+    });
 }
 
-static void webKitWebSrcEnoughDataCb(GstAppSrc*, gpointer userData)
+static gboolean webKitWebSrcSeek(WebKitWebSrc* src, guint64 offset)
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
     WebKitWebSrcPrivate* priv = src->priv;
 
-    GST_DEBUG_OBJECT(src, "Have enough data");
-
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
-    if (priv->enoughDataSource.isScheduled() || priv->paused)
-        return;
+    {
+        WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
+        if (offset == priv->offset && priv->requestedOffset == priv->offset)
+            return TRUE;
 
-    gst_object_ref(src);
-    priv->enoughDataSource.schedule("[WebKit] webKitWebSrcEnoughDataMainCb", std::function<void()>(std::bind(webKitWebSrcEnoughDataMainCb, src)), G_PRIORITY_DEFAULT,
-        [src] { gst_object_unref(src); });
-}
-
-static void webKitWebSrcSeekMainCb(WebKitWebSrc* src)
-{
-    ASSERT(isMainThread());
+        if (!priv->seekable)
+            return FALSE;
 
-    webKitWebSrcStop(src);
-    webKitWebSrcStart(src);
-}
-
-static gboolean webKitWebSrcSeekDataCb(GstAppSrc*, guint64 offset, gpointer userData)
-{
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(userData);
-    WebKitWebSrcPrivate* priv = src->priv;
+        priv->isSeeking = true;
+        priv->requestedOffset = offset;
+    }
 
-    GST_DEBUG_OBJECT(src, "Seeking to offset: %" G_GUINT64_FORMAT, offset);
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
-    if (offset == priv->offset && priv->requestedOffset == priv->offset)
+    GST_DEBUG_OBJECT(src, "Seeking to offset: %" G_GUINT64_FORMAT, src->priv->requestedOffset);
+    if (priv->client) {
+        webKitWebSrcStop(src);
+        webKitWebSrcStart(src);
         return TRUE;
+    }
 
-    if (!priv->seekable)
-        return FALSE;
-
-    GST_DEBUG_OBJECT(src, "Doing range-request seek");
-    priv->requestedOffset = offset;
-
-    gst_object_ref(src);
-    priv->seekSource.schedule("[WebKit] webKitWebSrcSeekMainCb", std::function<void()>(std::bind(webKitWebSrcSeekMainCb, src)), G_PRIORITY_DEFAULT,
-        [src] { gst_object_unref(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)
 {
     ASSERT(player);
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+    ASSERT(src->priv->createdInMainThread);
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
     src->priv->player = player;
 }
 
 bool webKitSrcPassedCORSAccessCheck(WebKitWebSrc* src)
 {
-    return src->priv->corsAccessCheck == CORSSuccess;
+    return src->priv->didPassAccessControlCheck;
 }
 
 StreamingClient::StreamingClient(WebKitWebSrc* src)
-    : m_src(adoptGRef(static_cast<GstElement*>(gst_object_ref(src))))
+    : m_src(static_cast<GstElement*>(gst_object_ref(src)))
 {
 }
 
 StreamingClient::~StreamingClient()
 {
+    gst_object_unref(m_src);
 }
 
 char* StreamingClient::createReadBuffer(size_t requestedSize, size_t& actualSize)
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
     WebKitWebSrcPrivate* priv = src->priv;
 
     ASSERT(!priv->buffer);
 
     GstBuffer* buffer = gst_buffer_new_and_alloc(requestedSize);
 
-    mapGstBuffer(buffer);
+    mapGstBuffer(buffer, GST_MAP_WRITE);
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
     priv->buffer = adoptGRef(buffer);
     locker.unlock();
 
@@ -800,29 +875,23 @@ char* StreamingClient::createReadBuffer(size_t requestedSize, size_t& actualSize
     return getGstBufferDataPointer(buffer);
 }
 
-void StreamingClient::handleResponseReceived(const ResourceResponse& response, CORSAccessCheckResult corsAccessCheck)
+void StreamingClient::handleResponseReceived(const ResourceResponse& response)
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
     WebKitWebSrcPrivate* priv = src->priv;
 
     GST_DEBUG_OBJECT(src, "Received response: %d", response.httpStatusCode());
 
-    if (response.httpStatusCode() >= 400 || corsAccessCheck == CORSFailure) {
-        // Received error code or CORS check failed
-        if (corsAccessCheck == CORSFailure)
-            GST_ELEMENT_ERROR(src, RESOURCE, READ, ("Cross-origin stream load denied by Cross-Origin Resource Sharing policy."), (nullptr));
-        else
-            GST_ELEMENT_ERROR(src, RESOURCE, READ, ("Received %d HTTP error code", response.httpStatusCode()), (nullptr));
+    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(src);
         return;
     }
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
-
-    priv->corsAccessCheck = corsAccessCheck;
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
 
-    if (priv->seekSource.isActive()) {
+    if (priv->isSeeking) {
         GST_DEBUG_OBJECT(src, "Seek in progress, ignoring response");
         return;
     }
@@ -849,41 +918,7 @@ void StreamingClient::handleResponseReceived(const ResourceResponse& response, C
     priv->size = length >= 0 ? length : 0;
     priv->seekable = length > 0 && g_ascii_strcasecmp("none", response.httpHeaderField(HTTPHeaderName::AcceptRanges).utf8().data());
 
-    // Wait until we unlock to send notifications
-    g_object_freeze_notify(G_OBJECT(src));
-
-    GstTagList* tags = gst_tag_list_new_empty();
-    String value = response.httpHeaderField(HTTPHeaderName::IcyName);
-    if (!value.isEmpty()) {
-        g_free(priv->iradioName);
-        priv->iradioName = g_strdup(value.utf8().data());
-        g_object_notify(G_OBJECT(src), "iradio-name");
-        gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_ORGANIZATION, priv->iradioName, NULL);
-    }
-    value = response.httpHeaderField(HTTPHeaderName::IcyGenre);
-    if (!value.isEmpty()) {
-        g_free(priv->iradioGenre);
-        priv->iradioGenre = g_strdup(value.utf8().data());
-        g_object_notify(G_OBJECT(src), "iradio-genre");
-        gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_GENRE, priv->iradioGenre, NULL);
-    }
-    value = response.httpHeaderField(HTTPHeaderName::IcyURL);
-    if (!value.isEmpty()) {
-        g_free(priv->iradioUrl);
-        priv->iradioUrl = g_strdup(value.utf8().data());
-        g_object_notify(G_OBJECT(src), "iradio-url");
-        gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_LOCATION, priv->iradioUrl, NULL);
-    }
-    value = response.httpHeaderField(HTTPHeaderName::IcyTitle);
-    if (!value.isEmpty()) {
-        g_free(priv->iradioTitle);
-        priv->iradioTitle = g_strdup(value.utf8().data());
-        g_object_notify(G_OBJECT(src), "iradio-title");
-        gst_tag_list_add(tags, GST_TAG_MERGE_REPLACE, GST_TAG_TITLE, priv->iradioTitle, NULL);
-    }
-
     locker.unlock();
-    g_object_thaw_notify(G_OBJECT(src));
 
     // notify size/duration
     if (length > 0) {
@@ -891,33 +926,15 @@ void StreamingClient::handleResponseReceived(const ResourceResponse& response, C
     } else
         gst_app_src_set_size(priv->appsrc, -1);
 
-    // icecast stuff
-    value = response.httpHeaderField(HTTPHeaderName::IcyMetaInt);
-    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());
-        }
-    } else
-        gst_app_src_set_caps(priv->appsrc, 0);
-
-    // notify tags
-    if (gst_tag_list_is_empty(tags))
-        gst_tag_list_unref(tags);
-    else
-        gst_pad_push_event(priv->srcpad, gst_event_new_tag(tags));
+    gst_app_src_set_caps(priv->appsrc, 0);
 }
 
 void StreamingClient::handleDataReceived(const char* data, int length)
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
     WebKitWebSrcPrivate* priv = src->priv;
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
 
     GST_LOG_OBJECT(src, "Have %lld bytes of data", priv->buffer ? static_cast<long long>(gst_buffer_get_size(priv->buffer.get())) : length);
 
@@ -926,7 +943,7 @@ void StreamingClient::handleDataReceived(const char* data, int length)
     if (priv->buffer)
         unmapGstBuffer(priv->buffer.get());
 
-    if (priv->seekSource.isActive()) {
+    if (priv->isSeeking) {
         GST_DEBUG_OBJECT(src, "Seek in progress, ignoring data");
         priv->buffer.clear();
         return;
@@ -981,105 +998,112 @@ void StreamingClient::handleDataReceived(const char* data, int length)
 
 void StreamingClient::handleNotifyFinished()
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
     WebKitWebSrcPrivate* priv = src->priv;
 
     GST_DEBUG_OBJECT(src, "Have EOS");
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
-    if (!priv->seekSource.isActive()) {
+    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, CachedResourceLoader* resourceLoader, const ResourceRequest& request, MediaPlayerClient::CORSMode corsMode)
+CachedResourceStreamingClient::CachedResourceStreamingClient(WebKitWebSrc* src)
     : StreamingClient(src)
 {
-    DataBufferingPolicy bufferingPolicy = request.url().protocolIs("blob") ? BufferData : DoNotBufferData;
-    RequestOriginPolicy corsPolicy = corsMode != MediaPlayerClient::Unspecified ? PotentiallyCrossOriginEnabled : UseDefaultOriginRestrictionsForType;
-    StoredCredentials allowCredentials = corsMode == MediaPlayerClient::UseCredentials ? AllowStoredCredentials : DoNotAllowStoredCredentials;
-    ResourceLoaderOptions options(SendCallbacks, DoNotSniffContent, bufferingPolicy, allowCredentials, DoNotAskClientForCrossOriginCredentials, DoSecurityCheck, corsPolicy);
-
-    CachedResourceRequest cacheRequest(request, options);
-
-    if (corsMode != MediaPlayerClient::Unspecified) {
-        m_origin = resourceLoader->document() ? resourceLoader->document()->securityOrigin() : nullptr;
-        updateRequestForAccessControl(cacheRequest.mutableResourceRequest(), m_origin.get(), allowCredentials);
-    }
-
-    // TODO: Decide whether to use preflight mode for cross-origin requests (see http://wkbug.com/131484).
-    m_resource = resourceLoader->requestRawResource(cacheRequest);
-    if (m_resource)
-        m_resource->addClient(this);
 }
 
 CachedResourceStreamingClient::~CachedResourceStreamingClient()
 {
-    if (m_resource) {
-        m_resource->removeClient(this);
-        m_resource = 0;
-    }
 }
 
-bool CachedResourceStreamingClient::loadFailed() const
-{
-    return !m_resource;
-}
-
-void CachedResourceStreamingClient::setDefersLoading(bool defers)
+#if USE(SOUP)
+char* CachedResourceStreamingClient::getOrCreateReadBuffer(PlatformMediaResource&, size_t requestedSize, size_t& actualSize)
 {
-    if (m_resource)
-        m_resource->setDefersLoading(defers);
+    return createReadBuffer(requestedSize, actualSize);
 }
+#endif
 
-char* CachedResourceStreamingClient::getOrCreateReadBuffer(CachedResource*, size_t requestedSize, size_t& actualSize)
+void CachedResourceStreamingClient::responseReceived(PlatformMediaResource&, const ResourceResponse& response)
 {
-    return createReadBuffer(requestedSize, actualSize);
+    WebKitWebSrcPrivate* priv = WEBKIT_WEB_SRC(m_src)->priv;
+    priv->didPassAccessControlCheck = priv->resource->didPassAccessControlCheck();
+    handleResponseReceived(response);
 }
 
-void CachedResourceStreamingClient::responseReceived(CachedResource* resource, const ResourceResponse& response)
+void CachedResourceStreamingClient::dataReceived(PlatformMediaResource&, const char* data, int length)
 {
-    CORSAccessCheckResult corsAccessCheck = CORSNoCheck;
-    if (m_origin)
-        corsAccessCheck = (m_origin->canRequest(response.url()) || resource->passesAccessControlCheck(m_origin.get())) ? CORSSuccess : CORSFailure;
-    handleResponseReceived(response, corsAccessCheck);
+    handleDataReceived(data, length);
 }
 
-void CachedResourceStreamingClient::dataReceived(CachedResource*, const char* data, int length)
+void CachedResourceStreamingClient::accessControlCheckFailed(PlatformMediaResource&, const ResourceError& error)
 {
-    handleDataReceived(data, length);
+    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);
 }
 
-void CachedResourceStreamingClient::notifyFinished(CachedResource* resource)
+void CachedResourceStreamingClient::loadFailed(PlatformMediaResource&, const ResourceError& error)
 {
-    if (resource->loadFailedOrCanceled()) {
-        WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
 
-        if (!resource->wasCanceled()) {
-            const ResourceError& error = resource->resourceError();
-            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);
-        return;
+    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, const ResourceRequest& request)
+ResourceHandleStreamingClient::ResourceHandleStreamingClient(WebKitWebSrc* src, ResourceRequest&& request)
     : StreamingClient(src)
 {
-    m_resource = ResourceHandle::create(0 /*context*/, request, this, false, false);
+    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_resource) {
-        m_resource->cancel();
-        m_resource.release();
-        m_resource = 0;
+    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);
     }
 }
 
@@ -1090,22 +1114,27 @@ bool ResourceHandleStreamingClient::loadFailed() const
 
 void ResourceHandleStreamingClient::setDefersLoading(bool defers)
 {
-    if (m_resource)
-        m_resource->setDefersLoading(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
 
-void ResourceHandleStreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&, const ResourceResponse&)
+ResourceRequest ResourceHandleStreamingClient::willSendRequest(ResourceHandle*, ResourceRequest&& request, ResourceResponse&&)
 {
+    return WTFMove(request);
 }
 
-void ResourceHandleStreamingClient::didReceiveResponse(ResourceHandle*, const ResourceResponse& response)
+void ResourceHandleStreamingClient::didReceiveResponse(ResourceHandle*, ResourceResponse&& response)
 {
-    handleResponseReceived(response, CORSNoCheck);
+    handleResponseReceived(response);
 }
 
 void ResourceHandleStreamingClient::didReceiveData(ResourceHandle*, const char* /* data */, unsigned /* length */, int)
@@ -1113,7 +1142,7 @@ void ResourceHandleStreamingClient::didReceiveData(ResourceHandle*, const char*
     ASSERT_NOT_REACHED();
 }
 
-void ResourceHandleStreamingClient::didReceiveBuffer(ResourceHandle*, PassRefPtr<SharedBuffer> buffer, int /* encodedLength */)
+void ResourceHandleStreamingClient::didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&& buffer, int /* encodedLength */)
 {
     // This pattern is suggested by SharedBuffer.h.
     const char* segment;
@@ -1131,7 +1160,7 @@ void ResourceHandleStreamingClient::didFinishLoading(ResourceHandle*, double)
 
 void ResourceHandleStreamingClient::didFail(ResourceHandle*, const ResourceError& error)
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
+    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));
@@ -1140,12 +1169,12 @@ void ResourceHandleStreamingClient::didFail(ResourceHandle*, const ResourceError
 
 void ResourceHandleStreamingClient::wasBlocked(ResourceHandle*)
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
     GUniquePtr<gchar> uri;
 
     GST_ERROR_OBJECT(src, "Request was blocked");
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
     uri.reset(g_strdup(src->priv->uri));
     locker.unlock();
 
@@ -1154,12 +1183,12 @@ void ResourceHandleStreamingClient::wasBlocked(ResourceHandle*)
 
 void ResourceHandleStreamingClient::cannotShowURL(ResourceHandle*)
 {
-    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
+    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src);
     GUniquePtr<gchar> uri;
 
     GST_ERROR_OBJECT(src, "Cannot show URL");
 
-    GMutexLocker locker(GST_OBJECT_GET_LOCK(src));
+    WTF::GMutexLocker<GMutex> locker(*GST_OBJECT_GET_LOCK(src));
     uri.reset(g_strdup(src->priv->uri));
     locker.unlock();