rtci_interceptor/gcc/rate_control.rs
1//! AIMD: what the target bitrate does in each state (draft-ietf-rmcat-gcc-02 section 5.5).
2
3use super::overuse::Usage;
4use super::state::RateControlState;
5use std::time::{Duration, Instant};
6
7/// Multiplier applied to the *received* rate when backing off (beta, section 5.5).
8pub const DEFAULT_DECREASE_FACTOR: f64 = 0.85;
9
10/// Multiplicative growth per second while far from convergence (the 1.08 of eta, section 5.5).
11pub const DEFAULT_INCREASE_FACTOR: f64 = 1.08;
12
13/// The step the first update of a controller is taken to cover, before there is a previous
14/// update to measure from.
15pub const DEFAULT_RATE_CONTROL_INTERVAL: Duration = Duration::from_millis(200);
16
17/// The round trip time assumed until one has been measured.
18pub const DEFAULT_ROUND_TRIP_TIME: Duration = Duration::from_millis(200);
19
20/// How far the estimate may be above the received rate: `A_hat(i) < 1.5 * R_hat(i)`.
21pub const MAX_ESTIMATE_TO_RECEIVED_RATIO: f64 = 1.5;
22
23/// What the bound of the estimate by the received rate (`A_hat(i) < 1.5 * R_hat(i)`,
24/// draft-ietf-rmcat-gcc-02 section 5.5) does to an estimate that is above it.
25///
26/// The draft introduces the bound for a sender that has less to send than the estimate
27/// allows: "we must make sure that our estimate does not diverge from the rate at which the
28/// sender is actually sending. Thus, if the sender is unable to produce a bit stream with the
29/// bitrate the congestion controller is asking for, the available bandwidth estimate should
30/// stay within a given bound. Therefore we introduce a threshold `A_hat(i) < 1.5 * R_hat(i)`".
31/// It does not say what becomes of an estimate that the received rate has fallen away from:
32/// a camera that was turned off, a key frame that has left the measurement window, a call
33/// that has only just started at the start rate.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35pub enum ReceivedRateBound {
36 /// The bound limits the increase: an estimate at or above it is not increased, and is
37 /// left where it is until over-use sets it to `beta * R_hat` (which is within the
38 /// bound). The default.
39 ///
40 /// The same section lowers the estimate for one reason, "As soon as over-use has been
41 /// detected", holds it "constant" in the Hold state and has it "increased" on "every
42 /// update" in the Increase state; lowering it because the application sends less does
43 /// none of these, and tells an application whose camera is off that a path which has
44 /// shown no congestion carries one and a half times its audio. libwebrtc, the
45 /// implementation the draft's section 8 names, limits the increase as well
46 /// (`modules/remote_bitrate_estimator/aimd_rate_control.cc:235-249, 266`: "We limit the
47 /// new bitrate based on the troughput to avoid unlimited bitrate increases",
48 /// `if (current_bitrate_ < increase_limit)`, `std::min(increased_bitrate,
49 /// increase_limit)`).
50 #[default]
51 LimitsIncrease,
52 /// The inequality holds after every update: an estimate above the bound is brought down
53 /// to it, in every state, with no congestion signal. The inequality read by itself.
54 Clamps,
55}
56
57/// Smoothing of the average and the variance of the received rate measured at each decrease
58/// ("an exponential moving average with smoothing factor 0.95", section 5.5).
59const CONVERGENCE_SMOOTHING: f64 = 0.95;
60
61/// The average received rate seen in the Decrease state, and its variance: the estimate of where
62/// the path's capacity is.
63///
64/// Rates are kept in kbit/s and the variance is normalised by the average, as libwebrtc's
65/// `LinkCapacityEstimator` keeps them, so the deviation scales with the rate and the constants
66/// below mean the same at 100 kbit/s and at 100 Mbit/s.
67#[derive(Debug, Clone, Copy)]
68struct Convergence {
69 average_kbps: Option<f64>,
70 /// Variance of the samples around the average, divided by the average.
71 normalised_variance_kbps: f64,
72}
73
74impl Convergence {
75 const INITIAL_VARIANCE: f64 = 0.4;
76 const MIN_VARIANCE: f64 = 0.4;
77 const MAX_VARIANCE: f64 = 2.5;
78
79 fn new() -> Self {
80 Self {
81 average_kbps: None,
82 normalised_variance_kbps: Self::INITIAL_VARIANCE,
83 }
84 }
85
86 /// Three standard deviations, in kbit/s, around `average_kbps`.
87 fn three_sigma(&self, average_kbps: f64) -> f64 {
88 3.0 * (self.normalised_variance_kbps * average_kbps).sqrt()
89 }
90
91 /// The band of received rates that count as "close to convergence", in bits per second.
92 fn band(&self) -> Option<(f64, f64)> {
93 let average = self.average_kbps?;
94 let spread = self.three_sigma(average);
95 Some((
96 (average - spread).max(0.0) * 1_000.0,
97 (average + spread) * 1_000.0,
98 ))
99 }
100
101 fn reset(&mut self) {
102 self.average_kbps = None;
103 }
104
105 /// Fold in the received rate measured at a decrease.
106 fn on_decrease(&mut self, received: f64) {
107 let sample = received / 1_000.0;
108 let average = match self.average_kbps {
109 None => sample,
110 Some(average) => {
111 CONVERGENCE_SMOOTHING * average + (1.0 - CONVERGENCE_SMOOTHING) * sample
112 }
113 };
114 let error = average - sample;
115 self.normalised_variance_kbps = (CONVERGENCE_SMOOTHING * self.normalised_variance_kbps
116 + (1.0 - CONVERGENCE_SMOOTHING) * error * error / average.max(1.0))
117 .clamp(Self::MIN_VARIANCE, Self::MAX_VARIANCE);
118 self.average_kbps = Some(average);
119 }
120}
121
122/// The AIMD controller: a usage signal and a received rate in, a target bitrate out.
123///
124/// # Additive versus multiplicative increase
125///
126/// Climbing multiplicatively is fast but overshoots, which on a path already known to be near its
127/// limit means congesting it again immediately. So the controller keeps the average and the
128/// deviation of the received rate measured each time it backed off, and climbs additively, about
129/// half a packet per response time, while the received rate is within three deviations of that
130/// average ("close to convergence"). When the received rate rises above the band the path has
131/// changed: the average is forgotten and the climb is multiplicative again, 8% per second.
132///
133/// # The bound
134///
135/// The estimate is verified by over-using the path, so it must not drift away from what is
136/// actually sent: it is not increased past 1.5 times the received rate. Without the bound a
137/// sender that has less to send than the estimate allows (a muted source, a static screen) lets
138/// the estimate climb to the configured maximum, and overshoots by that much when it has
139/// something to send again. An estimate that is above the bound because the sender now sends
140/// less than it did is held, not lowered ([`ReceivedRateBound`]): only over-use lowers it.
141#[derive(Debug, Clone)]
142pub struct RateController {
143 state: RateControlState,
144 /// Current target, in bits per second.
145 target: f64,
146 min: f64,
147 max: f64,
148 decrease_factor: f64,
149 increase_factor: f64,
150 round_trip_time: Duration,
151 /// What a probe measured the path to deliver, while that is news the received rate has
152 /// not caught up with.
153 measured_rate: Option<f64>,
154 convergence: Convergence,
155 last_change: Option<Instant>,
156 /// Whether a decrease is taken at most once per round trip (see
157 /// [`with_one_decrease_per_round_trip`](Self::with_one_decrease_per_round_trip)).
158 one_decrease_per_round_trip: bool,
159 /// When the target was last decreased.
160 last_decrease: Option<Instant>,
161 received_rate_bound: ReceivedRateBound,
162}
163
164impl RateController {
165 /// A controller starting at `initial`, clamped to `min..=max`.
166 ///
167 /// **One clamp, from configuration** — see D3. Upstream clamps in two places with two different
168 /// hard-coded ranges, and they disagree.
169 pub fn new(initial: f64, min: f64, max: f64) -> Self {
170 Self {
171 state: RateControlState::default(),
172 target: initial.clamp(min, max),
173 min,
174 max,
175 decrease_factor: DEFAULT_DECREASE_FACTOR,
176 increase_factor: DEFAULT_INCREASE_FACTOR,
177 round_trip_time: DEFAULT_ROUND_TRIP_TIME,
178 measured_rate: None,
179 convergence: Convergence::new(),
180 last_change: None,
181 one_decrease_per_round_trip: false,
182 last_decrease: None,
183 received_rate_bound: ReceivedRateBound::default(),
184 }
185 }
186
187 /// What the bound by the received rate does to an estimate above it: see
188 /// [`ReceivedRateBound`].
189 pub fn with_received_rate_bound(mut self, received_rate_bound: ReceivedRateBound) -> Self {
190 self.received_rate_bound = received_rate_bound;
191 self
192 }
193
194 /// Whether over-use lowers the target at most once per round trip, or on every update
195 /// while it lasts (the default).
196 ///
197 /// draft-ietf-rmcat-gcc-02 section 5.5 stays in Decrease while over-use lasts and sets
198 /// `A_hat = beta * R_hat` on each update: `false`, the default. The estimate then follows
199 /// the received rate down as its measurement window empties of what arrived before the
200 /// path changed, which is what matters when a path loses most of its capacity at once
201 /// (`tests/capacity_cap_video_rtc2rtc.rs`: a 300 kbit/s cap under a sender at 1 Mbit/s
202 /// freezes the video 0.56 to 1.26 s and leaves the oldest picture 1.68 to 2.48 s old;
203 /// with one decrease per round trip 0.85 to 1.36 s and 2.33 to 2.61 s).
204 ///
205 /// `true` is libwebrtc's form (`AimdRateControl::TimeToReduceFurther`): a further cut
206 /// waits one round trip (held within 10 to 200 ms) unless the received rate has fallen
207 /// below half the target. Two flows sharing a bottleneck then keep a shorter queue
208 /// (`rtci-interceptor/tests/rfc8836_multi_flow.rs`: mean 2.8 ms and 95th percentile 10.8 ms
209 /// of queueing delay, against 18.5 ms and 93 ms with the draft's form; the shares are
210 /// 0.48 / 0.50 and 0.49 / 0.49).
211 pub fn with_one_decrease_per_round_trip(mut self, enabled: bool) -> Self {
212 self.one_decrease_per_round_trip = enabled;
213 self
214 }
215
216 /// How hard to back off, as a fraction of the received rate.
217 pub fn with_decrease_factor(mut self, decrease_factor: f64) -> Self {
218 self.decrease_factor = decrease_factor;
219 self
220 }
221
222 /// The current target, in bits per second.
223 pub fn target(&self) -> f64 {
224 self.target
225 }
226
227 /// The current state.
228 pub fn state(&self) -> RateControlState {
229 self.state
230 }
231
232 /// The round trip time the additive increase is scaled by (`response_time = 100 ms + rtt`).
233 pub fn set_round_trip_time(&mut self, round_trip_time: Duration) {
234 self.round_trip_time = round_trip_time;
235 }
236
237 /// Change the range the target is held in, and bring the target into it.
238 pub fn set_bounds(&mut self, min: f64, max: f64) {
239 self.min = min;
240 self.max = max.max(min);
241 self.target = self.target.clamp(self.min, self.max);
242 }
243
244 /// Replace the target, as when the path changed and the old estimate describes nothing.
245 pub fn set_target(&mut self, target: f64) {
246 self.target = target.clamp(self.min, self.max);
247 }
248
249 /// A rate the path was measured to deliver apart from the running received rate (a probe
250 /// cluster), or `None` to forget it. While set, the estimate may be as high as this
251 /// measurement even where one and a half times the received rate (the bound of section
252 /// 5.5) is less: the received rate lags a sender that has only just been told it may
253 /// send more, and would pull the estimate straight back to where it was. Over-use lowers
254 /// it to where the estimate backs off to.
255 pub fn set_measured_rate(&mut self, measured: Option<f64>) {
256 self.measured_rate = measured;
257 }
258
259 /// Forget where the path's capacity was thought to be: the next climb is multiplicative.
260 pub fn reset_convergence(&mut self) {
261 self.convergence.reset();
262 }
263
264 /// The band of received rates within which the controller considers itself close to
265 /// convergence, in bits per second, once a decrease has measured one.
266 pub fn convergence_band(&self) -> Option<(f64, f64)> {
267 self.convergence.band()
268 }
269
270 /// Advance the state with a usage signal and move the target accordingly.
271 ///
272 /// `received` is what the remote is actually getting (R_hat), from
273 /// [`RateCalculator`](super::rate_calc::RateCalculator). It is `None` until enough has
274 /// arrived to measure, and while it is unknown a decrease holds and an increase is unbounded
275 /// by it — there is no meaningful figure to act on.
276 pub fn update(&mut self, now: Instant, usage: Usage, received: Option<f64>) -> f64 {
277 self.state = self.state.next(usage);
278
279 // Both increases are scaled by the time since the last update, so how often this is
280 // called does not change how fast the target climbs.
281 let elapsed = self
282 .last_change
283 .map_or(DEFAULT_RATE_CONTROL_INTERVAL, |last| {
284 now.saturating_duration_since(last)
285 });
286
287 match self.state {
288 RateControlState::Hold => {}
289
290 RateControlState::Decrease => {
291 // Back off from what is being *received*, not from the current target. If the
292 // path is delivering less than the target, the target is the wrong thing to
293 // scale.
294 let Some(received) = received else {
295 return self.target;
296 };
297 if self.one_decrease_per_round_trip
298 && let Some(last) = self.last_decrease
299 && now.saturating_duration_since(last)
300 < self
301 .round_trip_time
302 .clamp(Duration::from_millis(10), Duration::from_millis(200))
303 && received >= 0.5 * self.target
304 {
305 return self.target;
306 }
307 self.last_decrease = Some(now);
308 // A rate far below the average means the path lost capacity: the old average
309 // describes a path that is gone.
310 if let Some((low, _)) = self.convergence.band()
311 && received < low
312 {
313 self.convergence.reset();
314 }
315 self.convergence.on_decrease(received);
316 // What the path delivers is the received rate, or what a probe measured when
317 // the sender has less to send than that: backing off from the received rate
318 // of an application-limited sender would cut the estimate to a fraction of
319 // what it sends, and the bound below would then cut it again on every update
320 // (1.5 times a fifth of the target is less than the target). The measurement
321 // backs off with the estimate: over-use says the path carries less than the
322 // probe saw, so the estimate never climbs back above where it backed off to
323 // until a new probe measures the path, and over-use that lasts brings both
324 // down by the decrease factor each time.
325 let delivered = self
326 .measured_rate
327 .map_or(received, |measured| measured.max(received).min(self.target));
328 self.target = (delivered * self.decrease_factor).clamp(self.min, self.max);
329 if self.measured_rate.is_some() {
330 self.measured_rate = Some(self.target);
331 }
332 self.last_change = Some(now);
333 }
334
335 RateControlState::Increase => {
336 // The received rate rising above the band means the congestion level changed:
337 // forget the average and go back to a multiplicative increase.
338 if let (Some(received), Some((_, high))) = (received, self.convergence.band())
339 && received > high
340 {
341 self.convergence.reset();
342 }
343
344 // A_hat(i) < 1.5 * R_hat(i): the estimate does not run away from what is
345 // sent. One and a half times what is received, or what a probe measured the
346 // path to deliver when that is more: a measurement is a bound in itself,
347 // with no margin on top, so an estimate that rests on a probe never passes
348 // what the probe saw. An estimate already at or above the bound stays where
349 // it is.
350 let bound = self.bound(received);
351 if self.received_rate_bound == ReceivedRateBound::LimitsIncrease
352 && bound.is_some_and(|bound| self.target >= bound)
353 {
354 self.last_change = Some(now);
355 return self.target;
356 }
357
358 let increased = if self.convergence.band().is_some() {
359 // Close to convergence: about half a packet per response time.
360 let response_time = Duration::from_millis(100) + self.round_trip_time;
361 let alpha =
362 0.5 * (elapsed.as_secs_f64() / response_time.as_secs_f64()).min(1.0);
363 self.target + (alpha * self.expected_packet_size_bits()).max(1_000.0)
364 } else {
365 // `increase_factor` is per second; scale it to the time actually elapsed.
366 let eta = self.increase_factor.powf(elapsed.as_secs_f64().min(1.0));
367 (self.target * eta).max(self.target + 1_000.0)
368 };
369 self.target = increased
370 .min(bound.unwrap_or(f64::INFINITY))
371 .clamp(self.min, self.max);
372 self.last_change = Some(now);
373 }
374 }
375
376 // The inequality as a clamp: in every state.
377 if self.received_rate_bound == ReceivedRateBound::Clamps
378 && let Some(bound) = self.bound(received)
379 {
380 self.target = self.target.min(bound).clamp(self.min, self.max);
381 }
382
383 self.target
384 }
385
386 /// The bound of section 5.5 for a received rate: one and a half times it, or what a probe
387 /// measured when that is more. `None` while the received rate is unknown.
388 fn bound(&self, received: Option<f64>) -> Option<f64> {
389 received.map(|received| {
390 (MAX_ESTIMATE_TO_RECEIVED_RATIO * received).max(self.measured_rate.unwrap_or(0.0))
391 })
392 }
393
394 /// The size of a packet of a 30 frames-per-second stream at the current target, in bits
395 /// (section 5.5: `bits_per_frame = A_hat / 30`, split into packets of at most 1200 bytes).
396 fn expected_packet_size_bits(&self) -> f64 {
397 let bits_per_frame = self.target / 30.0;
398 let packets_per_frame = (bits_per_frame / (1_200.0 * 8.0)).ceil().max(1.0);
399 bits_per_frame / packets_per_frame
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406
407 const MIN: f64 = 100_000.0;
408 const MAX: f64 = 10_000_000.0;
409
410 fn controller() -> RateController {
411 RateController::new(1_000_000.0, MIN, MAX)
412 }
413
414 /// Overuse backs off to a fraction of what is being **received**, not of the target. On a path
415 /// delivering far less than the sender is aiming for, those differ by the whole overshoot.
416 #[test]
417 fn overuse_backs_off_from_the_received_rate() {
418 let epoch = Instant::now();
419 let mut controller = RateController::new(2_000_000.0, MIN, MAX);
420
421 let target = controller.update(epoch, Usage::Over, Some(600_000.0));
422
423 assert!(
424 (target - 510_000.0).abs() < 1.0,
425 "expected 0.85 × 600 kb/s, got {target}"
426 );
427 }
428
429 /// A quiet path climbs.
430 #[test]
431 fn a_quiet_path_increases() {
432 let epoch = Instant::now();
433 let mut controller = controller();
434
435 let mut at = epoch;
436 let before = controller.target();
437 for _ in 0..10 {
438 at += DEFAULT_RATE_CONTROL_INTERVAL;
439 controller.update(at, Usage::Normal, Some(1_000_000.0));
440 }
441
442 assert!(
443 controller.target() > before,
444 "a healthy path should be probed for more: {before} → {}",
445 controller.target()
446 );
447 }
448
449 /// And climbs **carefully** once near a ceiling it has already hit, rather than overshooting
450 /// straight back into congestion.
451 #[test]
452 fn it_climbs_carefully_near_a_known_ceiling() {
453 let epoch = Instant::now();
454 let mut controller = controller();
455
456 // Establish a ceiling.
457 let mut at = epoch;
458 controller.update(at, Usage::Over, Some(1_000_000.0));
459 let after_backoff = controller.target();
460
461 // Climb back towards it.
462 let mut steps = 0;
463 while controller.target() < after_backoff * 1.5 && steps < 200 {
464 at += DEFAULT_RATE_CONTROL_INTERVAL;
465 controller.update(at, Usage::Normal, Some(1_000_000.0));
466 steps += 1;
467 }
468
469 assert!(
470 steps > 5,
471 "approaching a known ceiling should take several steps, took {steps}"
472 );
473 }
474
475 /// Without a received rate the controller holds. Guessing here is how an estimate collapses on
476 /// a feedback gap.
477 #[test]
478 fn it_holds_when_the_received_rate_is_unknown() {
479 let epoch = Instant::now();
480 let mut controller = controller();
481 let before = controller.target();
482
483 let target = controller.update(epoch, Usage::Over, None);
484
485 assert_eq!(before, target, "no rate to back off from means no change");
486 }
487
488 /// One clamp, from configuration (D3). Upstream clamps twice with two different hard-coded
489 /// ranges that disagree.
490 #[test]
491 fn the_target_stays_within_configured_bounds() {
492 let epoch = Instant::now();
493 let mut controller = RateController::new(MIN, MIN, 500_000.0);
494
495 let mut at = epoch;
496 for _ in 0..500 {
497 at += DEFAULT_RATE_CONTROL_INTERVAL;
498 controller.update(at, Usage::Normal, Some(10_000_000.0));
499 }
500 assert!(
501 controller.target() <= 500_000.0,
502 "ceiling breached: {}",
503 controller.target()
504 );
505
506 for _ in 0..50 {
507 at += DEFAULT_RATE_CONTROL_INTERVAL;
508 controller.update(at, Usage::Over, Some(1.0));
509 }
510 assert!(
511 controller.target() >= MIN,
512 "floor breached: {}",
513 controller.target()
514 );
515 }
516
517 /// A decrease is immediate, and an increase is proportional to the time since the last
518 /// update (section 5.5: eta = 1.08^min(dt, 1 s)), so how often the controller runs does not
519 /// change how fast it climbs.
520 #[test]
521 fn an_increase_scales_with_elapsed_time_and_a_decrease_is_immediate() {
522 let epoch = Instant::now();
523 let mut controller = controller();
524
525 controller.update(epoch, Usage::Normal, Some(1_000_000.0));
526 let after_first = controller.target();
527 controller.update(
528 epoch + Duration::from_millis(500),
529 Usage::Normal,
530 Some(1_000_000.0),
531 );
532 let expected = after_first * 1.08f64.powf(0.5);
533 assert!(
534 (controller.target() - expected).abs() < 1.0,
535 "half a second is 1.08^0.5: expected {expected}, got {}",
536 controller.target()
537 );
538
539 let before_backoff = controller.target();
540 controller.update(
541 epoch + Duration::from_millis(501),
542 Usage::Over,
543 Some(500_000.0),
544 );
545 assert!(
546 (controller.target() - 425_000.0).abs() < 1.0,
547 "a decrease is not delayed: {before_backoff} to {}",
548 controller.target()
549 );
550 }
551
552 /// Section 5.5: A_hat(i) < 1.5 * R_hat(i). A sender with less to send than the estimate
553 /// allows must not let the estimate climb to the maximum (draft-ietf-rmcat-gcc.md bug G1).
554 #[test]
555 fn the_estimate_stays_within_one_and_a_half_times_the_received_rate() {
556 let epoch = Instant::now();
557 let mut controller = RateController::new(300_000.0, MIN, MAX);
558
559 let mut at = epoch;
560 for _ in 0..600 {
561 at += Duration::from_millis(100);
562 controller.update(at, Usage::Normal, Some(200_000.0));
563 }
564
565 assert!(
566 (controller.target() - 300_000.0).abs() < 1.0,
567 "1.5 x 200 kbit/s, got {}",
568 controller.target()
569 );
570 }
571
572 /// Section 5.5: the bound is for a sender that "is unable to produce a bit stream with the
573 /// bitrate the congestion controller is asking for"; the estimate is lowered "As soon as
574 /// over-use has been detected" and for nothing else. An estimate of 1 Mbit/s whose sender
575 /// goes down to its audio (76 kbit/s received, no over-use) is held for as long as that
576 /// lasts, is not increased meanwhile, and climbs again from where it was held once the
577 /// sender sends more.
578 #[test]
579 fn an_estimate_above_the_bound_is_held_and_not_lowered() {
580 let epoch = Instant::now();
581 let mut controller = RateController::new(1_000_000.0, MIN, MAX);
582
583 let mut at = epoch;
584 for _ in 0..600 {
585 at += Duration::from_millis(100);
586 let target = controller.update(at, Usage::Normal, Some(76_000.0));
587 assert_eq!(1_000_000.0, target, "held, neither lowered nor increased");
588 }
589
590 // The video is back at the held estimate: the climb goes on from there, at 8% a
591 // second and not by the whole minute at once.
592 at += Duration::from_millis(100);
593 let target = controller.update(at, Usage::Normal, Some(900_000.0));
594 assert!(
595 target > 1_000_000.0 && target < 1_010_000.0,
596 "one step of 100 ms at 8% a second from the held estimate, got {target}"
597 );
598 }
599
600 /// Held is not frozen: over-use while the sender sends less than the estimate lowers it
601 /// as section 5.5 has it, to beta times the received rate.
602 #[test]
603 fn over_use_lowers_an_estimate_that_was_held_above_the_bound() {
604 let epoch = Instant::now();
605 let mut controller = RateController::new(1_000_000.0, MIN, MAX);
606 let mut at = epoch;
607 for _ in 0..10 {
608 at += Duration::from_millis(100);
609 controller.update(at, Usage::Normal, Some(400_000.0));
610 }
611 assert_eq!(1_000_000.0, controller.target());
612
613 at += Duration::from_millis(100);
614 let target = controller.update(at, Usage::Over, Some(400_000.0));
615 assert!(
616 (target - 340_000.0).abs() < 1.0,
617 "0.85 x 400 kbit/s, got {target}"
618 );
619 }
620
621 /// The inequality read as a clamp ([`ReceivedRateBound::Clamps`]): the same estimate is
622 /// brought down to one and a half times what is received, with usage normal.
623 #[test]
624 fn the_bound_as_a_clamp_lowers_an_estimate_to_one_and_a_half_times_the_received_rate() {
625 let epoch = Instant::now();
626 let mut controller = RateController::new(1_000_000.0, MIN, MAX)
627 .with_received_rate_bound(ReceivedRateBound::Clamps);
628
629 let target = controller.update(
630 epoch + Duration::from_millis(100),
631 Usage::Normal,
632 Some(76_000.0),
633 );
634
635 assert!(
636 (target - 114_000.0).abs() < 1.0,
637 "1.5 x 76 kbit/s, got {target}"
638 );
639
640 // In every state: under-use holds the estimate (section 5.5), and the clamp still
641 // brings it to the bound.
642 let mut controller = RateController::new(1_000_000.0, MIN, MAX)
643 .with_received_rate_bound(ReceivedRateBound::Clamps);
644 let target = controller.update(
645 epoch + Duration::from_millis(100),
646 Usage::Under,
647 Some(76_000.0),
648 );
649 assert_eq!(RateControlState::Hold, controller.state());
650 assert!(
651 (target - 114_000.0).abs() < 1.0,
652 "1.5 x 76 kbit/s held, got {target}"
653 );
654 }
655
656 /// Section 5.5: close to convergence the increase is additive,
657 /// `A_hat += max(1000, alpha * expected_packet_size_bits)` with
658 /// `alpha = 0.5 * min(dt / (100 ms + rtt), 1)`.
659 #[test]
660 fn the_additive_increase_is_half_a_packet_per_response_time() {
661 let epoch = Instant::now();
662 let mut controller = RateController::new(2_000_000.0, MIN, MAX);
663 controller.set_round_trip_time(Duration::from_millis(100));
664
665 // A decrease at 1 Mbit/s measures the convergence point; the target is 850 kbit/s.
666 controller.update(epoch, Usage::Over, Some(1_000_000.0));
667 assert!((controller.target() - 850_000.0).abs() < 1.0);
668 // Decrease, then Hold for one normal reading.
669 controller.update(
670 epoch + Duration::from_millis(100),
671 Usage::Normal,
672 Some(1_000_000.0),
673 );
674 assert_eq!(RateControlState::Hold, controller.state());
675 assert!((controller.target() - 850_000.0).abs() < 1.0);
676
677 // 100 ms after the last change with a 200 ms response time: alpha = 0.25. At 850 kbit/s
678 // a frame is 28 333 bits in three packets of 9 444 bits.
679 controller.update(
680 epoch + Duration::from_millis(100),
681 Usage::Normal,
682 Some(1_000_000.0),
683 );
684 assert_eq!(RateControlState::Increase, controller.state());
685 let expected = 850_000.0 + 0.25 * (850_000.0 / 30.0 / 3.0);
686 assert!(
687 (controller.target() - expected).abs() < 1.0,
688 "expected {expected}, got {}",
689 controller.target()
690 );
691 }
692
693 /// Section 5.5: a received rate above three deviations of the average seen at decrease means
694 /// the congestion level changed: the average is reset and the increase is multiplicative
695 /// again (draft-ietf-rmcat-gcc.md bug G3: the controller stayed additive for ever).
696 #[test]
697 fn a_received_rate_above_the_convergence_band_returns_to_multiplicative_increase() {
698 let epoch = Instant::now();
699 let mut controller = RateController::new(2_000_000.0, MIN, 100_000_000.0);
700
701 controller.update(epoch, Usage::Over, Some(1_000_000.0));
702 let (low, high) = controller
703 .convergence_band()
704 .expect("measured at the decrease");
705 assert!(low < 1_000_000.0 && high > 1_000_000.0);
706 assert!(
707 high < 1_100_000.0,
708 "three deviations at 1 Mbit/s is about 60 kbit/s"
709 );
710
711 // The path widens and the sender follows its target: the received rate is the target.
712 let mut at = epoch;
713 let mut received = controller.target();
714 while controller.convergence_band().is_some() {
715 at += Duration::from_millis(100);
716 received = controller.update(at, Usage::Normal, Some(received));
717 assert!(
718 at < epoch + Duration::from_secs(60),
719 "the band was never left: target {}",
720 controller.target()
721 );
722 }
723
724 // From here one second of quiet is 8%.
725 let before = controller.target();
726 for _ in 0..10 {
727 at += Duration::from_millis(100);
728 received = controller.update(at, Usage::Normal, Some(received));
729 }
730 assert!(
731 (controller.target() / before - 1.08).abs() < 0.001,
732 "expected 8% in a second, got {}",
733 controller.target() / before
734 );
735 }
736
737 /// A decrease far below the average seen so far means the path lost capacity: the average
738 /// restarts from the new rate.
739 #[test]
740 fn a_decrease_far_below_the_band_restarts_the_average() {
741 let epoch = Instant::now();
742 let mut controller = RateController::new(2_000_000.0, MIN, MAX);
743
744 controller.update(epoch, Usage::Over, Some(1_000_000.0));
745 controller.update(
746 epoch + Duration::from_millis(100),
747 Usage::Over,
748 Some(300_000.0),
749 );
750
751 let (low, high) = controller.convergence_band().expect("still measured");
752 assert!(
753 low < 300_000.0 && high > 300_000.0 && high < 400_000.0,
754 "the band is around 300 kbit/s, not an average with 1 Mbit/s: {low}..{high}"
755 );
756 }
757
758 /// An application-limited sender (a fifth of the target) over-uses the path with a probe
759 /// cluster: the estimate backs off from the probe's measurement, not from what the
760 /// application sends, and the updates that follow keep it there instead of cutting it to
761 /// one and a half times the received rate again and again (which spiralled the target
762 /// down to the minimum).
763 #[test]
764 fn over_use_after_a_probe_backs_off_from_the_measurement_and_stays() {
765 let epoch = Instant::now();
766 let mut controller = RateController::new(2_000_000.0, MIN, MAX);
767 controller.set_measured_rate(Some(2_000_000.0));
768 let received = Some(400_000.0);
769
770 let mut at = epoch;
771 let backed_off = controller.update(at, Usage::Over, received);
772 assert!(
773 (backed_off - 1_700_000.0).abs() < 1.0,
774 "0.85 × the measured 2 Mbit/s, got {backed_off}"
775 );
776 for usage in [Usage::Normal, Usage::Normal, Usage::Normal, Usage::Under] {
777 at += DEFAULT_RATE_CONTROL_INTERVAL;
778 let target = controller.update(at, usage, received);
779 assert!(
780 (target - backed_off).abs() < 1.0,
781 "the estimate rests where it backed off to: {target} after {usage:?}"
782 );
783 }
784
785 // Over-use that lasts brings it down by the decrease factor each time.
786 at += DEFAULT_RATE_CONTROL_INTERVAL;
787 let again = controller.update(at, Usage::Over, received);
788 assert!((again - 0.85 * backed_off).abs() < 1.0, "{again}");
789 }
790
791 /// Over-use that lasts through several updates, answered by the first cut: with the
792 /// default, a second cut waits a round trip (here 100 ms, so the update 50 ms later holds
793 /// and the one 100 ms later cuts again), as libwebrtc's `TimeToReduceFurther` does; with
794 /// the draft as written every update cuts.
795 #[test]
796 fn lasting_over_use_cuts_once_per_round_trip() {
797 let epoch = Instant::now();
798 let run = |once: bool| {
799 let mut controller =
800 RateController::new(1_000_000.0, MIN, MAX).with_one_decrease_per_round_trip(once);
801 controller.set_round_trip_time(Duration::from_millis(100));
802 [0u64, 50, 100].map(|ms| {
803 controller.update(
804 epoch + Duration::from_millis(ms),
805 Usage::Over,
806 Some(900_000.0),
807 )
808 })
809 };
810 assert_eq!([765_000.0, 765_000.0, 765_000.0], run(true).map(f64::round));
811 assert_eq!(
812 [765_000.0, 765_000.0, 765_000.0],
813 run(false).map(f64::round)
814 );
815 // The cut is from the received rate: repeated, it compounds only as the received
816 // rate follows. With the received rate falling with the target, the draft cuts again
817 // on every update.
818 let follow = |once: bool| {
819 let mut controller =
820 RateController::new(1_000_000.0, MIN, MAX).with_one_decrease_per_round_trip(once);
821 controller.set_round_trip_time(Duration::from_millis(100));
822 let mut received = 900_000.0;
823 let mut targets = Vec::new();
824 for ms in [0u64, 50, 100] {
825 let target = controller.update(
826 epoch + Duration::from_millis(ms),
827 Usage::Over,
828 Some(received),
829 );
830 targets.push(target.round());
831 received = target;
832 }
833 targets
834 };
835 assert_eq!(vec![765_000.0, 765_000.0, 650_250.0], follow(true));
836 assert_eq!(vec![765_000.0, 650_250.0, 552_713.0], follow(false));
837 }
838
839 /// The received rate falling below half the target is news: the cut is not held back.
840 #[test]
841 fn a_collapse_of_the_received_rate_cuts_at_once() {
842 let epoch = Instant::now();
843 let mut controller = RateController::new(1_000_000.0, MIN, MAX);
844 controller.set_round_trip_time(Duration::from_millis(200));
845 controller.update(epoch, Usage::Over, Some(900_000.0));
846 let target = controller.update(
847 epoch + Duration::from_millis(20),
848 Usage::Over,
849 Some(300_000.0),
850 );
851 assert_eq!(255_000.0, target.round());
852 }
853}