File: multi_buffer_data_source.cc

package info (click to toggle)
chromium 139.0.7258.138-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,120,676 kB
  • sloc: cpp: 35,100,869; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (799 lines) | stat: -rw-r--r-- 26,005 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/platform/media/multi_buffer_data_source.h"

#include <algorithm>
#include <memory>
#include <utility>

#include "base/containers/adapters.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "media/base/media_log.h"
#include "net/base/net_errors.h"
#include "third_party/blink/renderer/platform/media/buffered_data_source_host_impl.h"
#include "third_party/blink/renderer/platform/media/multi_buffer_reader.h"
#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_copier_base.h"
#include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "url/gurl.h"

namespace blink {

namespace {

// Minimum preload buffer.
const int64_t kMinBufferPreload = 2 << 20;  // 2 Mb
// Maxmimum preload buffer.
const int64_t kMaxBufferPreload = 50 << 20;  // 50 Mb

// If preload_ == METADATA, preloading size will be
// shifted down this many bits. This shift turns
// one Mb into one 32k block.
// This seems to be the smallest amount of preload we can do without
// ending up repeatedly closing and re-opening the connection
// due to read calls after StopPreloading() have been called.
const int64_t kMetadataShift = 6;

// Preload this much extra, then stop preloading until we fall below the
// preload_seconds_.value().
const int64_t kPreloadHighExtra = 1 << 20;  // 1 Mb

// Default pin region size.
// Note that we go over this if preload is calculated high enough.
const int64_t kDefaultPinSize = 25 << 20;  // 25 Mb

// If bitrate is not known, use this.
const int64_t kDefaultBitrate = 200 * 8 << 10;  // 200 Kbps.

// Maximum bitrate for buffer calculations.
const int64_t kMaxBitrate = 20 * 8 << 20;  // 20 Mbps.

// Maximum playback rate for buffer calculations.
const double kMaxPlaybackRate = 25.0;

// Extra buffer accumulation speed, in terms of download buffer.
const int kSlowPreloadPercentage = 10;

// Update buffer sizes every 32 progress updates.
const int kUpdateBufferSizeFrequency = 32;

// How long to we delay a seek after a read?
constexpr base::TimeDelta kSeekDelay = base::Milliseconds(20);

}  // namespace

class MultiBufferDataSource::ReadOperation {
 public:
  ReadOperation() = delete;
  ReadOperation(int64_t position,
                int size,
                uint8_t* data,
                media::DataSource::ReadCB callback);
  ReadOperation(const ReadOperation&) = delete;
  ReadOperation& operator=(const ReadOperation&) = delete;
  ~ReadOperation();

  // Runs |callback_| with the given |result|, deleting the operation
  // afterwards.
  static void Run(std::unique_ptr<ReadOperation> read_op, int result);

  int64_t position() { return position_; }
  int size() { return size_; }
  uint8_t* data() { return data_; }

 private:
  const int64_t position_;
  const int size_;
  raw_ptr<uint8_t, DanglingUntriaged> data_;
  media::DataSource::ReadCB callback_;
};

MultiBufferDataSource::ReadOperation::ReadOperation(
    int64_t position,
    int size,
    uint8_t* data,
    media::DataSource::ReadCB callback)
    : position_(position),
      size_(size),
      data_(data),
      callback_(std::move(callback)) {
  DCHECK(callback_);
}

MultiBufferDataSource::ReadOperation::~ReadOperation() {
  DCHECK(!callback_);
}

// static
void MultiBufferDataSource::ReadOperation::Run(
    std::unique_ptr<ReadOperation> read_op,
    int result) {
  std::move(read_op->callback_).Run(result);
}

MultiBufferDataSource::MultiBufferDataSource(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
    scoped_refptr<UrlData> url_data_arg,
    media::MediaLog* media_log,
    BufferedDataSourceHost* host,
    DownloadingCB downloading_cb)
    : render_task_runner_(task_runner),
      url_data_(std::move(url_data_arg)),
      media_log_(media_log->Clone()),
      host_(host),
      downloading_cb_(std::move(downloading_cb)) {
  weak_ptr_ = weak_factory_.GetWeakPtr();
  DCHECK(host_);
  DCHECK(downloading_cb_);
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  DCHECK(url_data_);
  url_data_->Use();
  url_data_->OnRedirect(
      WTF::BindOnce(&MultiBufferDataSource::OnRedirected, weak_ptr_));
}

MultiBufferDataSource::~MultiBufferDataSource() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
}

