782fc1ff5be481357eb8ce7270aed5c0091371e0
[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     m_parent = nullptr;
100     stopLoading();
101 }
102
103 void WebCoreAVFResourceLoader::responseReceived(CachedResource* resource, const ResourceResponse& response)
104 {
105     ASSERT(resource);
106     ASSERT(resource == m_resource);
107
108     int status = response.httpStatusCode();
109     if (status && (status < 200 || status > 299)) {
110         [m_avRequest.get() finishLoadingWithError:0];
111         return;
112     }
113
114     if (AVAssetResourceLoadingContentInformationRequest* contentInfo = [m_avRequest.get() contentInformationRequest]) {
115         String uti = UTIFromMIMEType(response.mimeType().createCFString().get()).get();
116
117         [contentInfo setContentType:uti];
118
119         ParsedContentRange& contentRange = resource->response().contentRange();
120         [contentInfo setContentLength:contentRange.isValid() ? contentRange.instanceLength() : response.expectedContentLength()];
121         [contentInfo setByteRangeAccessSupported:YES];
122
123         if (![m_avRequest dataRequest]) {
124             [m_avRequest.get() finishLoading];
125             stopLoading();
126         }
127     }
128 }
129
130 void WebCoreAVFResourceLoader::dataReceived(CachedResource* resource, const char*, int)
131 {
132     fulfillRequestWithResource(resource);
133 }
134
135 void WebCoreAVFResourceLoader::notifyFinished(CachedResource* resource)
136 {
137     if (resource->loadFailedOrCanceled()) {
138         // <rdar://problem/13987417> Set the contentType of the contentInformationRequest to an empty
139         // string to trigger AVAsset's playable value to complete loading.
140         if ([m_avRequest.get() contentInformationRequest] && ![[m_avRequest.get() contentInformationRequest] contentType])
141             [[m_avRequest.get() contentInformationRequest] setContentType:@""];
142
143         [m_avRequest.get() finishLoadingWithError:0];
144     } else {
145         fulfillRequestWithResource(resource);
146         [m_avRequest.get() finishLoading];
147     }
148     stopLoading();
149 }
150
151 void WebCoreAVFResourceLoader::fulfillRequestWithResource(CachedResource* resource)
152 {
153     ASSERT(resource);
154     ASSERT(resource == m_resource);
155     AVAssetResourceLoadingDataRequest* dataRequest = [m_avRequest dataRequest];
156     if (!dataRequest)
157         return;
158
159     SharedBuffer* data = resource->resourceBuffer();
160     if (!data)
161         return;
162
163     NSUInteger responseOffset = 0;
164     ParsedContentRange contentRange = resource->response().contentRange();
165     if (contentRange.isValid())
166         responseOffset = static_cast<NSUInteger>(contentRange.firstBytePosition());
167
168     // Check for possible unsigned overflow.
169     ASSERT([dataRequest currentOffset] >= [dataRequest requestedOffset]);
170     ASSERT([dataRequest requestedLength] >= ([dataRequest currentOffset] - [dataRequest requestedOffset]));
171
172     NSUInteger remainingLength = [dataRequest requestedLength] - static_cast<NSUInteger>([dataRequest currentOffset] - [dataRequest requestedOffset]);
173     do {
174         // Check to see if there is any data available in the buffer to fulfill the data request.
175         if (data->size() <= [dataRequest currentOffset] - responseOffset)
176             return;
177
178         const char* someData;
179         NSUInteger receivedLength = data->getSomeData(someData, static_cast<unsigned>([dataRequest currentOffset] - responseOffset));
180
181         // Create an NSData with only as much of the received data as necessary to fulfill the request.
182         NSUInteger length = MIN(receivedLength, remainingLength);
183         RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytes:someData length:length]);
184
185         [dataRequest respondWithData:nsData.get()];
186         remainingLength -= length;
187     } while (remainingLength);
188
189     if ([dataRequest currentOffset] + [dataRequest requestedLength] >= [dataRequest requestedOffset]) {
190         [m_avRequest.get() finishLoading];
191         stopLoading();
192     }
193 }
194
195 }
196
197 #endif // ENABLE(VIDEO) && USE(AVFOUNDATION)