Skip to main content

labstream_proto/
timesync.rs

1//! Time synchronization over UDP. SPEC.md 3.
2//!
3//! The estimator is a pure function of four timestamps, so a test drives it
4//! with fixed numbers and no socket.
5
6/// Build a time probe. SPEC.md 3.1, `src/time_receiver.cpp:136`.
7///
8/// liblsl writes the values with 16 digits of precision.
9pub fn build_probe(wave_id: i32, t0: f64) -> Vec<u8> {
10    format!("LSL:timedata\r\n{wave_id} {t0:.16}\r\n").into_bytes()
11}
12
13/// A parsed probe, as an outlet reads it.
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub struct Probe {
16    /// The identifier of the current burst.
17    pub wave_id: i32,
18    /// The sender clock at the moment of the request.
19    pub t0: f64,
20}
21
22/// Read a time probe.
23pub fn parse_probe(buf: &[u8]) -> Option<Probe> {
24    let text = String::from_utf8_lossy(buf);
25    let mut lines = text.split('\n');
26    if lines.next()?.trim_end_matches('\r').trim() != "LSL:timedata" {
27        return None;
28    }
29    let mut parts = lines.next()?.split_whitespace();
30    Some(Probe {
31        wave_id: parts.next()?.parse().ok()?,
32        t0: parts.next()?.parse().ok()?,
33    })
34}
35
36/// Build the answer to a probe. SPEC.md 3.2.
37///
38/// The answer starts with a space. `t1` is the clock on arrival, and `t2` is
39/// the clock at the moment of the answer.
40pub fn build_answer(wave_id: i32, t0: f64, t1: f64, t2: f64) -> Vec<u8> {
41    format!(" {wave_id} {t0:.16} {t1:.16} {t2:.16}").into_bytes()
42}
43
44/// A parsed answer.
45#[derive(Debug, Clone, Copy, PartialEq)]
46pub struct Answer {
47    /// The burst identifier that came back.
48    pub wave_id: i32,
49    /// The sender clock at the moment of the request.
50    pub t0: f64,
51    /// The other clock on arrival.
52    pub t1: f64,
53    /// The other clock at the moment of the answer.
54    pub t2: f64,
55}
56
57/// Read an answer to a probe.
58pub fn parse_answer(buf: &[u8]) -> Option<Answer> {
59    let text = String::from_utf8_lossy(buf);
60    let mut parts = text.split_whitespace();
61    Some(Answer {
62        wave_id: parts.next()?.parse().ok()?,
63        t0: parts.next()?.parse().ok()?,
64        t1: parts.next()?.parse().ok()?,
65        t2: parts.next()?.parse().ok()?,
66    })
67}
68
69/// One round-trip measurement.
70#[derive(Debug, Clone, Copy, PartialEq)]
71pub struct Estimate {
72    /// The round-trip time.
73    pub rtt: f64,
74    /// The clock offset, before the sign change.
75    pub offset: f64,
76}
77
78/// Compute one estimate from four timestamps. SPEC.md 3.3.
79///
80/// `src/time_receiver.cpp:170-178`.
81pub fn estimate(a: &Answer, t3: f64) -> Estimate {
82    Estimate {
83        rtt: (t3 - a.t0) - (a.t2 - a.t1),
84        offset: ((a.t1 - a.t0) + (a.t2 - t3)) / 2.0,
85    }
86}
87
88/// Collects the estimates of one burst and keeps the best one.
89///
90/// liblsl keeps the estimate with the lowest round-trip time and discards the
91/// others (`src/time_receiver.cpp:190-205`). A fast exchange leaves less room
92/// for an asymmetric delay.
93#[derive(Debug, Clone)]
94pub struct Burst {
95    wave_id: i32,
96    best: Option<Estimate>,
97    seen: usize,
98}
99
100impl Burst {
101    /// Start a burst with an identifier.
102    pub fn new(wave_id: i32) -> Self {
103        Burst {
104            wave_id,
105            best: None,
106            seen: 0,
107        }
108    }
109
110    /// The identifier of this burst.
111    pub fn wave_id(&self) -> i32 {
112        self.wave_id
113    }
114
115    /// The number of answers that this burst accepted.
116    pub fn accepted(&self) -> usize {
117        self.seen
118    }
119
120    /// Take one answer.
121    ///
122    /// An answer from another burst is dropped. SPEC.md 3.4,
123    /// `src/time_receiver.cpp:166`.
124    pub fn accept(&mut self, a: &Answer, t3: f64) -> bool {
125        if a.wave_id != self.wave_id {
126            return false;
127        }
128        let e = estimate(a, t3);
129        self.seen += 1;
130        match self.best {
131            Some(b) if b.rtt <= e.rtt => {}
132            _ => self.best = Some(e),
133        }
134        true
135    }
136
137    /// The offset that this burst produced.
138    ///
139    /// liblsl stores the negative of the computed offset
140    /// (`src/time_receiver.cpp:204`).
141    pub fn time_offset(&self) -> Option<f64> {
142        self.best.map(|e| -e.offset)
143    }
144
145    /// The round-trip time of the best estimate. liblsl calls it the
146    /// uncertainty (`src/time_receiver.cpp:204`).
147    pub fn uncertainty(&self) -> Option<f64> {
148        self.best.map(|e| e.rtt)
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn a_probe_round_trips() {
158        let bytes = build_probe(12345, 1.5);
159        let p = parse_probe(&bytes).expect("a probe");
160        assert_eq!(p.wave_id, 12345);
161        assert!((p.t0 - 1.5).abs() < 1e-12);
162    }
163
164    #[test]
165    fn an_answer_starts_with_a_space() {
166        let bytes = build_answer(7, 1.0, 2.0, 3.0);
167        assert_eq!(bytes[0], b' ');
168        let a = parse_answer(&bytes).expect("an answer");
169        assert_eq!(a.wave_id, 7);
170    }
171
172    #[test]
173    fn the_captured_answer_parses() {
174        // From captures/timeprobe.json.
175        let raw = b" 12345 7958.920835802 7958.921048403 7958.921142721";
176        let a = parse_answer(raw).expect("an answer");
177        assert_eq!(a.wave_id, 12345);
178        assert!((a.t1 - 7958.921048403).abs() < 1e-9);
179    }
180
181    #[test]
182    fn a_symmetric_exchange_shows_the_offset() {
183        // The other clock runs 10 seconds ahead. The path takes 1 second each
184        // way, so the estimator must find the offset with no bias.
185        let a = Answer {
186            wave_id: 1,
187            t0: 0.0,
188            t1: 11.0,
189            t2: 11.0,
190        };
191        let e = estimate(&a, 2.0);
192        assert!((e.rtt - 2.0).abs() < 1e-12);
193        assert!((e.offset - 10.0).abs() < 1e-12);
194    }
195
196    #[test]
197    fn the_burst_keeps_the_lowest_round_trip_time() {
198        let mut b = Burst::new(9);
199        // A slow exchange first, then a fast one.
200        b.accept(
201            &Answer {
202                wave_id: 9,
203                t0: 0.0,
204                t1: 15.0,
205                t2: 15.0,
206            },
207            10.0,
208        );
209        b.accept(
210            &Answer {
211                wave_id: 9,
212                t0: 0.0,
213                t1: 10.5,
214                t2: 10.5,
215            },
216            1.0,
217        );
218        assert_eq!(b.accepted(), 2);
219        assert!((b.uncertainty().unwrap() - 1.0).abs() < 1e-12);
220        assert!((b.time_offset().unwrap() + 10.0).abs() < 1e-12);
221    }
222
223    #[test]
224    fn a_late_answer_from_an_earlier_burst_is_dropped() {
225        let mut b = Burst::new(9);
226        assert!(!b.accept(
227            &Answer {
228                wave_id: 8,
229                t0: 0.0,
230                t1: 1.0,
231                t2: 1.0
232            },
233            2.0
234        ));
235        assert_eq!(b.accepted(), 0);
236        assert_eq!(b.time_offset(), None);
237    }
238
239    #[test]
240    fn the_stored_offset_carries_the_opposite_sign() {
241        let mut b = Burst::new(1);
242        b.accept(
243            &Answer {
244                wave_id: 1,
245                t0: 0.0,
246                t1: 5.0,
247                t2: 5.0,
248            },
249            0.0,
250        );
251        // The computed offset is 5. liblsl stores minus 5.
252        assert!((b.time_offset().unwrap() + 5.0).abs() < 1e-12);
253    }
254}