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}