Skip to main content

rtci_interceptor/gcc/
overuse.rs

1//! Deciding whether the delay trend means the path is congested.
2
3use super::threshold::{AdaptiveThreshold, ThresholdTimeBase};
4use std::time::{Duration, Instant};
5
6/// What the delay signal currently says about the path.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
8pub enum Usage {
9    /// The queue is neither growing nor draining meaningfully.
10    #[default]
11    Normal,
12    /// The queue is growing: more is being sent than the path can carry.
13    Over,
14    /// The queue is draining: there is room the sender is not using.
15    Under,
16}
17
18/// How long the trend must stay outside the threshold before overuse is declared.
19///
20/// Without this any single noisy group would trigger a backoff, and the estimate would sawtooth on
21/// a path that is fine.
22pub const DEFAULT_OVERUSE_TIME: Duration = Duration::from_millis(10);
23
24/// Turns a filtered delay trend into a [`Usage`], with hysteresis.
25///
26/// # Why the debounce
27///
28/// The trend crossing the threshold once means very little — the filter is still noisy, and a
29/// single video frame arriving late will do it. Overuse is only declared when the trend stays
30/// outside **and** has not decreased since the last reading **and** at least two readings agree.
31/// Upstream does the same (`overuse_detector.go`); it is what stops the estimate sawtoothing.
32///
33/// Coming *back* has no such delay: `Normal` and `Under` are declared immediately, because being
34/// slow to notice that a path has recovered wastes capacity for as long as it takes to notice.
35#[derive(Debug, Clone, Copy)]
36pub struct OveruseDetector {
37    threshold: AdaptiveThreshold,
38    overuse_time: Duration,
39    /// When the trend first went outside the threshold in the current run.
40    outside_since: Option<Instant>,
41    /// Consecutive readings outside, so a lone sample cannot trigger.
42    consecutive: u32,
43    /// The previous estimate, to tell a growing queue from one that has stopped growing.
44    previous_estimate_ms: f64,
45    usage: Usage,
46    time_base: ThresholdTimeBase,
47    /// The arrival time of the previous reading's group, for [`ThresholdTimeBase::Arrival`].
48    last_arrival: Option<Duration>,
49}
50
51impl Default for OveruseDetector {
52    fn default() -> Self {
53        Self {
54            threshold: AdaptiveThreshold::new(),
55            overuse_time: DEFAULT_OVERUSE_TIME,
56            outside_since: None,
57            consecutive: 0,
58            previous_estimate_ms: 0.0,
59            usage: Usage::Normal,
60            time_base: ThresholdTimeBase::default(),
61            last_arrival: None,
62        }
63    }
64}
65
66impl OveruseDetector {
67    /// A detector with the draft's tuning.
68    pub fn new() -> Self {
69        Self::default()
70    }
71
72    /// The time step the threshold adapts over ([`ThresholdTimeBase`]).
73    pub fn with_threshold_time_base(mut self, time_base: ThresholdTimeBase) -> Self {
74        self.time_base = time_base;
75        self
76    }
77
78    /// As [`update`](Self::update), with the arrival time of the reading's group on the
79    /// receiver's clock, which [`ThresholdTimeBase::Arrival`] adapts the threshold over.
80    pub fn update_with_arrival(
81        &mut self,
82        now: Instant,
83        arrival: Duration,
84        estimate_ms: f64,
85    ) -> Usage {
86        let usage = self.classify(now, estimate_ms);
87        match self.time_base {
88            ThresholdTimeBase::Departure => {
89                self.threshold.update(now, estimate_ms);
90            }
91            ThresholdTimeBase::Arrival | ThresholdTimeBase::ArrivalCapped => {
92                if let Some(last) = self.last_arrival {
93                    let step = arrival.saturating_sub(last);
94                    let step = if self.time_base == ThresholdTimeBase::ArrivalCapped {
95                        step.min(crate::gcc::threshold::MAX_STEP)
96                    } else {
97                        step
98                    };
99                    self.threshold.update_over(step, estimate_ms);
100                }
101                self.last_arrival = Some(arrival);
102            }
103        }
104        usage
105    }
106
107    /// What the detector currently believes.
108    pub fn usage(&self) -> Usage {
109        self.usage
110    }
111
112    /// The threshold the trend is being compared against, in milliseconds.
113    pub fn threshold_ms(&self) -> f64 {
114        self.threshold.value_ms()
115    }
116
117    /// Fold in one filtered trend reading and return the resulting usage.
118    ///
119    /// `estimate_ms` is the kalman-filtered delay gradient; `now` is when it was measured.
120    pub fn update(&mut self, now: Instant, estimate_ms: f64) -> Usage {
121        self.classify(now, estimate_ms);
122        // The threshold follows the trend, so a persistently jittery path stops reading as
123        // persistently congested. Updated after the comparison, so a reading is judged against the
124        // threshold that was in force when it was taken.
125        self.threshold.update(now, estimate_ms);
126        self.usage
127    }
128
129    fn classify(&mut self, now: Instant, estimate_ms: f64) -> Usage {
130        let threshold_ms = self.threshold.value_ms();
131
132        self.usage = if estimate_ms > threshold_ms {
133            // Growing. Declare overuse only once it has persisted, is still growing, and more than
134            // one reading agrees.
135            let since = *self.outside_since.get_or_insert(now);
136            self.consecutive += 1;
137
138            let long_enough = now.saturating_duration_since(since) >= self.overuse_time;
139            let still_growing = estimate_ms >= self.previous_estimate_ms;
140
141            if long_enough && still_growing && self.consecutive > 1 {
142                Usage::Over
143            } else {
144                // Not yet convinced: hold whatever was believed before rather than flapping.
145                self.usage
146            }
147        } else if estimate_ms < -threshold_ms {
148            self.outside_since = None;
149            self.consecutive = 0;
150            Usage::Under
151        } else {
152            self.outside_since = None;
153            self.consecutive = 0;
154            Usage::Normal
155        };
156
157        self.previous_estimate_ms = estimate_ms;
158        self.usage
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    /// A trend inside the threshold is not congestion, however long it goes on.
167    #[test]
168    fn a_quiet_path_reads_normal() {
169        let epoch = Instant::now();
170        let mut detector = OveruseDetector::new();
171
172        for step in 0..100u64 {
173            let usage = detector.update(epoch + Duration::from_millis(step * 20), 1.0);
174            assert_eq!(Usage::Normal, usage, "at step {step}");
175        }
176    }
177
178    /// A single spike must not trigger a backoff — that is what the debounce is for.
179    #[test]
180    fn one_spike_is_not_overuse() {
181        let epoch = Instant::now();
182        let mut detector = OveruseDetector::new();
183
184        detector.update(epoch, 0.0);
185        let usage = detector.update(epoch + Duration::from_millis(20), 40.0);
186
187        assert_eq!(
188            Usage::Normal,
189            usage,
190            "a lone reading outside the threshold is noise, not congestion"
191        );
192    }
193
194    /// A sustained, growing trend is.
195    #[test]
196    fn a_sustained_growing_trend_is_overuse() {
197        let epoch = Instant::now();
198        let mut detector = OveruseDetector::new();
199
200        let mut usage = Usage::Normal;
201        for step in 0..10u64 {
202            // Growing each time, so `still_growing` holds.
203            usage = detector.update(
204                epoch + Duration::from_millis(step * 20),
205                20.0 + step as f64 * 2.0,
206            );
207        }
208
209        assert_eq!(
210            Usage::Over,
211            usage,
212            "a queue that keeps growing must eventually be declared"
213        );
214    }
215
216    /// Recovery is immediate: once the trend is back inside, the path is usable again and waiting
217    /// to say so wastes capacity.
218    #[test]
219    fn recovery_is_not_debounced() {
220        let epoch = Instant::now();
221        let mut detector = OveruseDetector::new();
222
223        let mut at = epoch;
224        for step in 0..10u64 {
225            at = epoch + Duration::from_millis(step * 20);
226            detector.update(at, 20.0 + step as f64 * 2.0);
227        }
228        assert_eq!(Usage::Over, detector.usage());
229
230        let usage = detector.update(at + Duration::from_millis(20), 0.0);
231        assert_eq!(
232            Usage::Normal,
233            usage,
234            "back inside the threshold must be believed at once"
235        );
236    }
237
238    /// A strongly negative trend is a draining queue: there is room the sender is not using.
239    #[test]
240    fn a_draining_queue_reads_under() {
241        let epoch = Instant::now();
242        let mut detector = OveruseDetector::new();
243
244        let usage = detector.update(epoch, -40.0);
245        assert_eq!(Usage::Under, usage);
246    }
247
248    /// A queue that grew and then *stopped* growing is not still overusing — the trend is high but
249    /// flat, which means the backlog is steady rather than increasing.
250    #[test]
251    fn a_high_but_flat_trend_does_not_re_declare_overuse() {
252        let epoch = Instant::now();
253        let mut detector = OveruseDetector::new();
254
255        // Climb into overuse.
256        let mut at = epoch;
257        for step in 0..10u64 {
258            at = epoch + Duration::from_millis(step * 20);
259            detector.update(at, 20.0 + step as f64 * 2.0);
260        }
261        assert_eq!(Usage::Over, detector.usage());
262
263        // Now flat, and back inside the threshold as it adapts upward.
264        for step in 0..200u64 {
265            at += Duration::from_millis(20);
266            detector.update(at, 1.0);
267            let _ = step;
268        }
269        assert_eq!(
270            Usage::Normal,
271            detector.usage(),
272            "a settled path must return to normal"
273        );
274    }
275
276    /// Section 5.4: "if m(i) < m(i-1), over-use will not be signaled even if all the above
277    /// conditions are met". A trend above the threshold for long enough, but falling, is not
278    /// over-use.
279    #[test]
280    fn a_trend_above_the_threshold_but_falling_is_not_overuse() {
281        let epoch = Instant::now();
282        let mut detector = OveruseDetector::new();
283        for step in 0..10u64 {
284            let usage =
285                detector.update(epoch + Duration::from_millis(step * 20), 40.0 - step as f64);
286            assert_eq!(Usage::Normal, usage, "at step {step}");
287        }
288    }
289
290    /// Section 5.4, overuse_time_th = 10 ms: a growing trend above the threshold is over-use
291    /// once it has lasted 10 ms, not before.
292    #[test]
293    fn overuse_needs_ten_milliseconds_outside_the_threshold() {
294        let epoch = Instant::now();
295        let mut detector = OveruseDetector::new();
296        assert_eq!(Usage::Normal, detector.update(epoch, 20.0));
297        assert_eq!(
298            Usage::Normal,
299            detector.update(epoch + Duration::from_millis(5), 21.0)
300        );
301        assert_eq!(
302            Usage::Normal,
303            detector.update(epoch + Duration::from_millis(9), 22.0)
304        );
305        assert_eq!(
306            Usage::Over,
307            detector.update(epoch + Duration::from_millis(10), 23.0)
308        );
309    }
310
311    /// libwebrtc's time base (`TrendlineEstimator::UpdateThreshold`): the threshold moves over
312    /// the gap between the groups' arrival times, as the draft's, but never by more than a
313    /// 100 ms step; the draft's takes the whole gap.
314    #[test]
315    fn the_capped_arrival_time_base_steps_at_most_100_ms() {
316        let now = Instant::now();
317        let after = |time_base: ThresholdTimeBase, gap_ms: u64| {
318            let mut detector = OveruseDetector::new().with_threshold_time_base(time_base);
319            detector.update_with_arrival(now, Duration::ZERO, 1.0);
320            // The sender's clock does not move: only the arrival gap can step the threshold.
321            detector.update_with_arrival(now, Duration::from_millis(gap_ms), 1.0);
322            detector.threshold_ms()
323        };
324        let capped = ThresholdTimeBase::ArrivalCapped;
325        let draft = ThresholdTimeBase::Arrival;
326        // Inside the cap both take the arrival gap.
327        assert_eq!(after(capped, 60), after(draft, 60));
328        assert!(after(capped, 60) < DEFAULT_THRESHOLD_FOR_TEST);
329        // Beyond it the capped one steps 100 ms, the draft's the whole 400 ms.
330        assert_eq!(after(capped, 400), after(capped, 100));
331        assert!(after(draft, 400) < after(capped, 400));
332        // Departure takes the sender's clock, which did not move.
333        assert_eq!(
334            after(ThresholdTimeBase::Departure, 400),
335            DEFAULT_THRESHOLD_FOR_TEST
336        );
337    }
338
339    const DEFAULT_THRESHOLD_FOR_TEST: f64 = crate::gcc::threshold::DEFAULT_INITIAL_MS;
340    /// draft-ietf-rmcat-gcc-02 section 5.4 as written (`ThresholdTimeBase::Arrival`):
341    /// `del_var_th(i) = del_var_th(i-1) + (t(i)-t(i-1)) * K(i) * (|m(i)| - del_var_th(i-1))`,
342    /// t(i) the arrival time of group i, the step not capped. Two groups 300 ms apart on the
343    /// receiver's clock, read 1 ms apart: the threshold moves by K_u * 300 ms * (20 - 12.5)
344    /// = 22.5 ms. The default (`Departure`) takes libwebrtc's step, here the 1 ms between the
345    /// readings.
346    #[test]
347    fn the_drafts_threshold_adapts_over_the_uncapped_arrival_gap() {
348        let epoch = Instant::now();
349        let mut draft = OveruseDetector::new().with_threshold_time_base(ThresholdTimeBase::Arrival);
350        draft.update_with_arrival(epoch, Duration::ZERO, 20.0);
351        draft.update_with_arrival(
352            epoch + Duration::from_millis(1),
353            Duration::from_millis(300),
354            20.0,
355        );
356        assert!(
357            (draft.threshold_ms() - 35.0).abs() < 1e-9,
358            "{}",
359            draft.threshold_ms()
360        );
361
362        let mut default = OveruseDetector::new();
363        default.update_with_arrival(epoch, Duration::ZERO, 20.0);
364        default.update_with_arrival(
365            epoch + Duration::from_millis(1),
366            Duration::from_millis(300),
367            20.0,
368        );
369        assert!(
370            (default.threshold_ms() - 12.575).abs() < 1e-9,
371            "{}",
372            default.threshold_ms()
373        );
374    }
375}