Skip to main content

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 (`A_hat(i) = beta * R_hat(i)`,
317                // section 5.5), or what a probe measured when the sender has less to send
318                // than that: backing off from the received rate of an application-limited
319                // sender would cut the estimate to a fraction of what it sends, and the bound
320                // below would then cut it again on every update (1.5 times a fifth of the
321                // target is less than the target). The measurement backs off with the
322                // estimate: over-use says the path carries less than the probe saw, so the
323                // estimate never climbs back above where it backed off to until a new probe
324                // measures the path, and over-use that lasts with a sender that still sends
325                // less than the measurement brings both down by the decrease factor each
326                // time.
327                //
328                // A sender received at the measurement or above it is not application
329                // limited: the received rate is the path's, and the estimate follows it as
330                // the draft has it, however many updates the over-use lasts. (Taking the
331                // measurement there, which is the estimate itself from the second update on,
332                // multiplied the estimate by the decrease factor on every feedback report:
333                // 268 to 100 kbit/s in six reports, 0.3 s, while 213 to 252 kbit/s arrived.)
334                // The measurement only ever lowers the estimate here: over-use does not raise
335                // an estimate that rests on a probe.
336                let decreased = match self.measured_rate {
337                    Some(measured) if received < measured => {
338                        measured.min(self.target) * self.decrease_factor
339                    }
340                    Some(_) => (received * self.decrease_factor).min(self.target),
341                    None => received * self.decrease_factor,
342                };
343                self.target = decreased.clamp(self.min, self.max);
344                if self.measured_rate.is_some() {
345                    self.measured_rate = Some(self.target);
346                }
347                self.last_change = Some(now);
348            }
349
350            RateControlState::Increase => {
351                // The received rate rising above the band means the congestion level changed:
352                // forget the average and go back to a multiplicative increase.
353                if let (Some(received), Some((_, high))) = (received, self.convergence.band())
354                    && received > high
355                {
356                    self.convergence.reset();
357                }
358
359                // A_hat(i) < 1.5 * R_hat(i): the estimate does not run away from what is
360                // sent. One and a half times what is received, or what a probe measured the
361                // path to deliver when that is more: a measurement is a bound in itself,
362                // with no margin on top, so an estimate that rests on a probe never passes
363                // what the probe saw. An estimate already at or above the bound stays where
364                // it is.
365                let bound = self.bound(received);
366                if self.received_rate_bound == ReceivedRateBound::LimitsIncrease
367                    && bound.is_some_and(|bound| self.target >= bound)
368                {
369                    self.last_change = Some(now);
370                    return self.target;
371                }
372
373                let increased = if self.convergence.band().is_some() {
374                    // Close to convergence: about half a packet per response time.
375                    let response_time = Duration::from_millis(100) + self.round_trip_time;
376                    let alpha =
377                        0.5 * (elapsed.as_secs_f64() / response_time.as_secs_f64()).min(1.0);
378                    self.target + (alpha * self.expected_packet_size_bits()).max(1_000.0)
379                } else {
380                    // `increase_factor` is per second; scale it to the time actually elapsed.
381                    let eta = self.increase_factor.powf(elapsed.as_secs_f64().min(1.0));
382                    (self.target * eta).max(self.target + 1_000.0)
383                };
384                self.target = increased
385                    .min(bound.unwrap_or(f64::INFINITY))
386                    .clamp(self.min, self.max);
387                self.last_change = Some(now);
388            }
389        }
390
391        // The inequality as a clamp: in every state.
392        if self.received_rate_bound == ReceivedRateBound::Clamps
393            && let Some(bound) = self.bound(received)
394        {
395            self.target = self.target.min(bound).clamp(self.min, self.max);
396        }
397
398        self.target
399    }
400
401    /// The bound of section 5.5 for a received rate: one and a half times it, or what a probe
402    /// measured when that is more. `None` while the received rate is unknown.
403    fn bound(&self, received: Option<f64>) -> Option<f64> {
404        received.map(|received| {
405            (MAX_ESTIMATE_TO_RECEIVED_RATIO * received).max(self.measured_rate.unwrap_or(0.0))
406        })
407    }
408
409    /// The size of a packet of a 30 frames-per-second stream at the current target, in bits
410    /// (section 5.5: `bits_per_frame = A_hat / 30`, split into packets of at most 1200 bytes).
411    fn expected_packet_size_bits(&self) -> f64 {
412        let bits_per_frame = self.target / 30.0;
413        let packets_per_frame = (bits_per_frame / (1_200.0 * 8.0)).ceil().max(1.0);
414        bits_per_frame / packets_per_frame
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421
422    const MIN: f64 = 100_000.0;
423    const MAX: f64 = 10_000_000.0;
424
425    fn controller() -> RateController {
426        RateController::new(1_000_000.0, MIN, MAX)
427    }
428
429    /// Overuse backs off to a fraction of what is being **received**, not of the target. On a path
430    /// delivering far less than the sender is aiming for, those differ by the whole overshoot.
431    #[test]
432    fn overuse_backs_off_from_the_received_rate() {
433        let epoch = Instant::now();
434        let mut controller = RateController::new(2_000_000.0, MIN, MAX);
435
436        let target = controller.update(epoch, Usage::Over, Some(600_000.0));
437
438        assert!(
439            (target - 510_000.0).abs() < 1.0,
440            "expected 0.85 × 600 kb/s, got {target}"
441        );
442    }
443
444    /// A quiet path climbs.
445    #[test]
446    fn a_quiet_path_increases() {
447        let epoch = Instant::now();
448        let mut controller = controller();
449
450        let mut at = epoch;
451        let before = controller.target();
452        for _ in 0..10 {
453            at += DEFAULT_RATE_CONTROL_INTERVAL;
454            controller.update(at, Usage::Normal, Some(1_000_000.0));
455        }
456
457        assert!(
458            controller.target() > before,
459            "a healthy path should be probed for more: {before} → {}",
460            controller.target()
461        );
462    }
463
464    /// And climbs **carefully** once near a ceiling it has already hit, rather than overshooting
465    /// straight back into congestion.
466    #[test]
467    fn it_climbs_carefully_near_a_known_ceiling() {
468        let epoch = Instant::now();
469        let mut controller = controller();
470
471        // Establish a ceiling.
472        let mut at = epoch;
473        controller.update(at, Usage::Over, Some(1_000_000.0));
474        let after_backoff = controller.target();
475
476        // Climb back towards it.
477        let mut steps = 0;
478        while controller.target() < after_backoff * 1.5 && steps < 200 {
479            at += DEFAULT_RATE_CONTROL_INTERVAL;
480            controller.update(at, Usage::Normal, Some(1_000_000.0));
481            steps += 1;
482        }
483
484        assert!(
485            steps > 5,
486            "approaching a known ceiling should take several steps, took {steps}"
487        );
488    }
489
490    /// Without a received rate the controller holds. Guessing here is how an estimate collapses on
491    /// a feedback gap.
492    #[test]
493    fn it_holds_when_the_received_rate_is_unknown() {
494        let epoch = Instant::now();
495        let mut controller = controller();
496        let before = controller.target();
497
498        let target = controller.update(epoch, Usage::Over, None);
499
500        assert_eq!(before, target, "no rate to back off from means no change");
501    }
502
503    /// One clamp, from configuration (D3). Upstream clamps twice with two different hard-coded
504    /// ranges that disagree.
505    #[test]
506    fn the_target_stays_within_configured_bounds() {
507        let epoch = Instant::now();
508        let mut controller = RateController::new(MIN, MIN, 500_000.0);
509
510        let mut at = epoch;
511        for _ in 0..500 {
512            at += DEFAULT_RATE_CONTROL_INTERVAL;
513            controller.update(at, Usage::Normal, Some(10_000_000.0));
514        }
515        assert!(
516            controller.target() <= 500_000.0,
517            "ceiling breached: {}",
518            controller.target()
519        );
520
521        for _ in 0..50 {
522            at += DEFAULT_RATE_CONTROL_INTERVAL;
523            controller.update(at, Usage::Over, Some(1.0));
524        }
525        assert!(
526            controller.target() >= MIN,
527            "floor breached: {}",
528            controller.target()
529        );
530    }
531
532    /// A decrease is immediate, and an increase is proportional to the time since the last
533    /// update (section 5.5: eta = 1.08^min(dt, 1 s)), so how often the controller runs does not
534    /// change how fast it climbs.
535    #[test]
536    fn an_increase_scales_with_elapsed_time_and_a_decrease_is_immediate() {
537        let epoch = Instant::now();
538        let mut controller = controller();
539
540        controller.update(epoch, Usage::Normal, Some(1_000_000.0));
541        let after_first = controller.target();
542        controller.update(
543            epoch + Duration::from_millis(500),
544            Usage::Normal,
545            Some(1_000_000.0),
546        );
547        let expected = after_first * 1.08f64.powf(0.5);
548        assert!(
549            (controller.target() - expected).abs() < 1.0,
550            "half a second is 1.08^0.5: expected {expected}, got {}",
551            controller.target()
552        );
553
554        let before_backoff = controller.target();
555        controller.update(
556            epoch + Duration::from_millis(501),
557            Usage::Over,
558            Some(500_000.0),
559        );
560        assert!(
561            (controller.target() - 425_000.0).abs() < 1.0,
562            "a decrease is not delayed: {before_backoff} to {}",
563            controller.target()
564        );
565    }
566
567    /// Section 5.5: A_hat(i) < 1.5 * R_hat(i). A sender with less to send than the estimate
568    /// allows must not let the estimate climb to the maximum (draft-ietf-rmcat-gcc.md bug G1).
569    #[test]
570    fn the_estimate_stays_within_one_and_a_half_times_the_received_rate() {
571        let epoch = Instant::now();
572        let mut controller = RateController::new(300_000.0, MIN, MAX);
573
574        let mut at = epoch;
575        for _ in 0..600 {
576            at += Duration::from_millis(100);
577            controller.update(at, Usage::Normal, Some(200_000.0));
578        }
579
580        assert!(
581            (controller.target() - 300_000.0).abs() < 1.0,
582            "1.5 x 200 kbit/s, got {}",
583            controller.target()
584        );
585    }
586
587    /// Section 5.5: the bound is for a sender that "is unable to produce a bit stream with the
588    /// bitrate the congestion controller is asking for"; the estimate is lowered "As soon as
589    /// over-use has been detected" and for nothing else. An estimate of 1 Mbit/s whose sender
590    /// goes down to its audio (76 kbit/s received, no over-use) is held for as long as that
591    /// lasts, is not increased meanwhile, and climbs again from where it was held once the
592    /// sender sends more.
593    #[test]
594    fn an_estimate_above_the_bound_is_held_and_not_lowered() {
595        let epoch = Instant::now();
596        let mut controller = RateController::new(1_000_000.0, MIN, MAX);
597
598        let mut at = epoch;
599        for _ in 0..600 {
600            at += Duration::from_millis(100);
601            let target = controller.update(at, Usage::Normal, Some(76_000.0));
602            assert_eq!(1_000_000.0, target, "held, neither lowered nor increased");
603        }
604
605        // The video is back at the held estimate: the climb goes on from there, at 8% a
606        // second and not by the whole minute at once.
607        at += Duration::from_millis(100);
608        let target = controller.update(at, Usage::Normal, Some(900_000.0));
609        assert!(
610            target > 1_000_000.0 && target < 1_010_000.0,
611            "one step of 100 ms at 8% a second from the held estimate, got {target}"
612        );
613    }
614
615    /// Held is not frozen: over-use while the sender sends less than the estimate lowers it
616    /// as section 5.5 has it, to beta times the received rate.
617    #[test]
618    fn over_use_lowers_an_estimate_that_was_held_above_the_bound() {
619        let epoch = Instant::now();
620        let mut controller = RateController::new(1_000_000.0, MIN, MAX);
621        let mut at = epoch;
622        for _ in 0..10 {
623            at += Duration::from_millis(100);
624            controller.update(at, Usage::Normal, Some(400_000.0));
625        }
626        assert_eq!(1_000_000.0, controller.target());
627
628        at += Duration::from_millis(100);
629        let target = controller.update(at, Usage::Over, Some(400_000.0));
630        assert!(
631            (target - 340_000.0).abs() < 1.0,
632            "0.85 x 400 kbit/s, got {target}"
633        );
634    }
635
636    /// The inequality read as a clamp ([`ReceivedRateBound::Clamps`]): the same estimate is
637    /// brought down to one and a half times what is received, with usage normal.
638    #[test]
639    fn the_bound_as_a_clamp_lowers_an_estimate_to_one_and_a_half_times_the_received_rate() {
640        let epoch = Instant::now();
641        let mut controller = RateController::new(1_000_000.0, MIN, MAX)
642            .with_received_rate_bound(ReceivedRateBound::Clamps);
643
644        let target = controller.update(
645            epoch + Duration::from_millis(100),
646            Usage::Normal,
647            Some(76_000.0),
648        );
649
650        assert!(
651            (target - 114_000.0).abs() < 1.0,
652            "1.5 x 76 kbit/s, got {target}"
653        );
654
655        // In every state: under-use holds the estimate (section 5.5), and the clamp still
656        // brings it to the bound.
657        let mut controller = RateController::new(1_000_000.0, MIN, MAX)
658            .with_received_rate_bound(ReceivedRateBound::Clamps);
659        let target = controller.update(
660            epoch + Duration::from_millis(100),
661            Usage::Under,
662            Some(76_000.0),
663        );
664        assert_eq!(RateControlState::Hold, controller.state());
665        assert!(
666            (target - 114_000.0).abs() < 1.0,
667            "1.5 x 76 kbit/s held, got {target}"
668        );
669    }
670
671    /// Section 5.5: close to convergence the increase is additive,
672    /// `A_hat += max(1000, alpha * expected_packet_size_bits)` with
673    /// `alpha = 0.5 * min(dt / (100 ms + rtt), 1)`.
674    #[test]
675    fn the_additive_increase_is_half_a_packet_per_response_time() {
676        let epoch = Instant::now();
677        let mut controller = RateController::new(2_000_000.0, MIN, MAX);
678        controller.set_round_trip_time(Duration::from_millis(100));
679
680        // A decrease at 1 Mbit/s measures the convergence point; the target is 850 kbit/s.
681        controller.update(epoch, Usage::Over, Some(1_000_000.0));
682        assert!((controller.target() - 850_000.0).abs() < 1.0);
683        // Decrease, then Hold for one normal reading.
684        controller.update(
685            epoch + Duration::from_millis(100),
686            Usage::Normal,
687            Some(1_000_000.0),
688        );
689        assert_eq!(RateControlState::Hold, controller.state());
690        assert!((controller.target() - 850_000.0).abs() < 1.0);
691
692        // 100 ms after the last change with a 200 ms response time: alpha = 0.25. At 850 kbit/s
693        // a frame is 28 333 bits in three packets of 9 444 bits.
694        controller.update(
695            epoch + Duration::from_millis(100),
696            Usage::Normal,
697            Some(1_000_000.0),
698        );
699        assert_eq!(RateControlState::Increase, controller.state());
700        let expected = 850_000.0 + 0.25 * (850_000.0 / 30.0 / 3.0);
701        assert!(
702            (controller.target() - expected).abs() < 1.0,
703            "expected {expected}, got {}",
704            controller.target()
705        );
706    }
707
708    /// Section 5.5: a received rate above three deviations of the average seen at decrease means
709    /// the congestion level changed: the average is reset and the increase is multiplicative
710    /// again (draft-ietf-rmcat-gcc.md bug G3: the controller stayed additive for ever).
711    #[test]
712    fn a_received_rate_above_the_convergence_band_returns_to_multiplicative_increase() {
713        let epoch = Instant::now();
714        let mut controller = RateController::new(2_000_000.0, MIN, 100_000_000.0);
715
716        controller.update(epoch, Usage::Over, Some(1_000_000.0));
717        let (low, high) = controller
718            .convergence_band()
719            .expect("measured at the decrease");
720        assert!(low < 1_000_000.0 && high > 1_000_000.0);
721        assert!(
722            high < 1_100_000.0,
723            "three deviations at 1 Mbit/s is about 60 kbit/s"
724        );
725
726        // The path widens and the sender follows its target: the received rate is the target.
727        let mut at = epoch;
728        let mut received = controller.target();
729        while controller.convergence_band().is_some() {
730            at += Duration::from_millis(100);
731            received = controller.update(at, Usage::Normal, Some(received));
732            assert!(
733                at < epoch + Duration::from_secs(60),
734                "the band was never left: target {}",
735                controller.target()
736            );
737        }
738
739        // From here one second of quiet is 8%.
740        let before = controller.target();
741        for _ in 0..10 {
742            at += Duration::from_millis(100);
743            received = controller.update(at, Usage::Normal, Some(received));
744        }
745        assert!(
746            (controller.target() / before - 1.08).abs() < 0.001,
747            "expected 8% in a second, got {}",
748            controller.target() / before
749        );
750    }
751
752    /// A decrease far below the average seen so far means the path lost capacity: the average
753    /// restarts from the new rate.
754    #[test]
755    fn a_decrease_far_below_the_band_restarts_the_average() {
756        let epoch = Instant::now();
757        let mut controller = RateController::new(2_000_000.0, MIN, MAX);
758
759        controller.update(epoch, Usage::Over, Some(1_000_000.0));
760        controller.update(
761            epoch + Duration::from_millis(100),
762            Usage::Over,
763            Some(300_000.0),
764        );
765
766        let (low, high) = controller.convergence_band().expect("still measured");
767        assert!(
768            low < 300_000.0 && high > 300_000.0 && high < 400_000.0,
769            "the band is around 300 kbit/s, not an average with 1 Mbit/s: {low}..{high}"
770        );
771    }
772
773    /// An application-limited sender (a fifth of the target) over-uses the path with a probe
774    /// cluster: the estimate backs off from the probe's measurement, not from what the
775    /// application sends, and the updates that follow keep it there instead of cutting it to
776    /// one and a half times the received rate again and again (which spiralled the target
777    /// down to the minimum).
778    #[test]
779    fn over_use_after_a_probe_backs_off_from_the_measurement_and_stays() {
780        let epoch = Instant::now();
781        let mut controller = RateController::new(2_000_000.0, MIN, MAX);
782        controller.set_measured_rate(Some(2_000_000.0));
783        let received = Some(400_000.0);
784
785        let mut at = epoch;
786        let backed_off = controller.update(at, Usage::Over, received);
787        assert!(
788            (backed_off - 1_700_000.0).abs() < 1.0,
789            "0.85 × the measured 2 Mbit/s, got {backed_off}"
790        );
791        for usage in [Usage::Normal, Usage::Normal, Usage::Normal, Usage::Under] {
792            at += DEFAULT_RATE_CONTROL_INTERVAL;
793            let target = controller.update(at, usage, received);
794            assert!(
795                (target - backed_off).abs() < 1.0,
796                "the estimate rests where it backed off to: {target} after {usage:?}"
797            );
798        }
799
800        // Over-use that lasts brings it down by the decrease factor each time.
801        at += DEFAULT_RATE_CONTROL_INTERVAL;
802        let again = controller.update(at, Usage::Over, received);
803        assert!((again - 0.85 * backed_off).abs() < 1.0, "{again}");
804    }
805
806    /// draft-ietf-rmcat-gcc-02 section 5.5, `A_hat(i) = beta * R_hat(i)`, while a probe's
807    /// measurement is held and the sender is received at that measurement or above it (it is
808    /// not application limited): over-use that lasts through several feedback reports keeps
809    /// the estimate at 0.85 times the received rate. It was multiplied by 0.85 on every
810    /// report instead (the measurement, which is the estimate itself after the first cut,
811    /// was taken for what the path delivers): 268 kbit/s fell to the 100 kbit/s floor in six
812    /// reports while 213 to 252 kbit/s arrived (`tests/capacity_cap_video_rtc2rtc.rs`'s
813    /// path, trace of run 45489776509).
814    #[test]
815    fn lasting_over_use_with_a_probe_measurement_follows_the_received_rate() {
816        let epoch = Instant::now();
817        let mut controller = RateController::new(268_000.0, MIN, MAX);
818        controller.set_measured_rate(Some(238_000.0));
819        let received = [
820            252_000.0, 242_000.0, 242_000.0, 252_000.0, 232_000.0, 213_000.0,
821        ];
822        let mut targets = Vec::new();
823        for (index, received) in received.into_iter().enumerate() {
824            let at = epoch + Duration::from_millis(60 * index as u64);
825            targets.push(controller.update(at, Usage::Over, Some(received)).round());
826        }
827        // 0.85 times what arrived, never raised by a later report that shows more.
828        assert_eq!(
829            vec![
830                214_200.0, 205_700.0, 205_700.0, 205_700.0, 197_200.0, 181_050.0
831            ],
832            targets
833        );
834    }
835
836    /// Over-use that lasts through several updates, answered by the first cut: with the
837    /// default, a second cut waits a round trip (here 100 ms, so the update 50 ms later holds
838    /// and the one 100 ms later cuts again), as libwebrtc's `TimeToReduceFurther` does; with
839    /// the draft as written every update cuts.
840    #[test]
841    fn lasting_over_use_cuts_once_per_round_trip() {
842        let epoch = Instant::now();
843        let run = |once: bool| {
844            let mut controller =
845                RateController::new(1_000_000.0, MIN, MAX).with_one_decrease_per_round_trip(once);
846            controller.set_round_trip_time(Duration::from_millis(100));
847            [0u64, 50, 100].map(|ms| {
848                controller.update(
849                    epoch + Duration::from_millis(ms),
850                    Usage::Over,
851                    Some(900_000.0),
852                )
853            })
854        };
855        assert_eq!([765_000.0, 765_000.0, 765_000.0], run(true).map(f64::round));
856        assert_eq!(
857            [765_000.0, 765_000.0, 765_000.0],
858            run(false).map(f64::round)
859        );
860        // The cut is from the received rate: repeated, it compounds only as the received
861        // rate follows. With the received rate falling with the target, the draft cuts again
862        // on every update.
863        let follow = |once: bool| {
864            let mut controller =
865                RateController::new(1_000_000.0, MIN, MAX).with_one_decrease_per_round_trip(once);
866            controller.set_round_trip_time(Duration::from_millis(100));
867            let mut received = 900_000.0;
868            let mut targets = Vec::new();
869            for ms in [0u64, 50, 100] {
870                let target = controller.update(
871                    epoch + Duration::from_millis(ms),
872                    Usage::Over,
873                    Some(received),
874                );
875                targets.push(target.round());
876                received = target;
877            }
878            targets
879        };
880        assert_eq!(vec![765_000.0, 765_000.0, 650_250.0], follow(true));
881        assert_eq!(vec![765_000.0, 650_250.0, 552_713.0], follow(false));
882    }
883
884    /// The received rate falling below half the target is news: the cut is not held back.
885    #[test]
886    fn a_collapse_of_the_received_rate_cuts_at_once() {
887        let epoch = Instant::now();
888        let mut controller = RateController::new(1_000_000.0, MIN, MAX);
889        controller.set_round_trip_time(Duration::from_millis(200));
890        controller.update(epoch, Usage::Over, Some(900_000.0));
891        let target = controller.update(
892            epoch + Duration::from_millis(20),
893            Usage::Over,
894            Some(300_000.0),
895        );
896        assert_eq!(255_000.0, target.round());
897    }
898}