Skip to main content

rtci_interceptor/gcc/
arrival_group.rs

1//! Grouping acknowledgements into bursts, and measuring the delay gradient between them.
2
3use crate::rtpfb::acknowledgement::PacketReport;
4use std::time::{Duration, Instant};
5
6/// Packets sent within this of each other are one burst.
7///
8/// A sender does not emit packets one at a time — a video frame is a burst — and the delay signal
9/// lives *between* bursts, not inside them. Grouping too finely turns the pacer's own release
10/// spacing into a delay measurement.
11pub const DEFAULT_BURST_INTERVAL: Duration = Duration::from_millis(5);
12
13/// A run of packets that departed together, and when they turned up.
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub struct ArrivalGroup {
16    /// When the first packet of the group left.
17    pub first_departure: Instant,
18    /// When the last packet of the group left.
19    pub departure: Instant,
20    /// When the last packet of the group arrived, on the receiver's clock.
21    pub arrival: Duration,
22    /// How many packets the group holds.
23    pub packets: usize,
24    /// Total wire size, in bytes.
25    pub size: usize,
26}
27
28/// The delay gradient between two consecutive groups.
29///
30/// This is the measurement everything downstream is built on: if the path is not queueing, packets
31/// spread apart on arrival exactly as much as they were spread apart on departure, and this is
32/// zero. A growing queue makes arrivals spread *more* than departures, and it goes positive.
33#[derive(Debug, Clone, Copy, PartialEq)]
34pub struct InterGroupDelay {
35    /// Arrival spread minus departure spread, in milliseconds. Positive means the queue is growing.
36    pub delta_ms: f64,
37    /// When the later group's last packet departed — the instant this measurement belongs to.
38    pub at: Instant,
39    /// Bytes in the later group, for the rate calculation downstream.
40    pub size: usize,
41    /// When the later group's last packet arrived, on the receiver's clock: t(i) of
42    /// draft-ietf-rmcat-gcc-02 section 5.3.
43    pub arrival: Duration,
44}
45
46/// Collects acknowledgements into bursts and emits the gradient between consecutive bursts.
47///
48/// # Difference from upstream
49///
50/// Upstream's accumulator emits a group only when the *next* group begins, so the final group is
51/// never emitted (`arrival_group_accumulator.go:26-67`). Live that is invisible; in a test that
52/// ends, the last measurement silently disappears. Here [`flush`](Self::flush) exists so a test can
53/// close the stream, and the live path is unchanged.
54#[derive(Debug, Clone)]
55pub struct ArrivalGroupAccumulator {
56    burst_interval: Duration,
57    current: Option<ArrivalGroup>,
58    previous: Option<ArrivalGroup>,
59}
60
61impl Default for ArrivalGroupAccumulator {
62    fn default() -> Self {
63        Self::new(DEFAULT_BURST_INTERVAL)
64    }
65}
66
67impl ArrivalGroupAccumulator {
68    /// An accumulator grouping packets sent within `burst_interval` of each other.
69    pub fn new(burst_interval: Duration) -> Self {
70        Self {
71            burst_interval,
72            current: None,
73            previous: None,
74        }
75    }
76
77    /// Feed one report. Returns a gradient when this report started a new group.
78    ///
79    /// Reports that did not arrive carry no timing and are skipped — loss is the loss controller's
80    /// signal, not the delay controller's.
81    pub fn accumulate(&mut self, report: &PacketReport) -> Option<InterGroupDelay> {
82        let arrival = report.arrival?;
83        if !report.arrived {
84            return None;
85        }
86
87        let Some(current) = self.current.as_mut() else {
88            self.current = Some(ArrivalGroup {
89                first_departure: report.departure,
90                departure: report.departure,
91                arrival,
92                packets: 1,
93                size: report.size,
94            });
95            return None;
96        };
97
98        // Still the same burst: extend it.
99        if report
100            .departure
101            .saturating_duration_since(current.first_departure)
102            <= self.burst_interval
103        {
104            current.departure = current.departure.max(report.departure);
105            current.arrival = current.arrival.max(arrival);
106            current.packets += 1;
107            current.size += report.size;
108            return None;
109        }
110
111        // draft-ietf-rmcat-gcc-02 section 5.1: a packet received out of order (before the
112        // group it follows) is ignored by the arrival-time model.
113        if arrival < current.arrival {
114            return None;
115        }
116
117        // Section 5.2: a packet that arrives within burst_time of the group and with a
118        // negative inter-group delay variation (it caught up: the path delivered a backlog at
119        // once, after an outage) is part of the current group.
120        let arrival_delta = arrival.saturating_sub(current.arrival);
121        let departure_delta = report
122            .departure
123            .saturating_duration_since(current.departure);
124        if arrival_delta < self.burst_interval && arrival_delta < departure_delta {
125            current.departure = current.departure.max(report.departure);
126            current.arrival = current.arrival.max(arrival);
127            current.packets += 1;
128            current.size += report.size;
129            return None;
130        }
131
132        // A new burst begins, so the one that just closed can be measured against its predecessor.
133        let closed = *current;
134        self.current = Some(ArrivalGroup {
135            first_departure: report.departure,
136            departure: report.departure,
137            arrival,
138            packets: 1,
139            size: report.size,
140        });
141
142        let measurement = self.previous.map(|previous| gradient(&previous, &closed));
143        self.previous = Some(closed);
144        measurement
145    }
146
147    /// Close the stream, emitting the gradient for the group still open.
148    ///
149    /// Upstream has no equivalent and therefore drops its last group. Live that does not matter;
150    /// for a test with a definite end it is the difference between measuring what happened and
151    /// measuring all but the last of it.
152    pub fn flush(&mut self) -> Option<InterGroupDelay> {
153        let closed = self.current.take()?;
154        let measurement = self.previous.map(|previous| gradient(&previous, &closed));
155        self.previous = Some(closed);
156        measurement
157    }
158}
159
160/// Arrival spread minus departure spread, between two consecutive groups.
161fn gradient(previous: &ArrivalGroup, current: &ArrivalGroup) -> InterGroupDelay {
162    let arrival_delta = current.arrival.as_secs_f64() - previous.arrival.as_secs_f64();
163    let departure_delta = current
164        .departure
165        .saturating_duration_since(previous.departure)
166        .as_secs_f64();
167
168    InterGroupDelay {
169        delta_ms: (arrival_delta - departure_delta) * 1_000.0,
170        at: current.departure,
171        size: current.size,
172        arrival: current.arrival,
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
180
181    fn report(departure: Instant, arrival_ms: u64, size: usize) -> PacketReport {
182        PacketReport {
183            ssrc: 1,
184            id: 0,
185            rtp_sequence_number: 0,
186            is_twcc: true,
187            twcc_sequence_number: 0,
188            size,
189            arrived: true,
190            departure,
191            arrival: Some(Duration::from_millis(arrival_ms)),
192            ecn: Ecn::default(),
193        }
194    }
195
196    /// Packets sent inside the burst interval are one group, whatever their count.
197    #[test]
198    fn packets_sent_together_form_one_group() {
199        let epoch = Instant::now();
200        let mut accumulator = ArrivalGroupAccumulator::default();
201
202        for offset in [0, 1, 2, 3, 4] {
203            assert_eq!(
204                None,
205                accumulator.accumulate(&report(epoch + Duration::from_millis(offset), 100, 1200)),
206                "nothing is emitted until a group closes"
207            );
208        }
209
210        // 20 ms later is a new burst, which closes the first — but there is no predecessor yet.
211        assert_eq!(
212            None,
213            accumulator.accumulate(&report(epoch + Duration::from_millis(20), 120, 1200))
214        );
215        let group = accumulator
216            .flush()
217            .expect("the second group closes against the first");
218        assert_eq!(1200, group.size, "the second group holds one packet");
219    }
220
221    /// A path that is not queueing: arrivals spread exactly as much as departures, so the gradient
222    /// is zero. This is the baseline everything else is measured against.
223    #[test]
224    fn a_path_that_does_not_queue_has_a_zero_gradient() {
225        let epoch = Instant::now();
226        let mut accumulator = ArrivalGroupAccumulator::default();
227        let mut gradients = Vec::new();
228
229        // One packet every 20 ms, arriving 20 ms apart.
230        for burst in 0..5u64 {
231            let departure = epoch + Duration::from_millis(burst * 20);
232            if let Some(delay) = accumulate_and_flush(&mut accumulator, departure, 100 + burst * 20)
233            {
234                gradients.push(delay.delta_ms);
235            }
236        }
237
238        assert!(
239            gradients.iter().all(|delta| delta.abs() < 1e-6),
240            "a non-queueing path must measure zero delay gradient: {gradients:?}"
241        );
242    }
243
244    /// A queue building: arrivals spread *more* than departures, so the gradient goes positive.
245    #[test]
246    fn a_growing_queue_has_a_positive_gradient() {
247        let epoch = Instant::now();
248        let mut accumulator = ArrivalGroupAccumulator::default();
249        let mut gradients = Vec::new();
250
251        // Sent 20 ms apart, arriving 30 ms apart: 10 ms of queue per group.
252        for burst in 0..5u64 {
253            let departure = epoch + Duration::from_millis(burst * 20);
254            if let Some(delay) = accumulate_and_flush(&mut accumulator, departure, 100 + burst * 30)
255            {
256                gradients.push(delay.delta_ms);
257            }
258        }
259
260        assert!(!gradients.is_empty(), "no gradients were produced");
261        assert!(
262            gradients.iter().all(|delta| (*delta - 10.0).abs() < 1e-6),
263            "each group should measure 10 ms of added delay: {gradients:?}"
264        );
265    }
266
267    /// A queue draining: arrivals spread *less* than departures, so the gradient goes negative.
268    #[test]
269    fn a_draining_queue_has_a_negative_gradient() {
270        let epoch = Instant::now();
271        let mut accumulator = ArrivalGroupAccumulator::default();
272        let mut gradients = Vec::new();
273
274        for burst in 0..5u64 {
275            let departure = epoch + Duration::from_millis(burst * 20);
276            if let Some(delay) = accumulate_and_flush(&mut accumulator, departure, 200 + burst * 15)
277            {
278                gradients.push(delay.delta_ms);
279            }
280        }
281
282        assert!(
283            gradients.iter().all(|delta| *delta < 0.0),
284            "a draining queue must measure negative: {gradients:?}"
285        );
286    }
287
288    /// Lost packets carry no timing and must not be measured as though they arrived at zero.
289    #[test]
290    fn lost_packets_are_not_measured() {
291        let epoch = Instant::now();
292        let mut accumulator = ArrivalGroupAccumulator::default();
293
294        let mut lost = report(epoch, 0, 1200);
295        lost.arrived = false;
296        lost.arrival = None;
297
298        assert_eq!(None, accumulator.accumulate(&lost));
299        assert_eq!(
300            None,
301            accumulator.flush(),
302            "a lost packet must not open a group"
303        );
304    }
305
306    /// One packet per burst, so every call closes the previous group.
307    fn accumulate_and_flush(
308        accumulator: &mut ArrivalGroupAccumulator,
309        departure: Instant,
310        arrival_ms: u64,
311    ) -> Option<InterGroupDelay> {
312        accumulator.accumulate(&report(departure, arrival_ms, 1200))
313    }
314
315    /// Section 5.2: after an outage the path delivers its backlog at once. Packets sent 20 ms
316    /// apart that arrive 1 ms apart (inter-arrival under burst_time, negative delay variation)
317    /// are one group with the one they caught up with, not a run of groups each reading as a
318    /// draining queue.
319    #[test]
320    fn a_backlog_delivered_at_once_is_one_group() {
321        let epoch = Instant::now();
322        let mut accumulator = ArrivalGroupAccumulator::default();
323        let mut emitted = Vec::new();
324        // Steady: 20 ms apart both ways.
325        for n in 0..3u64 {
326            emitted.extend(accumulator.accumulate(&report(
327                epoch + Duration::from_millis(n * 20),
328                100 + n * 20,
329                1200,
330            )));
331        }
332        // An outage: the next five arrive together, 1 ms apart.
333        for n in 3..8u64 {
334            emitted.extend(accumulator.accumulate(&report(
335                epoch + Duration::from_millis(n * 20),
336                300 + n,
337                1200,
338            )));
339        }
340        // Steady again.
341        emitted.extend(accumulator.accumulate(&report(
342            epoch + Duration::from_millis(8 * 20),
343            330,
344            1200,
345        )));
346        emitted.extend(accumulator.flush());
347        let sizes: Vec<usize> = emitted.iter().map(|delay| delay.size).collect();
348        assert!(
349            sizes.contains(&(5 * 1200)),
350            "the backlog is one group of five: {sizes:?}"
351        );
352    }
353
354    /// Section 5.1: t(i) is the arrival of the group's last packet, and a packet that arrived
355    /// before the group it follows (reordered on the path) is left out of the model.
356    #[test]
357    fn a_packet_received_out_of_order_is_ignored() {
358        let epoch = Instant::now();
359        let mut accumulator = ArrivalGroupAccumulator::default();
360        accumulator.accumulate(&report(epoch, 100, 1200));
361        accumulator.accumulate(&report(epoch + Duration::from_millis(20), 140, 1200));
362        // Sent after the second, arrived before it.
363        assert_eq!(
364            None,
365            accumulator.accumulate(&report(epoch + Duration::from_millis(40), 130, 1200))
366        );
367        let delay = accumulator
368            .accumulate(&report(epoch + Duration::from_millis(60), 160, 1200))
369            .expect("the second group closes");
370        // Against the first: arrival 140 - 100 less departure 20 - 0, the reordered packet
371        // not part of it.
372        assert!((delay.delta_ms - 20.0).abs() < 1e-9, "{}", delay.delta_ms);
373        assert_eq!(1200, delay.size);
374    }
375}