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