interval_budget.cc (2359B)
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 #include <cstddef> 15 #include <cstdint> 16 17 #include "rtc_base/numerics/safe_conversions.h" 18 19 namespace webrtc { 20 namespace { 21 constexpr int64_t kWindowMs = 500; 22 } // namespace 23 24 IntervalBudget::IntervalBudget(int initial_target_rate_kbps) 25 : IntervalBudget(initial_target_rate_kbps, false) {} 26 27 IntervalBudget::IntervalBudget(int initial_target_rate_kbps, 28 bool can_build_up_underuse) 29 : bytes_remaining_(0), can_build_up_underuse_(can_build_up_underuse) { 30 set_target_rate_kbps(initial_target_rate_kbps); 31 } 32 33 void IntervalBudget::set_target_rate_kbps(int target_rate_kbps) { 34 target_rate_kbps_ = target_rate_kbps; 35 max_bytes_in_budget_ = (kWindowMs * target_rate_kbps_) / 8; 36 bytes_remaining_ = std::min(std::max(-max_bytes_in_budget_, bytes_remaining_), 37 max_bytes_in_budget_); 38 } 39 40 void IntervalBudget::IncreaseBudget(int64_t delta_time_ms) { 41 int64_t bytes = target_rate_kbps_ * delta_time_ms / 8; 42 if (bytes_remaining_ < 0 || can_build_up_underuse_) { 43 // We overused last interval, compensate this interval. 44 bytes_remaining_ = std::min(bytes_remaining_ + bytes, max_bytes_in_budget_); 45 } else { 46 // If we underused last interval we can't use it this interval. 47 bytes_remaining_ = std::min(bytes, max_bytes_in_budget_); 48 } 49 } 50 51 void IntervalBudget::UseBudget(size_t bytes) { 52 bytes_remaining_ = std::max(bytes_remaining_ - static_cast<int>(bytes), 53 -max_bytes_in_budget_); 54 } 55 56 size_t IntervalBudget::bytes_remaining() const { 57 return saturated_cast<size_t>(std::max<int64_t>(0, bytes_remaining_)); 58 } 59 60 double IntervalBudget::budget_ratio() const { 61 if (max_bytes_in_budget_ == 0) 62 return 0.0; 63 return static_cast<double>(bytes_remaining_) / max_bytes_in_budget_; 64 } 65 66 int IntervalBudget::target_rate_kbps() const { 67 return target_rate_kbps_; 68 } 69 70 } // namespace webrtc