16b07e64c4da201ca97e151ec47f5eea1c0fe38c
[WebKit-https.git] / Source / WebCore / platform / graphics / avfoundation / objc / WebCoreAVFResourceLoader.mm
1 /*
2  * Copyright (C) 2012-2017 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 "UTIUtilities.h"
38 #import <AVFoundation/AVAssetResourceLoader.h>
39 #import <objc/runtime.h>
40 #import <wtf/SoftLinking.h>
41 #import <wtf/text/CString.h>
42
43 namespace WebCore {
44
45 Ref<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     ResourceRequest resourceRequest(nsRequest);
71     resourceRequest.setPriority(ResourceLoadPriority::Low);
72
73     // FIXME: Skip Content Security Policy check if the element that inititated this request
74     // is in a user-agent shadow tree. See <https://bugs.webkit.org/show_bug.cgi?id=173498>.
75     CachedResourceRequest request(WTFMove(resourceRequest), ResourceLoaderOptions(SendCallbacks, DoNotSniffContent, BufferData, StoredCredentialsPolicy::DoNotUse, ClientCredentialPolicy::CannotAskClientForCredentials, FetchOptions::Credentials::Omit, DoSecurityCheck, FetchOptions::Mode::NoCors, DoNotIncludeCertificateInfo, ContentSecurityPolicyImposition::DoPolicyCheck, DefersLoadingPolicy::AllowDefersLoading, CachingPolicy::DisallowCaching));
76     if (auto* loader = m_parent->player()->cachedResourceLoader())
77         m_resource = loader->requestMedia(WTFMove(request)).value_or(nullptr);
78
79     if (m_resource)
80         m_resource->addClient(*this);
81     else {
82         LOG_ERROR("Failed to start load for media at url %s", [[[nsRequest URL] absoluteString] UTF8String]);
83         [m_avRequest.get() finishLoadingWithError:0];
84     }
85 }
86
87 void WebCoreAVFResourceLoader::stopLoading()
88 {
89     if (!m_resource)
90         return;
91
92     m_resource->removeClient(*this);
93     m_resource = 0;
94
95     if (m_parent && m_avRequest)
96         m_parent->didStopLoadingRequest(m_avRequest.get());
97 }
98
99 void WebCoreAVFResourceLoader::invalidate()
100 {
101     if (!m_parent)
102         return;
103
104     m_parent = nullptr;
105
106     callOnMainThread([protectedThis = makeRef(*this)] () mutable {
107         protectedThis->stopLoading();
108     });
109 }
110
111 void WebCoreAVFResourceLoader::responseReceived(CachedResource& resource, const ResourceResponse& response, CompletionHandler<void()>&& completionHandler)
112 {
113     ASSERT_UNUSED(resource, &resource == m_resource);
114     CompletionHandlerCallingScope completionHandlerCaller(WTFMove(completionHandler));
115
116     int status = response.httpStatusCode();
117     if (status && (status < 200 || status > 299)) {
118         [m_avRequest.get() finishLoadingWithError:0];
119         return;
120     }
121
122     if (AVAssetResourceLoadingContentInformationRequest* contentInfo = [m_avRequest.get() contentInformationRequest]) {
123         String uti = UTIFromMIMEType(response.mimeType());
124
125         [contentInfo setContentType:uti];
126
127         ParsedContentRange& contentRange = m_resource->response().contentRange();
128         [contentInfo setContentLength:contentRange.isValid() ? contentRange.instanceLength() : response.expectedContentLength()];
129         [contentInfo setByteRangeAccessSupported:YES];
130
131         if (![m_avRequest dataRequest]) {
132             [m_avRequest.get() finishLoading];
133             stopLoading();
134         }
135     }
136 }
137
138 void WebCoreAVFResourceLoader::dataReceived(CachedResource& resource, const char*, int)
139 {
140     fulfillRequestWithResource(resource);
141 }
142
143 void WebCoreAVFResourceLoader::notifyFinished(CachedResource& resource)
144 {
145     if (resource.loadFailedOrCanceled()) {
146         // <rdar://problem/13987417> Set the contentType of the contentInformationRequest to an empty
147         // string to trigger AVAsset's playable value to complete loading.
148         if ([m_avRequest.get() contentInformationRequest] && ![[m_avRequest.get() contentInformationRequest] contentType])
149             [[m_avRequest.get() contentInformationRequest] setContentType:@""];
150
151         NSError* error = resource.errorOccurred() ? resource.resourceError().nsError() : nil;
152         [m_avRequest.get() finishLoadingWithError:error];
153     } else {
154         fulfillRequestWithResource(resource);
155         [m_avRequest.get() finishLoading];
156     }
157     stopLoading();
158 }
159
160 void WebCoreAVFResourceLoader::fulfillRequestWithResource(CachedResource& resource)
161 {
162     ASSERT_UNUSED(resource, &resource == m_resource);
163     AVAssetResourceLoadingDataRequest* dataRequest = [m_avRequest dataRequest];
164     if (!dataRequest)
165         return;
166
167     SharedBuffer* data = m_resource->resourceBuffer();
168     if (!data)
169         return;
170
171     NSUInteger responseOffset = 0;
172     ParsedContentRange contentRange = m_resource->response().contentRange();
173     if (contentRange.isValid())
174         responseOffset = static_cast<NSUInteger>(contentRange.firstBytePosition());
175
176     // Check for possible unsigned overflow.
177     ASSERT(dataRequest.currentOffset >= dataRequest.requestedOffset);
178     ASSERT(dataRequest.requestedLength >= (dataRequest.currentOffset - dataRequest.requestedOffset));
179
180     NSUInteger remainingLength = dataRequest.requestedLength - static_cast<NSUInteger>(dataRequest.currentOffset - dataRequest.requestedOffset);
181
182     auto bytesToSkip = dataRequest.currentOffset - responseOffset;
183     RetainPtr<NSArray> array = data->createNSDataArray();
184     for (NSData *segment in array.get()) {
185         if (bytesToSkip) {
186             if (bytesToSkip > segment.length) {
187                 bytesToSkip -= segment.length;
188                 continue;
189             }
190             auto bytesToUse = segment.length - bytesToSkip;
191             [dataRequest respondWithData:[segment subdataWithRange:NSMakeRange(static_cast<NSUInteger>(bytesToSkip), static_cast<NSUInteger>(segment.length - bytesToSkip))]];
192             bytesToSkip = 0;
193             remainingLength -= bytesToUse;
194             continue;
195         }
196         if (segment.length <= remainingLength) {
197             [dataRequest respondWithData:segment];
198             remainingLength -= segment.length;
199             continue;
200         }
201         [dataRequest respondWithData:[segment subdataWithRange:NSMakeRange(0, remainingLength)]];
202         remainingLength = 0;
203         break;
204     }
205
206     // There was not enough data in the buffer to satisfy the data request.
207     if (remainingLength)
208         return;
209
210     if (dataRequest.currentOffset + dataRequest.requestedLength >= dataRequest.requestedOffset) {
211         [m_avRequest.get() finishLoading];
212         stopLoading();
213     }
214 }
215
216 }
217
218 #endif // ENABLE(VIDEO) && USE(AVFOUNDATION)