bool MultiBufferDataSource::media_has_played() const {
  return media_has_played_;
}

bool MultiBufferDataSource::AssumeFullyBuffered() const {
  DCHECK(url_data_);
  return !url_data_->url().ProtocolIsInHTTPFamily();
}

void MultiBufferDataSource::SetReader(
    std::unique_ptr<MultiBufferReader> reader) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  base::AutoLock auto_lock(lock_);
  reader_ = std::move(reader);
}

void MultiBufferDataSource::CreateResourceLoader(int64_t first_byte_position,
                                                 int64_t last_byte_position) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  SetReader(std::make_unique<MultiBufferReader>(
      url_data_->multibuffer(), first_byte_position, last_byte_position,
      is_client_audio_element_,
      WTF::BindRepeating(&MultiBufferDataSource::ProgressCallback, weak_ptr_),
      render_task_runner_));
  UpdateBufferSizes();
}

void MultiBufferDataSource::CreateResourceLoader_Locked(
    int64_t first_byte_position,
    int64_t last_byte_position) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  lock_.AssertAcquired();

  reader_ = std::make_unique<MultiBufferReader>(
      url_data_->multibuffer(), first_byte_position, last_byte_position,
      is_client_audio_element_,
      WTF::BindRepeating(&MultiBufferDataSource::ProgressCallback, weak_ptr_),
      render_task_runner_);
  UpdateBufferSizes();
}

void MultiBufferDataSource::Initialize(InitializeCB init_cb) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  DCHECK(init_cb);
  DCHECK(!reader_);

  init_cb_ = std::move(init_cb);

  CreateResourceLoader(0, kPositionNotSpecified);

  // We're not allowed to call Wait() if data is already available.
  if (reader_->Available()) {
    PostCrossThreadTask(
        *render_task_runner_, FROM_HERE,
        CrossThreadBindOnce(&MultiBufferDataSource::StartCallback, weak_ptr_));

    // When the entire file is already in the cache, we won't get any more
    // progress callbacks, which breaks some expectations. Post a task to
    // make sure that the client gets at least one call each for the progress
    // and loading callbacks.
    PostCrossThreadTask(
        *render_task_runner_, FROM_HERE,
        CrossThreadBindOnce(&MultiBufferDataSource::UpdateProgress,
                            weak_factory_.GetWeakPtr()));
  } else {
    reader_->Wait(
        1, WTF::BindOnce(&MultiBufferDataSource::StartCallback, weak_ptr_));
  }
}

void MultiBufferDataSource::OnRedirected(
    const scoped_refptr<UrlData>& new_destination) {
  if (!new_destination || !url_data_) {
    // A failure occurred.
    failed_ = true;
    if (init_cb_) {
      PostCrossThreadTask(
          *render_task_runner_, FROM_HERE,
          CrossThreadBindOnce(&MultiBufferDataSource::StartCallback,
                              weak_ptr_));
    } else {
      base::AutoLock auto_lock(lock_);
      StopInternal_Locked();
    }
    StopLoader();
    return;
  }
  if (!SecurityOrigin::AreSameOrigin(url_data_->url(),
                                     new_destination->url())) {
    single_origin_ = false;
  }
  SetReader(nullptr);
  url_data_ = std::move(new_destination);

  url_data_->OnRedirect(
      WTF::BindOnce(&MultiBufferDataSource::OnRedirected, weak_ptr_));

  if (init_cb_) {
    CreateResourceLoader(0, kPositionNotSpecified);
    if (reader_->Available()) {
      PostCrossThreadTask(
          *render_task_runner_, FROM_HERE,
          CrossThreadBindOnce(&MultiBufferDataSource::StartCallback,
                              weak_ptr_));
    } else {
      reader_->Wait(
          1, WTF::BindOnce(&MultiBufferDataSource::StartCallback, weak_ptr_));
    }
  } else if (read_op_) {
    CreateResourceLoader(read_op_->position(), kPositionNotSpecified);
    if (reader_->Available()) {
      PostCrossThreadTask(
          *render_task_runner_, FROM_HERE,
          CrossThreadBindOnce(&MultiBufferDataSource::ReadTask, weak_ptr_));
    } else {
      reader_->Wait(1,
                    WTF::BindOnce(&MultiBufferDataSource::ReadTask, weak_ptr_));
    }
  }

  // The "redirect" may just be `reader_` being merged into an existing UrlData,
  // in this case we need to ensure we report the buffered byte ranges from the
  // existing UrlData instance.
  UpdateProgress();

  if (redirect_cb_)
    redirect_cb_.Run();
}

