1use 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
18pub struct SyncGroup {
21 inlets: Vec<Inlet>,
22 aligner: StreamAligner,
23 scratch: Vec<PackedSample>,
24 val_scratch: Vec<f64>,
25}
26
27impl SyncGroup {
28 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 pub fn stream_count(&self) -> usize {
78 self.aligner.stream_count()
79 }
80
81 pub fn total_channels(&self) -> usize {
83 self.aligner.total_channels()
84 }
85
86 pub fn output_rate(&self) -> f64 {
88 self.aligner.output_rate()
89 }
90
91 pub fn lookahead_seconds(&self) -> f64 {
93 self.aligner.lookahead_seconds()
94 }
95
96 pub fn inlets(&self) -> &[Inlet] {
98 &self.inlets
99 }
100
101 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 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}