Skip to main content

buffering_runtime/
policy.rs

1//! Target-buffer policy: need, clamp, asymmetric slew-limited follower and
2//! the resume threshold. All integer (Q8 multipliers, microseconds), with
3//! spans crossing the edge as [`Duration`].
4//!
5//! `max` is a hard cap: [`Policy::target`], [`Policy::start`] and
6//! [`Policy::resume`] are never above it, whatever the estimator reports.
7
8use core::time::Duration;
9
10use crate::config::{PolicyConfig, Q8_SHIFT, US_PER_S, mul_q};
11use crate::time::{instant_micros, micros_as_duration, window_micros};
12
13/// Target follower and threshold calculator.
14#[derive(Clone, Copy, Debug)]
15pub struct Policy {
16    cfg: PolicyConfig,
17    min_us: u64,
18    initial_us: u64,
19    max_us: u64,
20    margin_us: u64,
21    step_down_us_per_s: u64,
22    reprime_floor_us: u64,
23    reprime_hold_us: u64,
24    target: u64,
25    last_t: Option<u64>,
26}
27
28impl Policy {
29    /// New policy at the floor target.
30    #[must_use]
31    pub fn new(cfg: PolicyConfig) -> Self {
32        Self {
33            cfg,
34            min_us: window_micros(cfg.min),
35            initial_us: window_micros(cfg.initial),
36            max_us: window_micros(cfg.max),
37            margin_us: window_micros(cfg.margin),
38            step_down_us_per_s: window_micros(cfg.max_step_down_per_s),
39            reprime_floor_us: window_micros(cfg.reprime_floor),
40            reprime_hold_us: window_micros(cfg.reprime_hold),
41            target: window_micros(cfg.min),
42            last_t: None,
43        }
44    }
45
46    /// Unclamped need:
47    /// `max(k1 * baseline + margin, k2 * stall_peak, granularity + margin)`
48    /// (the last term only when `granularity_us > 0`).
49    #[must_use]
50    pub fn need_with_granularity_us(
51        &self,
52        baseline_us: u64,
53        stall_peak_us: u64,
54        granularity_us: u64,
55    ) -> u64 {
56        let a = mul_q(baseline_us, self.cfg.k1_q8, Q8_SHIFT).saturating_add(self.margin_us);
57        let b = mul_q(stall_peak_us, self.cfg.k2_q8, Q8_SHIFT);
58        let c = self.granularity_need_us(granularity_us);
59        a.max(b).max(c)
60    }
61
62    /// Unclamped need without a granularity floor:
63    /// `max(k1 * baseline + margin, k2 * stall_peak)`.
64    #[must_use]
65    pub fn need_us(&self, baseline_us: u64, stall_peak_us: u64) -> u64 {
66        self.need_with_granularity_us(baseline_us, stall_peak_us, 0)
67    }
68
69    /// The delivery-granularity floor: `granularity + margin`, 0 when there is
70    /// no granularity to cover.
71    #[must_use]
72    pub fn granularity_need_us(&self, granularity_us: u64) -> u64 {
73        if granularity_us == 0 {
74            0
75        } else {
76            granularity_us.saturating_add(self.margin_us)
77        }
78    }
79
80    /// Clamp into `[min, max]`.
81    #[must_use]
82    pub fn clamp(&self, v: u64) -> u64 {
83        v.clamp(self.min_us, self.max_us)
84    }
85
86    /// Asymmetric follower: rise instantly, fall at most
87    /// `max_step_down_per_s`. Returns the new target.
88    pub fn follow(&mut self, need_us: u64, now_us: u64) -> u64 {
89        let raw = self.clamp(need_us);
90        let dt = self.last_t.map_or(0, |t| now_us.saturating_sub(t));
91        let fall = u128::from(self.step_down_us_per_s) * u128::from(dt) / u128::from(US_PER_S);
92        let fall = u64::try_from(fall).unwrap_or(u64::MAX);
93        self.target = raw.max(self.target.saturating_sub(fall));
94        self.last_t = Some(now_us);
95        self.target
96    }
97
98    /// Raise (never lower) the target to at least `clamp(need)`.
99    pub fn raise(&mut self, need_us: u64) {
100        self.target = self.target.max(self.clamp(need_us));
101    }
102
103    /// Back to the floor.
104    pub fn reset(&mut self) {
105        self.target = self.min_us;
106        self.last_t = None;
107    }
108
109    /// Current target.
110    #[must_use]
111    pub fn target(&self) -> Duration {
112        micros_as_duration(self.target)
113    }
114
115    /// Current target in whole microseconds.
116    pub(crate) fn target_us(&self) -> u64 {
117        self.target
118    }
119
120    /// First-fill threshold: `max(initial, target)`.
121    #[must_use]
122    pub fn start(&self) -> Duration {
123        micros_as_duration(self.clamp(self.initial_us.max(self.target)))
124    }
125
126    /// Post-stall resume threshold: `clamp(max(target, after_rebuffer * stall_peak))`.
127    #[must_use]
128    pub fn resume(&self, stall_peak: Duration) -> Duration {
129        micros_as_duration(self.clamp(self.target.max(mul_q(
130            instant_micros(stall_peak),
131            self.cfg.after_rebuffer_q8,
132            Q8_SHIFT,
133        ))))
134    }
135
136    /// The configured cap.
137    #[must_use]
138    pub fn max(&self) -> Duration {
139        self.cfg.max
140    }
141
142    /// The configured voluntary re-prime floor (`0` when disabled).
143    #[must_use]
144    pub fn reprime_floor(&self) -> Duration {
145        micros_as_duration(self.reprime_floor_us)
146    }
147
148    /// The configured re-prime hold.
149    #[must_use]
150    pub fn reprime_hold(&self) -> Duration {
151        micros_as_duration(self.reprime_hold_us)
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::Policy;
158    use crate::config::PolicyConfig;
159    use core::time::Duration;
160
161    #[test]
162    fn the_policy_reports_the_configured_bounds_and_target() {
163        let cfg = PolicyConfig {
164            reprime_floor: Duration::from_millis(250),
165            reprime_hold: Duration::from_millis(1_500),
166            ..PolicyConfig::DEFAULT
167        };
168        let mut p = Policy::new(cfg);
169        assert_eq!(p.max(), Duration::from_secs(3));
170        assert_eq!(p.reprime_floor(), Duration::from_millis(250));
171        assert_eq!(p.reprime_hold(), Duration::from_millis(1_500));
172        assert_eq!(p.target(), Duration::from_millis(300));
173        assert_eq!(p.target_us(), 300_000);
174        p.raise(900_000);
175        assert_eq!(p.target_us(), 900_000);
176        assert_eq!(p.target(), Duration::from_millis(900));
177    }
178}