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(double 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
);
201 // Cancels and closes any outstanding deferred ActiveLoader instances. Does
202 // not report a failed state, so subsequent read calls to cache may still
203 // complete okay. If the ActiveLoader is not deferred it will be canceled once
204 // it is unless playback starts before then (as determined by the reported
206 void CancelUponDeferral();
209 friend class BufferedDataSourceTest
;
210 friend class BufferedResourceLoaderTest
;
211 friend class MockBufferedDataSource
;
213 // Updates the |buffer_|'s forward and backward capacities.
214 void UpdateBufferWindow();
216 // Updates deferring behavior based on current buffering scheme.
217 void UpdateDeferBehavior();
219 // Sets |active_loader_|'s defer state and fires |loading_cb_| if the state
221 void SetDeferred(bool deferred
);
223 // Returns true if we should defer resource loading based on the current
225 bool ShouldDefer() const;
227 // Returns true if the current read request can be fulfilled by what is in
229 bool CanFulfillRead() const;
231 // Returns true if the current read request will be fulfilled in the future.
232 bool WillFulfillRead() const;
234 // Method that does the actual read and calls the |read_cb_|, assuming the
235 // request range is in |buffer_|.
238 // If we have made a range request, verify the response from the server.
239 bool VerifyPartialResponse(const blink::WebURLResponse
& response
);
241 // Done with read. Invokes the read callback and reset parameters for the
243 void DoneRead(Status status
, int bytes_read
);
245 // Done with start. Invokes the start callback and reset it.
246 void DoneStart(Status status
);
248 bool HasPendingRead() { return !read_cb_
.is_null(); }
250 // Helper function that returns true if a range request was specified.
251 bool IsRangeRequest() const;
253 // Log everything interesting to |media_log_|.
256 // A sliding window of buffer.
257 SeekableBuffer buffer_
;
259 // Keeps track of an active WebURLLoader and associated state.
260 scoped_ptr
<ActiveLoader
> active_loader_
;
262 // Tracks if |active_loader_| failed. If so, then all calls to Read() will
266 // Current buffering algorithm in place for resource loading.
267 DeferStrategy defer_strategy_
;
269 // True if the currently-reading response might be used to satisfy a future
270 // request from the cache.
271 bool might_be_reused_from_cache_in_future_
;
273 // True if Range header is supported.
274 bool range_supported_
;
276 // Forward capacity to reset to after an extension.
277 int saved_forward_capacity_
;
281 const int64 first_byte_position_
;
282 const int64 last_byte_position_
;
285 // Executed whenever the state of resource loading has changed.
286 LoadingStateChangedCB loading_cb_
;
288 // Executed whenever additional data has been downloaded and reports the
289 // zero-indexed file offset of the furthest buffered byte.
290 ProgressCB progress_cb_
;
292 // Members used during request start.
295 int64 content_length_
;
296 int64 instance_size_
;
298 // Members used during a read operation. They should be reset after each
299 // read has completed or failed.
301 int64 read_position_
;
305 // Offsets of the requested first byte and last byte in |buffer_|. They are
306 // written by Read().
310 // Injected WebURLLoader instance for testing purposes.
311 scoped_ptr
<blink::WebURLLoader
> test_loader_
;
313 // Bitrate of the media. Set to 0 if unknown.
316 // Playback rate of the media.
317 double playback_rate_
;
319 scoped_refptr
<MediaLog
> media_log_
;
321 bool cancel_upon_deferral_
;
323 DISALLOW_COPY_AND_ASSIGN(BufferedResourceLoader
);
328 #endif // MEDIA_BLINK_BUFFERED_RESOURCE_LOADER_H_