void MultiBufferDataSource::SetPreload(media::DataSource::Preload preload) {
  DVLOG(1) << __func__ << "(" << preload << ")";
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  preload_ = preload;
  UpdateBufferSizes();
}

bool MultiBufferDataSource::HasSingleOrigin() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  // Before initialization completes there is no risk of leaking data. Callers
  // are required to order checks such that this isn't a race.
  return single_origin_;
}

bool MultiBufferDataSource::IsCorsCrossOrigin() const {
  return url_data_->is_cors_cross_origin();
}

void MultiBufferDataSource::OnRedirect(RedirectCB callback) {
  redirect_cb_ = std::move(callback);
}

bool MultiBufferDataSource::HasAccessControl() const {
  return url_data_->has_access_control();
}

bool MultiBufferDataSource::PassedTimingAllowOriginCheck() {
  return url_data_->passed_timing_allow_origin_check();
}

bool MultiBufferDataSource::WouldTaintOrigin() {
  // When the resource is redirected to another origin we think of it as
  // tainted. This is actually not specified, and is under discussion.
  // See https://github.com/whatwg/fetch/issues/737.
  if (!HasSingleOrigin() && cors_mode() == UrlData::CORS_UNSPECIFIED)
    return true;
  return IsCorsCrossOrigin();
}

UrlData::CorsMode MultiBufferDataSource::cors_mode() const {
  return url_data_->cors_mode();
}

void MultiBufferDataSource::OnMediaPlaybackRateChanged(double playback_rate) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  if (playback_rate < 0 || playback_rate == playback_rate_)
    return;

  playback_rate_ = playback_rate;
  cancel_on_defer_ = false;
  UpdateBufferSizes();
}

void MultiBufferDataSource::OnMediaIsPlaying() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  // Always clear this since it can be set by StopPreloading() calls at
  // any point in time.
  cancel_on_defer_ = false;

  if (media_has_played_)
    return;

  media_has_played_ = true;

  // Once we start playing, we need preloading.
  preload_ = AUTO;
  UpdateBufferSizes();
}

/////////////////////////////////////////////////////////////////////////////
// DataSource implementation.
void MultiBufferDataSource::Stop() {
  {
    base::AutoLock auto_lock(lock_);
    StopInternal_Locked();

    // Cleanup resources immediately if we're already on the right thread.
    if (render_task_runner_->BelongsToCurrentThread()) {
      reader_.reset();
      url_data_.reset();
      return;
    }
  }

  PostCrossThreadTask(*render_task_runner_, FROM_HERE,
                      CrossThreadBindOnce(&MultiBufferDataSource::StopLoader,
                                          weak_factory_.GetWeakPtr()));
}

void MultiBufferDataSource::Abort() {
  base::AutoLock auto_lock(lock_);
  DCHECK(!init_cb_);
  if (read_op_)
    ReadOperation::Run(std::move(read_op_), kAborted);

  // Abort does not call StopLoader() since it is typically called prior to a
  // seek or suspend. Let the loader logic make the decision about whether a new
  // loader is necessary upon the seek or resume.
}

void MultiBufferDataSource::SetBitrate(int bitrate) {
  PostCrossThreadTask(
      *render_task_runner_, FROM_HERE,
      CrossThreadBindOnce(&MultiBufferDataSource::SetBitrateTask,
                          weak_factory_.GetWeakPtr(), bitrate));
}

void MultiBufferDataSource::StopPreloading() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  if (!reader_) {
    return;
  }

  cancel_on_defer_ = true;
  if (!loading_) {
    base::AutoLock auto_lock(lock_);
    if (read_op_) {
      // We can't destroy the reader if a read operation is pending.
      // UpdateLoadingState_Locked will take care of it after the
      // operation is done.
      return;
    }
    // Already locked, no need to use SetReader().
    reader_.reset();
  }
}

int64_t MultiBufferDataSource::GetMemoryUsage() {
  // TODO(hubbe): Make more accurate when url_data_ is shared.
  return base::checked_cast<int64_t>(url_data_->CachedSize())
         << url_data_->multibuffer()->block_size_shift();
}

