CrashTracer beneath JSC::MarkedBlock::specializedSweep
[WebKit-https.git] / Source / WebCore / platform / graphics / avfoundation / objc / WebCoreAVFResourceLoader.mm
1 /*
2  * Copyright (C) 2012 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "WebCoreAVFResourceLoader.h"
28
29 #if ENABLE(VIDEO) && USE(AVFOUNDATION) && HAVE(AVFOUNDATION_LOADER_DELEGATE)
30
31 #import "CachedRawResource.h"
32 #import "CachedResourceLoader.h"
33 #import "CachedResourceRequest.h"
34 #import "MediaPlayerPrivateAVFoundationObjC.h"
35 #import "ResourceLoaderOptions.h"
36 #import "SharedBuffer.h"
37 #import "SoftLinking.h"
38 #import "UTIUtilities.h"
39 #import <AVFoundation/AVAssetResourceLoader.h>
40 #import <objc/runtime.h>
41 #import <wtf/text/CString.h>
42
43 namespace WebCore {
44
45 PassRefPtr<WebCoreAVFResourceLoader> WebCoreAVFResourceLoader::create(MediaPlayerPrivateAVFoundationObjC* parent, AVAssetResourceLoadingRequest *avRequest)
46 {
47     ASSERT(avRequest);
48     ASSERT(parent);
49     return adoptRef(new WebCoreAVFResourceLoader(parent, avRequest));
50 }
51
52 WebCoreAVFResourceLoader::WebCoreAVFResourceLoader(MediaPlayerPrivateAVFoundationObjC* parent, AVAssetResourceLoadingRequest *avRequest)
53     : m_parent(parent)
54     , m_avRequest(avRequest)
55 {
56 }
57
58 WebCoreAVFResourceLoader::~WebCoreAVFResourceLoader()
59 {
60     stopLoading();
61 }
62
63 void WebCoreAVFResourceLoader::startLoading()
64 {
65     if (m_resource || !m_parent)
66         return;
67
68     NSURLRequest *nsRequest = [m_avRequest.get() request];
69
70     // FIXME: Skip Content Security Policy check if the element that inititated this request
71     // is in a user-agent shadow tree. See <https://bugs.webkit.org/show_bug.cgi?id=155505>.
72     CachedResourceRequest request(nsRequest, ResourceLoaderOptions(SendCallbacks, DoNotSniffContent, BufferData, DoNotAllowStoredCredentials, DoNotAskClientForCrossOriginCredentials, ClientDidNotRequestCredentials, DoSecurityCheck, UseDefaultOriginRestrictionsForType, DoNotIncludeCertificateInfo, ContentSecurityPolicyImposition::DoPolicyCheck, DefersLoadingPolicy::AllowDefersLoading, CachingPolicy::DisallowCaching));
73     request.mutableResourceRequest().setPriority(ResourceLoadPriority::Low);
74     if (auto* loader = m_parent->player()->cachedResourceLoader())
75         m_resource = loader->requestMedia(request);
76
77     if (m_resource)
78         m_resource->addClient(this);
79     else {
80         LOG_ERROR("Failed to start load for media at url %s", [[[nsRequest URL] absoluteString] UTF8String]);
81         [m_avRequest.get() finishLoadingWithError:0];
82     }
83 }
84
85 void WebCoreAVFResourceLoader::stopLoading()
86 {
87     if (!m_resource)
88         return;
89
90     m_resource->removeClient(this);
91     m_resource = 0;
92
93     if (m_parent && m_avRequest)
94         m_parent->didStopLoadingRequest(m_avRequest.get());
95 }
96
97 void WebCoreAVFResourceLoader::invalidate()
98 {
99     if (!m_parent)
100         return;
101
102     m_parent = nullptr;
103
104     callOnMainThread([protectedThis = Ref<WebCoreAVFResourceLoader>(*this)] () mutable {
105         protectedThis->stopLoading();
106     });
107 }
108
109 void WebCoreAVFResourceLoader::responseReceived(CachedResource* resource, const ResourceResponse& response)
110 {
111     ASSERT(resource);
112     ASSERT(resource == m_resource);
113
114     int status = response.httpStatusCode();
115     if (status && (status < 200 || status > 299)) {
116         [m_avRequest.get() finishLoadingWithError:0];
117         return;
118     }
119
120     if (AVAssetResourceLoadingContentInformationRequest* contentInfo = [m_avRequest.get() contentInformationRequest]) {
121         String uti = UTIFromMIMEType(response.mimeType().createCFString().get()).get();
122
123         [contentInfo setContentType:uti];
124
125         ParsedContentRange& contentRange = resource->response().contentRange();
126         [contentInfo setContentLength:contentRange.isValid() ? contentRange.instanceLength() : response.expectedContentLength()];
127         [contentInfo setByteRangeAccessSupported:YES];
128
129         if (![m_avRequest dataRequest]) {
130             [m_avRequest.get() finishLoading];
131             stopLoading();
132         }
133     }
134 }
135
136 void WebCoreAVFResourceLoader::dataReceived(CachedResource* resource, const char*, int)
137 {
138     fulfillRequestWithResource(resource);
139 }
140
141 void WebCoreAVFResourceLoader::notifyFinished(CachedResource* resource)
142 {
143     if (resource->loadFailedOrCanceled()) {
144         // <rdar://problem/13987417> Set the contentType of the contentInformationRequest to an empty
145         // string to trigger AVAsset's playable value to complete loading.
146         if ([m_avRequest.get() contentInformationRequest] && ![[m_avRequest.get() contentInformationRequest] contentType])
147             [[m_avRequest.get() contentInformationRequest] setContentType:@""];
148
149         [m_avRequest.get() finishLoadingWithError:0];
150     } else {
151         fulfillRequestWithResource(resource);
152         [m_avRequest.get() finishLoading];
153     }
154     stopLoading();
155 }
156
157 void WebCoreAVFResourceLoader::fulfillRequestWithResource(CachedResource* resource)
158 {
159     ASSERT(resource);
160     ASSERT(resource == m_resource);
161     AVAssetResourceLoadingDataRequest* dataRequest = [m_avRequest dataRequest];
162     if (!dataRequest)
163         return;
164
165     SharedBuffer* data = resource->resourceBuffer();
166     if (!data)
167         return;
168
169     NSUInteger responseOffset = 0;
170     ParsedContentRange contentRange = resource->response().contentRange();
171     if (contentRange.isValid())
172         responseOffset = static_cast<NSUInteger>(contentRange.firstBytePosition());
173
174     // Check for possible unsigned overflow.
175     ASSERT([dataRequest currentOffset] >= [dataRequest requestedOffset]);
176     ASSERT([dataRequest requestedLength] >= ([dataRequest currentOffset] - [dataRequest requestedOffset]));
177
178     NSUInteger remainingLength = [dataRequest requestedLength] - static_cast<NSUInteger>([dataRequest currentOffset] - [dataRequest requestedOffset]);
179     do {
180         // Check to see if there is any data available in the buffer to fulfill the data request.
181         if (data->size() <= [dataRequest currentOffset] - responseOffset)
182             return;
183
184         const char* someData;
185         NSUInteger receivedLength = data->getSomeData(someData, static_cast<unsigned>([dataRequest currentOffset] - responseOffset));
186
187         // Create an NSData with only as much of the received data as necessary to fulfill the request.
188         NSUInteger length = MIN(receivedLength, remainingLength);
189         RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytes:someData length:length]);
190
191         [dataRequest respondWithData:nsData.get()];
192         remainingLength -= length;
193     } while (remainingLength);
194
195     if ([dataRequest currentOffset] + [dataRequest requestedLength] >= [dataRequest requestedOffset]) {
196         [m_avRequest.get() finishLoading];
197         stopLoading();
198     }
199 }
200
201 }
202
203 #endif // ENABLE(VIDEO) && USE(AVFOUNDATION)