Skip to main content

avb_stream/
clock.rs

1//! gPTP time as the media clock: the interface's PTP hardware clock, which
2//! gPTP keeps on the grandmaster's time, mapped to the monotonic clock the
3//! threads sleep on.
4
5use std::io;
6use std::sync::Mutex;
7use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
8use std::time::Duration;
9
10use avb_net::clock::{HardwareClock, monotonic_now};
11
12/// How often the offset between the clocks is measured again.
13const REFRESH: Duration = Duration::from_millis(100);
14/// How far the offset may move between measurements before others have
15/// to confirm it, in nanoseconds: once locked gPTP only steers the
16/// clock's rate, moving it a few microseconds between measurements at
17/// most, so a bigger move is a bad reading (a card's clock was seen off
18/// by 167 us for a tenth of a second), or a step the next measurements
19/// show again.
20const MOST_MOVE: i64 = 50_000;
21/// How far apart the two clocks' rates can be, in parts per million: the
22/// offset can move that much more for each second since it was last
23/// measured, as when no stream asked for a while.
24const MOST_RATE: i64 = 200;
25/// Measurements in a row that a big move needs.
26const CONFIRMATIONS: u8 = 3;
27
28/// The hardware clock, and an offset that moved too far, waiting to be
29/// confirmed, with the measurements in a row that agreed with it.
30struct Hardware {
31    clock: HardwareClock,
32    waiting: Option<(i64, u8)>,
33}
34
35/// gPTP time, read through the monotonic clock.
36pub struct MediaClock {
37    hardware: Option<Mutex<Hardware>>,
38    /// gPTP nanoseconds minus monotonic nanoseconds.
39    offset: AtomicI64,
40    measured: AtomicI64,
41    /// When the offset was last taken, in monotonic nanoseconds.
42    taken: AtomicI64,
43    /// The offset comes from a hardware clock, not a guess.
44    locked: AtomicBool,
45    /// Nanoseconds added to the hardware clock's time to give gPTP time:
46    /// what PTP's measurement cannot see, such as the asymmetry of links
47    /// at different speeds.
48    correction: AtomicI64,
49}
50
51impl MediaClock {
52    /// The clock of the interface's PTP hardware clock `index`, or the
53    /// monotonic clock alone when there is none: streams then flow, but
54    /// their presentation times mean nothing to other entities.
55    pub fn open(index: Option<u32>) -> io::Result<Self> {
56        let hardware = match index {
57            Some(index) => Some(Mutex::new(Hardware {
58                clock: HardwareClock::open(index)?,
59                waiting: None,
60            })),
61            None => None,
62        };
63        let clock = MediaClock {
64            hardware,
65            offset: AtomicI64::new(0),
66            measured: AtomicI64::new(i64::MIN),
67            taken: AtomicI64::new(0),
68            locked: AtomicBool::new(false),
69            correction: AtomicI64::new(0),
70        };
71        clock.refresh(true);
72        Ok(clock)
73    }
74
75    /// Measures the offset again, when it is due or `now` asks.
76    fn refresh(&self, now: bool) {
77        let monotonic = monotonic_now().as_nanos() as i64;
78        let measured = self.measured.load(Ordering::Relaxed);
79        if !now && monotonic.saturating_sub(measured) < REFRESH.as_nanos() as i64 {
80            return;
81        }
82        self.measured.store(monotonic, Ordering::Relaxed);
83        let Some(hardware) = &self.hardware else {
84            return;
85        };
86        let mut hardware = hardware
87            .lock()
88            .unwrap_or_else(std::sync::PoisonError::into_inner);
89        let Hardware { clock, waiting } = &mut *hardware;
90        let Ok(offset) = clock.offset_from_monotonic() else {
91            return;
92        };
93        let offset = offset as i64;
94        let current = self.offset.load(Ordering::Relaxed);
95        let since = monotonic.saturating_sub(self.taken.load(Ordering::Relaxed));
96        let allowed = MOST_MOVE.saturating_add(since / 1_000_000 * MOST_RATE);
97        let near_current = (offset - current).abs() <= allowed;
98        let near = |other: i64| (offset - other).abs() <= MOST_MOVE;
99        let seen = match *waiting {
100            Some((waiting, seen)) if near(waiting) => seen + 1,
101            _ => 1,
102        };
103        if !self.locked.load(Ordering::Relaxed) || near_current || seen >= CONFIRMATIONS {
104            self.offset.store(offset, Ordering::Relaxed);
105            self.taken.store(monotonic, Ordering::Relaxed);
106            self.locked.store(true, Ordering::Relaxed);
107            *waiting = None;
108        } else {
109            *waiting = Some((offset, seen));
110        }
111    }
112
113    /// Whether gPTP time comes from a hardware clock.
114    pub fn locked(&self) -> bool {
115        self.locked.load(Ordering::Relaxed)
116    }
117
118    /// gPTP time now, in nanoseconds.
119    pub fn now(&self) -> i64 {
120        self.refresh(false);
121        monotonic_now().as_nanos() as i64
122            + self.offset.load(Ordering::Relaxed)
123            + self.correction.load(Ordering::Relaxed)
124    }
125
126    /// gPTP time less monotonic time, in nanoseconds.
127    pub fn offset(&self) -> i64 {
128        self.refresh(false);
129        self.offset.load(Ordering::Relaxed) + self.correction.load(Ordering::Relaxed)
130    }
131
132    /// Adds `nanoseconds` to the hardware clock's time from now on, in
133    /// place of what was added before.
134    pub fn set_correction(&self, nanoseconds: i64) {
135        self.correction.store(nanoseconds, Ordering::Relaxed);
136    }
137
138    /// The monotonic time at which gPTP time reaches `gptp` nanoseconds.
139    pub fn monotonic_at(&self, gptp: i64) -> Duration {
140        let monotonic =
141            gptp - self.offset.load(Ordering::Relaxed) - self.correction.load(Ordering::Relaxed);
142        Duration::from_nanos(monotonic.max(0) as u64)
143    }
144}