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//!
11//! Arrival instants and spans are [`Duration`], media positions are
12//! [`Clock27`] ([`crate::time`]); the estimator carries them as whole
13//! microseconds internally.
14
15use core::time::Duration;
16
17use broadcast_common::clock33::Clock27;
18
19use crate::config::{JitterConfig, TICKS_PER_US};
20use crate::error::Error;
21use crate::histogram::ForgettingHistogram;
22use crate::stall_memory::{MaxHold, StallMemorySnapshot};
23use crate::time::{instant_micros, micros_as_duration, window_micros};
24use crate::window::MinWindow;
25use broadcast_common::clock33::pcr_signed_distance;
26
27/// What happened to one fed sample.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29#[cfg_attr(feature = "serde", derive(serde::Serialize))]
30#[non_exhaustive]
31pub enum SampleOutcome {
32    /// Folded into the estimate.
33    Accepted,
34    /// A media-time jump beyond `discontinuity`: the baseline was reset
35    /// and this sample starts the new one.
36    Discontinuity,
37    /// The arrival clock went backwards: the sample is ignored.
38    NonMonotonicArrival,
39    /// The media time repeats the previous one (a duplicated PCR carries no
40    /// new media time): the sample is ignored.
41    Duplicate,
42}
43
44impl SampleOutcome {
45    /// Stable label.
46    #[must_use]
47    pub fn name(&self) -> &'static str {
48        match self {
49            Self::Accepted => "accepted",
50            Self::Discontinuity => "discontinuity",
51            Self::NonMonotonicArrival => "non-monotonic arrival",
52            Self::Duplicate => "duplicate",
53        }
54    }
55}
56broadcast_common::impl_spec_display!(SampleOutcome);
57
58/// Current estimator outputs.
59#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
60#[cfg_attr(feature = "serde", derive(serde::Serialize))]
61#[non_exhaustive]
62pub struct JitterEstimate {
63    /// Latest `D - Dmin`.
64    pub pdv_last: Duration,
65    /// Histogram quantile of interval maxima (ordinary-jitter upper tail).
66    pub baseline: Duration,
67    /// Max-hold with linear decay (stall memory).
68    pub stall_peak: Duration,
69    /// RFC 3550 A.8 `J`, reporting only.
70    pub rfc3550_jitter: Duration,
71    /// Samples accepted since construction.
72    pub samples: u64,
73}
74
75#[derive(Clone, Copy, Debug)]
76struct Origin {
77    arrival_us: u64,
78    media_us: i128,
79}
80
81/// Burst-aware PDV estimator (sliding-minimum window, per-interval maximum,
82/// forgetting histogram, stall max-hold, RFC 3550 `J`).
83#[derive(Clone, Debug)]
84pub struct DeliveryJitter {
85    window: MinWindow,
86    hist: ForgettingHistogram,
87    hold: MaxHold,
88    interval_us: u64,
89    outlier_us: u64,
90    discontinuity_us: u64,
91    origin: Option<Origin>,
92    prev_raw: Option<u64>,
93    unrolled_ticks: i128,
94    last_arrival: Option<u64>,
95    istart: Option<u64>,
96    imax: Option<u64>,
97    recovering: bool,
98    base: u64,
99    pdv_last: u64,
100    j16: i64,
101    prev_d: Option<i64>,
102    samples: u64,
103}
104
105/// RFC 3550 A.8 integer-form scaling: the estimate is kept x16, rounded by 8.
106const J_SHIFT: u32 = 4;
107const J_ROUND: i64 = 8;
108
109fn sat_i64(v: i128) -> i64 {
110    i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX })
111}
112
113impl DeliveryJitter {
114    /// Build an estimator.
115    ///
116    /// # Errors
117    /// Any [`JitterConfig::validate`] failure.
118    pub fn new(cfg: JitterConfig) -> Result<Self, Error> {
119        cfg.validate()?;
120        let interval_us = window_micros(cfg.interval);
121        Ok(Self {
122            window: MinWindow::new(cfg.min_window, cfg.max_samples)?,
123            hist: ForgettingHistogram::new(
124                cfg.buckets,
125                cfg.bucket,
126                cfg.forget_q15,
127                cfg.quantile_permille,
128            ),
129            hold: MaxHold::new(window_micros(cfg.hold), window_micros(cfg.decay)),
130            interval_us,
131            outlier_us: window_micros(cfg.outlier),
132            discontinuity_us: window_micros(cfg.discontinuity),
133            origin: None,
134            prev_raw: None,
135            unrolled_ticks: 0,
136            last_arrival: None,
137            istart: None,
138            imax: None,
139            recovering: false,
140            base: 0,
141            pdv_last: 0,
142            j16: 0,
143            prev_d: None,
144            samples: 0,
145        })
146    }
147
148    /// Feed one media-time-carrying chunk. `media` is the raw (wrapped)
149    /// 27 MHz media time (the PCR; or the media end in PCR-less mode), unrolled
150    /// here with `clock33::pcr_signed_distance`. `_bytes` is reserved (the
151    /// estimator is time-based; the C-ABI mirror carries it).
152    pub fn on_chunk(&mut self, arrival: Duration, media: Clock27, _bytes: u32) -> SampleOutcome {
153        let arrival_us = instant_micros(arrival);
154        if self.last_arrival.is_some_and(|l| arrival_us < l) {
155            return SampleOutcome::NonMonotonicArrival;
156        }
157        if self.prev_raw == Some(media.ticks()) {
158            return SampleOutcome::Duplicate;
159        }
160        self.hold.anchor(arrival_us);
161        let mut outcome = SampleOutcome::Accepted;
162        if let (Some(prev), Some(last)) = (self.prev_raw, self.last_arrival) {
163            let media_delta =
164                i128::from(pcr_signed_distance(prev, media.ticks())) / i128::from(TICKS_PER_US);
165            let arrival_delta = i128::from(arrival_us - last);
166            let disc = i128::from(self.discontinuity_us);
167            if media_delta < -disc || media_delta - arrival_delta > disc {
168                self.reset_baseline();
169                outcome = SampleOutcome::Discontinuity;
170            }
171        }
172        match self.prev_raw {
173            Some(prev) => {
174                self.unrolled_ticks += i128::from(pcr_signed_distance(prev, media.ticks()));
175            }
176            None => self.unrolled_ticks = 0,
177        }
178        let media_us = self.unrolled_ticks.div_euclid(i128::from(TICKS_PER_US));
179        let origin = *self.origin.get_or_insert(Origin {
180            arrival_us,
181            media_us,
182        });
183        self.prev_raw = Some(media.ticks());
184        self.last_arrival = Some(arrival_us);
185
186        let rel_arrival = arrival_us - origin.arrival_us;
187        let d = sat_i64(i128::from(rel_arrival) - (media_us - origin.media_us));
188        let dmin = self.window.push(rel_arrival, d);
189        let pdv = u64::try_from(i128::from(d) - i128::from(dmin)).unwrap_or(0);
190
191        if let Some(pd) = self.prev_d {
192            let diff = sat_i64((i128::from(d) - i128::from(pd)).abs());
193            // RFC 3550 A.8 integer form: `jitter += d - ((jitter + 8) >> 4)`, reported `>> 4`.
194            self.j16 = self
195                .j16
196                .saturating_add(diff - (self.j16.saturating_add(J_ROUND) >> J_SHIFT));
197        }
198        self.prev_d = Some(d);
199
200        self.hold.observe(arrival_us, pdv);
201        self.fold_interval(arrival_us, pdv);
202        self.pdv_last = pdv;
203        self.samples = self.samples.saturating_add(1);
204        outcome
205    }
206
207    fn fold_interval(&mut self, arrival_us: u64, pdv: u64) {
208        match self.istart {
209            None => self.istart = Some(arrival_us),
210            Some(start) if arrival_us >= start.saturating_add(self.interval_us) => {
211                if let Some(m) = self.imax.take() {
212                    if m > self.outlier_us {
213                        // a stall interval: max-hold only; its aftermath is not baseline either
214                        self.recovering = true;
215                    } else if self.recovering {
216                        // the interval after a stall holds the tail of a catch-up burst
217                        // (D still above the minimum while the backlog drains): skip it once
218                        self.recovering = false;
219                    } else {
220                        self.hist.add(m);
221                        self.base = self.hist.quantile_us();
222                    }
223                }
224                let whole = (arrival_us - start) / self.interval_us;
225                self.istart = Some(start.saturating_add(whole.saturating_mul(self.interval_us)));
226            }
227            Some(_) => {}
228        }
229        self.imax = Some(self.imax.map_or(pdv, |m| m.max(pdv)));
230    }
231
232    /// Current outputs (stall peak evaluated at the latest arrival).
233    #[must_use]
234    pub fn estimate(&self) -> JitterEstimate {
235        JitterEstimate {
236            pdv_last: micros_as_duration(self.pdv_last),
237            baseline: micros_as_duration(self.base),
238            stall_peak: self.stall_peak_at(micros_as_duration(self.latest_arrival())),
239            rfc3550_jitter: micros_as_duration(u64::try_from(self.j16 >> J_SHIFT).unwrap_or(0)),
240            samples: self.samples,
241        }
242    }
243
244    /// Histogram baseline (ordinary-jitter upper tail).
245    #[must_use]
246    pub fn baseline(&self) -> Duration {
247        micros_as_duration(self.base)
248    }
249
250    /// The latest arrival instant this estimator was anchored at.
251    fn latest_arrival(&self) -> u64 {
252        self.last_arrival.unwrap_or(0)
253    }
254
255    /// Decayed stall-memory value at `now`.
256    #[must_use]
257    pub fn stall_peak_at(&self, now: Duration) -> Duration {
258        micros_as_duration(self.hold.value(instant_micros(now)))
259    }
260
261    /// A starvation with data still arriving proves the buffer was too small
262    /// by an unknown amount: remember `depth` (the target that failed) in
263    /// the stall memory, so a repeat ratchets the target even when the PDV is
264    /// low.
265    pub(crate) fn note_starvation(&mut self, now: Duration, depth: Duration) {
266        self.hold
267            .observe(instant_micros(now), instant_micros(depth));
268    }
269
270    /// Anchor a restored snapshot at the clock reading `now`.
271    pub(crate) fn anchor(&mut self, now: Duration) {
272        self.hold.anchor(instant_micros(now));
273    }
274
275    /// Entries dropped by the minimum-window cap.
276    #[must_use]
277    pub fn window_overflows(&self) -> u32 {
278        self.window.overflows()
279    }
280
281    /// PCR discontinuity / new connection: drops the minimum window and the
282    /// histogram, **keeps the stall memory**.
283    pub fn reset_baseline(&mut self) {
284        self.window.clear();
285        self.hist.clear();
286        self.base = 0;
287        self.istart = None;
288        self.imax = None;
289        self.recovering = false;
290        self.origin = None;
291        self.prev_raw = None;
292        self.unrolled_ticks = 0;
293        self.prev_d = None;
294        self.j16 = 0;
295    }
296
297    /// Forget everything including the stall memory (new channel).
298    pub fn reset(&mut self) {
299        self.reset_baseline();
300        self.hold.clear();
301        self.pdv_last = 0;
302    }
303
304    /// Stall memory for session persistence, aged to the latest arrival.
305    #[must_use]
306    pub fn snapshot(&self) -> StallMemorySnapshot {
307        self.hold.snapshot(self.latest_arrival())
308    }
309
310    /// Snapshot aged to an explicit clock reading.
311    #[must_use]
312    pub(crate) fn snapshot_at(&self, now: Duration) -> StallMemorySnapshot {
313        self.hold.snapshot(instant_micros(now))
314    }
315
316    /// Install a stall memory (see [`StallMemorySnapshot`] for aging).
317    pub fn restore(&mut self, m: StallMemorySnapshot) {
318        self.hold.restore(m);
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::{DeliveryJitter, SampleOutcome, sat_i64};
325    use crate::config::JitterConfig;
326    use crate::stall_memory::StallMemorySnapshot;
327    use crate::time::Clock27;
328    use broadcast_common::clock33::PCR_WRAP_27MHZ;
329    use core::time::Duration;
330
331    fn us(n: u64) -> Duration {
332        Duration::from_micros(n)
333    }
334
335    fn ticks(n: u64) -> Clock27 {
336        Clock27::from_27mhz(n).expect("on the clock")
337    }
338
339    fn milli(n: u64) -> Clock27 {
340        Clock27::from_27mhz(n * 27_000).expect("on the clock")
341    }
342
343    fn jitter(cfg: JitterConfig) -> DeliveryJitter {
344        DeliveryJitter::new(cfg).expect("the config validates")
345    }
346
347    #[test]
348    fn the_relative_transit_difference_is_the_pdv() {
349        let mut j = jitter(JitterConfig::DEFAULT);
350        let arrivals = [0u64, 20_000, 40_000, 65_000, 80_000];
351        let media = [0u64, 20_000, 40_000, 60_000, 80_000];
352        let pdv = [0u64, 0, 0, 5_000, 0];
353        for i in 0..arrivals.len() {
354            assert_eq!(
355                j.on_chunk(us(arrivals[i]), milli(media[i] / 1_000), 0),
356                SampleOutcome::Accepted,
357                "sample {i}"
358            );
359            assert_eq!(j.estimate().pdv_last, us(pdv[i]), "sample {i}");
360        }
361        assert_eq!(j.estimate().samples, 5);
362    }
363
364    #[test]
365    fn a_value_off_the_i64_range_saturates_on_its_own_side() {
366        assert_eq!(sat_i64(i128::from(i64::MIN) - 1), i64::MIN);
367        assert_eq!(sat_i64(i128::from(i64::MAX) + 1), i64::MAX);
368    }
369
370    #[test]
371    fn a_media_step_back_exactly_the_discontinuity_is_still_a_sample() {
372        let mut j = jitter(JitterConfig::DEFAULT);
373        assert_eq!(
374            j.on_chunk(Duration::ZERO, ticks(0), 0),
375            SampleOutcome::Accepted
376        );
377        let back =
378            Clock27::from_27mhz(PCR_WRAP_27MHZ - 27_000_000).expect("one second before the wrap");
379        assert_eq!(
380            j.on_chunk(Duration::from_secs(1), back, 0),
381            SampleOutcome::Accepted
382        );
383    }
384
385    #[test]
386    fn an_interval_maximum_exactly_at_the_outlier_still_feeds_the_baseline() {
387        let mut j = jitter(JitterConfig::DEFAULT);
388        assert_eq!(
389            j.on_chunk(Duration::ZERO, ticks(0), 0),
390            SampleOutcome::Accepted
391        );
392        assert_eq!(
393            j.on_chunk(Duration::from_millis(500), ticks(1), 0),
394            SampleOutcome::Accepted
395        );
396        assert_eq!(
397            j.on_chunk(Duration::from_millis(1_000), ticks(2), 0),
398            SampleOutcome::Accepted
399        );
400        assert_eq!(j.baseline(), us(510_000));
401    }
402
403    #[test]
404    fn exceeding_the_minimum_window_cap_drops_and_counts_entries() {
405        let mut j = jitter(JitterConfig {
406            max_samples: 8,
407            ..JitterConfig::DEFAULT
408        });
409        for i in 0..10u64 {
410            assert_eq!(
411                j.on_chunk(us(i * 10), ticks(i), 0),
412                SampleOutcome::Accepted,
413                "{i}"
414            );
415        }
416        assert_eq!(j.window_overflows(), 2);
417    }
418
419    #[test]
420    fn an_anchored_stall_memory_ages_from_the_reading_it_was_restored_at() {
421        let mut j = jitter(JitterConfig::DEFAULT);
422        j.restore(StallMemorySnapshot::new(
423            Duration::from_millis(500),
424            Duration::ZERO,
425        ));
426        j.anchor(Duration::ZERO);
427        assert_eq!(j.stall_peak_at(Duration::from_secs(90)), us(250_000));
428    }
429
430    #[test]
431    fn every_sample_outcome_has_its_stable_label() {
432        assert_eq!(SampleOutcome::Accepted.name(), "accepted");
433        assert_eq!(SampleOutcome::Discontinuity.name(), "discontinuity");
434        assert_eq!(
435            SampleOutcome::NonMonotonicArrival.name(),
436            "non-monotonic arrival"
437        );
438        assert_eq!(SampleOutcome::Duplicate.name(), "duplicate");
439    }
440}