forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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