buffering-runtime 0.5.0

Sans-IO live-TS playout buffer controller: measures delivery jitter (RFC 5481 PDV), keeps a stall memory, and decides when a player should start, pause and resume and how deep its buffer must be. Integer-only, no_std + alloc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Delivery-jitter estimator, usable alone.
//!
//! Sample definition: RFC 5481 s4.2 / s7.1.2 packet delay variation. For each
//! media-time-carrying chunk the relative transit
//! `D = arrival - media` (the constant clock offset cancels) is pushed into a
//! trailing-window minimum; `PDV = D - Dmin`. The RFC 3550 s6.4.1 / A.8
//! interarrival jitter `J` is computed alongside, for reporting only.
//! Everything else (per-interval maxima, forgetting histogram, stall
//! max-hold) is implementation-defined; see the crate docs.
//!
//! Arrival instants and spans are [`Duration`], media positions are
//! [`Clock27`] ([`crate::time`]); the estimator carries them as whole
//! microseconds internally.

use core::time::Duration;

use broadcast_common::clock33::Clock27;

use crate::config::{JitterConfig, TICKS_PER_US};
use crate::error::Error;
use crate::histogram::ForgettingHistogram;
use crate::stall_memory::{MaxHold, StallMemorySnapshot};
use crate::time::{instant_micros, micros_as_duration, window_micros};
use crate::window::MinWindow;
use broadcast_common::clock33::pcr_signed_distance;

/// What happened to one fed sample.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum SampleOutcome {
    /// Folded into the estimate.
    Accepted,
    /// A media-time jump beyond `discontinuity`: the baseline was reset
    /// and this sample starts the new one.
    Discontinuity,
    /// The arrival clock went backwards: the sample is ignored.
    NonMonotonicArrival,
    /// The media time repeats the previous one (a duplicated PCR carries no
    /// new media time): the sample is ignored.
    Duplicate,
}

impl SampleOutcome {
    /// Stable label.
    #[must_use]
    pub fn name(&self) -> &'static str {
        match self {
            Self::Accepted => "accepted",
            Self::Discontinuity => "discontinuity",
            Self::NonMonotonicArrival => "non-monotonic arrival",
            Self::Duplicate => "duplicate",
        }
    }
}
broadcast_common::impl_spec_display!(SampleOutcome);

/// Current estimator outputs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct JitterEstimate {
    /// Latest `D - Dmin`.
    pub pdv_last: Duration,
    /// Histogram quantile of interval maxima (ordinary-jitter upper tail).
    pub baseline: Duration,
    /// Max-hold with linear decay (stall memory).
    pub stall_peak: Duration,
    /// RFC 3550 A.8 `J`, reporting only.
    pub rfc3550_jitter: Duration,
    /// Samples accepted since construction.
    pub samples: u64,
}

#[derive(Clone, Copy, Debug)]
struct Origin {
    arrival_us: u64,
    media_us: i128,
}

/// Burst-aware PDV estimator (sliding-minimum window, per-interval maximum,
/// forgetting histogram, stall max-hold, RFC 3550 `J`).
#[derive(Clone, Debug)]
pub struct DeliveryJitter {
    window: MinWindow,
    hist: ForgettingHistogram,
    hold: MaxHold,
    interval_us: u64,
    outlier_us: u64,
    discontinuity_us: u64,
    origin: Option<Origin>,
    prev_raw: Option<u64>,
    unrolled_ticks: i128,
    last_arrival: Option<u64>,
    istart: Option<u64>,
    imax: Option<u64>,
    recovering: bool,
    base: u64,
    pdv_last: u64,
    j16: i64,
    prev_d: Option<i64>,
    samples: u64,
}

/// RFC 3550 A.8 integer-form scaling: the estimate is kept x16, rounded by 8.
const J_SHIFT: u32 = 4;
const J_ROUND: i64 = 8;

fn sat_i64(v: i128) -> i64 {
    i64::try_from(v).unwrap_or(if v < 0 { i64::MIN } else { i64::MAX })
}

