Title: [285295] branches/safari-612-branch/Source/WebCore
Revision
285295
Author
[email protected]
Date
2021-11-04 12:40:01 -0700 (Thu, 04 Nov 2021)

Log Message

Cherry-pick r285069. rdar://problem/84558835

    Have PlatformMediaResourceClient use SharedBuffer
    https://bugs.webkit.org/show_bug.cgi?id=232422
    rdar://84558835

    Reviewed by Alex Christensen.

    When playing a non-mse media element, the download gets controlled by a
    MediaResource into a WebCoreNSURLSession to be used by the media framework.
    The data got copied at least three times along the way due to the
    multi-threaded nature of the framework and the need for thread
    safety.
    The situation was made worse when the content server didn't support
    range-request: as a RangeResponseGenerator is then used by the
    WebCoreNSURLSession which downloads the entire media to be played and
    keep it in memory.

    By modifying the various actors between a MediaResource and WebCoreNSURLSession
    to use SharedBuffers ; we can remove most copies and allocation.
    This also completely eliminates the need for new memory buffer allocations and
    copies by the RangeResponseGenerator object.

    With WK2 and the GPU process, it allows for the memory to be allocated once
    and only be assigned to the content process by using SharedMemory wrapped
    in a SharedBuffer.

    In the future, by refactoring CachedRawResourceClient to use SharedBuffers,
    we could remove further allocation/copies. We could likely get the data from the
    network process all the way to the final client in the GPU process without
    a single copy. This is tracked in bug 232424.

    No change in observable behaviour. Covered by all the existing media tests.

    * platform/SharedBuffer.cpp:
    (WebCore::SharedBufferDataView::size const):
    (WebCore::SharedBufferDataView::trim): Add ability to trim a SharedBufferDataView.
    This allows to avoid having to copy into a new buffer.
    (WebCore::SharedBufferDataView::createSharedBuffer const): Cross declarations
    makes it difficult to add a new SharedBuffer constructor that would take a
    SharedBufferDataView.
    * platform/SharedBuffer.h: Add new methods.
    * platform/cocoa/SharedBufferCocoa.mm: Update to allow for end trimming
    information.
    (-[WebCoreSharedBufferData initWithDataSegment:position:endTrim:]):
    (-[WebCoreSharedBufferData length]):
    (WebCore::SharedBuffer::DataSegment::createNSData const):
    (WebCore::SharedBufferDataView::createNSData const):
    (-[WebCoreSharedBufferData initWithDataSegment:position:]): Deleted.
    * platform/graphics/PlatformMediaResourceLoader.h:
    (WebCore::PlatformMediaResourceClient::dataReceived): Add a new API using
    a SharedBuffer. We keep the old one taking a pointer/size due to a WebKit
    implementation details which allows us to save an intermediary allocation/copy
    when used with SharedMemory.
    * platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm:
    (WebCore::PlatformResourceMediaLoader::dataReceived):
    * platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp:
    (CachedResourceStreamingClient::dataReceived): Update to use SharedBuffer.
    * platform/network/cocoa/RangeResponseGenerator.mm:
    (WebCore::RangeResponseGenerator::giveResponseToTaskIfBytesInRangeReceived):
    * platform/network/cocoa/WebCoreNSURLSession.h: Change prototypes.
    Fly-by fix, property countOfBytesReceived needed to be atomic.
    * platform/network/cocoa/WebCoreNSURLSession.mm:
    (WebCore::WebCoreNSURLSessionDataTaskClient::dataReceived):
    (-[WebCoreNSURLSessionDataTask resource:receivedData:]):
    (-[WebCoreNSURLSessionDataTask resource:receivedRedirect:request:completionHandler:]):

    git-svn-id: https://svn.webkit.org/repository/webkit/trunk@285069 268f45cc-cd09-0410-ab3c-d52691b4dbfc

Modified Paths

Diff

