1use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering, fence};
11use std::sync::{Mutex, PoisonError};
12use std::time::Duration;
13
14use avb_net::clock::monotonic_now;
15use gptp::time::{Mapping, State};
16
17#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
19const REFRESH: Duration = Duration::from_millis(100);
20#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
25const CARRIED: i64 = 10_000;
26#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
31const CONFIRMATIONS: u8 = 3;
32
33#[derive(Debug, Clone, Copy)]
36struct Candidate {
37 at: i64,
38 base: i64,
39 rate: f64,
40 seen: u8,
41}
42
43impl Candidate {
44 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
45 fn gptp_at(&self, monotonic: i64) -> i64 {
46 self.base
47 .saturating_add((monotonic.saturating_sub(self.at) as f64 * self.rate) as i64)
48 }
49}
50
51struct Line {
56 sequence: AtomicU64,
57 at: AtomicI64,
58 base: AtomicI64,
59 rate: AtomicU64,
60}
61
62impl Line {
63 fn new() -> Self {
65 Line {
66 sequence: AtomicU64::new(0),
67 at: AtomicI64::new(0),
68 base: AtomicI64::new(0),
69 rate: AtomicU64::new(1.0f64.to_bits()),
70 }
71 }
72
73 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
75 fn store(&self, at: i64, base: i64, rate: f64) {
76 let sequence = self.sequence.load(Ordering::Relaxed);
77 self.sequence
78 .store(sequence.wrapping_add(1), Ordering::Relaxed);
79 fence(Ordering::Release);
80 self.at.store(at, Ordering::Relaxed);
81 self.base.store(base, Ordering::Relaxed);
82 self.rate.store(rate.to_bits(), Ordering::Relaxed);
83 self.sequence
84 .store(sequence.wrapping_add(2), Ordering::Release);
85 }
86
87 fn load(&self) -> (i64, i64, f64) {
88 loop {
89 let before = self.sequence.load(Ordering::Acquire);
90 let at = self.at.load(Ordering::Relaxed);
91 let base = self.base.load(Ordering::Relaxed);
92 let rate = self.rate.load(Ordering::Relaxed);
93 fence(Ordering::Acquire);
94 if before.is_multiple_of(2) && self.sequence.load(Ordering::Relaxed) == before {
95 return (at, base, f64::from_bits(rate));
96 }
97 std::hint::spin_loop();
98 }
99 }
100
101 fn gptp_at(&self, monotonic: i64) -> i64 {
103 let (at, base, rate) = self.load();
104 base.saturating_add((monotonic.saturating_sub(at) as f64 * rate) as i64)
105 }
106
107 fn monotonic_at(&self, gptp: i64) -> i64 {
109 let (at, base, rate) = self.load();
110 at.saturating_add((gptp.saturating_sub(base) as f64 / rate) as i64)
111 }
112}
113
114fn monotonic_nanos() -> i64 {
115 monotonic_now().as_nanos() as i64
116}
117
118pub struct MediaClock {
120 #[cfg(target_os = "linux")]
121 source: Option<Mutex<gptp::time::Reader>>,
122 line: Line,
123 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
125 held: AtomicBool,
126 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
128 candidate: Mutex<Option<Candidate>>,
129 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
131 measured: AtomicI64,
132 locked: AtomicBool,
135 generation: AtomicU32,
138 last_step: AtomicI64,
140}
141
142impl MediaClock {
143 pub fn gptpd(interface: &str) -> Self {
146 #[cfg(target_os = "linux")]
147 {
148 let clock = MediaClock {
149 source: gptp::time::Reader::open(interface).ok().map(Mutex::new),
150 ..MediaClock::monotonic()
151 };
152 clock.refresh(true);
153 clock
154 }
155 #[cfg(not(target_os = "linux"))]
156 {
157 let _ = interface;
158 MediaClock::monotonic()
159 }
160 }
161
162 pub fn monotonic() -> Self {
165 MediaClock {
166 #[cfg(target_os = "linux")]
167 source: None,
168 line: Line::new(),
169 held: AtomicBool::new(false),
170 candidate: Mutex::new(None),
171 measured: AtomicI64::new(i64::MIN),
172 locked: AtomicBool::new(false),
173 generation: AtomicU32::new(0),
174 last_step: AtomicI64::new(0),
175 }
176 }
177
178 #[cfg_attr(not(target_os = "linux"), allow(unused_variables))]
181 fn refresh(&self, now: bool) {
182 #[cfg(target_os = "linux")]
183 {
184 let monotonic = monotonic_nanos();
185 let measured = self.measured.load(Ordering::Relaxed);
186 if !now && monotonic.saturating_sub(measured) < REFRESH.as_nanos() as i64 {
187 return;
188 }
189 let Some(source) = &self.source else {
190 return;
191 };
192 let Ok(mut reader) = source.try_lock() else {
193 return;
194 };
195 self.measured.store(monotonic, Ordering::Relaxed);
196 let mapping = reader.read(monotonic).ok().flatten();
197 self.apply(mapping);
198 }
199 }
200
201 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
206 fn apply(&self, mapping: Option<Mapping>) {
207 let mut candidate = self
208 .candidate
209 .lock()
210 .unwrap_or_else(PoisonError::into_inner);
211 let Some(mapping) = mapping.filter(|mapping| mapping.state != State::None) else {
212 *candidate = None;
213 self.locked.store(false, Ordering::Relaxed);
214 return;
215 };
216 let base = mapping
217 .at_monotonic
218 .clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
219 let held = self.held.load(Ordering::Relaxed);
220 let step = base - self.line.gptp_at(mapping.monotonic);
221 let carried = held && step.abs() <= CARRIED;
222 if held && !carried {
223 let seen = match *candidate {
224 Some(waiting) if (base - waiting.gptp_at(mapping.monotonic)).abs() <= CARRIED => {
225 waiting.seen + 1
226 }
227 _ => 1,
228 };
229 if seen < CONFIRMATIONS {
230 *candidate = Some(Candidate {
231 at: mapping.monotonic,
232 base,
233 rate: mapping.monotonic_rate,
234 seen,
235 });
236 self.locked.store(true, Ordering::Relaxed);
237 return;
238 }
239 }
240 *candidate = None;
241 self.line
242 .store(mapping.monotonic, base, mapping.monotonic_rate);
243 if !carried {
244 self.last_step.store(step, Ordering::Relaxed);
245 self.generation.fetch_add(1, Ordering::Relaxed);
246 }
247 self.held.store(true, Ordering::Relaxed);
248 self.locked.store(true, Ordering::Relaxed);
249 }
250
251 pub fn locked(&self) -> bool {
254 self.refresh(false);
255 self.locked.load(Ordering::Relaxed)
256 }
257
258 pub fn generation(&self) -> u32 {
261 self.refresh(false);
262 self.generation.load(Ordering::Relaxed)
263 }
264
265 pub fn last_step(&self) -> i64 {
269 self.last_step.load(Ordering::Relaxed)
270 }
271
272 pub fn now(&self) -> i64 {
274 self.refresh(false);
275 self.line.gptp_at(monotonic_nanos())
276 }
277
278 pub fn offset(&self) -> i64 {
280 self.refresh(false);
281 let monotonic = monotonic_nanos();
282 self.line.gptp_at(monotonic) - monotonic
283 }
284
285 pub fn monotonic_at(&self, gptp: i64) -> Duration {
287 Duration::from_nanos(self.line.monotonic_at(gptp).max(0) as u64)
288 }
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294 use gptp::ClockIdentity;
295
296 fn mapping(generation: u32, at: i64, base: i128, rate: f64) -> Mapping {
299 Mapping {
300 generation,
301 state: State::Following,
302 grandmaster: ClockIdentity(0x0001_f2ff_feff_3b14),
303 updated: at,
304 monotonic: at,
305 at_monotonic: base,
306 monotonic_rate: rate,
307 local: 0,
308 at_local: base,
309 local_rate: rate,
310 asymmetry_included: false,
311 residual: Some(12),
312 }
313 }
314
315 const SECOND: i64 = 1_000_000_000;
316
317 #[test]
318 fn without_gptpd_the_monotonic_clock_is_the_time() {
319 let clock = MediaClock::monotonic();
320 assert!(!clock.locked());
321 let before = monotonic_nanos();
322 let now = clock.now();
323 assert!(now >= before && now - before < SECOND);
324 assert_eq!(clock.monotonic_at(now).as_nanos() as i64, now);
325 assert_eq!(clock.generation(), 0);
326 }
327
328 #[test]
331 fn time_follows_the_mapping() {
332 let clock = MediaClock::monotonic();
333 let at = monotonic_nanos();
334 let base = 1_793_400_000 * i128::from(SECOND);
335 clock.apply(Some(mapping(3, at, base, 1.000_010)));
336 assert!(clock.locked());
337 assert_eq!(clock.generation(), 1);
338 assert_eq!(clock.line.gptp_at(at), base as i64);
339 assert_eq!(
341 clock.line.gptp_at(at + SECOND),
342 base as i64 + SECOND + 10_000
343 );
344 let gptp = base as i64 + 2 * SECOND;
345 let wake = clock.line.monotonic_at(gptp);
346 assert!((clock.line.gptp_at(wake) - gptp).abs() <= 1);
347 let offset = clock.offset();
348 assert!((offset - (base as i64 - at)).abs() < SECOND / 1000);
349 }
350
351 fn confirmed(clock: &MediaClock, generation: u32, at: i64, base: i128) {
354 for record in 0..3 {
355 let later = at + record * SECOND / 10;
356 clock.apply(Some(mapping(
357 generation,
358 later,
359 base + i128::from(record * SECOND / 10),
360 1.0,
361 )));
362 }
363 }
364
365 #[test]
370 fn only_a_line_that_does_not_carry_on_counts() {
371 let clock = MediaClock::monotonic();
372 clock.apply(Some(mapping(5, 0, 1_000 * i128::from(SECOND), 1.0)));
373 assert_eq!(clock.generation(), 1);
374 clock.apply(Some(mapping(5, SECOND, 1_001 * i128::from(SECOND), 1.0)));
375 clock.apply(Some(Mapping {
377 state: State::Grandmaster,
378 ..mapping(6, 2 * SECOND, 1_002 * i128::from(SECOND) + 400, 1.0)
379 }));
380 assert_eq!(clock.generation(), 1);
381 clock.apply(Some(mapping(
384 6,
385 3 * SECOND,
386 1_003 * i128::from(SECOND) + 20_400,
387 1.0,
388 )));
389 assert_eq!(clock.generation(), 1);
390 assert_eq!(clock.line.gptp_at(3 * SECOND), 1_003 * SECOND + 400);
391 confirmed(&clock, 6, 3 * SECOND, 1_003 * i128::from(SECOND) + 20_400);
392 assert_eq!(clock.generation(), 2);
393 assert_eq!(clock.last_step(), 20_000);
394 confirmed(&clock, 7, 4 * SECOND, 5_000 * i128::from(SECOND));
395 assert_eq!(clock.generation(), 3);
396 assert_eq!(clock.line.gptp_at(5 * SECOND), 5_001 * SECOND);
397 }
398
399 #[test]
403 fn a_record_off_and_back_is_no_discontinuity() {
404 let clock = MediaClock::monotonic();
405 clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
406 clock.apply(Some(mapping(
407 1,
408 SECOND,
409 1_001 * i128::from(SECOND) + 50_000,
410 1.0,
411 )));
412 clock.apply(Some(mapping(
413 1,
414 SECOND + SECOND / 10,
415 1_001 * i128::from(SECOND + SECOND / 10),
416 1.0,
417 )));
418 clock.apply(Some(mapping(
419 1,
420 2 * SECOND,
421 1_002 * i128::from(SECOND) + 90_000,
422 1.0,
423 )));
424 clock.apply(Some(mapping(
425 1,
426 2 * SECOND + SECOND / 10,
427 1_002 * i128::from(SECOND + SECOND / 10) - 70_000,
428 1.0,
429 )));
430 clock.apply(Some(mapping(
431 1,
432 2 * SECOND + SECOND / 5,
433 1_002 * i128::from(SECOND + SECOND / 5) + 30_000,
434 1.0,
435 )));
436 assert_eq!(clock.generation(), 1);
437 assert_eq!(clock.line.gptp_at(3 * SECOND), 1_003 * SECOND);
438 }
439
440 #[test]
443 fn a_pause_without_a_grandmaster_is_no_discontinuity() {
444 let clock = MediaClock::monotonic();
445 clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
446 let none = Mapping {
447 state: State::None,
448 ..mapping(2, SECOND, 0, 1.0)
449 };
450 clock.apply(Some(none));
451 clock.apply(None);
452 clock.apply(Some(mapping(
453 2,
454 2 * SECOND,
455 1_002 * i128::from(SECOND),
456 1.0,
457 )));
458 assert_eq!(clock.generation(), 1);
459 clock.apply(Some(none));
460 confirmed(&clock, 3, 3 * SECOND, 9_000 * i128::from(SECOND));
461 assert_eq!(clock.generation(), 2);
462 }
463
464 #[test]
468 fn without_a_grandmaster_the_last_line_carries_on() {
469 let clock = MediaClock::monotonic();
470 clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
471 clock.apply(None);
472 assert!(!clock.locked.load(Ordering::Relaxed));
473 assert_eq!(clock.line.gptp_at(SECOND), 1_001 * SECOND);
474 let none = Mapping {
475 state: State::None,
476 ..mapping(2, SECOND, 9 * i128::from(SECOND), 1.0)
477 };
478 clock.apply(Some(none));
479 assert!(!clock.locked.load(Ordering::Relaxed));
480 assert_eq!(clock.line.gptp_at(2 * SECOND), 1_002 * SECOND);
481 assert_eq!(clock.generation.load(Ordering::Relaxed), 1);
482 let ours = Mapping {
484 state: State::Grandmaster,
485 ..mapping(3, 3 * SECOND, 2_000 * i128::from(SECOND), 1.0)
486 };
487 clock.apply(Some(ours));
488 assert!(clock.locked.load(Ordering::Relaxed));
489 }
490
491 #[test]
494 fn a_line_is_read_whole() {
495 let line = std::sync::Arc::new(Line::new());
496 let stop = std::sync::Arc::new(AtomicBool::new(false));
497 let readers: Vec<_> = (0..3)
498 .map(|_| {
499 let line = line.clone();
500 let stop = stop.clone();
501 std::thread::spawn(move || {
502 while !stop.load(Ordering::Relaxed) {
503 let (at, base, rate) = line.load();
504 assert_eq!(base, 2 * at);
506 assert!(at == 0 || rate == at as f64);
507 }
508 })
509 })
510 .collect();
511 for at in 1..200_000i64 {
512 line.store(at, 2 * at, at as f64);
513 }
514 stop.store(true, Ordering::Relaxed);
515 for reader in readers {
516 reader.join().unwrap();
517 }
518 }
519}