Skip to main content

viva_gige/
time.rs

1//! Mapping device timestamps to host time.
2//!
3//! The [`TimeSync`] struct maintains a sliding window of timestamp measurements
4//! and computes a linear model mapping device ticks to host time. It supports:
5//! - Configurable window capacity
6//! - Optional outlier trimming for robustness
7//! - Both immediate (auto-fit on update) and deferred (manual fit) modes
8
9use std::cmp::Ordering;
10use std::collections::VecDeque;
11use std::time::{Duration, Instant, SystemTime};
12
13use tracing::trace;
14
15/// Default maximum number of samples kept for linear regression.
16pub const DEFAULT_TIME_WINDOW: usize = 32;
17
18/// Maintain a linear mapping between device ticks and host time.
19///
20/// This struct collects timestamp measurement pairs and uses linear regression
21/// to compute a mapping from device ticks to host time. It supports:
22/// - Configurable window size (number of samples to retain)
23/// - Optional outlier trimming for robustness against jitter
24/// - Both auto-fit (recompute on every update) and manual fit modes
25#[derive(Debug, Clone)]
26pub struct TimeSync {
27    /// Linear fit slope (seconds per tick).
28    a: f64,
29    /// Linear fit intercept (seconds).
30    b: f64,
31    /// Sample window storing device ticks and host instants.
32    window: VecDeque<(u64, Instant)>,
33    /// Maximum number of samples retained in the window.
34    cap: usize,
35    /// Host instant corresponding to the first recorded sample.
36    origin_instant: Option<Instant>,
37    /// Host system time captured alongside the origin instant.
38    origin_system: Option<SystemTime>,
39    /// Optional device tick frequency when reported by the camera.
40    freq_hz: Option<f64>,
41    /// Whether to automatically recompute fit on every update.
42    auto_fit: bool,
43    /// Whether to trim outliers when fitting (10% from each end when n≄10).
44    trim_outliers: bool,
45    /// Whether `a` and `b` hold a fit of the samples, rather than their
46    /// defaults: a mapping exists only then.
47    fitted: bool,
48}
49
50impl TimeSync {
51    /// Create an empty synchroniser with default capacity and auto-fit enabled.
52    pub fn new() -> Self {
53        Self::with_capacity(DEFAULT_TIME_WINDOW)
54    }
55
56    /// Create a synchroniser with custom capacity.
57    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    /// Enable or disable automatic refitting on every update.
73    ///
74    /// When disabled, you must call [`fit`](Self::fit) manually to update coefficients.
75    pub fn set_auto_fit(&mut self, enabled: bool) -> &mut Self {
76        self.auto_fit = enabled;
77        self
78    }
79
80    /// Enable or disable outlier trimming during fit.
81    ///
82    /// When enabled, the 10% most extreme residuals are excluded from
83    /// the regression when at least 10 samples are available.
84    pub fn set_trim_outliers(&mut self, enabled: bool) -> &mut Self {
85        self.trim_outliers = enabled;
86        self
87    }
88
89    /// Return the current slope and intercept of the time mapping.
90    pub fn coefficients(&self) -> (f64, f64) {
91        (self.a, self.b)
92    }
93
94    /// Number of samples retained in the sliding window.
95    pub fn len(&self) -> usize {
96        self.window.len()
97    }
98
99    /// Check if samples window is empty.
100    pub fn is_empty(&self) -> bool {
101        self.window.is_empty()
102    }
103
104    /// Iterator over the samples contained in the sliding window.
105    pub fn samples(&self) -> impl Iterator<Item = (u64, Instant)> + '_ {
106        self.window.iter().copied()
107    }
108
109    /// Maximum number of samples stored in the sliding window.
110    pub fn capacity(&self) -> usize {
111        self.cap
112    }
113
114    /// Access the origin instant if at least one sample has been recorded.
115    pub fn origin_instant(&self) -> Option<Instant> {
116        self.origin_instant
117    }
118
119    /// Access the origin system time if available.
120    pub fn origin_system(&self) -> Option<SystemTime> {
121        self.origin_system
122    }
123
124    /// Return the first and last sample retained in the window.
125    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    /// Retrieve the reported device tick frequency.
132    pub fn freq_hz(&self) -> Option<f64> {
133        self.freq_hz
134    }
135
136    /// Set the device tick frequency.
137    pub fn set_freq_hz(&mut self, freq: f64) {
138        self.freq_hz = Some(freq);
139    }
140
141    /// Add a new measurement pair to the regression window.
142    ///
143    /// If auto-fit is enabled (default), the linear model is recomputed immediately.
144    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    /// Fit the linear model, optionally updating the frequency.
159    ///
160    /// With a frequency — given here, or earlier through
161    /// [`set_freq_hz`](Self::set_freq_hz) — the slope is one over it and only
162    /// the offset is fitted, as the median over the samples; without one both
163    /// come from a least-squares regression. Returns the updated
164    /// `(slope, intercept)` coefficients when enough samples are available,
165    /// or `None` if fewer than 2 samples exist or the device clock did not
166    /// move.
167    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        // A reported frequency is the slope; only the offset is fitted. A
199        // short window of samples taken over the network cannot beat it: the
200        // host instant of each sample carries the round trip's jitter.
201        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        // Apply outlier trimming if enabled and we have enough samples
228        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    /// Convert a device timestamp into a host `SystemTime`, or `None` until a
268    /// fit of the samples has succeeded: samples alone are not a mapping when
269    /// auto-fit is off, or when they cannot be fitted (Codex review of #185).
270    ///
271    /// Without a mapping this returned `SystemTime::now()`, which looks like a
272    /// device time mapped to the host but is only when it was asked; every
273    /// frame of a Python GigE stream carried one (backlog DOC-11).
274    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
297/// Compute linear regression slope and intercept from samples.
298fn 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    /// No mapping without two samples: an answer then would be the time it
332    /// was asked, not the device's time (backlog DOC-11).
333    #[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    /// Samples are not a mapping: with auto-fit off and no `fit()`, or with
344    /// samples a fit rejects, there is still no host time to give (Codex
345    /// review of #185).
346    #[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        // Coefficients should still be default since auto_fit is off
394        let (a, _) = sync.coefficients();
395        assert_eq!(a, 0.0);
396
397        // Now fit manually
398        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    /// A camera that reports its tick frequency fixes the slope: only the
406    /// offset is fitted. Sixteen samples taken 50 ms apart over GVCP fitted
407    /// an Allied Vision Manta G-125B's 48 MHz clock at 48.46 MHz, and
408    /// frames mapped through that fit drifted 9.5 ms a second from their
409    /// arrival; mapped at 48 MHz they drifted 31 ms in 20 minutes.
410    #[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        // 1 MHz, the host instant of each sample 0.2 ms later than the one
416        // before: a regression reads the clock 0.4 % slow.
417        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        // An hour on, the mapping is off by the offset's error, not by 2 %.
424        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        // Add samples with one outlier
450        for i in 0..20u64 {
451            let dev = i * 1000;
452            let jitter = if i == 10 { 50 } else { 0 }; // outlier at i=10
453            let host = start + Duration::from_millis(i * 10 + jitter);
454            sync.update(dev, host);
455        }
456        sync.fit(None);
457        // With trimming, the fit should be more accurate
458        assert_eq!(sync.len(), 20);
459    }
460}