1use std::cmp::Ordering;
10use std::collections::VecDeque;
11use std::time::{Duration, Instant, SystemTime};
12
13use tracing::trace;
14
15pub const DEFAULT_TIME_WINDOW: usize = 32;
17
18#[derive(Debug, Clone)]
26pub struct TimeSync {
27 a: f64,
29 b: f64,
31 window: VecDeque<(u64, Instant)>,
33 cap: usize,
35 origin_instant: Option<Instant>,
37 origin_system: Option<SystemTime>,
39 freq_hz: Option<f64>,
41 auto_fit: bool,
43 trim_outliers: bool,
45 fitted: bool,
48}
49
50impl TimeSync {
51 pub fn new() -> Self {
53 Self::with_capacity(DEFAULT_TIME_WINDOW)
54 }
55
56 pub fn with_capacity(cap: usize) -> Self {
58 Self {
59 a: 0.0,
60 b: 0.0,
61 window: VecDeque::with_capacity(cap),
62 cap,
63 origin_instant: None,
64 origin_system: None,
65 freq_hz: None,
66 auto_fit: true,
67 trim_outliers: false,
68 fitted: false,
69 }
70 }
71
72 pub fn set_auto_fit(&mut self, enabled: bool) -> &mut Self {
76 self.auto_fit = enabled;
77 self
78 }
79
80 pub fn set_trim_outliers(&mut self, enabled: bool) -> &mut Self {
85 self.trim_outliers = enabled;
86 self
87 }
88
89 pub fn coefficients(&self) -> (f64, f64) {
91 (self.a, self.b)
92 }
93
94 pub fn len(&self) -> usize {
96 self.window.len()
97 }
98
99 pub fn is_empty(&self) -> bool {
101 self.window.is_empty()
102 }
103
104 pub fn samples(&self) -> impl Iterator<Item = (u64, Instant)> + '_ {
106 self.window.iter().copied()
107 }
108
109 pub fn capacity(&self) -> usize {
111 self.cap
112 }
113
114 pub fn origin_instant(&self) -> Option<Instant> {
116 self.origin_instant
117 }
118
119 pub fn origin_system(&self) -> Option<SystemTime> {
121 self.origin_system
122 }
123
124 pub fn sample_bounds(&self) -> Option<((u64, Instant), (u64, Instant))> {
126 let first = *self.window.front()?;
127 let last = *self.window.back()?;
128 Some((first, last))
129 }
130
131 pub fn freq_hz(&self) -> Option<f64> {
133 self.freq_hz
134 }
135
136 pub fn set_freq_hz(&mut self, freq: f64) {
138 self.freq_hz = Some(freq);
139 }
140
141 pub fn update(&mut self, dev_ts: u64, host_instant: Instant) {
145 if self.origin_instant.is_none() {
146 self.origin_instant = Some(host_instant);
147 self.origin_system = Some(SystemTime::now());
148 }
149 if self.window.len() == self.cap {
150 self.window.pop_front();
151 }
152 self.window.push_back((dev_ts, host_instant));
153 if self.auto_fit {
154 self.recompute();
155 }
156 }
157
158 pub fn fit(&mut self, freq_hz: Option<f64>) -> Option<(f64, f64)> {
168 if let Some(freq) = freq_hz {
169 self.freq_hz = Some(freq);
170 }
171 self.recompute();
172 self.fitted.then_some((self.a, self.b))
173 }
174
175 fn recompute(&mut self) {
176 if self.window.len() < 2 {
177 return;
178 }
179 let origin = match self.origin_instant {
180 Some(o) => o,
181 None => return,
182 };
183 let base_tick = match self.window.front() {
184 Some((t, _)) => *t as f64,
185 None => return,
186 };
187
188 let samples: Vec<(f64, f64)> = self
189 .window
190 .iter()
191 .map(|(ticks, host)| {
192 let x = (*ticks as f64) - base_tick;
193 let y = host.duration_since(origin).as_secs_f64();
194 (x, y)
195 })
196 .collect();
197
198 if let Some(freq) = self.freq_hz.filter(|f| f.is_finite() && *f > 0.0) {
202 let (first, last) = (samples[0], samples[samples.len() - 1]);
203 if last.0 <= first.0 {
204 return;
205 }
206 let slope = 1.0 / freq;
207 let mut offsets: Vec<f64> = samples.iter().map(|(x, y)| y - slope * x).collect();
208 offsets.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
209 let intercept_rel = offsets[offsets.len() / 2];
210 self.a = slope;
211 self.b = intercept_rel - slope * base_tick;
212 self.fitted = true;
213 trace!(
214 slope = self.a,
215 intercept = self.b,
216 samples = self.window.len(),
217 "recomputed time mapping from the reported frequency"
218 );
219 return;
220 }
221
222 let (mut slope, mut intercept_rel) = match compute_fit(&samples) {
223 Some((s, i)) => (s, i),
224 None => return,
225 };
226
227 if self.trim_outliers && samples.len() >= 10 {
229 let mut residuals: Vec<(usize, f64)> = samples
230 .iter()
231 .enumerate()
232 .map(|(idx, (x, y))| {
233 let predicted = slope * *x + intercept_rel;
234 (idx, y - predicted)
235 })
236 .collect();
237 residuals.sort_by(|a, b| match a.1.partial_cmp(&b.1) {
238 Some(order) => order,
239 None => Ordering::Equal,
240 });
241 let trim = ((residuals.len() as f64) * 0.1).floor() as usize;
242 if trim > 0 && residuals.len() > trim * 2 {
243 let trimmed_samples: Vec<(f64, f64)> = residuals[trim..residuals.len() - trim]
244 .iter()
245 .map(|(idx, _)| samples[*idx])
246 .collect();
247 if let Some((s, i)) = compute_fit(&trimmed_samples) {
248 slope = s;
249 intercept_rel = i;
250 }
251 }
252 }
253
254 let intercept = intercept_rel - slope * base_tick;
255 self.a = slope;
256 self.b = intercept;
257 self.fitted = true;
258
259 trace!(
260 slope = self.a,
261 intercept = self.b,
262 samples = self.window.len(),
263 "recomputed time mapping"
264 );
265 }
266
267 pub fn to_host_time(&self, dev_ts: u64) -> Option<SystemTime> {
275 if !self.fitted {
276 return None;
277 }
278 let origin = self.origin_system?;
279 let seconds = self.a * dev_ts as f64 + self.b;
280 if seconds.is_finite() && seconds >= 0.0 {
281 match Duration::try_from_secs_f64(seconds) {
282 Ok(duration) => Some(origin + duration),
283 Err(_) => Some(origin),
284 }
285 } else {
286 Some(origin)
287 }
288 }
289}
290
291impl Default for TimeSync {
292 fn default() -> Self {
293 Self::new()
294 }
295}
296
297fn compute_fit(samples: &[(f64, f64)]) -> Option<(f64, f64)> {
299 if samples.len() < 2 {
300 return None;
301 }
302 let mut sum_x = 0.0;
303 let mut sum_y = 0.0;
304 for (x, y) in samples {
305 sum_x += x;
306 sum_y += y;
307 }
308 let n = samples.len() as f64;
309 let mean_x = sum_x / n;
310 let mean_y = sum_y / n;
311 let mut denom = 0.0;
312 let mut numer = 0.0;
313 for (x, y) in samples {
314 let dx = x - mean_x;
315 let dy = y - mean_y;
316 denom += dx * dx;
317 numer += dx * dy;
318 }
319 if denom.abs() < f64::EPSILON {
320 return None;
321 }
322 let slope = numer / denom;
323 let intercept = mean_y - slope * mean_x;
324 Some((slope, intercept))
325}
326
327#[cfg(test)]
328mod tests {
329 use super::*;
330
331 #[test]
334 fn nothing_maps_before_two_samples() {
335 let mut sync = TimeSync::new();
336 assert_eq!(sync.to_host_time(1_000), None);
337 sync.update(1_000, Instant::now());
338 assert_eq!(sync.to_host_time(1_000), None);
339 sync.update(2_000, Instant::now() + Duration::from_millis(1));
340 assert!(sync.to_host_time(1_500).is_some());
341 }
342
343 #[test]
347 fn nothing_maps_without_a_successful_fit() {
348 let start = Instant::now();
349 let mut manual = TimeSync::new();
350 manual.set_auto_fit(false);
351 manual.update(1_000, start);
352 manual.update(2_000, start + Duration::from_millis(1));
353 assert_eq!(manual.to_host_time(1_500), None, "no fit() was called");
354 manual.fit(None);
355 assert!(manual.to_host_time(1_500).is_some());
356
357 let mut stuck = TimeSync::new();
358 stuck.update(5_000, start);
359 stuck.update(5_000, start + Duration::from_millis(1));
360 assert_eq!(
361 stuck.to_host_time(5_000),
362 None,
363 "a device clock that did not move"
364 );
365 }
366
367 #[test]
368 fn regression_tracks_linear_relation() {
369 let mut sync = TimeSync::new();
370 let start = Instant::now();
371 for i in 0..16u64 {
372 let dev = i * 1000;
373 let host = start + Duration::from_millis(i * 16);
374 sync.update(dev, host);
375 }
376 let mapped = sync.to_host_time(64_000).expect("16 samples map");
377 let origin = sync.origin_system().unwrap();
378 let mapped_secs = mapped.duration_since(origin).unwrap().as_secs_f64();
379 let expected_secs = Duration::from_millis(1024).as_secs_f64();
380 assert!((mapped_secs - expected_secs).abs() < 0.1);
381 }
382
383 #[test]
384 fn with_capacity_and_manual_fit() {
385 let mut sync = TimeSync::with_capacity(8);
386 sync.set_auto_fit(false);
387 let start = Instant::now();
388 for i in 0..8u64 {
389 let dev = i * 1000;
390 let host = start + Duration::from_millis(i * 10);
391 sync.update(dev, host);
392 }
393 let (a, _) = sync.coefficients();
395 assert_eq!(a, 0.0);
396
397 let result = sync.fit(Some(100_000.0));
399 assert!(result.is_some());
400 let (a, _) = sync.coefficients();
401 assert!(a > 0.0);
402 assert_eq!(sync.freq_hz(), Some(100_000.0));
403 }
404
405 #[test]
411 fn a_reported_frequency_fixes_the_slope() {
412 let start = Instant::now();
413 let mut sync = TimeSync::new();
414 sync.set_auto_fit(false);
415 for i in 0..16u64 {
418 let late = Duration::from_micros(i * 200);
419 sync.update(i * 50_000, start + Duration::from_millis(i * 50) + late);
420 }
421 let (slope, _) = sync.fit(Some(1_000_000.0)).expect("fit");
422 assert_eq!(slope, 1e-6);
423 let origin = sync.origin_system().expect("origin");
425 let mapped = sync.to_host_time(3_600_000_000).expect("mapped");
426 let off = mapped
427 .duration_since(origin)
428 .expect("after origin")
429 .as_secs_f64()
430 - 3600.0;
431 assert!(off.abs() < 0.01, "{off} s off after an hour, not 14 s");
432
433 let mut unreported = TimeSync::new();
434 for (ticks, host) in sync.samples() {
435 unreported.update(ticks, host);
436 }
437 let (regressed, _) = unreported.fit(None).expect("fit");
438 assert!(
439 (regressed - 1.004e-6).abs() < 1e-12,
440 "without the frequency the slope is regressed: {regressed}"
441 );
442 }
443
444 #[test]
445 fn outlier_trimming() {
446 let mut sync = TimeSync::with_capacity(32);
447 sync.set_trim_outliers(true).set_auto_fit(false);
448 let start = Instant::now();
449 for i in 0..20u64 {
451 let dev = i * 1000;
452 let jitter = if i == 10 { 50 } else { 0 }; let host = start + Duration::from_millis(i * 10 + jitter);
454 sync.update(dev, host);
455 }
456 sync.fit(None);
457 assert_eq!(sync.len(), 20);
459 }
460}