Modified: branches/safari-612-branch/Source/WebCore/ChangeLog (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/ChangeLog	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/ChangeLog	2021-11-04 19:40:01 UTC (rev 285295)
@@ -1,5 +1,144 @@
 2021-11-04  Russell Epstein  <[email protected]>
 
+        Cherry-pick r285069. rdar://problem/84558835
+
+    Have PlatformMediaResourceClient use SharedBuffer
+    https://bugs.webkit.org/show_bug.cgi?id=232422
+    rdar://84558835
+    
+    Reviewed by Alex Christensen.
+    
+    When playing a non-mse media element, the download gets controlled by a
+    MediaResource into a WebCoreNSURLSession to be used by the media framework.
+    The data got copied at least three times along the way due to the
+    multi-threaded nature of the framework and the need for thread
+    safety.
+    The situation was made worse when the content server didn't support
+    range-request: as a RangeResponseGenerator is then used by the
+    WebCoreNSURLSession which downloads the entire media to be played and
+    keep it in memory.
+    
+    By modifying the various actors between a MediaResource and WebCoreNSURLSession
+    to use SharedBuffers ; we can remove most copies and allocation.
+    This also completely eliminates the need for new memory buffer allocations and
+    copies by the RangeResponseGenerator object.
+    
+    With WK2 and the GPU process, it allows for the memory to be allocated once
+    and only be assigned to the content process by using SharedMemory wrapped
+    in a SharedBuffer.
+    
+    In the future, by refactoring CachedRawResourceClient to use SharedBuffers,
+    we could remove further allocation/copies. We could likely get the data from the
+    network process all the way to the final client in the GPU process without
+    a single copy. This is tracked in bug 232424.
+    
+    No change in observable behaviour. Covered by all the existing media tests.
+    
+    * platform/SharedBuffer.cpp:
+    (WebCore::SharedBufferDataView::size const):
+    (WebCore::SharedBufferDataView::trim): Add ability to trim a SharedBufferDataView.
+    This allows to avoid having to copy into a new buffer.
+    (WebCore::SharedBufferDataView::createSharedBuffer const): Cross declarations
+    makes it difficult to add a new SharedBuffer constructor that would take a
+    SharedBufferDataView.
+    * platform/SharedBuffer.h: Add new methods.
+    * platform/cocoa/SharedBufferCocoa.mm: Update to allow for end trimming
+    information.
+    (-[WebCoreSharedBufferData initWithDataSegment:position:endTrim:]):
+    (-[WebCoreSharedBufferData length]):
+    (WebCore::SharedBuffer::DataSegment::createNSData const):
+    (WebCore::SharedBufferDataView::createNSData const):
+    (-[WebCoreSharedBufferData initWithDataSegment:position:]): Deleted.
+    * platform/graphics/PlatformMediaResourceLoader.h:
+    (WebCore::PlatformMediaResourceClient::dataReceived): Add a new API using
+    a SharedBuffer. We keep the old one taking a pointer/size due to a WebKit
+    implementation details which allows us to save an intermediary allocation/copy
+    when used with SharedMemory.
+    * platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm:
+    (WebCore::PlatformResourceMediaLoader::dataReceived):
+    * platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp:
+    (CachedResourceStreamingClient::dataReceived): Update to use SharedBuffer.
+    * platform/network/cocoa/RangeResponseGenerator.mm:
+    (WebCore::RangeResponseGenerator::giveResponseToTaskIfBytesInRangeReceived):
+    * platform/network/cocoa/WebCoreNSURLSession.h: Change prototypes.
+    Fly-by fix, property countOfBytesReceived needed to be atomic.
+    * platform/network/cocoa/WebCoreNSURLSession.mm:
+    (WebCore::WebCoreNSURLSessionDataTaskClient::dataReceived):
+    (-[WebCoreNSURLSessionDataTask resource:receivedData:]):
+    (-[WebCoreNSURLSessionDataTask resource:receivedRedirect:request:completionHandler:]):
+    
+    
+    git-svn-id: https://svn.webkit.org/repository/webkit/trunk@285069 268f45cc-cd09-0410-ab3c-d52691b4dbfc
+
+    2021-10-29  Jean-Yves Avenard  <[email protected]>
+
+            Have PlatformMediaResourceClient use SharedBuffer
+            https://bugs.webkit.org/show_bug.cgi?id=232422
+            rdar://84558835
+
+            Reviewed by Alex Christensen.
+
+            When playing a non-mse media element, the download gets controlled by a
+            MediaResource into a WebCoreNSURLSession to be used by the media framework.
+            The data got copied at least three times along the way due to the
+            multi-threaded nature of the framework and the need for thread
+            safety.
+            The situation was made worse when the content server didn't support
+            range-request: as a RangeResponseGenerator is then used by the
+            WebCoreNSURLSession which downloads the entire media to be played and
+            keep it in memory.
+
+            By modifying the various actors between a MediaResource and WebCoreNSURLSession
+            to use SharedBuffers ; we can remove most copies and allocation.
+            This also completely eliminates the need for new memory buffer allocations and
+            copies by the RangeResponseGenerator object.
+
+            With WK2 and the GPU process, it allows for the memory to be allocated once
+            and only be assigned to the content process by using SharedMemory wrapped
+            in a SharedBuffer.
+
+            In the future, by refactoring CachedRawResourceClient to use SharedBuffers,
+            we could remove further allocation/copies. We could likely get the data from the
+            network process all the way to the final client in the GPU process without
+            a single copy. This is tracked in bug 232424.
+
+            No change in observable behaviour. Covered by all the existing media tests.
+
+            * platform/SharedBuffer.cpp:
+            (WebCore::SharedBufferDataView::size const):
+            (WebCore::SharedBufferDataView::trim): Add ability to trim a SharedBufferDataView.
+            This allows to avoid having to copy into a new buffer.
+            (WebCore::SharedBufferDataView::createSharedBuffer const): Cross declarations
+            makes it difficult to add a new SharedBuffer constructor that would take a
+            SharedBufferDataView.
+            * platform/SharedBuffer.h: Add new methods.
+            * platform/cocoa/SharedBufferCocoa.mm: Update to allow for end trimming
+            information.
+            (-[WebCoreSharedBufferData initWithDataSegment:position:endTrim:]):
+            (-[WebCoreSharedBufferData length]):
+            (WebCore::SharedBuffer::DataSegment::createNSData const):
+            (WebCore::SharedBufferDataView::createNSData const):
+            (-[WebCoreSharedBufferData initWithDataSegment:position:]): Deleted.
+            * platform/graphics/PlatformMediaResourceLoader.h:
+            (WebCore::PlatformMediaResourceClient::dataReceived): Add a new API using
+            a SharedBuffer. We keep the old one taking a pointer/size due to a WebKit
+            implementation details which allows us to save an intermediary allocation/copy
+            when used with SharedMemory.
+            * platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm:
+            (WebCore::PlatformResourceMediaLoader::dataReceived):
+            * platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp:
+            (CachedResourceStreamingClient::dataReceived): Update to use SharedBuffer.
+            * platform/network/cocoa/RangeResponseGenerator.mm:
+            (WebCore::RangeResponseGenerator::giveResponseToTaskIfBytesInRangeReceived):
+            * platform/network/cocoa/WebCoreNSURLSession.h: Change prototypes.
+            Fly-by fix, property countOfBytesReceived needed to be atomic.
+            * platform/network/cocoa/WebCoreNSURLSession.mm:
+            (WebCore::WebCoreNSURLSessionDataTaskClient::dataReceived):
+            (-[WebCoreNSURLSessionDataTask resource:receivedData:]):
+            (-[WebCoreNSURLSessionDataTask resource:receivedRedirect:request:completionHandler:]):
+
+2021-11-04  Russell Epstein  <[email protected]>
+
         Cherry-pick r284853. rdar://problem/84516016
 
     Fix issue for transform-origin in SVG

Modified: branches/safari-612-branch/Source/WebCore/platform/SharedBuffer.cpp (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/platform/SharedBuffer.cpp	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/platform/SharedBuffer.cpp	2021-11-04 19:40:01 UTC (rev 285295)
@@ -441,16 +441,23 @@
     return WTF::visit(visitor, m_immutableData);
 }
 
-SharedBufferDataView::SharedBufferDataView(Ref<SharedBuffer::DataSegment>&& segment, size_t positionWithinSegment)
-    : m_positionWithinSegment(positionWithinSegment)
-    , m_segment(WTFMove(segment))
+SharedBufferDataView::SharedBufferDataView(Ref<SharedBuffer::DataSegment>&& segment, size_t positionWithinSegment, std::optional<size_t> size)
+    : m_segment(WTFMove(segment))
+    , m_positionWithinSegment(positionWithinSegment)
+    , m_size(size ? *size : m_segment->size() - positionWithinSegment)
 {
-    RELEASE_ASSERT(positionWithinSegment < m_segment->size());
+    RELEASE_ASSERT(m_positionWithinSegment < m_segment->size());
+    RELEASE_ASSERT(m_size <= m_segment->size() - m_positionWithinSegment);
 }
 
+SharedBufferDataView::SharedBufferDataView(const SharedBufferDataView& other, size_t newSize)
+    : SharedBufferDataView(other.m_segment.copyRef(), other.m_positionWithinSegment, newSize)
+{
+}
+
 size_t SharedBufferDataView::size() const
 {
-    return m_segment->size() - m_positionWithinSegment;
+    return m_size;
 }
 
 const uint8_t* SharedBufferDataView::data() const
@@ -458,6 +465,15 @@
     return m_segment->data() + m_positionWithinSegment;
 }
 