impl DeliveryJitter {
    /// Build an estimator.
    ///
    /// # Errors
    /// Any [`JitterConfig::validate`] failure.
    pub fn new(cfg: JitterConfig) -> Result<Self, Error> {
        cfg.validate()?;
        let interval_us = window_micros(cfg.interval);
        Ok(Self {
            window: MinWindow::new(cfg.min_window, cfg.max_samples)?,
            hist: ForgettingHistogram::new(
                cfg.buckets,
                cfg.bucket,
                cfg.forget_q15,
                cfg.quantile_permille,
            ),
            hold: MaxHold::new(window_micros(cfg.hold), window_micros(cfg.decay)),
            interval_us,
            outlier_us: window_micros(cfg.outlier),
            discontinuity_us: window_micros(cfg.discontinuity),
            origin: None,
            prev_raw: None,
            unrolled_ticks: 0,
            last_arrival: None,
            istart: None,
            imax: None,
            recovering: false,
            base: 0,
            pdv_last: 0,
            j16: 0,
            prev_d: None,
            samples: 0,
        })
    }

    /// Feed one media-time-carrying chunk. `media` is the raw (wrapped)
    /// 27 MHz media time (the PCR; or the media end in PCR-less mode), unrolled
    /// here with `clock33::pcr_signed_distance`. `_bytes` is reserved (the
    /// estimator is time-based; the C-ABI mirror carries it).
    pub fn on_chunk(&mut self, arrival: Duration, media: Clock27, _bytes: u32) -> SampleOutcome {
        let arrival_us = instant_micros(arrival);
        if self.last_arrival.is_some_and(|l| arrival_us < l) {
            return SampleOutcome::NonMonotonicArrival;
        }
        if self.prev_raw == Some(media.ticks()) {
            return SampleOutcome::Duplicate;
        }
        self.hold.anchor(arrival_us);
        let mut outcome = SampleOutcome::Accepted;
        if let (Some(prev), Some(last)) = (self.prev_raw, self.last_arrival) {
            let media_delta =
                i128::from(pcr_signed_distance(prev, media.ticks())) / i128::from(TICKS_PER_US);
            let arrival_delta = i128::from(arrival_us - last);
            let disc = i128::from(self.discontinuity_us);
            if media_delta < -disc || media_delta - arrival_delta > disc {
                self.reset_baseline();
                outcome = SampleOutcome::Discontinuity;
            }
        }
        match self.prev_raw {
            Some(prev) => {
                self.unrolled_ticks += i128::from(pcr_signed_distance(prev, media.ticks()));
            }
            None => self.unrolled_ticks = 0,
        }
        let media_us = self.unrolled_ticks.div_euclid(i128::from(TICKS_PER_US));
        let origin = *self.origin.get_or_insert(Origin {
            arrival_us,
            media_us,
        });
        self.prev_raw = Some(media.ticks());
        self.last_arrival = Some(arrival_us);

        let rel_arrival = arrival_us - origin.arrival_us;
        let d = sat_i64(i128::from(rel_arrival) - (media_us - origin.media_us));
        let dmin = self.window.push(rel_arrival, d);
        let pdv = u64::try_from(i128::from(d) - i128::from(dmin)).unwrap_or(0);

        if let Some(pd) = self.prev_d {
            let diff = sat_i64((i128::from(d) - i128::from(pd)).abs());
            // RFC 3550 A.8 integer form: `jitter += d - ((jitter + 8) >> 4)`, reported `>> 4`.
            self.j16 = self
                .j16
                .saturating_add(diff - (self.j16.saturating_add(J_ROUND) >> J_SHIFT));
        }
        self.prev_d = Some(d);

        self.hold.observe(arrival_us, pdv);
        self.fold_interval(arrival_us, pdv);
        self.pdv_last = pdv;
        self.samples = self.samples.saturating_add(1);
        outcome
    }

