1use crate::rtpfb::acknowledgement::PacketReport;
4use std::time::{Duration, Instant};
5
6pub const DEFAULT_BURST_INTERVAL: Duration = Duration::from_millis(5);
12
13#[derive(Debug, Clone, Copy, PartialEq)]
15pub struct ArrivalGroup {
16 pub first_departure: Instant,
18 pub departure: Instant,
20 pub arrival: Duration,
22 pub packets: usize,
24 pub size: usize,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq)]
34pub struct InterGroupDelay {
35 pub delta_ms: f64,
37 pub at: Instant,
39 pub size: usize,
41 pub arrival: Duration,
44}
45
46#[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 pub fn new(burst_interval: Duration) -> Self {
70 Self {
71 burst_interval,
72 current: None,
73 previous: None,
74 }
75 }
76
77 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 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 if arrival < current.arrival {
114 return None;
115 }
116
117 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 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 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
160fn 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 #[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 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 #[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 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 #[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 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 #[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 #[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 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 #[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 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 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 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 #[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 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 assert!((delay.delta_ms - 20.0).abs() < 1e-9, "{}", delay.delta_ms);
373 assert_eq!(1200, delay.size);
374 }
375}