+Ref<SharedBuffer> SharedBufferDataView::createSharedBuffer() const
+{
+    const Ref<SharedBuffer::DataSegment> segment = m_segment;
+    return SharedBuffer::create(SharedBuffer::DataSegment::Provider {
+        [segment, data = "" { return data; },
+        [segment, size = size()]() { return size; }
+    });
+}
+
 RefPtr<SharedBuffer> utf8Buffer(const String& string)
 {
     // Allocate a buffer big enough to hold all the characters.

Modified: branches/safari-612-branch/Source/WebCore/platform/SharedBuffer.h (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/platform/SharedBuffer.h	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/platform/SharedBuffer.h	2021-11-04 19:40:01 UTC (rev 285295)
@@ -210,7 +210,7 @@
     DataSegmentVector::const_iterator begin() const { return m_segments.begin(); }
     DataSegmentVector::const_iterator end() const { return m_segments.end(); }
     bool hasOneSegment() const;
-    
+
     // begin and end take O(1) time, this takes O(log(N)) time.
     SharedBufferDataView getSomeData(size_t position) const;
 
@@ -265,16 +265,19 @@
 
 class WEBCORE_EXPORT SharedBufferDataView {
 public:
-    SharedBufferDataView(Ref<SharedBuffer::DataSegment>&&, size_t);
+    SharedBufferDataView(Ref<SharedBuffer::DataSegment>&&, size_t positionWithinSegment, std::optional<size_t> newSize = std::nullopt);
+    SharedBufferDataView(const SharedBufferDataView&, size_t newSize);
     size_t size() const;
     const uint8_t* data() const;
     const char* dataAsCharPtr() const { return reinterpret_cast<const char*>(data()); }
+    Ref<SharedBuffer> createSharedBuffer() const;
 #if USE(FOUNDATION)
     RetainPtr<NSData> createNSData() const;
 #endif
 private:
-    size_t m_positionWithinSegment;
-    Ref<SharedBuffer::DataSegment> m_segment;
+    const Ref<SharedBuffer::DataSegment> m_segment;
+    const size_t m_positionWithinSegment;
+    const size_t m_size;
 };
 
 RefPtr<SharedBuffer> utf8Buffer(const String&);

Modified: branches/safari-612-branch/Source/WebCore/platform/cocoa/SharedBufferCocoa.mm (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/platform/cocoa/SharedBufferCocoa.mm	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/platform/cocoa/SharedBufferCocoa.mm	2021-11-04 19:40:01 UTC (rev 285295)
@@ -34,12 +34,13 @@
 #import <wtf/cocoa/VectorCocoa.h>
 
 @interface WebCoreSharedBufferData : NSData
-- (instancetype)initWithDataSegment:(const WebCore::SharedBuffer::DataSegment&)dataSegment position:(NSUInteger)position;
+- (instancetype)initWithDataSegment:(const WebCore::SharedBuffer::DataSegment&)dataSegment position:(NSUInteger)position size:(NSUInteger)size;
 @end
 
 @implementation WebCoreSharedBufferData {
     RefPtr<const WebCore::SharedBuffer::DataSegment> _dataSegment;
     NSUInteger _position;
+    NSUInteger _size;
 }
 
 + (void)initialize
@@ -59,20 +60,22 @@
     [super dealloc];
 }
 
-- (instancetype)initWithDataSegment:(const WebCore::SharedBuffer::DataSegment&)dataSegment position:(NSUInteger)position
+- (instancetype)initWithDataSegment:(const WebCore::SharedBuffer::DataSegment&)dataSegment position:(NSUInteger)position size:(NSUInteger)size
 {
     if (!(self = [super init]))
         return nil;
 
-    RELEASE_ASSERT(!position || position < dataSegment.size());
+    RELEASE_ASSERT(position <= dataSegment.size());
+    RELEASE_ASSERT(size <= dataSegment.size() - position);
     _dataSegment = &dataSegment;
     _position = position;
+    _size = size;
     return self;
 }
 
 - (NSUInteger)length
 {
-    return _dataSegment->size() - _position;
+    return _size;
 }
 
 - (const void *)bytes
@@ -125,12 +128,12 @@
 
 RetainPtr<NSData> SharedBuffer::DataSegment::createNSData() const
 {
-    return adoptNS([[WebCoreSharedBufferData alloc] initWithDataSegment:*this position:0]);
+    return adoptNS([[WebCoreSharedBufferData alloc] initWithDataSegment:*this position:0 size:size()]);
 }
 
 RetainPtr<NSData> SharedBufferDataView::createNSData() const
 {
-    return adoptNS([[WebCoreSharedBufferData alloc] initWithDataSegment:m_segment.get() position:m_positionWithinSegment]);
+    return adoptNS([[WebCoreSharedBufferData alloc] initWithDataSegment:m_segment.get() position:m_positionWithinSegment size:size()]);
 }
 
 } // namespace WebCore

Modified: branches/safari-612-branch/Source/WebCore/platform/graphics/PlatformMediaResourceLoader.h (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/platform/graphics/PlatformMediaResourceLoader.h	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/platform/graphics/PlatformMediaResourceLoader.h	2021-11-04 19:40:01 UTC (rev 285295)
@@ -28,9 +28,11 @@
 #if ENABLE(VIDEO)
 
 #include "PolicyChecker.h"
+#include "SharedBuffer.h"
 #include <wtf/CompletionHandler.h>
 #include <wtf/Expected.h>
 #include <wtf/Noncopyable.h>
+#include <wtf/Ref.h>
 #include <wtf/RefCounted.h>
 #include <wtf/ThreadSafeRefCounted.h>
 
@@ -49,7 +51,9 @@
     virtual void redirectReceived(PlatformMediaResource&, ResourceRequest&& request, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&& completionHandler) { completionHandler(WTFMove(request)); }
     virtual bool shouldCacheResponse(PlatformMediaResource&, const ResourceResponse&) { return true; }
     virtual void dataSent(PlatformMediaResource&, unsigned long long, unsigned long long) { }
-    virtual void dataReceived(PlatformMediaResource&, const uint8_t*, int) { }
+    virtual void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&&) { RELEASE_ASSERT_NOT_REACHED(); }
+    // This method should be removed once CachedRawResourceClient uses SharedBuffer.
+    virtual void dataReceived(PlatformMediaResource& platform, const uint8_t* data, int length) { dataReceived(platform, SharedBuffer::create(data, length)); }
     virtual void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) { }
     virtual void loadFailed(PlatformMediaResource&, const ResourceError&) { }
     virtual void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) { }