GURL MultiBufferDataSource::GetUrlAfterRedirects() const {
  return GURL(url_data_->url());
}

void MultiBufferDataSource::Read(int64_t position,
                                 int size,
                                 uint8_t* data,
                                 media::DataSource::ReadCB read_cb) {
  DVLOG(1) << "Read: " << position << " offset, " << size << " bytes";
  // Reading is not allowed until after initialization.
  DCHECK(!init_cb_);
  DCHECK(read_cb);

  {
    base::AutoLock auto_lock(lock_);
    DCHECK(!read_op_);

    if (stop_signal_received_) {
      std::move(read_cb).Run(kReadError);
      return;
    }

    // Optimization: Try reading from the cache here to get back to
    // muxing as soon as possible. This works because TryReadAt is
    // thread-safe.
    if (reader_) {
      int64_t bytes_read = reader_->TryReadAt(position, data, size);
      if (bytes_read > 0) {
        bytes_read_ += bytes_read;
        seek_positions_.push_back(position + bytes_read);
        if (seek_positions_.size() == 1) {
          PostDelayedCrossThreadTask(
              *render_task_runner_, FROM_HERE,
              CrossThreadBindOnce(&MultiBufferDataSource::SeekTask,
                                  weak_factory_.GetWeakPtr()),
              kSeekDelay);
        }

        std::move(read_cb).Run(static_cast<int>(bytes_read));
        return;
      }
    }
    read_op_ = std::make_unique<ReadOperation>(position, size, data,
                                               std::move(read_cb));
  }

  PostCrossThreadTask(*render_task_runner_, FROM_HERE,
                      CrossThreadBindOnce(&MultiBufferDataSource::ReadTask,
                                          weak_factory_.GetWeakPtr()));
}

bool MultiBufferDataSource::GetSize(int64_t* size_out) {
  base::AutoLock auto_lock(lock_);
  if (total_bytes_ != kPositionNotSpecified) {
    *size_out = total_bytes_;
    return true;
  }
  *size_out = 0;
  return false;
}

bool MultiBufferDataSource::IsStreaming() {
  return streaming_;
}

/////////////////////////////////////////////////////////////////////////////
// This method is the place where actual read happens,
void MultiBufferDataSource::ReadTask() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  base::AutoLock auto_lock(lock_);
  if (stop_signal_received_ || !read_op_)
    return;
  DCHECK(read_op_->size());

  if (!reader_)
    CreateResourceLoader_Locked(read_op_->position(), kPositionNotSpecified);

  int64_t available = reader_->AvailableAt(read_op_->position());
  if (available < 0) {
    // A failure has occured.
    ReadOperation::Run(std::move(read_op_), kReadError);
    return;
  }
  if (available) {
    int64_t bytes_read = std::min<int64_t>(available, read_op_->size());
    bytes_read =
        reader_->TryReadAt(read_op_->position(), read_op_->data(), bytes_read);

    bytes_read_ += bytes_read;
    seek_positions_.push_back(read_op_->position() + bytes_read);

    if (bytes_read == 0 && total_bytes_ == kPositionNotSpecified) {
      // We've reached the end of the file and we didn't know the total size
      // before. Update the total size so Read()s past the end of the file will
      // fail like they would if we had known the file size at the beginning.
      total_bytes_ = read_op_->position() + bytes_read;
      if (total_bytes_ != kPositionNotSpecified)
        host_->SetTotalBytes(total_bytes_);
    }

    ReadOperation::Run(std::move(read_op_), static_cast<int>(bytes_read));

    SeekTask_Locked();
  } else {
    reader_->Seek(read_op_->position());
    reader_->Wait(1, WTF::BindOnce(&MultiBufferDataSource::ReadTask,
                                   weak_factory_.GetWeakPtr()));
    UpdateLoadingState_Locked(false);
  }
}

void MultiBufferDataSource::SeekTask() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  base::AutoLock auto_lock(lock_);
  SeekTask_Locked();
}

