Skip to main content

labstream_net/
calibrate.rs

1//! Device-delay calibration against a reference trigger stream
2//! (`docs/roadmap.md`, step 15).
3//!
4//! A physical sensor or acquisition pipeline introduces a fixed delay between
5//! the physical event and the timestamp stamped at `Outlet::push`. This module
6//! measures that delay by pairing rising edges on a numeric device channel
7//! (with sub-sample linear interpolation) against reference event timestamps,
8//! stores the result in `<desc><synchronization><offset_mean>` (an XDF-retained
9//! LSL metadata field), and lets an inlet subtract it opt-in via
10//! `labstream_time::flags::DEVICE_DELAY`.
11
12use crate::{Inlet, StreamInfo};
13use labstream_time::flags;
14use labstream_wire::Format;
15use std::time::{Duration, Instant};
16
17/// Options controlling [`calibrate_streams`].
18#[derive(Debug, Clone)]
19pub struct CalibrationOptions {
20    /// Zero-based channel index on the device stream that carries the
21    /// calibration pulse (default: `0`).
22    pub channel: usize,
23    /// Optional explicit rising-edge threshold. When `None`, the midpoint
24    /// between the observed baseline and peak is computed automatically.
25    pub threshold: Option<f64>,
26    /// Target number of matched pulses to collect before returning (default: `20`).
27    pub target_pulses: usize,
28    /// Minimum plausible delay in seconds (default: `-0.05`, allowing slight
29    /// negative offsets if the reference itself is delayed).
30    pub min_delay_s: f64,
31    /// Maximum plausible delay in seconds (default: `0.50`).
32    pub max_delay_s: f64,
33    /// Minimum refractory interval between two detected device rising edges in
34    /// seconds (default: `0.05`).
35    pub refractory_s: f64,
36    /// Maximum total wall-clock time to wait for calibration pulses (default: `30 s`).
37    pub timeout: Duration,
38}
39
40impl Default for CalibrationOptions {
41    fn default() -> Self {
42        CalibrationOptions {
43            channel: 0,
44            threshold: None,
45            target_pulses: 20,
46            min_delay_s: -0.05,
47            max_delay_s: 0.50,
48            refractory_s: 0.05,
49            timeout: Duration::from_secs(30),
50        }
51    }
52}
53
54/// Summary statistics of a device-delay calibration run.
55#[derive(Debug, Clone, PartialEq)]
56pub struct CalibrationResult {
57    /// Trimmed mean delay `t_device - t_reference` in seconds (positive means
58    /// the device sample timestamp lags the reference event).
59    pub delay_mean_s: f64,
60    /// Median delay in seconds.
61    pub delay_median_s: f64,
62    /// Root-mean-square jitter around `delay_mean_s` in seconds.
63    pub delay_rms_s: f64,
64    /// 5th percentile delay in seconds.
65    pub delay_p5_s: f64,
66    /// 95th percentile delay in seconds.
67    pub delay_p95_s: f64,
68    /// Number of paired reference-to-device pulses used in the estimate.
69    pub matched_pulses: usize,
70    /// Total reference events observed.
71    pub reference_events: usize,
72    /// Total rising edges detected on the device channel.
73    pub device_edges: usize,
74    /// Threshold used to detect device rising edges.
75    pub threshold_used: f64,
76}
77
78impl CalibrationResult {
79    /// Write this calibration into `info`'s `<desc><synchronization>` subtree.
80    ///
81    /// `liblsl` tools and `LabRecorder` keep `<desc>` verbatim in XDF files.
82    pub fn apply_to_info(&self, info: &mut StreamInfo) {
83        info.set_device_delay_stats(
84            self.delay_mean_s,
85            Some(self.delay_rms_s),
86            Some(self.delay_median_s),
87            Some(self.delay_p5_s),
88            Some(self.delay_p95_s),
89        );
90    }
91
92    /// Format the `<synchronization>` XML snippet for embedding in a stream
93    /// description.
94    pub fn to_xml_snippet(&self) -> String {
95        format!(
96            "<synchronization>\n\
97             \t<offset_mean>{:.6}</offset_mean>\n\
98             \t<offset_rms>{:.6}</offset_rms>\n\
99             \t<offset_median>{:.6}</offset_median>\n\
100             \t<offset_5_percentile>{:.6}</offset_5_percentile>\n\
101             \t<offset_95_percentile>{:.6}</offset_95_percentile>\n\
102             </synchronization>\n",
103            self.delay_mean_s,
104            self.delay_rms_s,
105            self.delay_median_s,
106            self.delay_p5_s,
107            self.delay_p95_s,
108        )
109    }
110
111    /// Format this calibration as a single-line JSON object.
112    pub fn to_json(&self) -> String {
113        format!(
114            "{{\"delay_mean_s\":{:.6},\"delay_median_s\":{:.6},\"delay_rms_s\":{:.6},\"delay_p5_s\":{:.6},\"delay_p95_s\":{:.6},\"matched_pulses\":{},\"reference_events\":{},\"device_edges\":{},\"threshold_used\":{:.6}}}",
115            self.delay_mean_s,
116            self.delay_median_s,
117            self.delay_rms_s,
118            self.delay_p5_s,
119            self.delay_p95_s,
120            self.matched_pulses,
121            self.reference_events,
122            self.device_edges,
123            self.threshold_used,
124        )
125    }
126}
127
128/// Detect rising-edge timestamps on a scalar `(timestamp, value)` sequence
129/// using sub-sample linear interpolation between adjacent samples.
130pub fn detect_rising_edges(samples: &[(f64, f64)], threshold: f64, refractory_s: f64) -> Vec<f64> {
131    let mut edges = Vec::new();
132    let mut last_edge = f64::NEG_INFINITY;
133    for w in samples.windows(2) {
134        let (t0, v0) = w[0];
135        let (t1, v1) = w[1];
136        if !t0.is_finite() || !t1.is_finite() || !v0.is_finite() || !v1.is_finite() {
137            continue;
138        }
139        if v0 < threshold && v1 >= threshold {
140            let dv = v1 - v0;
141            let frac = if dv.abs() > 0.0 {
142                ((threshold - v0) / dv).clamp(0.0, 1.0)
143            } else {
144                0.0
145            };
146            let t_cross = t0 + frac * (t1 - t0);
147            if t_cross - last_edge >= refractory_s {
148                edges.push(t_cross);
149                last_edge = t_cross;
150            }
151        }
152    }
153    edges
154}
155
156/// Measure device delay from recorded reference timestamps and device
157/// `(timestamp, value)` samples.
158///
159/// Pairs each reference timestamp `t_ref` with the earliest device rising edge
160/// in `[t_ref + min_delay_s, t_ref + max_delay_s]`, filters outliers via MAD,
161/// and computes mean, median, RMS jitter, and 5th/95th percentiles.
162pub fn measure_pulse_delays(
163    reference_times: &[f64],
164    device_samples: &[(f64, f64)],
165    opts: &CalibrationOptions,
166) -> Result<CalibrationResult, String> {
167    if reference_times.is_empty() {
168        return Err("no reference events recorded".to_string());
169    }
170    if device_samples.len() < 2 {
171        return Err("not enough device samples to detect edges".to_string());
172    }
173
174    let threshold = match opts.threshold {
175        Some(th) if th.is_finite() => th,
176        _ => {
177            let mut vals: Vec<f64> = device_samples
178                .iter()
179                .map(|&(_, v)| v)
180                .filter(|v| v.is_finite())
181                .collect();
182            if vals.len() < 2 {
183                return Err("device channel contains no finite values".to_string());
184            }
185            vals.sort_by(f64::total_cmp);
186            let low = vals[vals.len() / 10];
187            let high = vals[(vals.len() * 99) / 100];
188            if (high - low).abs() < 1e-12 {
189                return Err("device channel is flat; no calibration pulses found".to_string());
190            }
191            0.5 * (low + high)
192        }
193    };
194
195    let edges = detect_rising_edges(device_samples, threshold, opts.refractory_s);
196    if edges.is_empty() {
197        return Err(format!(
198            "no rising edges crossed threshold {threshold:.6} on device channel"
199        ));
200    }
201
202    let mut refs: Vec<f64> = reference_times
203        .iter()
204        .copied()
205        .filter(|t| t.is_finite())
206        .collect();
207    refs.sort_by(f64::total_cmp);
208
209    let mut deltas = Vec::new();
210    let mut e_idx = 0usize;
211    for &t_ref in &refs {
212        while e_idx < edges.len() && edges[e_idx] < t_ref + opts.min_delay_s {
213            e_idx += 1;
214        }
215        if e_idx < edges.len() {
216            let d = edges[e_idx] - t_ref;
217            if d >= opts.min_delay_s && d <= opts.max_delay_s {
218                deltas.push(d);
219                e_idx += 1;
220            }
221        }
222    }
223
224    if deltas.is_empty() {
225        return Err("no device pulses fell within the delay search window".to_string());
226    }
227
228    deltas.sort_by(f64::total_cmp);
229    let med = quantile_sorted(&deltas, 0.5);
230
231    // Reject gross outliers when >= 5 pulses were paired.
232    let kept: Vec<f64> = if deltas.len() >= 5 {
233        let mut abs_dev: Vec<f64> = deltas.iter().map(|d| (d - med).abs()).collect();
234        abs_dev.sort_by(f64::total_cmp);
235        let mad = abs_dev[abs_dev.len() / 2];
236        let limit = (3.5 * mad).max(0.002);
237        let filtered: Vec<f64> = deltas
238            .iter()
239            .copied()
240            .filter(|d| (d - med).abs() <= limit)
241            .collect();
242        if filtered.is_empty() {
243            deltas.clone()
244        } else {
245            filtered
246        }
247    } else {
248        deltas.clone()
249    };
250
251    let n = kept.len() as f64;
252    let mean = kept.iter().sum::<f64>() / n;
253    let var = kept.iter().map(|d| (d - mean) * (d - mean)).sum::<f64>() / n;
254    let rms = var.sqrt();
255
256    Ok(CalibrationResult {
257        delay_mean_s: mean,
258        delay_median_s: quantile_sorted(&kept, 0.5),
259        delay_rms_s: rms,
260        delay_p5_s: quantile_sorted(&kept, 0.05),
261        delay_p95_s: quantile_sorted(&kept, 0.95),
262        matched_pulses: kept.len(),
263        reference_events: refs.len(),
264        device_edges: edges.len(),
265        threshold_used: threshold,
266    })
267}
268
269fn quantile_sorted(sorted: &[f64], q: f64) -> f64 {
270    let idx = ((sorted.len().saturating_sub(1)) as f64 * q).round() as usize;
271    sorted[idx.min(sorted.len() - 1)]
272}
273
274/// Live device-delay calibration between a numeric device stream and a
275/// reference trigger/marker stream.
276///
277/// Both inlets enable `CLOCKSYNC | DRIFT` so cross-machine calibration uses
278/// smooth drift-corrected timestamps on the local clock.
279pub fn calibrate_streams(
280    device_info: &StreamInfo,
281    reference_info: &StreamInfo,
282    opts: &CalibrationOptions,
283) -> Result<CalibrationResult, String> {
284    if device_info.format == Format::String {
285        return Err("device stream must carry numeric samples".to_string());
286    }
287    if opts.channel >= device_info.channel_count as usize {
288        return Err(format!(
289            "channel {} is out of range for stream with {} channels",
290            opts.channel, device_info.channel_count
291        ));
292    }
293
294    let mut dev_inlet = Inlet::open_with_buffer(device_info, Duration::from_secs(5), 65_536)
295        .map_err(|e| format!("failed to open device stream: {e}"))?;
296    let mut ref_inlet = Inlet::open_with_buffer(reference_info, Duration::from_secs(5), 16_384)
297        .map_err(|e| format!("failed to open reference stream: {e}"))?;
298
299    let post = flags::CLOCKSYNC | flags::DRIFT;
300    dev_inlet.set_postprocessing(post);
301    ref_inlet.set_postprocessing(post);
302
303    // Wait briefly for initial clock offset on both inlets.
304    let _ = dev_inlet.wait_for_time_correction(Duration::from_secs(2));
305    let _ = ref_inlet.wait_for_time_correction(Duration::from_secs(2));
306
307    let mut dev_samples: Vec<(f64, f64)> = Vec::new();
308    let mut ref_times: Vec<f64> = Vec::new();
309    let mut ref_numeric: Vec<(f64, f64)> = Vec::new();
310    let ref_is_string = reference_info.format == Format::String;
311    let mut dev_batch = Vec::new();
312    let mut ref_batch = Vec::new();
313
314    let deadline = Instant::now() + opts.timeout;
315    let mut last_ref_count = 0usize;
316    let mut tail_until: Option<Instant> = None;
317
318    while Instant::now() < deadline {
319        dev_batch.clear();
320        let _ = dev_inlet.pull_chunk(&mut dev_batch, 4096, Duration::from_millis(20));
321        for s in &dev_batch {
322            if let Some(v) = s.values.get(opts.channel).and_then(value_as_f64) {
323                dev_samples.push((s.timestamp, v));
324            }
325        }
326
327        ref_batch.clear();
328        let _ = ref_inlet.pull_chunk(&mut ref_batch, 1024, Duration::ZERO);
329        for s in &ref_batch {
330            if ref_is_string {
331                ref_times.push(s.timestamp);
332            } else if let Some(v) = s.values.first().and_then(value_as_f64) {
333                ref_numeric.push((s.timestamp, v));
334            }
335        }
336
337        let current_refs = if ref_is_string {
338            ref_times.len()
339        } else {
340            // Estimate rising edges on numeric reference stream.
341            if ref_numeric.len() >= 2 {
342                let mut vals: Vec<f64> = ref_numeric.iter().map(|&(_, v)| v).collect();
343                vals.sort_by(f64::total_cmp);
344                let low = vals[vals.len() / 10];
345                let high = vals[(vals.len() * 99) / 100];
346                if (high - low).abs() > 1e-12 {
347                    detect_rising_edges(&ref_numeric, 0.5 * (low + high), opts.refractory_s).len()
348                } else {
349                    0
350                }
351            } else {
352                0
353            }
354        };
355
356        if current_refs >= opts.target_pulses && tail_until.is_none() {
357            // Wait one `max_delay_s` tail so the final device pulse arrives.
358            let tail = Duration::from_secs_f64(opts.max_delay_s.clamp(0.05, 1.0));
359            tail_until = Some(Instant::now() + tail);
360        }
361        if let Some(t_end) = tail_until {
362            if Instant::now() >= t_end {
363                break;
364            }
365        }
366        if current_refs != last_ref_count {
367            last_ref_count = current_refs;
368        }
369    }
370
371    if !ref_is_string {
372        if ref_numeric.len() < 2 {
373            return Err("not enough numeric reference samples".to_string());
374        }
375        let mut vals: Vec<f64> = ref_numeric.iter().map(|&(_, v)| v).collect();
376        vals.sort_by(f64::total_cmp);
377        let low = vals[vals.len() / 10];
378        let high = vals[(vals.len() * 99) / 100];
379        if (high - low).abs() < 1e-12 {
380            return Err("numeric reference channel is flat".to_string());
381        }
382        ref_times = detect_rising_edges(&ref_numeric, 0.5 * (low + high), opts.refractory_s);
383    }
384
385    measure_pulse_delays(&ref_times, &dev_samples, opts)
386}
387
388fn value_as_f64(v: &labstream_wire::Value) -> Option<f64> {
389    use labstream_wire::Value;
390    Some(match *v {
391        Value::F32(x) => x as f64,
392        Value::F64(x) => x,
393        Value::I32(x) => x as f64,
394        Value::I16(x) => x as f64,
395        Value::I8(x) => x as f64,
396        Value::I64(x) => x as f64,
397        Value::Str(_) => return None,
398    })
399}
400
401#[cfg(test)]
402mod tests {
403    use super::*;
404
405    #[test]
406    fn sub_sample_pulse_calibration_measures_known_delay_within_one_ms() {
407        // Simulate a 500 Hz device with a true 23.4 ms delay and 0.2 ms jitter.
408        let srate = 500.0;
409        let true_delay = 0.0234;
410        let mut ref_times = Vec::new();
411        for k in 0..25 {
412            ref_times.push(100.0 + k as f64 * 0.2);
413        }
414
415        let mut dev_samples = Vec::new();
416        let total = (6.0 * srate) as usize;
417        for i in 0..total {
418            let t = 99.8 + i as f64 / srate;
419            // Pulse high for 20 ms starting at `t_ref + true_delay`.
420            let mut val = 0.0;
421            for (k, &tr) in ref_times.iter().enumerate() {
422                let jitter = ((k % 3) as f64 - 1.0) * 0.0002;
423                let edge = tr + true_delay + jitter;
424                if t >= edge && t < edge + 0.02 {
425                    val = 1.0;
426                    break;
427                }
428            }
429            dev_samples.push((t, val));
430        }
431
432        let res = measure_pulse_delays(&ref_times, &dev_samples, &CalibrationOptions::default())
433            .expect("calibration succeeds");
434        assert_eq!(res.matched_pulses, 25);
435        assert!(
436            (res.delay_mean_s - true_delay).abs() < 0.001,
437            "expected error < 1 ms, got {:.3} ms (measured {:.3} ms)",
438            (res.delay_mean_s - true_delay).abs() * 1000.0,
439            res.delay_mean_s * 1000.0
440        );
441        assert!(res.delay_rms_s < 0.001);
442    }
443}