blob: b63bc37149e6c55e910f122b91a394ce6eaad330 [file] [log] [blame]
tschumim82c55932017-07-11 06:56:04 -07001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/pacing/interval_budget.h"
tschumim82c55932017-07-11 06:56:04 -070012
13#include <algorithm>
14
15namespace webrtc {
16namespace {
17constexpr int kWindowMs = 500;
tschumim5afa3f22017-08-18 03:38:49 -070018constexpr int kDeltaTimeMs = 2000;
tschumim82c55932017-07-11 06:56:04 -070019}
20
21IntervalBudget::IntervalBudget(int initial_target_rate_kbps)
22 : IntervalBudget(initial_target_rate_kbps, false) {}
23
24IntervalBudget::IntervalBudget(int initial_target_rate_kbps,
25 bool can_build_up_underuse)
26 : bytes_remaining_(0), can_build_up_underuse_(can_build_up_underuse) {
27 set_target_rate_kbps(initial_target_rate_kbps);
28}
29
30void IntervalBudget::set_target_rate_kbps(int target_rate_kbps) {
31 target_rate_kbps_ = target_rate_kbps;
32 max_bytes_in_budget_ = (kWindowMs * target_rate_kbps_) / 8;
33 bytes_remaining_ = std::min(std::max(-max_bytes_in_budget_, bytes_remaining_),
34 max_bytes_in_budget_);
35}
36
37void IntervalBudget::IncreaseBudget(int64_t delta_time_ms) {
tschumim5afa3f22017-08-18 03:38:49 -070038 RTC_DCHECK_LT(delta_time_ms, kDeltaTimeMs);
tschumim82c55932017-07-11 06:56:04 -070039 int 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
49void IntervalBudget::UseBudget(size_t bytes) {
50 bytes_remaining_ = std::max(bytes_remaining_ - static_cast<int>(bytes),
51 -max_bytes_in_budget_);
52}
53
54size_t IntervalBudget::bytes_remaining() const {
55 return static_cast<size_t>(std::max(0, bytes_remaining_));
56}
57
58int IntervalBudget::budget_level_percent() const {
59 return bytes_remaining_ * 100 / max_bytes_in_budget_;
60}
61
62int IntervalBudget::target_rate_kbps() const {
63 return target_rate_kbps_;
64}
65
66} // namespace webrtc