Skip to main content

labstream_net/
sync.rs

1//! Live multi-inlet time-grid aligner and resampler (`docs/roadmap.md`, step 18).
2//!
3//! [`SyncGroup`] combines `N` live numeric [`Inlet`]s (enabling the opt-in
4//! drift clock from step 17 and calibrated device delay from step 15 by
5//! default), forwards inlet gap descriptors, and resamples all streams onto one
6//! common monotonic time grid with bounded lookahead and bounded memory.
7
8use crate::inlet::Inlet;
9use labstream_time::flags;
10pub use labstream_time::sync::{
11    AlignedSample, StreamAligner, StreamSpec, SyncConfig, DEFAULT_GAP_FACTOR, DEFAULT_HALF_WIDTH,
12    DEFAULT_MAX_BUFFER_SAMPLES,
13};
14use labstream_wire::{Format, PackedSample, Value};
15use std::io;
16use std::time::{Duration, Instant};
17
18/// Live multi-stream aligner combining `N` numeric [`Inlet`]s onto one common
19/// monotonic time grid.
20pub struct SyncGroup {
21    inlets: Vec<Inlet>,
22    aligner: StreamAligner,
23    scratch: Vec<PackedSample>,
24    val_scratch: Vec<f64>,
25}
26
27impl SyncGroup {
28    /// Build a [`SyncGroup`] from opened numeric [`Inlet`]s and `cfg`.
29    ///
30    /// When `cfg.auto_postprocess` is true (the default), enables
31    /// `CLOCKSYNC | DRIFT | DEVICE_DELAY` on each inlet so clock drift and
32    /// calibrated device delays are corrected before resampling.
33    pub fn new(mut inlets: Vec<Inlet>, cfg: SyncConfig) -> io::Result<Self> {
34        if inlets.is_empty() {
35            return Err(io::Error::new(
36                io::ErrorKind::InvalidInput,
37                "SyncGroup requires at least one inlet",
38            ));
39        }
40        let mut specs = Vec::with_capacity(inlets.len());
41        for inlet in &mut inlets {
42            let (fmt, channels, nominal_srate) = {
43                let info = inlet.info();
44                (info.format, info.channel_count as usize, info.nominal_srate)
45            };
46            if fmt == Format::String || fmt == Format::Undefined {
47                return Err(io::Error::new(
48                    io::ErrorKind::InvalidInput,
49                    "SyncGroup supports numeric streams only",
50                ));
51            }
52            if !nominal_srate.is_finite() || nominal_srate <= 0.0 {
53                return Err(io::Error::new(
54                    io::ErrorKind::InvalidInput,
55                    "SyncGroup requires regular streams with nominal_srate > 0",
56                ));
57            }
58            if cfg.auto_postprocess {
59                inlet.set_postprocessing(flags::CLOCKSYNC | flags::DRIFT | flags::DEVICE_DELAY);
60            }
61            specs.push(StreamSpec {
62                channels,
63                nominal_srate,
64            });
65        }
66        let aligner = StreamAligner::new(specs, cfg)
67            .map_err(|msg| io::Error::new(io::ErrorKind::InvalidInput, msg))?;
68        Ok(SyncGroup {
69            inlets,
70            aligner,
71            scratch: Vec::with_capacity(256),
72            val_scratch: Vec::with_capacity(64),
73        })
74    }
75
76    /// Number of input streams in this group.
77    pub fn stream_count(&self) -> usize {
78        self.aligner.stream_count()
79    }
80
81    /// Total concatenated channels across all input streams.
82    pub fn total_channels(&self) -> usize {
83        self.aligner.total_channels()
84    }
85
86    /// Common output grid sampling rate in Hz.
87    pub fn output_rate(&self) -> f64 {
88        self.aligner.output_rate()
89    }
90
91    /// Lookahead latency in seconds (`half_width / min_input_srate`).
92    pub fn lookahead_seconds(&self) -> f64 {
93        self.aligner.lookahead_seconds()
94    }
95
96    /// Borrow the underlying inlets.
97    pub fn inlets(&self) -> &[Inlet] {
98        &self.inlets
99    }
100
101    /// Drain all currently available samples and gaps from each inlet into the
102    /// aligner without blocking.
103    fn pump_inlets(&mut self) -> io::Result<usize> {
104        let mut pulled_any = 0usize;
105        for (idx, inlet) in self.inlets.iter_mut().enumerate() {
106            for gap in inlet.take_gaps() {
107                self.aligner.mark_gap(idx, gap.start, gap.end);
108            }
109            self.scratch.clear();
110            let got = inlet.pull_chunk_packed(&mut self.scratch, 1024, Duration::ZERO)?;
111            pulled_any += got;
112            let ch = inlet.info().channel_count as usize;
113            let fmt = inlet.info().format;
114            for sample in &self.scratch {
115                self.val_scratch.clear();
116                decode_packed_to_f64(sample, fmt, ch, &mut self.val_scratch);
117                if self.val_scratch.len() == ch {
118                    self.aligner.push(idx, sample.timestamp, &self.val_scratch);
119                }
120            }
121        }
122        Ok(pulled_any)
123    }
124
125    /// Pull up to `max_samples` aligned samples onto the common monotonic time
126    /// grid, waiting up to `timeout` for enough lookahead samples to arrive.
127    pub fn pull(
128        &mut self,
129        out: &mut Vec<AlignedSample>,
130        max_samples: usize,
131        timeout: Duration,
132    ) -> io::Result<usize> {
133        if max_samples == 0 {
134            return Ok(0);
135        }
136        let deadline = Instant::now() + timeout;
137        loop {
138            let _ = self.pump_inlets()?;
139            let emitted = self.aligner.pull_aligned(out, max_samples);
140            if emitted > 0 || Instant::now() >= deadline {
141                return Ok(emitted);
142            }
143            let rem = deadline.saturating_duration_since(Instant::now());
144            std::thread::sleep(rem.min(Duration::from_millis(5)));
145        }
146    }
147}
148
149fn decode_packed_to_f64(sample: &PackedSample, fmt: Format, channels: usize, dst: &mut Vec<f64>) {
150    if let Some(raw) = sample.as_numeric_bytes(fmt) {
151        match fmt {
152            Format::Float32 => {
153                for b in raw.chunks_exact(4).take(channels) {
154                    dst.push(f32::from_ne_bytes(b.try_into().unwrap()) as f64);
155                }
156            }
157            Format::Double64 => {
158                for b in raw.chunks_exact(8).take(channels) {
159                    dst.push(f64::from_ne_bytes(b.try_into().unwrap()));
160                }
161            }
162            Format::Int32 => {
163                for b in raw.chunks_exact(4).take(channels) {
164                    dst.push(i32::from_ne_bytes(b.try_into().unwrap()) as f64);
165                }
166            }
167            Format::Int16 => {
168                for b in raw.chunks_exact(2).take(channels) {
169                    dst.push(i16::from_ne_bytes(b.try_into().unwrap()) as f64);
170                }
171            }
172            Format::Int8 => {
173                for &b in raw.iter().take(channels) {
174                    dst.push((b as i8) as f64);
175                }
176            }
177            Format::Int64 => {
178                for b in raw.chunks_exact(8).take(channels) {
179                    dst.push(i64::from_ne_bytes(b.try_into().unwrap()) as f64);
180                }
181            }
182            Format::String | Format::Undefined => {}
183        }
184        return;
185    }
186    let s = sample.to_sample();
187    for v in s.values.into_iter().take(channels) {
188        match v {
189            Value::F32(x) => dst.push(x as f64),
190            Value::F64(x) => dst.push(x),
191            Value::I32(x) => dst.push(x as f64),
192            Value::I16(x) => dst.push(x as f64),
193            Value::I8(x) => dst.push(x as f64),
194            Value::I64(x) => dst.push(x as f64),
195            Value::Str(_) => {}
196        }
197    }
198}