1 /*
2 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11 #include "modules/pacing/interval_budget.h"
12
13 #include <algorithm>
14
15 #include "rtc_base/numerics/safe_conversions.h"
16
17 namespace webrtc {
18 namespace {
19 constexpr int64_t kWindowMs = 500;
20 }
21
IntervalBudget(int initial_target_rate_kbps)22 IntervalBudget::IntervalBudget(int initial_target_rate_kbps)
23 : IntervalBudget(initial_target_rate_kbps, false) {}
24
IntervalBudget(int initial_target_rate_kbps,bool can_build_up_underuse)25 IntervalBudget::IntervalBudget(int initial_target_rate_kbps,
26 bool can_build_up_underuse)
27 : bytes_remaining_(0), can_build_up_underuse_(can_build_up_underuse) {
28 set_target_rate_kbps(initial_target_rate_kbps);
29 }
30
set_target_rate_kbps(int target_rate_kbps)31 void IntervalBudget::set_target_rate_kbps(int target_rate_kbps) {
32 target_rate_kbps_ = target_rate_kbps;
33 max_bytes_in_budget_ = (kWindowMs * target_rate_kbps_) / 8;
34 bytes_remaining_ = std::min(std::max(-max_bytes_in_budget_, bytes_remaining_),
35 max_bytes_in_budget_);
36 }
37
IncreaseBudget(int64_t delta_time_ms)38 void IntervalBudget::IncreaseBudget(int64_t delta_time_ms) {
39 int64_t bytes = target_rate_kbps_ * delta_time_ms / 8;
40 if (bytes_remaining_ < 0 || can_build_up_underuse_) {
41 // We overused last interval, compensate this interval.
42 bytes_remaining_ = std::min(bytes_remaining_ + bytes, max_bytes_in_budget_);
43 } else {
44 // If we underused last interval we can't use it this interval.
45 bytes_remaining_ = std::min(bytes, max_bytes_in_budget_);
46 }
47 }
48
UseBudget(size_t bytes)49 void IntervalBudget::UseBudget(size_t bytes) {
50 bytes_remaining_ = std::max(bytes_remaining_ - static_cast<int>(bytes),
51 -max_bytes_in_budget_);
52 }
53
bytes_remaining() const54 size_t IntervalBudget::bytes_remaining() const {
55 return rtc::saturated_cast<size_t>(std::max<int64_t>(0, bytes_remaining_));
56 }
57
budget_ratio() const58 double IntervalBudget::budget_ratio() const {
59 if (max_bytes_in_budget_ == 0)
60 return 0.0;
61 return static_cast<double>(bytes_remaining_) / max_bytes_in_budget_;
62 }
63
target_rate_kbps() const64 int IntervalBudget::target_rate_kbps() const {
65 return target_rate_kbps_;
66 }
67
68 } // namespace webrtc
69