Skip to main content

buffering_runtime/
jitter.rs

1//! Delivery-jitter estimator, usable alone.
2//!
3//! Sample definition: RFC 5481 s4.2 / s7.1.2 packet delay variation. For each
4//! media-time-carrying chunk the relative transit
5//! `D = arrival - media` (the constant clock offset cancels) is pushed into a
6//! trailing-window minimum; `PDV = D - Dmin`. The RFC 3550 s6.4.1 / A.8
7//! interarrival jitter `J` is computed alongside, for reporting only.
8//! Everything else (per-interval maxima, forgetting histogram, stall
9//! max-hold) is implementation-defined; see the crate docs.
10
11use crate::config::{JitterConfig, Micros, TICKS_PER_US, Ticks27};
12use crate::error::Error;
13use crate::histogram::ForgettingHistogram;
14use crate::stall_memory::{MaxHold, StallMemorySnapshot};
15use crate::window::MinWindow;
16use broadcast_common::clock33::pcr_signed_distance;
17
18/// What happened to one fed sample.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize))]
21#[non_exhaustive]
22pub enum SampleOutcome {
23    /// Folded into the estimate.
24    Accepted,
25    /// A media-time jump beyond `discontinuity_us`: the baseline was reset
26    /// and this sample starts the new one.
27    Discontinuity,
28    /// The arrival clock went backwards: the sample is ignored.
29    NonMonotonicArrival,
30    /// The media time repeats the previous one (a duplicated PCR carries no
31    /// new media time): the sample is ignored.
32    Duplicate,
33}
34
35impl SampleOutcome {
36    /// Stable label.
37    #[must_use]
38    pub fn name(&self) -> &'static str {
39        match self {
40            Self::Accepted => "accepted",
41            Self::Discontinuity => "discontinuity",
42            Self::NonMonotonicArrival => "non-monotonic arrival",
43            Self::Duplicate => "duplicate",
44        }
45    }
46}
47broadcast_common::impl_spec_display!(SampleOutcome);
48
49/// Current estimator outputs.
50#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
51#[cfg_attr(feature = "serde", derive(serde::Serialize))]
52#[non_exhaustive]
53pub struct JitterEstimate {
54    /// Latest `D - Dmin`.
55    pub pdv_last_us: Micros,
56    /// Histogram quantile of interval maxima (ordinary-jitter upper tail).
57    pub baseline_us: Micros,
58    /// Max-hold with linear decay (stall memory).
59    pub stall_peak_us: Micros,
60    /// RFC 3550 A.8 `J`, reporting only.
61    pub rfc3550_jitter_us: Micros,
62    /// Samples accepted since construction.
63    pub samples: u64,
64}
65
66#[derive(Clone, Copy, Debug)]
67struct Origin {
68    arrival_us: u64,
69    media_us: i128,
70}
71
72/// Burst-aware PDV estimator (sliding-minimum window, per-interval maximum,
73/// forgetting histogram, stall max-hold, RFC 3550 `J`).
74#[derive(Clone, Debug)]
75pub struct DeliveryJitter {
76    cfg: JitterConfig,
77    window: MinWindow,
78    hist: ForgettingHistogram,
79    hold: MaxHold,
80    origin: Option<Origin>,
81    prev_raw: Option<u64>,
82    unrolled_ticks: i128,
83    last_arrival: Option<u64>,
84    istart: Option<u64>,
85    imax: Option<u64>,
86    recovering: bool,
87    base: u64,
88    pdv_last: u64,
89    j16: i64,
90    prev_d: Option<i64>,
91    samples: u64,
92}
93
94/// RFC 3550 A.8 integer-form scaling: the estimate is kept x16, rounded by 8.
95const J_SHIFT: u32 = 4;
96const J_ROUND: i64 = 8;
97
98fn sat_i64(v: i128) -> i64 {
99    i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX })
100}
101
102impl DeliveryJitter {
103    /// Build an estimator.
104    ///
105    /// # Errors
106    /// Any [`JitterConfig::validate`] failure.
107    pub fn new(cfg: JitterConfig) -> Result<Self, Error> {
108        cfg.validate()?;
109        Ok(Self {
110            window: MinWindow::new(cfg.min_window_us, cfg.max_samples)?,
111            hist: ForgettingHistogram::new(
112                cfg.buckets,
113                cfg.bucket_us,
114                cfg.forget_q15,
115                cfg.quantile_permille,
116            ),
117            hold: MaxHold::new(cfg.hold_us, cfg.decay_us),
118            cfg,
119            origin: None,
120            prev_raw: None,
121            unrolled_ticks: 0,
122            last_arrival: None,
123            istart: None,
124            imax: None,
125            recovering: false,
126            base: 0,
127            pdv_last: 0,
128            j16: 0,
129            prev_d: None,
130            samples: 0,
131        })
132    }
133
134    /// Feed one media-time-carrying chunk. `media_27mhz` is the raw (wrapped)
135    /// 27 MHz media time (the PCR; or the media end in PCR-less mode), unrolled
136    /// here with `clock33::pcr_signed_distance`. `_bytes` is reserved (the
137    /// estimator is time-based; the C-ABI mirror carries it).
138    pub fn on_chunk(
139        &mut self,
140        arrival_us: Micros,
141        media_27mhz: Ticks27,
142        _bytes: u32,
143    ) -> SampleOutcome {
144        if self.last_arrival.is_some_and(|l| arrival_us < l) {
145            return SampleOutcome::NonMonotonicArrival;
146        }
147        if self.prev_raw == Some(media_27mhz) {
148            return SampleOutcome::Duplicate;
149        }
150        self.hold.anchor(arrival_us);
151        let mut outcome = SampleOutcome::Accepted;
152        if let (Some(prev), Some(last)) = (self.prev_raw, self.last_arrival) {
153            let media_delta =
154                i128::from(pcr_signed_distance(prev, media_27mhz)) / i128::from(TICKS_PER_US);
155            let arrival_delta = i128::from(arrival_us - last);
156            let disc = i128::from(self.cfg.discontinuity_us);
157            if media_delta < -disc || media_delta - arrival_delta > disc {
158                self.reset_baseline();
159                outcome = SampleOutcome::Discontinuity;
160            }
161        }
162        match self.prev_raw {
163            Some(prev) => {
164                self.unrolled_ticks += i128::from(pcr_signed_distance(prev, media_27mhz));
165            }
166            None => self.unrolled_ticks = 0,
167        }
168        let media_us = self.unrolled_ticks.div_euclid(i128::from(TICKS_PER_US));
169        let origin = *self.origin.get_or_insert(Origin {
170            arrival_us,
171            media_us,
172        });
173        self.prev_raw = Some(media_27mhz);
174        self.last_arrival = Some(arrival_us);
175
176        let rel_arrival = arrival_us - origin.arrival_us;
177        let d = sat_i64(i128::from(rel_arrival) - (media_us - origin.media_us));
178        let dmin = self.window.push(rel_arrival, d);
179        let pdv = u64::try_from(i128::from(d) - i128::from(dmin)).unwrap_or(0);
180
181        if let Some(pd) = self.prev_d {
182            let diff = sat_i64((i128::from(d) - i128::from(pd)).abs());
183            // RFC 3550 A.8 integer form: `jitter += d - ((jitter + 8) >> 4)`, reported `>> 4`.
184            self.j16 = self
185                .j16
186                .saturating_add(diff - (self.j16.saturating_add(J_ROUND) >> J_SHIFT));
187        }
188        self.prev_d = Some(d);
189
190        self.hold.observe(arrival_us, pdv);
191        self.fold_interval(arrival_us, pdv);
192        self.pdv_last = pdv;
193        self.samples = self.samples.saturating_add(1);
194        outcome
195    }
196
197    fn fold_interval(&mut self, arrival_us: u64, pdv: u64) {
198        match self.istart {
199            None => self.istart = Some(arrival_us),
200            Some(start) if arrival_us >= start.saturating_add(self.cfg.interval_us) => {
201                if let Some(m) = self.imax.take() {
202                    if m > self.cfg.outlier_us {
203                        // a stall interval: max-hold only; its aftermath is not baseline either
204                        self.recovering = true;
205                    } else if self.recovering {
206                        // the interval after a stall holds the tail of a catch-up burst
207                        // (D still above the minimum while the backlog drains): skip it once
208                        self.recovering = false;
209                    } else {
210                        self.hist.add(m);
211                        self.base = self.hist.quantile_us();
212                    }
213                }
214                let whole = (arrival_us - start) / self.cfg.interval_us;
215                self.istart =
216                    Some(start.saturating_add(whole.saturating_mul(self.cfg.interval_us)));
217            }
218            Some(_) => {}
219        }
220        self.imax = Some(self.imax.map_or(pdv, |m| m.max(pdv)));
221    }
222
223    /// Current outputs (stall peak evaluated at the latest arrival).
224    #[must_use]
225    pub fn estimate(&self) -> JitterEstimate {
226        JitterEstimate {
227            pdv_last_us: self.pdv_last,
228            baseline_us: self.base,
229            stall_peak_us: self.stall_peak_at(self.last_arrival.unwrap_or(0)),
230            rfc3550_jitter_us: u64::try_from(self.j16 >> J_SHIFT).unwrap_or(0),
231            samples: self.samples,
232        }
233    }
234
235    /// Histogram baseline (ordinary-jitter upper tail).
236    #[must_use]
237    pub fn baseline_us(&self) -> Micros {
238        self.base
239    }
240
241    /// Decayed stall-memory value at `now_us`.
242    #[must_use]
243    pub fn stall_peak_at(&self, now_us: Micros) -> Micros {
244        self.hold.value(now_us)
245    }
246
247    /// A starvation with data still arriving proves the buffer was too small
248    /// by an unknown amount: remember `depth_us` (the target that failed) in
249    /// the stall memory, so a repeat ratchets the target even when the PDV is
250    /// low.
251    pub(crate) fn note_starvation(&mut self, now_us: Micros, depth_us: Micros) {
252        self.hold.observe(now_us, depth_us);
253    }
254
255    /// Anchor a restored snapshot at the clock reading `now_us`.
256    pub(crate) fn anchor(&mut self, now_us: Micros) {
257        self.hold.anchor(now_us);
258    }
259
260    /// Entries dropped by the minimum-window cap.
261    #[must_use]
262    pub fn window_overflows(&self) -> u32 {
263        self.window.overflows()
264    }
265
266    /// PCR discontinuity / new connection: drops the minimum window and the
267    /// histogram, **keeps the stall memory**.
268    pub fn reset_baseline(&mut self) {
269        self.window.clear();
270        self.hist.clear();
271        self.base = 0;
272        self.istart = None;
273        self.imax = None;
274        self.recovering = false;
275        self.origin = None;
276        self.prev_raw = None;
277        self.unrolled_ticks = 0;
278        self.prev_d = None;
279        self.j16 = 0;
280    }
281
282    /// Forget everything including the stall memory (new channel).
283    pub fn reset(&mut self) {
284        self.reset_baseline();
285        self.hold.clear();
286        self.pdv_last = 0;
287    }
288
289    /// Stall memory for session persistence, aged to the latest arrival.
290    #[must_use]
291    pub fn snapshot(&self) -> StallMemorySnapshot {
292        self.hold.snapshot(self.last_arrival.unwrap_or(0))
293    }
294
295    /// Snapshot aged to an explicit clock reading.
296    #[must_use]
297    pub(crate) fn snapshot_at(&self, now_us: Micros) -> StallMemorySnapshot {
298        self.hold.snapshot(now_us)
299    }
300
301    /// Install a stall memory (see [`StallMemorySnapshot`] for aging).
302    pub fn restore(&mut self, m: StallMemorySnapshot) {
303        self.hold.restore(m);
304    }
305}