1use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering, fence};
13use std::sync::{Mutex, PoisonError};
14use std::time::Duration;
15
16use avb_net::clock::monotonic_now;
17use gptp::time::{Mapping, State};
18
19#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
21const REFRESH: Duration = Duration::from_millis(100);
22#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
27const CARRIED: i64 = 10_000;
28#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
33const CONFIRMATIONS: u8 = 3;
34#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
40const STALE: Duration = Duration::from_secs(1);
41
42#[derive(Debug, Clone, Copy)]
45struct Candidate {
46 at: i64,
47 base: i64,
48 rate: f64,
49 seen: u8,
50}
51
52impl Candidate {
53 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
54 fn gptp_at(&self, monotonic: i64) -> i64 {
55 self.base
56 .saturating_add((monotonic.saturating_sub(self.at) as f64 * self.rate) as i64)
57 }
58}
59
60struct Line {
65 sequence: AtomicU64,
66 at: AtomicI64,
67 base: AtomicI64,
68 rate: AtomicU64,
69}
70
71impl Line {
72 fn new() -> Self {
74 Line {
75 sequence: AtomicU64::new(0),
76 at: AtomicI64::new(0),
77 base: AtomicI64::new(0),
78 rate: AtomicU64::new(1.0f64.to_bits()),
79 }
80 }
81
82 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
84 fn store(&self, at: i64, base: i64, rate: f64) {
85 let sequence = self.sequence.load(Ordering::Relaxed);
86 self.sequence
87 .store(sequence.wrapping_add(1), Ordering::Relaxed);
88 fence(Ordering::Release);
89 self.at.store(at, Ordering::Relaxed);
90 self.base.store(base, Ordering::Relaxed);
91 self.rate.store(rate.to_bits(), Ordering::Relaxed);
92 self.sequence
93 .store(sequence.wrapping_add(2), Ordering::Release);
94 }
95
96 fn load(&self) -> (i64, i64, f64) {
97 loop {
98 let before = self.sequence.load(Ordering::Acquire);
99 let at = self.at.load(Ordering::Relaxed);
100 let base = self.base.load(Ordering::Relaxed);
101 let rate = self.rate.load(Ordering::Relaxed);
102 fence(Ordering::Acquire);
103 if before.is_multiple_of(2) && self.sequence.load(Ordering::Relaxed) == before {
104 return (at, base, f64::from_bits(rate));
105 }
106 std::hint::spin_loop();
107 }
108 }
109
110 fn gptp_at(&self, monotonic: i64) -> i64 {
112 let (at, base, rate) = self.load();
113 base.saturating_add((monotonic.saturating_sub(at) as f64 * rate) as i64)
114 }
115
116 fn monotonic_at(&self, gptp: i64) -> i64 {
118 let (at, base, rate) = self.load();
119 at.saturating_add((gptp.saturating_sub(base) as f64 / rate) as i64)
120 }
121}
122
123fn monotonic_nanos() -> i64 {
124 monotonic_now().as_nanos() as i64
125}
126
127pub struct MediaClock {
129 #[cfg(target_os = "linux")]
130 source: Option<Mutex<gptp::time::Reader>>,
131 line: Line,
132 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
135 held: AtomicBool,
136 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
138 candidate: Mutex<Option<Candidate>>,
139 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
141 measured: AtomicI64,
142 locked: AtomicBool,
145 generation: AtomicU32,
149 last_step: AtomicI64,
151}
152
153impl MediaClock {
154 pub fn gptpd(interface: &str) -> Self {
157 #[cfg(target_os = "linux")]
158 {
159 let clock = MediaClock {
160 source: gptp::time::Reader::open(interface).ok().map(Mutex::new),
161 ..MediaClock::monotonic()
162 };
163 clock.refresh(true);
164 clock
165 }
166 #[cfg(not(target_os = "linux"))]
167 {
168 let _ = interface;
169 MediaClock::monotonic()
170 }
171 }
172
173 pub fn monotonic() -> Self {
176 MediaClock {
177 #[cfg(target_os = "linux")]
178 source: None,
179 line: Line::new(),
180 held: AtomicBool::new(false),
181 candidate: Mutex::new(None),
182 measured: AtomicI64::new(i64::MIN),
183 locked: AtomicBool::new(false),
184 generation: AtomicU32::new(0),
185 last_step: AtomicI64::new(0),
186 }
187 }
188
189 #[cfg_attr(not(target_os = "linux"), allow(unused_variables))]
192 fn refresh(&self, now: bool) {
193 #[cfg(target_os = "linux")]
194 {
195 let monotonic = monotonic_nanos();
196 let measured = self.measured.load(Ordering::Relaxed);
197 if !now && monotonic.saturating_sub(measured) < REFRESH.as_nanos() as i64 {
198 return;
199 }
200 let Some(source) = &self.source else {
201 return;
202 };
203 let Ok(mut reader) = source.try_lock() else {
204 return;
205 };
206 let last = self.measured.swap(monotonic, Ordering::Relaxed);
209 let mapping = reader.read(monotonic).ok().flatten();
210 self.take(mapping, monotonic.saturating_sub(last));
211 }
212 }
213
214 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
221 fn take(&self, mapping: Option<Mapping>, since: i64) {
222 if since > STALE.as_nanos() as i64 {
223 self.held.store(false, Ordering::Relaxed);
224 }
225 self.apply(mapping);
226 }
227
228 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
233 fn apply(&self, mapping: Option<Mapping>) {
234 let mut candidate = self
235 .candidate
236 .lock()
237 .unwrap_or_else(PoisonError::into_inner);
238 let Some(mapping) = mapping.filter(|mapping| mapping.state != State::None) else {
239 *candidate = None;
240 self.locked.store(false, Ordering::Relaxed);
241 return;
242 };
243 let base = mapping
244 .at_monotonic
245 .clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
246 let held = self.held.load(Ordering::Relaxed);
247 let step = base - self.line.gptp_at(mapping.monotonic);
248 let carried = held && step.abs() <= CARRIED;
249 if held && !carried {
250 let seen = match *candidate {
251 Some(waiting) if (base - waiting.gptp_at(mapping.monotonic)).abs() <= CARRIED => {
252 waiting.seen + 1
253 }
254 _ => 1,
255 };
256 if seen < CONFIRMATIONS {
257 *candidate = Some(Candidate {
258 at: mapping.monotonic,
259 base,
260 rate: mapping.monotonic_rate,
261 seen,
262 });
263 self.locked.store(true, Ordering::Relaxed);
264 return;
265 }
266 }
267 *candidate = None;
268 self.line
269 .store(mapping.monotonic, base, mapping.monotonic_rate);
270 if !carried {
271 self.last_step.store(step, Ordering::Relaxed);
272 self.generation.fetch_add(1, Ordering::Relaxed);
273 }
274 self.held.store(true, Ordering::Relaxed);
275 self.locked.store(true, Ordering::Relaxed);
276 }
277
278 pub fn locked(&self) -> bool {
281 self.refresh(false);
282 self.locked.load(Ordering::Relaxed)
283 }
284
285 pub fn generation(&self) -> u32 {
288 self.refresh(false);
289 self.generation.load(Ordering::Relaxed)
290 }
291
292 pub fn last_step(&self) -> i64 {
296 self.last_step.load(Ordering::Relaxed)
297 }
298
299 pub fn now(&self) -> i64 {
301 self.refresh(false);
302 self.line.gptp_at(monotonic_nanos())
303 }
304
305 pub fn offset(&self) -> i64 {
307 self.refresh(false);
308 let monotonic = monotonic_nanos();
309 self.line.gptp_at(monotonic) - monotonic
310 }
311
312 pub fn monotonic_at(&self, gptp: i64) -> Duration {
314 Duration::from_nanos(self.line.monotonic_at(gptp).max(0) as u64)
315 }
316}
317
318#[cfg(test)]
319mod tests {
320 use super::*;
321 use gptp::ClockIdentity;
322
323 fn mapping(generation: u32, at: i64, base: i128, rate: f64) -> Mapping {
326 Mapping {
327 generation,
328 state: State::Following,
329 grandmaster: ClockIdentity(0x0001_f2ff_feff_3b14),
330 updated: at,
331 monotonic: at,
332 at_monotonic: base,
333 monotonic_rate: rate,
334 local: 0,
335 at_local: base,
336 local_rate: rate,
337 asymmetry_included: false,
338 residual: Some(12),
339 }
340 }
341
342 const SECOND: i64 = 1_000_000_000;
343
344 #[test]
345 fn without_gptpd_the_monotonic_clock_is_the_time() {
346 let clock = MediaClock::monotonic();
347 assert!(!clock.locked());
348 let before = monotonic_nanos();
349 let now = clock.now();
350 assert!(now >= before && now - before < SECOND);
351 assert_eq!(clock.monotonic_at(now).as_nanos() as i64, now);
352 assert_eq!(clock.generation(), 0);
353 }
354
355 #[test]
358 fn time_follows_the_mapping() {
359 let clock = MediaClock::monotonic();
360 let at = monotonic_nanos();
361 let base = 1_793_400_000 * i128::from(SECOND);
362 clock.apply(Some(mapping(3, at, base, 1.000_010)));
363 assert!(clock.locked());
364 assert_eq!(clock.generation(), 1);
365 assert_eq!(clock.line.gptp_at(at), base as i64);
366 assert_eq!(
368 clock.line.gptp_at(at + SECOND),
369 base as i64 + SECOND + 10_000
370 );
371 let gptp = base as i64 + 2 * SECOND;
372 let wake = clock.line.monotonic_at(gptp);
373 assert!((clock.line.gptp_at(wake) - gptp).abs() <= 1);
374 let offset = clock.offset();
375 assert!((offset - (base as i64 - at)).abs() < SECOND / 1000);
376 }
377
378 fn confirmed(clock: &MediaClock, generation: u32, at: i64, base: i128) {
381 for record in 0..3 {
382 let later = at + record * SECOND / 10;
383 clock.apply(Some(mapping(
384 generation,
385 later,
386 base + i128::from(record * SECOND / 10),
387 1.0,
388 )));
389 }
390 }
391
392 #[test]
397 fn only_a_line_that_does_not_carry_on_counts() {
398 let clock = MediaClock::monotonic();
399 clock.apply(Some(mapping(5, 0, 1_000 * i128::from(SECOND), 1.0)));
400 assert_eq!(clock.generation(), 1);
401 clock.apply(Some(mapping(5, SECOND, 1_001 * i128::from(SECOND), 1.0)));
402 clock.apply(Some(Mapping {
404 state: State::Grandmaster,
405 ..mapping(6, 2 * SECOND, 1_002 * i128::from(SECOND) + 400, 1.0)
406 }));
407 assert_eq!(clock.generation(), 1);
408 clock.apply(Some(mapping(
411 6,
412 3 * SECOND,
413 1_003 * i128::from(SECOND) + 20_400,
414 1.0,
415 )));
416 assert_eq!(clock.generation(), 1);
417 assert_eq!(clock.line.gptp_at(3 * SECOND), 1_003 * SECOND + 400);
418 confirmed(&clock, 6, 3 * SECOND, 1_003 * i128::from(SECOND) + 20_400);
419 assert_eq!(clock.generation(), 2);
420 assert_eq!(clock.last_step(), 20_000);
421 confirmed(&clock, 7, 4 * SECOND, 5_000 * i128::from(SECOND));
422 assert_eq!(clock.generation(), 3);
423 assert_eq!(clock.line.gptp_at(5 * SECOND), 5_001 * SECOND);
424 }
425
426 #[test]
430 fn a_record_off_and_back_is_no_discontinuity() {
431 let clock = MediaClock::monotonic();
432 clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
433 clock.apply(Some(mapping(
434 1,
435 SECOND,
436 1_001 * i128::from(SECOND) + 50_000,
437 1.0,
438 )));
439 clock.apply(Some(mapping(
440 1,
441 SECOND + SECOND / 10,
442 1_001 * i128::from(SECOND + SECOND / 10),
443 1.0,
444 )));
445 clock.apply(Some(mapping(
446 1,
447 2 * SECOND,
448 1_002 * i128::from(SECOND) + 90_000,
449 1.0,
450 )));
451 clock.apply(Some(mapping(
452 1,
453 2 * SECOND + SECOND / 10,
454 1_002 * i128::from(SECOND + SECOND / 10) - 70_000,
455 1.0,
456 )));
457 clock.apply(Some(mapping(
458 1,
459 2 * SECOND + SECOND / 5,
460 1_002 * i128::from(SECOND + SECOND / 5) + 30_000,
461 1.0,
462 )));
463 assert_eq!(clock.generation(), 1);
464 assert_eq!(clock.line.gptp_at(3 * SECOND), 1_003 * SECOND);
465 }
466
467 #[test]
472 fn a_line_unread_for_long_gives_way_at_once() {
473 let clock = MediaClock::monotonic();
474 clock.take(
475 Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)),
476 i64::MAX,
477 );
478 assert_eq!(clock.generation(), 1);
479 clock.take(
481 Some(mapping(
482 1,
483 SECOND / 10,
484 1_000 * i128::from(SECOND) + i128::from(SECOND / 10) + 20_000,
485 1.0,
486 )),
487 SECOND / 10,
488 );
489 assert_eq!(clock.generation(), 1);
490 let later = 5 * 3600 * SECOND;
493 let base = 1_000 * i128::from(SECOND) + i128::from(later) + 720_000;
494 clock.take(Some(mapping(1, later, base, 1.0)), later - SECOND / 10);
495 assert_eq!(clock.generation(), 2);
496 assert_eq!(clock.line.gptp_at(later), base as i64);
497 assert_eq!(clock.last_step(), 720_000);
498 clock.take(
500 Some(mapping(
501 1,
502 later + SECOND / 10,
503 base + i128::from(SECOND / 10),
504 1.0,
505 )),
506 SECOND / 10,
507 );
508 assert_eq!(clock.generation(), 2);
509 }
510
511 #[test]
514 fn a_pause_without_a_grandmaster_is_no_discontinuity() {
515 let clock = MediaClock::monotonic();
516 clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
517 let none = Mapping {
518 state: State::None,
519 ..mapping(2, SECOND, 0, 1.0)
520 };
521 clock.apply(Some(none));
522 clock.apply(None);
523 clock.apply(Some(mapping(
524 2,
525 2 * SECOND,
526 1_002 * i128::from(SECOND),
527 1.0,
528 )));
529 assert_eq!(clock.generation(), 1);
530 clock.apply(Some(none));
531 confirmed(&clock, 3, 3 * SECOND, 9_000 * i128::from(SECOND));
532 assert_eq!(clock.generation(), 2);
533 }
534
535 #[test]
539 fn without_a_grandmaster_the_last_line_carries_on() {
540 let clock = MediaClock::monotonic();
541 clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
542 clock.apply(None);
543 assert!(!clock.locked.load(Ordering::Relaxed));
544 assert_eq!(clock.line.gptp_at(SECOND), 1_001 * SECOND);
545 let none = Mapping {
546 state: State::None,
547 ..mapping(2, SECOND, 9 * i128::from(SECOND), 1.0)
548 };
549 clock.apply(Some(none));
550 assert!(!clock.locked.load(Ordering::Relaxed));
551 assert_eq!(clock.line.gptp_at(2 * SECOND), 1_002 * SECOND);
552 assert_eq!(clock.generation.load(Ordering::Relaxed), 1);
553 let ours = Mapping {
555 state: State::Grandmaster,
556 ..mapping(3, 3 * SECOND, 2_000 * i128::from(SECOND), 1.0)
557 };
558 clock.apply(Some(ours));
559 assert!(clock.locked.load(Ordering::Relaxed));
560 }
561
562 #[test]
565 fn a_line_is_read_whole() {
566 let line = std::sync::Arc::new(Line::new());
567 let stop = std::sync::Arc::new(AtomicBool::new(false));
568 let readers: Vec<_> = (0..3)
569 .map(|_| {
570 let line = line.clone();
571 let stop = stop.clone();
572 std::thread::spawn(move || {
573 while !stop.load(Ordering::Relaxed) {
574 let (at, base, rate) = line.load();
575 assert_eq!(base, 2 * at);
577 assert!(at == 0 || rate == at as f64);
578 }
579 })
580 })
581 .collect();
582 for at in 1..200_000i64 {
583 line.store(at, 2 * at, at as f64);
584 }
585 stop.store(true, Ordering::Relaxed);
586 for reader in readers {
587 reader.join().unwrap();
588 }
589 }
590}