void MultiBufferDataSource::SeekTask_Locked() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  lock_.AssertAcquired();

  if (stop_signal_received_)
    return;

  // A read operation is pending, which will call SeekTask_Locked when
  // it's done. We'll defer any seeking until the read op is done.
  if (read_op_)
    return;

  url_data_->AddBytesRead(bytes_read_);
  bytes_read_ = 0;

  if (reader_) {
    // If we're seeking to a new location, (not just slightly further
    // in the file) and we have more data buffered in that new location
    // than in our current location, then we don't actually seek anywhere.
    // Instead we keep preloading at the old location a while longer.

    int64_t pos = reader_->Tell();
    int64_t available = reader_->Available();

    // Iterate backwards, because if two positions have the same
    // amount of buffered data, we probably want to prefer the latest
    // one in the array.
    for (const auto& new_pos : base::Reversed(seek_positions_)) {
      int64_t available_at_new_pos = reader_->AvailableAt(new_pos);

      if (total_bytes_ != kPositionNotSpecified) {
        if (new_pos + available_at_new_pos >= total_bytes_) {
          // Buffer reaches end of file, no need to seek here.
          continue;
        }
      }
      if (available_at_new_pos < available) {
        pos = new_pos;
        available = available_at_new_pos;
      }
    }
    reader_->Seek(pos);
  }
  seek_positions_.clear();

  UpdateLoadingState_Locked(false);
}

void MultiBufferDataSource::StopInternal_Locked() {
  lock_.AssertAcquired();
  if (stop_signal_received_)
    return;

  stop_signal_received_ = true;

  // Initialize() isn't part of the DataSource interface so don't call it in
  // response to Stop().
  init_cb_.Reset();

  if (read_op_)
    ReadOperation::Run(std::move(read_op_), kReadError);
}

void MultiBufferDataSource::StopLoader() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  SetReader(nullptr);
}

void MultiBufferDataSource::SetBitrateTask(int bitrate) {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  bitrate_ = bitrate;
  UpdateBufferSizes();
}

/////////////////////////////////////////////////////////////////////////////
// BufferedResourceLoader callback methods.
void MultiBufferDataSource::StartCallback() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  // TODO(scherkus): we shouldn't have to lock to signal host(), see
  // http://crbug.com/113712 for details.
  base::AutoLock auto_lock(lock_);
  if (stop_signal_received_) {
    return;
  }

  if (!init_cb_) {
    // Can't call SetReader(nullptr) since we are holding the lock.
    reader_.reset();
    return;
  }

  // All responses must be successful. Resources that are assumed to be fully
  // buffered must have a known content length.
  bool success =
      reader_ && reader_->Available() > 0 && url_data_ &&
      (!AssumeFullyBuffered() || url_data_->length() != kPositionNotSpecified);

  if (success) {
    total_bytes_ = url_data_->length();
    streaming_ =
        !AssumeFullyBuffered() && (total_bytes_ == kPositionNotSpecified ||
                                   !url_data_->range_supported());

    media_log_->SetProperty<media::MediaLogProperty::kTotalBytes>(total_bytes_);
    media_log_->SetProperty<media::MediaLogProperty::kIsStreaming>(streaming_);
  } else {
    // Can't call SetReader(nullptr) since we are holding the lock.
    reader_.reset();
  }

  if (success) {
    if (total_bytes_ != kPositionNotSpecified) {
      host_->SetTotalBytes(total_bytes_);
      if (AssumeFullyBuffered())
        host_->AddBufferedByteRange(0, total_bytes_);
    }

    // Progress callback might be called after the start callback,
    // make sure that we update single_origin_ now.
    media_log_->SetProperty<media::MediaLogProperty::kIsSingleOrigin>(
        single_origin_);
    media_log_->SetProperty<media::MediaLogProperty::kIsRangeHeaderSupported>(
        url_data_->range_supported());
  }

  PostCrossThreadTask(*render_task_runner_, FROM_HERE,
                      CrossThreadBindOnce(std::move(init_cb_), success));

  UpdateBufferSizes();

  // Even if data is cached, say that we're loading at this point for
  // compatibility.
  UpdateLoadingState_Locked(true);
}

void MultiBufferDataSource::ProgressCallback(int64_t begin, int64_t end) {
  DVLOG(1) << __func__ << "(" << begin << ", " << end << ")";
  DCHECK(render_task_runner_->BelongsToCurrentThread());

  base::AutoLock auto_lock(lock_);
  if (stop_signal_received_)
    return;

  if (AssumeFullyBuffered())
    return;

  if (end > begin)
    host_->AddBufferedByteRange(begin, end);

  if (buffer_size_update_counter_ > 0)
    buffer_size_update_counter_--;
  else
    UpdateBufferSizes();

  UpdateLoadingState_Locked(false);
}

