1use 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
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
39#[derive(Debug)]
41pub struct ClockState {
42 offset_bits: AtomicU64,
44 uncertainty_bits: AtomicU64,
46 have: AtomicBool,
48 reset: AtomicBool,
50 stop: AtomicBool,
52 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 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 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 pub fn updates(&self) -> u64 {
91 self.updates.load(Ordering::SeqCst)
92 }
93
94 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 pub fn mark_reset(&self) {
108 self.reset.store(true, Ordering::SeqCst);
109 }
110
111 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
125pub fn start(target: std::net::SocketAddr, state: Arc<ClockState>, rng: Arc<Mutex<u64>>) {
131 std::thread::spawn(move || {
132 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 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 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 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 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
225pub struct LiveSource {
227 state: Arc<ClockState>,
228 srate: f64,
229}
230
231impl LiveSource {
232 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 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}