Skip to main content

labstream_time/
lib.rs

1//! Timestamp post-processing for LSL. SPEC.md 8.5.
2//!
3//! Three stages run in a fixed order: clock sync, then jitter removal, then
4//! monotonic clamping (`src/time_postprocessor.cpp:60-105`).
5//!
6//! # Float discipline
7//!
8//! The jitter filter is a recursive least squares fit. Every operation here
9//! keeps the order of the C++ source, because a different order gives a
10//! different result in the last bits.
11//!
12//! Three rules hold for every line of the filter:
13//!
14//! 1. Do not reassociate an expression to make it read better.
15//! 2. Do not use `mul_add`, because the source uses a separate multiply and add.
16//! 3. Keep the integer baseline subtraction.
17//!
18//! liblsl builds with plain IEEE semantics, and no fast-math flag appears in
19//! its build configuration. Bit-exact agreement is therefore a target. It is
20//! not a promise across every platform.
21
22#![forbid(unsafe_code)]
23#![deny(missing_docs)]
24
25pub mod sync;
26pub use sync::{AlignedSample, StreamAligner, StreamSpec, SyncConfig};
27
28/// The default half-time of the jitter filter, in seconds.
29///
30/// `src/api_config.cpp:325` reads it as a `float`.
31pub const DEFAULT_SMOOTHING_HALFTIME: f64 = 90.0;
32
33/// How many samples pass between two clock offset queries.
34///
35/// `src/time_postprocessor.cpp:18`.
36pub const SAMPLES_BETWEEN_CLOCKSYNCS: u8 = 50;
37
38/// The shortest time between two clock offset queries, in seconds.
39///
40/// `src/time_postprocessor.cpp:80` adds this to the clock.
41pub const MIN_CLOCKSYNC_INTERVAL: f64 = 0.5;
42
43/// The post-processing stages, as a bit set.
44///
45/// Bits 0 to 3 match `include/lsl/common.h:103-126`. Bits 4 and 5 are opt-in
46/// labstream extensions (`docs/roadmap.md`, steps 15 and 17) that leave the
47/// default `CLOCKSYNC` and `ALL` behavior bit-exact with liblsl.
48pub mod flags {
49    /// Apply no stage. This is the default.
50    pub const NONE: u32 = 0;
51    /// Add the measured clock offset.
52    pub const CLOCKSYNC: u32 = 1;
53    /// Remove jitter with a recursive least squares fit.
54    pub const DEJITTER: u32 = 2;
55    /// Never let a timestamp go backward.
56    pub const MONOTONIZE: u32 = 4;
57    /// Guard the state with a lock.
58    pub const THREADSAFE: u32 = 8;
59    /// Every standard liblsl stage (`CLOCKSYNC | DEJITTER | MONOTONIZE | THREADSAFE`).
60    pub const ALL: u32 = 1 | 2 | 4 | 8;
61    /// Opt-in linear offset-and-drift clock model (`docs/roadmap.md`, step 17).
62    ///
63    /// Removes the step at each 2 s time-sync burst by evaluating the fitted
64    /// offset and drift continuously for each sample timestamp.
65    pub const DRIFT: u32 = 16;
66    /// Opt-in device-delay correction (`docs/roadmap.md`, step 15).
67    ///
68    /// Subtracts the calibrated device delay (from `<desc><synchronization><offset_mean>`
69    /// or [`crate::PostProcessor::set_device_delay`]) from each timestamp.
70    pub const DEVICE_DELAY: u32 = 32;
71}
72
73/// The recursive least squares filter that removes jitter.
74///
75/// The filter fits `t = w0 + w1 * n` over the sample index `n`. SPEC.md 8.5.
76#[derive(Debug, Clone, PartialEq)]
77pub struct Dejitterer {
78    /// The first timestamp, truncated to a whole number.
79    ///
80    /// liblsl stores this in an unsigned integer
81    /// (`src/time_postprocessor.h:18`). The truncation is part of the
82    /// behavior, because the value comes back at the end of every call.
83    pub t0: u32,
84    /// The number of samples since `t0`.
85    pub samples_since_t0: u32,
86    /// The intercept of the fit.
87    pub w0: f64,
88    /// The slope of the fit.
89    pub w1: f64,
90    /// The inverse covariance element P00.
91    pub p00: f64,
92    /// The inverse covariance element P11.
93    pub p11: f64,
94    /// The off-diagonal inverse covariance element.
95    pub p01: f64,
96    /// The forgetting factor.
97    pub lam: f64,
98}
99
100impl Default for Dejitterer {
101    /// The state before the first sample.
102    ///
103    /// `src/time_postprocessor.h:20-26` gives every initial value.
104    fn default() -> Self {
105        Dejitterer {
106            t0: 0,
107            samples_since_t0: 0,
108            w0: 0.0,
109            w1: 0.0,
110            p00: 1e10,
111            p11: 1e10,
112            p01: 0.0,
113            lam: 0.0,
114        }
115    }
116}
117
118impl Dejitterer {
119    /// Build a filter for a stream.
120    ///
121    /// `src/time_postprocessor.cpp:104-110`. A rate of zero or less leaves the
122    /// forgetting factor at zero, and the filter then returns every timestamp
123    /// unchanged.
124    pub fn new(t0: f64, srate: f64, halftime: f64) -> Self {
125        let mut d = Dejitterer {
126            t0: t0 as u32,
127            ..Default::default()
128        };
129        if srate > 0.0 {
130            d.w1 = 1. / srate;
131            d.lam = 2f64.powf(-1. / (srate * halftime));
132        }
133        d
134    }
135
136    /// True once a first timestamp has set the baseline.
137    ///
138    /// liblsl tests the baseline against zero
139    /// (`src/time_postprocessor.h:35`). A first timestamp below 1.0 therefore
140    /// truncates to zero, and the filter reads as uninitialized.
141    pub fn is_initialized(&self) -> bool {
142        self.t0 != 0
143    }
144
145    /// True when the filter changes a timestamp.
146    pub fn smoothing_applicable(&self) -> bool {
147        self.lam > 0.0
148    }
149
150    /// Take one timestamp and return the fitted value.
151    ///
152    /// The operation order matches `src/time_postprocessor.cpp:112-131` line
153    /// for line. Do not tidy this function.
154    pub fn dejitter(&mut self, t: f64) -> f64 {
155        if !self.smoothing_applicable() {
156            return t;
157        }
158
159        // Remove the baseline for numerical accuracy.
160        let t = t - self.t0 as f64;
161
162        let u1 = self.samples_since_t0 as f64;
163        self.samples_since_t0 = self.samples_since_t0.wrapping_add(1);
164
165        let pi0 = self.p00 + u1 * self.p01;
166        let pi1 = self.p01 + u1 * self.p11;
167        let al = t - (self.w0 + u1 * self.w1);
168        let g_inv = 1. / (self.lam + pi0 + pi1 * u1);
169        let il_ = 1. / self.lam;
170
171        self.p00 = il_ * (self.p00 - pi0 * pi0 * g_inv);
172        self.p01 = il_ * (self.p01 - pi0 * pi1 * g_inv);
173        self.p11 = il_ * (self.p11 - pi1 * pi1 * g_inv);
174        self.w0 += al * (self.p00 + self.p01 * u1);
175        self.w1 += al * (self.p01 + self.p11 * u1);
176
177        self.w0 + u1 * self.w1 + self.t0 as f64
178    }
179
180    /// Move the sample counter forward for samples that never arrived.
181    ///
182    /// `src/time_postprocessor.cpp:133-135`.
183    pub fn skip_samples(&mut self, skipped: u32) {
184        self.samples_since_t0 = self.samples_since_t0.wrapping_add(skipped);
185    }
186}
187
188/// Maximum number of time-sync burst observations retained by [`DriftModel`].
189const DRIFT_WINDOW: usize = 64;
190
191/// Minimum time span (in seconds) required before fitting a non-zero slope.
192const MIN_DRIFT_SPAN: f64 = 0.5;
193
194/// Physical sanity bound on relative clock drift (`±10,000 ppm`).
195const MAX_DRIFT_RATE: f64 = 0.01;
196
197/// One burst observation fed into [`DriftModel`].
198#[derive(Debug, Clone, Copy, PartialEq)]
199struct DriftObs {
200    /// Local-clock midpoint time of the lowest-RTT probe exchange (seconds).
201    local_time: f64,
202    /// Measured offset `local - remote` (seconds).
203    offset: f64,
204    /// Round-trip time of the exchange (seconds).
205    rtt: f64,
206}
207
208/// Fitted linear clock model `offset(t_local) = offset + drift * (t_local - t_ref)`.
209///
210/// Snapshot values can be cached atomically on the hot pull path so
211/// [`DriftFit::offset_for_remote`] runs with zero locks.
212#[derive(Debug, Clone, Copy, PartialEq)]
213pub struct DriftFit {
214    /// Reference local timestamp (seconds).
215    pub t_ref: f64,
216    /// Fitted clock offset `local - remote` at `t_ref` (seconds).
217    pub offset: f64,
218    /// Fitted relative clock drift `d(offset)/d(t_local)` (seconds per second).
219    pub drift: f64,
220}
221
222impl DriftFit {
223    /// Evaluate the smooth offset `local - remote` for a sample carrying
224    /// `remote_ts` on the source clock.
225    ///
226    /// Solves `t_local - remote_ts = offset + drift * (t_local - t_ref)` for
227    /// `t_local - remote_ts`, eliminating step jumps between bursts.
228    #[inline]
229    pub fn offset_for_remote(self, remote_ts: f64) -> f64 {
230        let denom = 1.0 - self.drift;
231        if denom.abs() < 0.5 {
232            return self.offset;
233        }
234        (self.offset + self.drift * (remote_ts - self.t_ref)) / denom
235    }
236
237    /// Evaluate the smooth offset `local - remote` at local clock time `local_t`.
238    #[inline]
239    pub fn offset_at_local(self, local_t: f64) -> f64 {
240        self.offset + self.drift * (local_t - self.t_ref)
241    }
242}
243
244/// Sliding-window RTT-weighted linear model of clock offset and drift
245/// (`docs/roadmap.md`, step 17).
246///
247/// Each burst contributes its lowest-RTT `(local_time, offset, rtt)` triple.
248/// Observations are weighted by `1 / max(rtt, 1e-6)^2` with one iteratively
249/// reweighted outlier-rejection pass so asymmetric Wi-Fi RTT spikes do not pull
250/// the fitted line.
251#[derive(Debug, Default, Clone)]
252pub struct DriftModel {
253    obs: Vec<DriftObs>,
254    fit: Option<DriftFit>,
255}
256
257impl DriftModel {
258    /// Create an empty model with no observations.
259    pub fn new() -> Self {
260        Self::default()
261    }
262
263    /// Clear all observations and the fitted line (for example after a source
264    /// restart).
265    pub fn reset(&mut self) {
266        self.obs.clear();
267        self.fit = None;
268    }
269
270    /// Number of observations currently retained in the sliding window.
271    pub fn len(&self) -> usize {
272        self.obs.len()
273    }
274
275    /// True when no observations have arrived yet.
276    pub fn is_empty(&self) -> bool {
277        self.obs.is_empty()
278    }
279
280    /// Current fitted linear parameters, or `None` before the first burst.
281    pub fn fit(&self) -> Option<DriftFit> {
282        self.fit
283    }
284
285    /// Estimated relative clock drift in seconds per second (e.g., `25e-6` for
286    /// +25 ppm), or `None` before the first burst.
287    pub fn drift(&self) -> Option<f64> {
288        self.fit.map(|f| f.drift)
289    }
290
291    /// Smooth offset for `remote_ts`, or `None` before the first burst.
292    pub fn offset_for_remote(&self, remote_ts: f64) -> Option<f64> {
293        self.fit.map(|f| f.offset_for_remote(remote_ts))
294    }
295
296    /// Record one burst estimate and recompute the weighted linear fit.
297    ///
298    /// `local_time` is the local midpoint `(t0 + t3) / 2`, `offset` is the
299    /// burst `time_offset()` (`local - remote`), and `rtt` is the burst
300    /// round-trip uncertainty in seconds.
301    pub fn update(&mut self, local_time: f64, offset: f64, rtt: f64) -> DriftFit {
302        if !local_time.is_finite() || !offset.is_finite() || !rtt.is_finite() {
303            return self.fit.unwrap_or(DriftFit {
304                t_ref: 0.0,
305                offset: 0.0,
306                drift: 0.0,
307            });
308        }
309        let rtt = rtt.max(1e-6);
310        if self.obs.len() >= DRIFT_WINDOW {
311            self.obs.remove(0);
312        }
313        self.obs.push(DriftObs {
314            local_time,
315            offset,
316            rtt,
317        });
318        let fit = self.compute_fit();
319        self.fit = Some(fit);
320        fit
321    }
322
323    fn compute_fit(&self) -> DriftFit {
324        let last = self.obs[self.obs.len() - 1];
325        if self.obs.len() == 1 {
326            return DriftFit {
327                t_ref: last.local_time,
328                offset: last.offset,
329                drift: 0.0,
330            };
331        }
332        let t_min = self
333            .obs
334            .iter()
335            .map(|o| o.local_time)
336            .fold(f64::INFINITY, f64::min);
337        let t_max = self
338            .obs
339            .iter()
340            .map(|o| o.local_time)
341            .fold(f64::NEG_INFINITY, f64::max);
342        if t_max - t_min < MIN_DRIFT_SPAN {
343            // Too short a time span for a reliable slope: return RTT-weighted mean.
344            let mut sw = 0.0;
345            let mut sy = 0.0;
346            for o in &self.obs {
347                let w = 1.0 / (o.rtt * o.rtt);
348                sw += w;
349                sy += w * o.offset;
350            }
351            return DriftFit {
352                t_ref: last.local_time,
353                offset: sy / sw,
354                drift: 0.0,
355            };
356        }
357
358        // First pass: inverse-RTT-squared weighted linear regression centered at `t_ref`.
359        let t_ref = last.local_time;
360        let first = weighted_line(&self.obs, t_ref, None);
361
362        // Second pass (when >= 4 points): down-weight asymmetric RTT spikes
363        // whose residual exceeds max(3 * MAD, 2 * rtt).
364        if self.obs.len() >= 4 {
365            let mut res: Vec<f64> = self
366                .obs
367                .iter()
368                .map(|o| (o.offset - first.offset_at_local(o.local_time)).abs())
369                .collect();
370            res.sort_by(f64::total_cmp);
371            let mad = res[res.len() / 2];
372            let refined = weighted_line(&self.obs, t_ref, Some((first, mad)));
373            if refined.drift.is_finite() && refined.offset.is_finite() {
374                return refined;
375            }
376        }
377        first
378    }
379}
380
381fn weighted_line(obs: &[DriftObs], t_ref: f64, reject: Option<(DriftFit, f64)>) -> DriftFit {
382    let mut sw = 0.0;
383    let mut sx = 0.0;
384    let mut sy = 0.0;
385    let mut sxx = 0.0;
386    let mut sxy = 0.0;
387    let mut kept = 0usize;
388    for o in obs {
389        let mut w = 1.0 / (o.rtt * o.rtt);
390        if let Some((prev, mad)) = reject {
391            let err = (o.offset - prev.offset_at_local(o.local_time)).abs();
392            let limit = (3.0 * mad).max(2.0 * o.rtt).max(1e-5);
393            if err > limit {
394                // Soft Huber down-weighting instead of hard drop so the system
395                // remains well-conditioned even if a real step occurs.
396                w *= (limit / err) * (limit / err);
397            }
398        }
399        let x = o.local_time - t_ref;
400        sw += w;
401        sx += w * x;
402        sy += w * o.offset;
403        sxx += w * x * x;
404        sxy += w * x * o.offset;
405        kept += 1;
406    }
407    if kept < 2 || sw <= 0.0 {
408        let last = obs[obs.len() - 1];
409        return DriftFit {
410            t_ref,
411            offset: last.offset,
412            drift: 0.0,
413        };
414    }
415    let det = sw * sxx - sx * sx;
416    if det.abs() < 1e-18 {
417        return DriftFit {
418            t_ref,
419            offset: sy / sw,
420            drift: 0.0,
421        };
422    }
423    let raw_drift = (sw * sxy - sx * sy) / det;
424    let drift = raw_drift.clamp(-MAX_DRIFT_RATE, MAX_DRIFT_RATE);
425    let offset = (sy - drift * sx) / sw;
426    DriftFit {
427        t_ref,
428        offset,
429        drift,
430    }
431}
432
433/// Reads the clock offset that the time sync channel measured.
434///
435/// The post-processor asks for a value instead of reading a clock, so a test
436/// drives it with fixed numbers.
437pub trait OffsetSource {
438    /// The current offset between the two clocks.
439    fn correction(&mut self) -> f64;
440    /// Smooth offset evaluated for `remote_ts` using the opt-in drift model
441    /// (`flags::DRIFT`). Defaults to [`OffsetSource::correction`].
442    fn smooth_correction(&mut self, _remote_ts: f64) -> f64 {
443        self.correction()
444    }
445    /// The nominal rate of the stream.
446    fn srate(&mut self) -> f64;
447    /// True when the connection reset since the last call.
448    fn was_reset(&mut self) -> bool;
449    /// The local clock, in seconds.
450    fn clock(&mut self) -> f64;
451}
452
453/// Applies the three stages to every timestamp. SPEC.md 8.5.
454pub struct PostProcessor {
455    options: u32,
456    halftime: f64,
457    device_delay: f64,
458    dejitter: Dejitterer,
459    samples_since_last_clocksync: u8,
460    next_query_time: f64,
461    last_offset: f64,
462    last_value: f64,
463}
464
465impl PostProcessor {
466    /// Build a post-processor with no stage enabled.
467    ///
468    /// `src/time_postprocessor.cpp:21-27` starts the last value at the lowest
469    /// possible number, so the first sample always passes the clamp.
470    pub fn new() -> Self {
471        PostProcessor {
472            options: flags::NONE,
473            halftime: DEFAULT_SMOOTHING_HALFTIME,
474            device_delay: 0.0,
475            dejitter: Dejitterer::default(),
476            samples_since_last_clocksync: SAMPLES_BETWEEN_CLOCKSYNCS,
477            next_query_time: 0.0,
478            last_offset: 0.0,
479            last_value: f64::MIN,
480        }
481    }
482
483    /// Set the half-time of the jitter filter.
484    pub fn set_halftime(&mut self, halftime: f64) {
485        self.halftime = halftime;
486    }
487
488    /// Set the calibrated device delay (in seconds) subtracted when
489    /// [`flags::DEVICE_DELAY`] is enabled (`docs/roadmap.md`, step 15).
490    pub fn set_device_delay(&mut self, delay_s: f64) {
491        if delay_s.is_finite() {
492            self.device_delay = delay_s;
493        }
494    }
495
496    /// The configured device delay in seconds.
497    pub fn device_delay(&self) -> f64 {
498        self.device_delay
499    }
500
501    /// The current options.
502    pub fn options(&self) -> u32 {
503        self.options
504    }
505
506    /// The state of the jitter filter.
507    pub fn dejitterer(&self) -> &Dejitterer {
508        &self.dejitter
509    }
510
511    /// Choose the stages.
512    ///
513    /// A change to a stage clears the state of that stage
514    /// (`src/time_postprocessor.cpp:45-58`).
515    pub fn set_options(&mut self, options: u32) {
516        let changed = self.options ^ options;
517        if changed & flags::DEJITTER != 0 {
518            self.dejitter = Dejitterer::default();
519        }
520        if changed & flags::MONOTONIZE != 0 {
521            self.last_value = f64::MIN;
522        }
523        self.options = options;
524    }
525
526    /// Take one timestamp and return the processed value.
527    ///
528    /// The order is clock sync, then jitter removal, then the clamp
529    /// (`src/time_postprocessor.cpp:60-105`).
530    pub fn process(&mut self, value: f64, src: &mut impl OffsetSource) -> f64 {
531        let mut value = value;
532
533        if self.options & flags::DRIFT != 0 {
534            // Opt-in smooth drift model (`docs/roadmap.md`, step 17): evaluate
535            // offset + drift continuously for each timestamp with no 2 s step.
536            if src.was_reset() {
537                self.last_value = f64::MIN;
538                self.dejitter = Dejitterer::default();
539            }
540            value += src.smooth_correction(value);
541        } else if self.options & flags::CLOCKSYNC != 0 {
542            // The offset refreshes every 50 samples, and never more than twice
543            // per second. Bit-exact with `src/time_postprocessor.cpp:60-83`.
544            self.samples_since_last_clocksync = self.samples_since_last_clocksync.saturating_add(1);
545            if self.samples_since_last_clocksync > SAMPLES_BETWEEN_CLOCKSYNCS
546                && src.clock() > self.next_query_time
547            {
548                self.last_offset = src.correction();
549                self.samples_since_last_clocksync = 0;
550                if src.was_reset() {
551                    self.last_offset = src.correction();
552                    self.last_value = f64::MIN;
553                    self.dejitter = Dejitterer::default();
554                }
555                self.next_query_time = src.clock() + MIN_CLOCKSYNC_INTERVAL;
556            }
557            value += self.last_offset;
558        }
559
560        if self.options & flags::DEVICE_DELAY != 0 {
561            value -= self.device_delay;
562        }
563
564        if self.options & flags::DEJITTER != 0 {
565            if !self.dejitter.is_initialized() {
566                let srate = src.srate();
567                self.dejitter = Dejitterer::new(value, srate, self.halftime);
568            }
569            value = self.dejitter.dejitter(value);
570        }
571
572        if self.options & flags::MONOTONIZE != 0 {
573            if value < self.last_value {
574                value = self.last_value;
575            } else {
576                self.last_value = value;
577            }
578        }
579
580        value
581    }
582
583    /// Tell the filter that samples were skipped.
584    pub fn skip_samples(&mut self, skipped: u32) {
585        if self.options & flags::DEJITTER != 0 && self.dejitter.smoothing_applicable() {
586            self.dejitter.skip_samples(skipped);
587        }
588    }
589}
590
591impl Default for PostProcessor {
592    fn default() -> Self {
593        Self::new()
594    }
595}
596
597/// A source with values that a test sets by hand.
598#[derive(Debug, Clone)]
599pub struct FixedSource {
600    /// The offset to return.
601    pub offset: f64,
602    /// The rate to return.
603    pub srate: f64,
604    /// The reset flag to return.
605    pub reset: bool,
606    /// The clock to return. A test moves it forward by hand.
607    pub now: f64,
608}
609
610impl OffsetSource for FixedSource {
611    fn correction(&mut self) -> f64 {
612        self.offset
613    }
614    fn srate(&mut self) -> f64 {
615        self.srate
616    }
617    fn was_reset(&mut self) -> bool {
618        self.reset
619    }
620    fn clock(&mut self) -> f64 {
621        self.now
622    }
623}
624
625#[cfg(test)]
626mod tests {
627    use super::*;
628
629    fn src(srate: f64) -> FixedSource {
630        FixedSource {
631            offset: 0.0,
632            srate,
633            reset: false,
634            now: 1e9,
635        }
636    }
637
638    #[test]
639    fn no_stage_changes_a_timestamp() {
640        let mut p = PostProcessor::new();
641        let mut s = src(1.0);
642        for t in [2.0, 3.1, 3.0, 5.0, 5.9, 7.1] {
643            assert_eq!(p.process(t, &mut s), t);
644        }
645    }
646
647    #[test]
648    fn clock_sync_adds_the_offset() {
649        // The upstream test uses these values (`testing/int/postproc.cpp`).
650        let mut p = PostProcessor::new();
651        p.set_options(flags::CLOCKSYNC);
652        let mut s = src(1.0);
653        s.offset = -50.0;
654        for t in [2.0, 3.1, 3.0, 5.0, 5.9, 7.1] {
655            assert!((p.process(t, &mut s) - (t - 50.0)).abs() < 1e-12);
656        }
657    }
658
659    #[test]
660    fn the_clamp_never_lets_a_timestamp_go_backward() {
661        // The upstream test expects this exact list.
662        let mut p = PostProcessor::new();
663        p.set_options(flags::MONOTONIZE);
664        let mut s = src(1.0);
665        let input = [2.0, 3.1, 3.0, 5.0, 5.9, 7.1];
666        let want = [2.0, 3.1, 3.1, 5.0, 5.9, 7.1];
667        for (i, t) in input.iter().enumerate() {
668            assert!(
669                (p.process(*t, &mut s) - want[i]).abs() < 1e-12,
670                "sample {i}"
671            );
672        }
673    }
674
675    #[test]
676    fn a_stage_change_clears_that_state() {
677        let mut p = PostProcessor::new();
678        p.set_options(flags::MONOTONIZE);
679        let mut s = src(1.0);
680        p.process(100.0, &mut s);
681        // Turning the clamp off and on again clears the running maximum.
682        p.set_options(flags::NONE);
683        p.set_options(flags::MONOTONIZE);
684        assert_eq!(p.process(2.0, &mut s), 2.0);
685    }
686
687    #[test]
688    fn a_rate_of_zero_leaves_the_filter_off() {
689        let d = Dejitterer::new(1000.0, 0.0, 90.0);
690        assert!(!d.smoothing_applicable());
691        let mut d = d;
692        assert_eq!(d.dejitter(1234.5), 1234.5);
693    }
694
695    #[test]
696    fn the_baseline_truncates_to_a_whole_number() {
697        // `src/time_postprocessor.h:18` holds an unsigned integer.
698        let d = Dejitterer::new(1000.75, 100.0, 90.0);
699        assert_eq!(d.t0, 1000);
700        assert!(d.is_initialized());
701    }
702
703    #[test]
704    fn a_first_timestamp_below_one_reads_as_uninitialized() {
705        // A real trap. The baseline truncates to zero, and the test for an
706        // initialized filter compares against zero.
707        let d = Dejitterer::new(0.5, 100.0, 90.0);
708        assert_eq!(d.t0, 0);
709        assert!(!d.is_initialized());
710    }
711
712    #[test]
713    fn the_filter_converges_on_a_clean_ramp() {
714        let srate = 100.0;
715        let t0 = 5000.0;
716        let mut d = Dejitterer::new(t0, srate, 90.0);
717        d.dejitter(t0);
718        for i in 0..2000 {
719            let t = t0 + i as f64 / srate;
720            d.dejitter(t);
721        }
722        // The upstream test asserts the same two bounds.
723        assert!((d.w1 - 1.0 / srate).abs() < 1e-6, "slope {}", d.w1);
724        assert!(d.w0.abs() < 0.1, "intercept {}", d.w0);
725    }
726
727    #[test]
728    fn the_filter_removes_a_constant_latency_from_the_slope() {
729        // A constant offset moves the intercept and leaves the slope alone.
730        let srate = 100.0;
731        let t0 = 5000.0;
732        let latency = 0.05;
733        let mut d = Dejitterer::new(t0, srate, 90.0);
734        d.dejitter(t0);
735        for i in 0..5000 {
736            d.dejitter(t0 + i as f64 / srate + latency);
737        }
738        assert!((d.w1 - 1.0 / srate).abs() < 1e-6);
739        assert!((d.w0 - latency).abs() < 0.1, "intercept {}", d.w0);
740    }
741
742    #[test]
743    fn skipped_samples_move_the_counter() {
744        let mut d = Dejitterer::new(1000.0, 100.0, 90.0);
745        d.dejitter(1000.0);
746        let before = d.samples_since_t0;
747        d.skip_samples(7);
748        assert_eq!(d.samples_since_t0, before + 7);
749    }
750
751    #[test]
752    fn loss_aware_skip_keeps_first_timestamp_after_100_sample_gap_accurate() {
753        let srate = 100.0;
754        let dt = 1.0 / srate;
755        let t0 = 5000.0;
756
757        let mut with_skip = PostProcessor::new();
758        with_skip.set_options(flags::DEJITTER);
759        let mut without_skip = PostProcessor::new();
760        without_skip.set_options(flags::DEJITTER);
761        let mut s = src(srate);
762
763        // Warm up on 200 contiguous samples with zero loss: both must be bit-exact.
764        for i in 0..200 {
765            let t = t0 + i as f64 * dt;
766            let a = with_skip.process(t, &mut s);
767            let b = without_skip.process(t, &mut s);
768            assert_eq!(a.to_bits(), b.to_bits(), "bit-exact with zero loss at {i}");
769        }
770
771        // Remove 100 samples (200..300) and feed sample 300.
772        let true_after = t0 + 300.0 * dt;
773        with_skip.skip_samples(100);
774        let smoothed_with = with_skip.process(true_after, &mut s);
775        let smoothed_without = without_skip.process(true_after, &mut s);
776
777        assert!(
778            (smoothed_with - true_after).abs() < dt,
779            "expected error < {dt} s, got {}",
780            (smoothed_with - true_after).abs()
781        );
782        // Without `skip_samples`, the filter lags by nearly a full second (~100 intervals).
783        assert!(
784            (true_after - smoothed_without) > 50.0 * dt,
785            "expected large lag without skip_samples, got {}",
786            true_after - smoothed_without
787        );
788    }
789
790    #[test]
791    fn clock_sync_refreshes_at_most_twice_per_second() {
792        let mut p = PostProcessor::new();
793        p.set_options(flags::CLOCKSYNC);
794        let mut s = src(1.0);
795        s.offset = 1.0;
796        s.now = 100.0;
797        // The first sample queries, because the counter starts at the limit.
798        p.process(0.0, &mut s);
799        s.offset = 99.0;
800        // The next 50 samples must not query again.
801        for _ in 0..50 {
802            let got = p.process(0.0, &mut s);
803            assert!((got - 1.0).abs() < 1e-12, "the offset changed too early");
804        }
805        // The counter is ready, but the clock has not moved.
806        assert!((p.process(0.0, &mut s) - 1.0).abs() < 1e-12);
807        // Move the clock past the interval.
808        s.now = 101.0;
809        assert!((p.process(0.0, &mut s) - 99.0).abs() < 1e-12);
810    }
811
812    #[test]
813    fn a_reset_gives_the_filter_a_new_baseline() {
814        // A reset means the source restarted, so the old fit describes a
815        // process that no longer exists. The filter takes a new baseline from
816        // the first timestamp after the reset.
817        let mut p = PostProcessor::new();
818        p.set_options(flags::CLOCKSYNC | flags::DEJITTER);
819        let mut s = src(100.0);
820        s.now = 100.0;
821
822        p.process(5000.0, &mut s);
823        assert_eq!(p.dejitterer().t0, 5000);
824
825        // Move the counter past the limit while the clock stays put, so no
826        // query fires yet.
827        for i in 1..60 {
828            p.process(5000.0 + i as f64 / 100.0, &mut s);
829        }
830        assert_eq!(p.dejitterer().t0, 5000, "no query fired yet");
831
832        // Now the clock passes the interval and the source reports a reset.
833        s.reset = true;
834        s.now = 101.0;
835        p.process(9000.0, &mut s);
836        assert_eq!(p.dejitterer().t0, 9000, "the reset gives a new baseline");
837    }
838
839    #[test]
840    fn the_clamp_state_clears_on_a_reset() {
841        // The clearing is visible only when the resetting sample itself
842        // carries a lower value. Any later sample sets the maximum again.
843        //
844        // The clock must stay put while the counter fills, so that the query
845        // fires on the call that carries the low value and on no earlier one.
846        let mut p = PostProcessor::new();
847        p.set_options(flags::CLOCKSYNC | flags::MONOTONIZE);
848        let mut s = src(100.0);
849        s.now = 100.0;
850
851        p.process(500.0, &mut s);
852        for _ in 0..55 {
853            p.process(500.0, &mut s);
854        }
855        // The counter is ready and the clock has not moved, so no query fired.
856        // A lower value is still clamped.
857        assert!((p.process(10.0, &mut s) - 500.0).abs() < 1e-12);
858
859        // Move the clock past the interval and report a reset. The query now
860        // fires on this call, and the clamp state clears before the clamp runs.
861        s.reset = true;
862        s.now = 101.0;
863        assert!((p.process(10.0, &mut s) - 10.0).abs() < 1e-12);
864    }
865
866    #[test]
867    fn drift_model_recovers_slope_rejects_rtt_spikes_and_removes_burst_steps() {
868        let mut model = DriftModel::new();
869        // True clock: offset(t) = 10.0 + 50e-6 * (t - 1000.0) (+50 ppm drift).
870        let true_offset = |t: f64| 10.0 + 50e-6 * (t - 1000.0);
871
872        for k in 0..20 {
873            let t = 1000.0 + (k as f64) * 2.0;
874            // Inject asymmetric Wi-Fi RTT spikes on bursts 5 and 12.
875            let (noise, rtt) = if k == 5 {
876                (0.008, 0.020)
877            } else if k == 12 {
878                (-0.006, 0.015)
879            } else {
880                (((k % 3) as f64 - 1.0) * 15e-6, 0.0005)
881            };
882            model.update(t, true_offset(t) + noise, rtt);
883        }
884
885        let fit = model.fit().expect("fitted drift model");
886        assert!(
887            (fit.drift - 50e-6).abs() < 1e-6,
888            "expected drift ~50 ppm, got {:.3} ppm",
889            fit.drift * 1e6
890        );
891        // Evaluate smoothly at mid-burst time t_local = 1039.0 s:
892        // raw step model uses burst 19 (t=1038.0), lagging by 50 us;
893        // drift model tracks continuously with < 20 us error.
894        let t_local = 1039.0;
895        let true_off = true_offset(t_local);
896        let remote_ts = t_local - true_off;
897        let pred_off = fit.offset_for_remote(remote_ts);
898        assert!(
899            (pred_off - true_off).abs() < 20e-6,
900            "expected smooth error < 20 us, got {:.1} us",
901            (pred_off - true_off).abs() * 1e6
902        );
903
904        // Compare max step across burst boundary (k=19 -> k=20):
905        // stepped model jumps by ~100 us (2 s * 50 ppm); drift model step is tiny.
906        let before = model
907            .offset_for_remote(1039.99 - true_offset(1039.99))
908            .unwrap();
909        model.update(1040.0, true_offset(1040.0), 0.0005);
910        let after = model
911            .offset_for_remote(1040.01 - true_offset(1040.01))
912            .unwrap();
913        let jump = ((after - before) - 50e-6 * 0.02).abs();
914        assert!(
915            jump < 10e-6,
916            "expected smooth burst transition (< 10 us), got {:.1} us",
917            jump * 1e6
918        );
919    }
920
921    #[test]
922    fn device_delay_is_opt_in_and_default_timestamps_are_unchanged() {
923        let mut default_pp = PostProcessor::new();
924        default_pp.set_device_delay(0.025);
925        let mut s = src(100.0);
926        // Without `flags::DEVICE_DELAY`, timestamps must not change at all.
927        assert_eq!(
928            default_pp.process(500.0, &mut s).to_bits(),
929            500.0f64.to_bits()
930        );
931
932        // With `flags::DEVICE_DELAY`, the 25 ms delay is subtracted.
933        default_pp.set_options(flags::DEVICE_DELAY);
934        assert!((default_pp.process(500.025, &mut s) - 500.0).abs() < 1e-12);
935    }
936}