Modified: branches/safari-612-branch/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm	2021-11-04 19:40:01 UTC (rev 285295)
@@ -154,7 +154,7 @@
     void redirectReceived(PlatformMediaResource&, ResourceRequest&& request, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&& completionHandler) final { completionHandler(WTFMove(request)); }
     bool shouldCacheResponse(PlatformMediaResource&, const ResourceResponse&) final { return false; }
     void dataSent(PlatformMediaResource&, unsigned long long, unsigned long long) final { }
-    void dataReceived(PlatformMediaResource&, const uint8_t*, int) final;
+    void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&&) final;
     void accessControlCheckFailed(PlatformMediaResource&, const ResourceError& error) final { loadFailed(error); }
     void loadFailed(PlatformMediaResource&, const ResourceError& error) final { loadFailed(error); }
     void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) final { loadFinished(); }
@@ -209,12 +209,12 @@
     m_parent.loadFinished();
 }
 
-void PlatformResourceMediaLoader::dataReceived(PlatformMediaResource&, const uint8_t* data, int size)
+void PlatformResourceMediaLoader::dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&& buffer)
 {
     if (!m_buffer)
-        m_buffer = SharedBuffer::create(data, size);
+        m_buffer = WTFMove(buffer);
     else
-        m_buffer->append(data, size);
+        m_buffer->append(WTFMove(buffer));
     m_parent.newDataStoredInSharedBuffer(*m_buffer);
 }
 

