Skip to main content

qualia_audio/features/filters/
highpass.rs

1//! RBJ Audio-EQ-Cookbook high-pass biquad coefficient design.
2
3use super::biquad::BiquadCoeffs;
4
5/// Design a 2nd-order high-pass (RBJ cookbook `HPF`).
6///
7/// `sample_rate` Hz, `cutoff_hz` corner frequency, `q` resonance
8/// (0.707 ≈ Butterworth). Inputs are clamped so coefficients stay finite.
9pub fn design_highpass(sample_rate: f32, cutoff_hz: f32, q: f32) -> BiquadCoeffs {
10    let sr = f64::from(if sample_rate > 1.0 { sample_rate } else { 1.0 });
11    let f0 = f64::from(cutoff_hz).clamp(1.0e-4, sr * 0.5 * 0.999);
12    let q64 = f64::from(if q > 1.0e-4 { q } else { 1.0e-4 });
13    etalon_signal::filter::rbj_highpass(sr, f0, q64)
14        .map(BiquadCoeffs::from_etalon)
15        .unwrap_or_else(|_| BiquadCoeffs::identity())
16}
17
18#[cfg(test)]
19mod tests {
20    use super::*;
21    use crate::features::filters::biquad::{BiquadCoeffs, BiquadState};
22
23    fn run_sine(sr: f32, freq: f32, c: &BiquadCoeffs) -> f32 {
24        let n = 8192usize;
25        let skip = 2048usize;
26        let mut st = BiquadState::new();
27        let mut acc_in = 0.0f32;
28        let mut acc_out = 0.0f32;
29        let mut cnt = 0.0f32;
30        for i in 0..n {
31            let x = (2.0 * core::f32::consts::PI * freq * i as f32 / sr).sin();
32            let y = st.process_sample(c, x);
33            if i >= skip {
34                acc_in += x * x;
35                acc_out += y * y;
36                cnt += 1.0;
37            }
38        }
39        (acc_out / cnt).sqrt() / (acc_in / cnt).sqrt()
40    }
41
42    #[test]
43    fn passband_preserves_rms() {
44        let c = design_highpass(48_000.0, 1_000.0, 0.707);
45        let ratio = run_sine(48_000.0, 12_000.0, &c); // well above cutoff
46        assert!(ratio > 0.9 && ratio < 1.1, "passband ratio {ratio}");
47    }
48
49    #[test]
50    fn stopband_attenuates() {
51        let c = design_highpass(48_000.0, 1_000.0, 0.707);
52        let ratio = run_sine(48_000.0, 100.0, &c); // well below cutoff
53        assert!(ratio < 0.3, "stopband ratio {ratio}");
54    }
55}