Skip to main content

rtci_interceptor/gcc/
kalman.rs

1//! The delay-gradient filter: noisy per-group measurements in, a trend out.
2
3/// `chi` (draft-ietf-rmcat-gcc-02 section 5.3: "typically chosen as a number in the interval
4/// [0.1, 0.001]"): 0.001, which at 100 groups a second gives the noise weight the filter had
5/// before the rate was measured (3e-4), and at 30 a second 1e-3.
6pub const DEFAULT_CHI: f64 = 0.001;
7
8/// K of section 5.3: how many groups `f_max`, their highest rate, is taken over (libwebrtc:
9/// 60).
10pub const PERIOD_HISTORY: usize = 60;
11
12/// Kalman filter over the one-way delay gradient, per draft-ietf-rmcat-gcc-02 §5.3.
13///
14/// # What it is for
15///
16/// A single inter-group delay measurement is mostly noise: scheduling jitter at either end, the
17/// receiver's clock resolution, and TWCC's 250 µs quantisation all move it around by more than the
18/// signal does early on. The filter estimates the *trend* — is the queue growing, and how fast —
19/// while adapting how much it trusts each new measurement to how noisy the measurements have been.
20///
21/// # Pure
22///
23/// No clock, no allocation, no state beyond four numbers. Every input is a parameter, which is what
24/// lets upstream's table-driven vectors port directly.
25#[derive(Debug, Clone, Copy)]
26pub struct Kalman {
27    /// Current estimate of the delay gradient, in milliseconds per group.
28    estimate: f64,
29    /// Estimate error variance.
30    error: f64,
31    /// Running estimate of measurement noise variance.
32    measurement_variance: f64,
33    /// How fast the process itself is believed to drift.
34    process_noise: f64,
35    /// Weight on each new sample when updating the noise estimate.
36    ///
37    /// Deliberately tiny. The residual that feeds this estimate is *signal* as well as noise, so a
38    /// large weight lets a genuine trend inflate the variance, which collapses the gain, which
39    /// stops the trend being tracked — the filter talks itself out of the thing it is measuring.
40    /// Used by [`update`](Self::update), which has no group period to derive it from; with one
41    /// ([`update_with_period`](Self::update_with_period)) it is the draft's `1 - alpha`.
42    noise_gain: f64,
43    /// `chi` of draft-ietf-rmcat-gcc-02 section 5.3, in [0.001, 0.1].
44    chi: f64,
45    /// The departure periods of the last `PERIOD_HISTORY` groups, milliseconds, for
46    /// `f_max`; zero where none was recorded yet.
47    periods: [f64; PERIOD_HISTORY],
48    next_period: usize,
49    /// Floor on the measurement-noise estimate, so the filter never trusts a sample completely.
50    min_measurement_variance: f64,
51}
52
53impl Default for Kalman {
54    fn default() -> Self {
55        Self {
56            estimate: 0.0,
57            // A large initial error means the first few measurements move the estimate freely,
58            // rather than being damped towards an arbitrary zero.
59            error: 0.1,
60            measurement_variance: 0.0,
61            process_noise: 1e-3,
62            noise_gain: 3e-4,
63            chi: DEFAULT_CHI,
64            periods: [0.0; PERIOD_HISTORY],
65            next_period: 0,
66            min_measurement_variance: 1.0,
67        }
68    }
69}
70
71impl Kalman {
72    /// A filter with the draft's default tuning.
73    pub fn new() -> Self {
74        Self::default()
75    }
76
77    /// How fast the underlying gradient is assumed to drift. Larger tracks faster and is noisier.
78    pub fn with_process_noise(mut self, process_noise: f64) -> Self {
79        self.process_noise = process_noise;
80        self
81    }
82
83    /// The current trend estimate, in milliseconds per group.
84    pub fn estimate(&self) -> f64 {
85        self.estimate
86    }
87
88    /// Fold in one inter-group delay measurement and return the updated estimate.
89    ///
90    /// `measurement` is arrival spread minus departure spread for a pair of groups, in
91    /// milliseconds.
92    pub fn update(&mut self, measurement: f64) -> f64 {
93        let noise_gain = self.noise_gain;
94        self.update_with_noise_gain(measurement, noise_gain)
95    }
96
97    /// `update` for a group that departed `period_ms` after the one before: the weight of the
98    /// sample in the noise variance is `1 - alpha`, `alpha = (1 - chi)^(30 / (1000 f_max))`,
99    /// `f_max` the highest group rate over the last `PERIOD_HISTORY` groups (section 5.3).
100    pub fn update_with_period(&mut self, measurement: f64, period_ms: f64) -> f64 {
101        if period_ms.is_finite() && period_ms > 0.0 {
102            self.periods[self.next_period] = period_ms;
103            self.next_period = (self.next_period + 1) % PERIOD_HISTORY;
104        }
105        let shortest = self
106            .periods
107            .iter()
108            .copied()
109            .filter(|period| *period > 0.0)
110            .fold(f64::INFINITY, f64::min);
111        let noise_gain = if shortest.is_finite() {
112            // f_max = 1 / shortest (per millisecond): 30 / (1000 f_max) = 30 shortest / 1000.
113            1.0 - (1.0 - self.chi).powf(30.0 * shortest / 1000.0)
114        } else {
115            self.noise_gain
116        };
117        self.update_with_noise_gain(measurement, noise_gain)
118    }
119
120    /// `chi` of section 5.3.
121    pub fn with_chi(mut self, chi: f64) -> Self {
122        self.chi = chi.clamp(0.001, 0.1);
123        self
124    }
125
126    fn update_with_noise_gain(&mut self, measurement: f64, noise_gain: f64) -> f64 {
127        // How far this sample is from what was predicted.
128        let residual = measurement - self.estimate;
129
130        // Track the noisiness of the measurements themselves, so a jittery path is trusted less.
131        // Clamped from below: with no floor, a run of identical samples drives the variance to
132        // zero and the filter starts believing each new sample absolutely. Section 5.3's outlier
133        // filter: a residual beyond three deviations enters the variance as three deviations.
134        let limit = 3.0
135            * self
136                .measurement_variance
137                .max(self.min_measurement_variance)
138                .sqrt();
139        let counted = residual.clamp(-limit, limit);
140        self.measurement_variance = ((1.0 - noise_gain) * self.measurement_variance
141            + noise_gain * counted * counted)
142            .max(self.min_measurement_variance);
143
144        // Predict: uncertainty grows by the process noise before the measurement is folded in.
145        let predicted_error = self.error + self.process_noise;
146
147        // The gain is how much of the residual to believe: high when the estimate is uncertain,
148        // low when the measurements are noisy.
149        let gain = predicted_error / (predicted_error + self.measurement_variance);
150
151        self.estimate += gain * residual;
152        self.error = (1.0 - gain) * predicted_error;
153
154        self.estimate
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    /// A path that is not queueing measures zero, and the filter must stay there rather than
163    /// drifting — a filter that wanders on a quiet path invents congestion.
164    #[test]
165    fn a_zero_signal_keeps_a_zero_estimate() {
166        let mut kalman = Kalman::new();
167        for _ in 0..100 {
168            kalman.update(0.0);
169        }
170        assert!(
171            kalman.estimate().abs() < 1e-9,
172            "estimate drifted to {}",
173            kalman.estimate()
174        );
175    }
176
177    /// A sustained gradient is tracked. Not instantly — that is the point of filtering — but it
178    /// must get there, or overuse is never detected.
179    #[test]
180    fn a_sustained_gradient_is_tracked() {
181        let mut kalman = Kalman::new();
182        for _ in 0..200 {
183            kalman.update(10.0);
184        }
185        assert!(
186            (kalman.estimate() - 10.0).abs() < 1.0,
187            "a steady 10 ms gradient should be tracked, got {}",
188            kalman.estimate()
189        );
190    }
191
192    /// Noise around zero must not be mistaken for a trend. This is the property that stops a
193    /// jittery but uncongested path from being throttled.
194    #[test]
195    fn symmetric_noise_does_not_move_the_estimate() {
196        let mut kalman = Kalman::new();
197        for step in 0..400 {
198            // ±8 ms alternating: far larger than any real gradient early on.
199            kalman.update(if step % 2 == 0 { 8.0 } else { -8.0 });
200        }
201        assert!(
202            kalman.estimate().abs() < 2.0,
203            "alternating noise should average out, got {}",
204            kalman.estimate()
205        );
206    }
207
208    /// The filter is asymmetric in time, not in sign: a negative trend is tracked as readily as a
209    /// positive one, or a draining queue would look like a stable one.
210    #[test]
211    fn a_negative_gradient_is_tracked_too() {
212        let mut kalman = Kalman::new();
213        for _ in 0..200 {
214            kalman.update(-6.0);
215        }
216        assert!(
217            (kalman.estimate() + 6.0).abs() < 1.0,
218            "a draining queue should read negative, got {}",
219            kalman.estimate()
220        );
221    }
222
223    /// Higher process noise tracks a change faster. This is the knob, and it must actually do
224    /// something — otherwise the tuning is decoration.
225    #[test]
226    fn process_noise_controls_how_fast_a_change_is_tracked() {
227        let mut slow = Kalman::new().with_process_noise(1e-5);
228        let mut fast = Kalman::new().with_process_noise(1e-1);
229
230        for _ in 0..30 {
231            slow.update(20.0);
232            fast.update(20.0);
233        }
234
235        assert!(
236            fast.estimate() > slow.estimate(),
237            "more process noise should track faster: slow {}, fast {}",
238            slow.estimate(),
239            fast.estimate()
240        );
241    }
242
243    /// Section 5.3, the first step from the start: e(0) = 0.1, q = 1e-3 and the variance
244    /// floor of 1 give the gain (0.1 + 0.001) / (1 + 0.1 + 0.001), so a first measurement of 10
245    /// moves the estimate to 10 times that.
246    #[test]
247    fn the_first_step_is_set_by_e0_q_and_the_variance_floor() {
248        let mut kalman = Kalman::new();
249        let estimate = kalman.update(10.0);
250        let gain = 0.101 / 1.101;
251        assert!((estimate - 10.0 * gain).abs() < 1e-9, "{estimate}");
252    }
253
254    /// Section 5.3's outlier filter: one residual far beyond three deviations raises the noise
255    /// variance only as three deviations would, so the filter goes on trusting the samples
256    /// that follow.
257    #[test]
258    fn an_outlier_enters_the_variance_as_three_deviations() {
259        let mut with_outlier = Kalman::new();
260        let mut with_three = Kalman::new();
261        for _ in 0..50 {
262            with_outlier.update_with_period(0.0, 10.0);
263            with_three.update_with_period(0.0, 10.0);
264        }
265        with_outlier.update_with_period(1_000.0, 10.0);
266        with_three.update_with_period(1_000.0, 10.0);
267        // Both clamp; an unclamped variance would be orders of magnitude larger.
268        assert!(
269            with_outlier.measurement_variance < 1.1,
270            "{}",
271            with_outlier.measurement_variance
272        );
273        assert_eq!(
274            with_outlier.measurement_variance,
275            with_three.measurement_variance
276        );
277    }
278
279    /// Section 5.3: alpha follows the highest group rate. Groups 5 ms apart weigh each sample
280    /// in the variance about six times less than groups 33 ms apart.
281    #[test]
282    fn the_noise_weight_follows_the_group_rate() {
283        let run = |period: f64| {
284            let mut kalman = Kalman::new();
285            for step in 0..200 {
286                kalman.update_with_period(if step % 2 == 0 { 5.0 } else { -5.0 }, period);
287            }
288            kalman.measurement_variance
289        };
290        let fast = run(5.0);
291        let slow = run(33.0);
292        assert!(slow > fast * 2.0, "fast {fast}, slow {slow}");
293    }
294}