Modified: branches/safari-612-branch/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp	2021-11-04 19:40:01 UTC (rev 285295)
@@ -69,7 +69,7 @@
 
     // PlatformMediaResourceClient virtual methods.
     void responseReceived(PlatformMediaResource&, const ResourceResponse&, CompletionHandler<void(ShouldContinuePolicyCheck)>&&) override;
-    void dataReceived(PlatformMediaResource&, const uint8_t*, int) override;
+    void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&&) override;
     void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) override;
     void loadFailed(PlatformMediaResource&, const ResourceError&) override;
     void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) override;
@@ -1091,7 +1091,7 @@
     completionHandler(ShouldContinuePolicyCheck::Yes);
 }
 
-void CachedResourceStreamingClient::dataReceived(PlatformMediaResource&, const uint8_t* data, int length)
+void CachedResourceStreamingClient::dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&& buffer)
 {
     ASSERT(isMainThread());
     WebKitWebSrc* src = ""
@@ -1101,13 +1101,11 @@
     if (members->requestNumber != m_requestNumber)
         return;
 
-    GST_LOG_OBJECT(src, "R%u: Have %d bytes of data", m_requestNumber, length);
-
     // Rough bandwidth calculation. We ignore here the first data package because we would have to reset the counters when we issue the request and
     // that first package delivery would include the time of sending out the request and getting the data back. Since we can't distinguish the
     // sending time from the receiving time, it is better to ignore it.
     if (!std::isnan(members->downloadStartTime)) {
-        members->totalDownloadedBytes += length;
+        members->totalDownloadedBytes += buffer->size();
         double timeSinceStart = (WallTime::now() - members->downloadStartTime).seconds();
         GST_TRACE_OBJECT(src, "R%u: downloaded %" G_GUINT64_FORMAT " bytes in %f seconds =~ %1.0f bytes/second", m_requestNumber, members->totalDownloadedBytes, timeSinceStart
             , timeSinceStart ? members->totalDownloadedBytes / timeSinceStart : 0);
@@ -1115,16 +1113,20 @@
         members->downloadStartTime = WallTime::now();
     }
 
-    members->readPosition += length;
-    ASSERT(!members->haveSize || members->readPosition <= members->size);
+    buffer->forEachSegment([&](auto& segment) {
+        int length = segment.size();
+        GST_LOG_OBJECT(src, "R%u: Have %d bytes of data", m_requestNumber, length);
 
-    gst_element_post_message(GST_ELEMENT_CAST(src), gst_message_new_element(GST_OBJECT_CAST(src),
-        gst_structure_new("webkit-network-statistics", "read-position", G_TYPE_UINT64, members->readPosition, "size", G_TYPE_UINT64, members->size, nullptr)));
+        members->readPosition += length;
+        ASSERT(!members->haveSize || members->readPosition <= members->size);
 
-    checkUpdateBlocksize(length);
+        gst_element_post_message(GST_ELEMENT_CAST(src), gst_message_new_element(GST_OBJECT_CAST(src),
+            gst_structure_new("webkit-network-statistics", "read-position", G_TYPE_UINT64, members->readPosition, "size", G_TYPE_UINT64, members->size, nullptr)));
 
-    GstBuffer* buffer = gstBufferNewWrappedFast(fastMemDup(data, length), length);
-    gst_adapter_push(members->adapter.get(), buffer);
+        checkUpdateBlocksize(length);
+        GstBuffer* buffer = gstBufferNewWrappedFast(fastMemDup(segment.data(), length), length);
+        gst_adapter_push(members->adapter.get(), buffer);
+    });
     stopLoaderIfNeeded(src, members);
     members->responseCondition.notifyOne();
 }

