Skip to main content

buffering_runtime/
histogram.rs

1//! NetEq-style forgetting histogram of per-interval maxima, Q15 weights.
2
3use core::time::Duration;
4
5use crate::config::{PERMILLE, Q15_ONE, Q15_SHIFT};
6use crate::time::window_micros;
7use alloc::vec;
8use alloc::vec::Vec;
9
10/// Histogram of interval maxima with exponential forgetting.
11///
12/// Per [`add`](Self::add): every weight is multiplied by `f` (Q15, truncating
13/// `>> 15`), then the value's bucket gains `1 - f`. `f` ramps as
14/// `min(forget, k/(k+1))` over the first intervals so the first few behave as a
15/// plain average (NetEq's start-weight idea).
16#[derive(Clone, Debug)]
17pub struct ForgettingHistogram {
18    w: Vec<u32>,
19    bucket_us: u64,
20    forget_q15: u64,
21    quantile_permille: u64,
22    intervals: u64,
23}
24
25impl ForgettingHistogram {
26    /// New histogram. `buckets` and `bucket` must be non-zero (validated
27    /// by the configs; a zero width is clamped to one microsecond here so this
28    /// never divides by zero).
29    #[must_use]
30    pub fn new(buckets: u16, bucket: Duration, forget_q15: u16, quantile_permille: u16) -> Self {
31        Self {
32            w: vec![0; usize::from(buckets).max(1)],
33            bucket_us: window_micros(bucket).max(1),
34            forget_q15: u64::from(forget_q15).min(Q15_ONE - 1),
35            quantile_permille: u64::from(quantile_permille),
36            intervals: 0,
37        }
38    }
39
40    /// Fold in one interval maximum (microseconds).
41    pub fn add(&mut self, value_us: u64) {
42        let k = self.intervals.min(u64::from(u32::MAX));
43        let ramp = (k << Q15_SHIFT) / (k + 1);
44        let f = self.forget_q15.min(ramp);
45        for x in &mut self.w {
46            *x = u32::try_from((u64::from(*x) * f) >> Q15_SHIFT).unwrap_or(u32::MAX);
47        }
48        let last = self.w.len() - 1;
49        let idx = usize::try_from(value_us / self.bucket_us)
50            .unwrap_or(usize::MAX)
51            .min(last);
52        let gain = u32::try_from(Q15_ONE - f).unwrap_or(u32::MAX);
53        self.w[idx] = self.w[idx].saturating_add(gain);
54        self.intervals = self.intervals.saturating_add(1);
55    }
56
57    /// Smallest bucket upper edge whose cumulative weight reaches the
58    /// quantile (`cum * 1000 >= total * q`); 0 for an empty histogram.
59    #[must_use]
60    pub fn quantile_us(&self) -> u64 {
61        let total: u64 = self.w.iter().map(|&x| u64::from(x)).sum();
62        if total == 0 {
63            return 0;
64        }
65        let mut cum = 0u64;
66        for (i, &x) in self.w.iter().enumerate() {
67            cum += u64::from(x);
68            if cum * PERMILLE >= total * self.quantile_permille {
69                return (i as u64 + 1) * self.bucket_us;
70            }
71        }
72        self.w.len() as u64 * self.bucket_us
73    }
74
75    /// Weight (Q15) of bucket `i`, 0 out of range.
76    #[must_use]
77    pub fn weight(&self, i: usize) -> u32 {
78        self.w.get(i).copied().unwrap_or(0)
79    }
80
81    /// Sum of all weights.
82    #[must_use]
83    pub fn total_weight(&self) -> u64 {
84        self.w.iter().map(|&x| u64::from(x)).sum()
85    }
86
87    /// Intervals folded in so far.
88    #[must_use]
89    pub fn intervals(&self) -> u64 {
90        self.intervals
91    }
92
93    /// Forget everything.
94    pub fn clear(&mut self) {
95        self.w.fill(0);
96        self.intervals = 0;
97    }
98}
99
100#[cfg(test)]
101mod tests {
102    use super::ForgettingHistogram;
103    use core::time::Duration;
104
105    fn bucket() -> Duration {
106        Duration::from_millis(10)
107    }
108
109    #[test]
110    fn an_interval_weight_halves_after_one_more_interval() {
111        let mut h = ForgettingHistogram::new(400, bucket(), 16_384, 1_000);
112        h.add(10_000);
113        assert_eq!(h.weight(1), 32_768);
114        assert_eq!(h.total_weight(), 32_768);
115        assert_eq!(h.intervals(), 1);
116        h.add(20_000);
117        assert_eq!(h.weight(1), 16_384);
118        assert_eq!(h.weight(2), 16_384);
119        h.add(10_000);
120        assert_eq!(h.weight(1), 24_576);
121        assert_eq!(h.weight(2), 8_192);
122        assert_eq!(h.total_weight(), 32_768);
123        assert_eq!(h.intervals(), 3);
124    }
125
126    #[test]
127    fn the_quantile_lands_in_the_dominant_bucket() {
128        let mut h = ForgettingHistogram::new(400, bucket(), 32_113, 990);
129        for _ in 0..100 {
130            h.add(10_000);
131        }
132        h.add(90_000);
133        assert_eq!(h.intervals(), 101);
134        assert_eq!(h.quantile_us(), 100_000);
135        let mut h = ForgettingHistogram::new(400, bucket(), 32_113, 900);
136        for _ in 0..100 {
137            h.add(10_000);
138        }
139        h.add(90_000);
140        assert_eq!(h.quantile_us(), 20_000);
141    }
142
143    #[test]
144    fn a_quantile_above_one_thousand_falls_through_to_the_histogram_range() {
145        let mut h = ForgettingHistogram::new(4, bucket(), 0, 1_001);
146        h.add(10_000);
147        assert_eq!(h.quantile_us(), 40_000);
148    }
149}