1use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering, fence};
19use std::sync::{Mutex, PoisonError};
20use std::time::Duration;
21
22use avb_net::clock::monotonic_now;
23use gptp::time::{Mapping, State};
24
25#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
27const REFRESH: Duration = Duration::from_millis(100);
28#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
33const CARRIED: i64 = 10_000;
34#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
39const CONFIRMATIONS: u8 = 3;
40#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
46const STALE: Duration = Duration::from_secs(1);
47
48#[derive(Debug, Clone, Copy)]
51struct Candidate {
52 at: i64,
53 base: i64,
54 rate: f64,
55 seen: u8,
56}
57
58impl Candidate {
59 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
60 fn gptp_at(&self, monotonic: i64) -> i64 {
61 self.base
62 .saturating_add((monotonic.saturating_sub(self.at) as f64 * self.rate) as i64)
63 }
64}
65
66struct Line {
71 sequence: AtomicU64,
72 at: AtomicI64,
73 base: AtomicI64,
74 rate: AtomicU64,
75}
76
77impl Line {
78 fn new() -> Self {
80 Line {
81 sequence: AtomicU64::new(0),
82 at: AtomicI64::new(0),
83 base: AtomicI64::new(0),
84 rate: AtomicU64::new(1.0f64.to_bits()),
85 }
86 }
87
88 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
90 fn store(&self, at: i64, base: i64, rate: f64) {
91 let sequence = self.sequence.load(Ordering::Relaxed);
92 self.sequence
93 .store(sequence.wrapping_add(1), Ordering::Relaxed);
94 fence(Ordering::Release);
95 self.at.store(at, Ordering::Relaxed);
96 self.base.store(base, Ordering::Relaxed);
97 self.rate.store(rate.to_bits(), Ordering::Relaxed);
98 self.sequence
99 .store(sequence.wrapping_add(2), Ordering::Release);
100 }
101
102 fn load(&self) -> (i64, i64, f64) {
103 loop {
104 let before = self.sequence.load(Ordering::Acquire);
105 let at = self.at.load(Ordering::Relaxed);
106 let base = self.base.load(Ordering::Relaxed);
107 let rate = self.rate.load(Ordering::Relaxed);
108 fence(Ordering::Acquire);
109 if before.is_multiple_of(2) && self.sequence.load(Ordering::Relaxed) == before {
110 return (at, base, f64::from_bits(rate));
111 }
112 std::hint::spin_loop();
113 }
114 }
115
116 fn gptp_at(&self, monotonic: i64) -> i64 {
118 let (at, base, rate) = self.load();
119 base.saturating_add((monotonic.saturating_sub(at) as f64 * rate) as i64)
120 }
121
122 fn monotonic_at(&self, gptp: i64) -> i64 {
124 let (at, base, rate) = self.load();
125 at.saturating_add((gptp.saturating_sub(base) as f64 / rate) as i64)
126 }
127}
128
129fn monotonic_nanos() -> i64 {
130 monotonic_now().as_nanos() as i64
131}
132
133pub struct MediaClock {
135 #[cfg(target_os = "linux")]
136 source: Option<Mutex<gptp::time::Reader>>,
137 line: Line,
138 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
141 held: AtomicBool,
142 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
144 candidate: Mutex<Option<Candidate>>,
145 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
147 measured: AtomicI64,
148 locked: AtomicBool,
151 generation: AtomicU32,
155 last_step: AtomicI64,
157 card: Line,
160 launching: AtomicBool,
163}
164
165impl MediaClock {
166 pub fn gptpd(interface: &str) -> Self {
169 #[cfg(target_os = "linux")]
170 {
171 let clock = MediaClock {
172 source: gptp::time::Reader::open(interface).ok().map(Mutex::new),
173 ..MediaClock::monotonic()
174 };
175 clock.refresh(true);
176 clock
177 }
178 #[cfg(not(target_os = "linux"))]
179 {
180 let _ = interface;
181 MediaClock::monotonic()
182 }
183 }
184
185 pub fn monotonic() -> Self {
188 MediaClock {
189 #[cfg(target_os = "linux")]
190 source: None,
191 line: Line::new(),
192 held: AtomicBool::new(false),
193 candidate: Mutex::new(None),
194 measured: AtomicI64::new(i64::MIN),
195 locked: AtomicBool::new(false),
196 generation: AtomicU32::new(0),
197 last_step: AtomicI64::new(0),
198 card: Line::new(),
199 launching: AtomicBool::new(false),
200 }
201 }
202
203 #[cfg_attr(not(target_os = "linux"), allow(unused_variables))]
206 fn refresh(&self, now: bool) {
207 #[cfg(target_os = "linux")]
208 {
209 let monotonic = monotonic_nanos();
210 let measured = self.measured.load(Ordering::Relaxed);
211 if !now && monotonic.saturating_sub(measured) < REFRESH.as_nanos() as i64 {
212 return;
213 }
214 let Some(source) = &self.source else {
215 return;
216 };
217 let Ok(mut reader) = source.try_lock() else {
218 return;
219 };
220 let last = self.measured.swap(monotonic, Ordering::Relaxed);
223 let mapping = reader.read(monotonic).ok().flatten();
224 self.take(mapping, monotonic.saturating_sub(last));
225 }
226 }
227
228 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
235 fn take(&self, mapping: Option<Mapping>, since: i64) {
236 if since > STALE.as_nanos() as i64 {
237 self.held.store(false, Ordering::Relaxed);
238 }
239 self.apply(mapping);
240 }
241
242 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
247 fn apply(&self, mapping: Option<Mapping>) {
248 let mut candidate = self
249 .candidate
250 .lock()
251 .unwrap_or_else(PoisonError::into_inner);
252 let Some(mapping) = mapping.filter(|mapping| mapping.state != State::None) else {
253 *candidate = None;
254 self.locked.store(false, Ordering::Relaxed);
255 self.launching.store(false, Ordering::Relaxed);
256 return;
257 };
258 let base = mapping
259 .at_monotonic
260 .clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
261 let held = self.held.load(Ordering::Relaxed);
262 let step = base - self.line.gptp_at(mapping.monotonic);
263 let carried = held && step.abs() <= CARRIED;
264 if held && !carried {
265 let seen = match *candidate {
266 Some(waiting) if (base - waiting.gptp_at(mapping.monotonic)).abs() <= CARRIED => {
267 waiting.seen + 1
268 }
269 _ => 1,
270 };
271 if seen < CONFIRMATIONS {
272 *candidate = Some(Candidate {
273 at: mapping.monotonic,
274 base,
275 rate: mapping.monotonic_rate,
276 seen,
277 });
278 self.locked.store(true, Ordering::Relaxed);
279 self.launching.store(false, Ordering::Relaxed);
281 return;
282 }
283 }
284 *candidate = None;
285 self.line
286 .store(mapping.monotonic, base, mapping.monotonic_rate);
287 if mapping.tai.is_some() {
288 let clamp = |time: i128| time.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
289 self.card.store(
290 clamp(mapping.local),
291 clamp(mapping.at_local),
292 mapping.local_rate,
293 );
294 }
295 self.launching
296 .store(mapping.tai.is_some(), Ordering::Relaxed);
297 if !carried {
298 self.last_step.store(step, Ordering::Relaxed);
299 self.generation.fetch_add(1, Ordering::Relaxed);
300 }
301 self.held.store(true, Ordering::Relaxed);
302 self.locked.store(true, Ordering::Relaxed);
303 }
304
305 pub fn locked(&self) -> bool {
308 self.refresh(false);
309 self.locked.load(Ordering::Relaxed)
310 }
311
312 pub fn generation(&self) -> u32 {
315 self.refresh(false);
316 self.generation.load(Ordering::Relaxed)
317 }
318
319 pub fn last_step(&self) -> i64 {
323 self.last_step.load(Ordering::Relaxed)
324 }
325
326 pub fn now(&self) -> i64 {
328 self.refresh(false);
329 self.line.gptp_at(monotonic_nanos())
330 }
331
332 pub fn offset(&self) -> i64 {
334 self.refresh(false);
335 let monotonic = monotonic_nanos();
336 self.line.gptp_at(monotonic) - monotonic
337 }
338
339 pub fn monotonic_at(&self, gptp: i64) -> Duration {
341 Duration::from_nanos(self.line.monotonic_at(gptp).max(0) as u64)
342 }
343
344 pub fn card_at(&self, gptp: i64) -> Option<u64> {
349 self.refresh(false);
350 if !self.launching.load(Ordering::Relaxed) {
351 return None;
352 }
353 Some(self.card.monotonic_at(gptp).max(0) as u64)
354 }
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360 use gptp::ClockIdentity;
361
362 fn mapping(generation: u32, at: i64, base: i128, rate: f64) -> Mapping {
365 Mapping {
366 generation,
367 state: State::Following,
368 grandmaster: ClockIdentity(0x0001_f2ff_feff_3b14),
369 updated: at,
370 monotonic: at,
371 at_monotonic: base,
372 monotonic_rate: rate,
373 local: 0,
374 at_local: base,
375 local_rate: rate,
376 asymmetry_included: false,
377 residual: Some(12),
378 tai: None,
379 }
380 }
381
382 const SECOND: i64 = 1_000_000_000;
383
384 #[test]
385 fn without_gptpd_the_monotonic_clock_is_the_time() {
386 let clock = MediaClock::monotonic();
387 assert!(!clock.locked());
388 let before = monotonic_nanos();
389 let now = clock.now();
390 assert!(now >= before && now - before < SECOND);
391 assert_eq!(clock.monotonic_at(now).as_nanos() as i64, now);
392 assert_eq!(clock.generation(), 0);
393 }
394
395 #[test]
398 fn time_follows_the_mapping() {
399 let clock = MediaClock::monotonic();
400 let at = monotonic_nanos();
401 let base = 1_793_400_000 * i128::from(SECOND);
402 clock.apply(Some(mapping(3, at, base, 1.000_010)));
403 assert!(clock.locked());
404 assert_eq!(clock.generation(), 1);
405 assert_eq!(clock.line.gptp_at(at), base as i64);
406 assert_eq!(
408 clock.line.gptp_at(at + SECOND),
409 base as i64 + SECOND + 10_000
410 );
411 let gptp = base as i64 + 2 * SECOND;
412 let wake = clock.line.monotonic_at(gptp);
413 assert!((clock.line.gptp_at(wake) - gptp).abs() <= 1);
414 let offset = clock.offset();
415 assert!((offset - (base as i64 - at)).abs() < SECOND / 1000);
416 }
417
418 fn confirmed(clock: &MediaClock, generation: u32, at: i64, base: i128) {
421 for record in 0..3 {
422 let later = at + record * SECOND / 10;
423 clock.apply(Some(mapping(
424 generation,
425 later,
426 base + i128::from(record * SECOND / 10),
427 1.0,
428 )));
429 }
430 }
431
432 #[test]
437 fn only_a_line_that_does_not_carry_on_counts() {
438 let clock = MediaClock::monotonic();
439 clock.apply(Some(mapping(5, 0, 1_000 * i128::from(SECOND), 1.0)));
440 assert_eq!(clock.generation(), 1);
441 clock.apply(Some(mapping(5, SECOND, 1_001 * i128::from(SECOND), 1.0)));
442 clock.apply(Some(Mapping {
444 state: State::Grandmaster,
445 ..mapping(6, 2 * SECOND, 1_002 * i128::from(SECOND) + 400, 1.0)
446 }));
447 assert_eq!(clock.generation(), 1);
448 clock.apply(Some(mapping(
451 6,
452 3 * SECOND,
453 1_003 * i128::from(SECOND) + 20_400,
454 1.0,
455 )));
456 assert_eq!(clock.generation(), 1);
457 assert_eq!(clock.line.gptp_at(3 * SECOND), 1_003 * SECOND + 400);
458 confirmed(&clock, 6, 3 * SECOND, 1_003 * i128::from(SECOND) + 20_400);
459 assert_eq!(clock.generation(), 2);
460 assert_eq!(clock.last_step(), 20_000);
461 confirmed(&clock, 7, 4 * SECOND, 5_000 * i128::from(SECOND));
462 assert_eq!(clock.generation(), 3);
463 assert_eq!(clock.line.gptp_at(5 * SECOND), 5_001 * SECOND);
464 }
465
466 #[test]
470 fn a_record_off_and_back_is_no_discontinuity() {
471 let clock = MediaClock::monotonic();
472 clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
473 clock.apply(Some(mapping(
474 1,
475 SECOND,
476 1_001 * i128::from(SECOND) + 50_000,
477 1.0,
478 )));
479 clock.apply(Some(mapping(
480 1,
481 SECOND + SECOND / 10,
482 1_001 * i128::from(SECOND + SECOND / 10),
483 1.0,
484 )));
485 clock.apply(Some(mapping(
486 1,
487 2 * SECOND,
488 1_002 * i128::from(SECOND) + 90_000,
489 1.0,
490 )));
491 clock.apply(Some(mapping(
492 1,
493 2 * SECOND + SECOND / 10,
494 1_002 * i128::from(SECOND + SECOND / 10) - 70_000,
495 1.0,
496 )));
497 clock.apply(Some(mapping(
498 1,
499 2 * SECOND + SECOND / 5,
500 1_002 * i128::from(SECOND + SECOND / 5) + 30_000,
501 1.0,
502 )));
503 assert_eq!(clock.generation(), 1);
504 assert_eq!(clock.line.gptp_at(3 * SECOND), 1_003 * SECOND);
505 }
506
507 #[test]
512 fn a_line_unread_for_long_gives_way_at_once() {
513 let clock = MediaClock::monotonic();
514 clock.take(
515 Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)),
516 i64::MAX,
517 );
518 assert_eq!(clock.generation(), 1);
519 clock.take(
521 Some(mapping(
522 1,
523 SECOND / 10,
524 1_000 * i128::from(SECOND) + i128::from(SECOND / 10) + 20_000,
525 1.0,
526 )),
527 SECOND / 10,
528 );
529 assert_eq!(clock.generation(), 1);
530 let later = 5 * 3600 * SECOND;
533 let base = 1_000 * i128::from(SECOND) + i128::from(later) + 720_000;
534 clock.take(Some(mapping(1, later, base, 1.0)), later - SECOND / 10);
535 assert_eq!(clock.generation(), 2);
536 assert_eq!(clock.line.gptp_at(later), base as i64);
537 assert_eq!(clock.last_step(), 720_000);
538 clock.take(
540 Some(mapping(
541 1,
542 later + SECOND / 10,
543 base + i128::from(SECOND / 10),
544 1.0,
545 )),
546 SECOND / 10,
547 );
548 assert_eq!(clock.generation(), 2);
549 }
550
551 #[test]
554 fn a_pause_without_a_grandmaster_is_no_discontinuity() {
555 let clock = MediaClock::monotonic();
556 clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
557 let none = Mapping {
558 state: State::None,
559 ..mapping(2, SECOND, 0, 1.0)
560 };
561 clock.apply(Some(none));
562 clock.apply(None);
563 clock.apply(Some(mapping(
564 2,
565 2 * SECOND,
566 1_002 * i128::from(SECOND),
567 1.0,
568 )));
569 assert_eq!(clock.generation(), 1);
570 clock.apply(Some(none));
571 confirmed(&clock, 3, 3 * SECOND, 9_000 * i128::from(SECOND));
572 assert_eq!(clock.generation(), 2);
573 }
574
575 #[test]
579 fn without_a_grandmaster_the_last_line_carries_on() {
580 let clock = MediaClock::monotonic();
581 clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
582 clock.apply(None);
583 assert!(!clock.locked.load(Ordering::Relaxed));
584 assert_eq!(clock.line.gptp_at(SECOND), 1_001 * SECOND);
585 let none = Mapping {
586 state: State::None,
587 ..mapping(2, SECOND, 9 * i128::from(SECOND), 1.0)
588 };
589 clock.apply(Some(none));
590 assert!(!clock.locked.load(Ordering::Relaxed));
591 assert_eq!(clock.line.gptp_at(2 * SECOND), 1_002 * SECOND);
592 assert_eq!(clock.generation.load(Ordering::Relaxed), 1);
593 let ours = Mapping {
595 state: State::Grandmaster,
596 ..mapping(3, 3 * SECOND, 2_000 * i128::from(SECOND), 1.0)
597 };
598 clock.apply(Some(ours));
599 assert!(clock.locked.load(Ordering::Relaxed));
600 }
601
602 #[test]
605 fn a_line_is_read_whole() {
606 let line = std::sync::Arc::new(Line::new());
607 let stop = std::sync::Arc::new(AtomicBool::new(false));
608 let readers: Vec<_> = (0..3)
609 .map(|_| {
610 let line = line.clone();
611 let stop = stop.clone();
612 std::thread::spawn(move || {
613 while !stop.load(Ordering::Relaxed) {
614 let (at, base, rate) = line.load();
615 assert_eq!(base, 2 * at);
617 assert!(at == 0 || rate == at as f64);
618 }
619 })
620 })
621 .collect();
622 for at in 1..200_000i64 {
623 line.store(at, 2 * at, at as f64);
624 }
625 stop.store(true, Ordering::Relaxed);
626 for reader in readers {
627 reader.join().unwrap();
628 }
629 }
630
631 #[test]
635 fn launch_times_only_where_the_card_follows_tai() {
636 let clock = MediaClock::monotonic();
637 let base = 1_000 * i128::from(SECOND);
638 clock.apply(Some(mapping(1, 0, base, 1.0)));
639 assert_eq!(clock.card_at(1_000 * SECOND), None);
640 let card = 1_700_000_000 * i128::from(SECOND);
643 let following = |at: i64, gptp: i128| Mapping {
644 local: card + i128::from(at),
645 at_local: gptp,
646 local_rate: 1.0 / (1.0 + 1e-6),
647 tai: Some(-3),
648 ..mapping(1, at, gptp, 1.0)
649 };
650 clock.apply(Some(following(SECOND, base + i128::from(SECOND))));
651 let launch = clock.card_at(1_002 * SECOND).unwrap();
652 let expected = card + i128::from(SECOND) + 1_000_001_000;
653 assert!(
654 (i128::from(launch) - expected).abs() <= 1,
655 "{launch} {expected}"
656 );
657 clock.apply(Some(following(
659 2 * SECOND,
660 base + 2 * i128::from(SECOND) + 20_000,
661 )));
662 assert_eq!(clock.card_at(1_002 * SECOND), None);
663 clock.apply(Some(following(
664 3 * SECOND,
665 base + 3 * i128::from(SECOND) + 20_000,
666 )));
667 clock.apply(Some(following(
668 4 * SECOND,
669 base + 4 * i128::from(SECOND) + 20_000,
670 )));
671 assert_eq!(clock.generation(), 2);
672 assert!(clock.card_at(1_005 * SECOND).is_some());
673 clock.apply(None);
675 assert_eq!(clock.card_at(1_005 * SECOND), None);
676 clock.apply(Some(mapping(
677 2,
678 5 * SECOND,
679 base + 5 * i128::from(SECOND) + 20_000,
680 1.0,
681 )));
682 assert_eq!(clock.card_at(1_006 * SECOND), None);
683 }
684}