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