forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBc327308Tahinli26 days ago1014 commits

eq.rs663 lines, 26.5 KiBHistoryRawDownload
1//! Per-segment audio equalizer: a cascade of RBJ biquads applied engine-side by
2//! sample math. The effect has to live in our own samples, never in a device
3//! property — a daemon-side gain would be invisible to an export and to anyone
4//! reading the graph, and the RT callback is allocation-free either way.
5//!
6//! Coefficients follow the Audio EQ Cookbook (Robert Bristow-Johnson,
7//! <https://www.w3.org/TR/audio-eq-cookbook/>), peaking, shelving and cut sections,
8//! run as transposed direct form II: two state words per band per channel, one
9//! multiply-add chain per sample, nothing to allocate.
10//!
11//! [`EqParams::default_layout`] is a five-band starting point — shelves at the
12//! edges (80 Hz, 12 kHz), where a peak would leave the last octave untouched,
13//! and peaks at 250 Hz / 1 kHz / 4 kHz for mud, presence and air. It is only a
14//! default: band count, frequency and kind are data, so a segment can carry any
15//! layout the .edith file cares to write.
16
17use std::f64::consts::PI;
18
19/// Shape of one band's response. Shelves tilt everything past their corner;
20/// a peak is local; a cut removes everything past its corner. A cut is a
21/// second-order filter at the band's frequency with the band's Q, and ignores
22/// the band's gain -- it has no level to set, only a corner to put.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum BandKind {
25 LowShelf,
26 Peak,
27 HighShelf,
28 /// High-pass: removes what is below the corner (rumble, mic handling).
29 LowCut,
30 /// Low-pass: removes what is above the corner (hiss, air).
31 HighCut,
32}
33
34/// One band. Plain data with no invariants of its own: out-of-range values are
35/// clamped when coefficients are built, so a deserializer can hand this over
36/// unchecked.
37#[derive(Debug, Clone, Copy, PartialEq)]
38pub struct Band {
39 pub freq_hz: f32,
40 pub gain_db: f32,
41 /// Bandwidth for a peak, slope for a shelf. 0.707 is the flat-shelf value.
42 pub q: f32,
43 pub kind: BandKind,
44}
45
46/// A segment's equalizer setting: the bands, in cascade order.
47#[derive(Debug, Clone, PartialEq, Default)]
48pub struct EqParams {
49 pub bands: Vec<Band>,
50}
51
52impl EqParams {
53 /// The five-band default described in the module docs, all gains flat.
54 pub fn default_layout() -> Self {
55 let band = |freq_hz, kind| Band {
56 freq_hz,
57 gain_db: 0.0,
58 q: 0.707,
59 kind,
60 };
61 Self {
62 bands: vec![
63 band(80.0, BandKind::LowShelf),
64 band(250.0, BandKind::Peak),
65 band(1000.0, BandKind::Peak),
66 band(4000.0, BandKind::Peak),
67 band(12000.0, BandKind::HighShelf),
68 ],
69 }
70 }
71
72 /// True when no band moves anything, so processing can be skipped outright.
73 /// A cut always moves something, whatever its gain says, so it is never
74 /// identity: a cut band the listener put down is not a flat curve.
75 pub fn is_identity(&self) -> bool {
76 self.bands.iter().all(|b| match b.kind {
77 BandKind::LowCut | BandKind::HighCut => false,
78 _ => b.gain_db.abs() < 1e-4,
79 })
80 }
81
82 /// How much the cascade moves a sine at `freq_hz`, in dB — the curve a UI
83 /// draws. Read off the *same* [`Coeffs`] [`EqState`] filters with and
84 /// evaluated at `z = e^{jw}`, so a drawn curve cannot drift from what is
85 /// heard: there is one set of coefficients and one formula for both.
86 /// Cascaded sections multiply, so their dB add.
87 pub fn response_db(&self, freq_hz: f32, sample_rate: u32) -> f32 {
88 self.bands
89 .iter()
90 .map(|b| Coeffs::new(b, sample_rate).magnitude_db(freq_hz, sample_rate))
91 .sum()
92 }
93}
94
95/// Normalized biquad coefficients (a0 divided out).
96#[derive(Debug, Clone, Copy, Default)]
97struct Coeffs {
98 b0: f32,
99 b1: f32,
100 b2: f32,
101 a1: f32,
102 a2: f32,
103}
104
105/// How far a band's gain may go either side of flat, in dB: the bound
106/// [`Coeffs::new`] holds the one field [`Band`]'s doc says is clamped for it.
107///
108/// Deliberately far past anything a card offers -- the UI's own limit is a
109/// card decision, not a project one, and a project is allowed to be more
110/// extreme than the control that set it -- but bounded all the same, because
111/// the gain is not a magnitude anywhere else in this struct: it enters as
112/// `a = 10^(gain_db/40)`, and `a` drives the peak section's pole radius toward
113/// the unit circle. A few hundred dB puts the poles *on* it, and a section
114/// whose poles are on the unit circle does not decay, it rings -- growing the
115/// samples without limit until the device clamp and the export's own [-1, 1]
116/// turn the whole clip into a full-scale square. Past 10_000 dB `a` is not even
117/// finite any more and the coefficients come out `inf`.
118///
119/// 40 dB is the ceiling because it is where the arithmetic stays comfortably
120/// inside f32 (a linear gain of 100) while being louder than any boost a
121/// mixing console offers. Clamped, not refused: the struct's contract is that
122/// a deserializer may hand this over unchecked, and a project that says
123/// +400 dB gets +40 dB rather than a project that will not open.
124pub const MAX_BAND_GAIN_DB: f32 = 40.0;
125/// ...and the floor, the same distance the other way. Symmetric because a
126/// wide cut and a wide boost are the same filter run at two gains.
127pub const MIN_BAND_GAIN_DB: f32 = -40.0;
128
129impl Coeffs {
130 /// Cookbook peaking, shelving or cut section for `band` at `sample_rate`.
131 fn new(band: &Band, sample_rate: u32) -> Self {
132 // A frequency at or past Nyquist has no cookbook answer (sin(w0) folds),
133 // Q of zero divides by zero, and a gain of a few hundred dB walks the
134 // peak's poles onto the unit circle: clamp rather than reject, the
135 // caller's value came out of a text file. The gain is the fourth of
136 // these four clamps, and the one the struct's own doc promised.
137 let fs = f64::from(sample_rate.max(1));
138 let f0 = f64::from(band.freq_hz).clamp(1.0, fs * 0.49);
139 let q = f64::from(band.q).clamp(0.05, 40.0);
140 let gain =
141 f64::from(band.gain_db).clamp(f64::from(MIN_BAND_GAIN_DB), f64::from(MAX_BAND_GAIN_DB));
142 let a = 10f64.powf(gain / 40.0);
143 let w0 = 2.0 * PI * f0 / fs;
144 let (sin_w0, cos_w0) = (w0.sin(), w0.cos());
145 let alpha = sin_w0 / (2.0 * q);
146 let two_sqrt_a_alpha = 2.0 * a.sqrt() * alpha;
147
148 let (b0, b1, b2, a0, a1, a2) = match band.kind {
149 BandKind::Peak => (
150 1.0 + alpha * a,
151 -2.0 * cos_w0,
152 1.0 - alpha * a,
153 1.0 + alpha / a,
154 -2.0 * cos_w0,
155 1.0 - alpha / a,
156 ),
157 BandKind::LowShelf => (
158 a * ((a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha),
159 2.0 * a * ((a - 1.0) - (a + 1.0) * cos_w0),
160 a * ((a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha),
161 (a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha,
162 -2.0 * ((a - 1.0) + (a + 1.0) * cos_w0),
163 (a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha,
164 ),
165 BandKind::HighShelf => (
166 a * ((a + 1.0) + (a - 1.0) * cos_w0 + two_sqrt_a_alpha),
167 -2.0 * a * ((a - 1.0) + (a + 1.0) * cos_w0),
168 a * ((a + 1.0) + (a - 1.0) * cos_w0 - two_sqrt_a_alpha),
169 (a + 1.0) - (a - 1.0) * cos_w0 + two_sqrt_a_alpha,
170 2.0 * ((a - 1.0) - (a + 1.0) * cos_w0),
171 (a + 1.0) - (a - 1.0) * cos_w0 - two_sqrt_a_alpha,
172 ),
173 // RBJ high-pass and low-pass; the gain never enters them.
174 BandKind::LowCut => (
175 (1.0 + cos_w0) / 2.0,
176 -(1.0 + cos_w0),
177 (1.0 + cos_w0) / 2.0,
178 1.0 + alpha,
179 -2.0 * cos_w0,
180 1.0 - alpha,
181 ),
182 BandKind::HighCut => (
183 (1.0 - cos_w0) / 2.0,
184 1.0 - cos_w0,
185 (1.0 - cos_w0) / 2.0,
186 1.0 + alpha,
187 -2.0 * cos_w0,
188 1.0 - alpha,
189 ),
190 };
191 Self {
192 b0: (b0 / a0) as f32,
193 b1: (b1 / a0) as f32,
194 b2: (b2 / a0) as f32,
195 a1: (a1 / a0) as f32,
196 a2: (a2 / a0) as f32,
197 }
198 }
199
200 /// |H(e^{jw})| in dB for this section at `freq_hz`. Past Nyquist there is
201 /// no answer to give, so the frequency clamps there like `f0` does.
202 fn magnitude_db(&self, freq_hz: f32, sample_rate: u32) -> f32 {
203 let fs = f64::from(sample_rate.max(1));
204 let w = 2.0 * PI * f64::from(freq_hz).clamp(0.0, fs * 0.5) / fs;
205 let (sin1, cos1) = w.sin_cos();
206 let (sin2, cos2) = (2.0 * w).sin_cos();
207 let (b0, b1, b2) = (f64::from(self.b0), f64::from(self.b1), f64::from(self.b2));
208 let (a1, a2) = (f64::from(self.a1), f64::from(self.a2));
209 let num = ((b0 + b1 * cos1 + b2 * cos2).powi(2) + (b1 * sin1 + b2 * sin2).powi(2)).sqrt();
210 // A stable section never puts the denominator at zero, but a hand-
211 // written file could; the floor keeps the curve finite rather than
212 // painting an infinity.
213 let den = ((1.0 + a1 * cos1 + a2 * cos2).powi(2) + (a1 * sin1 + a2 * sin2).powi(2))
214 .sqrt()
215 .max(1e-12);
216 (20.0 * (num / den).log10()) as f32
217 }
218}
219
220/// Anything smaller than this is inaudible at any gain we allow, and letting it
221/// stay would drag the state into denormals — where a decaying tail costs tens
222/// of times what a live signal does on x86. Flushed to a hard zero instead.
223const DENORMAL_FLOOR: f32 = 1e-20;
224
225/// A running equalizer: the coefficients plus one filter memory per band per
226/// channel. Built off the UI thread, driven from the audio path.
227pub struct EqState {
228 sample_rate: u32,
229 channels: usize,
230 coeffs: Vec<Coeffs>,
231 /// `[s1, s2]` per (band, channel), band-major.
232 state: Vec<[f32; 2]>,
233 /// All-flat params: [`process`](EqState::process) is then a no-op and the
234 /// samples come out bit-identical.
235 identity: bool,
236}
237
238impl EqState {
239 /// Allocates coefficients and filter memory for `params`. `channels` is the
240 /// interleave width of the buffers [`process`](EqState::process) will see.
241 pub fn new(params: &EqParams, sample_rate: u32, channels: u16) -> Self {
242 let mut eq = Self {
243 sample_rate,
244 channels: (channels as usize).max(1),
245 coeffs: Vec::new(),
246 state: Vec::new(),
247 identity: true,
248 };
249 eq.set_params(params);
250 eq
251 }
252
253 /// Recomputes coefficients for edited params, keeping the filter memory so a
254 /// live segment does not click. Allocates — a UI edit, never the RT path.
255 pub fn set_params(&mut self, params: &EqParams) {
256 self.identity = params.is_identity();
257 self.coeffs.clear();
258 self.coeffs.extend(
259 params
260 .bands
261 .iter()
262 .map(|b| Coeffs::new(b, self.sample_rate)),
263 );
264 self.state
265 .resize(self.coeffs.len() * self.channels, [0.0; 2]);
266 }
267
268 /// Drops the filter memory: for a seek, where the samples either side of the
269 /// cut are unrelated and a carried tail would ring.
270 pub fn reset(&mut self) {
271 self.state.fill([0.0; 2]);
272 }
273
274 /// Filters `interleaved` in place, `channels` values per frame. Allocation-
275 /// free and branch-light: safe to call from the feeder.
276 ///
277 /// A trailing partial frame is left alone rather than filtered into the
278 /// wrong channel's state.
279 pub fn process(&mut self, interleaved: &mut [f32]) {
280 if self.identity || self.coeffs.is_empty() {
281 return;
282 }
283 let channels = self.channels;
284 for (band, c) in self.coeffs.iter().enumerate() {
285 let state = &mut self.state[band * channels..][..channels];
286 for frame in interleaved.chunks_exact_mut(channels) {
287 for (ch, x) in frame.iter_mut().enumerate() {
288 let s = &mut state[ch];
289 let y = c.b0 * *x + s[0];
290 s[0] = c.b1 * *x - c.a1 * y + s[1];
291 s[1] = c.b2 * *x - c.a2 * y;
292 if s[0].abs() < DENORMAL_FLOOR {
293 s[0] = 0.0;
294 }
295 if s[1].abs() < DENORMAL_FLOOR {
296 s[1] = 0.0;
297 }
298 *x = y;
299 }
300 }
301 }
302 }
303}
304
305#[cfg(test)]
306mod tests {
307 use std::f32::consts::TAU;
308
309 use super::{Band, BandKind, EqParams, EqState};
310
311 const FS: u32 = 48_000;
312
313 fn peak(freq_hz: f32, gain_db: f32, q: f32) -> EqParams {
314 EqParams {
315 bands: vec![Band {
316 freq_hz,
317 gain_db,
318 q,
319 kind: BandKind::Peak,
320 }],
321 }
322 }
323
324 fn sine(freq_hz: f32, frames: usize, channels: usize) -> Vec<f32> {
325 (0..frames * channels)
326 .map(|i| (TAU * freq_hz * (i / channels) as f32 / FS as f32).sin())
327 .collect()
328 }
329
330 /// RMS of the second half only: the first half is the filter's transient.
331 fn rms(samples: &[f32]) -> f32 {
332 let tail = &samples[samples.len() / 2..];
333 (tail.iter().map(|v| v * v).sum::<f32>() / tail.len() as f32).sqrt()
334 }
335
336 fn db(measured: f32, reference: f32) -> f32 {
337 20.0 * (measured / reference).log10()
338 }
339
340 #[test]
341 fn flat_params_pass_samples_through_bit_identical() {
342 let input = sine(440.0, 4800, 2);
343 let mut out = input.clone();
344 EqState::new(&EqParams::default_layout(), FS, 2).process(&mut out);
345 assert_eq!(out, input, "a flat EQ must not touch the samples at all");
346
347 // ...and an explicitly built cascade of 0 dB bands is flat too, which is
348 // the case a serialized "EQ enabled, nothing moved" segment hits.
349 let mut params = EqParams::default_layout();
350 params.bands[2].q = 4.0;
351 assert!(params.is_identity());
352 }
353
354 #[test]
355 fn a_band_moves_its_own_center_and_leaves_two_octaves_away_alone() {
356 for gain in [6.0, -6.0] {
357 let center = sine(1000.0, 48_000, 1);
358 let mut out = center.clone();
359 EqState::new(&peak(1000.0, gain, 1.0), FS, 1).process(&mut out);
360 let at_center = db(rms(&out), rms(&center));
361 assert!(
362 (at_center - gain).abs() < 0.5,
363 "1 kHz sine through a {gain:+} dB band at 1 kHz measured {at_center:+.2} dB"
364 );
365
366 for off in [250.0, 4000.0] {
367 let away = sine(off, 48_000, 1);
368 let mut out = away.clone();
369 EqState::new(&peak(1000.0, gain, 1.0), FS, 1).process(&mut out);
370 let leak = db(rms(&out), rms(&away));
371 assert!(
372 leak.abs() < 1.0,
373 "{off} Hz is two octaves off but moved {leak:+.2} dB"
374 );
375 }
376 }
377 }
378
379 /// The curve a card draws is the filter a listener hears: a sine measured
380 /// through `process` lands where `response_db` said it would, at the band
381 /// centres and between them, boosted and cut.
382 #[test]
383 fn the_drawn_response_is_the_gain_the_samples_actually_get() {
384 let mut params = EqParams::default_layout();
385 params.bands[0].gain_db = -8.0; // 80 Hz low shelf
386 params.bands[2].gain_db = 10.0; // 1 kHz peak
387 params.bands[2].q = 1.4;
388 params.bands[4].gain_db = 5.0; // 12 kHz high shelf
389
390 // Centres, the slopes between them, and the two ends of the axis the
391 // card draws -- a curve is wrong in the gaps or nowhere.
392 for freq in [
393 40.0, 80.0, 250.0, 600.0, 1000.0, 2000.0, 4000.0, 12000.0, 16000.0,
394 ] {
395 let input = sine(freq, 48_000, 1);
396 let mut out = input.clone();
397 EqState::new(&params, FS, 1).process(&mut out);
398 let measured = db(rms(&out), rms(&input));
399 let drawn = params.response_db(freq, FS);
400 assert!(
401 (measured - drawn).abs() < 0.5,
402 "{freq} Hz: curve says {drawn:+.2} dB, samples measured {measured:+.2} dB"
403 );
404 }
405
406 // Flat draws flat, and nothing is drawn past Nyquist.
407 let flat = EqParams::default_layout();
408 assert!(flat.response_db(1000.0, FS).abs() < 1e-4);
409 assert!(params.response_db(FS as f32, FS).is_finite());
410 }
411
412 #[test]
413 fn ten_seconds_of_noise_through_every_band_boosted_stays_bounded() {
414 let mut params = EqParams::default_layout();
415 for band in &mut params.bands {
416 band.gain_db = 12.0;
417 }
418 let mut eq = EqState::new(&params, FS, 2);
419
420 // xorshift: a fixed white-noise source, no dev-dependency.
421 let mut seed = 0x2545_f491_4f6c_dd1du64;
422 let mut noise = || {
423 seed ^= seed << 13;
424 seed ^= seed >> 7;
425 seed ^= seed << 17;
426 (seed >> 40) as f32 / 8_388_608.0 - 1.0
427 };
428
429 let mut peak = 0.0f32;
430 // Fed in 1024-frame blocks, as the feeder would: state must survive the
431 // block boundary, so a per-call reset would show up as clicks here.
432 for _ in 0..(10 * FS as usize / 1024) {
433 let mut block: Vec<f32> = (0..1024 * 2).map(|_| noise()).collect();
434 eq.process(&mut block);
435 for v in block {
436 assert!(v.is_finite(), "EQ output went to {v}");
437 peak = peak.max(v.abs());
438 }
439 }
440 // +12 dB on five overlapping bands is about 4x on the worst-case sum of
441 // a full-scale input; anything past that is instability, not gain.
442 assert!(
443 (1.0..20.0).contains(&peak),
444 "peak {peak} out of the plausible band for +12 dB x5"
445 );
446 }
447
448 #[test]
449 fn a_decaying_tail_leaves_the_state_at_a_hard_zero() {
450 let mut params = EqParams::default_layout();
451 params.bands[1].gain_db = 9.0;
452 let mut eq = EqState::new(&params, FS, 2);
453
454 let mut decay: Vec<f32> = (0..4800 * 2)
455 .map(|i| 0.9f32.powi(i / 2) * if i % 2 == 0 { 1.0 } else { -1.0 })
456 .collect();
457 eq.process(&mut decay);
458 let mut silence = vec![0.0f32; 4800 * 2];
459 eq.process(&mut silence);
460
461 for (i, s) in eq.state.iter().enumerate() {
462 assert!(
463 s[0] == 0.0 && s[1] == 0.0,
464 "state {i} still holds {s:?} after a decayed tail — denormal territory"
465 );
466 }
467 }
468
469 #[test]
470 fn an_impulse_in_the_left_channel_never_reaches_the_right() {
471 let mut params = EqParams::default_layout();
472 params.bands[3].gain_db = -10.0;
473 let mut eq = EqState::new(&params, FS, 2);
474
475 let mut buf = vec![0.0f32; 512 * 2];
476 buf[0] = 1.0;
477 eq.process(&mut buf);
478
479 assert!(buf[2] != 0.0, "the left channel should be ringing");
480 for (frame, pair) in buf.as_chunks::<2>().0.iter().enumerate() {
481 assert_eq!(
482 pair[1], 0.0,
483 "frame {frame}: right channel picked up {pair:?}"
484 );
485 }
486 }
487
488 /// A gain a `.edith` line can name, and the pole radius that comes of it.
489 ///
490 /// The invariant [`Band`] documents is that out-of-range values are clamped
491 /// when the coefficients are built, so a deserializer may hand one over
492 /// unchecked -- and three of the four fields were clamped at
493 /// [`Coeffs::new`] while `gain_db` was not. `a = 10^(gain_db/40)` feeds the
494 /// peak's `sqrt(a2/a0)` pole radius straight to 1 as the gain grows, and at
495 /// a few hundred dB the f32 rounding puts the poles *exactly* on the unit
496 /// circle: a marginally-stable section that rings for seconds, blowing up
497 /// the samples until the device clamp turns the whole clip into a
498 /// full-scale square (in monitoring and in the export alike). This is an
499 /// arithmetic claim about the pole radius, not an audibility claim: nothing
500 /// here says what the filter sounds like, only that it is stable.
501 ///
502 /// The poles are solved off the normalized coefficients, so this is the
503 /// filter the sample loop actually runs rather than a restatement of the
504 /// formula that built it.
505 #[test]
506 fn a_gain_a_file_can_name_leaves_the_poles_strictly_inside_the_unit_circle() {
507 for gain in [
508 12.0f32, 40.0, 100.0, 200.0, 400.0, 10_000.0, -200.0, -10_000.0,
509 ] {
510 let c = super::Coeffs::new(
511 &Band {
512 freq_hz: 1000.0,
513 gain_db: gain,
514 q: 1.0,
515 kind: BandKind::Peak,
516 },
517 FS,
518 );
519 // The poles of `z^2 + a1 z + a2`, solved: the number the sample
520 // loop's homogeneous solution is actually made of, and the only
521 // place a section's stability is decided. `radius` is the larger
522 // of the two, so a section is stable exactly when it is `< 1`.
523 let (a1, a2) = (c.a1 as f64, c.a2 as f64);
524 let disc = (a1 * a1 - 4.0 * a2).max(0.0).sqrt();
525 let radius = [(-a1 + disc) / 2.0, (-a1 - disc) / 2.0]
526 .into_iter()
527 .fold(0.0f64, |m, r| m.max(r.abs()));
528 assert!(
529 radius < 0.999,
530 "gain {gain} dB gives a pole radius of {radius:.9} -- \
531 the section rings instead of decaying"
532 );
533 assert!(
534 c.b0.is_finite() && c.b1.is_finite() && c.b2.is_finite(),
535 "gain {gain} dB produced non-finite coefficients {c:?}"
536 );
537 }
538 }
539
540 /// The same claim about the samples rather than the coefficients: a
541 /// full-scale burst through a band whose gain a file named, with the gain
542 /// far past the card's own 12 dB limit, has to come out at the gain the
543 /// clamp ceiling *is*. +40 dB is a linear gain of 100, so a full-scale
544 /// burst peaks at ~100 and that is the answer, not a fault; anything past
545 /// it is the section ringing rather than a band being loud. Pre-fix, 200 dB
546 /// and 400 dB are past it by orders of magnitude.
547 #[test]
548 fn a_gain_a_file_can_name_does_not_blow_the_samples_up() {
549 for gain in [40.0f32, 100.0, 200.0, 400.0, 10_000.0] {
550 let mut out = vec![0.0f32; 48_000 * 2];
551 // A full-scale 1 kHz burst for a tenth of a second, then silence:
552 // whatever the section rings into is what shows up after it.
553 for (i, o) in out.iter_mut().enumerate().take(4_800 * 2) {
554 *o = (TAU * 1000.0 * (i / 2) as f32 / FS as f32).sin();
555 }
556 EqState::new(&peak(1000.0, gain, 1.0), FS, 2).process(&mut out);
557 let peak = out.iter().fold(0.0f32, |m, v| m.max(v.abs()));
558 assert!(
559 peak.is_finite() && peak < 200.0,
560 "gain {gain} dB sent a full-scale burst to {peak}: the clamp ceiling is \
561 +40 dB, a linear gain of 100, and 200x that is a section ringing, not a band"
562 );
563 }
564 }
565
566 fn cut(kind: BandKind, freq_hz: f32) -> EqParams {
567 EqParams {
568 bands: vec![Band {
569 freq_hz,
570 gain_db: 0.0,
571 q: 0.707,
572 kind,
573 }],
574 }
575 }
576
577 /// A second-order cut attenuates well past its corner and passes well
578 /// above it (high-pass) or below it (low-pass): the response curve, not the
579 /// samples, so the corner and the slope are checked without transients.
580 #[test]
581 fn a_cut_attenuates_past_its_corner_and_passes_the_other_side() {
582 let low = cut(BandKind::LowCut, 1000.0);
583 assert!(
584 low.response_db(100.0, FS) < -30.0,
585 "high-pass at 1 kHz, 100 Hz"
586 );
587 assert!(
588 low.response_db(10_000.0, FS).abs() < 0.1,
589 "high-pass passes 10 kHz"
590 );
591
592 let high = cut(BandKind::HighCut, 1000.0);
593 assert!(
594 high.response_db(10_000.0, FS) < -30.0,
595 "low-pass at 1 kHz, 10 kHz"
596 );
597 assert!(
598 high.response_db(100.0, FS).abs() < 0.1,
599 "low-pass passes 100 Hz"
600 );
601
602 // Butterworth (Q 0.707) is -3 dB at the corner for either side.
603 for kind in [BandKind::LowCut, BandKind::HighCut] {
604 let at_corner = cut(kind, 1000.0).response_db(1000.0, FS);
605 assert!(
606 (at_corner + 3.0).abs() < 0.2,
607 "{kind:?} at its corner measured {at_corner:+.2} dB, want -3"
608 );
609 }
610 }
611
612 /// The same claim through the samples: a 50 Hz tone through a 1 kHz
613 /// high-pass is nearly gone, and a 10 kHz tone through a 1 kHz low-pass is.
614 #[test]
615 fn a_cut_removes_the_tone_it_names_from_the_samples() {
616 for (kind, freq, want_below) in [
617 (BandKind::LowCut, 50.0, -30.0),
618 (BandKind::HighCut, 10_000.0, -30.0),
619 ] {
620 let input = sine(freq, 48_000, 1);
621 let mut out = input.clone();
622 EqState::new(&cut(kind, 1000.0), FS, 1).process(&mut out);
623 let measured = db(rms(&out), rms(&input));
624 assert!(
625 measured < want_below,
626 "{kind:?} at 1 kHz left {freq} Hz at {measured:+.2} dB"
627 );
628 }
629 }
630
631 /// The gain is not a parameter of a cut: the same corner at +12 dB and at
632 /// -12 dB draws the same curve, and the drawn curve is what the samples get.
633 #[test]
634 fn a_cut_ignores_its_gain() {
635 for kind in [BandKind::LowCut, BandKind::HighCut] {
636 let flat = cut(kind, 1000.0);
637 let mut loud = flat.clone();
638 loud.bands[0].gain_db = 12.0;
639 let mut quiet = flat.clone();
640 quiet.bands[0].gain_db = -12.0;
641 for freq in [50.0, 300.0, 1000.0, 3000.0, 15_000.0] {
642 let want = flat.response_db(freq, FS);
643 assert_eq!(loud.response_db(freq, FS), want, "{kind:?} at {freq} Hz");
644 assert_eq!(quiet.response_db(freq, FS), want, "{kind:?} at {freq} Hz");
645 }
646 }
647 }
648
649 /// A cut is never identity, whatever gain it carries, so processing runs
650 /// and the samples do change. A peak at 0 dB still is.
651 #[test]
652 fn a_cut_band_is_never_identity() {
653 for kind in [BandKind::LowCut, BandKind::HighCut] {
654 let params = cut(kind, 1000.0);
655 assert!(!params.is_identity(), "{kind:?} at 0 dB reads as flat");
656 let input = sine(50.0, 4800, 1);
657 let mut out = input.clone();
658 EqState::new(&params, FS, 1).process(&mut out);
659 assert_ne!(out, input, "{kind:?} left the samples untouched");
660 }
661 assert!(peak(1000.0, 0.0, 1.0).is_identity());
662 }
663}