04b5c3883ac9507301386f705cc213c0a43306bf
[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 "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, DoNotAllowStoredCredentials, 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));
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)
112 {
113     ASSERT_UNUSED(resource, &resource == m_resource);
114
115     int status = response.httpStatusCode();
116     if (status && (status < 200 || status > 299)) {
117         [m_avRequest.get() finishLoadingWithError:0];
118         return;
119     }
120
121     if (AVAssetResourceLoadingContentInformationRequest* contentInfo = [m_avRequest.get() contentInformationRequest]) {
122         String uti = UTIFromMIMEType(response.mimeType().createCFString().get()).get();
123
124         [contentInfo setContentType:uti];
125
126         ParsedContentRange& contentRange = m_resource->response().contentRange();
127         [contentInfo setContentLength:contentRange.isValid() ? contentRange.instanceLength() : response.expectedContentLength()];
128         [contentInfo setByteRangeAccessSupported:YES];
129
130         if (![m_avRequest dataRequest]) {
131             [m_avRequest.get() finishLoading];
132             stopLoading();
133         }
134     }
135 }
136
137 void WebCoreAVFResourceLoader::dataReceived(CachedResource& resource, const char*, int)
138 {
139     fulfillRequestWithResource(resource);
140 }
141
142 void WebCoreAVFResourceLoader::notifyFinished(CachedResource& resource)
143 {
144     if (resource.loadFailedOrCanceled()) {
145         // <rdar://problem/13987417> Set the contentType of the contentInformationRequest to an empty
146         // string to trigger AVAsset's playable value to complete loading.
147         if ([m_avRequest.get() contentInformationRequest] && ![[m_avRequest.get() contentInformationRequest] contentType])
148             [[m_avRequest.get() contentInformationRequest] setContentType:@""];
149
150         NSError* error = resource.errorOccurred() ? resource.resourceError().nsError() : nil;
151         [m_avRequest.get() finishLoadingWithError:error];
152     } else {
153         fulfillRequestWithResource(resource);
154         [m_avRequest.get() finishLoading];
155     }
156     stopLoading();
157 }
158
159 void WebCoreAVFResourceLoader::fulfillRequestWithResource(CachedResource& resource)
160 {
161     ASSERT_UNUSED(resource, &resource == m_resource);
162     AVAssetResourceLoadingDataRequest* dataRequest = [m_avRequest dataRequest];
163     if (!dataRequest)
164         return;
165
166     SharedBuffer* data = m_resource->resourceBuffer();
167     if (!data)
168         return;
169
170     NSUInteger responseOffset = 0;
171     ParsedContentRange contentRange = m_resource->response().contentRange();
172     if (contentRange.isValid())
173         responseOffset = static_cast<NSUInteger>(contentRange.firstBytePosition());
174
175     // Check for possible unsigned overflow.
176     ASSERT(dataRequest.currentOffset >= dataRequest.requestedOffset);
177     ASSERT(dataRequest.requestedLength >= (dataRequest.currentOffset - dataRequest.requestedOffset));
178
179     NSUInteger remainingLength = dataRequest.requestedLength - static_cast<NSUInteger>(dataRequest.currentOffset - dataRequest.requestedOffset);
180
181     auto bytesToSkip = dataRequest.currentOffset - responseOffset;
182     RetainPtr<NSArray> array = data->createNSDataArray();
183     for (NSData *segment in array.get()) {
184         if (bytesToSkip) {
185             if (bytesToSkip > segment.length) {
186                 bytesToSkip -= segment.length;
187                 continue;
188             }
189             auto bytesToUse = segment.length - bytesToSkip;
190             [dataRequest respondWithData:[segment subdataWithRange:NSMakeRange(static_cast<NSUInteger>(bytesToSkip), static_cast<NSUInteger>(segment.length - bytesToSkip))]];
191             bytesToSkip = 0;
192             remainingLength -= bytesToUse;
193             continue;
194         }
195         if (segment.length <= remainingLength) {
196             [dataRequest respondWithData:segment];
197             remainingLength -= segment.length;
198             continue;
199         }
200         [dataRequest respondWithData:[segment subdataWithRange:NSMakeRange(0, remainingLength)]];
201         remainingLength = 0;
202         break;
203     }
204
205     // There was not enough data in the buffer to satisfy the data request.
206     if (remainingLength)
207         return;
208
209     if (dataRequest.currentOffset + dataRequest.requestedLength >= dataRequest.requestedOffset) {
210         [m_avRequest.get() finishLoading];
211         stopLoading();
212     }
213 }
214
215 }
216
217 #endif // ENABLE(VIDEO) && USE(AVFOUNDATION)