Skip to main content

rtci_interceptor/gcc/
queue_limit.rs

1//! Telling loss at a full queue from loss on the way: the queueing delay the reports show.
2
3use crate::rtpfb::acknowledgement::PacketReport;
4use std::collections::VecDeque;
5use std::time::{Duration, Instant};
6
7/// How far back the lowest one-way delay is looked for: the path's delay with an empty queue.
8pub const QUEUE_BASE_WINDOW: Duration = Duration::from_secs(30);
9
10/// How far back the highest queueing delay is looked for: where the queue overflows.
11pub const QUEUE_HIGH_WINDOW: Duration = Duration::from_secs(5);
12
13/// A batch whose packets all met at least this share of the recent highest queueing delay
14/// arrived out of a queue at its limit.
15pub const QUEUE_AT_LIMIT_SHARE: f64 = 0.75;
16
17/// And at least this much queueing delay: below it there is no queue to speak of, and loss is
18/// loss on the way (a radio link, a policer), which the loss-based controller is for.
19pub const QUEUE_AT_LIMIT_MIN_DELAY: Duration = Duration::from_millis(10);
20
21/// The queueing delay of the packets reported, and whether a loss among them is the queue
22/// overflowing.
23///
24/// The one-way delay of a packet is its arrival on the receiver's clock less its departure on
25/// the sender's: the clocks' offset is unknown but constant, so the lowest one-way delay over
26/// [`QUEUE_BASE_WINDOW`] stands for the path with an empty queue and anything above it is
27/// queueing. A feedback batch with a loss in it, whose arrived packets all waited at least
28/// [`QUEUE_AT_LIMIT_SHARE`] of the highest queueing delay of the last [`QUEUE_HIGH_WINDOW`]
29/// (and at least [`QUEUE_AT_LIMIT_MIN_DELAY`]), lost its packets out of a queue at its limit:
30/// a tail drop.
31#[derive(Debug, Clone, Default)]
32pub struct QueueLimitDetector {
33    /// The departure the one-way delays are measured from.
34    reference: Option<Instant>,
35    /// The lowest one-way delay, in milliseconds, per second of feedback.
36    base: VecDeque<(Instant, f64)>,
37    /// The highest queueing delay of each batch, in milliseconds.
38    high: VecDeque<(Instant, f64)>,
39}
40
41impl QueueLimitDetector {
42    /// A detector that has seen nothing yet.
43    pub fn new() -> Self {
44        Self::default()
45    }
46
47    fn one_way_ms(&mut self, departure: Instant, arrival: Duration) -> f64 {
48        let reference = *self.reference.get_or_insert(departure);
49        let sent = match departure.checked_duration_since(reference) {
50            Some(after) => after.as_secs_f64(),
51            None => -reference.saturating_duration_since(departure).as_secs_f64(),
52        };
53        (arrival.as_secs_f64() - sent) * 1_000.0
54    }
55
56    fn add_base(&mut self, now: Instant, one_way_ms: f64) {
57        match self.base.back_mut() {
58            Some((start, lowest))
59                if now.saturating_duration_since(*start) < Duration::from_secs(1) =>
60            {
61                *lowest = lowest.min(one_way_ms);
62            }
63            _ => self.base.push_back((now, one_way_ms)),
64        }
65        while self
66            .base
67            .front()
68            .is_some_and(|(start, _)| now.saturating_duration_since(*start) > QUEUE_BASE_WINDOW)
69        {
70            self.base.pop_front();
71        }
72    }
73
74    /// Reads one feedback batch, read at `now`: whether a packet in it was lost out of a queue
75    /// at its limit.
76    pub fn on_reports(&mut self, now: Instant, reports: &[PacketReport]) -> bool {
77        let one_way: Vec<f64> = reports
78            .iter()
79            .filter(|report| report.arrived)
80            .filter_map(|report| Some(self.one_way_ms(report.departure, report.arrival?)))
81            .collect();
82        for delay in &one_way {
83            self.add_base(now, *delay);
84        }
85        let Some(base) = self.base.iter().map(|(_, lowest)| *lowest).reduce(f64::min) else {
86            return false;
87        };
88        let (Some(lowest), Some(highest)) = (
89            one_way.iter().copied().reduce(f64::min),
90            one_way.iter().copied().reduce(f64::max),
91        ) else {
92            return false;
93        };
94        self.high.push_back((now, highest - base));
95        while self
96            .high
97            .front()
98            .is_some_and(|(at, _)| now.saturating_duration_since(*at) > QUEUE_HIGH_WINDOW)
99        {
100            self.high.pop_front();
101        }
102        let recent_high = self.high.iter().map(|(_, high)| *high).fold(0.0, f64::max);
103        let waited = lowest - base;
104        reports.iter().any(|report| !report.arrived)
105            && waited >= QUEUE_AT_LIMIT_MIN_DELAY.as_secs_f64() * 1_000.0
106            && waited >= QUEUE_AT_LIMIT_SHARE * recent_high
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
114
115    /// A batch of `count` packets 10 ms apart from `first`, each waiting `queue_ms` on a 20 ms
116    /// path, with the ones in `lost` missing.
117    fn batch(
118        epoch: Instant,
119        first: u64,
120        count: u64,
121        queue_ms: impl Fn(u64) -> u64,
122        lost: &[u64],
123    ) -> Vec<PacketReport> {
124        (first..first + count)
125            .map(|id| {
126                let arrived = !lost.contains(&id);
127                PacketReport {
128                    ssrc: 1,
129                    id,
130                    rtp_sequence_number: id as u16,
131                    is_twcc: true,
132                    twcc_sequence_number: id as u16,
133                    size: 1200,
134                    arrived,
135                    departure: epoch + Duration::from_millis(id * 10),
136                    arrival: arrived
137                        .then(|| Duration::from_millis(1_000 + id * 10 + 20 + queue_ms(id))),
138                    ecn: Ecn::default(),
139                }
140            })
141            .collect()
142    }
143
144    /// A queue that fills to 200 ms and drops there: the loss is the queue's limit.
145    #[test]
146    fn a_loss_out_of_a_full_queue_is_at_the_limit() {
147        let epoch = Instant::now();
148        let mut detector = QueueLimitDetector::new();
149        // An empty queue first, then one that grows to 200 ms and stays.
150        assert!(!detector.on_reports(epoch, &batch(epoch, 0, 10, |_| 0, &[])));
151        for round in 1..10u64 {
152            let at = epoch + Duration::from_millis(round * 100);
153            let reports = batch(epoch, round * 10, 10, |id| (id * 2).min(200), &[]);
154            assert!(!detector.on_reports(at, &reports), "no loss, round {round}");
155        }
156        let reports = batch(epoch, 100, 10, |_| 200, &[104]);
157        assert!(detector.on_reports(epoch + Duration::from_secs(1), &reports));
158    }
159
160    /// Loss with the queue empty is loss on the way, not congestion of a queue.
161    #[test]
162    fn a_loss_with_no_queue_is_not_at_the_limit() {
163        let epoch = Instant::now();
164        let mut detector = QueueLimitDetector::new();
165        for round in 0..10u64 {
166            let at = epoch + Duration::from_millis(round * 100);
167            let reports = batch(epoch, round * 10, 10, |_| 0, &[round * 10 + 3]);
168            assert!(!detector.on_reports(at, &reports), "round {round}");
169        }
170    }
171
172    /// Jitter: some packets wait long, others not at all, and one is lost. The batch did not
173    /// sit at a limit: its quickest packet hardly waited.
174    #[test]
175    fn a_loss_on_a_jittery_path_is_not_at_the_limit() {
176        let epoch = Instant::now();
177        let mut detector = QueueLimitDetector::new();
178        for round in 0..20u64 {
179            let at = epoch + Duration::from_millis(round * 100);
180            let reports = batch(
181                epoch,
182                round * 10,
183                10,
184                |id| (id * 37) % 60,
185                &[round * 10 + 5],
186            );
187            assert!(!detector.on_reports(at, &reports), "round {round}");
188        }
189    }
190}