Modified: branches/safari-612-branch/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm	2021-11-04 19:40:01 UTC (rev 285295)
@@ -130,7 +130,7 @@
 
             size_t bytesFromThisViewToDeliver = std::min(bufferView.size(), range.end - byteIndex + 1);
             byteIndex += bytesFromThisViewToDeliver;
-            [task resource:nullptr receivedData:bufferView.data() length:bytesFromThisViewToDeliver];
+            [task resource:nullptr receivedData:SharedBufferDataView(bufferView, bytesFromThisViewToDeliver).createSharedBuffer()];
         }
         if (byteIndex >= range.end) {
             [task resourceFinished:nullptr metrics:NetworkLoadMetrics { }];
@@ -236,7 +236,7 @@
         return false;
     }
 
-    void dataReceived(PlatformMediaResource&, const uint8_t* bytes, int length) final
+    void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&& buffer) final
     {
         ASSERT(isMainThread());
         if (!m_generator)
@@ -244,7 +244,7 @@
         auto* data = ""
         if (!data)
             return;
-        data->buffer->append(bytes, length);
+        data->buffer->append(WTFMove(buffer));
         m_generator->giveResponseToTasksWithFinishedRanges(*data);
     }
 

Modified: branches/safari-612-branch/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.h (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.h	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.h	2021-11-04 19:40:01 UTC (rev 285295)
@@ -30,6 +30,7 @@
 #import <wtf/HashSet.h>
 #import <wtf/Lock.h>
 #import <wtf/OSObjectPtr.h>
+#import <wtf/Ref.h>
 #import <wtf/RefPtr.h>
 #import <wtf/RetainPtr.h>
 #import <wtf/WeakObjCPtr.h>
@@ -49,6 +50,8 @@
 class ResourceError;
 class ResourceRequest;
 class ResourceResponse;
+class SharedBuffer;
+class SharedBufferDataView;
 class WebCoreNSURLSessionDataTaskClient;
 enum class ShouldContinuePolicyCheck : bool;
 }
