1use 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
15pub fn update_interval() -> Duration {
20 Duration::from_secs_f64(crate::config::get().time_update_interval)
21}
22pub fn probe_count() -> usize {
24 crate::config::get().time_probe_count as usize
25}
26pub fn probe_interval() -> Duration {
28 Duration::from_secs_f64(crate::config::get().time_probe_interval)
29}
30pub fn probe_max_rtt() -> Duration {
32 Duration::from_secs_f64(crate::config::get().time_probe_max_rtt)
33}
34pub fn update_min_probes() -> usize {
36 crate::config::get().time_update_min_probes as usize
37}
38
39pub const FIRST_OFFSET_TIMEOUT: Duration = Duration::from_secs(5);
44
45pub const FIRST_PROBE_INTERVAL: Duration = Duration::from_millis(4);
53
54pub const FIRST_RETRY: Duration = Duration::from_millis(250);
60
61#[derive(Debug)]
63pub struct ClockState {
64 offset_bits: AtomicU64,
66 uncertainty_bits: AtomicU64,
68 drift_model: Mutex<DriftModel>,
70 drift_fit: Mutex<Option<DriftFit>>,
73 have: AtomicBool,
75 reset: AtomicBool,
77 stop: AtomicBool,
79 alive: AtomicBool,
82 updates: AtomicU64,
84 target: Mutex<Option<SocketAddr>>,
86 epoch: AtomicU64,
89 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 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 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 pub fn updates(&self) -> u64 {
134 self.updates.load(Ordering::SeqCst)
135 }
136
137 pub fn drift(&self) -> Option<f64> {
141 self.drift_fit.lock().unwrap().map(|f| f.drift)
142 }
143
144 pub fn drift_fit(&self) -> Option<DriftFit> {
146 *self.drift_fit.lock().unwrap()
147 }
148
149 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 pub fn is_running(&self) -> bool {
160 self.alive.load(Ordering::SeqCst) && !self.stop.load(Ordering::SeqCst)
161 }
162
163 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 guard = cvar
185 .wait_timeout(guard, left.min(Duration::from_millis(50)))
186 .unwrap()
187 .0;
188 }
189 }
190
191 pub fn mark_reset(&self) {
193 self.reset.store(true, Ordering::SeqCst);
194 }
195
196 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 pub fn retarget(&self, target: SocketAddr) {
216 *self.target.lock().unwrap() = Some(target);
217 self.epoch.fetch_add(1, Ordering::SeqCst);
218 }
219
220 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
252struct 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
262fn 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
274fn 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 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 Err(_) => std::thread::sleep(left.min(Duration::from_millis(5))),
303 }
304 }
305}
306
307pub fn start(target: SocketAddr, state: Arc<ClockState>, rng: Arc<Mutex<u64>>) {
315 *state.target.lock().unwrap() = Some(target);
316 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 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 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 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(&sock, &mut burst, Instant::now() + gap, None);
374 }
375
376 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 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 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
417pub struct LiveSource {
419 state: Arc<ClockState>,
420 srate: f64,
421 waited_out: bool,
424 last: f64,
426}
427
428impl LiveSource {
429 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 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 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 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 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 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}