Skip to main content

avb_stream/
clock.rs

1//! gPTP time as the media clock: the grandmaster's time as gptpd gives it
2//! for the interface, a line against the monotonic clock the threads
3//! sleep on, read again ten times a second. gptpd moves no clock to carry
4//! the grandmaster's time. A new line that does not carry the last one on,
5//! as from a grandmaster with time of its own, is a discontinuity the
6//! streams start again across, once records in a row confirm it; one that
7//! does, as gptpd restarting or taking over as grandmaster, is not,
8//! whatever gptpd numbers it.
9
10use 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/// How often gptpd's mapping is read again.
18#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
19const REFRESH: Duration = Duration::from_millis(100);
20/// How far a new line may stand from where the last puts it, in
21/// nanoseconds, and still carry it on: far past a Sync's jitter and what
22/// NTP moving CLOCK_MONOTONIC's rate does in a tenth of a second, short
23/// of half a sample at 48 kHz.
24#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
25const CARRIED: i64 = 10_000;
26/// Records in a row, a tenth of a second apart, that a line not carrying
27/// the last one on needs before it is taken: a single record off and then
28/// back, as gptpd can give while a comparison settles, is no
29/// discontinuity.
30#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
31const CONFIRMATIONS: u8 = 3;
32
33/// A new line waiting to be confirmed, and the records in a row that
34/// agreed with it.
35#[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
51/// The grandmaster's time as a line against the monotonic clock: at
52/// monotonic time `at` it was `base`, and it runs `rate` times as fast,
53/// all behind a sequence count, odd while a line is being stored, so that
54/// a thread never takes half of one line and half of the next.
55struct Line {
56    sequence: AtomicU64,
57    at: AtomicI64,
58    base: AtomicI64,
59    rate: AtomicU64,
60}
61
62impl Line {
63    /// The monotonic clock itself.
64    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    /// Stores a line; one thread at a time, the one refreshing.
74    #[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    /// gPTP time at monotonic time `monotonic`.
102    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    /// Monotonic time when gPTP time is `gptp`.
108    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
118/// gPTP time, read through the monotonic clock.
119pub struct MediaClock {
120    #[cfg(target_os = "linux")]
121    source: Option<Mutex<gptp::time::Reader>>,
122    line: Line,
123    /// The line is a grandmaster's, not the monotonic clock's.
124    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
125    held: AtomicBool,
126    /// A line that does not carry the current one on, until confirmed.
127    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
128    candidate: Mutex<Option<Candidate>>,
129    /// When gptpd's mapping was last read, in monotonic nanoseconds.
130    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
131    measured: AtomicI64,
132    /// A grandmaster's time is followed, or this system's given, as gptpd
133    /// last said within the second.
134    locked: AtomicBool,
135    /// Counts the discontinuities: the first grandmaster's line, and each
136    /// that does not carry the last one on.
137    generation: AtomicU32,
138    /// How far the last discontinuity moved gPTP time, in nanoseconds.
139    last_step: AtomicI64,
140}
141
142impl MediaClock {
143    /// gPTP time as gptpd gives it for `interface`, on Linux; elsewhere,
144    /// and until gptpd gives it, the monotonic clock.
145    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    /// The monotonic clock alone: streams flow, but their presentation
163    /// times mean nothing to other entities.
164    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    /// Reads gptpd's mapping again, when it is due or `now` asks, unless
179    /// another thread is reading it.
180    #[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    /// Takes a mapping read, or none. Without a grandmaster's time the
202    /// last line carries on, unlocked. A line that does not carry the last
203    /// one on waits for [`CONFIRMATIONS`] records in a row agreeing with
204    /// it, the last line carrying on meanwhile.
205    #[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    /// Whether gPTP time is a grandmaster's, followed or this system's,
252    /// rather than the monotonic clock's or an old line carried on.
253    pub fn locked(&self) -> bool {
254        self.refresh(false);
255        self.locked.load(Ordering::Relaxed)
256    }
257
258    /// Counts gPTP time's discontinuities: a stream's timeline built on
259    /// it before a change is no longer good after.
260    pub fn generation(&self) -> u32 {
261        self.refresh(false);
262        self.generation.load(Ordering::Relaxed)
263    }
264
265    /// How far gPTP time moved at the last discontinuity, in nanoseconds:
266    /// against the monotonic clock at the first, against the last line
267    /// after.
268    pub fn last_step(&self) -> i64 {
269        self.last_step.load(Ordering::Relaxed)
270    }
271
272    /// gPTP time now, in nanoseconds.
273    pub fn now(&self) -> i64 {
274        self.refresh(false);
275        self.line.gptp_at(monotonic_nanos())
276    }
277
278    /// gPTP time less monotonic time, in nanoseconds.
279    pub fn offset(&self) -> i64 {
280        self.refresh(false);
281        let monotonic = monotonic_nanos();
282        self.line.gptp_at(monotonic) - monotonic
283    }
284
285    /// The monotonic time at which gPTP time reaches `gptp` nanoseconds.
286    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    /// A grandmaster at `base` ns when the monotonic clock read `at`,
297    /// running `rate` times as fast, in generation `generation`.
298    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    /// gPTP time runs along the mapping's line, its rate and all, and
329    /// wake times come back off it.
330    #[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        // 10 ppm fast: a second on the monotonic clock is 10 us more.
340        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    /// Three records, a tenth of a second apart, of a line from `at`,
352    /// gPTP time `base` there.
353    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    /// A line that carries the last one on counts no discontinuity, as
366    /// gptpd restarting or taking over as grandmaster gives, whatever its
367    /// generation; one that does not counts once three records in a row
368    /// confirm it, as does the first.
369    #[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        // A restart's new generation, its time 400 ns on.
376        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        // A grandmaster of its own time, 20 us off, taken at its third
382        // record.
383        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    /// One record off and then back, as gptpd can give while a
400    /// comparison settles, moves nothing; nor do two records that
401    /// disagree with each other.
402    #[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    /// While gptpd says no grandmaster is present the line holds, and the
441    /// first grandmaster after counts only if it does not carry it on.
442    #[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    /// When gptpd says nothing, or that no grandmaster is present, the
465    /// last line carries on, unlocked, so time does not jump back to the
466    /// monotonic clock's.
467    #[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        // This system as grandmaster is locked too.
483        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    /// Threads reading while another stores a line each take one line
492    /// whole, never half of two.
493    #[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                        // Each line stored has base = 2 × at and rate = at.
505                        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}