Unreviewed, rolling out r215608.
[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     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=155505>.
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     do {
181         // Check to see if there is any data available in the buffer to fulfill the data request.
182         if (data->size() <= [dataRequest currentOffset] - responseOffset)
183             return;
184
185         const char* someData;
186         NSUInteger receivedLength = data->getSomeData(someData, static_cast<unsigned>([dataRequest currentOffset] - responseOffset));
187
188         // Create an NSData with only as much of the received data as necessary to fulfill the request.
189         NSUInteger length = MIN(receivedLength, remainingLength);
190         RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytes:someData length:length]);
191
192         [dataRequest respondWithData:nsData.get()];
193         remainingLength -= length;
194     } while (remainingLength);
195
196     if ([dataRequest currentOffset] + [dataRequest requestedLength] >= [dataRequest requestedOffset]) {
197         [m_avRequest.get() finishLoading];
198         stopLoading();
199     }
200 }
201
202 }
203
204 #endif // ENABLE(VIDEO) && USE(AVFOUNDATION)