OLD | NEW |
| (Empty) |
1 // Copyright 2013 The Chromium Authors. All rights reserved. | |
2 // Use of this source code is governed by a BSD-style license that can be | |
3 // found in the LICENSE file. | |
4 | |
5 #ifndef MEDIA_BLINK_BUFFERED_RESOURCE_LOADER_H_ | |
6 #define MEDIA_BLINK_BUFFERED_RESOURCE_LOADER_H_ | |
7 | |
8 #include <stdint.h> | |
9 | |
10 #include <memory> | |
11 #include <string> | |
12 | |
13 #include "base/callback.h" | |
14 #include "base/macros.h" | |
15 #include "media/base/seekable_buffer.h" | |
16 #include "media/blink/active_loader.h" | |
17 #include "media/blink/media_blink_export.h" | |
18 #include "media/blink/url_index.h" // for kPositionNotSpecified | |
19 #include "third_party/WebKit/public/platform/WebURLLoader.h" | |
20 #include "third_party/WebKit/public/platform/WebURLLoaderClient.h" | |
21 #include "third_party/WebKit/public/platform/WebURLRequest.h" | |
22 #include "third_party/WebKit/public/web/WebFrame.h" | |
23 #include "url/gurl.h" | |
24 | |
25 namespace media { | |
26 class MediaLog; | |
27 class SeekableBuffer; | |
28 | |
29 // BufferedResourceLoader is single threaded and must be accessed on the | |
30 // render thread. It wraps a WebURLLoader and does in-memory buffering, | |
31 // pausing resource loading when the in-memory buffer is full and resuming | |
32 // resource loading when there is available capacity. | |
33 class MEDIA_BLINK_EXPORT BufferedResourceLoader | |
34 : NON_EXPORTED_BASE(public blink::WebURLLoaderClient) { | |
35 public: | |
36 // kNeverDefer - Aggresively buffer; never defer loading while paused. | |
37 // kReadThenDefer - Request only enough data to fulfill read requests. | |
38 // kCapacityDefer - Try to keep amount of buffered data at capacity. | |
39 enum DeferStrategy { | |
40 kNeverDefer, | |
41 kReadThenDefer, | |
42 kCapacityDefer, | |
43 }; | |
44 | |
45 // Status codes for start/read operations on BufferedResourceLoader. | |
46 enum Status { | |
47 // Everything went as planned. | |
48 kOk, | |
49 | |
50 // The operation failed, which may have been due to: | |
51 // - Page navigation | |
52 // - Server replied 4xx/5xx | |
53 // - The response was invalid | |
54 // - Connection was terminated | |
55 // | |
56 // At this point you should delete the loader. | |
57 kFailed, | |
58 | |
59 // The loader will never be able to satisfy the read request. Please stop, | |
60 // delete, create a new loader, and try again. | |
61 kCacheMiss, | |
62 }; | |
63 | |
64 // Keep in sync with WebMediaPlayer::CORSMode. | |
65 enum CORSMode { kUnspecified, kAnonymous, kUseCredentials }; | |
66 | |
67 enum LoadingState { | |
68 kLoading, // Actively attempting to download data. | |
69 kLoadingDeferred, // Loading intentionally deferred. | |
70 kLoadingFinished, // Loading finished normally; no more data will arrive. | |
71 kLoadingFailed, // Loading finished abnormally; no more data will arrive. | |
72 }; | |
73 | |
74 // |url| - URL for the resource to be loaded. | |
75 // |cors_mode| - HTML media element's crossorigin attribute. | |
76 // |first_byte_position| - First byte to start loading from, | |
77 // |kPositionNotSpecified| for not specified. | |
78 // |last_byte_position| - Last byte to be loaded, | |
79 // |kPositionNotSpecified| for not specified. | |
80 // |strategy| is the initial loading strategy to use. | |
81 // |bitrate| is the bitrate of the media, 0 if unknown. | |
82 // |playback_rate| is the current playback rate of the media. | |
83 BufferedResourceLoader(const GURL& url, | |
84 CORSMode cors_mode, | |
85 int64_t first_byte_position, | |
86 int64_t last_byte_position, | |
87 DeferStrategy strategy, | |
88 int bitrate, | |
89 double playback_rate, | |
90 MediaLog* media_log); | |
91 ~BufferedResourceLoader() override; | |
92 | |
93 // Start the resource loading with the specified URL and range. | |
94 // | |
95 // |loading_cb| is executed when the loading state has changed. | |
96 // |progress_cb| is executed when additional data has arrived. | |
97 typedef base::Callback<void(Status)> StartCB; | |
98 typedef base::Callback<void(LoadingState)> LoadingStateChangedCB; | |
99 typedef base::Callback<void(int64_t)> ProgressCB; | |
100 void Start(const StartCB& start_cb, | |
101 const LoadingStateChangedCB& loading_cb, | |
102 const ProgressCB& progress_cb, | |
103 blink::WebFrame* frame); | |
104 | |
105 // Stops everything associated with this loader, including active URL loads | |
106 // and pending callbacks. | |
107 // | |
108 // It is safe to delete a BufferedResourceLoader after calling Stop(). | |
109 void Stop(); | |
110 | |
111 // Copies |read_size| bytes from |position| into |buffer|, executing |read_cb| | |
112 // when the operation has completed. | |
113 // | |
114 // The callback will contain the number of bytes read iff the status is kOk, | |
115 // zero otherwise. | |
116 // | |
117 // If necessary will temporarily increase forward capacity of buffer to | |
118 // accomodate an unusually large read. | |
119 typedef base::Callback<void(Status, int)> ReadCB; | |
120 void Read(int64_t position, | |
121 int read_size, | |
122 uint8_t* buffer, | |
123 const ReadCB& read_cb); | |
124 | |
125 // Gets the content length in bytes of the instance after this loader has been | |
126 // started. If this value is |kPositionNotSpecified|, then content length is | |
127 // unknown. | |
128 int64_t content_length(); | |
129 | |
130 // Gets the original size of the file requested. If this value is | |
131 // |kPositionNotSpecified|, then the size is unknown. | |
132 int64_t instance_size(); | |
133 | |
134 // Returns true if the server supports byte range requests. | |
135 bool range_supported(); | |
136 | |
137 // blink::WebURLLoaderClient implementation. | |
138 void willFollowRedirect(blink::WebURLLoader* loader, | |
139 blink::WebURLRequest& newRequest, | |
140 const blink::WebURLResponse& redirectResponse, | |
141 int64_t encodedDataLength) override; | |
142 void didSendData( | |
143 blink::WebURLLoader* loader, | |
144 unsigned long long bytesSent, | |
145 unsigned long long totalBytesToBeSent) override; | |
146 void didReceiveResponse( | |
147 blink::WebURLLoader* loader, | |
148 const blink::WebURLResponse& response) override; | |
149 void didDownloadData( | |
150 blink::WebURLLoader* loader, | |
151 int data_length, | |
152 int encoded_data_length) override; | |
153 void didReceiveData(blink::WebURLLoader* loader, | |
154 const char* data, | |
155 int data_length, | |
156 int encoded_data_length, | |
157 int encoded_body_length) override; | |
158 void didReceiveCachedMetadata( | |
159 blink::WebURLLoader* loader, | |
160 const char* data, int dataLength) override; | |
161 void didFinishLoading(blink::WebURLLoader* loader, | |
162 double finishTime, | |
163 int64_t total_encoded_data_length) override; | |
164 void didFail( | |
165 blink::WebURLLoader* loader, | |
166 const blink::WebURLError&) override; | |
167 | |
168 // Returns true if the media resource has a single origin, false otherwise. | |
169 // Only valid to call after Start() has completed. | |
170 bool HasSingleOrigin() const; | |
171 | |
172 // Returns true if the media resource passed a CORS access control check. | |
173 // Only valid to call after Start() has completed. | |
174 bool DidPassCORSAccessCheck() const; | |
175 | |
176 // Sets the defer strategy to the given value unless it seems unwise. | |
177 // Specifically downgrade kNeverDefer to kCapacityDefer if we know the | |
178 // current response will not be used to satisfy future requests (the cache | |
179 // won't help us). | |
180 void UpdateDeferStrategy(DeferStrategy strategy); | |
181 | |
182 // Sets the playback rate to the given value and updates buffer window | |
183 // accordingly. | |
184 void SetPlaybackRate(double playback_rate); | |
185 | |
186 // Sets the bitrate to the given value and updates buffer window | |
187 // accordingly. | |
188 void SetBitrate(int bitrate); | |
189 | |
190 // Return the |first_byte_position| passed into the ctor. | |
191 int64_t first_byte_position() const; | |
192 | |
193 // Parse a Content-Range header into its component pieces and return true if | |
194 // each of the expected elements was found & parsed correctly. | |
195 // |*instance_size| may be set to kPositionNotSpecified if the range ends in | |
196 // "/*". | |
197 // NOTE: only public for testing! This is an implementation detail of | |
198 // VerifyPartialResponse (a private method). | |
199 static bool ParseContentRange(const std::string& content_range_str, | |
200 int64_t* first_byte_position, | |
201 int64_t* last_byte_position, | |
202 int64_t* instance_size); | |
203 | |
204 // Cancels and closes any outstanding deferred ActiveLoader instances. Does | |
205 // not report a failed state, so subsequent read calls to cache may still | |
206 // complete okay. If the ActiveLoader is not deferred it will be canceled once | |
207 // it is unless playback starts before then (as determined by the reported | |
208 // playback rate). | |
209 void CancelUponDeferral(); | |
210 | |
211 // Returns the original URL of the response. If the request is redirected to | |
212 // another URL it is the URL after redirected. If the response is generated in | |
213 // a Service Worker it is empty. | |
214 const GURL& response_original_url() const { return response_original_url_; } | |
215 | |
216 // Returns an estimate of the amount of memory owned by the resource loader. | |
217 int64_t GetMemoryUsage() const; | |
218 | |
219 private: | |
220 friend class BufferedDataSourceTest; | |
221 friend class BufferedResourceLoaderTest; | |
222 friend class MockBufferedDataSource; | |
223 | |
224 // Updates the |buffer_|'s forward and backward capacities. | |
225 void UpdateBufferWindow(); | |
226 | |
227 // Updates deferring behavior based on current buffering scheme. | |
228 void UpdateDeferBehavior(); | |
229 | |
230 // Sets |active_loader_|'s defer state and fires |loading_cb_| if the state | |
231 // changed. | |
232 void SetDeferred(bool deferred); | |
233 | |
234 // Returns true if we should defer resource loading based on the current | |
235 // buffering scheme. | |
236 bool ShouldDefer() const; | |
237 | |
238 // Returns true if the current read request can be fulfilled by what is in | |
239 // the buffer. | |
240 bool CanFulfillRead() const; | |
241 | |
242 // Returns true if the current read request will be fulfilled in the future. | |
243 bool WillFulfillRead() const; | |
244 | |
245 // Method that does the actual read and calls the |read_cb_|, assuming the | |
246 // request range is in |buffer_|. | |
247 void ReadInternal(); | |
248 | |
249 // If we have made a range request, verify the response from the server. | |
250 bool VerifyPartialResponse(const blink::WebURLResponse& response); | |
251 | |
252 // Done with read. Invokes the read callback and reset parameters for the | |
253 // read request. | |
254 void DoneRead(Status status, int bytes_read); | |
255 | |
256 // Done with start. Invokes the start callback and reset it. | |
257 void DoneStart(Status status); | |
258 | |
259 bool HasPendingRead() { return !read_cb_.is_null(); } | |
260 | |
261 // Helper function that returns true if a range request was specified. | |
262 bool IsRangeRequest() const; | |
263 | |
264 // Log everything interesting to |media_log_|. | |
265 void Log(); | |
266 | |
267 // A sliding window of buffer. | |
268 SeekableBuffer buffer_; | |
269 | |
270 // Keeps track of an active WebURLLoader and associated state. | |
271 std::unique_ptr<ActiveLoader> active_loader_; | |
272 | |
273 // Tracks if |active_loader_| failed. If so, then all calls to Read() will | |
274 // fail. | |
275 bool loader_failed_; | |
276 | |
277 // Current buffering algorithm in place for resource loading. | |
278 DeferStrategy defer_strategy_; | |
279 | |
280 // True if the currently-reading response might be used to satisfy a future | |
281 // request from the cache. | |
282 bool might_be_reused_from_cache_in_future_; | |
283 | |
284 // True if Range header is supported. | |
285 bool range_supported_; | |
286 | |
287 // Forward capacity to reset to after an extension. | |
288 int saved_forward_capacity_; | |
289 | |
290 GURL url_; | |
291 CORSMode cors_mode_; | |
292 const int64_t first_byte_position_; | |
293 const int64_t last_byte_position_; | |
294 bool single_origin_; | |
295 | |
296 // Executed whenever the state of resource loading has changed. | |
297 LoadingStateChangedCB loading_cb_; | |
298 | |
299 // Executed whenever additional data has been downloaded and reports the | |
300 // zero-indexed file offset of the furthest buffered byte. | |
301 ProgressCB progress_cb_; | |
302 | |
303 // Members used during request start. | |
304 StartCB start_cb_; | |
305 int64_t offset_; | |
306 int64_t content_length_; | |
307 int64_t instance_size_; | |
308 | |
309 // Members used during a read operation. They should be reset after each | |
310 // read has completed or failed. | |
311 ReadCB read_cb_; | |
312 int64_t read_position_; | |
313 int read_size_; | |
314 uint8_t* read_buffer_; | |
315 | |
316 // Offsets of the requested first byte and last byte in |buffer_|. They are | |
317 // written by Read(). | |
318 int first_offset_; | |
319 int last_offset_; | |
320 | |
321 // Injected WebURLLoader instance for testing purposes. | |
322 std::unique_ptr<blink::WebURLLoader> test_loader_; | |
323 | |
324 // Bitrate of the media. Set to 0 if unknown. | |
325 int bitrate_; | |
326 | |
327 // Playback rate of the media. | |
328 double playback_rate_; | |
329 | |
330 GURL response_original_url_; | |
331 | |
332 scoped_refptr<MediaLog> media_log_; | |
333 | |
334 bool cancel_upon_deferral_; | |
335 | |
336 DISALLOW_COPY_AND_ASSIGN(BufferedResourceLoader); | |
337 }; | |
338 | |
339 } // namespace media | |
340 | |
341 #endif // MEDIA_BLINK_BUFFERED_RESOURCE_LOADER_H_ | |
OLD | NEW |