void MultiBufferDataSource::UpdateLoadingState_Locked(bool force_loading) {
  DVLOG(1) << __func__;
  lock_.AssertAcquired();
  if (AssumeFullyBuffered())
    return;
  // Update loading state.
  bool is_loading = !!reader_ && reader_->IsLoading();
  if (force_loading || is_loading != loading_) {
    bool loading = is_loading || force_loading;

    if (!loading && cancel_on_defer_) {
      if (read_op_) {
        // We can't destroy the reader if a read operation is pending.
        // UpdateLoadingState_Locked will be called again when the read
        // operation is done.
        return;
      }
      // Already locked, no need to use SetReader().
      reader_.reset();
    }

    loading_ = loading;
    downloading_cb_.Run(loading_);
  }
}

void MultiBufferDataSource::UpdateProgress() {
  DCHECK(render_task_runner_->BelongsToCurrentThread());
  if (reader_) {
    uint64_t available = reader_->Available();
    uint64_t pos = reader_->Tell();
    ProgressCallback(pos, pos + available);
  }
}

void MultiBufferDataSource::UpdateBufferSizes() {
  DVLOG(1) << __func__;
  if (!reader_)
    return;

  buffer_size_update_counter_ = kUpdateBufferSizeFrequency;

  // Use a default bit rate if unknown and clamp to prevent overflow.
  int64_t bitrate = std::clamp<int64_t>(bitrate_, 0, kMaxBitrate);
  if (bitrate == 0)
    bitrate = kDefaultBitrate;

  // Only scale the buffer window for playback rates greater than 1.0 in
  // magnitude and clamp to prevent overflow.
  double playback_rate = playback_rate_;

  playback_rate = std::max(playback_rate, 1.0);
  playback_rate = std::min(playback_rate, kMaxPlaybackRate);

  int64_t bytes_per_second = (bitrate / 8.0) * playback_rate;

  // Preload 10 seconds of data, clamped to some min/max value.
  int64_t preload = std::clamp(preload_seconds_.value() * bytes_per_second,
                               kMinBufferPreload, kMaxBufferPreload);

  // Increase buffering slowly at a rate of 10% of data downloaded so
  // far, maxing out at the preload size.
  int64_t extra_buffer = std::min(
      preload, url_data_->BytesReadFromCache() * kSlowPreloadPercentage / 100);

  // Add extra buffer to preload.
  preload += extra_buffer;

  // We preload this much, then we stop unil we read |preload| before resuming.
  int64_t preload_high = preload + kPreloadHighExtra;

  // We pin a few seconds of data behind the current reading position.
  int64_t pin_backward =
      std::clamp(keep_after_playback_seconds_.value() * bytes_per_second,
                 kMinBufferPreload, kMaxBufferPreload);

  // We always pin at least kDefaultPinSize ahead of the read position.
  // Normally, the extra space between preload_high and kDefaultPinSize will
  // not actually have any data in it, but if it does, we don't want to throw it
  // away right before we need it.
  int64_t pin_forward = std::max(preload_high, kDefaultPinSize);

  // Note that the buffer size is advisory as only non-pinned data is allowed
  // to be thrown away. Most of the time we pin a region that is larger than
  // |buffer_size|, which only makes sense because most of the time, some of
  // the data in pinned region is not present in the cache.
  int64_t buffer_size = std::min(
      (preload_seconds_.value() + keep_after_playback_seconds_.value()) *
              bytes_per_second +
          extra_buffer * 3,
      preload_high + pin_backward + extra_buffer);

  if (url_data_->FullyCached() ||
      (url_data_->length() != kPositionNotSpecified &&
       url_data_->length() < kDefaultPinSize)) {
    // We just make pin_forwards/backwards big enough to encompass the
    // whole file regardless of where we are, with some extra margins.
    pin_forward = std::max(pin_forward, url_data_->length() * 2);
    pin_backward = std::max(pin_backward, url_data_->length() * 2);
    buffer_size = url_data_->length();
  }

  reader_->SetMaxBuffer(buffer_size);
  reader_->SetPinRange(pin_backward, pin_forward);

  if (preload_ == METADATA) {
    preload_high >>= kMetadataShift;
    preload >>= kMetadataShift;
  }
  reader_->SetPreload(preload_high, preload);
}

}  // namespace blink