fc1e48a94ea5dbafe9c2a653350d6806d015866b
[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     URL requestURL = [[m_avRequest.get() request] URL];
69
70     // ContentSecurityPolicyImposition::DoPolicyCheck is a placeholder value. It does not affect the request since Content Security Policy does not apply to raw resources.
71     CachedResourceRequest request(ResourceRequest(requestURL), ResourceLoaderOptions(SendCallbacks, DoNotSniffContent, BufferData, DoNotAllowStoredCredentials, DoNotAskClientForCrossOriginCredentials, DoSecurityCheck, UseDefaultOriginRestrictionsForType, DoNotIncludeCertificateInfo, ContentSecurityPolicyImposition::DoPolicyCheck, DefersLoadingPolicy::AllowDefersLoading));
72
73     request.mutableResourceRequest().setPriority(ResourceLoadPriority::Low);
74     CachedResourceLoader* loader = m_parent->player()->cachedResourceLoader();
75     m_resource = loader ? loader->requestRawResource(request) : 0;
76     if (m_resource)
77         m_resource->addClient(this);
78     else {
79         LOG_ERROR("Failed to start load for media at url %s", requestURL.string().ascii().data());
80         [m_avRequest.get() finishLoadingWithError:0];
81     }
82 }
83
84 void WebCoreAVFResourceLoader::stopLoading()
85 {
86     if (!m_resource)
87         return;
88
89     m_resource->removeClient(this);
90     m_resource = 0;
91
92     if (m_parent && m_avRequest)
93         m_parent->didStopLoadingRequest(m_avRequest.get());
94 }
95
96 void WebCoreAVFResourceLoader::invalidate()
97 {
98     m_parent = nullptr;
99     stopLoading();
100 }
101
102 void WebCoreAVFResourceLoader::responseReceived(CachedResource* resource, const ResourceResponse& response)
103 {
104     ASSERT(resource == m_resource);
105     UNUSED_PARAM(resource);
106
107     int status = response.httpStatusCode();
108     if (status && (status < 200 || status > 299)) {
109         [m_avRequest.get() finishLoadingWithError:0];
110         return;
111     }
112
113     if (AVAssetResourceLoadingContentInformationRequest* contentInfo = [m_avRequest.get() contentInformationRequest]) {
114         String uti = UTIFromMIMEType(response.mimeType().createCFString().get()).get();
115
116         [contentInfo setContentType:uti];
117         [contentInfo setContentLength:response.expectedContentLength()];
118         [contentInfo setByteRangeAccessSupported:YES];
119
120         if (![m_avRequest dataRequest]) {
121             [m_avRequest.get() finishLoading];
122             stopLoading();
123         }
124     }
125 }
126
127 void WebCoreAVFResourceLoader::dataReceived(CachedResource* resource, const char*, int)
128 {
129     fulfillRequestWithResource(resource);
130 }
131
132 void WebCoreAVFResourceLoader::notifyFinished(CachedResource* resource)
133 {
134     if (resource->loadFailedOrCanceled()) {
135         // <rdar://problem/13987417> Set the contentType of the contentInformationRequest to an empty
136         // string to trigger AVAsset's playable value to complete loading.
137         if ([m_avRequest.get() contentInformationRequest] && ![[m_avRequest.get() contentInformationRequest] contentType])
138             [[m_avRequest.get() contentInformationRequest] setContentType:@""];
139
140         [m_avRequest.get() finishLoadingWithError:0];
141     } else {
142         fulfillRequestWithResource(resource);
143         [m_avRequest.get() finishLoading];
144     }
145     stopLoading();
146 }
147
148 void WebCoreAVFResourceLoader::fulfillRequestWithResource(CachedResource* resource)
149 {
150     ASSERT(resource == m_resource);
151     AVAssetResourceLoadingDataRequest* dataRequest = [m_avRequest dataRequest];
152     if (!dataRequest)
153         return;
154
155     SharedBuffer* data = resource->resourceBuffer();
156     if (!data)
157         return;
158
159     // Check for possible unsigned overflow.
160     ASSERT([dataRequest currentOffset] >= [dataRequest requestedOffset]);
161     ASSERT([dataRequest requestedLength] >= ([dataRequest currentOffset] - [dataRequest requestedOffset]));
162
163     NSUInteger remainingLength = [dataRequest requestedLength] - static_cast<NSUInteger>([dataRequest currentOffset] - [dataRequest requestedOffset]);
164     do {
165         // Check to see if there is any data available in the buffer to fulfill the data request.
166         if (data->size() <= [dataRequest currentOffset])
167             return;
168
169         const char* someData;
170         NSUInteger receivedLength = data->getSomeData(someData, static_cast<unsigned>([dataRequest currentOffset]));
171
172         // Create an NSData with only as much of the received data as necessary to fulfill the request.
173         NSUInteger length = MIN(receivedLength, remainingLength);
174         RetainPtr<NSData> nsData = adoptNS([[NSData alloc] initWithBytes:someData length:length]);
175
176         [dataRequest respondWithData:nsData.get()];
177         remainingLength -= length;
178     } while (remainingLength);
179
180     if ([dataRequest currentOffset] + [dataRequest requestedLength] >= [dataRequest requestedOffset]) {
181         [m_avRequest.get() finishLoading];
182         stopLoading();
183     }
184 }
185
186 }
187
188 #endif // ENABLE(VIDEO) && USE(AVFOUNDATION)