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. The line is read only while something asks
9//! for the time; one nothing read for a while has drifted, and the next
10//! record replaces it at once, as the first does.
11
12use 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/// How often gptpd's mapping is read again.
20#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
21const REFRESH: Duration = Duration::from_millis(100);
22/// How far a new line may stand from where the last puts it, in
23/// nanoseconds, and still carry it on: far past a Sync's jitter and what
24/// NTP moving CLOCK_MONOTONIC's rate does in a tenth of a second, short
25/// of half a sample at 48 kHz.
26#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
27const CARRIED: i64 = 10_000;
28/// Records in a row, a tenth of a second apart, that a line not carrying
29/// the last one on needs before it is taken: a single record off and then
30/// back, as gptpd can give while a comparison settles, is no
31/// discontinuity.
32#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
33const CONFIRMATIONS: u8 = 3;
34/// How long the line may go unread and still judge the next record: ten
35/// reads missed. The line runs on at the rate of the record it came from,
36/// and the monotonic clock's rate moves under it, as NTP moves it, so
37/// that after minutes or hours it stands far past [`CARRIED`] from gPTP
38/// time with no discontinuity in gPTP time at all.
39#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
40const STALE: Duration = Duration::from_secs(1);
41
42/// A new line waiting to be confirmed, and the records in a row that
43/// agreed with it.
44#[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
60/// The grandmaster's time as a line against the monotonic clock: at
61/// monotonic time `at` it was `base`, and it runs `rate` times as fast,
62/// all behind a sequence count, odd while a line is being stored, so that
63/// a thread never takes half of one line and half of the next.
64struct Line {
65    sequence: AtomicU64,
66    at: AtomicI64,
67    base: AtomicI64,
68    rate: AtomicU64,
69}
70
71impl Line {
72    /// The monotonic clock itself.
73    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    /// Stores a line; one thread at a time, the one refreshing.
83    #[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    /// gPTP time at monotonic time `monotonic`.
111    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    /// Monotonic time when gPTP time is `gptp`.
117    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
127/// gPTP time, read through the monotonic clock.
128pub struct MediaClock {
129    #[cfg(target_os = "linux")]
130    source: Option<Mutex<gptp::time::Reader>>,
131    line: Line,
132    /// The line is a grandmaster's, not the monotonic clock's, and read
133    /// recently enough to judge the next record by.
134    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
135    held: AtomicBool,
136    /// A line that does not carry the current one on, until confirmed.
137    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
138    candidate: Mutex<Option<Candidate>>,
139    /// When gptpd's mapping was last read, in monotonic nanoseconds.
140    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
141    measured: AtomicI64,
142    /// A grandmaster's time is followed, or this system's given, as gptpd
143    /// last said within the second.
144    locked: AtomicBool,
145    /// Counts the discontinuities: the first grandmaster's line, the first
146    /// after the line went unread past [`STALE`], and each that does not
147    /// carry the last one on.
148    generation: AtomicU32,
149    /// How far the last discontinuity moved gPTP time, in nanoseconds.
150    last_step: AtomicI64,
151}
152
153impl MediaClock {
154    /// gPTP time as gptpd gives it for `interface`, on Linux; elsewhere,
155    /// and until gptpd gives it, the monotonic clock.
156    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    /// The monotonic clock alone: streams flow, but their presentation
174    /// times mean nothing to other entities.
175    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    /// Reads gptpd's mapping again, when it is due or `now` asks, unless
190    /// another thread is reading it.
191    #[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            // Swapped under the reader's lock, the last read's time is the
207            // one before this, not one another thread has just replaced.
208            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    /// Takes a mapping read `since` nanoseconds after the read before it.
215    /// A line nothing read for longer than [`STALE`], as while no stream
216    /// ran, says nothing of where the next record should stand, so that
217    /// record goes in at once, as the first does: a stream starting then
218    /// starts on the new line, rather than on the old one until records
219    /// confirm the new and then again across the change.
220    #[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    /// Takes a mapping read, or none. Without a grandmaster's time the
229    /// last line carries on, unlocked. A line that does not carry the last
230    /// one on waits for [`CONFIRMATIONS`] records in a row agreeing with
231    /// it, the last line carrying on meanwhile.
232    #[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    /// Whether gPTP time is a grandmaster's, followed or this system's,
279    /// rather than the monotonic clock's or an old line carried on.
280    pub fn locked(&self) -> bool {
281        self.refresh(false);
282        self.locked.load(Ordering::Relaxed)
283    }
284
285    /// Counts gPTP time's discontinuities: a stream's timeline built on
286    /// it before a change is no longer good after.
287    pub fn generation(&self) -> u32 {
288        self.refresh(false);
289        self.generation.load(Ordering::Relaxed)
290    }
291
292    /// How far gPTP time moved at the last discontinuity, in nanoseconds:
293    /// against the monotonic clock at the first, against the last line
294    /// after.
295    pub fn last_step(&self) -> i64 {
296        self.last_step.load(Ordering::Relaxed)
297    }
298
299    /// gPTP time now, in nanoseconds.
300    pub fn now(&self) -> i64 {
301        self.refresh(false);
302        self.line.gptp_at(monotonic_nanos())
303    }
304
305    /// gPTP time less monotonic time, in nanoseconds.
306    pub fn offset(&self) -> i64 {
307        self.refresh(false);
308        let monotonic = monotonic_nanos();
309        self.line.gptp_at(monotonic) - monotonic
310    }
311
312    /// The monotonic time at which gPTP time reaches `gptp` nanoseconds.
313    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    /// A grandmaster at `base` ns when the monotonic clock read `at`,
324    /// running `rate` times as fast, in generation `generation`.
325    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    /// gPTP time runs along the mapping's line, its rate and all, and
356    /// wake times come back off it.
357    #[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        // 10 ppm fast: a second on the monotonic clock is 10 us more.
367        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    /// Three records, a tenth of a second apart, of a line from `at`,
379    /// gPTP time `base` there.
380    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    /// A line that carries the last one on counts no discontinuity, as
393    /// gptpd restarting or taking over as grandmaster gives, whatever its
394    /// generation; one that does not counts once three records in a row
395    /// confirm it, as does the first.
396    #[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        // A restart's new generation, its time 400 ns on.
403        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        // A grandmaster of its own time, 20 us off, taken at its third
409        // record.
410        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    /// One record off and then back, as gptpd can give while a
427    /// comparison settles, moves nothing; nor do two records that
428    /// disagree with each other.
429    #[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    /// A line nothing read for hours has drifted with the monotonic
468    /// clock's rate, and the next record goes in at once, as the first
469    /// does; a record a tenth of a second after its last read still waits
470    /// for confirmation.
471    #[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        // Read again a tenth of a second on, 20 us off: a candidate.
480        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        // Five hours unread, gPTP time where a rate 0.04 ppm off puts it,
491        // 720 us from the line: taken at its first record.
492        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        // The next read, on time and on the new line, carries it on.
499        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    /// While gptpd says no grandmaster is present the line holds, and the
512    /// first grandmaster after counts only if it does not carry it on.
513    #[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    /// When gptpd says nothing, or that no grandmaster is present, the
536    /// last line carries on, unlocked, so time does not jump back to the
537    /// monotonic clock's.
538    #[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        // This system as grandmaster is locked too.
554        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    /// Threads reading while another stores a line each take one line
563    /// whole, never half of two.
564    #[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                        // Each line stored has base = 2 × at and rate = at.
576                        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}