Skip to main content

buffering_runtime/
config.rs

1//! Configuration, units and the single source of defaults.
2//!
3//! Every default is a named constant in a `DEFAULT` block and `Default` is
4//! implemented from it, so a C wrapper asks the crate (`br_config_default`)
5//! instead of duplicating numbers. Each default carries its evidence tag in
6//! `docs/buffering-runtime/DESIGN.md` section 4 (`[tuned]` / `[sourced]` /
7//! `[guess]`); all of them are **implementation-defined** (no standard
8//! specifies a de-jitter policy).
9//!
10//! Every span is a [`Duration`] (see [`crate::time`]); the controller keeps
11//! them in whole microseconds internally.
12
13use core::time::Duration;
14
15use broadcast_common::clock33::PCR_HZ;
16
17use crate::error::{ConfigField, Error};
18use crate::time::{micros_as_duration, window_micros};
19
20/// Microseconds per second.
21pub const US_PER_S: u64 = 1_000_000;
22/// 27 MHz ticks per microsecond.
23pub(crate) const TICKS_PER_US: u64 = PCR_HZ / US_PER_S;
24/// Q15 fixed point: shift, and the value of 1.0.
25pub(crate) const Q15_SHIFT: u32 = 15;
26pub(crate) const Q15_ONE: u64 = 1 << Q15_SHIFT;
27/// Q8 fixed point shift.
28pub(crate) const Q8_SHIFT: u32 = 8;
29/// Quantiles are expressed in permille.
30pub(crate) const PERMILLE: u64 = 1000;
31/// Smallest legal `max_samples`.
32pub(crate) const MIN_SAMPLES_CAP: u16 = 8;
33/// Over-max re-arm fraction: re-armed when `need <= max * NUM / DEN`.
34pub(crate) const REARM_NUM: u64 = 3;
35pub(crate) const REARM_DEN: u64 = 4;
36
37/// `value * q >> shift`, widened so it cannot overflow, saturating at `u64::MAX`.
38pub(crate) fn mul_q(value: u64, q: u16, shift: u32) -> u64 {
39    let wide = (u128::from(value) * u128::from(q)) >> shift;
40    u64::try_from(wide).unwrap_or(u64::MAX)
41}
42
43/// Delivery-jitter estimator configuration.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
46#[non_exhaustive]
47pub struct JitterConfig {
48    /// Sliding-minimum window for the relative transit `D` (2 s).
49    pub min_window: Duration,
50    /// Per-interval maximum resampling period (500 ms).
51    pub interval: Duration,
52    /// Interval maxima above this feed ONLY the max-hold, never the histogram (500 ms).
53    pub outlier: Duration,
54    /// Histogram bucket width (10 ms).
55    pub bucket: Duration,
56    /// Histogram bucket count (400 => 0..4 s).
57    pub buckets: u16,
58    /// Per-interval forgetting factor, Q15 (0.98 => 32113).
59    pub forget_q15: u16,
60    /// Baseline quantile in permille (990).
61    pub quantile_permille: u16,
62    /// Stall-memory hold before decay (60 s).
63    pub hold: Duration,
64    /// Linear decay duration after the hold (60 s).
65    pub decay: Duration,
66    /// Hard cap of the sliding-minimum deque (4096).
67    pub max_samples: u16,
68    /// PCR jump threshold (1 s): media ahead of arrival by more, or backwards by more.
69    pub discontinuity: Duration,
70}
71
72impl JitterConfig {
73    /// The documented defaults.
74    pub const DEFAULT: Self = Self {
75        min_window: Duration::from_secs(2),
76        interval: Duration::from_millis(500),
77        outlier: Duration::from_millis(500),
78        bucket: Duration::from_millis(10),
79        buckets: 400,
80        forget_q15: 32113,
81        quantile_permille: 990,
82        hold: Duration::from_secs(60),
83        decay: Duration::from_secs(60),
84        max_samples: 4096,
85        discontinuity: Duration::from_secs(1),
86    };
87
88    /// Check every field.
89    ///
90    /// # Errors
91    /// [`Error::ZeroLengthWindow`] or [`Error::InvalidConfig`] naming the field.
92    pub fn validate(&self) -> Result<(), Error> {
93        if self.min_window.is_zero() {
94            return Err(Error::ZeroLengthWindow);
95        }
96        if self.interval.is_zero() {
97            return Err(Error::InvalidConfig(ConfigField::Interval));
98        }
99        if window_micros(self.min_window) < window_micros(self.interval).saturating_mul(2) {
100            return Err(Error::InvalidConfig(ConfigField::MinWindow));
101        }
102        if self.bucket.is_zero() || self.buckets == 0 {
103            return Err(Error::InvalidConfig(ConfigField::Bucket));
104        }
105        if u64::from(self.forget_q15) >= Q15_ONE {
106            return Err(Error::InvalidConfig(ConfigField::Forget));
107        }
108        if self.quantile_permille == 0 || u64::from(self.quantile_permille) > PERMILLE {
109            return Err(Error::InvalidConfig(ConfigField::Quantile));
110        }
111        if self.outlier.is_zero() {
112            return Err(Error::InvalidConfig(ConfigField::Outlier));
113        }
114        if self.decay.is_zero() {
115            return Err(Error::InvalidConfig(ConfigField::Decay));
116        }
117        if self.max_samples < MIN_SAMPLES_CAP {
118            return Err(Error::InvalidConfig(ConfigField::Capacity));
119        }
120        if self.discontinuity.is_zero() {
121            return Err(Error::InvalidConfig(ConfigField::Discontinuity));
122        }
123        Ok(())
124    }
125
126    /// Histogram range (`buckets * bucket`).
127    #[must_use]
128    pub fn range(&self) -> Duration {
129        micros_as_duration(self.range_us())
130    }
131
132    pub(crate) fn range_us(&self) -> u64 {
133        u64::from(self.buckets) * window_micros(self.bucket)
134    }
135}
136
137impl Default for JitterConfig {
138    fn default() -> Self {
139        Self::DEFAULT
140    }
141}
142
143/// Target-buffer policy configuration.
144///
145/// `max` is a **hard cap**: neither the target, nor the start threshold, nor
146/// the resume threshold ever exceeds it, so a caller can size its compressed
147/// queue from it.
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
149#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
150#[non_exhaustive]
151pub struct PolicyConfig {
152    /// Floor of every target (300 ms).
153    pub min: Duration,
154    /// Cold-start target without stall memory (1.8 s, owner-approved 2026-10-17).
155    pub initial: Duration,
156    /// Hard ceiling of every target and threshold (3 s).
157    pub max: Duration,
158    /// Baseline multiplier, Q8 (2.0 => 512).
159    pub k1_q8: u16,
160    /// Additive margin (100 ms).
161    pub margin: Duration,
162    /// Stall-peak multiplier, Q8 (1.2 => 307).
163    pub k2_q8: u16,
164    /// Resume target after a stall = `max(target, x * stall_peak)`, Q8 (1.25 => 320).
165    pub after_rebuffer_q8: u16,
166    /// Target decrease rate per second of clock (100 ms per second).
167    pub max_step_down_per_s: Duration,
168    /// Voluntary re-prime below this lead while playing (0 = disabled).
169    pub reprime_floor: Duration,
170    /// How long below the floor before re-priming (2 s).
171    pub reprime_hold: Duration,
172}
173
174impl PolicyConfig {
175    /// The documented defaults.
176    pub const DEFAULT: Self = Self {
177        min: Duration::from_millis(300),
178        initial: Duration::from_millis(1_800),
179        max: Duration::from_secs(3),
180        k1_q8: 512,
181        margin: Duration::from_millis(100),
182        k2_q8: 307,
183        after_rebuffer_q8: 320,
184        max_step_down_per_s: Duration::from_millis(100),
185        reprime_floor: Duration::ZERO,
186        reprime_hold: Duration::from_secs(2),
187    };
188
189    /// Check every field.
190    ///
191    /// # Errors
192    /// [`Error::InvalidConfig`] naming the field.
193    pub fn validate(&self) -> Result<(), Error> {
194        if self.min.is_zero() || self.min > self.initial || self.initial > self.max {
195            return Err(Error::InvalidConfig(ConfigField::Order));
196        }
197        if self.k1_q8 == 0 || self.k2_q8 == 0 || self.after_rebuffer_q8 == 0 {
198            return Err(Error::InvalidConfig(ConfigField::Multiplier));
199        }
200        if self.max_step_down_per_s.is_zero() {
201            return Err(Error::InvalidConfig(ConfigField::Slew));
202        }
203        Ok(())
204    }
205}
206
207impl Default for PolicyConfig {
208    fn default() -> Self {
209        Self::DEFAULT
210    }
211}
212
213/// Whole-controller configuration.
214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
215#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
216#[non_exhaustive]
217pub struct ControllerConfig {
218    /// Estimator configuration.
219    pub jitter: JitterConfig,
220    /// Policy configuration.
221    pub policy: PolicyConfig,
222    /// Starved when lead is at or below this while the clock advances (20 ms).
223    pub starve_threshold: Duration,
224    /// No chunk for this long => pause reason `NoData` (200 ms).
225    pub nodata_after: Duration,
226    /// A track with no delivery for this long is excluded from the effective
227    /// media end (`on_track_media` / `register_track`), so a dead track cannot
228    /// starve playback forever (3 s).
229    #[cfg_attr(feature = "serde", serde(default = "default_track_silence_timeout"))]
230    pub track_silence_timeout: Duration,
231    /// Per-track delivery-granularity floor on/off (default on): the target is
232    /// kept at least `max over tracks of (largest media-end step) + policy.margin`,
233    /// so a track that delivers in coarse bursts (MP2 audio in ~0.3 s bursts)
234    /// cannot starve between bursts. See `DESIGN.md` section 0.7.
235    #[cfg_attr(feature = "serde", serde(default = "default_track_granularity"))]
236    pub track_granularity: bool,
237    /// How long a track's largest delivery step is held before it decays (30 s).
238    #[cfg_attr(feature = "serde", serde(default = "default_granularity_hold"))]
239    pub granularity_hold: Duration,
240    /// Linear decay of a held delivery step to zero after the hold (30 s).
241    #[cfg_attr(feature = "serde", serde(default = "default_granularity_decay"))]
242    pub granularity_decay: Duration,
243}
244
245/// Default of [`ControllerConfig::track_silence_timeout`].
246pub const DEFAULT_TRACK_SILENCE_TIMEOUT: Duration = Duration::from_secs(3);
247/// Default of [`ControllerConfig::track_granularity`].
248pub const DEFAULT_TRACK_GRANULARITY: bool = true;
249/// Default of [`ControllerConfig::granularity_hold`].
250pub const DEFAULT_GRANULARITY_HOLD: Duration = Duration::from_secs(30);
251/// Default of [`ControllerConfig::granularity_decay`].
252pub const DEFAULT_GRANULARITY_DECAY: Duration = Duration::from_secs(30);
253
254#[cfg(feature = "serde")]
255fn default_track_silence_timeout() -> Duration {
256    DEFAULT_TRACK_SILENCE_TIMEOUT
257}
258#[cfg(feature = "serde")]
259fn default_track_granularity() -> bool {
260    DEFAULT_TRACK_GRANULARITY
261}
262#[cfg(feature = "serde")]
263fn default_granularity_hold() -> Duration {
264    DEFAULT_GRANULARITY_HOLD
265}
266#[cfg(feature = "serde")]
267fn default_granularity_decay() -> Duration {
268    DEFAULT_GRANULARITY_DECAY
269}
270
271impl ControllerConfig {
272    /// The documented defaults.
273    pub const DEFAULT: Self = Self {
274        jitter: JitterConfig::DEFAULT,
275        policy: PolicyConfig::DEFAULT,
276        starve_threshold: Duration::from_millis(20),
277        nodata_after: Duration::from_millis(200),
278        track_silence_timeout: DEFAULT_TRACK_SILENCE_TIMEOUT,
279        track_granularity: DEFAULT_TRACK_GRANULARITY,
280        granularity_hold: DEFAULT_GRANULARITY_HOLD,
281        granularity_decay: DEFAULT_GRANULARITY_DECAY,
282    };
283
284    /// Build and validate a configuration (the per-track silence timeout takes
285    /// its default; change it with
286    /// [`with_track_silence_timeout`](Self::with_track_silence_timeout)).
287    ///
288    /// # Errors
289    /// See [`ControllerConfig::validate`].
290    pub fn new(
291        jitter: JitterConfig,
292        policy: PolicyConfig,
293        starve_threshold: Duration,
294        nodata_after: Duration,
295    ) -> Result<Self, Error> {
296        let c = Self {
297            jitter,
298            policy,
299            starve_threshold,
300            nodata_after,
301            track_silence_timeout: DEFAULT_TRACK_SILENCE_TIMEOUT,
302            track_granularity: DEFAULT_TRACK_GRANULARITY,
303            granularity_hold: DEFAULT_GRANULARITY_HOLD,
304            granularity_decay: DEFAULT_GRANULARITY_DECAY,
305        };
306        c.validate()?;
307        Ok(c)
308    }
309
310    /// Replace the per-track silence timeout and re-validate.
311    ///
312    /// # Errors
313    /// [`Error::InvalidConfig`] ([`ConfigField::TrackSilence`]) when zero.
314    pub fn with_track_silence_timeout(mut self, timeout: Duration) -> Result<Self, Error> {
315        self.track_silence_timeout = timeout;
316        self.validate()?;
317        Ok(self)
318    }
319
320    /// Switch the per-track delivery-granularity floor on or off.
321    #[must_use]
322    pub fn with_track_granularity(mut self, enabled: bool) -> Self {
323        self.track_granularity = enabled;
324        self
325    }
326
327    /// Replace the granularity memory (hold, then linear decay) and re-validate.
328    ///
329    /// # Errors
330    /// [`Error::InvalidConfig`] ([`ConfigField::GranularityDecay`]) when `decay` is zero.
331    pub fn with_granularity_memory(
332        mut self,
333        hold: Duration,
334        decay: Duration,
335    ) -> Result<Self, Error> {
336        self.granularity_hold = hold;
337        self.granularity_decay = decay;
338        self.validate()?;
339        Ok(self)
340    }
341
342    /// Validate the parts and the cross-field rules (`max` within the
343    /// histogram range, `starve_threshold < min`, non-zero silence timeout).
344    ///
345    /// # Errors
346    /// [`Error::InvalidConfig`] / [`Error::ZeroLengthWindow`].
347    pub fn validate(&self) -> Result<(), Error> {
348        self.jitter.validate()?;
349        self.policy.validate()?;
350        if window_micros(self.policy.max) > self.jitter.range_us() {
351            return Err(Error::InvalidConfig(ConfigField::Bucket));
352        }
353        if self.starve_threshold >= self.policy.min || self.nodata_after.is_zero() {
354            return Err(Error::InvalidConfig(ConfigField::Threshold));
355        }
356        if self.track_silence_timeout.is_zero() {
357            return Err(Error::InvalidConfig(ConfigField::TrackSilence));
358        }
359        if self.granularity_decay.is_zero() {
360            return Err(Error::InvalidConfig(ConfigField::GranularityDecay));
361        }
362        Ok(())
363    }
364}
365
366impl Default for ControllerConfig {
367    fn default() -> Self {
368        Self::DEFAULT
369    }
370}
371
372#[cfg(test)]
373mod tests {
374    use super::{ControllerConfig, Error, JitterConfig, PolicyConfig};
375    use core::time::Duration;
376
377    #[test]
378    fn the_defaults_are_spans_and_validate() {
379        ControllerConfig::DEFAULT
380            .validate()
381            .expect("defaults validate");
382        assert_eq!(JitterConfig::DEFAULT.min_window, Duration::from_secs(2));
383        assert_eq!(JitterConfig::DEFAULT.range(), Duration::from_secs(4));
384        assert_eq!(PolicyConfig::DEFAULT.max, Duration::from_secs(3));
385        assert_eq!(
386            ControllerConfig::DEFAULT.nodata_after,
387            Duration::from_millis(200)
388        );
389    }
390
391    /// A zero-length window is the typed error: the span type has no "unset"
392    /// distinguished from zero, so the validation that compared against the
393    /// old zero newtype must still catch it.
394    #[test]
395    fn a_zero_length_window_is_rejected() {
396        let jitter = JitterConfig {
397            min_window: Duration::ZERO,
398            ..JitterConfig::DEFAULT
399        };
400        assert_eq!(jitter.validate(), Err(Error::ZeroLengthWindow));
401    }
402
403    /// The spans carry the same magnitudes the microsecond fields did, so a
404    /// migration that only changed the type cannot silently move a default.
405    #[test]
406    fn every_default_span_is_its_documented_size() {
407        let c = ControllerConfig::DEFAULT;
408        assert_eq!(c.starve_threshold, Duration::from_millis(20));
409        assert_eq!(c.policy.initial, Duration::from_millis(1_800));
410        assert_eq!(c.policy.margin, Duration::from_millis(100));
411        assert_eq!(c.policy.max_step_down_per_s, Duration::from_millis(100));
412        assert_eq!(c.jitter.bucket, Duration::from_millis(10));
413        assert_eq!(c.granularity_hold, Duration::from_secs(30));
414        assert_eq!(c.track_silence_timeout, Duration::from_secs(3));
415    }
416}