Skip to main content

avb_stream/
recovered.rs

1//! A media clock recovered from a CRF stream: the gPTP times its
2//! timestamps give its events, fitted to a line that a talker group's
3//! samples then follow.
4//!
5//! The timestamps are the talker's numbers, not times of arrival, so the
6//! line is exact but for their nanosecond steps: its rate comes from the
7//! first and last events of the last two seconds, its phase from the
8//! last.
9
10use std::collections::VecDeque;
11use std::fmt;
12use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
13
14/// How much of the stream the rate is taken over, in nanoseconds.
15const WINDOW: i64 = 2_000_000_000;
16/// How much of the stream the first fit needs.
17const LEAST_SPAN: i64 = 250_000_000;
18/// How far from its nominal rate the clock may run, in parts per million,
19/// before its stream is taken for a broken one.
20const MOST_PPM: i128 = 1000;
21
22/// The recovered clock as a line: event `event` at gPTP time `time`, each
23/// next one `period` on.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct Fit {
26    /// Counts the times the clock started again: each start numbers its
27    /// events afresh.
28    pub generation: u64,
29    pub event: i64,
30    pub time: i64,
31    /// Nanoseconds from one event to the next, in 32.32 fixed point.
32    pub period: u64,
33    /// The clock's nominal rate, in events a second.
34    pub base_frequency: u32,
35}
36
37impl Fit {
38    /// The gPTP time of event `sub / per`, a fraction of an event as a
39    /// talker's samples at a higher rate than the clock's fall.
40    pub fn time_at(&self, sub: i128, per: u64) -> i64 {
41        let since = sub - i128::from(self.event) * i128::from(per);
42        self.time + ((since * i128::from(self.period) / i128::from(per)) >> 32) as i64
43    }
44
45    /// How far the clock runs from its nominal rate, in parts per
46    /// million: above zero when fast.
47    pub fn ppm(&self) -> f64 {
48        let nominal = 1e9 / f64::from(self.base_frequency.max(1));
49        let period = self.period as f64 / 4_294_967_296.0;
50        (nominal / period - 1.0) * 1e6
51    }
52
53    /// The first event at or after gPTP time `time`, in `1 / per` of an
54    /// event.
55    pub fn sub_at(&self, time: i64, per: u64) -> i128 {
56        let since = (i128::from(time) - i128::from(self.time)) << 32;
57        let subs = div_ceil(since * i128::from(per), i128::from(self.period));
58        i128::from(self.event) * i128::from(per) + subs
59    }
60}
61
62/// `numerator / denominator` rounded up, for a positive denominator.
63pub(crate) fn div_ceil(numerator: i128, denominator: i128) -> i128 {
64    let quotient = numerator.div_euclid(denominator);
65    if numerator.rem_euclid(denominator) == 0 {
66        quotient
67    } else {
68        quotient + 1
69    }
70}
71
72#[derive(Default)]
73struct State {
74    generation: u64,
75    /// The events seen over the window and their times, oldest first.
76    seen: VecDeque<(i64, i64)>,
77    fit: Option<Fit>,
78    /// The talker's media reset bit, which it toggles as its clock starts
79    /// again.
80    media_reset: Option<bool>,
81}
82
83impl State {
84    /// Forgets the clock, to recover it afresh.
85    fn restart(&mut self) {
86        self.generation += 1;
87        self.seen.clear();
88        self.fit = None;
89    }
90}
91
92/// A media clock recovered from a CRF stream, shared between the listener
93/// that takes the stream and the talkers that follow it. Clones share it.
94#[derive(Clone, Default)]
95pub struct RecoveredClock {
96    state: Arc<Mutex<State>>,
97}
98
99impl PartialEq for RecoveredClock {
100    fn eq(&self, other: &Self) -> bool {
101        Arc::ptr_eq(&self.state, &other.state)
102    }
103}
104
105impl fmt::Debug for RecoveredClock {
106    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
107        formatter
108            .debug_struct("RecoveredClock")
109            .field("fit", &self.fit())
110            .finish()
111    }
112}
113
114impl RecoveredClock {
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    fn lock(&self) -> MutexGuard<'_, State> {
120        self.state.lock().unwrap_or_else(PoisonError::into_inner)
121    }
122
123    /// The clock as a line, once it is recovered.
124    pub fn fit(&self) -> Option<Fit> {
125        self.lock().fit
126    }
127
128    pub fn locked(&self) -> bool {
129        self.lock().fit.is_some()
130    }
131
132    /// Takes a CRF frame's timestamps, each `interval` events of a clock
133    /// at `base_frequency` from the last, and its media reset bit.
134    pub fn take(
135        &self,
136        timestamps: impl IntoIterator<Item = u64>,
137        interval: u16,
138        base_frequency: u32,
139        media_reset: bool,
140    ) {
141        if interval == 0 || base_frequency == 0 {
142            return;
143        }
144        let mut state = self.lock();
145        if state.media_reset.replace(media_reset) == Some(!media_reset) {
146            state.restart();
147        }
148        let interval = i64::from(interval);
149        let nominal = interval as f64 * 1e9 / f64::from(base_frequency);
150        let nominal_period = (1_000_000_000i128 << 32) / i128::from(base_frequency);
151        for time in timestamps {
152            let time = time as i64;
153            let event = match state.seen.back() {
154                None => 0,
155                Some(&(last_event, last_time)) => {
156                    // Frames lost leave whole intervals out; anything else
157                    // is a clock that jumped.
158                    let gap = (time - last_time) as f64;
159                    let intervals = (gap / nominal).round();
160                    if !(1.0..=1000.0).contains(&intervals)
161                        || (gap - intervals * nominal).abs() > nominal / 100.0
162                    {
163                        state.restart();
164                        0
165                    } else {
166                        last_event + intervals as i64 * interval
167                    }
168                }
169            };
170            state.seen.push_back((event, time));
171            while state.seen.len() > 2
172                && state
173                    .seen
174                    .front()
175                    .is_some_and(|&(_, first)| time - first > WINDOW)
176            {
177                state.seen.pop_front();
178            }
179            let Some(&(first_event, first_time)) = state.seen.front() else {
180                continue;
181            };
182            if time - first_time < LEAST_SPAN || event <= first_event {
183                continue;
184            }
185            let period = (i128::from(time - first_time) << 32) / i128::from(event - first_event);
186            if (period - nominal_period).abs() * 1_000_000 > nominal_period * MOST_PPM {
187                state.restart();
188                continue;
189            }
190            state.fit = Some(Fit {
191                generation: state.generation,
192                event,
193                time,
194                period: period as u64,
195                base_frequency,
196            });
197        }
198    }
199
200    /// The stream stopped: the clock is lost until it comes again.
201    pub fn lose(&self) {
202        let mut state = self.lock();
203        state.restart();
204        state.media_reset = None;
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    /// 500 frames a second of one timestamp each 96 events at 48 kHz, of
213    /// a clock `ppm` fast, from `start`.
214    fn feed(clock: &RecoveredClock, start: u64, frames: u64, ppm: f64) {
215        let period = 2_000_000.0 / (1.0 + ppm / 1e6);
216        for frame in 0..frames {
217            let time = start + (frame as f64 * period) as u64;
218            clock.take([time], 96, 48_000, false);
219        }
220    }
221
222    /// A clock 50 ppm fast is recovered to well under a nanosecond an
223    /// event, and its line meets the timestamps.
224    #[test]
225    fn a_fast_clock_is_recovered() {
226        let clock = RecoveredClock::new();
227        feed(&clock, 1_000_000_000, 100, 0.0);
228        assert!(!clock.locked(), "a fifth of a second is too little");
229        let clock = RecoveredClock::new();
230        feed(&clock, 1_000_000_000, 1500, 50.0);
231        let fit = clock.fit().expect("locked");
232        let nominal = 1e9 / 48_000.0;
233        let period = fit.period as f64 / 4_294_967_296.0;
234        assert!((period - nominal / (1.0 + 50e-6)).abs() < 0.001, "{period}");
235        assert!((fit.ppm() - 50.0).abs() < 0.01, "{}", fit.ppm());
236        // The line through the last event gives the one before it, a
237        // frame back.
238        let before = fit.time_at(i128::from(fit.event - 96), 1);
239        let expected = 1_000_000_000 + (1498.0 * 2_000_000.0 / (1.0 + 50e-6)) as i64;
240        assert!((before - expected).abs() <= 1, "{before} {expected}");
241        // At 192 kHz, four of a talker's samples to an event.
242        assert_eq!(
243            fit.time_at(i128::from(fit.event) * 4 + 4, 4),
244            fit.time_at(i128::from(fit.event + 1), 1)
245        );
246        let sub = fit.sub_at(fit.time + 1, 4);
247        assert_eq!(sub, i128::from(fit.event) * 4 + 1);
248    }
249
250    /// An audio stream's presentation times, one a frame of 6 samples at
251    /// 48 kHz, 8000 a second, recover its talker's clock as a media
252    /// clock's timestamps do.
253    #[test]
254    fn an_audio_streams_clock_is_recovered() {
255        let clock = RecoveredClock::new();
256        let period = 125_000.0 / (1.0 + 20e-6);
257        for frame in 0..4000u64 {
258            let time = 2_000_000_000 + (frame as f64 * period) as u64;
259            clock.take([time], 6, 48_000, false);
260        }
261        let fit = clock.fit().expect("locked");
262        assert!((fit.ppm() - 20.0).abs() < 0.05, "{}", fit.ppm());
263        assert_eq!(fit.event, 3999 * 6);
264    }
265
266    /// Lost frames leave the count of events as it was; a jump, a media
267    /// reset or silence start it again.
268    #[test]
269    fn a_jump_starts_the_clock_again() {
270        let clock = RecoveredClock::new();
271        feed(&clock, 1_000_000_000, 1000, 0.0);
272        let fit = clock.fit().unwrap();
273        // Ten frames lost.
274        clock.take([1_000_000_000 + 1010 * 2_000_000], 96, 48_000, false);
275        let after = clock.fit().unwrap();
276        assert_eq!(after.generation, fit.generation);
277        assert_eq!(after.event, fit.event + 11 * 96);
278        // Half a frame off.
279        let jumped = 1_000_000_000 + 1011 * 2_000_000 + 1_000_000;
280        clock.take([jumped], 96, 48_000, false);
281        assert!(clock.fit().is_none());
282        feed(&clock, jumped + 2_000_000, 500, 0.0);
283        assert_eq!(clock.fit().unwrap().generation, fit.generation + 1);
284        clock.take([6_000_000_000], 96, 48_000, true);
285        assert!(clock.fit().is_none(), "the media reset bit toggled");
286        clock.lose();
287        assert!(!clock.locked());
288    }
289}