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 #include "media/blink/buffered_data_source.h"
8 #include "base/callback_helpers.h"
9 #include "base/location.h"
10 #include "base/single_thread_task_runner.h"
11 #include "media/base/media_log.h"
12 #include "net/base/net_errors.h"
14 using blink::WebFrame
;
18 // BufferedDataSource has an intermediate buffer, this value governs the initial
19 // size of that buffer. It is set to 32KB because this is a typical read size
21 const int kInitialReadBufferSize
= 32768;
23 // Number of cache misses or read failures we allow for a single Read() before
24 // signaling an error.
25 const int kLoaderRetries
= 3;
27 // The number of milliseconds to wait before retrying a failed load.
28 const int kLoaderFailedRetryDelayMs
= 250;
34 class BufferedDataSource::ReadOperation
{
36 ReadOperation(int64 position
, int size
, uint8
* data
,
37 const DataSource::ReadCB
& callback
);
40 // Runs |callback_| with the given |result|, deleting the operation
42 static void Run(scoped_ptr
<ReadOperation
> read_op
, int result
);
44 // State for the number of times this read operation has been retried.
45 int retries() { return retries_
; }
46 void IncrementRetries() { ++retries_
; }
48 int64
position() { return position_
; }
49 int size() { return size_
; }
50 uint8
* data() { return data_
; }
55 const int64 position_
;
58 DataSource::ReadCB callback_
;
60 DISALLOW_IMPLICIT_CONSTRUCTORS(ReadOperation
);
63 BufferedDataSource::ReadOperation::ReadOperation(
64 int64 position
, int size
, uint8
* data
,
65 const DataSource::ReadCB
& callback
)
71 DCHECK(!callback_
.is_null());
74 BufferedDataSource::ReadOperation::~ReadOperation() {
75 DCHECK(callback_
.is_null());
79 void BufferedDataSource::ReadOperation::Run(
80 scoped_ptr
<ReadOperation
> read_op
, int result
) {
81 base::ResetAndReturn(&read_op
->callback_
).Run(result
);
84 BufferedDataSource::BufferedDataSource(
86 BufferedResourceLoader::CORSMode cors_mode
,
87 const scoped_refptr
<base::SingleThreadTaskRunner
>& task_runner
,
90 BufferedDataSourceHost
* host
,
91 const DownloadingCB
& downloading_cb
)
93 cors_mode_(cors_mode
),
94 total_bytes_(kPositionNotSpecified
),
97 intermediate_read_buffer_(kInitialReadBufferSize
),
98 render_task_runner_(task_runner
),
99 stop_signal_received_(false),
100 media_has_played_(false),
104 media_log_(media_log
),
106 downloading_cb_(downloading_cb
),
107 weak_factory_(this) {
108 weak_ptr_
= weak_factory_
.GetWeakPtr();
110 DCHECK(!downloading_cb_
.is_null());
111 DCHECK(render_task_runner_
->BelongsToCurrentThread());
114 BufferedDataSource::~BufferedDataSource() {
115 DCHECK(render_task_runner_
->BelongsToCurrentThread());
118 // A factory method to create BufferedResourceLoader using the read parameters.
119 // This method can be overridden to inject mock BufferedResourceLoader object
120 // for testing purpose.
121 BufferedResourceLoader
* BufferedDataSource::CreateResourceLoader(
122 int64 first_byte_position
, int64 last_byte_position
) {
123 DCHECK(render_task_runner_
->BelongsToCurrentThread());
125 BufferedResourceLoader::DeferStrategy strategy
= preload_
== METADATA
?
126 BufferedResourceLoader::kReadThenDefer
:
127 BufferedResourceLoader::kCapacityDefer
;
129 return new BufferedResourceLoader(url_
,
139 void BufferedDataSource::Initialize(const InitializeCB
& init_cb
) {
140 DCHECK(render_task_runner_
->BelongsToCurrentThread());
141 DCHECK(!init_cb
.is_null());
142 DCHECK(!loader_
.get());
146 if (url_
.SchemeIsHTTPOrHTTPS()) {
147 // Do an unbounded range request starting at the beginning. If the server
148 // responds with 200 instead of 206 we'll fall back into a streaming mode.
149 loader_
.reset(CreateResourceLoader(0, kPositionNotSpecified
));
151 // For all other protocols, assume they support range request. We fetch
152 // the full range of the resource to obtain the instance size because
153 // we won't be served HTTP headers.
154 loader_
.reset(CreateResourceLoader(kPositionNotSpecified
,
155 kPositionNotSpecified
));
158 base::WeakPtr
<BufferedDataSource
> weak_this
= weak_factory_
.GetWeakPtr();
160 base::Bind(&BufferedDataSource::StartCallback
, weak_this
),
161 base::Bind(&BufferedDataSource::LoadingStateChangedCallback
, weak_this
),
162 base::Bind(&BufferedDataSource::ProgressCallback
, weak_this
),
166 void BufferedDataSource::SetPreload(Preload preload
) {
167 DCHECK(render_task_runner_
->BelongsToCurrentThread());
171 bool BufferedDataSource::HasSingleOrigin() {
172 DCHECK(render_task_runner_
->BelongsToCurrentThread());
173 DCHECK(init_cb_
.is_null() && loader_
.get())
174 << "Initialize() must complete before calling HasSingleOrigin()";
175 return loader_
->HasSingleOrigin();
178 bool BufferedDataSource::DidPassCORSAccessCheck() const {
179 return loader_
.get() && loader_
->DidPassCORSAccessCheck();
182 void BufferedDataSource::Abort() {
183 DCHECK(render_task_runner_
->BelongsToCurrentThread());
185 base::AutoLock
auto_lock(lock_
);
186 StopInternal_Locked();
192 void BufferedDataSource::MediaPlaybackRateChanged(float playback_rate
) {
193 DCHECK(render_task_runner_
->BelongsToCurrentThread());
194 DCHECK(loader_
.get());
196 if (playback_rate
< 0.0f
)
199 playback_rate_
= playback_rate
;
200 loader_
->SetPlaybackRate(playback_rate
);
203 void BufferedDataSource::MediaIsPlaying() {
204 DCHECK(render_task_runner_
->BelongsToCurrentThread());
205 media_has_played_
= true;
206 UpdateDeferStrategy(false);
209 void BufferedDataSource::MediaIsPaused() {
210 DCHECK(render_task_runner_
->BelongsToCurrentThread());
211 UpdateDeferStrategy(true);
214 /////////////////////////////////////////////////////////////////////////////
215 // DataSource implementation.
216 void BufferedDataSource::Stop() {
218 base::AutoLock
auto_lock(lock_
);
219 StopInternal_Locked();
222 render_task_runner_
->PostTask(
224 base::Bind(&BufferedDataSource::StopLoader
, weak_factory_
.GetWeakPtr()));
227 void BufferedDataSource::SetBitrate(int bitrate
) {
228 render_task_runner_
->PostTask(FROM_HERE
,
229 base::Bind(&BufferedDataSource::SetBitrateTask
,
230 weak_factory_
.GetWeakPtr(),
234 void BufferedDataSource::Read(
235 int64 position
, int size
, uint8
* data
,
236 const DataSource::ReadCB
& read_cb
) {
237 DVLOG(1) << "Read: " << position
<< " offset, " << size
<< " bytes";
238 DCHECK(!read_cb
.is_null());
241 base::AutoLock
auto_lock(lock_
);
244 if (stop_signal_received_
) {
245 read_cb
.Run(kReadError
);
249 read_op_
.reset(new ReadOperation(position
, size
, data
, read_cb
));
252 render_task_runner_
->PostTask(
254 base::Bind(&BufferedDataSource::ReadTask
, weak_factory_
.GetWeakPtr()));
257 bool BufferedDataSource::GetSize(int64
* size_out
) {
258 if (total_bytes_
!= kPositionNotSpecified
) {
259 *size_out
= total_bytes_
;
266 bool BufferedDataSource::IsStreaming() {
270 /////////////////////////////////////////////////////////////////////////////
271 // Render thread tasks.
272 void BufferedDataSource::ReadTask() {
273 DCHECK(render_task_runner_
->BelongsToCurrentThread());
277 void BufferedDataSource::StopInternal_Locked() {
278 lock_
.AssertAcquired();
279 if (stop_signal_received_
)
282 stop_signal_received_
= true;
284 // Initialize() isn't part of the DataSource interface so don't call it in
285 // response to Stop().
289 ReadOperation::Run(read_op_
.Pass(), kReadError
);
292 void BufferedDataSource::StopLoader() {
293 DCHECK(render_task_runner_
->BelongsToCurrentThread());
299 void BufferedDataSource::SetBitrateTask(int bitrate
) {
300 DCHECK(render_task_runner_
->BelongsToCurrentThread());
301 DCHECK(loader_
.get());
304 loader_
->SetBitrate(bitrate
);
307 // This method is the place where actual read happens, |loader_| must be valid
308 // prior to make this method call.
309 void BufferedDataSource::ReadInternal() {
310 DCHECK(render_task_runner_
->BelongsToCurrentThread());
314 base::AutoLock
auto_lock(lock_
);
315 if (stop_signal_received_
)
318 position
= read_op_
->position();
319 size
= read_op_
->size();
322 // First we prepare the intermediate read buffer for BufferedResourceLoader
324 if (static_cast<int>(intermediate_read_buffer_
.size()) < size
)
325 intermediate_read_buffer_
.resize(size
);
327 // Perform the actual read with BufferedResourceLoader.
328 DCHECK(!intermediate_read_buffer_
.empty());
329 loader_
->Read(position
,
331 &intermediate_read_buffer_
[0],
332 base::Bind(&BufferedDataSource::ReadCallback
,
333 weak_factory_
.GetWeakPtr()));
337 /////////////////////////////////////////////////////////////////////////////
338 // BufferedResourceLoader callback methods.
339 void BufferedDataSource::StartCallback(
340 BufferedResourceLoader::Status status
) {
341 DCHECK(render_task_runner_
->BelongsToCurrentThread());
342 DCHECK(loader_
.get());
344 bool init_cb_is_null
= false;
346 base::AutoLock
auto_lock(lock_
);
347 init_cb_is_null
= init_cb_
.is_null();
349 if (init_cb_is_null
) {
354 // All responses must be successful. Resources that are assumed to be fully
355 // buffered must have a known content length.
356 bool success
= status
== BufferedResourceLoader::kOk
&&
357 (!assume_fully_buffered() ||
358 loader_
->instance_size() != kPositionNotSpecified
);
361 total_bytes_
= loader_
->instance_size();
363 !assume_fully_buffered() &&
364 (total_bytes_
== kPositionNotSpecified
|| !loader_
->range_supported());
366 media_log_
->SetDoubleProperty("total_bytes",
367 static_cast<double>(total_bytes_
));
368 media_log_
->SetBooleanProperty("streaming", streaming_
);
373 // TODO(scherkus): we shouldn't have to lock to signal host(), see
374 // http://crbug.com/113712 for details.
375 base::AutoLock
auto_lock(lock_
);
376 if (stop_signal_received_
)
380 if (total_bytes_
!= kPositionNotSpecified
) {
381 host_
->SetTotalBytes(total_bytes_
);
382 if (assume_fully_buffered())
383 host_
->AddBufferedByteRange(0, total_bytes_
);
386 media_log_
->SetBooleanProperty("single_origin", loader_
->HasSingleOrigin());
387 media_log_
->SetBooleanProperty("passed_cors_access_check",
388 loader_
->DidPassCORSAccessCheck());
389 media_log_
->SetBooleanProperty("range_header_supported",
390 loader_
->range_supported());
393 base::ResetAndReturn(&init_cb_
).Run(success
);
396 void BufferedDataSource::PartialReadStartCallback(
397 BufferedResourceLoader::Status status
) {
398 DCHECK(render_task_runner_
->BelongsToCurrentThread());
399 DCHECK(loader_
.get());
401 if (status
== BufferedResourceLoader::kOk
) {
402 // Once the request has started successfully, we can proceed with
408 // Stop the resource loader since we have received an error.
411 // TODO(scherkus): we shouldn't have to lock to signal host(), see
412 // http://crbug.com/113712 for details.
413 base::AutoLock
auto_lock(lock_
);
414 if (stop_signal_received_
)
416 ReadOperation::Run(read_op_
.Pass(), kReadError
);
419 void BufferedDataSource::ReadCallback(
420 BufferedResourceLoader::Status status
,
422 DCHECK(render_task_runner_
->BelongsToCurrentThread());
424 // TODO(scherkus): we shouldn't have to lock to signal host(), see
425 // http://crbug.com/113712 for details.
426 base::AutoLock
auto_lock(lock_
);
427 if (stop_signal_received_
)
430 if (status
!= BufferedResourceLoader::kOk
) {
431 // Stop the resource load if it failed.
434 if (read_op_
->retries() < kLoaderRetries
) {
435 // Allow some resiliency against sporadic network failures or intentional
436 // cancellations due to a system suspend / resume. Here we treat failed
437 // reads as a cache miss so long as we haven't exceeded max retries.
438 if (status
== BufferedResourceLoader::kFailed
) {
439 render_task_runner_
->PostDelayedTask(
440 FROM_HERE
, base::Bind(&BufferedDataSource::ReadCallback
,
441 weak_factory_
.GetWeakPtr(),
442 BufferedResourceLoader::kCacheMiss
, 0),
443 base::TimeDelta::FromMilliseconds(kLoaderFailedRetryDelayMs
));
447 read_op_
->IncrementRetries();
449 // Recreate a loader starting from where we last left off until the
450 // end of the resource.
451 loader_
.reset(CreateResourceLoader(
452 read_op_
->position(), kPositionNotSpecified
));
454 base::WeakPtr
<BufferedDataSource
> weak_this
= weak_factory_
.GetWeakPtr();
456 base::Bind(&BufferedDataSource::PartialReadStartCallback
, weak_this
),
457 base::Bind(&BufferedDataSource::LoadingStateChangedCallback
,
459 base::Bind(&BufferedDataSource::ProgressCallback
, weak_this
),
464 ReadOperation::Run(read_op_
.Pass(), kReadError
);
468 if (bytes_read
> 0) {
469 DCHECK(!intermediate_read_buffer_
.empty());
470 memcpy(read_op_
->data(), &intermediate_read_buffer_
[0], bytes_read
);
471 } else if (bytes_read
== 0 && total_bytes_
== kPositionNotSpecified
) {
472 // We've reached the end of the file and we didn't know the total size
473 // before. Update the total size so Read()s past the end of the file will
474 // fail like they would if we had known the file size at the beginning.
475 total_bytes_
= loader_
->instance_size();
477 if (total_bytes_
!= kPositionNotSpecified
) {
478 host_
->SetTotalBytes(total_bytes_
);
479 host_
->AddBufferedByteRange(loader_
->first_byte_position(),
483 ReadOperation::Run(read_op_
.Pass(), bytes_read
);
486 void BufferedDataSource::LoadingStateChangedCallback(
487 BufferedResourceLoader::LoadingState state
) {
488 DCHECK(render_task_runner_
->BelongsToCurrentThread());
490 if (assume_fully_buffered())
493 bool is_downloading_data
;
495 case BufferedResourceLoader::kLoading
:
496 is_downloading_data
= true;
498 case BufferedResourceLoader::kLoadingDeferred
:
499 case BufferedResourceLoader::kLoadingFinished
:
500 is_downloading_data
= false;
503 // TODO(scherkus): we don't signal network activity changes when loads
504 // fail to preserve existing behaviour when deferring is toggled, however
505 // we should consider changing DownloadingCB to also propagate loading
506 // state. For example there isn't any signal today to notify the client that
507 // loading has failed (we only get errors on subsequent reads).
508 case BufferedResourceLoader::kLoadingFailed
:
512 downloading_cb_
.Run(is_downloading_data
);
515 void BufferedDataSource::ProgressCallback(int64 position
) {
516 DCHECK(render_task_runner_
->BelongsToCurrentThread());
518 if (assume_fully_buffered())
521 // TODO(scherkus): we shouldn't have to lock to signal host(), see
522 // http://crbug.com/113712 for details.
523 base::AutoLock
auto_lock(lock_
);
524 if (stop_signal_received_
)
527 host_
->AddBufferedByteRange(loader_
->first_byte_position(), position
);
530 void BufferedDataSource::UpdateDeferStrategy(bool paused
) {
531 // No need to aggressively buffer when we are assuming the resource is fully
533 if (assume_fully_buffered()) {
534 loader_
->UpdateDeferStrategy(BufferedResourceLoader::kCapacityDefer
);
538 // If the playback has started (at which point the preload value is ignored)
539 // and we're paused, then try to load as much as possible (the loader will
540 // fall back to kCapacityDefer if it knows the current response won't be
541 // useful from the cache in the future).
542 if (media_has_played_
&& paused
&& loader_
->range_supported()) {
543 loader_
->UpdateDeferStrategy(BufferedResourceLoader::kNeverDefer
);
547 // If media is currently playing or the page indicated preload=auto or the
548 // the server does not support the byte range request or we do not want to go
549 // too far ahead of the read head, use threshold strategy to enable/disable
550 // deferring when the buffer is full/depleted.
551 loader_
->UpdateDeferStrategy(BufferedResourceLoader::kCapacityDefer
);