use super::overuse::Usage;
use super::state::RateControlState;
use std::time::{Duration, Instant};
pub const DEFAULT_DECREASE_FACTOR: f64 = 0.85;
pub const DEFAULT_INCREASE_FACTOR: f64 = 1.08;
pub const DEFAULT_RATE_CONTROL_INTERVAL: Duration = Duration::from_millis(200);
pub const DEFAULT_ROUND_TRIP_TIME: Duration = Duration::from_millis(200);
pub const MAX_ESTIMATE_TO_RECEIVED_RATIO: f64 = 1.5;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReceivedRateBound {
#[default]
LimitsIncrease,
Clamps,
}
const CONVERGENCE_SMOOTHING: f64 = 0.95;
#[derive(Debug, Clone, Copy)]
struct Convergence {
average_kbps: Option<f64>,
normalised_variance_kbps: f64,
}
impl Convergence {
const INITIAL_VARIANCE: f64 = 0.4;
const MIN_VARIANCE: f64 = 0.4;
const MAX_VARIANCE: f64 = 2.5;
fn new() -> Self {
Self {
average_kbps: None,
normalised_variance_kbps: Self::INITIAL_VARIANCE,
}
}
fn three_sigma(&self, average_kbps: f64) -> f64 {
3.0 * (self.normalised_variance_kbps * average_kbps).sqrt()
}
fn band(&self) -> Option<(f64, f64)> {
let average = self.average_kbps?;
let spread = self.three_sigma(average);
Some((
(average - spread).max(0.0) * 1_000.0,
(average + spread) * 1_000.0,
))
}
fn reset(&mut self) {
self.average_kbps = None;
}
fn on_decrease(&mut self, received: f64) {
let sample = received / 1_000.0;
let average = match self.average_kbps {
None => sample,
Some(average) => {
CONVERGENCE_SMOOTHING * average + (1.0 - CONVERGENCE_SMOOTHING) * sample
}
};
let error = average - sample;
self.normalised_variance_kbps = (CONVERGENCE_SMOOTHING * self.normalised_variance_kbps
+ (1.0 - CONVERGENCE_SMOOTHING) * error * error / average.max(1.0))
.clamp(Self::MIN_VARIANCE, Self::MAX_VARIANCE);
self.average_kbps = Some(average);
}
}
#[derive(Debug, Clone)]
pub struct RateController {
state: RateControlState,
target: f64,
min: f64,
max: f64,
decrease_factor: f64,
increase_factor: f64,
round_trip_time: Duration,
measured_rate: Option<f64>,
convergence: Convergence,
last_change: Option<Instant>,
one_decrease_per_round_trip: bool,
last_decrease: Option<Instant>,
received_rate_bound: ReceivedRateBound,
}
impl RateController {
pub fn new(initial: f64, min: f64, max: f64) -> Self {
Self {
state: RateControlState::default(),
target: initial.clamp(min, max),
min,
max,
decrease_factor: DEFAULT_DECREASE_FACTOR,
increase_factor: DEFAULT_INCREASE_FACTOR,
round_trip_time: DEFAULT_ROUND_TRIP_TIME,
measured_rate: None,
convergence: Convergence::new(),
last_change: None,
one_decrease_per_round_trip: false,
last_decrease: None,
received_rate_bound: ReceivedRateBound::default(),
}
}
pub fn with_received_rate_bound(mut self, received_rate_bound: ReceivedRateBound) -> Self {
self.received_rate_bound = received_rate_bound;
self
}
pub fn with_one_decrease_per_round_trip(mut self, enabled: bool) -> Self {
self.one_decrease_per_round_trip = enabled;
self
}
pub fn with_decrease_factor(mut self, decrease_factor: f64) -> Self {
self.decrease_factor = decrease_factor;
self
}
pub fn target(&self) -> f64 {
self.target
}
pub fn state(&self) -> RateControlState {
self.state
}
pub fn set_round_trip_time(&mut self, round_trip_time: Duration) {
self.round_trip_time = round_trip_time;
}
pub fn set_bounds(&mut self, min: f64, max: f64) {
self.min = min;
self.max = max.max(min);
self.target = self.target.clamp(self.min, self.max);
}
pub fn set_target(&mut self, target: f64) {
self.target = target.clamp(self.min, self.max);
}
pub fn set_measured_rate(&mut self, measured: Option<f64>) {
self.measured_rate = measured;
}
pub fn reset_convergence(&mut self) {
self.convergence.reset();
}
pub fn convergence_band(&self) -> Option<(f64, f64)> {
self.convergence.band()
}
pub fn update(&mut self, now: Instant, usage: Usage, received: Option<f64>) -> f64 {
self.state = self.state.next(usage);
let elapsed = self
.last_change
.map_or(DEFAULT_RATE_CONTROL_INTERVAL, |last| {
now.saturating_duration_since(last)
});
match self.state {
RateControlState::Hold => {}
RateControlState::Decrease => {
let Some(received) = received else {
return self.target;
};
if self.one_decrease_per_round_trip
&& let Some(last) = self.last_decrease
&& now.saturating_duration_since(last)
< self
.round_trip_time
.clamp(Duration::from_millis(10), Duration::from_millis(200))
&& received >= 0.5 * self.target
{
return self.target;
}
self.last_decrease = Some(now);
if let Some((low, _)) = self.convergence.band()
&& received < low
{
self.convergence.reset();
}
self.convergence.on_decrease(received);
let delivered = self
.measured_rate
.map_or(received, |measured| measured.max(received).min(self.target));
self.target = (delivered * self.decrease_factor).clamp(self.min, self.max);
if self.measured_rate.is_some() {
self.measured_rate = Some(self.target);
}
self.last_change = Some(now);
}
RateControlState::Increase => {
if let (Some(received), Some((_, high))) = (received, self.convergence.band())
&& received > high
{
self.convergence.reset();
}
let bound = self.bound(received);
if self.received_rate_bound == ReceivedRateBound::LimitsIncrease
&& bound.is_some_and(|bound| self.target >= bound)
{
self.last_change = Some(now);
return self.target;
}
let increased = if self.convergence.band().is_some() {
let response_time = Duration::from_millis(100) + self.round_trip_time;
let alpha =
0.5 * (elapsed.as_secs_f64() / response_time.as_secs_f64()).min(1.0);
self.target + (alpha * self.expected_packet_size_bits()).max(1_000.0)
} else {
let eta = self.increase_factor.powf(elapsed.as_secs_f64().min(1.0));
(self.target * eta).max(self.target + 1_000.0)
};
self.target = increased
.min(bound.unwrap_or(f64::INFINITY))
.clamp(self.min, self.max);
self.last_change = Some(now);
}
}
if self.received_rate_bound == ReceivedRateBound::Clamps
&& let Some(bound) = self.bound(received)
{
self.target = self.target.min(bound).clamp(self.min, self.max);
}
self.target
}
fn bound(&self, received: Option<f64>) -> Option<f64> {
received.map(|received| {
(MAX_ESTIMATE_TO_RECEIVED_RATIO * received).max(self.measured_rate.unwrap_or(0.0))
})
}
fn expected_packet_size_bits(&self) -> f64 {
let bits_per_frame = self.target / 30.0;
let packets_per_frame = (bits_per_frame / (1_200.0 * 8.0)).ceil().max(1.0);
bits_per_frame / packets_per_frame
}
}
#[cfg(test)]
mod tests {
use super::*;
const MIN: f64 = 100_000.0;
const MAX: f64 = 10_000_000.0;
fn controller() -> RateController {
RateController::new(1_000_000.0, MIN, MAX)
}
#[test]
fn overuse_backs_off_from_the_received_rate() {
let epoch = Instant::now();
let mut controller = RateController::new(2_000_000.0, MIN, MAX);
let target = controller.update(epoch, Usage::Over, Some(600_000.0));
assert!(
(target - 510_000.0).abs() < 1.0,
"expected 0.85 × 600 kb/s, got {target}"
);
}
#[test]
fn a_quiet_path_increases() {
let epoch = Instant::now();
let mut controller = controller();
let mut at = epoch;
let before = controller.target();
for _ in 0..10 {
at += DEFAULT_RATE_CONTROL_INTERVAL;
controller.update(at, Usage::Normal, Some(1_000_000.0));
}
assert!(
controller.target() > before,
"a healthy path should be probed for more: {before} → {}",
controller.target()
);
}
#[test]
fn it_climbs_carefully_near_a_known_ceiling() {
let epoch = Instant::now();
let mut controller = controller();
let mut at = epoch;
controller.update(at, Usage::Over, Some(1_000_000.0));
let after_backoff = controller.target();
let mut steps = 0;
while controller.target() < after_backoff * 1.5 && steps < 200 {
at += DEFAULT_RATE_CONTROL_INTERVAL;
controller.update(at, Usage::Normal, Some(1_000_000.0));
steps += 1;
}
assert!(
steps > 5,
"approaching a known ceiling should take several steps, took {steps}"
);
}
#[test]
fn it_holds_when_the_received_rate_is_unknown() {
let epoch = Instant::now();
let mut controller = controller();
let before = controller.target();
let target = controller.update(epoch, Usage::Over, None);
assert_eq!(before, target, "no rate to back off from means no change");
}
#[test]
fn the_target_stays_within_configured_bounds() {
let epoch = Instant::now();
let mut controller = RateController::new(MIN, MIN, 500_000.0);
let mut at = epoch;
for _ in 0..500 {
at += DEFAULT_RATE_CONTROL_INTERVAL;
controller.update(at, Usage::Normal, Some(10_000_000.0));
}
assert!(
controller.target() <= 500_000.0,
"ceiling breached: {}",
controller.target()
);
for _ in 0..50 {
at += DEFAULT_RATE_CONTROL_INTERVAL;
controller.update(at, Usage::Over, Some(1.0));
}
assert!(
controller.target() >= MIN,
"floor breached: {}",
controller.target()
);
}
#[test]
fn an_increase_scales_with_elapsed_time_and_a_decrease_is_immediate() {
let epoch = Instant::now();
let mut controller = controller();
controller.update(epoch, Usage::Normal, Some(1_000_000.0));
let after_first = controller.target();
controller.update(
epoch + Duration::from_millis(500),
Usage::Normal,
Some(1_000_000.0),
);
let expected = after_first * 1.08f64.powf(0.5);
assert!(
(controller.target() - expected).abs() < 1.0,
"half a second is 1.08^0.5: expected {expected}, got {}",
controller.target()
);
let before_backoff = controller.target();
controller.update(
epoch + Duration::from_millis(501),
Usage::Over,
Some(500_000.0),
);
assert!(
(controller.target() - 425_000.0).abs() < 1.0,
"a decrease is not delayed: {before_backoff} to {}",
controller.target()
);
}
#[test]
fn the_estimate_stays_within_one_and_a_half_times_the_received_rate() {
let epoch = Instant::now();
let mut controller = RateController::new(300_000.0, MIN, MAX);
let mut at = epoch;
for _ in 0..600 {
at += Duration::from_millis(100);
controller.update(at, Usage::Normal, Some(200_000.0));
}
assert!(
(controller.target() - 300_000.0).abs() < 1.0,
"1.5 x 200 kbit/s, got {}",
controller.target()
);
}
#[test]
fn an_estimate_above_the_bound_is_held_and_not_lowered() {
let epoch = Instant::now();
let mut controller = RateController::new(1_000_000.0, MIN, MAX);
let mut at = epoch;
for _ in 0..600 {
at += Duration::from_millis(100);
let target = controller.update(at, Usage::Normal, Some(76_000.0));
assert_eq!(1_000_000.0, target, "held, neither lowered nor increased");
}
at += Duration::from_millis(100);
let target = controller.update(at, Usage::Normal, Some(900_000.0));
assert!(
target > 1_000_000.0 && target < 1_010_000.0,
"one step of 100 ms at 8% a second from the held estimate, got {target}"
);
}
#[test]
fn over_use_lowers_an_estimate_that_was_held_above_the_bound() {
let epoch = Instant::now();
let mut controller = RateController::new(1_000_000.0, MIN, MAX);
let mut at = epoch;
for _ in 0..10 {
at += Duration::from_millis(100);
controller.update(at, Usage::Normal, Some(400_000.0));
}
assert_eq!(1_000_000.0, controller.target());
at += Duration::from_millis(100);
let target = controller.update(at, Usage::Over, Some(400_000.0));
assert!(
(target - 340_000.0).abs() < 1.0,
"0.85 x 400 kbit/s, got {target}"
);
}
#[test]
fn the_bound_as_a_clamp_lowers_an_estimate_to_one_and_a_half_times_the_received_rate() {
let epoch = Instant::now();
let mut controller = RateController::new(1_000_000.0, MIN, MAX)
.with_received_rate_bound(ReceivedRateBound::Clamps);
let target = controller.update(
epoch + Duration::from_millis(100),
Usage::Normal,
Some(76_000.0),
);
assert!(
(target - 114_000.0).abs() < 1.0,
"1.5 x 76 kbit/s, got {target}"
);
let mut controller = RateController::new(1_000_000.0, MIN, MAX)
.with_received_rate_bound(ReceivedRateBound::Clamps);
let target = controller.update(
epoch + Duration::from_millis(100),
Usage::Under,
Some(76_000.0),
);
assert_eq!(RateControlState::Hold, controller.state());
assert!(
(target - 114_000.0).abs() < 1.0,
"1.5 x 76 kbit/s held, got {target}"
);
}
#[test]
fn the_additive_increase_is_half_a_packet_per_response_time() {
let epoch = Instant::now();
let mut controller = RateController::new(2_000_000.0, MIN, MAX);
controller.set_round_trip_time(Duration::from_millis(100));
controller.update(epoch, Usage::Over, Some(1_000_000.0));
assert!((controller.target() - 850_000.0).abs() < 1.0);
controller.update(
epoch + Duration::from_millis(100),
Usage::Normal,
Some(1_000_000.0),
);
assert_eq!(RateControlState::Hold, controller.state());
assert!((controller.target() - 850_000.0).abs() < 1.0);
controller.update(
epoch + Duration::from_millis(100),
Usage::Normal,
Some(1_000_000.0),
);
assert_eq!(RateControlState::Increase, controller.state());
let expected = 850_000.0 + 0.25 * (850_000.0 / 30.0 / 3.0);
assert!(
(controller.target() - expected).abs() < 1.0,
"expected {expected}, got {}",
controller.target()
);
}
#[test]
fn a_received_rate_above_the_convergence_band_returns_to_multiplicative_increase() {
let epoch = Instant::now();
let mut controller = RateController::new(2_000_000.0, MIN, 100_000_000.0);
controller.update(epoch, Usage::Over, Some(1_000_000.0));
let (low, high) = controller
.convergence_band()
.expect("measured at the decrease");
assert!(low < 1_000_000.0 && high > 1_000_000.0);
assert!(
high < 1_100_000.0,
"three deviations at 1 Mbit/s is about 60 kbit/s"
);
let mut at = epoch;
let mut received = controller.target();
while controller.convergence_band().is_some() {
at += Duration::from_millis(100);
received = controller.update(at, Usage::Normal, Some(received));
assert!(
at < epoch + Duration::from_secs(60),
"the band was never left: target {}",
controller.target()
);
}
let before = controller.target();
for _ in 0..10 {
at += Duration::from_millis(100);
received = controller.update(at, Usage::Normal, Some(received));
}
assert!(
(controller.target() / before - 1.08).abs() < 0.001,
"expected 8% in a second, got {}",
controller.target() / before
);
}
#[test]
fn a_decrease_far_below_the_band_restarts_the_average() {
let epoch = Instant::now();
let mut controller = RateController::new(2_000_000.0, MIN, MAX);
controller.update(epoch, Usage::Over, Some(1_000_000.0));
controller.update(
epoch + Duration::from_millis(100),
Usage::Over,
Some(300_000.0),
);
let (low, high) = controller.convergence_band().expect("still measured");
assert!(
low < 300_000.0 && high > 300_000.0 && high < 400_000.0,
"the band is around 300 kbit/s, not an average with 1 Mbit/s: {low}..{high}"
);
}
#[test]
fn over_use_after_a_probe_backs_off_from_the_measurement_and_stays() {
let epoch = Instant::now();
let mut controller = RateController::new(2_000_000.0, MIN, MAX);
controller.set_measured_rate(Some(2_000_000.0));
let received = Some(400_000.0);
let mut at = epoch;
let backed_off = controller.update(at, Usage::Over, received);
assert!(
(backed_off - 1_700_000.0).abs() < 1.0,
"0.85 × the measured 2 Mbit/s, got {backed_off}"
);
for usage in [Usage::Normal, Usage::Normal, Usage::Normal, Usage::Under] {
at += DEFAULT_RATE_CONTROL_INTERVAL;
let target = controller.update(at, usage, received);
assert!(
(target - backed_off).abs() < 1.0,
"the estimate rests where it backed off to: {target} after {usage:?}"
);
}
at += DEFAULT_RATE_CONTROL_INTERVAL;
let again = controller.update(at, Usage::Over, received);
assert!((again - 0.85 * backed_off).abs() < 1.0, "{again}");
}
#[test]
fn lasting_over_use_cuts_once_per_round_trip() {
let epoch = Instant::now();
let run = |once: bool| {
let mut controller =
RateController::new(1_000_000.0, MIN, MAX).with_one_decrease_per_round_trip(once);
controller.set_round_trip_time(Duration::from_millis(100));
[0u64, 50, 100].map(|ms| {
controller.update(
epoch + Duration::from_millis(ms),
Usage::Over,
Some(900_000.0),
)
})
};
assert_eq!([765_000.0, 765_000.0, 765_000.0], run(true).map(f64::round));
assert_eq!(
[765_000.0, 765_000.0, 765_000.0],
run(false).map(f64::round)
);
let follow = |once: bool| {
let mut controller =
RateController::new(1_000_000.0, MIN, MAX).with_one_decrease_per_round_trip(once);
controller.set_round_trip_time(Duration::from_millis(100));
let mut received = 900_000.0;
let mut targets = Vec::new();
for ms in [0u64, 50, 100] {
let target = controller.update(
epoch + Duration::from_millis(ms),
Usage::Over,
Some(received),
);
targets.push(target.round());
received = target;
}
targets
};
assert_eq!(vec![765_000.0, 765_000.0, 650_250.0], follow(true));
assert_eq!(vec![765_000.0, 650_250.0, 552_713.0], follow(false));
}
#[test]
fn a_collapse_of_the_received_rate_cuts_at_once() {
let epoch = Instant::now();
let mut controller = RateController::new(1_000_000.0, MIN, MAX);
controller.set_round_trip_time(Duration::from_millis(200));
controller.update(epoch, Usage::Over, Some(900_000.0));
let target = controller.update(
epoch + Duration::from_millis(20),
Usage::Over,
Some(300_000.0),
);
assert_eq!(255_000.0, target.round());
}
}