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
10use crate::error::{ConfigField, Error};
11use broadcast_common::clock33::PCR_HZ;
12
13/// Microseconds (arrival clock, intervals, targets).
14pub type Micros = u64;
15/// 27 MHz ticks (media positions: PCR domain for the estimator, PTS x 300 for
16/// the playback/lead domain).
17pub type Ticks27 = u64;
18
19/// Microseconds per second.
20pub const US_PER_S: u64 = 1_000_000;
21/// 27 MHz ticks per microsecond.
22pub(crate) const TICKS_PER_US: u64 = PCR_HZ / US_PER_S;
23/// Q15 fixed point: shift, and the value of 1.0.
24pub(crate) const Q15_SHIFT: u32 = 15;
25pub(crate) const Q15_ONE: u64 = 1 << Q15_SHIFT;
26/// Q8 fixed point shift.
27pub(crate) const Q8_SHIFT: u32 = 8;
28/// Quantiles are expressed in permille.
29pub(crate) const PERMILLE: u64 = 1000;
30/// Smallest legal `max_samples`.
31pub(crate) const MIN_SAMPLES_CAP: u16 = 8;
32/// Over-max re-arm fraction: re-armed when `need <= max * NUM / DEN`.
33pub(crate) const REARM_NUM: u64 = 3;
34pub(crate) const REARM_DEN: u64 = 4;
35
36/// `value * q >> shift`, widened so it cannot overflow, saturating at `u64::MAX`.
37pub(crate) fn mul_q(value: u64, q: u16, shift: u32) -> u64 {
38    let wide = (u128::from(value) * u128::from(q)) >> shift;
39    u64::try_from(wide).unwrap_or(u64::MAX)
40}
41
42/// Delivery-jitter estimator configuration.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
45#[non_exhaustive]
46pub struct JitterConfig {
47    /// Sliding-minimum window for the relative transit `D` (2 s).
48    pub min_window_us: Micros,
49    /// Per-interval maximum resampling period (500 ms).
50    pub interval_us: Micros,
51    /// Interval maxima above this feed ONLY the max-hold, never the histogram (500 ms).
52    pub outlier_us: Micros,
53    /// Histogram bucket width (10 ms).
54    pub bucket_us: u32,
55    /// Histogram bucket count (400 => 0..4 s).
56    pub buckets: u16,
57    /// Per-interval forgetting factor, Q15 (0.98 => 32113).
58    pub forget_q15: u16,
59    /// Baseline quantile in permille (990).
60    pub quantile_permille: u16,
61    /// Stall-memory hold before decay (60 s).
62    pub hold_us: Micros,
63    /// Linear decay duration after the hold (60 s).
64    pub decay_us: Micros,
65    /// Hard cap of the sliding-minimum deque (4096).
66    pub max_samples: u16,
67    /// PCR jump threshold (1 s): media ahead of arrival by more, or backwards by more.
68    pub discontinuity_us: Micros,
69}
70
71impl JitterConfig {
72    /// The documented defaults.
73    pub const DEFAULT: Self = Self {
74        min_window_us: 2_000_000,
75        interval_us: 500_000,
76        outlier_us: 500_000,
77        bucket_us: 10_000,
78        buckets: 400,
79        forget_q15: 32113,
80        quantile_permille: 990,
81        hold_us: 60_000_000,
82        decay_us: 60_000_000,
83        max_samples: 4096,
84        discontinuity_us: 1_000_000,
85    };
86
87    /// Check every field.
88    ///
89    /// # Errors
90    /// [`Error::ZeroLengthWindow`] or [`Error::InvalidConfig`] naming the field.
91    pub fn validate(&self) -> Result<(), Error> {
92        if self.min_window_us == 0 {
93            return Err(Error::ZeroLengthWindow);
94        }
95        if self.interval_us == 0 {
96            return Err(Error::InvalidConfig(ConfigField::Interval));
97        }
98        if self.min_window_us < self.interval_us.saturating_mul(2) {
99            return Err(Error::InvalidConfig(ConfigField::MinWindow));
100        }
101        if self.bucket_us == 0 || self.buckets == 0 {
102            return Err(Error::InvalidConfig(ConfigField::Bucket));
103        }
104        if u64::from(self.forget_q15) >= Q15_ONE {
105            return Err(Error::InvalidConfig(ConfigField::Forget));
106        }
107        if self.quantile_permille == 0 || u64::from(self.quantile_permille) > PERMILLE {
108            return Err(Error::InvalidConfig(ConfigField::Quantile));
109        }
110        if self.outlier_us == 0 {
111            return Err(Error::InvalidConfig(ConfigField::Outlier));
112        }
113        if self.decay_us == 0 {
114            return Err(Error::InvalidConfig(ConfigField::Decay));
115        }
116        if self.max_samples < MIN_SAMPLES_CAP {
117            return Err(Error::InvalidConfig(ConfigField::Capacity));
118        }
119        if self.discontinuity_us == 0 {
120            return Err(Error::InvalidConfig(ConfigField::Discontinuity));
121        }
122        Ok(())
123    }
124
125    /// Histogram range in microseconds (`buckets * bucket_us`).
126    #[must_use]
127    pub fn range_us(&self) -> u64 {
128        u64::from(self.buckets) * u64::from(self.bucket_us)
129    }
130}
131
132impl Default for JitterConfig {
133    fn default() -> Self {
134        Self::DEFAULT
135    }
136}
137
138/// Target-buffer policy configuration.
139///
140/// `max_us` is a **hard cap**: neither the target, nor the start threshold,
141/// nor the resume threshold ever exceeds it, so a caller can size its
142/// compressed queue from it.
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
145#[non_exhaustive]
146pub struct PolicyConfig {
147    /// Floor of every target (300 ms).
148    pub min_us: Micros,
149    /// Cold-start target without stall memory (1.8 s, owner-approved 2026-10-17).
150    pub initial_us: Micros,
151    /// Hard ceiling of every target and threshold (3 s).
152    pub max_us: Micros,
153    /// Baseline multiplier, Q8 (2.0 => 512).
154    pub k1_q8: u16,
155    /// Additive margin (100 ms).
156    pub margin_us: Micros,
157    /// Stall-peak multiplier, Q8 (1.2 => 307).
158    pub k2_q8: u16,
159    /// Resume target after a stall = `max(target, x * stall_peak)`, Q8 (1.25 => 320).
160    pub after_rebuffer_q8: u16,
161    /// Target decrease slew (100 ms per second).
162    pub max_step_down_us_per_s: u32,
163    /// Voluntary re-prime below this lead while playing (0 = disabled).
164    pub reprime_floor_us: Micros,
165    /// How long below the floor before re-priming (2 s).
166    pub reprime_hold_us: Micros,
167}
168
169impl PolicyConfig {
170    /// The documented defaults.
171    pub const DEFAULT: Self = Self {
172        min_us: 300_000,
173        initial_us: 1_800_000,
174        max_us: 3_000_000,
175        k1_q8: 512,
176        margin_us: 100_000,
177        k2_q8: 307,
178        after_rebuffer_q8: 320,
179        max_step_down_us_per_s: 100_000,
180        reprime_floor_us: 0,
181        reprime_hold_us: 2_000_000,
182    };
183
184    /// Check every field.
185    ///
186    /// # Errors
187    /// [`Error::InvalidConfig`] naming the field.
188    pub fn validate(&self) -> Result<(), Error> {
189        if self.min_us == 0 || self.min_us > self.initial_us || self.initial_us > self.max_us {
190            return Err(Error::InvalidConfig(ConfigField::Order));
191        }
192        if self.k1_q8 == 0 || self.k2_q8 == 0 || self.after_rebuffer_q8 == 0 {
193            return Err(Error::InvalidConfig(ConfigField::Multiplier));
194        }
195        if self.max_step_down_us_per_s == 0 {
196            return Err(Error::InvalidConfig(ConfigField::Slew));
197        }
198        Ok(())
199    }
200}
201
202impl Default for PolicyConfig {
203    fn default() -> Self {
204        Self::DEFAULT
205    }
206}
207
208/// Whole-controller configuration.
209#[derive(Clone, Copy, Debug, PartialEq, Eq)]
210#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
211#[non_exhaustive]
212pub struct ControllerConfig {
213    /// Estimator configuration.
214    pub jitter: JitterConfig,
215    /// Policy configuration.
216    pub policy: PolicyConfig,
217    /// Starved when lead is at or below this while the clock advances (20 ms).
218    pub starve_threshold_us: Micros,
219    /// No chunk for this long => pause reason `NoData` (200 ms).
220    pub nodata_after_us: Micros,
221    /// A track with no delivery for this long is excluded from the effective
222    /// media end (`on_track_media` / `register_track`), so a dead track cannot
223    /// starve playback forever (3 s).
224    #[cfg_attr(feature = "serde", serde(default = "default_track_silence_timeout_us"))]
225    pub track_silence_timeout_us: Micros,
226    /// Per-track delivery-granularity floor on/off (default on): the target is
227    /// kept at least `max over tracks of (largest media-end step) + policy.margin_us`,
228    /// so a track that delivers in coarse bursts (MP2 audio in ~0.3 s bursts)
229    /// cannot starve between bursts. See `DESIGN.md` section 0.7.
230    #[cfg_attr(feature = "serde", serde(default = "default_track_granularity"))]
231    pub track_granularity: bool,
232    /// How long a track's largest delivery step is held before it decays (30 s).
233    #[cfg_attr(feature = "serde", serde(default = "default_granularity_hold_us"))]
234    pub granularity_hold_us: Micros,
235    /// Linear decay of a held delivery step to zero after the hold (30 s).
236    #[cfg_attr(feature = "serde", serde(default = "default_granularity_decay_us"))]
237    pub granularity_decay_us: Micros,
238}
239
240/// Default of [`ControllerConfig::track_silence_timeout_us`].
241pub const DEFAULT_TRACK_SILENCE_TIMEOUT_US: Micros = 3_000_000;
242/// Default of [`ControllerConfig::track_granularity`].
243pub const DEFAULT_TRACK_GRANULARITY: bool = true;
244/// Default of [`ControllerConfig::granularity_hold_us`].
245pub const DEFAULT_GRANULARITY_HOLD_US: Micros = 30_000_000;
246/// Default of [`ControllerConfig::granularity_decay_us`].
247pub const DEFAULT_GRANULARITY_DECAY_US: Micros = 30_000_000;
248
249#[cfg(feature = "serde")]
250fn default_track_silence_timeout_us() -> Micros {
251    DEFAULT_TRACK_SILENCE_TIMEOUT_US
252}
253#[cfg(feature = "serde")]
254fn default_track_granularity() -> bool {
255    DEFAULT_TRACK_GRANULARITY
256}
257#[cfg(feature = "serde")]
258fn default_granularity_hold_us() -> Micros {
259    DEFAULT_GRANULARITY_HOLD_US
260}
261#[cfg(feature = "serde")]
262fn default_granularity_decay_us() -> Micros {
263    DEFAULT_GRANULARITY_DECAY_US
264}
265
266impl ControllerConfig {
267    /// The documented defaults.
268    pub const DEFAULT: Self = Self {
269        jitter: JitterConfig::DEFAULT,
270        policy: PolicyConfig::DEFAULT,
271        starve_threshold_us: 20_000,
272        nodata_after_us: 200_000,
273        track_silence_timeout_us: DEFAULT_TRACK_SILENCE_TIMEOUT_US,
274        track_granularity: DEFAULT_TRACK_GRANULARITY,
275        granularity_hold_us: DEFAULT_GRANULARITY_HOLD_US,
276        granularity_decay_us: DEFAULT_GRANULARITY_DECAY_US,
277    };
278
279    /// Build and validate a configuration (the per-track silence timeout takes
280    /// its default; change it with
281    /// [`with_track_silence_timeout_us`](Self::with_track_silence_timeout_us)).
282    ///
283    /// # Errors
284    /// See [`ControllerConfig::validate`].
285    pub fn new(
286        jitter: JitterConfig,
287        policy: PolicyConfig,
288        starve_threshold_us: Micros,
289        nodata_after_us: Micros,
290    ) -> Result<Self, Error> {
291        let c = Self {
292            jitter,
293            policy,
294            starve_threshold_us,
295            nodata_after_us,
296            track_silence_timeout_us: DEFAULT_TRACK_SILENCE_TIMEOUT_US,
297            track_granularity: DEFAULT_TRACK_GRANULARITY,
298            granularity_hold_us: DEFAULT_GRANULARITY_HOLD_US,
299            granularity_decay_us: DEFAULT_GRANULARITY_DECAY_US,
300        };
301        c.validate()?;
302        Ok(c)
303    }
304
305    /// Replace the per-track silence timeout and re-validate.
306    ///
307    /// # Errors
308    /// [`Error::InvalidConfig`] ([`ConfigField::TrackSilence`]) when zero.
309    pub fn with_track_silence_timeout_us(mut self, timeout_us: Micros) -> Result<Self, Error> {
310        self.track_silence_timeout_us = timeout_us;
311        self.validate()?;
312        Ok(self)
313    }
314
315    /// Switch the per-track delivery-granularity floor on or off.
316    #[must_use]
317    pub fn with_track_granularity(mut self, enabled: bool) -> Self {
318        self.track_granularity = enabled;
319        self
320    }
321
322    /// Replace the granularity memory (hold, then linear decay) and re-validate.
323    ///
324    /// # Errors
325    /// [`Error::InvalidConfig`] ([`ConfigField::GranularityDecay`]) when `decay_us` is zero.
326    pub fn with_granularity_memory_us(
327        mut self,
328        hold_us: Micros,
329        decay_us: Micros,
330    ) -> Result<Self, Error> {
331        self.granularity_hold_us = hold_us;
332        self.granularity_decay_us = decay_us;
333        self.validate()?;
334        Ok(self)
335    }
336
337    /// Validate the parts and the cross-field rules (`max_us` within the
338    /// histogram range, `starve_threshold_us < min_us`, non-zero silence timeout).
339    ///
340    /// # Errors
341    /// [`Error::InvalidConfig`] / [`Error::ZeroLengthWindow`].
342    pub fn validate(&self) -> Result<(), Error> {
343        self.jitter.validate()?;
344        self.policy.validate()?;
345        if self.policy.max_us > self.jitter.range_us() {
346            return Err(Error::InvalidConfig(ConfigField::Bucket));
347        }
348        if self.starve_threshold_us >= self.policy.min_us || self.nodata_after_us == 0 {
349            return Err(Error::InvalidConfig(ConfigField::Threshold));
350        }
351        if self.track_silence_timeout_us == 0 {
352            return Err(Error::InvalidConfig(ConfigField::TrackSilence));
353        }
354        if self.granularity_decay_us == 0 {
355            return Err(Error::InvalidConfig(ConfigField::GranularityDecay));
356        }
357        Ok(())
358    }
359}
360
361impl Default for ControllerConfig {
362    fn default() -> Self {
363        Self::DEFAULT
364    }
365}