Skip to main content

labstream_net/
clock.rs

1//! The clock offset that an inlet measures against its outlet. SPEC.md 3.
2//!
3//! A thread sends a burst of probes, keeps the estimate with the lowest
4//! round-trip time, and publishes it. The post-processor reads that value
5//! through [`OffsetSource`], so the arithmetic stays in `labstream-time` where a test
6//! can drive it with fixed numbers.
7
8use labstream_proto::timesync::{self, Burst};
9use labstream_time::OffsetSource;
10use std::net::UdpSocket;
11use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
12use std::sync::{Arc, Mutex};
13use std::time::{Duration, Instant};
14
15// The cadence below is the default. A configuration file changes it, and both
16// libraries then move together. `crates/labstream-net/src/config.rs` reads the file.
17
18/// How long between two bursts. `src/api_config.cpp:314`.
19pub fn update_interval() -> Duration {
20    Duration::from_secs_f64(crate::config::get().time_update_interval)
21}
22/// How many probes one burst sends. `src/api_config.cpp:316`.
23pub fn probe_count() -> usize {
24    crate::config::get().time_probe_count as usize
25}
26/// How long between two probes of one burst. `src/api_config.cpp:317`.
27pub fn probe_interval() -> Duration {
28    Duration::from_secs_f64(crate::config::get().time_probe_interval)
29}
30/// How long a burst waits for the last answer. `src/api_config.cpp:318`.
31pub fn probe_max_rtt() -> Duration {
32    Duration::from_secs_f64(crate::config::get().time_probe_max_rtt)
33}
34/// How many answers a burst needs before it publishes. `src/api_config.cpp:315`.
35pub fn update_min_probes() -> usize {
36    crate::config::get().time_update_min_probes as usize
37}
38
39/// The published result of the most recent burst.
40#[derive(Debug)]
41pub struct ClockState {
42    /// The offset, as `f64` bits. `u64::MAX` means no measurement yet.
43    offset_bits: AtomicU64,
44    /// The round-trip time of the kept estimate, as `f64` bits.
45    uncertainty_bits: AtomicU64,
46    /// Set once when a burst first publishes a value.
47    have: AtomicBool,
48    /// Set when the connection reset. The post-processor clears it.
49    reset: AtomicBool,
50    /// Tells the thread to stop.
51    stop: AtomicBool,
52    /// How many bursts have published.
53    updates: AtomicU64,
54}
55
56const NO_VALUE: u64 = u64::MAX;
57
58impl Default for ClockState {
59    fn default() -> Self {
60        ClockState {
61            offset_bits: AtomicU64::new(NO_VALUE),
62            uncertainty_bits: AtomicU64::new(NO_VALUE),
63            have: AtomicBool::new(false),
64            reset: AtomicBool::new(false),
65            stop: AtomicBool::new(false),
66            updates: AtomicU64::new(0),
67        }
68    }
69}
70
71impl ClockState {
72    /// The most recent offset, or `None` before the first burst finishes.
73    pub fn offset(&self) -> Option<f64> {
74        match self.offset_bits.load(Ordering::SeqCst) {
75            NO_VALUE => None,
76            b => Some(f64::from_bits(b)),
77        }
78    }
79
80    /// The round-trip time of the kept estimate. liblsl calls this the
81    /// uncertainty (`src/time_receiver.cpp:204`).
82    pub fn uncertainty(&self) -> Option<f64> {
83        match self.uncertainty_bits.load(Ordering::SeqCst) {
84            NO_VALUE => None,
85            b => Some(f64::from_bits(b)),
86        }
87    }
88
89    /// How many bursts have published a value.
90    pub fn updates(&self) -> u64 {
91        self.updates.load(Ordering::SeqCst)
92    }
93
94    /// Wait until a first measurement arrives.
95    pub fn wait(&self, timeout: Duration) -> Option<f64> {
96        let end = Instant::now() + timeout;
97        while Instant::now() < end {
98            if let Some(v) = self.offset() {
99                return Some(v);
100            }
101            std::thread::sleep(Duration::from_millis(10));
102        }
103        self.offset()
104    }
105
106    /// Record that the connection reset, so the post-processor clears its fit.
107    pub fn mark_reset(&self) {
108        self.reset.store(true, Ordering::SeqCst);
109    }
110
111    /// Stop the probe thread.
112    pub fn stop(&self) {
113        self.stop.store(true, Ordering::SeqCst);
114    }
115
116    fn publish(&self, offset: f64, uncertainty: f64) {
117        self.offset_bits.store(offset.to_bits(), Ordering::SeqCst);
118        self.uncertainty_bits
119            .store(uncertainty.to_bits(), Ordering::SeqCst);
120        self.have.store(true, Ordering::SeqCst);
121        self.updates.fetch_add(1, Ordering::SeqCst);
122    }
123}
124
125/// Start a thread that keeps the offset up to date.
126///
127/// The thread sends one burst every [`update_interval()`]. A burst that collects
128/// fewer than [`update_min_probes()`] answers publishes nothing, so a lost packet
129/// leaves the previous value in place instead of replacing it with a guess.
130pub fn start(target: std::net::SocketAddr, state: Arc<ClockState>, rng: Arc<Mutex<u64>>) {
131    std::thread::spawn(move || {
132        // The probe socket has to speak the protocol of the target.
133        let any: std::net::IpAddr = if target.is_ipv6() {
134            std::net::Ipv6Addr::UNSPECIFIED.into()
135        } else {
136            std::net::Ipv4Addr::UNSPECIFIED.into()
137        };
138        let sock = match UdpSocket::bind((any, 0)) {
139            Ok(s) => s,
140            Err(_) => return,
141        };
142        let _ = sock.set_read_timeout(Some(Duration::from_millis(40)));
143
144        while !state.stop.load(Ordering::SeqCst) {
145            // A new identifier for each burst, so a late answer from an earlier burst
146            // is dropped. SPEC.md 3.4.
147            let wave_id = {
148                let mut r = rng.lock().unwrap();
149                *r ^= *r << 13;
150                *r ^= *r >> 7;
151                *r ^= *r << 17;
152                (*r as u32 as i32).abs()
153            };
154            let mut burst = Burst::new(wave_id);
155            let burst_end =
156                Instant::now() + probe_interval() * probe_count() as u32 + probe_max_rtt();
157
158            for i in 0..probe_count() {
159                if state.stop.load(Ordering::SeqCst) {
160                    return;
161                }
162                let t0 = crate::clock();
163                let msg = timesync::build_probe(wave_id, t0);
164                let _ = sock.send_to(&msg, target);
165
166                // Collect whatever arrives before the next probe goes out.
167                let slot_end = Instant::now() + probe_interval();
168                let mut buf = [0u8; 4096];
169                while Instant::now() < slot_end {
170                    match sock.recv_from(&mut buf) {
171                        Ok((n, _)) => {
172                            let t3 = crate::clock();
173                            if let Some(a) = timesync::parse_answer(&buf[..n]) {
174                                burst.accept(&a, t3);
175                            }
176                        }
177                        Err(_) => break,
178                    }
179                }
180                let _ = i;
181            }
182
183            // Drain the tail of the burst.
184            let mut buf = [0u8; 4096];
185            while Instant::now() < burst_end {
186                match sock.recv_from(&mut buf) {
187                    Ok((n, _)) => {
188                        let t3 = crate::clock();
189                        if let Some(a) = timesync::parse_answer(&buf[..n]) {
190                            burst.accept(&a, t3);
191                        }
192                    }
193                    Err(_) => break,
194                }
195            }
196
197            if std::env::var_os("LSL_TRACE_CLOCK").is_some() {
198                eprintln!(
199                    "TRACE clock wave={wave_id} accepted={} offset={:?} rtt={:?}",
200                    burst.accepted(),
201                    burst.time_offset(),
202                    burst.uncertainty()
203                );
204            }
205            if burst.accepted() >= update_min_probes() {
206                if let (Some(o), Some(u)) = (burst.time_offset(), burst.uncertainty()) {
207                    state.publish(o, u);
208                }
209            }
210
211            // Wait out the rest of the interval.
212            let rest = update_interval()
213                .saturating_sub(probe_interval() * probe_count() as u32 + probe_max_rtt());
214            let wake = Instant::now() + rest;
215            while Instant::now() < wake {
216                if state.stop.load(Ordering::SeqCst) {
217                    return;
218                }
219                std::thread::sleep(Duration::from_millis(20));
220            }
221        }
222    });
223}
224
225/// Feeds the post-processor from a live connection.
226pub struct LiveSource {
227    state: Arc<ClockState>,
228    srate: f64,
229}
230
231impl LiveSource {
232    /// Build a source for a stream with the given nominal rate.
233    pub fn new(state: Arc<ClockState>, srate: f64) -> Self {
234        LiveSource { state, srate }
235    }
236}
237
238impl OffsetSource for LiveSource {
239    fn correction(&mut self) -> f64 {
240        // Before the first burst finishes there is no measurement, and a
241        // correction of zero leaves the timestamp alone. liblsl waits instead
242        // (`src/time_receiver.cpp:57-76`), and a caller that needs the wait can
243        // use `ClockState::wait`.
244        self.state.offset().unwrap_or(0.0)
245    }
246
247    fn srate(&mut self) -> f64 {
248        self.srate
249    }
250
251    fn was_reset(&mut self) -> bool {
252        self.state.reset.swap(false, Ordering::SeqCst)
253    }
254
255    fn clock(&mut self) -> f64 {
256        crate::clock()
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn a_fresh_state_holds_no_measurement() {
266        let s = ClockState::default();
267        assert_eq!(s.offset(), None);
268        assert_eq!(s.uncertainty(), None);
269        assert_eq!(s.updates(), 0);
270    }
271
272    #[test]
273    fn a_published_value_comes_back() {
274        let s = ClockState::default();
275        s.publish(-1.25, 0.004);
276        assert_eq!(s.offset(), Some(-1.25));
277        assert_eq!(s.uncertainty(), Some(0.004));
278        assert_eq!(s.updates(), 1);
279    }
280
281    #[test]
282    fn a_reset_reads_once() {
283        let s = Arc::new(ClockState::default());
284        let mut src = LiveSource::new(Arc::clone(&s), 100.0);
285        assert!(!src.was_reset());
286        s.mark_reset();
287        assert!(src.was_reset(), "the first read reports the reset");
288        assert!(!src.was_reset(), "a second read must not report it again");
289    }
290
291    #[test]
292    fn a_missing_measurement_leaves_a_timestamp_alone() {
293        let s = Arc::new(ClockState::default());
294        let mut src = LiveSource::new(s, 100.0);
295        assert_eq!(src.correction(), 0.0);
296    }
297}