use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering, fence};
use std::sync::{Mutex, PoisonError};
use std::time::Duration;
use avb_net::clock::monotonic_now;
use gptp::time::{Mapping, State};
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const REFRESH: Duration = Duration::from_millis(100);
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const CARRIED: i64 = 10_000;
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const CONFIRMATIONS: u8 = 3;
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
const STALE: Duration = Duration::from_secs(1);
#[derive(Debug, Clone, Copy)]
struct Candidate {
at: i64,
base: i64,
rate: f64,
seen: u8,
}
impl Candidate {
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn gptp_at(&self, monotonic: i64) -> i64 {
self.base
.saturating_add((monotonic.saturating_sub(self.at) as f64 * self.rate) as i64)
}
}
struct Line {
sequence: AtomicU64,
at: AtomicI64,
base: AtomicI64,
rate: AtomicU64,
}
impl Line {
fn new() -> Self {
Line {
sequence: AtomicU64::new(0),
at: AtomicI64::new(0),
base: AtomicI64::new(0),
rate: AtomicU64::new(1.0f64.to_bits()),
}
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn store(&self, at: i64, base: i64, rate: f64) {
let sequence = self.sequence.load(Ordering::Relaxed);
self.sequence
.store(sequence.wrapping_add(1), Ordering::Relaxed);
fence(Ordering::Release);
self.at.store(at, Ordering::Relaxed);
self.base.store(base, Ordering::Relaxed);
self.rate.store(rate.to_bits(), Ordering::Relaxed);
self.sequence
.store(sequence.wrapping_add(2), Ordering::Release);
}
fn load(&self) -> (i64, i64, f64) {
loop {
let before = self.sequence.load(Ordering::Acquire);
let at = self.at.load(Ordering::Relaxed);
let base = self.base.load(Ordering::Relaxed);
let rate = self.rate.load(Ordering::Relaxed);
fence(Ordering::Acquire);
if before.is_multiple_of(2) && self.sequence.load(Ordering::Relaxed) == before {
return (at, base, f64::from_bits(rate));
}
std::hint::spin_loop();
}
}
fn gptp_at(&self, monotonic: i64) -> i64 {
let (at, base, rate) = self.load();
base.saturating_add((monotonic.saturating_sub(at) as f64 * rate) as i64)
}
fn monotonic_at(&self, gptp: i64) -> i64 {
let (at, base, rate) = self.load();
at.saturating_add((gptp.saturating_sub(base) as f64 / rate) as i64)
}
}
fn monotonic_nanos() -> i64 {
monotonic_now().as_nanos() as i64
}
pub struct MediaClock {
#[cfg(target_os = "linux")]
source: Option<Mutex<gptp::time::Reader>>,
line: Line,
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
held: AtomicBool,
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
candidate: Mutex<Option<Candidate>>,
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
measured: AtomicI64,
locked: AtomicBool,
generation: AtomicU32,
last_step: AtomicI64,
card: Line,
launching: AtomicBool,
}
impl MediaClock {
pub fn gptpd(interface: &str) -> Self {
#[cfg(target_os = "linux")]
{
let clock = MediaClock {
source: gptp::time::Reader::open(interface).ok().map(Mutex::new),
..MediaClock::monotonic()
};
clock.refresh(true);
clock
}
#[cfg(not(target_os = "linux"))]
{
let _ = interface;
MediaClock::monotonic()
}
}
pub fn monotonic() -> Self {
MediaClock {
#[cfg(target_os = "linux")]
source: None,
line: Line::new(),
held: AtomicBool::new(false),
candidate: Mutex::new(None),
measured: AtomicI64::new(i64::MIN),
locked: AtomicBool::new(false),
generation: AtomicU32::new(0),
last_step: AtomicI64::new(0),
card: Line::new(),
launching: AtomicBool::new(false),
}
}
#[cfg_attr(not(target_os = "linux"), allow(unused_variables))]
fn refresh(&self, now: bool) {
#[cfg(target_os = "linux")]
{
let monotonic = monotonic_nanos();
let measured = self.measured.load(Ordering::Relaxed);
if !now && monotonic.saturating_sub(measured) < REFRESH.as_nanos() as i64 {
return;
}
let Some(source) = &self.source else {
return;
};
let Ok(mut reader) = source.try_lock() else {
return;
};
let last = self.measured.swap(monotonic, Ordering::Relaxed);
let mapping = reader.read(monotonic).ok().flatten();
self.take(mapping, monotonic.saturating_sub(last));
}
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn take(&self, mapping: Option<Mapping>, since: i64) {
if since > STALE.as_nanos() as i64 {
self.held.store(false, Ordering::Relaxed);
}
self.apply(mapping);
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn apply(&self, mapping: Option<Mapping>) {
let mut candidate = self
.candidate
.lock()
.unwrap_or_else(PoisonError::into_inner);
let Some(mapping) = mapping.filter(|mapping| mapping.state != State::None) else {
*candidate = None;
self.locked.store(false, Ordering::Relaxed);
self.launching.store(false, Ordering::Relaxed);
return;
};
let base = mapping
.at_monotonic
.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
let held = self.held.load(Ordering::Relaxed);
let step = base - self.line.gptp_at(mapping.monotonic);
let carried = held && step.abs() <= CARRIED;
if held && !carried {
let seen = match *candidate {
Some(waiting) if (base - waiting.gptp_at(mapping.monotonic)).abs() <= CARRIED => {
waiting.seen + 1
}
_ => 1,
};
if seen < CONFIRMATIONS {
*candidate = Some(Candidate {
at: mapping.monotonic,
base,
rate: mapping.monotonic_rate,
seen,
});
self.locked.store(true, Ordering::Relaxed);
self.launching.store(false, Ordering::Relaxed);
return;
}
}
*candidate = None;
self.line
.store(mapping.monotonic, base, mapping.monotonic_rate);
if mapping.tai.is_some() {
let clamp = |time: i128| time.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
self.card.store(
clamp(mapping.local),
clamp(mapping.at_local),
mapping.local_rate,
);
}
self.launching
.store(mapping.tai.is_some(), Ordering::Relaxed);
if !carried {
self.last_step.store(step, Ordering::Relaxed);
self.generation.fetch_add(1, Ordering::Relaxed);
}
self.held.store(true, Ordering::Relaxed);
self.locked.store(true, Ordering::Relaxed);
}
pub fn locked(&self) -> bool {
self.refresh(false);
self.locked.load(Ordering::Relaxed)
}
pub fn generation(&self) -> u32 {
self.refresh(false);
self.generation.load(Ordering::Relaxed)
}
pub fn last_step(&self) -> i64 {
self.last_step.load(Ordering::Relaxed)
}
pub fn now(&self) -> i64 {
self.refresh(false);
self.line.gptp_at(monotonic_nanos())
}
pub fn offset(&self) -> i64 {
self.refresh(false);
let monotonic = monotonic_nanos();
self.line.gptp_at(monotonic) - monotonic
}
pub fn monotonic_at(&self, gptp: i64) -> Duration {
Duration::from_nanos(self.line.monotonic_at(gptp).max(0) as u64)
}
pub fn card_at(&self, gptp: i64) -> Option<u64> {
self.refresh(false);
if !self.launching.load(Ordering::Relaxed) {
return None;
}
Some(self.card.monotonic_at(gptp).max(0) as u64)
}
}
#[cfg(test)]
mod tests {
use super::*;
use gptp::ClockIdentity;
fn mapping(generation: u32, at: i64, base: i128, rate: f64) -> Mapping {
Mapping {
generation,
state: State::Following,
grandmaster: ClockIdentity(0x0001_f2ff_feff_3b14),
updated: at,
monotonic: at,
at_monotonic: base,
monotonic_rate: rate,
local: 0,
at_local: base,
local_rate: rate,
asymmetry_included: false,
residual: Some(12),
tai: None,
}
}
const SECOND: i64 = 1_000_000_000;
#[test]
fn without_gptpd_the_monotonic_clock_is_the_time() {
let clock = MediaClock::monotonic();
assert!(!clock.locked());
let before = monotonic_nanos();
let now = clock.now();
assert!(now >= before && now - before < SECOND);
assert_eq!(clock.monotonic_at(now).as_nanos() as i64, now);
assert_eq!(clock.generation(), 0);
}
#[test]
fn time_follows_the_mapping() {
let clock = MediaClock::monotonic();
let at = monotonic_nanos();
let base = 1_793_400_000 * i128::from(SECOND);
clock.apply(Some(mapping(3, at, base, 1.000_010)));
assert!(clock.locked());
assert_eq!(clock.generation(), 1);
assert_eq!(clock.line.gptp_at(at), base as i64);
assert_eq!(
clock.line.gptp_at(at + SECOND),
base as i64 + SECOND + 10_000
);
let gptp = base as i64 + 2 * SECOND;
let wake = clock.line.monotonic_at(gptp);
assert!((clock.line.gptp_at(wake) - gptp).abs() <= 1);
let offset = clock.offset();
assert!((offset - (base as i64 - at)).abs() < SECOND / 1000);
}
fn confirmed(clock: &MediaClock, generation: u32, at: i64, base: i128) {
for record in 0..3 {
let later = at + record * SECOND / 10;
clock.apply(Some(mapping(
generation,
later,
base + i128::from(record * SECOND / 10),
1.0,
)));
}
}
#[test]
fn only_a_line_that_does_not_carry_on_counts() {
let clock = MediaClock::monotonic();
clock.apply(Some(mapping(5, 0, 1_000 * i128::from(SECOND), 1.0)));
assert_eq!(clock.generation(), 1);
clock.apply(Some(mapping(5, SECOND, 1_001 * i128::from(SECOND), 1.0)));
clock.apply(Some(Mapping {
state: State::Grandmaster,
..mapping(6, 2 * SECOND, 1_002 * i128::from(SECOND) + 400, 1.0)
}));
assert_eq!(clock.generation(), 1);
clock.apply(Some(mapping(
6,
3 * SECOND,
1_003 * i128::from(SECOND) + 20_400,
1.0,
)));
assert_eq!(clock.generation(), 1);
assert_eq!(clock.line.gptp_at(3 * SECOND), 1_003 * SECOND + 400);
confirmed(&clock, 6, 3 * SECOND, 1_003 * i128::from(SECOND) + 20_400);
assert_eq!(clock.generation(), 2);
assert_eq!(clock.last_step(), 20_000);
confirmed(&clock, 7, 4 * SECOND, 5_000 * i128::from(SECOND));
assert_eq!(clock.generation(), 3);
assert_eq!(clock.line.gptp_at(5 * SECOND), 5_001 * SECOND);
}
#[test]
fn a_record_off_and_back_is_no_discontinuity() {
let clock = MediaClock::monotonic();
clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
clock.apply(Some(mapping(
1,
SECOND,
1_001 * i128::from(SECOND) + 50_000,
1.0,
)));
clock.apply(Some(mapping(
1,
SECOND + SECOND / 10,
1_001 * i128::from(SECOND + SECOND / 10),
1.0,
)));
clock.apply(Some(mapping(
1,
2 * SECOND,
1_002 * i128::from(SECOND) + 90_000,
1.0,
)));
clock.apply(Some(mapping(
1,
2 * SECOND + SECOND / 10,
1_002 * i128::from(SECOND + SECOND / 10) - 70_000,
1.0,
)));
clock.apply(Some(mapping(
1,
2 * SECOND + SECOND / 5,
1_002 * i128::from(SECOND + SECOND / 5) + 30_000,
1.0,
)));
assert_eq!(clock.generation(), 1);
assert_eq!(clock.line.gptp_at(3 * SECOND), 1_003 * SECOND);
}
#[test]
fn a_line_unread_for_long_gives_way_at_once() {
let clock = MediaClock::monotonic();
clock.take(
Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)),
i64::MAX,
);
assert_eq!(clock.generation(), 1);
clock.take(
Some(mapping(
1,
SECOND / 10,
1_000 * i128::from(SECOND) + i128::from(SECOND / 10) + 20_000,
1.0,
)),
SECOND / 10,
);
assert_eq!(clock.generation(), 1);
let later = 5 * 3600 * SECOND;
let base = 1_000 * i128::from(SECOND) + i128::from(later) + 720_000;
clock.take(Some(mapping(1, later, base, 1.0)), later - SECOND / 10);
assert_eq!(clock.generation(), 2);
assert_eq!(clock.line.gptp_at(later), base as i64);
assert_eq!(clock.last_step(), 720_000);
clock.take(
Some(mapping(
1,
later + SECOND / 10,
base + i128::from(SECOND / 10),
1.0,
)),
SECOND / 10,
);
assert_eq!(clock.generation(), 2);
}
#[test]
fn a_pause_without_a_grandmaster_is_no_discontinuity() {
let clock = MediaClock::monotonic();
clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
let none = Mapping {
state: State::None,
..mapping(2, SECOND, 0, 1.0)
};
clock.apply(Some(none));
clock.apply(None);
clock.apply(Some(mapping(
2,
2 * SECOND,
1_002 * i128::from(SECOND),
1.0,
)));
assert_eq!(clock.generation(), 1);
clock.apply(Some(none));
confirmed(&clock, 3, 3 * SECOND, 9_000 * i128::from(SECOND));
assert_eq!(clock.generation(), 2);
}
#[test]
fn without_a_grandmaster_the_last_line_carries_on() {
let clock = MediaClock::monotonic();
clock.apply(Some(mapping(1, 0, 1_000 * i128::from(SECOND), 1.0)));
clock.apply(None);
assert!(!clock.locked.load(Ordering::Relaxed));
assert_eq!(clock.line.gptp_at(SECOND), 1_001 * SECOND);
let none = Mapping {
state: State::None,
..mapping(2, SECOND, 9 * i128::from(SECOND), 1.0)
};
clock.apply(Some(none));
assert!(!clock.locked.load(Ordering::Relaxed));
assert_eq!(clock.line.gptp_at(2 * SECOND), 1_002 * SECOND);
assert_eq!(clock.generation.load(Ordering::Relaxed), 1);
let ours = Mapping {
state: State::Grandmaster,
..mapping(3, 3 * SECOND, 2_000 * i128::from(SECOND), 1.0)
};
clock.apply(Some(ours));
assert!(clock.locked.load(Ordering::Relaxed));
}
#[test]
fn a_line_is_read_whole() {
let line = std::sync::Arc::new(Line::new());
let stop = std::sync::Arc::new(AtomicBool::new(false));
let readers: Vec<_> = (0..3)
.map(|_| {
let line = line.clone();
let stop = stop.clone();
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
let (at, base, rate) = line.load();
assert_eq!(base, 2 * at);
assert!(at == 0 || rate == at as f64);
}
})
})
.collect();
for at in 1..200_000i64 {
line.store(at, 2 * at, at as f64);
}
stop.store(true, Ordering::Relaxed);
for reader in readers {
reader.join().unwrap();
}
}
#[test]
fn launch_times_only_where_the_card_follows_tai() {
let clock = MediaClock::monotonic();
let base = 1_000 * i128::from(SECOND);
clock.apply(Some(mapping(1, 0, base, 1.0)));
assert_eq!(clock.card_at(1_000 * SECOND), None);
let card = 1_700_000_000 * i128::from(SECOND);
let following = |at: i64, gptp: i128| Mapping {
local: card + i128::from(at),
at_local: gptp,
local_rate: 1.0 / (1.0 + 1e-6),
tai: Some(-3),
..mapping(1, at, gptp, 1.0)
};
clock.apply(Some(following(SECOND, base + i128::from(SECOND))));
let launch = clock.card_at(1_002 * SECOND).unwrap();
let expected = card + i128::from(SECOND) + 1_000_001_000;
assert!(
(i128::from(launch) - expected).abs() <= 1,
"{launch} {expected}"
);
clock.apply(Some(following(
2 * SECOND,
base + 2 * i128::from(SECOND) + 20_000,
)));
assert_eq!(clock.card_at(1_002 * SECOND), None);
clock.apply(Some(following(
3 * SECOND,
base + 3 * i128::from(SECOND) + 20_000,
)));
clock.apply(Some(following(
4 * SECOND,
base + 4 * i128::from(SECOND) + 20_000,
)));
assert_eq!(clock.generation(), 2);
assert!(clock.card_at(1_005 * SECOND).is_some());
clock.apply(None);
assert_eq!(clock.card_at(1_005 * SECOND), None);
clock.apply(Some(mapping(
2,
5 * SECOND,
base + 5 * i128::from(SECOND) + 20_000,
1.0,
)));
assert_eq!(clock.card_at(1_006 * SECOND), None);
}
}