1use super::arrival_group::{ArrivalGroupAccumulator, InterGroupDelay};
4use super::kalman::Kalman;
5use crate::rtpfb::acknowledgement::PacketReport;
6use std::time::{Duration, Instant};
7
8#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct DelayTrend {
11 pub measurement_ms: f64,
13 pub estimate_ms: f64,
15 pub at: Instant,
17 pub size: usize,
19 pub arrival: Duration,
21}
22
23#[derive(Debug, Clone, Default)]
29pub struct SlopeEstimator {
30 groups: ArrivalGroupAccumulator,
31 kalman: Kalman,
32 last_departure: Option<Instant>,
35}
36
37impl SlopeEstimator {
38 pub fn new() -> Self {
40 Self::default()
41 }
42
43 pub fn with_burst_interval(burst_interval: Duration) -> Self {
45 Self {
46 groups: ArrivalGroupAccumulator::new(burst_interval),
47 kalman: Kalman::new(),
48 last_departure: None,
49 }
50 }
51
52 pub fn estimate_ms(&self) -> f64 {
54 self.kalman.estimate()
55 }
56
57 pub fn accumulate(&mut self, report: &PacketReport) -> Option<DelayTrend> {
59 let delay = self.groups.accumulate(report)?;
60 Some(self.filter(delay))
61 }
62
63 pub fn flush(&mut self) -> Option<DelayTrend> {
65 let delay = self.groups.flush()?;
66 Some(self.filter(delay))
67 }
68
69 fn filter(&mut self, delay: InterGroupDelay) -> DelayTrend {
70 let period_ms = self.last_departure.map_or(0.0, |last| {
71 delay.at.saturating_duration_since(last).as_secs_f64() * 1_000.0
72 });
73 self.last_departure = Some(delay.at);
74 DelayTrend {
75 measurement_ms: delay.delta_ms,
76 estimate_ms: self.kalman.update_with_period(delay.delta_ms, period_ms),
77 at: delay.at,
78 arrival: delay.arrival,
79 size: delay.size,
80 }
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87 use rtcp::transport_feedbacks::cc_feedback_report::Ecn;
88
89 fn report(departure: Instant, arrival_ms: u64) -> PacketReport {
90 PacketReport {
91 ssrc: 1,
92 id: 0,
93 rtp_sequence_number: 0,
94 is_twcc: true,
95 twcc_sequence_number: 0,
96 size: 1200,
97 arrived: true,
98 departure,
99 arrival: Some(Duration::from_millis(arrival_ms)),
100 ecn: Ecn::default(),
101 }
102 }
103
104 #[test]
106 fn a_steady_path_reads_flat() {
107 let epoch = Instant::now();
108 let mut slope = SlopeEstimator::new();
109
110 for burst in 0..40u64 {
111 slope.accumulate(&report(
112 epoch + Duration::from_millis(burst * 20),
113 100 + burst * 20,
114 ));
115 }
116
117 assert!(
118 slope.estimate_ms().abs() < 1.0,
119 "a steady path should read about zero, got {}",
120 slope.estimate_ms()
121 );
122 }
123
124 #[test]
126 fn a_queueing_path_reads_positive() {
127 let epoch = Instant::now();
128 let mut slope = SlopeEstimator::new();
129
130 for burst in 0..40u64 {
131 slope.accumulate(&report(
132 epoch + Duration::from_millis(burst * 20),
133 100 + burst * 26,
134 ));
135 }
136
137 assert!(
138 slope.estimate_ms() > 3.0,
139 "6 ms of queue per group should read clearly positive, got {}",
140 slope.estimate_ms()
141 );
142 }
143
144 #[test]
146 fn a_reading_carries_the_group_size() {
147 let epoch = Instant::now();
148 let mut slope = SlopeEstimator::new();
149
150 slope.accumulate(&report(epoch, 100));
151 slope.accumulate(&report(epoch + Duration::from_millis(20), 120));
152 let reading = slope
153 .accumulate(&report(epoch + Duration::from_millis(40), 140))
154 .expect("the second group closes against the first");
155
156 assert_eq!(1200, reading.size);
157 }
158
159 #[test]
167 #[ignore = "an investigation tool: prints the two groupings' readings"]
168 fn reorder_trace_against_libwebrtc_grouping() {
169 use crate::gcc::overuse::{OveruseDetector, Usage};
170 struct Rng(u64);
171 impl Rng {
172 fn unit(&mut self) -> f64 {
173 self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
174 let mut z = self.0;
175 z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
176 z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
177 ((z ^ (z >> 31)) >> 11) as f64 / (1u64 << 53) as f64
178 }
179 }
180 let epoch = Instant::now();
181 for (share, hold_ms) in [(0.0, 0.0), (0.5, 40.0), (1.0, 40.0), (0.5, 100.0)] {
182 let mut rng = Rng(7);
183 let packets: Vec<(f64, f64)> = (0..6000u64)
185 .map(|n| {
186 let sent = n as f64 * 10.0;
187 let hold = if rng.unit() < share {
188 hold_ms * rng.unit()
189 } else {
190 0.0
191 };
192 (sent, sent + 25.0 + hold)
193 })
194 .collect();
195 let at = |ms: f64| epoch + Duration::from_secs_f64(ms / 1000.0);
196
197 let mut ours = Vec::new();
199 let mut groups = ArrivalGroupAccumulator::default();
200 for (sent, arrived) in &packets {
201 let mut r = report(at(*sent), 0);
202 r.arrival = Some(Duration::from_secs_f64(arrived / 1000.0));
203 if let Some(delay) = groups.accumulate(&r) {
204 ours.push((delay.at, delay.delta_ms));
205 }
206 }
207
208 let mut sorted = packets.clone();
210 sorted.sort_by(|a, b| a.1.total_cmp(&b.1));
211 #[derive(Clone, Copy)]
212 struct Group {
213 first_send: f64,
214 send: f64,
215 first_arrival: f64,
216 complete: f64,
217 }
218 let mut current: Option<Group> = None;
219 let mut previous: Option<Group> = None;
220 let mut theirs = Vec::new();
221 let mut discarded = 0usize;
222 let mut reordered_groups = 0usize;
223 for (sent, arrived) in sorted {
224 let Some(mut group) = current else {
225 current = Some(Group {
226 first_send: sent,
227 send: sent,
228 first_arrival: arrived,
229 complete: arrived,
230 });
231 continue;
232 };
233 if group.first_send > sent {
234 discarded += 1;
235 continue;
236 }
237 let arrival_delta = arrived - group.complete;
238 let send_delta = sent - group.send;
239 let burst = send_delta == 0.0
240 || (arrival_delta - send_delta < 0.0
241 && arrival_delta <= 5.0
242 && arrived - group.first_arrival < 100.0);
243 if !burst && sent - group.first_send > 5.0 {
244 if let Some(prev) = previous {
245 let a = group.complete - prev.complete;
246 let d = group.send - prev.send;
247 if a < 0.0 {
248 reordered_groups += 1;
249 } else {
250 theirs.push((at(group.send), a - d));
251 }
252 }
253 previous = Some(group);
254 group = Group {
255 first_send: sent,
256 send: sent,
257 first_arrival: arrived,
258 complete: arrived,
259 };
260 } else {
261 group.send = group.send.max(sent);
262 group.complete = arrived;
263 }
264 current = Some(group);
265 }
266
267 let summarise = |name: &str, readings: &[(Instant, f64)]| {
268 let n = readings.len() as f64;
269 let mean = readings.iter().map(|r| r.1).sum::<f64>() / n;
270 let sd = (readings.iter().map(|r| (r.1 - mean).powi(2)).sum::<f64>() / n).sqrt();
271 let mut kalman = Kalman::new();
272 let mut detector = OveruseDetector::new();
273 let (mut over, mut under, mut last) = (0, 0, None);
274 let mut max_estimate: f64 = 0.0;
275 for (when, delta) in readings {
276 let period = last.map_or(0.0, |l: Instant| {
277 when.saturating_duration_since(l).as_secs_f64() * 1000.0
278 });
279 last = Some(*when);
280 let estimate = kalman.update_with_period(*delta, period);
281 max_estimate = max_estimate.max(estimate.abs());
282 match detector.update(*when, estimate) {
283 Usage::Over => over += 1,
284 Usage::Under => under += 1,
285 Usage::Normal => {}
286 }
287 }
288 println!(
289 " {name}: {} readings, delta mean {mean:+.3} ms sd {sd:.2} ms, |estimate| max {max_estimate:.2} ms, readings in overuse {over}, underuse {under}",
290 readings.len()
291 );
292 let first: Vec<String> = readings
293 .iter()
294 .take(12)
295 .map(|r| format!("{:+.1}", r.1))
296 .collect();
297 println!(" first deltas: {}", first.join(" "));
298 };
299 println!("share {share}, hold up to {hold_ms} ms:");
300 summarise("ours (send order, arrival-before-group ignored)", &ours);
301 summarise("libwebrtc (arrival order, InterArrivalDelta)", &theirs);
302 println!(
303 " libwebrtc discarded {discarded} reordered packets, {reordered_groups} groups"
304 );
305 }
306 }
307}