Skip to main content

labstream_time/
sync.rs

1//! Real-time multi-stream time-grid alignment and windowed-sinc resampler
2//! (`docs/roadmap.md`, step 18).
3//!
4//! Two asynchronous ADCs without a shared hardware clock sample the same
5//! physical signal with a worst-case sub-sample offset of `T_s / 2` (up to
6//! 72 degrees at 100 Hz for 250 SPS streams). [`StreamAligner`] buffers each
7//! stream in a bounded ring, tracks explicit and timestamp-inferred gaps, and
8//! resamples all streams onto one strictly monotonic common time grid using
9//! Blackman-windowed sinc fractional-delay interpolation with bounded
10//! lookahead.
11
12use std::collections::VecDeque;
13
14/// Default half-width of the windowed-sinc kernel in source samples (`2 * 16 = 32` taps).
15pub const DEFAULT_HALF_WIDTH: usize = 16;
16
17/// Default per-stream ring buffer capacity in samples.
18pub const DEFAULT_MAX_BUFFER_SAMPLES: usize = 8192;
19
20/// Default timestamp-jump multiple of `1 / nominal_srate` treated as a gap.
21pub const DEFAULT_GAP_FACTOR: f64 = 1.8;
22
23/// Description of one input stream fed into [`StreamAligner`].
24#[derive(Debug, Clone, Copy, PartialEq)]
25pub struct StreamSpec {
26    /// Number of numeric channels in this stream.
27    pub channels: usize,
28    /// Nominal sampling rate of this stream in Hz (must be positive and finite).
29    pub nominal_srate: f64,
30}
31
32/// Configuration for [`StreamAligner`] and `SyncGroup`.
33#[derive(Debug, Clone, Copy, PartialEq)]
34pub struct SyncConfig {
35    /// Common output grid sampling rate in Hz.
36    pub output_rate: f64,
37    /// Sinc kernel half-width in source samples (lookahead = `half_width / min_rate`).
38    pub half_width: usize,
39    /// Maximum samples buffered per input stream (bounds memory).
40    pub max_buffer_samples: usize,
41    /// Gap threshold as a multiple of nominal sample period (`1.8` default).
42    pub gap_threshold_factor: f64,
43    /// When true (default), `SyncGroup` enables `CLOCKSYNC | DRIFT | DEVICE_DELAY`
44    /// on each inlet automatically.
45    pub auto_postprocess: bool,
46}
47
48impl SyncConfig {
49    /// Create a default configuration for `output_rate` Hz.
50    pub fn new(output_rate: f64) -> Self {
51        SyncConfig {
52            output_rate,
53            half_width: DEFAULT_HALF_WIDTH,
54            max_buffer_samples: DEFAULT_MAX_BUFFER_SAMPLES,
55            gap_threshold_factor: DEFAULT_GAP_FACTOR,
56            auto_postprocess: true,
57        }
58    }
59}
60
61/// One aligned sample on the common monotonic output grid.
62#[derive(Debug, Clone, PartialEq)]
63pub struct AlignedSample {
64    /// Monotonic timestamp on the common output grid, in seconds.
65    pub timestamp: f64,
66    /// Concatenated channel values across all input streams, in stream order.
67    /// Channels belonging to a stream with a gap at this timestamp are `NaN`.
68    pub values: Vec<f64>,
69    /// Bitmask of streams that experienced a gap covering this timestamp
70    /// (bit `i` = stream `i`; `0` means every stream is clean).
71    pub gap_mask: u64,
72}
73
74impl AlignedSample {
75    /// True when at least one input stream had a gap at this grid timestamp.
76    pub fn any_gap(&self) -> bool {
77        self.gap_mask != 0
78    }
79}
80
81#[derive(Debug)]
82struct StreamBuf {
83    spec: StreamSpec,
84    dt: f64,
85    timestamps: VecDeque<f64>,
86    /// Interleaved channel values (`timestamps.len() * spec.channels`).
87    values: VecDeque<f64>,
88    /// Explicit gap intervals `(start, end)` reported by the inlet.
89    gaps: VecDeque<(f64, f64)>,
90}
91
92impl StreamBuf {
93    fn new(spec: StreamSpec) -> Self {
94        StreamBuf {
95            spec,
96            dt: 1.0 / spec.nominal_srate,
97            timestamps: VecDeque::new(),
98            values: VecDeque::new(),
99            gaps: VecDeque::new(),
100        }
101    }
102
103    fn push(&mut self, ts: f64, vals: &[f64], max_samples: usize, gap_factor: f64) {
104        if !ts.is_finite() || vals.len() != self.spec.channels {
105            return;
106        }
107        if let Some(&prev) = self.timestamps.back() {
108            if ts <= prev {
109                // Keep per-stream buffer strictly monotonic.
110                return;
111            }
112            if ts - prev > self.dt * gap_factor {
113                self.record_gap(prev, ts);
114            }
115        }
116        if self.timestamps.len() >= max_samples {
117            self.timestamps.pop_front();
118            for _ in 0..self.spec.channels {
119                self.values.pop_front();
120            }
121        }
122        self.timestamps.push_back(ts);
123        self.values.extend(vals.iter().copied());
124    }
125
126    fn record_gap(&mut self, start: f64, end: f64) {
127        if start.is_finite() && end.is_finite() && end > start {
128            if self.gaps.len() >= 256 {
129                self.gaps.pop_front();
130            }
131            self.gaps.push_back((start, end));
132        }
133    }
134
135    fn has_explicit_gap(&self, t: f64) -> bool {
136        self.gaps.iter().any(|&(a, b)| t > a && t < b)
137    }
138
139    fn oldest_ts(&self) -> Option<f64> {
140        self.timestamps.front().copied()
141    }
142
143    fn latest_ts(&self) -> Option<f64> {
144        self.timestamps.back().copied()
145    }
146
147    /// Trim samples strictly older than `cutoff` and expired gap intervals.
148    fn trim_before(&mut self, cutoff: f64) {
149        while let Some(&front) = self.timestamps.front() {
150            if front < cutoff {
151                self.timestamps.pop_front();
152                for _ in 0..self.spec.channels {
153                    self.values.pop_front();
154                }
155            } else {
156                break;
157            }
158        }
159        while let Some(&(_, end)) = self.gaps.front() {
160            if end < cutoff {
161                self.gaps.pop_front();
162            } else {
163                break;
164            }
165        }
166    }
167
168    /// Evaluate windowed-sinc interpolation at `t_target`.
169    ///
170    /// Returns `true` if the interpolation is clean, or `false` if a gap covers
171    /// `t_target` (in which case `dst` is filled with `f64::NAN`).
172    fn interpolate(
173        &self,
174        t_target: f64,
175        half_width: usize,
176        gap_factor: f64,
177        dst: &mut [f64],
178    ) -> bool {
179        let ch = self.spec.channels;
180        if self.timestamps.is_empty() || self.has_explicit_gap(t_target) {
181            dst.fill(f64::NAN);
182            return false;
183        }
184        let n = self.timestamps.len();
185        // Binary search for the first index with timestamp >= t_target.
186        let mut lo = 0usize;
187        let mut hi = n;
188        while lo < hi {
189            let mid = lo + (hi - lo) / 2;
190            if self.timestamps[mid] < t_target {
191                lo = mid + 1;
192            } else {
193                hi = mid;
194            }
195        }
196
197        // Check bracketing samples around `t_target`.
198        if lo == 0 {
199            if (self.timestamps[0] - t_target).abs() > self.dt * 0.5 {
200                dst.fill(f64::NAN);
201                return false;
202            }
203        } else if lo == n {
204            if (t_target - self.timestamps[n - 1]).abs() > self.dt * 0.5 {
205                dst.fill(f64::NAN);
206                return false;
207            }
208        } else if self.timestamps[lo] - self.timestamps[lo - 1] > self.dt * gap_factor {
209            dst.fill(f64::NAN);
210            return false;
211        }
212
213        let center = lo.saturating_sub(1);
214        let start = center.saturating_sub(half_width);
215        let end = (center + half_width + 2).min(n);
216
217        // If any step inside the active kernel window is a gap, keep the window
218        // strictly on the same side of the gap or report a gap if it touches
219        // the immediate neighborhood.
220        let l_f = half_width as f64;
221        dst.fill(0.0);
222        let mut w_sum = 0.0f64;
223
224        for idx in start..end {
225            let ti = self.timestamps[idx];
226            // Do not cross a gap boundary when gathering sinc taps.
227            if idx < lo && self.has_explicit_gap(0.5 * (ti + t_target)) {
228                continue;
229            }
230            if idx >= lo && self.has_explicit_gap(0.5 * (t_target + ti)) {
231                continue;
232            }
233            let u = (t_target - ti) / self.dt;
234            if u.abs() >= l_f {
235                continue;
236            }
237            let w = blackman_sinc(u, l_f);
238            w_sum += w;
239            let base = idx * ch;
240            for (c, out_c) in dst.iter_mut().enumerate().take(ch) {
241                *out_c += w * self.values[base + c];
242            }
243        }
244
245        if w_sum.abs() < 1e-12 {
246            dst.fill(f64::NAN);
247            return false;
248        }
249        let inv = 1.0 / w_sum;
250        for v in dst.iter_mut() {
251            *v *= inv;
252        }
253        true
254    }
255}
256
257/// Blackman-windowed normalized sinc kernel evaluated at `u` (in samples) with
258/// half-width `half_width`.
259#[inline]
260fn blackman_sinc(u: f64, half_width: f64) -> f64 {
261    let pi = core::f64::consts::PI;
262    let sinc = if u.abs() < 1e-12 {
263        1.0
264    } else {
265        let x = pi * u;
266        x.sin() / x
267    };
268    let ratio = u / half_width;
269    let win = 0.42 + 0.5 * (pi * ratio).cos() + 0.08 * (2.0 * pi * ratio).cos();
270    sinc * win
271}
272
273/// Real-time multi-stream aligner and fractional-delay sinc resampler.
274#[derive(Debug)]
275pub struct StreamAligner {
276    cfg: SyncConfig,
277    streams: Vec<StreamBuf>,
278    total_channels: usize,
279    grid_dt: f64,
280    next_grid_ts: Option<f64>,
281    last_emitted_ts: Option<f64>,
282}
283
284impl StreamAligner {
285    /// Create a new aligner for `specs` using `cfg`.
286    pub fn new(specs: Vec<StreamSpec>, cfg: SyncConfig) -> Result<Self, &'static str> {
287        if specs.is_empty() {
288            return Err("SyncGroup requires at least one stream");
289        }
290        if specs.len() > 64 {
291            return Err("SyncGroup supports at most 64 streams");
292        }
293        if !cfg.output_rate.is_finite() || cfg.output_rate <= 0.0 {
294            return Err("output_rate must be positive and finite");
295        }
296        if cfg.half_width < 2 {
297            return Err("half_width must be at least 2");
298        }
299        if cfg.max_buffer_samples < cfg.half_width * 4 {
300            return Err("max_buffer_samples must be at least 4 * half_width");
301        }
302        let mut total_channels = 0usize;
303        let mut streams = Vec::with_capacity(specs.len());
304        for s in specs {
305            if s.channels == 0 || !s.nominal_srate.is_finite() || s.nominal_srate <= 0.0 {
306                return Err("each stream must have channels > 0 and finite nominal_srate > 0");
307            }
308            total_channels += s.channels;
309            streams.push(StreamBuf::new(s));
310        }
311        Ok(StreamAligner {
312            cfg,
313            streams,
314            total_channels,
315            grid_dt: 1.0 / cfg.output_rate,
316            next_grid_ts: None,
317            last_emitted_ts: None,
318        })
319    }
320
321    /// Number of input streams.
322    pub fn stream_count(&self) -> usize {
323        self.streams.len()
324    }
325
326    /// Total concatenated channels across all streams.
327    pub fn total_channels(&self) -> usize {
328        self.total_channels
329    }
330
331    /// Common output sampling rate in Hz.
332    pub fn output_rate(&self) -> f64 {
333        self.cfg.output_rate
334    }
335
336    /// Lookahead latency in seconds (`half_width / min_input_srate`).
337    pub fn lookahead_seconds(&self) -> f64 {
338        let min_rate = self
339            .streams
340            .iter()
341            .map(|s| s.spec.nominal_srate)
342            .fold(f64::INFINITY, f64::min);
343        self.cfg.half_width as f64 / min_rate
344    }
345
346    /// Push one `f64` sample for `stream_idx`.
347    pub fn push(&mut self, stream_idx: usize, timestamp: f64, values: &[f64]) {
348        if let Some(buf) = self.streams.get_mut(stream_idx) {
349            buf.push(
350                timestamp,
351                values,
352                self.cfg.max_buffer_samples,
353                self.cfg.gap_threshold_factor,
354            );
355        }
356    }
357
358    /// Push one `f32` sample for `stream_idx`.
359    pub fn push_f32(&mut self, stream_idx: usize, timestamp: f64, values: &[f32]) {
360        if let Some(buf) = self.streams.get_mut(stream_idx) {
361            if values.len() != buf.spec.channels {
362                return;
363            }
364            let tmp: Vec<f64> = values.iter().map(|&v| v as f64).collect();
365            buf.push(
366                timestamp,
367                &tmp,
368                self.cfg.max_buffer_samples,
369                self.cfg.gap_threshold_factor,
370            );
371        }
372    }
373
374    /// Record an explicit gap interval `(start, end)` from `Inlet::take_gaps`.
375    pub fn mark_gap(&mut self, stream_idx: usize, start_ts: f64, end_ts: f64) {
376        if let Some(buf) = self.streams.get_mut(stream_idx) {
377            buf.record_gap(start_ts, end_ts);
378        }
379    }
380
381    /// Number of buffered samples currently held for `stream_idx`.
382    pub fn buffered_samples(&self, stream_idx: usize) -> usize {
383        self.streams
384            .get(stream_idx)
385            .map_or(0, |b| b.timestamps.len())
386    }
387
388    /// Pull up to `max_samples` aligned samples onto the common monotonic grid.
389    pub fn pull_aligned(&mut self, out: &mut Vec<AlignedSample>, max_samples: usize) -> usize {
390        if max_samples == 0 {
391            return 0;
392        }
393        // Every stream must have at least one sample before we know the common horizon.
394        let mut ready_horizon = f64::INFINITY;
395        let mut init_start = f64::NEG_INFINITY;
396        for s in &self.streams {
397            let Some(latest) = s.latest_ts() else {
398                return 0;
399            };
400            let Some(oldest) = s.oldest_ts() else {
401                return 0;
402            };
403            let margin = self.cfg.half_width as f64 * s.dt;
404            ready_horizon = ready_horizon.min(latest - margin);
405            init_start = init_start.max(oldest + margin);
406        }
407
408        let mut t = match self.next_grid_ts {
409            Some(existing) => existing,
410            None => {
411                if init_start > ready_horizon {
412                    return 0;
413                }
414                self.next_grid_ts = Some(init_start);
415                init_start
416            }
417        };
418
419        let mut emitted = 0usize;
420        while emitted < max_samples && t <= ready_horizon {
421            // Enforce strict output monotonicity even across clock resets.
422            if let Some(last) = self.last_emitted_ts {
423                if t <= last {
424                    t = last + self.grid_dt;
425                    continue;
426                }
427            }
428
429            let mut values = vec![0.0f64; self.total_channels];
430            let mut gap_mask = 0u64;
431            let mut offset = 0usize;
432            for (idx, s) in self.streams.iter().enumerate() {
433                let ch = s.spec.channels;
434                let clean = s.interpolate(
435                    t,
436                    self.cfg.half_width,
437                    self.cfg.gap_threshold_factor,
438                    &mut values[offset..offset + ch],
439                );
440                if !clean {
441                    gap_mask |= 1u64 << idx;
442                }
443                offset += ch;
444            }
445
446            out.push(AlignedSample {
447                timestamp: t,
448                values,
449                gap_mask,
450            });
451            self.last_emitted_ts = Some(t);
452            t += self.grid_dt;
453            emitted += 1;
454        }
455
456        self.next_grid_ts = Some(t);
457
458        // Trim old samples behind the active kernel window so memory stays bounded.
459        for s in &mut self.streams {
460            let cutoff = t - (self.cfg.half_width as f64 + 2.0) * s.dt;
461            s.trim_before(cutoff);
462        }
463
464        emitted
465    }
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471
472    /// Criterion 1 of step 18:
473    /// Two simulated asynchronous 250 SPS streams of a 100 Hz sine wave with a
474    /// half-sample (2 ms) clock phase offset align to < 2 degrees of phase
475    /// error (down from 72 degrees with nearest-sample pairing).
476    #[test]
477    fn two_async_250sps_100hz_streams_with_half_sample_offset_align_below_2_deg() {
478        let fs = 250.0f64;
479        let f_sig = 100.0f64;
480        let dt = 1.0 / fs;
481        let half_sample = 0.5 * dt; // 2 ms -> 72 degrees at 100 Hz!
482
483        let mut aligner = StreamAligner::new(
484            vec![
485                StreamSpec {
486                    channels: 1,
487                    nominal_srate: fs,
488                },
489                StreamSpec {
490                    channels: 1,
491                    nominal_srate: fs,
492                },
493            ],
494            SyncConfig::new(fs),
495        )
496        .unwrap();
497
498        let n = 400;
499        let mut aligned = Vec::new();
500        for k in 0..n {
501            let t0 = 10.0 + k as f64 * dt;
502            let t1 = 10.0 + k as f64 * dt + half_sample;
503            let v0 = (2.0 * core::f64::consts::PI * f_sig * t0).sin();
504            let v1 = (2.0 * core::f64::consts::PI * f_sig * t1).sin();
505            aligner.push(0, t0, &[v0]);
506            aligner.push(1, t1, &[v1]);
507            aligner.pull_aligned(&mut aligned, 64);
508        }
509
510        assert!(aligned.len() > 200, "got {} aligned samples", aligned.len());
511        // Skip first few and check steady-state phase difference between stream 0 and stream 1
512        // via cross-correlation / quadrature phase estimation.
513        let slice = &aligned[10..aligned.len() - 10];
514        let mut sum_sq_err = 0.0f64;
515        let mut sum_sq_ref = 0.0f64;
516        for (i, s) in slice.iter().enumerate() {
517            assert!(!s.any_gap());
518            if i > 0 {
519                assert!(s.timestamp > slice[i - 1].timestamp);
520            }
521            let diff = s.values[0] - s.values[1];
522            sum_sq_err += diff * diff;
523            sum_sq_ref += s.values[0] * s.values[0];
524        }
525        // For two equal-amplitude sine waves differing by phase dphi:
526        // RMS(sin(wt) - sin(wt + dphi)) / RMS(sin(wt)) = 2 * sin(|dphi| / 2) ≈ |dphi| (radians).
527        let rel_rms = (sum_sq_err / sum_sq_ref).sqrt();
528        let phase_err_deg = 2.0 * (rel_rms / 2.0).min(1.0).asin() * 180.0 / core::f64::consts::PI;
529        assert!(
530            phase_err_deg < 2.0,
531            "expected phase error < 2 deg (vs 72 deg nearest-sample), got {phase_err_deg:.4} deg"
532        );
533    }
534
535    /// Criterion 2 of step 18:
536    /// Output timestamps stay monotonic across clock drift and recovery, and
537    /// every inlet gap propagates as an explicit gap marker.
538    #[test]
539    fn gaps_propagate_explicitly_and_memory_stays_bounded() {
540        let fs = 250.0f64;
541        let dt = 1.0 / fs;
542        let mut cfg = SyncConfig::new(fs);
543        cfg.max_buffer_samples = 128;
544
545        let mut aligner = StreamAligner::new(
546            vec![
547                StreamSpec {
548                    channels: 1,
549                    nominal_srate: fs,
550                },
551                StreamSpec {
552                    channels: 1,
553                    nominal_srate: fs,
554                },
555            ],
556            cfg,
557        )
558        .unwrap();
559
560        let mut aligned = Vec::new();
561        for k in 0..300 {
562            let t0 = 100.0 + k as f64 * dt;
563            // Stream 1 has a +100 ppm drift and drops samples 120..140.
564            let t1 = 100.0 + k as f64 * dt * 1.0001;
565            aligner.push(0, t0, &[1.0]);
566            if !(120..140).contains(&k) {
567                aligner.push(1, t1, &[2.0]);
568            }
569            aligner.pull_aligned(&mut aligned, 64);
570            assert!(aligner.buffered_samples(0) <= cfg.max_buffer_samples);
571            assert!(aligner.buffered_samples(1) <= cfg.max_buffer_samples);
572        }
573
574        // Strict monotonicity.
575        for w in aligned.windows(2) {
576            assert!(w[1].timestamp > w[0].timestamp);
577        }
578        // Gap on stream 1 (bit 1 = 0b10) must be explicitly flagged.
579        let gap_samples: Vec<_> = aligned
580            .iter()
581            .filter(|s| (s.gap_mask & 0b10) != 0)
582            .collect();
583        assert!(
584            !gap_samples.is_empty(),
585            "expected explicit gap markers on stream 1"
586        );
587        for g in &gap_samples {
588            assert!(g.values[0].is_finite());
589            assert!(g.values[1].is_nan());
590        }
591        // Clean samples after the gap recover to 2.0.
592        let last = aligned.last().unwrap();
593        assert_eq!(last.gap_mask, 0);
594        assert!((last.values[1] - 2.0).abs() < 1e-6);
595    }
596}