    fn fold_interval(&mut self, arrival_us: u64, pdv: u64) {
        match self.istart {
            None => self.istart = Some(arrival_us),
            Some(start) if arrival_us >= start.saturating_add(self.interval_us) => {
                if let Some(m) = self.imax.take() {
                    if m > self.outlier_us {
                        // a stall interval: max-hold only; its aftermath is not baseline either
                        self.recovering = true;
                    } else if self.recovering {
                        // the interval after a stall holds the tail of a catch-up burst
                        // (D still above the minimum while the backlog drains): skip it once
                        self.recovering = false;
                    } else {
                        self.hist.add(m);
                        self.base = self.hist.quantile_us();
                    }
                }
                let whole = (arrival_us - start) / self.interval_us;
                self.istart = Some(start.saturating_add(whole.saturating_mul(self.interval_us)));
            }
            Some(_) => {}
        }
        self.imax = Some(self.imax.map_or(pdv, |m| m.max(pdv)));
    }

    /// Current outputs (stall peak evaluated at the latest arrival).
    #[must_use]
    pub fn estimate(&self) -> JitterEstimate {
        JitterEstimate {
            pdv_last: micros_as_duration(self.pdv_last),
            baseline: micros_as_duration(self.base),
            stall_peak: self.stall_peak_at(micros_as_duration(self.latest_arrival())),
            rfc3550_jitter: micros_as_duration(u64::try_from(self.j16 >> J_SHIFT).unwrap_or(0)),
            samples: self.samples,
        }
    }

    /// Histogram baseline (ordinary-jitter upper tail).
    #[must_use]
    pub fn baseline(&self) -> Duration {
        micros_as_duration(self.base)
    }

    /// The latest arrival instant this estimator was anchored at.
    fn latest_arrival(&self) -> u64 {
        self.last_arrival.unwrap_or(0)
    }

    /// Decayed stall-memory value at `now`.
    #[must_use]
    pub fn stall_peak_at(&self, now: Duration) -> Duration {
        micros_as_duration(self.hold.value(instant_micros(now)))
    }

    /// A starvation with data still arriving proves the buffer was too small
    /// by an unknown amount: remember `depth` (the target that failed) in
    /// the stall memory, so a repeat ratchets the target even when the PDV is
    /// low.
    pub(crate) fn note_starvation(&mut self, now: Duration, depth: Duration) {
        self.hold
            .observe(instant_micros(now), instant_micros(depth));
    }

    /// Anchor a restored snapshot at the clock reading `now`.
    pub(crate) fn anchor(&mut self, now: Duration) {
        self.hold.anchor(instant_micros(now));
    }

    /// Entries dropped by the minimum-window cap.
    #[must_use]
    pub fn window_overflows(&self) -> u32 {
        self.window.overflows()
    }

    /// PCR discontinuity / new connection: drops the minimum window and the
    /// histogram, **keeps the stall memory**.
    pub fn reset_baseline(&mut self) {
        self.window.clear();
        self.hist.clear();
        self.base = 0;
        self.istart = None;
        self.imax = None;
        self.recovering = false;
        self.origin = None;
        self.prev_raw = None;
        self.unrolled_ticks = 0;
        self.prev_d = None;
        self.j16 = 0;
    }

    /// Forget everything including the stall memory (new channel).
    pub fn reset(&mut self) {
        self.reset_baseline();
        self.hold.clear();
        self.pdv_last = 0;
    }

    /// Stall memory for session persistence, aged to the latest arrival.
    #[must_use]
    pub fn snapshot(&self) -> StallMemorySnapshot {
        self.hold.snapshot(self.latest_arrival())
    }

    /// Snapshot aged to an explicit clock reading.
    #[must_use]
    pub(crate) fn snapshot_at(&self, now: Duration) -> StallMemorySnapshot {
        self.hold.snapshot(instant_micros(now))
    }

    /// Install a stall memory (see [`StallMemorySnapshot`] for aging).
    pub fn restore(&mut self, m: StallMemorySnapshot) {
        self.hold.restore(m);
    }
}

#[cfg(test)]
mod tests {
    use super::{DeliveryJitter, SampleOutcome, sat_i64};
    use crate::config::JitterConfig;
    use crate::stall_memory::StallMemorySnapshot;
    use crate::time::Clock27;
    use broadcast_common::clock33::PCR_WRAP_27MHZ;
    use core::time::Duration;