@@ -138,7 +141,7 @@
 @property (copy) NSURLRequest *originalRequest;
 @property (copy) NSURLRequest *currentRequest;
 @property (readonly, copy) NSURLResponse *response;
-@property int64_t countOfBytesReceived;
+@property (assign, atomic) int64_t countOfBytesReceived;
 @property int64_t countOfBytesSent;
 @property int64_t countOfBytesExpectedToSend;
 @property int64_t countOfBytesExpectedToReceive;
@@ -155,7 +158,7 @@
 - (void)resource:(nullable WebCore::PlatformMediaResource*)resource sentBytes:(unsigned long long)bytesSent totalBytesToBeSent:(unsigned long long)totalBytesToBeSent;
 - (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedResponse:(const WebCore::ResourceResponse&)response completionHandler:(CompletionHandler<void(WebCore::ShouldContinuePolicyCheck)>&&)completionHandler;
 - (BOOL)resource:(nullable WebCore::PlatformMediaResource*)resource shouldCacheResponse:(const WebCore::ResourceResponse&)response;
-- (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedData:(const uint8_t*)data length:(int)length;
+- (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedData:(Ref<WebCore::SharedBuffer>&&)data;
 - (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedRedirect:(const WebCore::ResourceResponse&)response request:(WebCore::ResourceRequest&&)request completionHandler:(CompletionHandler<void(WebCore::ResourceRequest&&)>&&)completionHandler;
 - (void)resource:(nullable WebCore::PlatformMediaResource*)resource accessControlCheckFailedWithError:(const WebCore::ResourceError&)error;
 - (void)resource:(nullable WebCore::PlatformMediaResource*)resource loadFailedWithError:(const WebCore::ResourceError&)error;

Modified: branches/safari-612-branch/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.mm (285294 => 285295)


--- branches/safari-612-branch/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.mm	2021-11-04 19:39:56 UTC (rev 285294)
+++ branches/safari-612-branch/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.mm	2021-11-04 19:40:01 UTC (rev 285295)
@@ -20,7 +20,7 @@
  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #import "config.h"
@@ -29,6 +29,7 @@
 #import "CachedResourceRequest.h"
 #import "ParsedRequestRange.h"
 #import "PlatformMediaResourceLoader.h"
+#import "SharedBuffer.h"
 #import "SubresourceLoader.h"
 #import <pal/spi/cf/CFNetworkSPI.h>
 #import <wtf/BlockPtr.h>
@@ -587,7 +588,7 @@
     void redirectReceived(PlatformMediaResource&, ResourceRequest&&, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&&) override;
     bool shouldCacheResponse(PlatformMediaResource&, const ResourceResponse&) override;
     void dataSent(PlatformMediaResource&, unsigned long long, unsigned long long) override;
-    void dataReceived(PlatformMediaResource&, const uint8_t* /* data */, int /* length */) override;
+    void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&&) override;
     void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) override;
     void loadFailed(PlatformMediaResource&, const ResourceError&) override;
     void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) override;
@@ -631,13 +632,13 @@
     return [m_task resource:&resource shouldCacheResponse:response];
 }
 
