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
44fn least_squares(points: &[(f64, f64)]) -> Option<(f64, f64)> {
45 let n = points.len() as f64;
46 if points.len() < 2 {
47 return None;
48 }
49 let (sx, sy) = points.iter().fold((0.0, 0.0), |(a, b), (x, y)| (a + x, b + y));
50 let (mx, my) = (sx / n, sy / n);
51 let (sxx, sxy) = points.iter().fold((0.0, 0.0), |(a, b), (x, y)| {
52 (a + (x - mx).powi(2), b + (x - mx) * (y - my))
53 });
54 if sxx <= 0.0 {
55 return None;
56 }
57 let slope = sxy / sxx;
58 Some((my - slope * mx, slope))
59}
60
61fn percentile(sorted: &[f64], q: f64) -> f64 {
62 if sorted.is_empty() {
63 return 0.0;
64 }
65 let idx = ((sorted.len() - 1) as f64 * q).round() as usize;
66 sorted.get(idx).copied().unwrap_or(0.0)
67}
68
69pub fn fit_lower_envelope(points: &[(f64, f64)], nominal_rate_hz: f64) -> ClockFit {
72 let nominal_period = 1.0 / nominal_rate_hz;
73 let (mut offset, mut period, nominal) = if points.len() >= 20 {
74 let mut fit = least_squares(points).unwrap_or((0.0, nominal_period));
75 for _ in 0..4 {
76 let mut residuals: Vec<f64> = points.iter().map(|(x, y)| y - (fit.0 + fit.1 * x)).collect();
77 residuals.sort_by(f64::total_cmp);
78 let cut = percentile(&residuals, 0.10);
79 let low: Vec<(f64, f64)> = points
80 .iter()
81 .copied()
82 .filter(|(x, y)| y - (fit.0 + fit.1 * x) <= cut)
83 .collect();
84 match least_squares(&low) {
85 Some(f) if (f.1 / nominal_period - 1.0).abs() < 0.05 => fit = f,
87 _ => break,
88 }
89 }
90 (fit.0, fit.1, false)
91 } else {
92 (0.0, nominal_period, true)
93 };
94 let min_residual = points
96 .iter()
97 .map(|(x, y)| y - (offset + period * x))
98 .fold(f64::INFINITY, f64::min);
99 if min_residual.is_finite() {
100 offset += min_residual;
101 }
102 if !period.is_finite() || period <= 0.0 {
103 period = nominal_period;
104 }
105 let mut delays: Vec<f64> = points.iter().map(|(x, y)| y - (offset + period * x)).collect();
106 delays.sort_by(f64::total_cmp);
107 ClockFit {
108 offset,
109 period,
110 jitter_p50: percentile(&delays, 0.5),
111 jitter_p95: percentile(&delays, 0.95),
112 packets: points.len(),
113 nominal,
114 }
115}
116
117#[cfg(test)]
118mod tests {
119 use super::*;
120
121 #[test]
122 fn recovers_rate_and_offset_under_one_sided_jitter() {
123 let true_period = 1.0 / 125.3;
125 let mut state = 7u64;
126 let points: Vec<(f64, f64)> = (0..2000)
127 .map(|k| {
128 state = state
129 .wrapping_mul(6364136223846793005)
130 .wrapping_add(1442695040888963407);
131 let delay = 0.005 + 0.145 * ((state >> 33) as f64 / (1u64 << 31) as f64).powi(3);
132 let n = (9 * k + 8) as f64;
133 (n, 1_800_000_000.0 + true_period * n + delay)
134 })
135 .collect();
136 let fit = fit_lower_envelope(&points, 125.0);
137 assert!((1.0 / fit.period - 125.3).abs() < 0.01, "rate {}", 1.0 / fit.period);
138 assert!(
139 (fit.offset - 1_800_000_000.005).abs() < 0.003,
140 "offset error {}",
141 fit.offset - 1_800_000_000.005
142 );
143 assert!(points.iter().all(|(x, y)| *y >= fit.time(*x) - 1e-9));
144 }
145
146 #[test]
147 fn short_segments_use_nominal_rate() {
148 let points = [(8.0, 10.1), (17.0, 10.2)];
149 let fit = fit_lower_envelope(&points, 125.0);
150 assert!(fit.nominal);
151 assert!((fit.period - 0.008).abs() < 1e-12);
152 }
153}