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//!
12//! Where gptpd keeps the port's hardware clock near CLOCK_TAI, its record
13//! says so, and a second line gives the card's clock at a gPTP time: the
14//! launch time of a frame due then, for a card that sends frames at their
15//! times. Without it, or while a new line waits to be confirmed, there is
16//! none, and frames are sent when due.
17
18use 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/// How often gptpd's mapping is read again.
26#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
27const REFRESH: Duration = Duration::from_millis(100);
28/// How far a new line may stand from where the last puts it, in
29/// nanoseconds, and still carry it on: far past a Sync's jitter and what
30/// NTP moving CLOCK_MONOTONIC's rate does in a tenth of a second, short
31/// of half a sample at 48 kHz.
32#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
33const CARRIED: i64 = 10_000;
34/// Records in a row, a tenth of a second apart, that a line not carrying
35/// the last one on needs before it is taken: a single record off and then
36/// back, as gptpd can give while a comparison settles, is no
37/// discontinuity.
38#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
39const CONFIRMATIONS: u8 = 3;
40/// How long the line may go unread and still judge the next record: ten
41/// reads missed. The line runs on at the rate of the record it came from,
42/// and the monotonic clock's rate moves under it, as NTP moves it, so
43/// that after minutes or hours it stands far past [`CARRIED`] from gPTP
44/// time with no discontinuity in gPTP time at all.
45#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
46const STALE: Duration = Duration::from_secs(1);
47
48/// A new line waiting to be confirmed, and the records in a row that
49/// agreed with it.
50#[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
66/// The grandmaster's time as a line against the monotonic clock: at
67/// monotonic time `at` it was `base`, and it runs `rate` times as fast,
68/// all behind a sequence count, odd while a line is being stored, so that
69/// a thread never takes half of one line and half of the next.
70struct Line {
71    sequence: AtomicU64,
72    at: AtomicI64,
73    base: AtomicI64,
74    rate: AtomicU64,
75}
76
77impl Line {
78    /// The monotonic clock itself.
79    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    /// Stores a line; one thread at a time, the one refreshing.
89    #[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    /// gPTP time at monotonic time `monotonic`.
117    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    /// Monotonic time when gPTP time is `gptp`.
123    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
133/// gPTP time, read through the monotonic clock.
134pub struct MediaClock {
135    #[cfg(target_os = "linux")]
136    source: Option<Mutex<gptp::time::Reader>>,
137    line: Line,
138    /// The line is a grandmaster's, not the monotonic clock's, and read
139    /// recently enough to judge the next record by.
140    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
141    held: AtomicBool,
142    /// A line that does not carry the current one on, until confirmed.
143    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
144    candidate: Mutex<Option<Candidate>>,
145    /// When gptpd's mapping was last read, in monotonic nanoseconds.
146    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
147    measured: AtomicI64,
148    /// A grandmaster's time is followed, or this system's given, as gptpd
149    /// last said within the second.
150    locked: AtomicBool,
151    /// Counts the discontinuities: the first grandmaster's line, the first
152    /// after the line went unread past [`STALE`], and each that does not
153    /// carry the last one on.
154    generation: AtomicU32,
155    /// How far the last discontinuity moved gPTP time, in nanoseconds.
156    last_step: AtomicI64,
157    /// gPTP time against the card's clock, as a line on that clock:
158    /// at card time `at` gPTP time was `base`.
159    card: Line,
160    /// The card's line holds: gptpd keeps the card's clock near CLOCK_TAI
161    /// and the gPTP line is the record's.
162    launching: AtomicBool,
163}
164
165impl MediaClock {
166    /// gPTP time as gptpd gives it for `interface`, on Linux; elsewhere,
167    /// and until gptpd gives it, the monotonic clock.
168    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    /// The monotonic clock alone: streams flow, but their presentation
186    /// times mean nothing to other entities.
187    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    /// Reads gptpd's mapping again, when it is due or `now` asks, unless
204    /// another thread is reading it.
205    #[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            // Swapped under the reader's lock, the last read's time is the
221            // one before this, not one another thread has just replaced.
222            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    /// Takes a mapping read `since` nanoseconds after the read before it.
229    /// A line nothing read for longer than [`STALE`], as while no stream
230    /// ran, says nothing of where the next record should stand, so that
231    /// record goes in at once, as the first does: a stream starting then
232    /// starts on the new line, rather than on the old one until records
233    /// confirm the new and then again across the change.
234    #[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    /// Takes a mapping read, or none. Without a grandmaster's time the
243    /// last line carries on, unlocked. A line that does not carry the last
244    /// one on waits for [`CONFIRMATIONS`] records in a row agreeing with
245    /// it, the last line carrying on meanwhile.
246    #[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                // Frames are due on the old line, the card's on the new.
280                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    /// Whether gPTP time is a grandmaster's, followed or this system's,
306    /// rather than the monotonic clock's or an old line carried on.
307    pub fn locked(&self) -> bool {
308        self.refresh(false);
309        self.locked.load(Ordering::Relaxed)
310    }
311
312    /// Counts gPTP time's discontinuities: a stream's timeline built on
313    /// it before a change is no longer good after.
314    pub fn generation(&self) -> u32 {
315        self.refresh(false);
316        self.generation.load(Ordering::Relaxed)
317    }
318
319    /// How far gPTP time moved at the last discontinuity, in nanoseconds:
320    /// against the monotonic clock at the first, against the last line
321    /// after.
322    pub fn last_step(&self) -> i64 {
323        self.last_step.load(Ordering::Relaxed)
324    }
325
326    /// gPTP time now, in nanoseconds.
327    pub fn now(&self) -> i64 {
328        self.refresh(false);
329        self.line.gptp_at(monotonic_nanos())
330    }
331
332    /// gPTP time less monotonic time, in nanoseconds.
333    pub fn offset(&self) -> i64 {
334        self.refresh(false);
335        let monotonic = monotonic_nanos();
336        self.line.gptp_at(monotonic) - monotonic
337    }
338
339    /// The monotonic time at which gPTP time reaches `gptp` nanoseconds.
340    pub fn monotonic_at(&self, gptp: i64) -> Duration {
341        Duration::from_nanos(self.line.monotonic_at(gptp).max(0) as u64)
342    }
343
344    /// The card's clock, in nanoseconds on CLOCK_TAI's scale, when gPTP
345    /// time reaches `gptp`: the launch time of a frame due then. None
346    /// where gptpd does not keep the card's clock near CLOCK_TAI, or a new
347    /// line waits to be confirmed.
348    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    /// A grandmaster at `base` ns when the monotonic clock read `at`,
363    /// running `rate` times as fast, in generation `generation`.
364    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    /// gPTP time runs along the mapping's line, its rate and all, and
396    /// wake times come back off it.
397    #[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        // 10 ppm fast: a second on the monotonic clock is 10 us more.
407        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    /// Three records, a tenth of a second apart, of a line from `at`,
419    /// gPTP time `base` there.
420    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    /// A line that carries the last one on counts no discontinuity, as
433    /// gptpd restarting or taking over as grandmaster gives, whatever its
434    /// generation; one that does not counts once three records in a row
435    /// confirm it, as does the first.
436    #[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        // A restart's new generation, its time 400 ns on.
443        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        // A grandmaster of its own time, 20 us off, taken at its third
449        // record.
450        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    /// One record off and then back, as gptpd can give while a
467    /// comparison settles, moves nothing; nor do two records that
468    /// disagree with each other.
469    #[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    /// A line nothing read for hours has drifted with the monotonic
508    /// clock's rate, and the next record goes in at once, as the first
509    /// does; a record a tenth of a second after its last read still waits
510    /// for confirmation.
511    #[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        // Read again a tenth of a second on, 20 us off: a candidate.
520        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        // Five hours unread, gPTP time where a rate 0.04 ppm off puts it,
531        // 720 us from the line: taken at its first record.
532        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        // The next read, on time and on the new line, carries it on.
539        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    /// While gptpd says no grandmaster is present the line holds, and the
552    /// first grandmaster after counts only if it does not carry it on.
553    #[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    /// When gptpd says nothing, or that no grandmaster is present, the
576    /// last line carries on, unlocked, so time does not jump back to the
577    /// monotonic clock's.
578    #[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        // This system as grandmaster is locked too.
594        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    /// Threads reading while another stores a line each take one line
603    /// whole, never half of two.
604    #[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                        // Each line stored has base = 2 × at and rate = at.
616                        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    /// The card's line comes only with records saying gptpd keeps the
632    /// card's clock near CLOCK_TAI, and goes while a new gPTP line waits
633    /// to be confirmed.
634    #[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        // The card's clock 1.7e18 ns at gPTP time 1000 s, its rate 1 ppm
641        // over gPTP's.
642        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        // A line 20 us off waits for confirmation: no launch times meanwhile.
658        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        // No grandmaster, or a record without tai: none.
674        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}