forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBef5832fTahinli3 months ago597 commits

eq.rs431 lines, 16.0 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 and shelving 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.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum BandKind {
23 LowShelf,
24 Peak,
25 HighShelf,
26}
27
28/// One band. Plain data with no invariants of its own: out-of-range values are
29/// clamped when coefficients are built, so a deserializer can hand this over
30/// unchecked.
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct Band {
33 pub freq_hz: f32,
34 pub gain_db: f32,
35 /// Bandwidth for a peak, slope for a shelf. 0.707 is the flat-shelf value.
36 pub q: f32,
37 pub kind: BandKind,
38}
39
40/// A segment's equalizer setting: the bands, in cascade order.
41#[derive(Debug, Clone, PartialEq, Default)]
42pub struct EqParams {
43 pub bands: Vec<Band>,
44}
45
46impl EqParams {
47 /// The five-band default described in the module docs, all gains flat.
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 /// True when no band moves anything, so processing can be skipped outright.
67 pub fn is_identity(&self) -> bool {
68 self.bands.iter().all(|b| b.gain_db.abs() < 1e-4)
69 }
70
71 /// How much the cascade moves a sine at `freq_hz`, in dB — the curve a UI
72 /// draws. Read off the *same* [`Coeffs`] [`EqState`] filters with and
73 /// evaluated at `z = e^{jw}`, so a drawn curve cannot drift from what is
74 /// heard: there is one set of coefficients and one formula for both.
75 /// Cascaded sections multiply, so their dB add.
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/// Normalized biquad coefficients (a0 divided out).
85#[derive(Debug, Clone, Copy, Default)]
86struct Coeffs {
87 b0: f32,
88 b1: f32,
89 b2: f32,
90 a1: f32,
91 a2: f32,
92}
93
94impl Coeffs {
95 /// Cookbook peaking/shelving section for `band` at `sample_rate`.
96 fn new(band: &Band, sample_rate: u32) -> Self {
97 // A frequency at or past Nyquist has no cookbook answer (sin(w0) folds),
98 // and Q of zero divides by zero: clamp rather than reject, the caller's
99 // value came out of a text file.
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 /// |H(e^{jw})| in dB for this section at `freq_hz`. Past Nyquist there is
145 /// no answer to give, so the frequency clamps there like `f0` does.
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 // A stable section never puts the denominator at zero, but a hand-
155 // written file could; the floor keeps the curve finite rather than
156 // painting an infinity.
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/// Anything smaller than this is inaudible at any gain we allow, and letting it
165/// stay would drag the state into denormals — where a decaying tail costs tens
166/// of times what a live signal does on x86. Flushed to a hard zero instead.
167const DENORMAL_FLOOR: f32 = 1e-20;
168
169/// A running equalizer: the coefficients plus one filter memory per band per
170/// channel. Built off the UI thread, driven from the audio path.
171pub struct EqState {
172 sample_rate: u32,
173 channels: usize,
174 coeffs: Vec<Coeffs>,
175 /// `[s1, s2]` per (band, channel), band-major.
176 state: Vec<[f32; 2]>,
177 /// All-flat params: [`process`](EqState::process) is then a no-op and the
178 /// samples come out bit-identical.
179 identity: bool,
180}
181
182impl EqState {
183 /// Allocates coefficients and filter memory for `params`. `channels` is the
184 /// interleave width of the buffers [`process`](EqState::process) will see.
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 /// Recomputes coefficients for edited params, keeping the filter memory so a
198 /// live segment does not click. Allocates — a UI edit, never the RT path.
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 /// Drops the filter memory: for a seek, where the samples either side of the
213 /// cut are unrelated and a carried tail would ring.
214 pub fn reset(&mut self) {
215 self.state.fill([0.0; 2]);
216 }
217
218 /// Filters `interleaved` in place, `channels` values per frame. Allocation-
219 /// free and branch-light: safe to call from the feeder.
220 ///
221 /// A trailing partial frame is left alone rather than filtered into the
222 /// wrong channel's state.
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)]
250mod 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 /// RMS of the second half only: the first half is the filter's transient.
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 // ...and an explicitly built cascade of 0 dB bands is flat too, which is
292 // the case a serialized "EQ enabled, nothing moved" segment hits.
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(&center));
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 /// The curve a card draws is the filter a listener hears: a sine measured
324 /// through `process` lands where `response_db` said it would, at the band
325 /// centres and between them, boosted and cut.
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; // 80 Hz low shelf
330 params.bands[2].gain_db = 10.0; // 1 kHz peak
331 params.bands[2].q = 1.4;
332 params.bands[4].gain_db = 5.0; // 12 kHz high shelf
333
334 // Centres, the slopes between them, and the two ends of the axis the
335 // card draws -- a curve is wrong in the gaps or nowhere.
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(&params, 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 // Flat draws flat, and nothing is drawn past Nyquist.
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(&params, FS, 2);
363
364 // xorshift: a fixed white-noise source, no dev-dependency.
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 // Fed in 1024-frame blocks, as the feeder would: state must survive the
375 // block boundary, so a per-call reset would show up as clicks here.
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 // +12 dB on five overlapping bands is about 4x on the worst-case sum of
385 // a full-scale input; anything past that is instability, not gain.
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(&params, 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(&params, 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}