-void WebCoreNSURLSessionDataTaskClient::dataReceived(PlatformMediaResource& resource, const uint8_t* data, int length)
+void WebCoreNSURLSessionDataTaskClient::dataReceived(PlatformMediaResource& resource, Ref<SharedBuffer>&& buffer)
 {
     Locker locker { m_taskLock };
     if (!m_task)
         return;
 
-    [m_task resource:&resource receivedData:data length:length];
+    [m_task resource:&resource receivedData:WTFMove(buffer)];
 }
 
 void WebCoreNSURLSessionDataTaskClient::redirectReceived(PlatformMediaResource& resource, ResourceRequest&& request, const ResourceResponse& response, CompletionHandler<void(ResourceRequest&&)>&& completionHandler)
@@ -890,13 +891,12 @@
     return response.httpHeaderField(HTTPHeaderName::ContentRange).isEmpty();
 }
 
-- (void)resource:(PlatformMediaResource*)resource receivedData:(const uint8_t*)data length:(int)length
+- (void)resource:(PlatformMediaResource*)resource receivedData:(Ref<WebCore::SharedBuffer>&&)data
 {
     ASSERT_UNUSED(resource, !resource || resource == _resource);
-    RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytes:data length:length]);
-    RetainPtr<WebCoreNSURLSessionDataTask> strongSelf { self };
-    [self.session addDelegateOperation:[strongSelf, length, nsData] {
-        strongSelf.get().countOfBytesReceived += length;
+    [self.session addDelegateOperation:[strongSelf = RetainPtr { self }, data = "" {
+        auto nsData = data->createNSData();
+        strongSelf.get().countOfBytesReceived += data->size();
         id<NSURLSessionDataDelegate> dataDelegate = (id<NSURLSessionDataDelegate>)strongSelf.get().session.delegate;
         if ([dataDelegate respondsToSelector:@selector(URLSession:dataTask:didReceiveData:)])
             [dataDelegate URLSession:(NSURLSession *)strongSelf.get().session dataTask:(NSURLSessionDataTask *)strongSelf.get() didReceiveData:nsData.get()];
@@ -914,7 +914,7 @@
             });
             return;
         }
-        
+
         id<NSURLSessionDataDelegate> dataDelegate = (id<NSURLSessionDataDelegate>)strongSelf.get().session.delegate;
         if ([dataDelegate respondsToSelector:@selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)]) {
             auto completionHandlerBlock = makeBlockPtr([completionHandler = WTFMove(completionHandler)](NSURLRequest *newRequest) mutable {
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to