    fn us(n: u64) -> Duration {
        Duration::from_micros(n)
    }

    fn ticks(n: u64) -> Clock27 {
        Clock27::from_27mhz(n).expect("on the clock")
    }

    fn milli(n: u64) -> Clock27 {
        Clock27::from_27mhz(n * 27_000).expect("on the clock")
    }

    fn jitter(cfg: JitterConfig) -> DeliveryJitter {
        DeliveryJitter::new(cfg).expect("the config validates")
    }

    #[test]
    fn the_relative_transit_difference_is_the_pdv() {
        let mut j = jitter(JitterConfig::DEFAULT);
        let arrivals = [0u64, 20_000, 40_000, 65_000, 80_000];
        let media = [0u64, 20_000, 40_000, 60_000, 80_000];
        let pdv = [0u64, 0, 0, 5_000, 0];
        for i in 0..arrivals.len() {
            assert_eq!(
                j.on_chunk(us(arrivals[i]), milli(media[i] / 1_000), 0),
                SampleOutcome::Accepted,
                "sample {i}"
            );
            assert_eq!(j.estimate().pdv_last, us(pdv[i]), "sample {i}");
        }
        assert_eq!(j.estimate().samples, 5);
    }

    #[test]
    fn a_value_off_the_i64_range_saturates_on_its_own_side() {
        assert_eq!(sat_i64(i128::from(i64::MIN) - 1), i64::MIN);
        assert_eq!(sat_i64(i128::from(i64::MAX) + 1), i64::MAX);
    }

    #[test]
    fn a_media_step_back_exactly_the_discontinuity_is_still_a_sample() {
        let mut j = jitter(JitterConfig::DEFAULT);
        assert_eq!(
            j.on_chunk(Duration::ZERO, ticks(0), 0),
            SampleOutcome::Accepted
        );
        let back =
            Clock27::from_27mhz(PCR_WRAP_27MHZ - 27_000_000).expect("one second before the wrap");
        assert_eq!(
            j.on_chunk(Duration::from_secs(1), back, 0),
            SampleOutcome::Accepted
        );
    }

    #[test]
    fn an_interval_maximum_exactly_at_the_outlier_still_feeds_the_baseline() {
        let mut j = jitter(JitterConfig::DEFAULT);
        assert_eq!(
            j.on_chunk(Duration::ZERO, ticks(0), 0),
            SampleOutcome::Accepted
        );
        assert_eq!(
            j.on_chunk(Duration::from_millis(500), ticks(1), 0),
            SampleOutcome::Accepted
        );
        assert_eq!(
            j.on_chunk(Duration::from_millis(1_000), ticks(2), 0),
            SampleOutcome::Accepted
        );
        assert_eq!(j.baseline(), us(510_000));
    }

    #[test]
    fn exceeding_the_minimum_window_cap_drops_and_counts_entries() {
        let mut j = jitter(JitterConfig {
            max_samples: 8,
            ..JitterConfig::DEFAULT
        });
        for i in 0..10u64 {
            assert_eq!(
                j.on_chunk(us(i * 10), ticks(i), 0),
                SampleOutcome::Accepted,
                "{i}"
            );
        }
        assert_eq!(j.window_overflows(), 2);
    }

    #[test]
    fn an_anchored_stall_memory_ages_from_the_reading_it_was_restored_at() {
        let mut j = jitter(JitterConfig::DEFAULT);
        j.restore(StallMemorySnapshot::new(
            Duration::from_millis(500),
            Duration::ZERO,
        ));
        j.anchor(Duration::ZERO);
        assert_eq!(j.stall_peak_at(Duration::from_secs(90)), us(250_000));
    }

    #[test]
    fn every_sample_outcome_has_its_stable_label() {
        assert_eq!(SampleOutcome::Accepted.name(), "accepted");
        assert_eq!(SampleOutcome::Discontinuity.name(), "discontinuity");
        assert_eq!(
            SampleOutcome::NonMonotonicArrival.name(),
            "non-monotonic arrival"
        );
        assert_eq!(SampleOutcome::Duplicate.name(), "duplicate");
    }
}