Skip to main content

buffering_runtime/
histogram.rs

1//! NetEq-style forgetting histogram of per-interval maxima, Q15 weights.
2
3use crate::config::{PERMILLE, Q15_ONE, Q15_SHIFT};
4use alloc::vec;
5use alloc::vec::Vec;
6
7/// Histogram of interval maxima with exponential forgetting.
8///
9/// Per [`add`](Self::add): every weight is multiplied by `f` (Q15, truncating
10/// `>> 15`), then the value's bucket gains `1 - f`. `f` ramps as
11/// `min(forget, k/(k+1))` over the first intervals so the first few behave as a
12/// plain average (NetEq's start-weight idea).
13#[derive(Clone, Debug)]
14pub struct ForgettingHistogram {
15    w: Vec<u32>,
16    bucket_us: u64,
17    forget_q15: u64,
18    quantile_permille: u64,
19    intervals: u64,
20}
21
22impl ForgettingHistogram {
23    /// New histogram. `buckets` and `bucket_us` must be non-zero (validated
24    /// by the configs; zeros are clamped to 1 here so this never panics).
25    #[must_use]
26    pub fn new(buckets: u16, bucket_us: u32, forget_q15: u16, quantile_permille: u16) -> Self {
27        Self {
28            w: vec![0; usize::from(buckets).max(1)],
29            bucket_us: u64::from(bucket_us).max(1),
30            forget_q15: u64::from(forget_q15).min(Q15_ONE - 1),
31            quantile_permille: u64::from(quantile_permille),
32            intervals: 0,
33        }
34    }
35
36    /// Fold in one interval maximum (microseconds).
37    pub fn add(&mut self, value_us: u64) {
38        let k = self.intervals.min(u64::from(u32::MAX));
39        let ramp = (k << Q15_SHIFT) / (k + 1);
40        let f = self.forget_q15.min(ramp);
41        for x in &mut self.w {
42            *x = u32::try_from((u64::from(*x) * f) >> Q15_SHIFT).unwrap_or(u32::MAX);
43        }
44        let last = self.w.len() - 1;
45        let idx = usize::try_from(value_us / self.bucket_us)
46            .unwrap_or(usize::MAX)
47            .min(last);
48        let gain = u32::try_from(Q15_ONE - f).unwrap_or(u32::MAX);
49        self.w[idx] = self.w[idx].saturating_add(gain);
50        self.intervals = self.intervals.saturating_add(1);
51    }
52
53    /// Smallest bucket upper edge whose cumulative weight reaches the
54    /// quantile (`cum * 1000 >= total * q`); 0 for an empty histogram.
55    #[must_use]
56    pub fn quantile_us(&self) -> u64 {
57        let total: u64 = self.w.iter().map(|&x| u64::from(x)).sum();
58        if total == 0 {
59            return 0;
60        }
61        let mut cum = 0u64;
62        for (i, &x) in self.w.iter().enumerate() {
63            cum += u64::from(x);
64            if cum * PERMILLE >= total * self.quantile_permille {
65                return (i as u64 + 1) * self.bucket_us;
66            }
67        }
68        self.w.len() as u64 * self.bucket_us
69    }
70
71    /// Weight (Q15) of bucket `i`, 0 out of range.
72    #[must_use]
73    pub fn weight(&self, i: usize) -> u32 {
74        self.w.get(i).copied().unwrap_or(0)
75    }
76
77    /// Sum of all weights.
78    #[must_use]
79    pub fn total_weight(&self) -> u64 {
80        self.w.iter().map(|&x| u64::from(x)).sum()
81    }
82
83    /// Intervals folded in so far.
84    #[must_use]
85    pub fn intervals(&self) -> u64 {
86        self.intervals
87    }
88
89    /// Forget everything.
90    pub fn clear(&mut self) {
91        self.w.fill(0);
92        self.intervals = 0;
93    }
94}