use labstream_proto::timesync::{self, Burst};
use labstream_time::{DriftFit, DriftModel, OffsetSource};
use std::net::{SocketAddr, UdpSocket};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
pub fn update_interval() -> Duration {
Duration::from_secs_f64(crate::config::get().time_update_interval)
}
pub fn probe_count() -> usize {
crate::config::get().time_probe_count as usize
}
pub fn probe_interval() -> Duration {
Duration::from_secs_f64(crate::config::get().time_probe_interval)
}
pub fn probe_max_rtt() -> Duration {
Duration::from_secs_f64(crate::config::get().time_probe_max_rtt)
}
pub fn update_min_probes() -> usize {
crate::config::get().time_update_min_probes as usize
}
pub const FIRST_OFFSET_TIMEOUT: Duration = Duration::from_secs(5);
pub const FIRST_PROBE_INTERVAL: Duration = Duration::from_millis(4);
pub const FIRST_RETRY: Duration = Duration::from_millis(250);
#[derive(Debug)]
pub struct ClockState {
offset_bits: AtomicU64,
uncertainty_bits: AtomicU64,
drift_model: Mutex<DriftModel>,
drift_fit: Mutex<Option<DriftFit>>,
have: AtomicBool,
reset: AtomicBool,
stop: AtomicBool,
alive: AtomicBool,
updates: AtomicU64,
target: Mutex<Option<SocketAddr>>,
epoch: AtomicU64,
signal: (Mutex<()>, Condvar),
}
const NO_VALUE: u64 = u64::MAX;
impl Default for ClockState {
fn default() -> Self {
ClockState {
offset_bits: AtomicU64::new(NO_VALUE),
uncertainty_bits: AtomicU64::new(NO_VALUE),
drift_model: Mutex::new(DriftModel::new()),
drift_fit: Mutex::new(None),
have: AtomicBool::new(false),
reset: AtomicBool::new(false),
stop: AtomicBool::new(false),
alive: AtomicBool::new(false),
updates: AtomicU64::new(0),
target: Mutex::new(None),
epoch: AtomicU64::new(0),
signal: (Mutex::new(()), Condvar::new()),
}
}
}
impl ClockState {
pub fn offset(&self) -> Option<f64> {
match self.offset_bits.load(Ordering::SeqCst) {
NO_VALUE => None,
b => Some(f64::from_bits(b)),
}
}
pub fn uncertainty(&self) -> Option<f64> {
match self.uncertainty_bits.load(Ordering::SeqCst) {
NO_VALUE => None,
b => Some(f64::from_bits(b)),
}
}
pub fn updates(&self) -> u64 {
self.updates.load(Ordering::SeqCst)
}
pub fn drift(&self) -> Option<f64> {
self.drift_fit.lock().unwrap().map(|f| f.drift)
}
pub fn drift_fit(&self) -> Option<DriftFit> {
*self.drift_fit.lock().unwrap()
}
pub fn smooth_offset_at(&self, remote_ts: f64) -> Option<f64> {
self.drift_fit
.lock()
.unwrap()
.map(|f| f.offset_for_remote(remote_ts))
}
pub fn is_running(&self) -> bool {
self.alive.load(Ordering::SeqCst) && !self.stop.load(Ordering::SeqCst)
}
pub fn wait(&self, timeout: Duration) -> Option<f64> {
let end = Instant::now() + timeout;
let (lock, cvar) = &self.signal;
let mut guard = lock.lock().unwrap();
loop {
if let Some(v) = self.offset() {
return Some(v);
}
if !self.is_running() {
return None;
}
let left = end.saturating_duration_since(Instant::now());
if left.is_zero() {
return self.offset();
}
guard = cvar
.wait_timeout(guard, left.min(Duration::from_millis(50)))
.unwrap()
.0;
}
}
pub fn mark_reset(&self) {
self.reset.store(true, Ordering::SeqCst);
}
pub fn reset_offset(&self) {
if self.offset().is_some() {
self.reset.store(true, Ordering::SeqCst);
}
self.offset_bits.store(NO_VALUE, Ordering::SeqCst);
self.uncertainty_bits.store(NO_VALUE, Ordering::SeqCst);
self.drift_model.lock().unwrap().reset();
*self.drift_fit.lock().unwrap() = None;
}
pub fn retarget(&self, target: SocketAddr) {
*self.target.lock().unwrap() = Some(target);
self.epoch.fetch_add(1, Ordering::SeqCst);
}
pub fn stop(&self) {
self.stop.store(true, Ordering::SeqCst);
self.notify();
}
fn notify(&self) {
let _guard = self.signal.0.lock().unwrap();
self.signal.1.notify_all();
}
#[cfg(test)]
fn publish(&self, offset: f64, uncertainty: f64) {
self.publish_at(crate::clock(), offset, uncertainty);
}
fn publish_at(&self, local_time: f64, offset: f64, uncertainty: f64) {
let fit = self
.drift_model
.lock()
.unwrap()
.update(local_time, offset, uncertainty);
*self.drift_fit.lock().unwrap() = Some(fit);
self.offset_bits.store(offset.to_bits(), Ordering::SeqCst);
self.uncertainty_bits
.store(uncertainty.to_bits(), Ordering::SeqCst);
self.have.store(true, Ordering::SeqCst);
self.updates.fetch_add(1, Ordering::SeqCst);
self.notify();
}
}
struct AliveGuard(Arc<ClockState>);
impl Drop for AliveGuard {
fn drop(&mut self) {
self.0.alive.store(false, Ordering::SeqCst);
self.0.notify();
}
}
fn probe_socket(target: SocketAddr) -> Option<UdpSocket> {
let any: std::net::IpAddr = if target.is_ipv6() {
std::net::Ipv6Addr::UNSPECIFIED.into()
} else {
std::net::Ipv4Addr::UNSPECIFIED.into()
};
let sock = UdpSocket::bind((any, 0)).ok()?;
let _ = sock.set_read_timeout(Some(Duration::from_millis(40)));
Some(sock)
}
fn collect(sock: &UdpSocket, burst: &mut Burst, end: Instant, enough: Option<usize>) {
let mut buf = [0u8; 4096];
loop {
if enough.is_some_and(|n| burst.accepted() >= n) {
return;
}
let left = end.saturating_duration_since(Instant::now());
if left < Duration::from_micros(100) {
return;
}
let _ = sock.set_read_timeout(Some(left));
match sock.recv_from(&mut buf) {
Ok((n, _)) => {
let t3 = crate::clock();
if let Some(a) = timesync::parse_answer(&buf[..n]) {
burst.accept(&a, t3);
}
}
Err(ref e)
if e.kind() == std::io::ErrorKind::WouldBlock
|| e.kind() == std::io::ErrorKind::TimedOut => {}
Err(_) => std::thread::sleep(left.min(Duration::from_millis(5))),
}
}
}
pub fn start(target: SocketAddr, state: Arc<ClockState>, rng: Arc<Mutex<u64>>) {
*state.target.lock().unwrap() = Some(target);
state.alive.store(true, Ordering::SeqCst);
std::thread::spawn(move || {
let _alive = AliveGuard(Arc::clone(&state));
let mut sock = match probe_socket(target) {
Some(s) => s,
None => return,
};
let mut bound_v6 = target.is_ipv6();
while !state.stop.load(Ordering::SeqCst) {
let epoch = state.epoch.load(Ordering::SeqCst);
let target = match *state.target.lock().unwrap() {
Some(t) => t,
None => return,
};
if target.is_ipv6() != bound_v6 {
sock = match probe_socket(target) {
Some(s) => s,
None => return,
};
bound_v6 = target.is_ipv6();
}
let wave_id = {
let mut r = rng.lock().unwrap();
*r ^= *r << 13;
*r ^= *r >> 7;
*r ^= *r << 17;
(*r as u32 as i32).abs()
};
let mut burst = Burst::new(wave_id);
let fast = state.offset().is_none();
let gap = if fast {
FIRST_PROBE_INTERVAL.min(probe_interval())
} else {
probe_interval()
};
let burst_start = Instant::now();
let burst_end = burst_start + gap * probe_count() as u32 + probe_max_rtt();
for _ in 0..probe_count() {
if state.stop.load(Ordering::SeqCst) {
return;
}
let t0 = crate::clock();
let msg = timesync::build_probe(wave_id, t0);
let _ = sock.send_to(&msg, target);
collect(&sock, &mut burst, Instant::now() + gap, None);
}
let all = if fast { Some(probe_count()) } else { None };
collect(&sock, &mut burst, burst_end, all);
if std::env::var_os("LSL_TRACE_CLOCK").is_some() {
eprintln!(
"TRACE clock wave={wave_id} accepted={} offset={:?} rtt={:?}",
burst.accepted(),
burst.time_offset(),
burst.uncertainty()
);
}
if burst.accepted() >= update_min_probes()
&& state.epoch.load(Ordering::SeqCst) == epoch
{
if let (Some(o), Some(u), Some(lt)) =
(burst.time_offset(), burst.uncertainty(), burst.local_time())
{
state.publish_at(lt, o, u);
}
}
let mut wake = burst_start + update_interval();
if state.offset().is_none() {
wake = wake.min(Instant::now() + FIRST_RETRY);
}
while Instant::now() < wake {
if state.stop.load(Ordering::SeqCst) {
return;
}
std::thread::sleep(Duration::from_millis(20));
}
}
});
}
pub struct LiveSource {
state: Arc<ClockState>,
srate: f64,
waited_out: bool,
last: f64,
}
impl LiveSource {
pub fn new(state: Arc<ClockState>, srate: f64) -> Self {
LiveSource {
state,
srate,
waited_out: false,
last: 0.0,
}
}
}
impl OffsetSource for LiveSource {
fn correction(&mut self) -> f64 {
if let Some(v) = self.state.offset() {
self.waited_out = false;
self.last = v;
return v;
}
if !self.waited_out {
if let Some(v) = self.state.wait(FIRST_OFFSET_TIMEOUT) {
self.last = v;
return v;
}
self.waited_out = true;
if std::env::var_os("LSL_TRACE_CLOCK").is_some() {
eprintln!("TRACE clock: no offset arrived, the timestamps stay uncorrected");
}
}
self.last
}
fn smooth_correction(&mut self, remote_ts: f64) -> f64 {
if let Some(v) = self.state.smooth_offset_at(remote_ts) {
self.waited_out = false;
self.last = v;
return v;
}
if !self.waited_out {
if self.state.wait(FIRST_OFFSET_TIMEOUT).is_some() {
if let Some(v) = self.state.smooth_offset_at(remote_ts) {
self.last = v;
return v;
}
}
self.waited_out = true;
}
self.last
}
fn srate(&mut self) -> f64 {
self.srate
}
fn was_reset(&mut self) -> bool {
self.state.reset.swap(false, Ordering::SeqCst)
}
fn clock(&mut self) -> f64 {
crate::clock()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_fresh_state_holds_no_measurement() {
let s = ClockState::default();
assert_eq!(s.offset(), None);
assert_eq!(s.uncertainty(), None);
assert_eq!(s.updates(), 0);
}
#[test]
fn a_published_value_comes_back() {
let s = ClockState::default();
s.publish(-1.25, 0.004);
assert_eq!(s.offset(), Some(-1.25));
assert_eq!(s.uncertainty(), Some(0.004));
assert_eq!(s.updates(), 1);
}
#[test]
fn a_reset_reads_once() {
let s = Arc::new(ClockState::default());
let mut src = LiveSource::new(Arc::clone(&s), 100.0);
assert!(!src.was_reset());
s.mark_reset();
assert!(src.was_reset(), "the first read reports the reset");
assert!(!src.was_reset(), "a second read must not report it again");
}
#[test]
fn with_no_probe_thread_the_correction_does_not_wait() {
let s = Arc::new(ClockState::default());
let mut src = LiveSource::new(s, 100.0);
let t = Instant::now();
assert_eq!(src.correction(), 0.0);
assert!(t.elapsed() < Duration::from_secs(1));
}
#[test]
fn the_correction_waits_for_the_first_offset() {
let s = Arc::new(ClockState::default());
s.alive.store(true, Ordering::SeqCst);
let writer = Arc::clone(&s);
let h = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(200));
writer.publish(-3.5, 0.001);
});
let mut src = LiveSource::new(Arc::clone(&s), 100.0);
assert_eq!(
src.correction(),
-3.5,
"the first value is the measured offset"
);
h.join().unwrap();
}
#[test]
fn the_post_processor_never_sees_a_zero_offset_first() {
use labstream_time::{flags, PostProcessor};
let s = Arc::new(ClockState::default());
s.alive.store(true, Ordering::SeqCst);
let writer = Arc::clone(&s);
let h = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(100));
writer.publish(10.0, 0.001);
});
let mut src = LiveSource::new(Arc::clone(&s), 100.0);
let mut post = PostProcessor::new();
post.set_options(flags::CLOCKSYNC);
assert_eq!(post.process(1.0, &mut src), 11.0);
h.join().unwrap();
}
#[test]
fn a_stopped_thread_ends_the_wait() {
let s = Arc::new(ClockState::default());
s.alive.store(true, Ordering::SeqCst);
let stopper = Arc::clone(&s);
let h = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(100));
stopper.stop();
});
let t = Instant::now();
assert_eq!(s.wait(FIRST_OFFSET_TIMEOUT), None);
assert!(t.elapsed() < Duration::from_secs(2));
h.join().unwrap();
}
#[test]
fn a_reset_offset_sets_the_flag_only_after_a_value() {
let s = ClockState::default();
s.reset_offset();
assert!(!s.reset.load(Ordering::SeqCst), "no value, so no reset");
s.publish(1.0, 0.001);
s.reset_offset();
assert!(s.reset.load(Ordering::SeqCst));
assert_eq!(s.offset(), None);
assert_eq!(s.uncertainty(), None);
}
#[test]
fn a_new_source_needs_a_new_wait() {
let s = Arc::new(ClockState::default());
s.alive.store(true, Ordering::SeqCst);
s.publish(2.0, 0.001);
let mut src = LiveSource::new(Arc::clone(&s), 100.0);
assert_eq!(src.correction(), 2.0);
s.reset_offset();
let writer = Arc::clone(&s);
let h = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(100));
writer.publish(7.0, 0.001);
});
assert!(src.was_reset());
assert_eq!(src.correction(), 7.0, "the value of the new source");
h.join().unwrap();
}
}