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.
5 #ifndef MEDIA_BLINK_BUFFERED_RESOURCE_LOADER_H_
6 #define MEDIA_BLINK_BUFFERED_RESOURCE_LOADER_H_
10 #include "base/callback.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "media/base/media_export.h"
13 #include "media/base/seekable_buffer.h"
14 #include "media/blink/active_loader.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"
25 const int64 kPositionNotSpecified
= -1;
27 // BufferedResourceLoader is single threaded and must be accessed on the
28 // render thread. It wraps a WebURLLoader and does in-memory buffering,
29 // pausing resource loading when the in-memory buffer is full and resuming
30 // resource loading when there is available capacity.
31 class MEDIA_EXPORT BufferedResourceLoader
32 : NON_EXPORTED_BASE(public blink::WebURLLoaderClient
) {
34 // kNeverDefer - Aggresively buffer; never defer loading while paused.
35 // kReadThenDefer - Request only enough data to fulfill read requests.
36 // kCapacityDefer - Try to keep amount of buffered data at capacity.
43 // Status codes for start/read operations on BufferedResourceLoader.
45 // Everything went as planned.
48 // The operation failed, which may have been due to:
50 // - Server replied 4xx/5xx
51 // - The response was invalid
52 // - Connection was terminated
54 // At this point you should delete the loader.
57 // The loader will never be able to satisfy the read request. Please stop,
58 // delete, create a new loader, and try again.
62 // Keep in sync with WebMediaPlayer::CORSMode.
63 enum CORSMode
{ kUnspecified
, kAnonymous
, kUseCredentials
};
66 kLoading
, // Actively attempting to download data.
67 kLoadingDeferred
, // Loading intentionally deferred.
68 kLoadingFinished
, // Loading finished normally; no more data will arrive.
69 kLoadingFailed
, // Loading finished abnormally; no more data will arrive.
72 // |url| - URL for the resource to be loaded.
73 // |cors_mode| - HTML media element's crossorigin attribute.
74 // |first_byte_position| - First byte to start loading from,
75 // |kPositionNotSpecified| for not specified.
76 // |last_byte_position| - Last byte to be loaded,
77 // |kPositionNotSpecified| for not specified.
78 // |strategy| is the initial loading strategy to use.
79 // |bitrate| is the bitrate of the media, 0 if unknown.
80 // |playback_rate| is the current playback rate of the media.
81 BufferedResourceLoader(
84 int64 first_byte_position
,
85 int64 last_byte_position
,
86 DeferStrategy strategy
,
90 virtual ~BufferedResourceLoader();
92 // Start the resource loading with the specified URL and range.
94 // |loading_cb| is executed when the loading state has changed.
95 // |progress_cb| is executed when additional data has arrived.
96 typedef base::Callback
<void(Status
)> StartCB
;
97 typedef base::Callback
<void(LoadingState
)> LoadingStateChangedCB
;
98 typedef base::Callback
<void(int64
)> ProgressCB
;
99 void Start(const StartCB
& start_cb
,
100 const LoadingStateChangedCB
& loading_cb
,
101 const ProgressCB
& progress_cb
,
102 blink::WebFrame
* frame
);
104 // Stops everything associated with this loader, including active URL loads
105 // and pending callbacks.
107 // It is safe to delete a BufferedResourceLoader after calling Stop().
110 // Copies |read_size| bytes from |position| into |buffer|, executing |read_cb|
111 // when the operation has completed.
113 // The callback will contain the number of bytes read iff the status is kOk,
116 // If necessary will temporarily increase forward capacity of buffer to
117 // accomodate an unusually large read.
118 typedef base::Callback
<void(Status
, int)> ReadCB
;
119 void Read(int64 position
, int read_size
,
120 uint8
* buffer
, const ReadCB
& read_cb
);
122 // Gets the content length in bytes of the instance after this loader has been
123 // started. If this value is |kPositionNotSpecified|, then content length is
125 int64
content_length();
127 // Gets the original size of the file requested. If this value is
128 // |kPositionNotSpecified|, then the size is unknown.
129 int64
instance_size();
131 // Returns true if the server supports byte range requests.
132 bool range_supported();
134 // blink::WebURLLoaderClient implementation.
135 virtual void willSendRequest(
136 blink::WebURLLoader
* loader
,
137 blink::WebURLRequest
& newRequest
,
138 const blink::WebURLResponse
& redirectResponse
);
139 virtual void didSendData(
140 blink::WebURLLoader
* loader
,
141 unsigned long long bytesSent
,
142 unsigned long long totalBytesToBeSent
);
143 virtual void didReceiveResponse(
144 blink::WebURLLoader
* loader
,
145 const blink::WebURLResponse
& response
);
146 virtual void didDownloadData(
147 blink::WebURLLoader
* loader
,
149 int encoded_data_length
);
150 virtual void didReceiveData(
151 blink::WebURLLoader
* loader
,
154 int encoded_data_length
);
155 virtual void didReceiveCachedMetadata(
156 blink::WebURLLoader
* loader
,
157 const char* data
, int dataLength
);
158 virtual void didFinishLoading(
159 blink::WebURLLoader
* loader
,
161 int64_t total_encoded_data_length
);
162 virtual void didFail(
163 blink::WebURLLoader
* loader
,
164 const blink::WebURLError
&);
166 // Returns true if the media resource has a single origin, false otherwise.
167 // Only valid to call after Start() has completed.
168 bool HasSingleOrigin() const;
170 // Returns true if the media resource passed a CORS access control check.
171 // Only valid to call after Start() has completed.
172 bool DidPassCORSAccessCheck() const;
174 // Sets the defer strategy to the given value unless it seems unwise.
175 // Specifically downgrade kNeverDefer to kCapacityDefer if we know the
176 // current response will not be used to satisfy future requests (the cache
178 void UpdateDeferStrategy(DeferStrategy strategy
);
180 // Sets the playback rate to the given value and updates buffer window
182 void SetPlaybackRate(float playback_rate
);
184 // Sets the bitrate to the given value and updates buffer window
186 void SetBitrate(int bitrate
);
188 // Return the |first_byte_position| passed into the ctor.
189 int64
first_byte_position() const;
191 // Parse a Content-Range header into its component pieces and return true if
192 // each of the expected elements was found & parsed correctly.
193 // |*instance_size| may be set to kPositionNotSpecified if the range ends in
195 // NOTE: only public for testing! This is an implementation detail of
196 // VerifyPartialResponse (a private method).
197 static bool ParseContentRange(
198 const std::string
& content_range_str
, int64
* first_byte_position
,
199 int64
* last_byte_position
, int64
* instance_size
);
202 friend class BufferedDataSourceTest
;
203 friend class BufferedResourceLoaderTest
;
204 friend class MockBufferedDataSource
;
206 // Updates the |buffer_|'s forward and backward capacities.
207 void UpdateBufferWindow();
209 // Updates deferring behavior based on current buffering scheme.
210 void UpdateDeferBehavior();
212 // Sets |active_loader_|'s defer state and fires |loading_cb_| if the state
214 void SetDeferred(bool deferred
);
216 // Returns true if we should defer resource loading based on the current
218 bool ShouldDefer() const;
220 // Returns true if the current read request can be fulfilled by what is in
222 bool CanFulfillRead() const;
224 // Returns true if the current read request will be fulfilled in the future.
225 bool WillFulfillRead() const;
227 // Method that does the actual read and calls the |read_cb_|, assuming the
228 // request range is in |buffer_|.
231 // If we have made a range request, verify the response from the server.
232 bool VerifyPartialResponse(const blink::WebURLResponse
& response
);
234 // Done with read. Invokes the read callback and reset parameters for the
236 void DoneRead(Status status
, int bytes_read
);
238 // Done with start. Invokes the start callback and reset it.
239 void DoneStart(Status status
);
241 bool HasPendingRead() { return !read_cb_
.is_null(); }
243 // Helper function that returns true if a range request was specified.
244 bool IsRangeRequest() const;
246 // Log everything interesting to |media_log_|.
249 // A sliding window of buffer.
250 SeekableBuffer buffer_
;
252 // Keeps track of an active WebURLLoader and associated state.
253 scoped_ptr
<ActiveLoader
> active_loader_
;
255 // Tracks if |active_loader_| failed. If so, then all calls to Read() will
259 // Current buffering algorithm in place for resource loading.
260 DeferStrategy defer_strategy_
;
262 // True if the currently-reading response might be used to satisfy a future
263 // request from the cache.
264 bool might_be_reused_from_cache_in_future_
;
266 // True if Range header is supported.
267 bool range_supported_
;
269 // Forward capacity to reset to after an extension.
270 int saved_forward_capacity_
;
274 const int64 first_byte_position_
;
275 const int64 last_byte_position_
;
278 // Executed whenever the state of resource loading has changed.
279 LoadingStateChangedCB loading_cb_
;
281 // Executed whenever additional data has been downloaded and reports the
282 // zero-indexed file offset of the furthest buffered byte.
283 ProgressCB progress_cb_
;
285 // Members used during request start.
288 int64 content_length_
;
289 int64 instance_size_
;
291 // Members used during a read operation. They should be reset after each
292 // read has completed or failed.
294 int64 read_position_
;
298 // Offsets of the requested first byte and last byte in |buffer_|. They are
299 // written by Read().
303 // Injected WebURLLoader instance for testing purposes.
304 scoped_ptr
<blink::WebURLLoader
> test_loader_
;
306 // Bitrate of the media. Set to 0 if unknown.
309 // Playback rate of the media.
310 float playback_rate_
;
312 scoped_refptr
<MediaLog
> media_log_
;
314 DISALLOW_COPY_AND_ASSIGN(BufferedResourceLoader
);
319 #endif // MEDIA_BLINK_BUFFERED_RESOURCE_LOADER_H_