1use serde_json::json;
11
12#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct ClockFit {
15 pub offset: f64,
17 pub period: f64,
19 pub jitter_p50: f64,
21 pub jitter_p95: f64,
23 pub packets: usize,
25 pub nominal: bool,
27}
28
29impl ClockFit {
30 pub fn time(&self, n: f64) -> f64 {
32 self.offset + self.period * n
33 }
34
35 pub fn to_json(&self) -> serde_json::Value {
37 json!({
38 "rate_hz": 1.0 / self.period, "offset_unix_s": self.offset, "packets": self.packets,
39 "jitter_p50_s": self.jitter_p50, "jitter_p95_s": self.jitter_p95, "nominal_rate_used": self.nominal,
40 })
41 }
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Placed {
48 pub segment: i64,
50 pub first_sample: i64,
52}
53
54#[derive(Debug, Clone, Copy)]
55struct Previous {
56 arrival: f64,
57 device_time: u32,
58 sequence: Option<u8>,
59 samples: usize,
60}
61
62#[derive(Debug, Clone)]
69pub struct Segmenter {
70 rate_hz: f64,
71 packet_period: f64,
72 per_second: usize,
73 previous: Option<Previous>,
74 segment: i64,
75 next: i64,
76 same_second: usize,
77 pub lost_frames: u64,
79 pub restarts: u64,
81}
82
83impl Segmenter {
84 pub fn new(rate_hz: f64) -> Self {
86 Self {
87 rate_hz,
88 packet_period: 0.0,
89 per_second: 0,
90 previous: None,
91 segment: 0,
92 next: 0,
93 same_second: 0,
94 lost_frames: 0,
95 restarts: 0,
96 }
97 }
98
99 pub fn push(
104 &mut self,
105 arrival: f64,
106 device_time: u32,
107 sequence: Option<u8>,
108 samples: usize,
109 forced: bool,
110 after_start: bool,
111 ) -> Placed {
112 let Some(prev) = self.previous else {
113 self.packet_period = samples as f64 / self.rate_hz;
114 self.per_second = (1.0 / self.packet_period.max(1e-9)).round() as usize;
118 self.same_second = 1;
119 self.previous = Some(Previous {
120 arrival,
121 device_time,
122 sequence,
123 samples,
124 });
125 return Placed {
126 segment: self.segment,
127 first_sample: self.next,
128 };
129 };
130 let packet_period = self.packet_period;
131 let step = match (prev.sequence, sequence) {
132 (Some(a), Some(b)) => {
133 let d = i64::from(b.wrapping_sub(a));
134 if d == 1 {
135 Some(1)
136 } else if b == 0 && after_start {
137 self.restarts += 1;
139 (arrival - prev.arrival < 4.0 * packet_period + 0.5).then_some(1)
140 } else if d > 1 && arrival - prev.arrival < (d as f64 + 4.0) * packet_period + 1.0 {
141 self.lost_frames += (d - 1) as u64;
142 Some(d)
143 } else {
144 None
145 }
146 }
147 _ => {
150 let gap = arrival - prev.arrival;
151 let clock_step = i64::from(device_time) - i64::from(prev.device_time);
152 self.same_second = if clock_step == 0 { self.same_second + 1 } else { 1 };
153 let burst = self.same_second > self.per_second;
154 (gap < 2.0 * packet_period.max(0.5) && (0..=1).contains(&clock_step) && !burst).then_some(1)
155 }
156 };
157 let paused = arrival - prev.arrival > 1.0 + 2.0 * packet_period;
159 match step {
160 Some(d) if !forced && !paused => self.next += d * prev.samples as i64,
161 _ => {
162 self.segment += 1;
163 self.next = 0;
164 self.same_second = 1;
165 }
166 }
167 self.previous = Some(Previous {
168 arrival,
169 device_time,
170 sequence,
171 samples,
172 });
173 Placed {
174 segment: self.segment,
175 first_sample: self.next,
176 }
177 }
178}
179
180fn least_squares(points: &[(f64, f64)]) -> Option<(f64, f64)> {
181 let n = points.len() as f64;
182 if points.len() < 2 {
183 return None;
184 }
185 let (sx, sy) = points.iter().fold((0.0, 0.0), |(a, b), (x, y)| (a + x, b + y));
186 let (mx, my) = (sx / n, sy / n);
187 let (sxx, sxy) = points.iter().fold((0.0, 0.0), |(a, b), (x, y)| {
188 (a + (x - mx).powi(2), b + (x - mx) * (y - my))
189 });
190 if sxx <= 0.0 {
191 return None;
192 }
193 let slope = sxy / sxx;
194 Some((my - slope * mx, slope))
195}
196
197fn percentile(sorted: &[f64], q: f64) -> f64 {
198 if sorted.is_empty() {
199 return 0.0;
200 }
201 let idx = ((sorted.len() - 1) as f64 * q).round() as usize;
202 sorted.get(idx).copied().unwrap_or(0.0)
203}
204
205pub fn fit_lower_envelope(points: &[(f64, f64)], nominal_rate_hz: f64) -> ClockFit {
208 let nominal_period = 1.0 / nominal_rate_hz;
209 let (offset, period, nominal) = if points.len() >= 20 {
210 let mut fit = least_squares(points).unwrap_or((0.0, nominal_period));
211 for _ in 0..4 {
212 let mut residuals: Vec<f64> = points.iter().map(|(x, y)| y - (fit.0 + fit.1 * x)).collect();
213 residuals.sort_by(f64::total_cmp);
214 let cut = percentile(&residuals, 0.10);
215 let low: Vec<(f64, f64)> = points
216 .iter()
217 .copied()
218 .filter(|(x, y)| y - (fit.0 + fit.1 * x) <= cut)
219 .collect();
220 match least_squares(&low) {
221 Some(f) if (f.1 / nominal_period - 1.0).abs() < 0.05 => fit = f,
223 _ => break,
224 }
225 }
226 (fit.0, fit.1, false)
227 } else {
228 (0.0, nominal_period, true)
229 };
230 place_on_envelope(points, offset, period, nominal_period, nominal)
231}
232
233pub fn fit_nominal(points: &[(f64, f64)], nominal_rate_hz: f64) -> ClockFit {
236 let nominal_period = 1.0 / nominal_rate_hz;
237 place_on_envelope(points, 0.0, nominal_period, nominal_period, true)
238}
239
240fn place_on_envelope(
241 points: &[(f64, f64)],
242 mut offset: f64,
243 mut period: f64,
244 nominal_period: f64,
245 nominal: bool,
246) -> ClockFit {
247 let min_residual = points
249 .iter()
250 .map(|(x, y)| y - (offset + period * x))
251 .fold(f64::INFINITY, f64::min);
252 if min_residual.is_finite() {
253 offset += min_residual;
254 }
255 if !period.is_finite() || period <= 0.0 {
256 period = nominal_period;
257 }
258 let mut delays: Vec<f64> = points.iter().map(|(x, y)| y - (offset + period * x)).collect();
259 delays.sort_by(f64::total_cmp);
260 ClockFit {
261 offset,
262 period,
263 jitter_p50: percentile(&delays, 0.5),
264 jitter_p95: percentile(&delays, 0.95),
265 packets: points.len(),
266 nominal,
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273
274 #[test]
275 fn recovers_rate_and_offset_under_one_sided_jitter() {
276 let true_period = 1.0 / 125.3;
278 let mut state = 7u64;
279 let points: Vec<(f64, f64)> = (0..2000)
280 .map(|k| {
281 state = state
282 .wrapping_mul(6364136223846793005)
283 .wrapping_add(1442695040888963407);
284 let delay = 0.005 + 0.145 * ((state >> 33) as f64 / (1u64 << 31) as f64).powi(3);
285 let n = (9 * k + 8) as f64;
286 (n, 1_800_000_000.0 + true_period * n + delay)
287 })
288 .collect();
289 let fit = fit_lower_envelope(&points, 125.0);
290 assert!((1.0 / fit.period - 125.3).abs() < 0.01, "rate {}", 1.0 / fit.period);
291 assert!(
292 (fit.offset - 1_800_000_000.005).abs() < 0.003,
293 "offset error {}",
294 fit.offset - 1_800_000_000.005
295 );
296 assert!(points.iter().all(|(x, y)| *y >= fit.time(*x) - 1e-9));
297 }
298
299 #[test]
300 fn short_segments_use_nominal_rate() {
301 let points = [(8.0, 10.1), (17.0, 10.2)];
302 let fit = fit_lower_envelope(&points, 125.0);
303 assert!(fit.nominal);
304 assert!((fit.period - 0.008).abs() < 1e-12);
305 }
306}