Skip to main content

autoeq_core/
response.rs

1//! Frequency response calculation for filters
2
3use crate::Curve;
4use crate::error::{AutoeqError, Result};
5use crate::iir::Biquad;
6use ndarray::Array1;
7use num_complex::Complex64;
8use std::f64::consts::PI;
9
10/// Lowest response magnitude exposed to optimization and reporting.
11pub const MIN_FILTER_RESPONSE_DB: f64 = -40.0;
12/// Finite floor used when reconstructing a physical serialized DSP graph.
13/// This prevents `log10(0)` without clipping legitimate crossover stopbands.
14pub const MIN_REALIZATION_RESPONSE_DB: f64 = -240.0;
15
16fn validate_response_grid(freqs: &Array1<f64>, sample_rate: f64, context: &str) -> Result<()> {
17    if !sample_rate.is_finite() || sample_rate <= 0.0 {
18        return Err(AutoeqError::InvalidConfiguration {
19            message: format!(
20                "{context} sample rate must be finite and positive, got {sample_rate}"
21            ),
22        });
23    }
24    Curve::validate_frequency_grid(freqs, context)
25}
26
27/// Checked PEQ response entry point for untrusted public inputs.
28pub fn try_compute_peq_complex_response(
29    filters: &[Biquad],
30    freqs: &Array1<f64>,
31    sample_rate: f64,
32) -> Result<Vec<Complex64>> {
33    validate_response_grid(freqs, sample_rate, "PEQ response")?;
34    Ok(compute_peq_complex_response(filters, freqs, sample_rate))
35}
36
37/// Compute complex frequency response of a list of Biquad filters
38pub fn compute_peq_complex_response(
39    filters: &[Biquad],
40    freqs: &Array1<f64>,
41    sample_rate: f64,
42) -> Vec<Complex64> {
43    // `Biquad` owns the canonical coefficient generation for every filter
44    // type. Cache those normalized coefficients once instead of maintaining a
45    // second set of formulas here (and recomputing them for every frequency).
46    let coefficients: Vec<_> = filters.iter().map(Biquad::constants).collect();
47
48    freqs
49        .iter()
50        .map(|&f| {
51            let w = 2.0 * PI * f / sample_rate;
52            let z_inv = Complex64::from_polar(1.0, -w);
53            let z_inv_2 = z_inv * z_inv;
54
55            let mut total_h = Complex64::new(1.0, 0.0);
56
57            for &(a1, a2, b0, b1, b2) in &coefficients {
58                let num = b0 + b1 * z_inv + b2 * z_inv_2;
59                let den = 1.0 + a1 * z_inv + a2 * z_inv_2;
60
61                // Complex division stays finite even for very small
62                // denominators (numerator shrinks with them); skipping the
63                // factor would silently substitute unity gain.
64                total_h *= num / den;
65            }
66            total_h
67        })
68        .collect()
69}
70
71/// Compute complex frequency response of FIR coefficients
72pub fn compute_fir_complex_response(
73    coeffs: &[f64],
74    freqs: &Array1<f64>,
75    sample_rate: f64,
76) -> Vec<Complex64> {
77    // Direct DFT calculation (O(N*M))
78    // Appropriate for evaluation at specific log-spaced frequencies
79    freqs
80        .iter()
81        .map(|&f| {
82            let w = 2.0 * PI * f / sample_rate;
83            let mut h = Complex64::new(0.0, 0.0);
84
85            for (n, &val) in coeffs.iter().enumerate() {
86                let angle = -w * n as f64;
87                h += Complex64::from_polar(val, angle);
88            }
89            h
90        })
91        .collect()
92}
93
94/// Checked FIR response entry point for untrusted public inputs.
95pub fn try_compute_fir_complex_response(
96    coeffs: &[f64],
97    freqs: &Array1<f64>,
98    sample_rate: f64,
99) -> Result<Vec<Complex64>> {
100    validate_response_grid(freqs, sample_rate, "FIR response")?;
101    if coeffs.is_empty() || coeffs.iter().any(|value| !value.is_finite()) {
102        return Err(AutoeqError::InvalidConfiguration {
103            message: "FIR response coefficients must be non-empty and finite".to_string(),
104        });
105    }
106    Ok(compute_fir_complex_response(coeffs, freqs, sample_rate))
107}
108
109/// Apply complex filter response (magnitude and phase) to a curve
110pub fn apply_complex_response(curve: &Curve, response: &[Complex64]) -> Curve {
111    apply_complex_response_with_min_db(curve, response, MIN_FILTER_RESPONSE_DB)
112}
113
114/// Apply a complex response with an explicit finite magnitude floor.
115pub fn apply_complex_response_with_min_db(
116    curve: &Curve,
117    response: &[Complex64],
118    min_response_db: f64,
119) -> Curve {
120    if response.len() != curve.freq.len() {
121        // A half-applied response silently corrupts every downstream stage;
122        // fail fast instead of truncating. Checked callers should use
123        // `try_apply_complex_response`, which reports this as an error.
124        panic!(
125            "complex response length {} does not match curve length {}",
126            response.len(),
127            curve.freq.len()
128        );
129    }
130
131    let mut new_spl = curve.spl.clone();
132    let old_phase = curve.phase.as_ref();
133    let mut new_phase = old_phase
134        .cloned()
135        .unwrap_or_else(|| Array1::zeros(curve.freq.len()));
136
137    for (i, &h) in response.iter().enumerate() {
138        let h_mag_db = (20.0 * h.norm().log10()).max(min_response_db);
139        let h_phase_deg = h.arg().to_degrees();
140
141        new_spl[i] = curve.spl[i] + h_mag_db;
142        let p_in = old_phase.map(|p| p[i]).unwrap_or(0.0);
143        new_phase[i] = p_in + h_phase_deg;
144    }
145
146    Curve {
147        freq: curve.freq.clone(),
148        spl: new_spl,
149        phase: Some(new_phase),
150        // Filtering changes magnitude/phase, not measurement provenance or
151        // confidence. Preserve coherence, noise floor, quality metadata and
152        // any other side-channel data needed by later phase-aware stages.
153        ..curve.clone()
154    }
155}
156
157/// Checked complex-response application for public or deserialized data.
158pub fn try_apply_complex_response(curve: &Curve, response: &[Complex64]) -> Result<Curve> {
159    curve.validate("complex-response curve")?;
160    if response.len() != curve.freq.len() {
161        return Err(AutoeqError::InvalidMeasurement {
162            message: format!(
163                "complex response length {} does not match curve length {}",
164                response.len(),
165                curve.freq.len()
166            ),
167        });
168    }
169    if response
170        .iter()
171        .any(|value| !value.re.is_finite() || !value.im.is_finite())
172    {
173        return Err(AutoeqError::InvalidMeasurement {
174            message: "complex response must contain only finite values".to_string(),
175        });
176    }
177    Ok(apply_complex_response(curve, response))
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use crate::iir::BiquadFilterType;
184    use ndarray::Array1;
185    use num_complex::Complex64;
186    use std::f64::consts::PI;
187
188    #[test]
189    fn test_fir_response_impulse() {
190        // Impulse response [1.0] should have flat magnitude (0 dB) and 0 phase
191        let coeffs = vec![1.0];
192        let freqs = Array1::from(vec![100.0, 1000.0, 10000.0]);
193        let sample_rate = 48000.0;
194
195        let response = compute_fir_complex_response(&coeffs, &freqs, sample_rate);
196
197        for h in response {
198            assert!((h.norm() - 1.0).abs() < 1e-10);
199            assert!(h.arg().abs() < 1e-10);
200        }
201    }
202
203    #[test]
204    fn test_fir_response_delay() {
205        // Delayed impulse [0.0, 1.0] should have flat magnitude and linear phase
206        let coeffs = vec![0.0, 1.0];
207        let freqs = Array1::from(vec![100.0, 1000.0, 10000.0]);
208        let sample_rate = 48000.0;
209
210        let response = compute_fir_complex_response(&coeffs, &freqs, sample_rate);
211
212        for (i, h) in response.iter().enumerate() {
213            assert!((h.norm() - 1.0).abs() < 1e-10);
214
215            // Phase should be -w * delay
216            // delay = 1 sample
217            let w = 2.0 * PI * freqs[i] / sample_rate;
218            let expected_phase = -w;
219
220            // Normalize phase to [-pi, pi]
221            let phase = h.arg();
222            let mut diff = (phase - expected_phase).abs();
223            while diff > PI {
224                diff -= 2.0 * PI;
225            }
226            assert!(diff.abs() < 1e-10);
227        }
228    }
229
230    #[test]
231    fn test_peq_empty_filters_identity() {
232        let filters: Vec<crate::iir::Biquad> = vec![];
233        let freqs = Array1::from(vec![100.0, 1000.0, 10000.0]);
234        let sr = 48000.0;
235        let resp = compute_peq_complex_response(&filters, &freqs, sr);
236        assert_eq!(resp.len(), freqs.len());
237        for h in &resp {
238            assert!((h.norm() - 1.0).abs() < 1e-12);
239            assert!(h.arg().abs() < 1e-12);
240        }
241    }
242
243    fn response_from_stored_coefficients(
244        biquad: &Biquad,
245        frequency: f64,
246        sample_rate: f64,
247    ) -> Complex64 {
248        let (a1, a2, b0, b1, b2) = biquad.constants();
249        let z_inv = Complex64::from_polar(1.0, -2.0 * PI * frequency / sample_rate);
250        let z_inv_2 = z_inv * z_inv;
251        (b0 + b1 * z_inv + b2 * z_inv_2) / (1.0 + a1 * z_inv + a2 * z_inv_2)
252    }
253
254    #[test]
255    fn test_peq_response_uses_coefficients_for_every_biquad_type() {
256        let sample_rate = 48_000.0;
257        let frequencies = Array1::from(vec![500.0, 1_000.0, 2_000.0]);
258        let filter_types = [
259            BiquadFilterType::Bandpass,
260            BiquadFilterType::Notch,
261            BiquadFilterType::AllPass,
262            BiquadFilterType::LowshelfOrf,
263            BiquadFilterType::HighshelfOrf,
264            BiquadFilterType::PeakMatched,
265            BiquadFilterType::HighpassVariableQ,
266        ];
267
268        for filter_type in filter_types {
269            let biquad = Biquad::new(filter_type, 1_000.0, sample_rate, 1.1, 6.0);
270            let actual = compute_peq_complex_response(
271                std::slice::from_ref(&biquad),
272                &frequencies,
273                sample_rate,
274            );
275
276            for (&frequency, actual) in frequencies.iter().zip(actual) {
277                let expected = response_from_stored_coefficients(&biquad, frequency, sample_rate);
278                assert!(
279                    (actual - expected).norm() < 1e-12,
280                    "{filter_type:?} response mismatch at {frequency} Hz: actual={actual:?}, expected={expected:?}"
281                );
282            }
283        }
284    }
285
286    #[test]
287    fn test_apply_complex_response_identity() {
288        let curve = Curve {
289            freq: Array1::from(vec![100.0, 1000.0]),
290            spl: Array1::from(vec![0.0, 10.0]),
291            phase: None,
292            coherence: Some(Array1::from(vec![0.8, 0.9])),
293            ..Default::default()
294        };
295        let identity = vec![Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
296        let out = apply_complex_response(&curve, &identity);
297        assert!((out.spl[0] - 0.0).abs() < 1e-12);
298        assert!((out.spl[1] - 10.0).abs() < 1e-12);
299        assert!(out.phase.is_some());
300        assert!(out.phase.unwrap()[0].abs() < 1e-12);
301        assert_eq!(out.coherence.unwrap().to_vec(), vec![0.8, 0.9]);
302    }
303
304    #[test]
305    fn test_apply_complex_response_boost() {
306        let curve = Curve {
307            freq: Array1::from(vec![1000.0]),
308            spl: Array1::from(vec![0.0]),
309            phase: None,
310            ..Default::default()
311        };
312        let boost = vec![Complex64::new(2.0, 0.0)];
313        let out = apply_complex_response(&curve, &boost);
314        let expected_db = 20.0 * 2.0f64.log10();
315        assert!(
316            (out.spl[0] - expected_db).abs() < 1e-9,
317            "got {}",
318            out.spl[0]
319        );
320    }
321
322    #[test]
323    fn audit_zero_complex_response_is_limited_to_minus_40_db() {
324        let curve = Curve {
325            freq: Array1::from(vec![1000.0]),
326            spl: Array1::from(vec![0.0]),
327            phase: None,
328            ..Default::default()
329        };
330        let out = apply_complex_response(&curve, &[Complex64::new(0.0, 0.0)]);
331
332        assert!(out.spl[0].is_finite());
333        assert_eq!(out.spl[0], -40.0);
334    }
335
336    #[test]
337    fn mismatched_complex_response_length_fails_fast() {
338        // A half-filtered curve silently corrupts every downstream stage, so
339        // length mismatches must be loud instead of truncating the response.
340        let curve = Curve {
341            freq: Array1::from(vec![100.0, 1000.0]),
342            spl: Array1::from(vec![1.0, 2.0]),
343            phase: None,
344            ..Default::default()
345        };
346        let outcome = std::panic::catch_unwind(|| {
347            apply_complex_response(&curve, &[Complex64::new(1.0, 0.0)])
348        });
349
350        assert!(outcome.is_err(), "mismatched response must fail fast");
351    }
352
353    #[test]
354    fn tiny_denominator_filters_contribute_not_skipped() {
355        // High-Q peaking filter: |den|² drops under 1e-12 near its center
356        // frequency while num/den stays finite (= the +12 dB boost). The
357        // filter must contribute its actual ratio instead of being silently
358        // replaced by unity gain.
359        let sample_rate = 48_000.0;
360        let biquad = Biquad::new(BiquadFilterType::Peak, 20.0, sample_rate, 500.0, 12.0);
361        let (a1, a2, _, _, _) = biquad.constants();
362        let w = 2.0 * PI * 20.0 / sample_rate;
363        let z_inv = Complex64::from_polar(1.0, -w);
364        let z_inv_2 = z_inv * z_inv;
365        let den = 1.0 + a1 * z_inv + a2 * z_inv_2;
366        assert!(
367            den.norm_sqr() <= 1e-12,
368            "test precondition: denominator should fall under the old skip threshold, got {}",
369            den.norm_sqr()
370        );
371
372        let frequencies = Array1::from(vec![20.0]);
373        let response = compute_peq_complex_response(&[biquad], &frequencies, sample_rate);
374        let gain_db = 20.0 * response[0].norm().log10();
375        assert!(
376            (gain_db - 12.0).abs() < 0.5,
377            "expected ≈ +12 dB at the boost center, got {gain_db:.3} dB"
378        );
379    }
380
381    #[test]
382    fn checked_response_apis_reject_invalid_grids_and_sample_rates() {
383        let valid = Array1::from_vec(vec![100.0, 1_000.0]);
384        for sample_rate in [0.0, -48_000.0, f64::NAN, f64::INFINITY] {
385            assert!(matches!(
386                try_compute_peq_complex_response(&[], &valid, sample_rate),
387                Err(AutoeqError::InvalidConfiguration { .. })
388            ));
389            assert!(matches!(
390                try_compute_fir_complex_response(&[1.0], &valid, sample_rate),
391                Err(AutoeqError::InvalidConfiguration { .. })
392            ));
393        }
394
395        for invalid in [
396            Array1::from_vec(vec![]),
397            Array1::from_vec(vec![100.0]),
398            Array1::from_vec(vec![100.0, f64::NAN]),
399            Array1::from_vec(vec![100.0, f64::INFINITY]),
400        ] {
401            assert!(matches!(
402                try_compute_peq_complex_response(&[], &invalid, 48_000.0),
403                Err(AutoeqError::InvalidMeasurement { .. })
404            ));
405            assert!(matches!(
406                try_compute_fir_complex_response(&[1.0], &invalid, 48_000.0),
407                Err(AutoeqError::InvalidMeasurement { .. })
408            ));
409        }
410    }
411
412    #[test]
413    fn checked_fir_response_rejects_empty_or_non_finite_coefficients() {
414        let frequencies = Array1::from_vec(vec![100.0, 1_000.0]);
415        for coefficients in [vec![], vec![1.0, f64::NAN], vec![f64::INFINITY]] {
416            assert!(matches!(
417                try_compute_fir_complex_response(&coefficients, &frequencies, 48_000.0),
418                Err(AutoeqError::InvalidConfiguration { .. })
419            ));
420        }
421    }
422
423    #[test]
424    fn checked_complex_response_rejects_invalid_curve_or_length() {
425        let valid = Curve {
426            freq: Array1::from_vec(vec![100.0, 1_000.0]),
427            spl: Array1::from_vec(vec![80.0, 81.0]),
428            ..Default::default()
429        };
430        let identity = [Complex64::new(1.0, 0.0), Complex64::new(1.0, 0.0)];
431        assert!(try_apply_complex_response(&valid, &identity).is_ok());
432        assert!(matches!(
433            try_apply_complex_response(&valid, &identity[..1]),
434            Err(AutoeqError::InvalidMeasurement { .. })
435        ));
436
437        let mut invalid_spl = valid.clone();
438        invalid_spl.spl[0] = f64::NAN;
439        assert!(matches!(
440            try_apply_complex_response(&invalid_spl, &identity),
441            Err(AutoeqError::InvalidMeasurement { .. })
442        ));
443        assert!(matches!(
444            try_apply_complex_response(&valid, &[Complex64::new(f64::INFINITY, 0.0), identity[1]],),
445            Err(AutoeqError::InvalidMeasurement { .. })
446        ));
447    }
448}