| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | use std::f64::consts::PI; |
| 18 | |
| 19 | |
| 20 | |
| 21 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 22 | pub enum BandKind { |
| 23 | LowShelf, |
| 24 | Peak, |
| 25 | HighShelf, |
| 26 | } |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 32 | pub struct Band { |
| 33 | pub freq_hz: f32, |
| 34 | pub gain_db: f32, |
| 35 | |
| 36 | pub q: f32, |
| 37 | pub kind: BandKind, |
| 38 | } |
| 39 | |
| 40 | |
| 41 | #[derive(Debug, Clone, PartialEq, Default)] |
| 42 | pub struct EqParams { |
| 43 | pub bands: Vec<Band>, |
| 44 | } |
| 45 | |
| 46 | impl EqParams { |
| 47 | |
| 48 | pub fn default_layout() -> Self { |
| 49 | let band = |freq_hz, kind| Band { |
| 50 | freq_hz, |
| 51 | gain_db: 0.0, |
| 52 | q: 0.707, |
| 53 | kind, |
| 54 | }; |
| 55 | Self { |
| 56 | bands: vec![ |
| 57 | band(80.0, BandKind::LowShelf), |
| 58 | band(250.0, BandKind::Peak), |
| 59 | band(1000.0, BandKind::Peak), |
| 60 | band(4000.0, BandKind::Peak), |
| 61 | band(12000.0, BandKind::HighShelf), |
| 62 | ], |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | |
| 67 | pub fn is_identity(&self) -> bool { |
| 68 | self.bands.iter().all(|b| b.gain_db.abs() < 1e-4) |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | |
| 73 | #[derive(Debug, Clone, Copy, Default)] |
| 74 | struct Coeffs { |
| 75 | b0: f32, |
| 76 | b1: f32, |
| 77 | b2: f32, |
| 78 | a1: f32, |
| 79 | a2: f32, |
| 80 | } |
| 81 | |
| 82 | impl Coeffs { |
| 83 | |
| 84 | fn new(band: &Band, sample_rate: u32) -> Self { |
| 85 | |
| 86 | |
| 87 | |
| 88 | let fs = f64::from(sample_rate.max(1)); |
| 89 | let f0 = f64::from(band.freq_hz).clamp(1.0, fs * 0.49); |
| 90 | let q = f64::from(band.q).clamp(0.05, 40.0); |
| 91 | let a = 10f64.powf(f64::from(band.gain_db) / 40.0); |
| 92 | let w0 = 2.0 * PI * f0 / fs; |
| 93 | let (sin_w0, cos_w0) = (w0.sin(), w0.cos()); |
| 94 | let alpha = sin_w0 / (2.0 * q); |
| 95 | let two_sqrt_a_alpha = 2.0 * a.sqrt() * alpha; |
| 96 | |
| 97 | let (b0, b1, b2, a0, a1, a2) = match band.kind { |
| 98 | BandKind::Peak => ( |
| 99 | 1.0 + alpha * a, |
| 100 | -2.0 * cos_w0, |
| 101 | 1.0 - alpha * a, |
| 102 | 1.0 + alpha / a, |
| 103 | -2.0 * cos_w0, |
| 104 | 1.0 - alpha / a, |
| 105 | ), |
| 106 | BandKind::LowShelf => ( |
| 107 | a * ((a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha), |
| 108 | 2.0 * a * ((a - 1.0) - (a + 1.0) * cos_w0), |
| 109 | a * ((a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha), |
| 110 | (a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha, |
| 111 | -2.0 * ((a - 1.0) + (a + 1.0) * cos_w0), |
| 112 | (a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha, |
| 113 | ), |
| 114 | BandKind::HighShelf => ( |
| 115 | a * ((a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha), |
| 116 | -2.0 * a * ((a - 1.0) + (a + 1.0) * cos_w0), |
| 117 | a * ((a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha), |
| 118 | (a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha, |
| 119 | 2.0 * ((a - 1.0) - (a + 1.0) * cos_w0), |
| 120 | (a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha, |
| 121 | ), |
| 122 | }; |
| 123 | Self { |
| 124 | b0: (b0 / a0) as f32, |
| 125 | b1: (b1 / a0) as f32, |
| 126 | b2: (b2 / a0) as f32, |
| 127 | a1: (a1 / a0) as f32, |
| 128 | a2: (a2 / a0) as f32, |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | const DENORMAL_FLOOR: f32 = 1e-20; |
| 137 | |
| 138 | |
| 139 | |
| 140 | pub struct EqState { |
| 141 | sample_rate: u32, |
| 142 | channels: usize, |
| 143 | coeffs: Vec<Coeffs>, |
| 144 | |
| 145 | state: Vec<[f32; 2]>, |
| 146 | |
| 147 | |
| 148 | identity: bool, |
| 149 | } |
| 150 | |
| 151 | impl EqState { |
| 152 | |
| 153 | |
| 154 | pub fn new(params: &EqParams, sample_rate: u32, channels: u16) -> Self { |
| 155 | let mut eq = Self { |
| 156 | sample_rate, |
| 157 | channels: (channels as usize).max(1), |
| 158 | coeffs: Vec::new(), |
| 159 | state: Vec::new(), |
| 160 | identity: true, |
| 161 | }; |
| 162 | eq.set_params(params); |
| 163 | eq |
| 164 | } |
| 165 | |
| 166 | |
| 167 | |
| 168 | pub fn set_params(&mut self, params: &EqParams) { |
| 169 | self.identity = params.is_identity(); |
| 170 | self.coeffs.clear(); |
| 171 | self.coeffs.extend( |
| 172 | params |
| 173 | .bands |
| 174 | .iter() |
| 175 | .map(|b| Coeffs::new(b, self.sample_rate)), |
| 176 | ); |
| 177 | self.state |
| 178 | .resize(self.coeffs.len() * self.channels, [0.0; 2]); |
| 179 | } |
| 180 | |
| 181 | |
| 182 | |
| 183 | pub fn reset(&mut self) { |
| 184 | self.state.fill([0.0; 2]); |
| 185 | } |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | pub fn process(&mut self, interleaved: &mut [f32]) { |
| 193 | if self.identity || self.coeffs.is_empty() { |
| 194 | return; |
| 195 | } |
| 196 | let channels = self.channels; |
| 197 | for (band, c) in self.coeffs.iter().enumerate() { |
| 198 | let state = &mut self.state[band * channels..][..channels]; |
| 199 | for frame in interleaved.chunks_exact_mut(channels) { |
| 200 | for (ch, x) in frame.iter_mut().enumerate() { |
| 201 | let s = &mut state[ch]; |
| 202 | let y = c.b0 * *x + s[0]; |
| 203 | s[0] = c.b1 * *x - c.a1 * y + s[1]; |
| 204 | s[1] = c.b2 * *x - c.a2 * y; |
| 205 | if s[0].abs() < DENORMAL_FLOOR { |
| 206 | s[0] = 0.0; |
| 207 | } |
| 208 | if s[1].abs() < DENORMAL_FLOOR { |
| 209 | s[1] = 0.0; |
| 210 | } |
| 211 | *x = y; |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | #[cfg(test)] |
| 219 | mod tests { |
| 220 | use std::f32::consts::TAU; |
| 221 | |
| 222 | use super::{Band, BandKind, EqParams, EqState}; |
| 223 | |
| 224 | const FS: u32 = 48_000; |
| 225 | |
| 226 | fn peak(freq_hz: f32, gain_db: f32, q: f32) -> EqParams { |
| 227 | EqParams { |
| 228 | bands: vec![Band { |
| 229 | freq_hz, |
| 230 | gain_db, |
| 231 | q, |
| 232 | kind: BandKind::Peak, |
| 233 | }], |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | fn sine(freq_hz: f32, frames: usize, channels: usize) -> Vec<f32> { |
| 238 | (0..frames * channels) |
| 239 | .map(|i| (TAU * freq_hz * (i / channels) as f32 / FS as f32).sin()) |
| 240 | .collect() |
| 241 | } |
| 242 | |
| 243 | |
| 244 | fn rms(samples: &[f32]) -> f32 { |
| 245 | let tail = &samples[samples.len() / 2..]; |
| 246 | (tail.iter().map(|v| v * v).sum::<f32>() / tail.len() as f32).sqrt() |
| 247 | } |
| 248 | |
| 249 | fn db(measured: f32, reference: f32) -> f32 { |
| 250 | 20.0 * (measured / reference).log10() |
| 251 | } |
| 252 | |
| 253 | #[test] |
| 254 | fn flat_params_pass_samples_through_bit_identical() { |
| 255 | let input = sine(440.0, 4800, 2); |
| 256 | let mut out = input.clone(); |
| 257 | EqState::new(&EqParams::default_layout(), FS, 2).process(&mut out); |
| 258 | assert_eq!(out, input, "a flat EQ must not touch the samples at all"); |
| 259 | |
| 260 | |
| 261 | |
| 262 | let mut params = EqParams::default_layout(); |
| 263 | params.bands[2].q = 4.0; |
| 264 | assert!(params.is_identity()); |
| 265 | } |
| 266 | |
| 267 | #[test] |
| 268 | fn a_band_moves_its_own_center_and_leaves_two_octaves_away_alone() { |
| 269 | for gain in [6.0, -6.0] { |
| 270 | let center = sine(1000.0, 48_000, 1); |
| 271 | let mut out = center.clone(); |
| 272 | EqState::new(&peak(1000.0, gain, 1.0), FS, 1).process(&mut out); |
| 273 | let at_center = db(rms(&out), rms(¢er)); |
| 274 | assert!( |
| 275 | (at_center - gain).abs() < 0.5, |
| 276 | "1 kHz sine through a {gain:+} dB band at 1 kHz measured {at_center:+.2} dB" |
| 277 | ); |
| 278 | |
| 279 | for off in [250.0, 4000.0] { |
| 280 | let away = sine(off, 48_000, 1); |
| 281 | let mut out = away.clone(); |
| 282 | EqState::new(&peak(1000.0, gain, 1.0), FS, 1).process(&mut out); |
| 283 | let leak = db(rms(&out), rms(&away)); |
| 284 | assert!( |
| 285 | leak.abs() < 1.0, |
| 286 | "{off} Hz is two octaves off but moved {leak:+.2} dB" |
| 287 | ); |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | #[test] |
| 293 | fn ten_seconds_of_noise_through_every_band_boosted_stays_bounded() { |
| 294 | let mut params = EqParams::default_layout(); |
| 295 | for band in &mut params.bands { |
| 296 | band.gain_db = 12.0; |
| 297 | } |
| 298 | let mut eq = EqState::new(¶ms, FS, 2); |
| 299 | |
| 300 | |
| 301 | let mut seed = 0x2545_f491_4f6c_dd1du64; |
| 302 | let mut noise = || { |
| 303 | seed ^= seed << 13; |
| 304 | seed ^= seed >> 7; |
| 305 | seed ^= seed << 17; |
| 306 | (seed >> 40) as f32 / 8_388_608.0 - 1.0 |
| 307 | }; |
| 308 | |
| 309 | let mut peak = 0.0f32; |
| 310 | |
| 311 | |
| 312 | for _ in 0..(10 * FS as usize / 1024) { |
| 313 | let mut block: Vec<f32> = (0..1024 * 2).map(|_| noise()).collect(); |
| 314 | eq.process(&mut block); |
| 315 | for v in block { |
| 316 | assert!(v.is_finite(), "EQ output went to {v}"); |
| 317 | peak = peak.max(v.abs()); |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | |
| 322 | assert!( |
| 323 | (1.0..20.0).contains(&peak), |
| 324 | "peak {peak} out of the plausible band for +12 dB x5" |
| 325 | ); |
| 326 | } |
| 327 | |
| 328 | #[test] |
| 329 | fn a_decaying_tail_leaves_the_state_at_a_hard_zero() { |
| 330 | let mut params = EqParams::default_layout(); |
| 331 | params.bands[1].gain_db = 9.0; |
| 332 | let mut eq = EqState::new(¶ms, FS, 2); |
| 333 | |
| 334 | let mut decay: Vec<f32> = (0..4800 * 2) |
| 335 | .map(|i| 0.9f32.powi(i / 2) * if i % 2 == 0 { 1.0 } else { -1.0 }) |
| 336 | .collect(); |
| 337 | eq.process(&mut decay); |
| 338 | let mut silence = vec![0.0f32; 4800 * 2]; |
| 339 | eq.process(&mut silence); |
| 340 | |
| 341 | for (i, s) in eq.state.iter().enumerate() { |
| 342 | assert!( |
| 343 | s[0] == 0.0 && s[1] == 0.0, |
| 344 | "state {i} still holds {s:?} after a decayed tail — denormal territory" |
| 345 | ); |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn an_impulse_in_the_left_channel_never_reaches_the_right() { |
| 351 | let mut params = EqParams::default_layout(); |
| 352 | params.bands[3].gain_db = -10.0; |
| 353 | let mut eq = EqState::new(¶ms, FS, 2); |
| 354 | |
| 355 | let mut buf = vec![0.0f32; 512 * 2]; |
| 356 | buf[0] = 1.0; |
| 357 | eq.process(&mut buf); |
| 358 | |
| 359 | assert!(buf[2] != 0.0, "the left channel should be ringing"); |
| 360 | for (frame, pair) in buf.chunks_exact(2).enumerate() { |
| 361 | assert_eq!( |
| 362 | pair[1], 0.0, |
| 363 | "frame {frame}: right channel picked up {pair:?}" |
| 364 | ); |
| 365 | } |
| 366 | } |
| 367 | } |