Skip to main content

labstream_proto/
select.rs

1//! Channel projection and windowed-sinc FIR decimation for `select/1`
2//! (`docs/roadmap.md`, step 6).
3//!
4//! # Decimation filter specification
5//!
6//! For an integer decimation factor `D >= 2`, the outlet applies a symmetric
7//! Type I linear-phase Hamming-windowed sinc low-pass FIR filter to each
8//! selected numeric channel before keeping one sample every `D` input samples:
9//!
10//! - Tap count: `N = (4 * D + 1).min(257)` (always odd, center `M = (N - 1) / 2`).
11//! - Normalized cutoff frequency: `fc = 0.45 / D` (cycles per input sample).
12//! - Unnormalized impulse response for `k = 0..N`:
13//!   - `h_raw[M] = 2 * fc`
14//!   - `h_raw[k] = sin(2 * pi * fc * (k - M)) / (pi * (k - M))` for `k != M`
15//! - Hamming window: `w[k] = 0.54 - 0.46 * cos(2 * pi * k / (N - 1))`.
16//! - Normalized taps: `h[k] = (h_raw[k] * w[k]) / sum_j(h_raw[j] * w[j])`.
17//!
18//! The DC gain is exactly `1.0`. Each decimated output sample carries the
19//! timestamp of the center tap (`t_last - M / nominal_srate`), removing the
20//! constant group delay of the linear-phase filter.
21
22use crate::features::SelectParam;
23use labstream_wire::{Format, PackedSample, PackedValues};
24use std::collections::VecDeque;
25use std::f64::consts::PI;
26use std::sync::Arc;
27
28/// Maximum FIR tap count so very large decimation factors stay fast.
29const MAX_TAPS: usize = 257;
30
31/// Compute the normalized Hamming-windowed sinc low-pass FIR taps for
32/// integer decimation factor `decimate`.
33///
34/// For `decimate <= 1`, returns `[1.0]`.
35pub fn fir_taps(decimate: u32) -> Vec<f64> {
36    if decimate <= 1 {
37        return vec![1.0];
38    }
39    let mut n = (4 * decimate as usize + 1).min(MAX_TAPS);
40    if n % 2 == 0 {
41        n -= 1;
42    }
43    let m = (n - 1) / 2;
44    let fc = 0.45 / decimate as f64;
45    let mut taps = Vec::with_capacity(n);
46    let mut sum = 0.0;
47    for k in 0..n {
48        let x = k as f64 - m as f64;
49        let sinc = if k == m {
50            2.0 * fc
51        } else {
52            (2.0 * PI * fc * x).sin() / (PI * x)
53        };
54        let window = 0.54 - 0.46 * (2.0 * PI * k as f64 / (n - 1) as f64).cos();
55        let v = sinc * window;
56        taps.push(v);
57        sum += v;
58    }
59    for t in &mut taps {
60        *t /= sum;
61    }
62    taps
63}
64
65/// Project one [`PackedSample`] to the ordered channel indices in `channels`,
66/// keeping the exact bits of every selected channel across all seven formats.
67///
68/// When `channels` is empty, returns a cheap `Arc` clone of `sample`.
69pub fn project_packed(sample: &PackedSample, channels: &[u16]) -> PackedSample {
70    if channels.is_empty() {
71        return sample.clone();
72    }
73    match &sample.values {
74        PackedValues::Numeric { format, bytes } => {
75            let width = format.width().unwrap_or(1);
76            let mut out = Vec::with_capacity(channels.len() * width);
77            for &ch in channels {
78                let start = (ch as usize) * width;
79                let end = start + width;
80                if end <= bytes.len() {
81                    out.extend_from_slice(&bytes[start..end]);
82                } else {
83                    out.resize(out.len() + width, 0);
84                }
85            }
86            PackedSample::from_raw_bytes(sample.timestamp, *format, Arc::from(out))
87        }
88        PackedValues::Strings(list) => {
89            let mut out = Vec::with_capacity(channels.len());
90            for &ch in channels {
91                if let Some(s) = list.get(ch as usize) {
92                    out.push(s.clone());
93                } else {
94                    out.push(Vec::new());
95                }
96            }
97            PackedSample::from_strings(sample.timestamp, out)
98        }
99    }
100}
101
102/// Per-consumer channel selector and streaming FIR decimator.
103#[derive(Debug, Clone)]
104pub struct StreamSelector {
105    param: SelectParam,
106    format: Format,
107    out_channels: usize,
108    taps: Vec<f64>,
109    half_delay: usize,
110    /// Circular history of projected channel values (each entry has `out_channels` f64s).
111    history: VecDeque<(f64, Vec<f64>)>,
112    /// Input samples seen since the last emitted decimated sample.
113    phase: u32,
114    /// Reusable scratch buffer for numeric byte output.
115    out_bytes: Vec<u8>,
116}
117
118impl StreamSelector {
119    /// Build a selector for a source stream of `format` and `source_channels`.
120    pub fn new(param: SelectParam, format: Format, source_channels: usize) -> Self {
121        let out_channels = param.output_channels(source_channels);
122        let taps = fir_taps(param.decimate);
123        let half_delay = (taps.len() - 1) / 2;
124        StreamSelector {
125            param,
126            format,
127            out_channels,
128            taps,
129            half_delay,
130            history: VecDeque::new(),
131            phase: 0,
132            out_bytes: Vec::new(),
133        }
134    }
135
136    /// The validated selection parameters.
137    pub fn param(&self) -> &SelectParam {
138        &self.param
139    }
140
141    /// Feed one full-rate sample with its full deduced `timestamp`.
142    ///
143    /// Returns `Some(PackedSample)` whenever an output sample is ready:
144    /// - For `decimate == 1`, always returns `Some` (bit-exact projection).
145    /// - For `decimate > 1`, evaluates the Hamming-windowed sinc FIR filter
146    ///   every `decimate` input samples and emits a sample timestamped at the
147    ///   filter center tap.
148    pub fn push(&mut self, sample: &PackedSample, full_timestamp: f64) -> Option<PackedSample> {
149        if self.param.decimate <= 1 {
150            return Some(project_packed(sample, &self.param.channels));
151        }
152
153        // Convert selected channels into f64 for filtering.
154        let vals = extract_f64_channels(sample, &self.param.channels, self.out_channels);
155        let tap_len = self.taps.len();
156        if self.history.is_empty() {
157            // Pre-fill the left edge with the first sample so there is no
158            // artificial zero transient at startup and output starts immediately.
159            for _ in 0..self.half_delay {
160                self.history.push_back((full_timestamp, vals.clone()));
161            }
162        }
163        self.history.push_back((full_timestamp, vals));
164        while self.history.len() > tap_len {
165            self.history.pop_front();
166        }
167        if self.history.len() < tap_len {
168            return None;
169        }
170
171        let emit = self.phase == 0;
172        self.phase += 1;
173        if self.phase >= self.param.decimate {
174            self.phase = 0;
175        }
176        if !emit {
177            return None;
178        }
179
180        // Evaluate linear-phase FIR across all selected channels.
181        let center_ts = self.history[self.half_delay].0;
182        let mut acc = vec![0.0f64; self.out_channels];
183        for (h, (_, row)) in self.taps.iter().zip(self.history.iter()) {
184            let h = *h;
185            for (a, &x) in acc.iter_mut().zip(row.iter()) {
186                *a += h * x;
187            }
188        }
189        Some(pack_f64_channels(
190            self.format,
191            center_ts,
192            &acc,
193            &mut self.out_bytes,
194        ))
195    }
196}
197
198fn extract_f64_channels(sample: &PackedSample, channels: &[u16], out_ch: usize) -> Vec<f64> {
199    let mut vals = Vec::with_capacity(out_ch);
200    if let PackedValues::Numeric { format, bytes } = &sample.values {
201        let width = format.width().unwrap_or(1);
202        let read_at = |ch: usize| -> f64 {
203            let off = ch * width;
204            if off + width > bytes.len() {
205                return 0.0;
206            }
207            let c = &bytes[off..off + width];
208            match format {
209                Format::Float32 => f32::from_ne_bytes([c[0], c[1], c[2], c[3]]) as f64,
210                Format::Double64 => {
211                    f64::from_ne_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]])
212                }
213                Format::Int32 => i32::from_ne_bytes([c[0], c[1], c[2], c[3]]) as f64,
214                Format::Int16 => i16::from_ne_bytes([c[0], c[1]]) as f64,
215                Format::Int8 => (c[0] as i8) as f64,
216                Format::Int64 => {
217                    i64::from_ne_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]) as f64
218                }
219                Format::String | Format::Undefined => 0.0,
220            }
221        };
222        if channels.is_empty() {
223            for ch in 0..out_ch {
224                vals.push(read_at(ch));
225            }
226        } else {
227            for &ch in channels {
228                vals.push(read_at(ch as usize));
229            }
230        }
231    }
232    vals
233}
234
235fn pack_f64_channels(
236    format: Format,
237    timestamp: f64,
238    vals: &[f64],
239    scratch: &mut Vec<u8>,
240) -> PackedSample {
241    scratch.clear();
242    match format {
243        Format::Float32 => {
244            for &v in vals {
245                scratch.extend_from_slice(&(v as f32).to_ne_bytes());
246            }
247        }
248        Format::Double64 => {
249            for &v in vals {
250                scratch.extend_from_slice(&v.to_ne_bytes());
251            }
252        }
253        Format::Int32 => {
254            for &v in vals {
255                let q = v.round().clamp(i32::MIN as f64, i32::MAX as f64) as i32;
256                scratch.extend_from_slice(&q.to_ne_bytes());
257            }
258        }
259        Format::Int16 => {
260            for &v in vals {
261                let q = v.round().clamp(i16::MIN as f64, i16::MAX as f64) as i16;
262                scratch.extend_from_slice(&q.to_ne_bytes());
263            }
264        }
265        Format::Int8 => {
266            for &v in vals {
267                let q = v.round().clamp(i8::MIN as f64, i8::MAX as f64) as i8;
268                scratch.push(q as u8);
269            }
270        }
271        Format::Int64 => {
272            for &v in vals {
273                let q = v.round().clamp(i64::MIN as f64, i64::MAX as f64) as i64;
274                scratch.extend_from_slice(&q.to_ne_bytes());
275            }
276        }
277        Format::String | Format::Undefined => {}
278    }
279    PackedSample::from_raw_bytes(timestamp, format, Arc::from(scratch.as_slice()))
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn fir_taps_are_symmetric_normalized_and_match_reference_convolution() {
288        let d = 4u32;
289        let taps = fir_taps(d);
290        assert_eq!(taps.len(), 17);
291        let sum: f64 = taps.iter().sum();
292        assert!((sum - 1.0).abs() < 1e-12, "DC gain must be 1.0");
293        for k in 0..taps.len() {
294            assert!(
295                (taps[k] - taps[taps.len() - 1 - k]).abs() < 1e-15,
296                "taps must be symmetric"
297            );
298        }
299
300        // Feed a deterministic signal and compare every decimated output sample
301        // against direct reference convolution of the named Hamming-sinc filter.
302        let n_in = 200usize;
303        let signal: Vec<f64> = (0..n_in)
304            .map(|i| {
305                let t = i as f64 / 400.0;
306                (2.0 * PI * 10.0 * t).sin() + 0.5 * (2.0 * PI * 140.0 * t).cos()
307            })
308            .collect();
309
310        let mut sel = StreamSelector::new(SelectParam::decimate(d), Format::Double64, 1);
311        let mut got = Vec::new();
312        for (i, &x) in signal.iter().enumerate() {
313            let ts = i as f64 / 400.0;
314            let s = PackedSample::from_f64(ts, &[x]);
315            if let Some(out) = sel.push(&s, ts) {
316                let mut v = Vec::new();
317                out.push_into_f64(&mut v);
318                got.push((out.timestamp, v[0]));
319            }
320        }
321
322        // Independent direct reference convolution with the same edge padding.
323        let m = (taps.len() - 1) / 2;
324        let mut padded: Vec<f64> = vec![signal[0]; m];
325        padded.extend_from_slice(&signal);
326        let mut ref_out = Vec::new();
327        let mut idx = taps.len() - 1;
328        while idx < padded.len() {
329            let mut acc = 0.0;
330            for k in 0..taps.len() {
331                acc += taps[k] * padded[idx + 1 - taps.len() + k];
332            }
333            let center_in = idx - 2 * m;
334            ref_out.push((center_in as f64 / 400.0, acc));
335            idx += d as usize;
336        }
337
338        assert_eq!(got.len(), ref_out.len());
339        for (k, ((gt, gv), (rt, rv))) in got.iter().zip(&ref_out).enumerate() {
340            assert!((gt - rt).abs() < 1e-12, "timestamp mismatch at {k}");
341            assert!(
342                (gv - rv).abs() < 1e-12,
343                "value mismatch at {k}: {gv} vs {rv}"
344            );
345        }
346    }
347
348    #[test]
349    fn decimator_preserves_dc_and_passband_and_attenuates_aliasing_stopband() {
350        let d = 16u32; // 4000 Hz -> 250 Hz (Nyquist_out = 125 Hz)
351        let fs = 4000.0;
352
353        // 1. Constant DC signal: exact 3.5 after filter warmup.
354        let mut dc_sel = StreamSelector::new(SelectParam::decimate(d), Format::Float32, 1);
355        let mut dc_vals = Vec::new();
356        for i in 0..512 {
357            let ts = i as f64 / fs;
358            if let Some(o) = dc_sel.push(&PackedSample::from_f32(ts, &[3.5]), ts) {
359                o.push_into_f32(&mut dc_vals);
360            }
361        }
362        assert!(!dc_vals.is_empty());
363        for &v in &dc_vals {
364            assert!((v - 3.5).abs() < 1e-5, "DC drift: {v}");
365        }
366
367        // 2. Passband 20 Hz sine wave (well below 112.5 Hz cutoff): amplitude ~ 1.0.
368        let mut pb_sel = StreamSelector::new(SelectParam::decimate(d), Format::Double64, 1);
369        let mut pb_vals = Vec::new();
370        for i in 0..2000 {
371            let ts = i as f64 / fs;
372            let x = (2.0 * PI * 20.0 * ts).sin();
373            if let Some(o) = pb_sel.push(&PackedSample::from_f64(ts, &[x]), ts) {
374                o.push_into_f64(&mut pb_vals);
375            }
376        }
377        let pb_peak = pb_vals[10..].iter().map(|v| v.abs()).fold(0.0f64, f64::max);
378        assert!(pb_peak > 0.95, "passband attenuated too much: {pb_peak}");
379
380        // 3. Stopband 300 Hz sine wave (well above 125 Hz Nyquist_out): attenuated > 35 dB (< 0.018).
381        let mut sb_sel = StreamSelector::new(SelectParam::decimate(d), Format::Double64, 1);
382        let mut sb_vals = Vec::new();
383        for i in 0..2000 {
384            let ts = i as f64 / fs;
385            let x = (2.0 * PI * 300.0 * ts).sin();
386            if let Some(o) = sb_sel.push(&PackedSample::from_f64(ts, &[x]), ts) {
387                o.push_into_f64(&mut sb_vals);
388            }
389        }
390        let sb_peak = sb_vals[10..].iter().map(|v| v.abs()).fold(0.0f64, f64::max);
391        assert!(
392            sb_peak < 0.018,
393            "stopband 300 Hz must be attenuated > 35 dB, got peak {sb_peak}"
394        );
395    }
396
397    #[test]
398    fn channel_projection_preserves_exact_bits_including_negative_zero_and_nan() {
399        let neg_zero = -0.0f32;
400        let nan_payload = f32::from_bits(0x7fc0_1234);
401        let src = PackedSample::from_f32(12.5, &[1.0, neg_zero, 2.0, nan_payload, 4.0]);
402        let projected = project_packed(&src, &[3, 1, 0]);
403        let mut vals = Vec::new();
404        projected.push_into_f32(&mut vals);
405        assert_eq!(vals.len(), 3);
406        assert_eq!(vals[0].to_bits(), nan_payload.to_bits());
407        assert_eq!(vals[1].to_bits(), neg_zero.to_bits());
408        assert_eq!(vals[2].to_bits(), 1.0f32.to_bits());
409    }
410}