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, f64)>,
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        let local_mid = 0.5 * (a.t0 + t3);
130        self.seen += 1;
131        match self.best {
132            Some((b, _)) if b.rtt <= e.rtt => {}
133            _ => self.best = Some((e, local_mid)),
134        }
135        true
136    }
137
138    /// The offset that this burst produced.
139    ///
140    /// liblsl stores the negative of the computed offset
141    /// (`src/time_receiver.cpp:204`).
142    pub fn time_offset(&self) -> Option<f64> {
143        self.best.map(|(e, _)| -e.offset)
144    }
145
146    /// The round-trip time of the best estimate. liblsl calls it the
147    /// uncertainty (`src/time_receiver.cpp:204`).
148    pub fn uncertainty(&self) -> Option<f64> {
149        self.best.map(|(e, _)| e.rtt)
150    }
151
152    /// Local midpoint timestamp `(t0 + t3) / 2` of the best estimate in this
153    /// burst, used by the opt-in drift clock (`docs/roadmap.md`, step 17).
154    pub fn local_time(&self) -> Option<f64> {
155        self.best.map(|(_, t)| t)
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn a_probe_round_trips() {
165        let bytes = build_probe(12345, 1.5);
166        let p = parse_probe(&bytes).expect("a probe");
167        assert_eq!(p.wave_id, 12345);
168        assert!((p.t0 - 1.5).abs() < 1e-12);
169    }
170
171    #[test]
172    fn an_answer_starts_with_a_space() {
173        let bytes = build_answer(7, 1.0, 2.0, 3.0);
174        assert_eq!(bytes[0], b' ');
175        let a = parse_answer(&bytes).expect("an answer");
176        assert_eq!(a.wave_id, 7);
177    }
178
179    #[test]
180    fn the_captured_answer_parses() {
181        // From captures/timeprobe.json.
182        let raw = b" 12345 7958.920835802 7958.921048403 7958.921142721";
183        let a = parse_answer(raw).expect("an answer");
184        assert_eq!(a.wave_id, 12345);
185        assert!((a.t1 - 7958.921048403).abs() < 1e-9);
186    }
187
188    #[test]
189    fn a_symmetric_exchange_shows_the_offset() {
190        // The other clock runs 10 seconds ahead. The path takes 1 second each
191        // way, so the estimator must find the offset with no bias.
192        let a = Answer {
193            wave_id: 1,
194            t0: 0.0,
195            t1: 11.0,
196            t2: 11.0,
197        };
198        let e = estimate(&a, 2.0);
199        assert!((e.rtt - 2.0).abs() < 1e-12);
200        assert!((e.offset - 10.0).abs() < 1e-12);
201    }
202
203    #[test]
204    fn the_burst_keeps_the_lowest_round_trip_time() {
205        let mut b = Burst::new(9);
206        // A slow exchange first, then a fast one.
207        b.accept(
208            &Answer {
209                wave_id: 9,
210                t0: 0.0,
211                t1: 15.0,
212                t2: 15.0,
213            },
214            10.0,
215        );
216        b.accept(
217            &Answer {
218                wave_id: 9,
219                t0: 0.0,
220                t1: 10.5,
221                t2: 10.5,
222            },
223            1.0,
224        );
225        assert_eq!(b.accepted(), 2);
226        assert!((b.uncertainty().unwrap() - 1.0).abs() < 1e-12);
227        assert!((b.time_offset().unwrap() + 10.0).abs() < 1e-12);
228    }
229
230    #[test]
231    fn a_late_answer_from_an_earlier_burst_is_dropped() {
232        let mut b = Burst::new(9);
233        assert!(!b.accept(
234            &Answer {
235                wave_id: 8,
236                t0: 0.0,
237                t1: 1.0,
238                t2: 1.0
239            },
240            2.0
241        ));
242        assert_eq!(b.accepted(), 0);
243        assert_eq!(b.time_offset(), None);
244    }
245
246    #[test]
247    fn the_stored_offset_carries_the_opposite_sign() {
248        let mut b = Burst::new(1);
249        b.accept(
250            &Answer {
251                wave_id: 1,
252                t0: 0.0,
253                t1: 5.0,
254                t2: 5.0,
255            },
256            0.0,
257        );
258        // The computed offset is 5. liblsl stores minus 5.
259        assert!((b.time_offset().unwrap() + 5.0).abs() < 1e-12);
260    }
261}