| 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 | |
| 74 | |
| 75 | |
| 76 | pub fn response_db(&self, freq_hz: f32, sample_rate: u32) -> f32 { |
| 77 | self.bands |
| 78 | .iter() |
| 79 | .map(|b| Coeffs::new(b, sample_rate).magnitude_db(freq_hz, sample_rate)) |
| 80 | .sum() |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | |
| 85 | #[derive(Debug, Clone, Copy, Default)] |
| 86 | struct Coeffs { |
| 87 | b0: f32, |
| 88 | b1: f32, |
| 89 | b2: f32, |
| 90 | a1: f32, |
| 91 | a2: f32, |
| 92 | } |
| 93 | |
| 94 | impl Coeffs { |
| 95 | |
| 96 | fn new(band: &Band, sample_rate: u32) -> Self { |
| 97 | |
| 98 | |
| 99 | |
| 100 | let fs = f64::from(sample_rate.max(1)); |
| 101 | let f0 = f64::from(band.freq_hz).clamp(1.0, fs * 0.49); |
| 102 | let q = f64::from(band.q).clamp(0.05, 40.0); |
| 103 | let a = 10f64.powf(f64::from(band.gain_db) / 40.0); |
| 104 | let w0 = 2.0 * PI * f0 / fs; |
| 105 | let (sin_w0, cos_w0) = (w0.sin(), w0.cos()); |
| 106 | let alpha = sin_w0 / (2.0 * q); |
| 107 | let two_sqrt_a_alpha = 2.0 * a.sqrt() * alpha; |
| 108 | |
| 109 | let (b0, b1, b2, a0, a1, a2) = match band.kind { |
| 110 | BandKind::Peak => ( |
| 111 | 1.0 + alpha * a, |
| 112 | -2.0 * cos_w0, |
| 113 | 1.0 - alpha * a, |
| 114 | 1.0 + alpha / a, |
| 115 | -2.0 * cos_w0, |
| 116 | 1.0 - alpha / a, |
| 117 | ), |
| 118 | BandKind::LowShelf => ( |
| 119 | a * ((a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha), |
| 120 | 2.0 * a * ((a - 1.0) - (a + 1.0) * cos_w0), |
| 121 | a * ((a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha), |
| 122 | (a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha, |
| 123 | -2.0 * ((a - 1.0) + (a + 1.0) * cos_w0), |
| 124 | (a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha, |
| 125 | ), |
| 126 | BandKind::HighShelf => ( |
| 127 | a * ((a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha), |
| 128 | -2.0 * a * ((a - 1.0) + (a + 1.0) * cos_w0), |
| 129 | a * ((a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha), |
| 130 | (a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha, |
| 131 | 2.0 * ((a - 1.0) - (a + 1.0) * cos_w0), |
| 132 | (a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha, |
| 133 | ), |
| 134 | }; |
| 135 | Self { |
| 136 | b0: (b0 / a0) as f32, |
| 137 | b1: (b1 / a0) as f32, |
| 138 | b2: (b2 / a0) as f32, |
| 139 | a1: (a1 / a0) as f32, |
| 140 | a2: (a2 / a0) as f32, |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | |
| 145 | |
| 146 | fn magnitude_db(&self, freq_hz: f32, sample_rate: u32) -> f32 { |
| 147 | let fs = f64::from(sample_rate.max(1)); |
| 148 | let w = 2.0 * PI * f64::from(freq_hz).clamp(0.0, fs * 0.5) / fs; |
| 149 | let (sin1, cos1) = w.sin_cos(); |
| 150 | let (sin2, cos2) = (2.0 * w).sin_cos(); |
| 151 | let (b0, b1, b2) = (f64::from(self.b0), f64::from(self.b1), f64::from(self.b2)); |
| 152 | let (a1, a2) = (f64::from(self.a1), f64::from(self.a2)); |
| 153 | let num = ((b0 + b1 * cos1 + b2 * cos2).powi(2) + (b1 * sin1 + b2 * sin2).powi(2)).sqrt(); |
| 154 | |
| 155 | |
| 156 | |
| 157 | let den = ((1.0 + a1 * cos1 + a2 * cos2).powi(2) + (a1 * sin1 + a2 * sin2).powi(2)) |
| 158 | .sqrt() |
| 159 | .max(1e-12); |
| 160 | (20.0 * (num / den).log10()) as f32 |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | const DENORMAL_FLOOR: f32 = 1e-20; |
| 168 | |
| 169 | |
| 170 | |
| 171 | pub struct EqState { |
| 172 | sample_rate: u32, |
| 173 | channels: usize, |
| 174 | coeffs: Vec<Coeffs>, |
| 175 | |
| 176 | state: Vec<[f32; 2]>, |
| 177 | |
| 178 | |
| 179 | identity: bool, |
| 180 | } |
| 181 | |
| 182 | impl EqState { |
| 183 | |
| 184 | |
| 185 | pub fn new(params: &EqParams, sample_rate: u32, channels: u16) -> Self { |
| 186 | let mut eq = Self { |
| 187 | sample_rate, |
| 188 | channels: (channels as usize).max(1), |
| 189 | coeffs: Vec::new(), |
| 190 | state: Vec::new(), |
| 191 | identity: true, |
| 192 | }; |
| 193 | eq.set_params(params); |
| 194 | eq |
| 195 | } |
| 196 | |
| 197 | |
| 198 | |
| 199 | pub fn set_params(&mut self, params: &EqParams) { |
| 200 | self.identity = params.is_identity(); |
| 201 | self.coeffs.clear(); |
| 202 | self.coeffs.extend( |
| 203 | params |
| 204 | .bands |
| 205 | .iter() |
| 206 | .map(|b| Coeffs::new(b, self.sample_rate)), |
| 207 | ); |
| 208 | self.state |
| 209 | .resize(self.coeffs.len() * self.channels, [0.0; 2]); |
| 210 | } |
| 211 | |
| 212 | |
| 213 | |
| 214 | pub fn reset(&mut self) { |
| 215 | self.state.fill([0.0; 2]); |
| 216 | } |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | |
| 222 | |
| 223 | pub fn process(&mut self, interleaved: &mut [f32]) { |
| 224 | if self.identity || self.coeffs.is_empty() { |
| 225 | return; |
| 226 | } |
| 227 | let channels = self.channels; |
| 228 | for (band, c) in self.coeffs.iter().enumerate() { |
| 229 | let state = &mut self.state[band * channels..][..channels]; |
| 230 | for frame in interleaved.chunks_exact_mut(channels) { |
| 231 | for (ch, x) in frame.iter_mut().enumerate() { |
| 232 | let s = &mut state[ch]; |
| 233 | let y = c.b0 * *x + s[0]; |
| 234 | s[0] = c.b1 * *x - c.a1 * y + s[1]; |
| 235 | s[1] = c.b2 * *x - c.a2 * y; |
| 236 | if s[0].abs() < DENORMAL_FLOOR { |
| 237 | s[0] = 0.0; |
| 238 | } |
| 239 | if s[1].abs() < DENORMAL_FLOOR { |
| 240 | s[1] = 0.0; |
| 241 | } |
| 242 | *x = y; |
| 243 | } |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | |
| 249 | #[cfg(test)] |
| 250 | mod tests { |
| 251 | use std::f32::consts::TAU; |
| 252 | |
| 253 | use super::{Band, BandKind, EqParams, EqState}; |
| 254 | |
| 255 | const FS: u32 = 48_000; |
| 256 | |
| 257 | fn peak(freq_hz: f32, gain_db: f32, q: f32) -> EqParams { |
| 258 | EqParams { |
| 259 | bands: vec![Band { |
| 260 | freq_hz, |
| 261 | gain_db, |
| 262 | q, |
| 263 | kind: BandKind::Peak, |
| 264 | }], |
| 265 | } |
| 266 | } |
| 267 | |
| 268 | fn sine(freq_hz: f32, frames: usize, channels: usize) -> Vec<f32> { |
| 269 | (0..frames * channels) |
| 270 | .map(|i| (TAU * freq_hz * (i / channels) as f32 / FS as f32).sin()) |
| 271 | .collect() |
| 272 | } |
| 273 | |
| 274 | |
| 275 | fn rms(samples: &[f32]) -> f32 { |
| 276 | let tail = &samples[samples.len() / 2..]; |
| 277 | (tail.iter().map(|v| v * v).sum::<f32>() / tail.len() as f32).sqrt() |
| 278 | } |
| 279 | |
| 280 | fn db(measured: f32, reference: f32) -> f32 { |
| 281 | 20.0 * (measured / reference).log10() |
| 282 | } |
| 283 | |
| 284 | #[test] |
| 285 | fn flat_params_pass_samples_through_bit_identical() { |
| 286 | let input = sine(440.0, 4800, 2); |
| 287 | let mut out = input.clone(); |
| 288 | EqState::new(&EqParams::default_layout(), FS, 2).process(&mut out); |
| 289 | assert_eq!(out, input, "a flat EQ must not touch the samples at all"); |
| 290 | |
| 291 | |
| 292 | |
| 293 | let mut params = EqParams::default_layout(); |
| 294 | params.bands[2].q = 4.0; |
| 295 | assert!(params.is_identity()); |
| 296 | } |
| 297 | |
| 298 | #[test] |
| 299 | fn a_band_moves_its_own_center_and_leaves_two_octaves_away_alone() { |
| 300 | for gain in [6.0, -6.0] { |
| 301 | let center = sine(1000.0, 48_000, 1); |
| 302 | let mut out = center.clone(); |
| 303 | EqState::new(&peak(1000.0, gain, 1.0), FS, 1).process(&mut out); |
| 304 | let at_center = db(rms(&out), rms(¢er)); |
| 305 | assert!( |
| 306 | (at_center - gain).abs() < 0.5, |
| 307 | "1 kHz sine through a {gain:+} dB band at 1 kHz measured {at_center:+.2} dB" |
| 308 | ); |
| 309 | |
| 310 | for off in [250.0, 4000.0] { |
| 311 | let away = sine(off, 48_000, 1); |
| 312 | let mut out = away.clone(); |
| 313 | EqState::new(&peak(1000.0, gain, 1.0), FS, 1).process(&mut out); |
| 314 | let leak = db(rms(&out), rms(&away)); |
| 315 | assert!( |
| 316 | leak.abs() < 1.0, |
| 317 | "{off} Hz is two octaves off but moved {leak:+.2} dB" |
| 318 | ); |
| 319 | } |
| 320 | } |
| 321 | } |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | #[test] |
| 327 | fn the_drawn_response_is_the_gain_the_samples_actually_get() { |
| 328 | let mut params = EqParams::default_layout(); |
| 329 | params.bands[0].gain_db = -8.0; |
| 330 | params.bands[2].gain_db = 10.0; |
| 331 | params.bands[2].q = 1.4; |
| 332 | params.bands[4].gain_db = 5.0; |
| 333 | |
| 334 | |
| 335 | |
| 336 | for freq in [ |
| 337 | 40.0, 80.0, 250.0, 600.0, 1000.0, 2000.0, 4000.0, 12000.0, 16000.0, |
| 338 | ] { |
| 339 | let input = sine(freq, 48_000, 1); |
| 340 | let mut out = input.clone(); |
| 341 | EqState::new(¶ms, FS, 1).process(&mut out); |
| 342 | let measured = db(rms(&out), rms(&input)); |
| 343 | let drawn = params.response_db(freq, FS); |
| 344 | assert!( |
| 345 | (measured - drawn).abs() < 0.5, |
| 346 | "{freq} Hz: curve says {drawn:+.2} dB, samples measured {measured:+.2} dB" |
| 347 | ); |
| 348 | } |
| 349 | |
| 350 | |
| 351 | let flat = EqParams::default_layout(); |
| 352 | assert!(flat.response_db(1000.0, FS).abs() < 1e-4); |
| 353 | assert!(params.response_db(FS as f32, FS).is_finite()); |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn ten_seconds_of_noise_through_every_band_boosted_stays_bounded() { |
| 358 | let mut params = EqParams::default_layout(); |
| 359 | for band in &mut params.bands { |
| 360 | band.gain_db = 12.0; |
| 361 | } |
| 362 | let mut eq = EqState::new(¶ms, FS, 2); |
| 363 | |
| 364 | |
| 365 | let mut seed = 0x2545_f491_4f6c_dd1du64; |
| 366 | let mut noise = || { |
| 367 | seed ^= seed << 13; |
| 368 | seed ^= seed >> 7; |
| 369 | seed ^= seed << 17; |
| 370 | (seed >> 40) as f32 / 8_388_608.0 - 1.0 |
| 371 | }; |
| 372 | |
| 373 | let mut peak = 0.0f32; |
| 374 | |
| 375 | |
| 376 | for _ in 0..(10 * FS as usize / 1024) { |
| 377 | let mut block: Vec<f32> = (0..1024 * 2).map(|_| noise()).collect(); |
| 378 | eq.process(&mut block); |
| 379 | for v in block { |
| 380 | assert!(v.is_finite(), "EQ output went to {v}"); |
| 381 | peak = peak.max(v.abs()); |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | |
| 386 | assert!( |
| 387 | (1.0..20.0).contains(&peak), |
| 388 | "peak {peak} out of the plausible band for +12 dB x5" |
| 389 | ); |
| 390 | } |
| 391 | |
| 392 | #[test] |
| 393 | fn a_decaying_tail_leaves_the_state_at_a_hard_zero() { |
| 394 | let mut params = EqParams::default_layout(); |
| 395 | params.bands[1].gain_db = 9.0; |
| 396 | let mut eq = EqState::new(¶ms, FS, 2); |
| 397 | |
| 398 | let mut decay: Vec<f32> = (0..4800 * 2) |
| 399 | .map(|i| 0.9f32.powi(i / 2) * if i % 2 == 0 { 1.0 } else { -1.0 }) |
| 400 | .collect(); |
| 401 | eq.process(&mut decay); |
| 402 | let mut silence = vec![0.0f32; 4800 * 2]; |
| 403 | eq.process(&mut silence); |
| 404 | |
| 405 | for (i, s) in eq.state.iter().enumerate() { |
| 406 | assert!( |
| 407 | s[0] == 0.0 && s[1] == 0.0, |
| 408 | "state {i} still holds {s:?} after a decayed tail — denormal territory" |
| 409 | ); |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | #[test] |
| 414 | fn an_impulse_in_the_left_channel_never_reaches_the_right() { |
| 415 | let mut params = EqParams::default_layout(); |
| 416 | params.bands[3].gain_db = -10.0; |
| 417 | let mut eq = EqState::new(¶ms, FS, 2); |
| 418 | |
| 419 | let mut buf = vec![0.0f32; 512 * 2]; |
| 420 | buf[0] = 1.0; |
| 421 | eq.process(&mut buf); |
| 422 | |
| 423 | assert!(buf[2] != 0.0, "the left channel should be ringing"); |
| 424 | for (frame, pair) in buf.chunks_exact(2).enumerate() { |
| 425 | assert_eq!( |
| 426 | pair[1], 0.0, |
| 427 | "frame {frame}: right channel picked up {pair:?}" |
| 428 | ); |
| 429 | } |
| 430 | } |
| 431 | } |