Shaka Packager SDK
bandwidth_estimator.cc
1 // Copyright 2014 Google Inc. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6 
7 #include "packager/mpd/base/bandwidth_estimator.h"
8 
9 #include <cmath>
10 
11 #include "packager/base/logging.h"
12 
13 namespace shaka {
14 
15 BandwidthEstimator::BandwidthEstimator(size_t num_blocks)
16  : sliding_queue_(num_blocks) {}
17 BandwidthEstimator::~BandwidthEstimator() {}
18 
19 void BandwidthEstimator::AddBlock(uint64_t size, double duration) {
20  DCHECK_GT(duration, 0.0);
21  DCHECK_GT(size, 0u);
22 
23  const int kBitsInByte = 8;
24  const double bits_per_second_reciprocal = duration / (kBitsInByte * size);
25  sliding_queue_.Add(bits_per_second_reciprocal);
26 }
27 
28 uint64_t BandwidthEstimator::Estimate() const {
29  return sliding_queue_.size() == 0
30  ? 0
31  : static_cast<uint64_t>(
32  ceil(sliding_queue_.size() / sliding_queue_.sum()));
33 }
34 
35 uint64_t BandwidthEstimator::Max() const {
36  // The first element has minimum "bits per second reciprocal", thus the
37  // reverse is maximum "bits per second".
38  return sliding_queue_.size() == 0
39  ? 0
40  : static_cast<uint64_t>(ceil(1 / sliding_queue_.min()));
41 }
42 
43 BandwidthEstimator::SlidingQueue::SlidingQueue(size_t window_size)
44  : window_size_(window_size) {}
45 
46 void BandwidthEstimator::SlidingQueue::Add(double value) {
47  // Remove elements if needed to form a monotonic non-decreasing sequence.
48  while (!min_.empty() && min_.back() > value)
49  min_.pop_back();
50  min_.push_back(value);
51 
52  if (window_size_ == kUseAllBlocks) {
53  size_++;
54  sum_ += value;
55  min_.resize(1); // Keep only the minimum one.
56  return;
57  }
58 
59  window_.push_back(value);
60  sum_ += value;
61 
62  if (window_.size() <= window_size_) {
63  size_++;
64  return;
65  }
66 
67  if (min_.front() == window_.front())
68  min_.pop_front();
69 
70  sum_ -= window_.front();
71  window_.pop_front();
72 }
73 
74 } // namespace shaka
All the methods that are virtual are virtual for mocking.
void AddBlock(uint64_t size, double duration)