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::{DriftFit, DriftModel, OffsetSource};
10use std::net::{SocketAddr, UdpSocket};
11use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
12use std::sync::{Arc, Condvar, 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/// How long the post-processor waits for the first offset.
40///
41/// liblsl passes the same value to `time_correction`
42/// (`src/stream_inlet_impl.h:44`).
43pub const FIRST_OFFSET_TIMEOUT: Duration = Duration::from_secs(5);
44
45/// The gap between two probes while no offset exists.
46///
47/// The first burst sends its probes close together, so the first offset
48/// arrives in tens of milliseconds and not in a whole burst of
49/// [`probe_interval()`] slots. The kept estimate is still the one with the
50/// lowest round-trip time. The later bursts use the configured cadence.
51/// This is a local choice: the outlet answers each probe as it comes.
52pub const FIRST_PROBE_INTERVAL: Duration = Duration::from_millis(4);
53
54/// The wait before the next burst when a burst found no first offset.
55///
56/// A burst without enough answers tries again after this time and not after
57/// a full [`update_interval()`]. The wait keeps an outlet that does not answer
58/// from a flood of probes.
59pub const FIRST_RETRY: Duration = Duration::from_millis(250);
60
61/// The published result of the most recent burst.
62#[derive(Debug)]
63pub struct ClockState {
64    /// The offset, as `f64` bits. `u64::MAX` means no measurement yet.
65    offset_bits: AtomicU64,
66    /// The round-trip time of the kept estimate, as `f64` bits.
67    uncertainty_bits: AtomicU64,
68    /// Opt-in linear offset-and-drift model (`docs/roadmap.md`, step 17).
69    drift_model: Mutex<DriftModel>,
70    /// Cached latest [`DriftFit`] published alongside the raw burst offset so
71    /// hot-path smooth lookups never contend with the probe thread.
72    drift_fit: Mutex<Option<DriftFit>>,
73    /// Set once when a burst first publishes a value.
74    have: AtomicBool,
75    /// Set when the connection reset. The post-processor clears it.
76    reset: AtomicBool,
77    /// Tells the thread to stop.
78    stop: AtomicBool,
79    /// True while a probe thread runs. A wait for an offset ends when no
80    /// thread runs, because no value can then arrive.
81    alive: AtomicBool,
82    /// How many bursts have published.
83    updates: AtomicU64,
84    /// The service port that the probes go to. A recovery can change it.
85    target: Mutex<Option<SocketAddr>>,
86    /// Grows by one for each change of the target. A burst that started
87    /// before a change publishes nothing.
88    epoch: AtomicU64,
89    /// Wakes a caller of [`ClockState::wait`].
90    signal: (Mutex<()>, Condvar),
91}
92
93const NO_VALUE: u64 = u64::MAX;
94
95impl Default for ClockState {
96    fn default() -> Self {
97        ClockState {
98            offset_bits: AtomicU64::new(NO_VALUE),
99            uncertainty_bits: AtomicU64::new(NO_VALUE),
100            drift_model: Mutex::new(DriftModel::new()),
101            drift_fit: Mutex::new(None),
102            have: AtomicBool::new(false),
103            reset: AtomicBool::new(false),
104            stop: AtomicBool::new(false),
105            alive: AtomicBool::new(false),
106            updates: AtomicU64::new(0),
107            target: Mutex::new(None),
108            epoch: AtomicU64::new(0),
109            signal: (Mutex::new(()), Condvar::new()),
110        }
111    }
112}
113
114impl ClockState {
115    /// The most recent offset, or `None` before the first burst finishes.
116    pub fn offset(&self) -> Option<f64> {
117        match self.offset_bits.load(Ordering::SeqCst) {
118            NO_VALUE => None,
119            b => Some(f64::from_bits(b)),
120        }
121    }
122
123    /// The round-trip time of the kept estimate. liblsl calls this the
124    /// uncertainty (`src/time_receiver.cpp:204`).
125    pub fn uncertainty(&self) -> Option<f64> {
126        match self.uncertainty_bits.load(Ordering::SeqCst) {
127            NO_VALUE => None,
128            b => Some(f64::from_bits(b)),
129        }
130    }
131
132    /// How many bursts have published a value.
133    pub fn updates(&self) -> u64 {
134        self.updates.load(Ordering::SeqCst)
135    }
136
137    /// Estimated relative clock drift (`d(offset)/d(t_local)` in s/s) from the
138    /// opt-in drift model (`docs/roadmap.md`, step 17), or `None` before the
139    /// first burst finishes.
140    pub fn drift(&self) -> Option<f64> {
141        self.drift_fit.lock().unwrap().map(|f| f.drift)
142    }
143
144    /// Latest linear offset-and-drift fit, or `None` before the first burst.
145    pub fn drift_fit(&self) -> Option<DriftFit> {
146        *self.drift_fit.lock().unwrap()
147    }
148
149    /// Smooth offset `local - remote` for `remote_ts`, or `None` before the
150    /// first burst finishes.
151    pub fn smooth_offset_at(&self, remote_ts: f64) -> Option<f64> {
152        self.drift_fit
153            .lock()
154            .unwrap()
155            .map(|f| f.offset_for_remote(remote_ts))
156    }
157
158    /// True while a probe thread runs and can publish a value.
159    pub fn is_running(&self) -> bool {
160        self.alive.load(Ordering::SeqCst) && !self.stop.load(Ordering::SeqCst)
161    }
162
163    /// Wait until a first measurement arrives.
164    ///
165    /// The wait ends early when no probe thread runs, because no value can
166    /// then arrive. liblsl ends its wait when the connection is lost
167    /// (`src/time_receiver.cpp:59-61`).
168    pub fn wait(&self, timeout: Duration) -> Option<f64> {
169        let end = Instant::now() + timeout;
170        let (lock, cvar) = &self.signal;
171        let mut guard = lock.lock().unwrap();
172        loop {
173            if let Some(v) = self.offset() {
174                return Some(v);
175            }
176            if !self.is_running() {
177                return None;
178            }
179            let left = end.saturating_duration_since(Instant::now());
180            if left.is_zero() {
181                return self.offset();
182            }
183            // A short slice guards against a lost wake-up.
184            guard = cvar
185                .wait_timeout(guard, left.min(Duration::from_millis(50)))
186                .unwrap()
187                .0;
188        }
189    }
190
191    /// Record that the connection reset, so the post-processor clears its fit.
192    pub fn mark_reset(&self) {
193        self.reset.store(true, Ordering::SeqCst);
194    }
195
196    /// Forget the offset after the inlet attached to a new source.
197    ///
198    /// The old offset describes a process that has gone. The reset flag goes
199    /// up only if an offset existed, as in liblsl
200    /// (`src/time_receiver.cpp:212-218`).
201    pub fn reset_offset(&self) {
202        if self.offset().is_some() {
203            self.reset.store(true, Ordering::SeqCst);
204        }
205        self.offset_bits.store(NO_VALUE, Ordering::SeqCst);
206        self.uncertainty_bits.store(NO_VALUE, Ordering::SeqCst);
207        self.drift_model.lock().unwrap().reset();
208        *self.drift_fit.lock().unwrap() = None;
209    }
210
211    /// Send the next bursts to a different service port.
212    ///
213    /// A burst that is in progress publishes nothing. liblsl sets the new
214    /// address in its recovery callback (`src/time_receiver.cpp:26-33`).
215    pub fn retarget(&self, target: SocketAddr) {
216        *self.target.lock().unwrap() = Some(target);
217        self.epoch.fetch_add(1, Ordering::SeqCst);
218    }
219
220    /// Stop the probe thread.
221    pub fn stop(&self) {
222        self.stop.store(true, Ordering::SeqCst);
223        self.notify();
224    }
225
226    fn notify(&self) {
227        let _guard = self.signal.0.lock().unwrap();
228        self.signal.1.notify_all();
229    }
230
231    #[cfg(test)]
232    fn publish(&self, offset: f64, uncertainty: f64) {
233        self.publish_at(crate::clock(), offset, uncertainty);
234    }
235
236    fn publish_at(&self, local_time: f64, offset: f64, uncertainty: f64) {
237        let fit = self
238            .drift_model
239            .lock()
240            .unwrap()
241            .update(local_time, offset, uncertainty);
242        *self.drift_fit.lock().unwrap() = Some(fit);
243        self.offset_bits.store(offset.to_bits(), Ordering::SeqCst);
244        self.uncertainty_bits
245            .store(uncertainty.to_bits(), Ordering::SeqCst);
246        self.have.store(true, Ordering::SeqCst);
247        self.updates.fetch_add(1, Ordering::SeqCst);
248        self.notify();
249    }
250}
251
252/// Clears the running flag when the probe thread ends, also on a panic.
253struct AliveGuard(Arc<ClockState>);
254
255impl Drop for AliveGuard {
256    fn drop(&mut self) {
257        self.0.alive.store(false, Ordering::SeqCst);
258        self.0.notify();
259    }
260}
261
262/// Open a probe socket of the same protocol as the target.
263fn probe_socket(target: SocketAddr) -> Option<UdpSocket> {
264    let any: std::net::IpAddr = if target.is_ipv6() {
265        std::net::Ipv6Addr::UNSPECIFIED.into()
266    } else {
267        std::net::Ipv4Addr::UNSPECIFIED.into()
268    };
269    let sock = UdpSocket::bind((any, 0)).ok()?;
270    let _ = sock.set_read_timeout(Some(Duration::from_millis(40)));
271    Some(sock)
272}
273
274/// Read answers into `burst` until `end`, or until it holds `enough` answers.
275///
276/// Each read waits only for the time that is left. A fixed read timeout
277/// would end the slot early, or hold a short slot open for too long.
278fn collect(sock: &UdpSocket, burst: &mut Burst, end: Instant, enough: Option<usize>) {
279    let mut buf = [0u8; 4096];
280    loop {
281        if enough.is_some_and(|n| burst.accepted() >= n) {
282            return;
283        }
284        let left = end.saturating_duration_since(Instant::now());
285        // A read timeout of zero is an error, so the slot ends here.
286        if left < Duration::from_micros(100) {
287            return;
288        }
289        let _ = sock.set_read_timeout(Some(left));
290        match sock.recv_from(&mut buf) {
291            Ok((n, _)) => {
292                let t3 = crate::clock();
293                if let Some(a) = timesync::parse_answer(&buf[..n]) {
294                    burst.accept(&a, t3);
295                }
296            }
297            Err(ref e)
298                if e.kind() == std::io::ErrorKind::WouldBlock
299                    || e.kind() == std::io::ErrorKind::TimedOut => {}
300            // An ICMP error from an earlier probe can show as a read error.
301            // The slot then waits out its time with a short pause.
302            Err(_) => std::thread::sleep(left.min(Duration::from_millis(5))),
303        }
304    }
305}
306
307/// Start a thread that keeps the offset up to date.
308///
309/// The thread sends one burst every [`update_interval()`]. A burst that collects
310/// fewer than [`update_min_probes()`] answers publishes nothing, so a lost packet
311/// leaves the previous value in place instead of replacing it with a guess.
312///
313/// [`ClockState::retarget`] moves the probes to a different service port.
314pub fn start(target: SocketAddr, state: Arc<ClockState>, rng: Arc<Mutex<u64>>) {
315    *state.target.lock().unwrap() = Some(target);
316    // The flag goes up before the thread starts. A caller that waits at once
317    // therefore sees a running thread.
318    state.alive.store(true, Ordering::SeqCst);
319    std::thread::spawn(move || {
320        let _alive = AliveGuard(Arc::clone(&state));
321        let mut sock = match probe_socket(target) {
322            Some(s) => s,
323            None => return,
324        };
325        let mut bound_v6 = target.is_ipv6();
326
327        while !state.stop.load(Ordering::SeqCst) {
328            let epoch = state.epoch.load(Ordering::SeqCst);
329            let target = match *state.target.lock().unwrap() {
330                Some(t) => t,
331                None => return,
332            };
333            // A recovery can move the stream from IPv4 to IPv6. The socket
334            // must then change protocol too (`src/time_receiver.cpp:30-32`).
335            if target.is_ipv6() != bound_v6 {
336                sock = match probe_socket(target) {
337                    Some(s) => s,
338                    None => return,
339                };
340                bound_v6 = target.is_ipv6();
341            }
342
343            // A new identifier for each burst, so a late answer from an earlier burst
344            // is dropped. SPEC.md 3.4.
345            let wave_id = {
346                let mut r = rng.lock().unwrap();
347                *r ^= *r << 13;
348                *r ^= *r >> 7;
349                *r ^= *r << 17;
350                (*r as u32 as i32).abs()
351            };
352            let mut burst = Burst::new(wave_id);
353            // Without an offset, the burst is a fast one. A reset or a new
354            // target clears the offset, so a recovery also gets a fast burst.
355            let fast = state.offset().is_none();
356            let gap = if fast {
357                FIRST_PROBE_INTERVAL.min(probe_interval())
358            } else {
359                probe_interval()
360            };
361            let burst_start = Instant::now();
362            let burst_end = burst_start + gap * probe_count() as u32 + probe_max_rtt();
363
364            for _ in 0..probe_count() {
365                if state.stop.load(Ordering::SeqCst) {
366                    return;
367                }
368                let t0 = crate::clock();
369                let msg = timesync::build_probe(wave_id, t0);
370                let _ = sock.send_to(&msg, target);
371
372                // Collect whatever arrives before the next probe goes out.
373                collect(&sock, &mut burst, Instant::now() + gap, None);
374            }
375
376            // Collect the late answers. A fast burst stops when each probe
377            // has its answer.
378            let all = if fast { Some(probe_count()) } else { None };
379            collect(&sock, &mut burst, burst_end, all);
380
381            if std::env::var_os("LSL_TRACE_CLOCK").is_some() {
382                eprintln!(
383                    "TRACE clock wave={wave_id} accepted={} offset={:?} rtt={:?}",
384                    burst.accepted(),
385                    burst.time_offset(),
386                    burst.uncertainty()
387                );
388            }
389            // A burst that started before a change of target measured the old
390            // source. It publishes nothing.
391            if burst.accepted() >= update_min_probes()
392                && state.epoch.load(Ordering::SeqCst) == epoch
393            {
394                if let (Some(o), Some(u), Some(lt)) =
395                    (burst.time_offset(), burst.uncertainty(), burst.local_time())
396                {
397                    state.publish_at(lt, o, u);
398                }
399            }
400
401            // Wait out the rest of the interval. Without an offset, try again
402            // soon.
403            let mut wake = burst_start + update_interval();
404            if state.offset().is_none() {
405                wake = wake.min(Instant::now() + FIRST_RETRY);
406            }
407            while Instant::now() < wake {
408                if state.stop.load(Ordering::SeqCst) {
409                    return;
410                }
411                std::thread::sleep(Duration::from_millis(20));
412            }
413        }
414    });
415}
416
417/// Feeds the post-processor from a live connection.
418pub struct LiveSource {
419    state: Arc<ClockState>,
420    srate: f64,
421    /// True after one wait for the first offset ran out. Later calls then do
422    /// not wait again until a reset clears the offset.
423    waited_out: bool,
424    /// The most recent offset that this source gave.
425    last: f64,
426}
427
428impl LiveSource {
429    /// Build a source for a stream with the given nominal rate.
430    pub fn new(state: Arc<ClockState>, srate: f64) -> Self {
431        LiveSource {
432            state,
433            srate,
434            waited_out: false,
435            last: 0.0,
436        }
437    }
438}
439
440impl OffsetSource for LiveSource {
441    fn correction(&mut self) -> f64 {
442        // Before the first burst finishes there is no measurement. liblsl
443        // waits up to 5 s for it (`src/stream_inlet_impl.h:44`,
444        // `src/time_receiver.cpp:57-76`). Without the wait, the first
445        // timestamps and the start of the jitter fit use no offset, and the
446        // real offset arrives later as a step.
447        if let Some(v) = self.state.offset() {
448            self.waited_out = false;
449            self.last = v;
450            return v;
451        }
452        if !self.waited_out {
453            if let Some(v) = self.state.wait(FIRST_OFFSET_TIMEOUT) {
454                self.last = v;
455                return v;
456            }
457            // liblsl raises `timeout_error` here. This source gives the last
458            // value and does not wait again, so the samples continue to flow.
459            self.waited_out = true;
460            if std::env::var_os("LSL_TRACE_CLOCK").is_some() {
461                eprintln!("TRACE clock: no offset arrived, the timestamps stay uncorrected");
462            }
463        }
464        self.last
465    }
466
467    fn smooth_correction(&mut self, remote_ts: f64) -> f64 {
468        if let Some(v) = self.state.smooth_offset_at(remote_ts) {
469            self.waited_out = false;
470            self.last = v;
471            return v;
472        }
473        if !self.waited_out {
474            if self.state.wait(FIRST_OFFSET_TIMEOUT).is_some() {
475                if let Some(v) = self.state.smooth_offset_at(remote_ts) {
476                    self.last = v;
477                    return v;
478                }
479            }
480            self.waited_out = true;
481        }
482        self.last
483    }
484
485    fn srate(&mut self) -> f64 {
486        self.srate
487    }
488
489    fn was_reset(&mut self) -> bool {
490        // A reset clears the offset. The next call to `correction` then waits
491        // again, because a received value set `waited_out` to false.
492        self.state.reset.swap(false, Ordering::SeqCst)
493    }
494
495    fn clock(&mut self) -> f64 {
496        crate::clock()
497    }
498}
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503
504    #[test]
505    fn a_fresh_state_holds_no_measurement() {
506        let s = ClockState::default();
507        assert_eq!(s.offset(), None);
508        assert_eq!(s.uncertainty(), None);
509        assert_eq!(s.updates(), 0);
510    }
511
512    #[test]
513    fn a_published_value_comes_back() {
514        let s = ClockState::default();
515        s.publish(-1.25, 0.004);
516        assert_eq!(s.offset(), Some(-1.25));
517        assert_eq!(s.uncertainty(), Some(0.004));
518        assert_eq!(s.updates(), 1);
519    }
520
521    #[test]
522    fn a_reset_reads_once() {
523        let s = Arc::new(ClockState::default());
524        let mut src = LiveSource::new(Arc::clone(&s), 100.0);
525        assert!(!src.was_reset());
526        s.mark_reset();
527        assert!(src.was_reset(), "the first read reports the reset");
528        assert!(!src.was_reset(), "a second read must not report it again");
529    }
530
531    #[test]
532    fn with_no_probe_thread_the_correction_does_not_wait() {
533        // No thread runs, so no value can arrive. The call returns at once.
534        let s = Arc::new(ClockState::default());
535        let mut src = LiveSource::new(s, 100.0);
536        let t = Instant::now();
537        assert_eq!(src.correction(), 0.0);
538        assert!(t.elapsed() < Duration::from_secs(1));
539    }
540
541    #[test]
542    fn the_correction_waits_for_the_first_offset() {
543        let s = Arc::new(ClockState::default());
544        // Act as a running probe thread that publishes after 200 ms.
545        s.alive.store(true, Ordering::SeqCst);
546        let writer = Arc::clone(&s);
547        let h = std::thread::spawn(move || {
548            std::thread::sleep(Duration::from_millis(200));
549            writer.publish(-3.5, 0.001);
550        });
551        let mut src = LiveSource::new(Arc::clone(&s), 100.0);
552        assert_eq!(
553            src.correction(),
554            -3.5,
555            "the first value is the measured offset"
556        );
557        h.join().unwrap();
558    }
559
560    #[test]
561    fn the_post_processor_never_sees_a_zero_offset_first() {
562        use labstream_time::{flags, PostProcessor};
563        let s = Arc::new(ClockState::default());
564        s.alive.store(true, Ordering::SeqCst);
565        let writer = Arc::clone(&s);
566        let h = std::thread::spawn(move || {
567            std::thread::sleep(Duration::from_millis(100));
568            writer.publish(10.0, 0.001);
569        });
570        let mut src = LiveSource::new(Arc::clone(&s), 100.0);
571        let mut post = PostProcessor::new();
572        post.set_options(flags::CLOCKSYNC);
573        assert_eq!(post.process(1.0, &mut src), 11.0);
574        h.join().unwrap();
575    }
576
577    #[test]
578    fn a_stopped_thread_ends_the_wait() {
579        let s = Arc::new(ClockState::default());
580        s.alive.store(true, Ordering::SeqCst);
581        let stopper = Arc::clone(&s);
582        let h = std::thread::spawn(move || {
583            std::thread::sleep(Duration::from_millis(100));
584            stopper.stop();
585        });
586        let t = Instant::now();
587        assert_eq!(s.wait(FIRST_OFFSET_TIMEOUT), None);
588        assert!(t.elapsed() < Duration::from_secs(2));
589        h.join().unwrap();
590    }
591
592    #[test]
593    fn a_reset_offset_sets_the_flag_only_after_a_value() {
594        let s = ClockState::default();
595        s.reset_offset();
596        assert!(!s.reset.load(Ordering::SeqCst), "no value, so no reset");
597        s.publish(1.0, 0.001);
598        s.reset_offset();
599        assert!(s.reset.load(Ordering::SeqCst));
600        assert_eq!(s.offset(), None);
601        assert_eq!(s.uncertainty(), None);
602    }
603
604    #[test]
605    fn a_new_source_needs_a_new_wait() {
606        let s = Arc::new(ClockState::default());
607        s.alive.store(true, Ordering::SeqCst);
608        s.publish(2.0, 0.001);
609        let mut src = LiveSource::new(Arc::clone(&s), 100.0);
610        assert_eq!(src.correction(), 2.0);
611        s.reset_offset();
612        let writer = Arc::clone(&s);
613        let h = std::thread::spawn(move || {
614            std::thread::sleep(Duration::from_millis(100));
615            writer.publish(7.0, 0.001);
616        });
617        assert!(src.was_reset());
618        assert_eq!(src.correction(), 7.0, "the value of the new source");
619        h.join().unwrap();
620    }
621}