qualia_audio/io/eqloud/equal_loudness.rs
1//! Equal-loudness contour weighting applied to a magnitude spectrum.
2//!
3//! Human hearing is not flat: energy near 2–4 kHz is perceived as much louder
4//! than the same energy at 50 Hz or 15 kHz. This module weights a linear
5//! magnitude spectrum by an **A-weighting** curve — the standard analytic
6//! approximation of the (inverted) 40-phon ISO 226 equal-loudness contour — so
7//! that downstream loudness / salience measures reflect perception rather than
8//! raw physical energy.
9//!
10//! The curve is normalised to unity (0 dB) gain at 1 kHz. It is caller-buffered
11//! and allocation-free: bin `k` of an `N`-bin spectrum spanning `[0, Nyquist]`
12//! is treated as frequency `k · (fs/2) / (N-1)`.
13
14use crate::types::AudioError;
15
16/// Weight a magnitude spectrum `mag` by the A-weighting equal-loudness curve,
17/// writing `mag.len()` weighted magnitudes into `out`.
18///
19/// - `mag`: `N` linear magnitudes for bins `0..N`, spanning `[0, fs/2]`.
20/// - `sample_rate`: source sample rate `fs` (Hz); must be non-zero.
21/// - `out`: at least `N` floats; receives `mag[k] · w(f_k)`.
22///
23/// Returns the number of bins written (`mag.len()`), or
24/// [`AudioError::InvalidParameter`] for a zero sample rate, or
25/// [`AudioError::OutputBufferTooSmall`] if `out` is shorter than `mag`.
26pub fn apply_equal_loudness(
27 mag: &[f32],
28 sample_rate: u32,
29 out: &mut [f32],
30) -> Result<usize, AudioError> {
31 if sample_rate == 0 {
32 return Err(AudioError::InvalidParameter);
33 }
34 if mag.is_empty() {
35 return Ok(0);
36 }
37 if out.len() < mag.len() {
38 return Err(AudioError::OutputBufferTooSmall);
39 }
40 let bins = mag.len();
41 let nyquist = sample_rate as f64 / 2.0;
42 // Bin spacing: with `bins` samples across [0, Nyquist], the last bin is at
43 // Nyquist. Guard the single-bin case.
44 let denom = (bins - 1).max(1) as f64;
45 for k in 0..bins {
46 let f = k as f64 * nyquist / denom;
47 out[k] = mag[k] * a_weight_linear(f) as f32;
48 }
49 Ok(bins)
50}
51
52/// Linear (not dB) A-weighting gain at frequency `f` Hz, normalised to `1.0` at
53/// 1 kHz. DC (`f ≤ 0`) is fully attenuated, matching the A-curve's high-pass
54/// behaviour.
55///
56/// Uses the IEC 61672 pole frequencies:
57/// `R_A(f) = c4·f⁴ / [(f²+c1)·√((f²+c2)(f²+c3))·(f²+c4)]`, then applies the
58/// conventional `+2.0 dB` gain offset so `A(1000 Hz) = 0 dB`.
59fn a_weight_linear(f: f64) -> f64 {
60 if f <= 0.0 {
61 return 0.0;
62 }
63 let f2 = f * f;
64 let c1 = 20.598_997_f64 * 20.598_997_f64; // (20.6 Hz)²
65 let c2 = 107.652_65_f64 * 107.652_65_f64; // (107.7 Hz)²
66 let c3 = 737.862_23_f64 * 737.862_23_f64; // (737.9 Hz)²
67 let c4 = 12194.217_f64 * 12194.217_f64; // (12194 Hz)²
68 let num = c4 * f2 * f2;
69 let den = (f2 + c1) * ((f2 + c2) * (f2 + c3)).sqrt() * (f2 + c4);
70 let ra = num / den;
71 // +2.00 dB offset → 10^(2/20) ≈ 1.258925 in linear terms; makes 1 kHz unity.
72 ra * 1.258_925_4_f64
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78
79 #[test]
80 fn unity_at_1khz_and_rolloff_at_low_freq() {
81 // fs = 2000 Hz, 101 bins → 10 Hz spacing. Bin 100 = 1000 Hz, bin 5 = 50 Hz.
82 let bins = 101;
83 let mag = vec![1.0f32; bins];
84 let mut out = vec![0.0f32; bins];
85 let n = apply_equal_loudness(&mag, 2000, &mut out).unwrap();
86 assert_eq!(n, bins);
87
88 // 1 kHz: ~unity gain.
89 assert!(
90 (out[100] - 1.0).abs() < 0.05,
91 "1 kHz weight expected ~1.0, got {}",
92 out[100]
93 );
94 // 50 Hz: A-weighting attenuates by ~30 dB → linear ≪ 0.2.
95 assert!(out[5] < 0.2, "50 Hz weight expected ≪ 0.2, got {}", out[5]);
96 // DC fully attenuated.
97 assert_eq!(out[0], 0.0);
98 // Low frequencies attenuated relative to 1 kHz.
99 assert!(out[5] < out[100]);
100 }
101
102 #[test]
103 fn rejects_zero_rate() {
104 let mag = [1.0f32; 4];
105 let mut out = [0.0f32; 4];
106 assert_eq!(
107 apply_equal_loudness(&mag, 0, &mut out),
108 Err(AudioError::InvalidParameter)
109 );
110 }
111
112 #[test]
113 fn rejects_short_output() {
114 let mag = [1.0f32; 8];
115 let mut out = [0.0f32; 4];
116 assert_eq!(
117 apply_equal_loudness(&mag, 16000, &mut out),
118 Err(AudioError::OutputBufferTooSmall)
119 );
120 }
121}