OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011 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 #include "webkit/glue/media/buffered_resource_loader.h" | |
6 | |
7 #include "base/format_macros.h" | |
8 #include "base/stringprintf.h" | |
9 #include "base/string_util.h" | |
10 #include "media/base/media_log.h" | |
11 #include "net/base/net_errors.h" | |
12 #include "net/http/http_request_headers.h" | |
13 #include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" | |
14 #include "third_party/WebKit/Source/WebKit/chromium/public/WebKitPlatformSupport
.h" | |
15 #include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h" | |
16 #include "third_party/WebKit/Source/WebKit/chromium/public/WebURLError.h" | |
17 #include "third_party/WebKit/Source/WebKit/chromium/public/WebURLLoaderOptions.h
" | |
18 #include "webkit/glue/multipart_response_delegate.h" | |
19 #include "webkit/glue/webkit_glue.h" | |
20 | |
21 using WebKit::WebFrame; | |
22 using WebKit::WebString; | |
23 using WebKit::WebURLError; | |
24 using WebKit::WebURLLoader; | |
25 using WebKit::WebURLLoaderOptions; | |
26 using WebKit::WebURLRequest; | |
27 using WebKit::WebURLResponse; | |
28 using webkit_glue::MultipartResponseDelegate; | |
29 | |
30 namespace webkit_glue { | |
31 | |
32 static const int kHttpOK = 200; | |
33 static const int kHttpPartialContent = 206; | |
34 | |
35 // Define the number of bytes in a megabyte. | |
36 static const size_t kMegabyte = 1024 * 1024; | |
37 | |
38 // Minimum capacity of the buffer in forward or backward direction. | |
39 // | |
40 // 2MB is an arbitrary limit; it just seems to be "good enough" in practice. | |
41 static const size_t kMinBufferCapacity = 2 * kMegabyte; | |
42 | |
43 // Maximum capacity of the buffer in forward or backward direction. This is | |
44 // effectively the largest single read the code path can handle. | |
45 // 20MB is an arbitrary limit; it just seems to be "good enough" in practice. | |
46 static const size_t kMaxBufferCapacity = 20 * kMegabyte; | |
47 | |
48 // Maximum number of bytes outside the buffer we will wait for in order to | |
49 // fulfill a read. If a read starts more than 2MB away from the data we | |
50 // currently have in the buffer, we will not wait for buffer to reach the read's | |
51 // location and will instead reset the request. | |
52 static const int kForwardWaitThreshold = 2 * kMegabyte; | |
53 | |
54 // Computes the suggested backward and forward capacity for the buffer | |
55 // if one wants to play at |playback_rate| * the natural playback speed. | |
56 // Use a value of 0 for |bitrate| if it is unknown. | |
57 static void ComputeTargetBufferWindow(float playback_rate, int bitrate, | |
58 size_t* out_backward_capacity, | |
59 size_t* out_forward_capacity) { | |
60 static const size_t kDefaultBitrate = 200 * 1024 * 8; // 200 Kbps. | |
61 static const size_t kMaxBitrate = 20 * kMegabyte * 8; // 20 Mbps. | |
62 static const float kMaxPlaybackRate = 25.0; | |
63 static const size_t kTargetSecondsBufferedAhead = 10; | |
64 static const size_t kTargetSecondsBufferedBehind = 2; | |
65 | |
66 // Use a default bit rate if unknown and clamp to prevent overflow. | |
67 if (bitrate <= 0) | |
68 bitrate = kDefaultBitrate; | |
69 bitrate = std::min(static_cast<size_t>(bitrate), kMaxBitrate); | |
70 | |
71 // Only scale the buffer window for playback rates greater than 1.0 in | |
72 // magnitude and clamp to prevent overflow. | |
73 bool backward_playback = false; | |
74 if (playback_rate < 0.0f) { | |
75 backward_playback = true; | |
76 playback_rate *= -1.0f; | |
77 } | |
78 | |
79 playback_rate = std::max(playback_rate, 1.0f); | |
80 playback_rate = std::min(playback_rate, kMaxPlaybackRate); | |
81 | |
82 size_t bytes_per_second = static_cast<size_t>(playback_rate * bitrate / 8.0); | |
83 | |
84 // Clamp between kMinBufferCapacity and kMaxBufferCapacity. | |
85 *out_forward_capacity = std::max( | |
86 kTargetSecondsBufferedAhead * bytes_per_second, kMinBufferCapacity); | |
87 *out_backward_capacity = std::max( | |
88 kTargetSecondsBufferedBehind * bytes_per_second, kMinBufferCapacity); | |
89 | |
90 *out_forward_capacity = std::min(*out_forward_capacity, kMaxBufferCapacity); | |
91 *out_backward_capacity = std::min(*out_backward_capacity, kMaxBufferCapacity); | |
92 | |
93 if (backward_playback) | |
94 std::swap(*out_forward_capacity, *out_backward_capacity); | |
95 } | |
96 | |
97 | |
98 BufferedResourceLoader::BufferedResourceLoader( | |
99 const GURL& url, | |
100 int64 first_byte_position, | |
101 int64 last_byte_position, | |
102 DeferStrategy strategy, | |
103 int bitrate, | |
104 float playback_rate, | |
105 media::MediaLog* media_log) | |
106 : deferred_(false), | |
107 defer_strategy_(strategy), | |
108 completed_(false), | |
109 range_requested_(false), | |
110 range_supported_(false), | |
111 saved_forward_capacity_(0), | |
112 url_(url), | |
113 first_byte_position_(first_byte_position), | |
114 last_byte_position_(last_byte_position), | |
115 single_origin_(true), | |
116 start_callback_(NULL), | |
117 offset_(0), | |
118 content_length_(kPositionNotSpecified), | |
119 instance_size_(kPositionNotSpecified), | |
120 read_callback_(NULL), | |
121 read_position_(0), | |
122 read_size_(0), | |
123 read_buffer_(NULL), | |
124 first_offset_(0), | |
125 last_offset_(0), | |
126 keep_test_loader_(false), | |
127 bitrate_(bitrate), | |
128 playback_rate_(playback_rate), | |
129 media_log_(media_log) { | |
130 | |
131 size_t backward_capacity; | |
132 size_t forward_capacity; | |
133 ComputeTargetBufferWindow( | |
134 playback_rate_, bitrate_, &backward_capacity, &forward_capacity); | |
135 buffer_.reset(new media::SeekableBuffer(backward_capacity, forward_capacity)); | |
136 } | |
137 | |
138 BufferedResourceLoader::~BufferedResourceLoader() { | |
139 if (!completed_ && url_loader_.get()) | |
140 url_loader_->cancel(); | |
141 } | |
142 | |
143 void BufferedResourceLoader::Start(net::OldCompletionCallback* start_callback, | |
144 const base::Closure& event_callback, | |
145 WebFrame* frame) { | |
146 // Make sure we have not started. | |
147 DCHECK(!start_callback_.get()); | |
148 DCHECK(event_callback_.is_null()); | |
149 DCHECK(start_callback); | |
150 DCHECK(!event_callback.is_null()); | |
151 CHECK(frame); | |
152 | |
153 start_callback_.reset(start_callback); | |
154 event_callback_ = event_callback; | |
155 | |
156 if (first_byte_position_ != kPositionNotSpecified) { | |
157 // TODO(hclam): server may not support range request so |offset_| may not | |
158 // equal to |first_byte_position_|. | |
159 offset_ = first_byte_position_; | |
160 } | |
161 | |
162 // Increment the reference count right before we start the request. This | |
163 // reference will be release when this request has ended. | |
164 AddRef(); | |
165 | |
166 // Prepare the request. | |
167 WebURLRequest request(url_); | |
168 request.setTargetType(WebURLRequest::TargetIsMedia); | |
169 | |
170 if (IsRangeRequest()) { | |
171 range_requested_ = true; | |
172 request.setHTTPHeaderField( | |
173 WebString::fromUTF8(net::HttpRequestHeaders::kRange), | |
174 WebString::fromUTF8(GenerateHeaders(first_byte_position_, | |
175 last_byte_position_))); | |
176 } | |
177 frame->setReferrerForRequest(request, WebKit::WebURL()); | |
178 | |
179 // Disable compression, compression for audio/video doesn't make sense... | |
180 request.setHTTPHeaderField( | |
181 WebString::fromUTF8(net::HttpRequestHeaders::kAcceptEncoding), | |
182 WebString::fromUTF8("identity;q=1, *;q=0")); | |
183 | |
184 // This flag is for unittests as we don't want to reset |url_loader| | |
185 if (!keep_test_loader_) { | |
186 WebURLLoaderOptions options; | |
187 options.allowCredentials = true; | |
188 options.crossOriginRequestPolicy = | |
189 WebURLLoaderOptions::CrossOriginRequestPolicyAllow; | |
190 url_loader_.reset(frame->createAssociatedURLLoader(options)); | |
191 } | |
192 | |
193 // Start the resource loading. | |
194 url_loader_->loadAsynchronously(request, this); | |
195 } | |
196 | |
197 void BufferedResourceLoader::Stop() { | |
198 // Reset callbacks. | |
199 start_callback_.reset(); | |
200 event_callback_.Reset(); | |
201 read_callback_.reset(); | |
202 | |
203 // Use the internal buffer to signal that we have been stopped. | |
204 // TODO(hclam): Not so pretty to do this. | |
205 if (!buffer_.get()) | |
206 return; | |
207 | |
208 // Destroy internal buffer. | |
209 buffer_.reset(); | |
210 | |
211 if (url_loader_.get()) { | |
212 if (deferred_) | |
213 url_loader_->setDefersLoading(false); | |
214 deferred_ = false; | |
215 | |
216 if (!completed_) { | |
217 url_loader_->cancel(); | |
218 completed_ = true; | |
219 } | |
220 } | |
221 } | |
222 | |
223 void BufferedResourceLoader::Read(int64 position, | |
224 int read_size, | |
225 uint8* buffer, | |
226 net::OldCompletionCallback* read_callback) { | |
227 DCHECK(!read_callback_.get()); | |
228 DCHECK(buffer_.get()); | |
229 DCHECK(read_callback); | |
230 DCHECK(buffer); | |
231 DCHECK_GT(read_size, 0); | |
232 | |
233 // Save the parameter of reading. | |
234 read_callback_.reset(read_callback); | |
235 read_position_ = position; | |
236 read_size_ = read_size; | |
237 read_buffer_ = buffer; | |
238 | |
239 // If read position is beyond the instance size, we cannot read there. | |
240 if (instance_size_ != kPositionNotSpecified && | |
241 instance_size_ <= read_position_) { | |
242 DoneRead(0); | |
243 return; | |
244 } | |
245 | |
246 // Make sure |offset_| and |read_position_| does not differ by a large | |
247 // amount. | |
248 if (read_position_ > offset_ + kint32max || | |
249 read_position_ < offset_ + kint32min) { | |
250 DoneRead(net::ERR_CACHE_MISS); | |
251 return; | |
252 } | |
253 | |
254 // Make sure |read_size_| is not too large for the buffer to ever be able to | |
255 // fulfill the read request. | |
256 if (read_size_ > kMaxBufferCapacity) { | |
257 DoneRead(net::ERR_FAILED); | |
258 return; | |
259 } | |
260 | |
261 // Prepare the parameters. | |
262 first_offset_ = static_cast<int>(read_position_ - offset_); | |
263 last_offset_ = first_offset_ + read_size_; | |
264 | |
265 // If we can serve the request now, do the actual read. | |
266 if (CanFulfillRead()) { | |
267 ReadInternal(); | |
268 UpdateDeferBehavior(); | |
269 return; | |
270 } | |
271 | |
272 // If we expect the read request to be fulfilled later, expand capacity as | |
273 // necessary and disable deferring. | |
274 if (WillFulfillRead()) { | |
275 // Advance offset as much as possible to create additional capacity. | |
276 int advance = std::min(first_offset_, | |
277 static_cast<int>(buffer_->forward_bytes())); | |
278 bool ret = buffer_->Seek(advance); | |
279 DCHECK(ret); | |
280 | |
281 offset_ += advance; | |
282 first_offset_ -= advance; | |
283 last_offset_ -= advance; | |
284 | |
285 // Expand capacity to accomodate a read that extends past the normal | |
286 // capacity. | |
287 // | |
288 // This can happen when reading in a large seek index or when the | |
289 // first byte of a read request falls within kForwardWaitThreshold. | |
290 if (last_offset_ > static_cast<int>(buffer_->forward_capacity())) { | |
291 saved_forward_capacity_ = buffer_->forward_capacity(); | |
292 buffer_->set_forward_capacity(last_offset_); | |
293 } | |
294 | |
295 // Make sure we stop deferring now that there's additional capacity. | |
296 // | |
297 // XXX: can we DCHECK(url_loader_.get()) at this point in time? | |
298 if (deferred_) | |
299 SetDeferred(false); | |
300 | |
301 DCHECK(!ShouldEnableDefer()) | |
302 << "Capacity was not adjusted properly to prevent deferring."; | |
303 | |
304 return; | |
305 } | |
306 | |
307 // Make a callback to report failure. | |
308 DoneRead(net::ERR_CACHE_MISS); | |
309 } | |
310 | |
311 int64 BufferedResourceLoader::GetBufferedPosition() { | |
312 if (buffer_.get()) | |
313 return offset_ + static_cast<int>(buffer_->forward_bytes()) - 1; | |
314 return kPositionNotSpecified; | |
315 } | |
316 | |
317 int64 BufferedResourceLoader::content_length() { | |
318 return content_length_; | |
319 } | |
320 | |
321 int64 BufferedResourceLoader::instance_size() { | |
322 return instance_size_; | |
323 } | |
324 | |
325 bool BufferedResourceLoader::range_supported() { | |
326 return range_supported_; | |
327 } | |
328 | |
329 bool BufferedResourceLoader::is_downloading_data() { | |
330 return !completed_ && !deferred_; | |
331 } | |
332 | |
333 const GURL& BufferedResourceLoader::url() { | |
334 return url_; | |
335 } | |
336 | |
337 void BufferedResourceLoader::SetURLLoaderForTest(WebURLLoader* mock_loader) { | |
338 url_loader_.reset(mock_loader); | |
339 keep_test_loader_ = true; | |
340 } | |
341 | |
342 ///////////////////////////////////////////////////////////////////////////// | |
343 // WebKit::WebURLLoaderClient implementation. | |
344 void BufferedResourceLoader::willSendRequest( | |
345 WebURLLoader* loader, | |
346 WebURLRequest& newRequest, | |
347 const WebURLResponse& redirectResponse) { | |
348 | |
349 // The load may have been stopped and |start_callback| is destroyed. | |
350 // In this case we shouldn't do anything. | |
351 if (!start_callback_.get()) { | |
352 // Set the url in the request to an invalid value (empty url). | |
353 newRequest.setURL(WebKit::WebURL()); | |
354 return; | |
355 } | |
356 | |
357 // Only allow |single_origin_| if we haven't seen a different origin yet. | |
358 if (single_origin_) | |
359 single_origin_ = url_.GetOrigin() == GURL(newRequest.url()).GetOrigin(); | |
360 | |
361 if (!IsProtocolSupportedForMedia(newRequest.url())) { | |
362 // Set the url in the request to an invalid value (empty url). | |
363 newRequest.setURL(WebKit::WebURL()); | |
364 DoneStart(net::ERR_ADDRESS_INVALID); | |
365 return; | |
366 } | |
367 | |
368 url_ = newRequest.url(); | |
369 } | |
370 | |
371 void BufferedResourceLoader::didSendData( | |
372 WebURLLoader* loader, | |
373 unsigned long long bytes_sent, | |
374 unsigned long long total_bytes_to_be_sent) { | |
375 NOTIMPLEMENTED(); | |
376 } | |
377 | |
378 void BufferedResourceLoader::didReceiveResponse( | |
379 WebURLLoader* loader, | |
380 const WebURLResponse& response) { | |
381 VLOG(1) << "didReceiveResponse: " << response.httpStatusCode(); | |
382 | |
383 // The loader may have been stopped and |start_callback| is destroyed. | |
384 // In this case we shouldn't do anything. | |
385 if (!start_callback_.get()) | |
386 return; | |
387 | |
388 bool partial_response = false; | |
389 | |
390 // We make a strong assumption that when we reach here we have either | |
391 // received a response from HTTP/HTTPS protocol or the request was | |
392 // successful (in particular range request). So we only verify the partial | |
393 // response for HTTP and HTTPS protocol. | |
394 if (url_.SchemeIs(kHttpScheme) || url_.SchemeIs(kHttpsScheme)) { | |
395 int error = net::OK; | |
396 | |
397 // Check to see whether the server supports byte ranges. | |
398 std::string accept_ranges = | |
399 response.httpHeaderField("Accept-Ranges").utf8(); | |
400 range_supported_ = (accept_ranges.find("bytes") != std::string::npos); | |
401 | |
402 partial_response = (response.httpStatusCode() == kHttpPartialContent); | |
403 | |
404 if (range_requested_) { | |
405 // If we have verified the partial response and it is correct, we will | |
406 // return net::OK. It's also possible for a server to support range | |
407 // requests without advertising Accept-Ranges: bytes. | |
408 if (partial_response && VerifyPartialResponse(response)) | |
409 range_supported_ = true; | |
410 else | |
411 error = net::ERR_INVALID_RESPONSE; | |
412 } else if (response.httpStatusCode() != kHttpOK) { | |
413 // We didn't request a range but server didn't reply with "200 OK". | |
414 error = net::ERR_FAILED; | |
415 } | |
416 | |
417 if (error != net::OK) { | |
418 DoneStart(error); | |
419 Stop(); | |
420 return; | |
421 } | |
422 } else { | |
423 // For any protocol other than HTTP and HTTPS, assume range request is | |
424 // always fulfilled. | |
425 partial_response = range_requested_; | |
426 } | |
427 | |
428 // Expected content length can be |kPositionNotSpecified|, in that case | |
429 // |content_length_| is not specified and this is a streaming response. | |
430 content_length_ = response.expectedContentLength(); | |
431 | |
432 // If we have not requested a range, then the size of the instance is equal | |
433 // to the content length. | |
434 if (!partial_response) | |
435 instance_size_ = content_length_; | |
436 | |
437 // Calls with a successful response. | |
438 DoneStart(net::OK); | |
439 } | |
440 | |
441 void BufferedResourceLoader::didReceiveData( | |
442 WebURLLoader* loader, | |
443 const char* data, | |
444 int data_length, | |
445 int encoded_data_length) { | |
446 VLOG(1) << "didReceiveData: " << data_length << " bytes"; | |
447 | |
448 DCHECK(!completed_); | |
449 DCHECK_GT(data_length, 0); | |
450 | |
451 // If this loader has been stopped, |buffer_| would be destroyed. | |
452 // In this case we shouldn't do anything. | |
453 if (!buffer_.get()) | |
454 return; | |
455 | |
456 // Writes more data to |buffer_|. | |
457 buffer_->Append(reinterpret_cast<const uint8*>(data), data_length); | |
458 | |
459 // If there is an active read request, try to fulfill the request. | |
460 if (HasPendingRead() && CanFulfillRead()) | |
461 ReadInternal(); | |
462 | |
463 // At last see if the buffer is full and we need to defer the downloading. | |
464 UpdateDeferBehavior(); | |
465 | |
466 // Consume excess bytes from our in-memory buffer if necessary. | |
467 if (buffer_->forward_bytes() > buffer_->forward_capacity()) { | |
468 size_t excess = buffer_->forward_bytes() - buffer_->forward_capacity(); | |
469 bool success = buffer_->Seek(excess); | |
470 DCHECK(success); | |
471 offset_ += first_offset_ + excess; | |
472 } | |
473 | |
474 // Notify that we have received some data. | |
475 NotifyNetworkEvent(); | |
476 Log(); | |
477 } | |
478 | |
479 void BufferedResourceLoader::didDownloadData( | |
480 WebKit::WebURLLoader* loader, | |
481 int dataLength) { | |
482 NOTIMPLEMENTED(); | |
483 } | |
484 | |
485 void BufferedResourceLoader::didReceiveCachedMetadata( | |
486 WebURLLoader* loader, | |
487 const char* data, | |
488 int data_length) { | |
489 NOTIMPLEMENTED(); | |
490 } | |
491 | |
492 void BufferedResourceLoader::didFinishLoading( | |
493 WebURLLoader* loader, | |
494 double finishTime) { | |
495 VLOG(1) << "didFinishLoading"; | |
496 | |
497 DCHECK(!completed_); | |
498 completed_ = true; | |
499 | |
500 // If we didn't know the |instance_size_| we do now. | |
501 if (instance_size_ == kPositionNotSpecified) { | |
502 instance_size_ = offset_ + buffer_->forward_bytes(); | |
503 } | |
504 | |
505 // If there is a start callback, calls it. | |
506 if (start_callback_.get()) { | |
507 DoneStart(net::OK); | |
508 } | |
509 | |
510 // If there is a pending read but the request has ended, returns with what | |
511 // we have. | |
512 if (HasPendingRead()) { | |
513 // Make sure we have a valid buffer before we satisfy a read request. | |
514 DCHECK(buffer_.get()); | |
515 | |
516 // Try to fulfill with what is in the buffer. | |
517 if (CanFulfillRead()) | |
518 ReadInternal(); | |
519 else | |
520 DoneRead(net::ERR_CACHE_MISS); | |
521 } | |
522 | |
523 // There must not be any outstanding read request. | |
524 DCHECK(!HasPendingRead()); | |
525 | |
526 // Notify that network response is completed. | |
527 NotifyNetworkEvent(); | |
528 | |
529 url_loader_.reset(); | |
530 Release(); | |
531 } | |
532 | |
533 void BufferedResourceLoader::didFail( | |
534 WebURLLoader* loader, | |
535 const WebURLError& error) { | |
536 VLOG(1) << "didFail: " << error.reason; | |
537 | |
538 DCHECK(!completed_); | |
539 completed_ = true; | |
540 | |
541 // If there is a start callback, calls it. | |
542 if (start_callback_.get()) { | |
543 DoneStart(error.reason); | |
544 } | |
545 | |
546 // If there is a pending read but the request failed, return with the | |
547 // reason for the error. | |
548 if (HasPendingRead()) { | |
549 DoneRead(error.reason); | |
550 } | |
551 | |
552 // Notify that network response is completed. | |
553 NotifyNetworkEvent(); | |
554 | |
555 url_loader_.reset(); | |
556 Release(); | |
557 } | |
558 | |
559 bool BufferedResourceLoader::HasSingleOrigin() const { | |
560 return single_origin_; | |
561 } | |
562 | |
563 void BufferedResourceLoader::UpdateDeferStrategy(DeferStrategy strategy) { | |
564 defer_strategy_ = strategy; | |
565 UpdateDeferBehavior(); | |
566 } | |
567 | |
568 void BufferedResourceLoader::SetPlaybackRate(float playback_rate) { | |
569 playback_rate_ = playback_rate; | |
570 | |
571 // This is a pause so don't bother updating the buffer window as we'll likely | |
572 // get unpaused in the future. | |
573 if (playback_rate_ == 0.0) | |
574 return; | |
575 | |
576 UpdateBufferWindow(); | |
577 } | |
578 | |
579 void BufferedResourceLoader::SetBitrate(int bitrate) { | |
580 DCHECK(bitrate >= 0); | |
581 bitrate_ = bitrate; | |
582 UpdateBufferWindow(); | |
583 } | |
584 | |
585 ///////////////////////////////////////////////////////////////////////////// | |
586 // Helper methods. | |
587 | |
588 void BufferedResourceLoader::UpdateBufferWindow() { | |
589 if (!buffer_.get()) | |
590 return; | |
591 | |
592 size_t backward_capacity; | |
593 size_t forward_capacity; | |
594 ComputeTargetBufferWindow( | |
595 playback_rate_, bitrate_, &backward_capacity, &forward_capacity); | |
596 | |
597 // This does not evict data from the buffer if the new capacities are less | |
598 // than the current capacities; the new limits will be enforced after the | |
599 // existing excess buffered data is consumed. | |
600 buffer_->set_backward_capacity(backward_capacity); | |
601 buffer_->set_forward_capacity(forward_capacity); | |
602 } | |
603 | |
604 void BufferedResourceLoader::UpdateDeferBehavior() { | |
605 if (!url_loader_.get() || !buffer_.get()) | |
606 return; | |
607 | |
608 // If necessary, toggle defer state and continue/pause downloading data | |
609 // accordingly. | |
610 if (ShouldEnableDefer() || ShouldDisableDefer()) | |
611 SetDeferred(!deferred_); | |
612 } | |
613 | |
614 void BufferedResourceLoader::SetDeferred(bool deferred) { | |
615 deferred_ = deferred; | |
616 if (url_loader_.get()) { | |
617 url_loader_->setDefersLoading(deferred); | |
618 NotifyNetworkEvent(); | |
619 } | |
620 } | |
621 | |
622 bool BufferedResourceLoader::ShouldEnableDefer() { | |
623 // If we're already deferring, then enabling makes no sense. | |
624 if (deferred_) | |
625 return false; | |
626 | |
627 switch(defer_strategy_) { | |
628 // Never defer at all, so never enable defer. | |
629 case kNeverDefer: | |
630 return false; | |
631 | |
632 // Defer if nothing is being requested. | |
633 case kReadThenDefer: | |
634 return !read_callback_.get(); | |
635 | |
636 // Defer if we've reached the max capacity of the threshold. | |
637 case kThresholdDefer: | |
638 return buffer_->forward_bytes() >= buffer_->forward_capacity(); | |
639 } | |
640 // Otherwise don't enable defer. | |
641 return false; | |
642 } | |
643 | |
644 bool BufferedResourceLoader::ShouldDisableDefer() { | |
645 // If we're not deferring, then disabling makes no sense. | |
646 if (!deferred_) | |
647 return false; | |
648 | |
649 switch(defer_strategy_) { | |
650 // Always disable deferring. | |
651 case kNeverDefer: | |
652 return true; | |
653 | |
654 // We have an outstanding read request, and we have not buffered enough | |
655 // yet to fulfill the request; disable defer to get more data. | |
656 case kReadThenDefer: | |
657 return read_callback_.get() && | |
658 last_offset_ > static_cast<int>(buffer_->forward_bytes()); | |
659 | |
660 // We have less than half the capacity of our threshold, so | |
661 // disable defer to get more data. | |
662 case kThresholdDefer: { | |
663 size_t amount_buffered = buffer_->forward_bytes(); | |
664 size_t half_capacity = buffer_->forward_capacity() / 2; | |
665 return amount_buffered < half_capacity; | |
666 } | |
667 } | |
668 | |
669 // Otherwise keep deferring. | |
670 return false; | |
671 } | |
672 | |
673 bool BufferedResourceLoader::CanFulfillRead() { | |
674 // If we are reading too far in the backward direction. | |
675 if (first_offset_ < 0 && | |
676 first_offset_ + static_cast<int>(buffer_->backward_bytes()) < 0) | |
677 return false; | |
678 | |
679 // If the start offset is too far ahead. | |
680 if (first_offset_ >= static_cast<int>(buffer_->forward_bytes())) | |
681 return false; | |
682 | |
683 // At the point, we verified that first byte requested is within the buffer. | |
684 // If the request has completed, then just returns with what we have now. | |
685 if (completed_) | |
686 return true; | |
687 | |
688 // If the resource request is still active, make sure the whole requested | |
689 // range is covered. | |
690 if (last_offset_ > static_cast<int>(buffer_->forward_bytes())) | |
691 return false; | |
692 | |
693 return true; | |
694 } | |
695 | |
696 bool BufferedResourceLoader::WillFulfillRead() { | |
697 // Trying to read too far behind. | |
698 if (first_offset_ < 0 && | |
699 first_offset_ + static_cast<int>(buffer_->backward_bytes()) < 0) | |
700 return false; | |
701 | |
702 // Trying to read too far ahead. | |
703 if (first_offset_ - static_cast<int>(buffer_->forward_bytes()) >= | |
704 kForwardWaitThreshold) | |
705 return false; | |
706 | |
707 // The resource request has completed, there's no way we can fulfill the | |
708 // read request. | |
709 if (completed_) | |
710 return false; | |
711 | |
712 return true; | |
713 } | |
714 | |
715 void BufferedResourceLoader::ReadInternal() { | |
716 // Seek to the first byte requested. | |
717 bool ret = buffer_->Seek(first_offset_); | |
718 DCHECK(ret); | |
719 | |
720 // Then do the read. | |
721 int read = static_cast<int>(buffer_->Read(read_buffer_, read_size_)); | |
722 offset_ += first_offset_ + read; | |
723 | |
724 // And report with what we have read. | |
725 DoneRead(read); | |
726 } | |
727 | |
728 bool BufferedResourceLoader::VerifyPartialResponse( | |
729 const WebURLResponse& response) { | |
730 int64 first_byte_position, last_byte_position, instance_size; | |
731 | |
732 if (!MultipartResponseDelegate::ReadContentRanges(response, | |
733 &first_byte_position, | |
734 &last_byte_position, | |
735 &instance_size)) { | |
736 return false; | |
737 } | |
738 | |
739 if (instance_size != kPositionNotSpecified) { | |
740 instance_size_ = instance_size; | |
741 } | |
742 | |
743 if (first_byte_position_ != kPositionNotSpecified && | |
744 first_byte_position_ != first_byte_position) { | |
745 return false; | |
746 } | |
747 | |
748 // TODO(hclam): I should also check |last_byte_position|, but since | |
749 // we will never make such a request that it is ok to leave it unimplemented. | |
750 return true; | |
751 } | |
752 | |
753 std::string BufferedResourceLoader::GenerateHeaders( | |
754 int64 first_byte_position, | |
755 int64 last_byte_position) { | |
756 // Construct the value for the range header. | |
757 std::string header; | |
758 if (first_byte_position > kPositionNotSpecified && | |
759 last_byte_position > kPositionNotSpecified) { | |
760 if (first_byte_position <= last_byte_position) { | |
761 header = base::StringPrintf("bytes=%" PRId64 "-%" PRId64, | |
762 first_byte_position, | |
763 last_byte_position); | |
764 } | |
765 } else if (first_byte_position > kPositionNotSpecified) { | |
766 header = base::StringPrintf("bytes=%" PRId64 "-", | |
767 first_byte_position); | |
768 } else if (last_byte_position > kPositionNotSpecified) { | |
769 NOTIMPLEMENTED() << "Suffix range not implemented"; | |
770 } | |
771 return header; | |
772 } | |
773 | |
774 void BufferedResourceLoader::DoneRead(int error) { | |
775 read_callback_->RunWithParams(Tuple1<int>(error)); | |
776 read_callback_.reset(); | |
777 if (buffer_.get() && saved_forward_capacity_) { | |
778 buffer_->set_forward_capacity(saved_forward_capacity_); | |
779 saved_forward_capacity_ = 0; | |
780 } | |
781 read_position_ = 0; | |
782 read_size_ = 0; | |
783 read_buffer_ = NULL; | |
784 first_offset_ = 0; | |
785 last_offset_ = 0; | |
786 Log(); | |
787 } | |
788 | |
789 void BufferedResourceLoader::DoneStart(int error) { | |
790 start_callback_->RunWithParams(Tuple1<int>(error)); | |
791 start_callback_.reset(); | |
792 } | |
793 | |
794 void BufferedResourceLoader::NotifyNetworkEvent() { | |
795 if (!event_callback_.is_null()) | |
796 event_callback_.Run(); | |
797 } | |
798 | |
799 bool BufferedResourceLoader::IsRangeRequest() const { | |
800 return first_byte_position_ != kPositionNotSpecified; | |
801 } | |
802 | |
803 void BufferedResourceLoader::Log() { | |
804 if (buffer_.get()) { | |
805 media_log_->AddEvent( | |
806 media_log_->CreateBufferedExtentsChangedEvent( | |
807 offset_ - buffer_->backward_bytes(), | |
808 offset_, | |
809 offset_ + buffer_->forward_bytes())); | |
810 } | |
811 } | |
812 | |
813 } // namespace webkit_glue | |
OLD | NEW |