forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

eq_ui.rs320 lines, 13.6 KiBHistoryRawDownload
1//! The equalizer graph: its geometry, its analyser and its curve.
2
3use crate::*;
4
5/// Where a frequency sits across the graph, 0..1. Log, because an octave is an
6/// octave whether it is 40 Hz wide or 10 kHz wide -- a linear axis would spend
7/// three quarters of the card on the top two octaves and squeeze the bass, the
8/// half of the range people actually reach for, into nothing.
9pub(crate) fn eq_x(freq_hz: f32) -> f32 {
10 let span = (EQ_FREQ_HIGH / EQ_FREQ_LOW).log10();
11 ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.)
12}
13
14/// The frequency at a fraction across the graph -- [`eq_x`] backwards, which is
15/// how a drag and the curve's own sample points read one. Clamped to the axis
16/// either way, so a pointer that leaves the box stops at 20 Hz or 20 kHz.
17pub(crate) fn eq_freq(along: f32) -> f32 {
18 EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along.clamp(0., 1.))
19}
20
21/// The band an "add" makes: a flat peak half way -- in octaves, which is what
22/// the log axis draws -- between the picked band and whatever sits above it, so
23/// a new band lands in the gap on screen rather than on top of its neighbour.
24/// Above the topmost band the gap is the rest of the axis.
25pub(crate) fn inserted_band(bands: &[Band], after: usize) -> Band {
26 let below = bands.get(after).map_or(1000., |b| b.freq_hz);
27 let above = bands
28 .iter()
29 .map(|b| b.freq_hz)
30 .filter(|f| *f > below)
31 .min_by(f32::total_cmp)
32 .unwrap_or(EQ_FREQ_HIGH);
33 Band {
34 freq_hz: (below * above).sqrt().clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH),
35 gain_db: 0.,
36 // A shade narrower than the flat-shelf 0.707 the defaults use: a band
37 // someone asked for is a band they mean to aim, and a wide one aimed at
38 // 300 Hz is really a band at everything.
39 q: 1.,
40 kind: BandKind::Peak,
41 }
42}
43
44/// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle,
45/// so a cut reads as a dip below the line it is a cut from. The inverse of
46/// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a
47/// curve loaded from a file with a gain past the card's limit paints on the
48/// edge of the box rather than outside it.
49pub(crate) fn eq_y(gain_db: f32) -> f32 {
50 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2.
51}
52
53/// A frequency as the card writes it. Two decimals of a kHz at most, with the
54/// zeroes trimmed, so "1 kHz" stays "1 kHz" and a band nudged off it reads as
55/// 1.12 kHz rather than as the same "1 kHz" it was before the keystroke -- a
56/// number that does not move under an edit is worse than no number.
57#[cfg_attr(not(test), allow(dead_code, reason = "see band_label"))]
58pub(crate) fn eq_freq_label(freq_hz: f32) -> String {
59 if freq_hz < 1000. {
60 return format!("{freq_hz:.0} Hz");
61 }
62 let khz = format!("{:.2}", freq_hz / 1000.);
63 let khz = khz.trim_end_matches('0').trim_end_matches('.');
64 format!("{khz} kHz")
65}
66
67/// What a band row calls itself: the corner or centre frequency, and for a
68/// shelf the fact that it tilts everything past it -- which is the difference
69/// between "12 kHz" moving the last octave and moving one band inside it.
70#[cfg_attr(not(test), allow(dead_code, reason = "the band row now shows a number field; kept for the tests and the spoken name"))]
71pub(crate) fn band_label(band: &Band) -> String {
72 let freq = eq_freq_label(band.freq_hz);
73 match band.kind {
74 BandKind::LowShelf => format!("{freq} low shelf"),
75 BandKind::HighShelf => format!("{freq} high shelf"),
76 BandKind::LowCut => format!("{freq} low cut"),
77 BandKind::HighCut => format!("{freq} high cut"),
78 BandKind::Peak => freq,
79 }
80}
81
82/// The five kinds a band can be, in the order their chips lay out: the cuts at
83/// the ends and the shelves beside the bells. Each carries the sentence its
84/// chip's tooltip says, so a name like "shelf" is explained where it is picked.
85pub(crate) const EQ_KINDS: [(BandKind, &str, &str); 5] = [
86 (BandKind::LowCut, "Low cut", "Removes what is below the corner"),
87 (
88 BandKind::LowShelf,
89 "Low shelf",
90 "Lifts or cuts everything below the frequency",
91 ),
92 (BandKind::Peak, "Peak", "A bell around the frequency"),
93 (
94 BandKind::HighShelf,
95 "High shelf",
96 "Lifts or cuts everything above the frequency",
97 ),
98 (BandKind::HighCut, "High cut", "Removes what is above the corner"),
99];
100
101/// Whether a band's gain takes part in its response. A cut ignores it -- it has
102/// a corner to put and no level to set -- so the card does not draw its field.
103pub(crate) fn eq_takes_gain(kind: BandKind) -> bool {
104 !matches!(kind, BandKind::LowCut | BandKind::HighCut)
105}
106
107/// Which of a band's numbers have left the layout the clip opens on, as
108/// (frequency, gain, Q): what makes a number read ink1 rather than ink3. A band
109/// has no name but its place, so it is compared with the layout's band at the
110/// same index; one past the layout's end has no default to have left, so its
111/// frequency and Q count as moved. Every band's gain rests at flat.
112#[cfg_attr(not(test), allow(dead_code, reason = "see band_label"))]
113pub(crate) fn eq_band_changes(band: &Band, index: usize) -> (bool, bool, bool) {
114 const SAME: f32 = 1e-4;
115 let default = EqParams::default_layout().bands.get(index).copied();
116 let freq = default.is_none_or(|d| (band.freq_hz / d.freq_hz - 1.).abs() > SAME);
117 let gain = band.gain_db.abs() > SAME;
118 let q = default.is_none_or(|d| (band.q - d.q).abs() > SAME);
119 (freq, gain, q)
120}
121
122/// In-place radix-2 FFT of `re`/`im`, whose length must be a power of two.
123///
124/// Hand-written, and deliberately: a 1024-point transform once a frame is a
125/// few tens of microseconds of plain arithmetic, and a dependency for it would
126/// be a build cost this editor pays on every compile for one card's backdrop.
127pub(crate) fn fft(re: &mut [f32], im: &mut [f32]) {
128 let n = re.len();
129 // Decimation in time: the input is first put in bit-reversed order, after
130 // which the butterflies run over neighbours.
131 let mut j = 0usize;
132 for i in 1..n {
133 let mut bit = n >> 1;
134 while j & bit != 0 {
135 j ^= bit;
136 bit >>= 1;
137 }
138 j |= bit;
139 if i < j {
140 re.swap(i, j);
141 im.swap(i, j);
142 }
143 }
144 let mut span = 2;
145 while span <= n {
146 let step = std::f32::consts::TAU / span as f32;
147 for start in (0..n).step_by(span) {
148 for k in 0..span / 2 {
149 // e^{-i2πk/span}: the negative sign is the forward transform.
150 let (sin, cos) = (-step * k as f32).sin_cos();
151 let (a, b) = (start + k, start + k + span / 2);
152 let (tr, ti) = (cos * re[b] - sin * im[b], cos * im[b] + sin * re[b]);
153 re[b] = re[a] - tr;
154 im[b] = im[a] - ti;
155 re[a] += tr;
156 im[a] += ti;
157 }
158 }
159 span <<= 1;
160 }
161}
162
163/// The played signal as one height per curve point, 0 (silence) to 1 (the top
164/// of the box) -- the analyser the response curve is drawn on top of.
165///
166/// The newest [`EQ_FFT`] samples of the engine's tap, Hann-windowed so a tone
167/// that does not land on a bin centre is one hump rather than a smear across
168/// the axis. Each column takes the *loudest* bin between it and its
169/// neighbours: the axis is logarithmic, so one column near 20 Hz is a fraction
170/// of a bin while one near 20 kHz is hundreds, and averaging those would sink
171/// every peak up there into the noise beside it.
172///
173/// Empty -- nothing to draw -- for a tap too short to transform, which is what
174/// a session has just after a seek.
175///
176/// corner-cut: one transform length for the whole axis, so the bass end is a bin
177/// (47 Hz at 48 kHz) wide however many columns are drawn across it -- a 60 Hz
178/// hum and an 80 Hz one are the same hump down there. Upgrade path is the
179/// analyser every mastering EQ uses: two or three transforms of different
180/// lengths, each drawn over the octaves it resolves.
181pub(crate) fn eq_spectrum(samples: &[f32], sample_rate: u32) -> Vec<f32> {
182 if samples.len() < EQ_FFT {
183 return Vec::new();
184 }
185 let tail = &samples[samples.len() - EQ_FFT..];
186 let mut re: Vec<f32> = tail
187 .iter()
188 .enumerate()
189 .map(|(i, s)| {
190 let w = 0.5 * (1. - (std::f32::consts::TAU * i as f32 / EQ_FFT as f32).cos());
191 s * w
192 })
193 .collect();
194 let mut im = vec![0.; EQ_FFT];
195 fft(&mut re, &mut im);
196 // Magnitude per bin, scaled so a full-scale sine reads 0 dBFS: half the
197 // energy is in the mirrored half of the transform, and the Hann window
198 // takes another factor of two off.
199 let mags: Vec<f32> = (0..EQ_FFT / 2)
200 .map(|k| (re[k] * re[k] + im[k] * im[k]).sqrt() * 4. / EQ_FFT as f32)
201 .collect();
202 let bin_hz = sample_rate as f32 / EQ_FFT as f32;
203 let (floor, ceiling) = EQ_SPECTRUM_DB;
204 let at = |along: f32| EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along);
205 (0..=EQ_CURVE_STEPS)
206 .map(|step| {
207 let along = step as f32 / EQ_CURVE_STEPS as f32;
208 let half = 0.5 / EQ_CURVE_STEPS as f32;
209 // Bin 0 is DC and means nothing here, so the low end starts at 1.
210 let low = (at(along - half) / bin_hz).round().max(1.) as usize;
211 let high = (at(along + half) / bin_hz).round().max(1.) as usize;
212 let peak = (low..=high)
213 .filter_map(|k| mags.get(k))
214 .fold(0f32, |a, &b| a.max(b));
215 let db = 20. * peak.max(1e-9).log10();
216 ((db - floor) / (ceiling - floor)).clamp(0., 1.)
217 })
218 .collect()
219}
220
221/// The analyser drawn as one filled shape from the floor of the box.
222pub(crate) fn eq_spectrum_curve(levels: Vec<f32>) -> impl IntoElement {
223 canvas(
224 |_, _, _| (),
225 move |bounds, _, window, _| {
226 let (o, s) = (bounds.origin, bounds.size);
227 let last = levels.len().saturating_sub(1).max(1) as f32;
228 let mut path = PathBuilder::fill();
229 path.move_to(point(o.x, o.y + s.height));
230 for (i, level) in levels.iter().enumerate() {
231 path.line_to(point(
232 o.x + s.width * (i as f32 / last),
233 o.y + s.height * (1. - level),
234 ));
235 }
236 path.line_to(point(o.x + s.width, o.y + s.height));
237 path.close();
238 if let Ok(path) = path.build() {
239 window.paint_path(path, rgba(EQ_SPECTRUM_INK()));
240 }
241 },
242 )
243 .absolute()
244 .size_full()
245}
246
247/// The cascade's frequency response, drawn as one line across the graph, with
248/// each band's own response threaded dimly under it.
249///
250/// Every point comes from `EqParams::response_db`, which reads the very
251/// coefficients the samples are filtered through: the curve cannot drift from
252/// what is heard, because there is no second copy of the maths. A single band's
253/// thread is that same call on a cascade of one, so the two cannot disagree
254/// either -- and it is what makes a boost sitting inside a cut visible at all,
255/// where the sum alone would draw a flat line and say nothing.
256///
257/// corner-cut: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the
258/// curve then rides the edge of the box; upgrade = a wider dB axis with the
259/// handles and [`Player::drag_band`] rescaled to it.
260pub(crate) fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement {
261 canvas(
262 |_, _, _| (),
263 move |bounds, _, window, _| {
264 let (o, s) = (bounds.origin, bounds.size);
265 let line = |of: &EqParams| -> Vec<_> {
266 (0..=EQ_CURVE_STEPS)
267 .map(|step| {
268 let along = step as f32 / EQ_CURVE_STEPS as f32;
269 point(
270 o.x + s.width * along,
271 o.y + s.height * eq_y(of.response_db(eq_freq(along), sample_rate)),
272 )
273 })
274 .collect()
275 };
276 // One thread per band, first, so the sum is drawn over them.
277 for band in &params.bands {
278 let mut bell = PathBuilder::stroke(px(1.));
279 for (step, at) in line(&EqParams { bands: vec![*band] })
280 .into_iter()
281 .enumerate()
282 {
283 match step {
284 0 => bell.move_to(at),
285 _ => bell.line_to(at),
286 }
287 }
288 if let Ok(bell) = bell.build() {
289 window.paint_path(bell, rgba(EQ_BELL_INK()));
290 }
291 }
292 let points = line(&params);
293 // The area between the curve and 0 dB, closed along that line: a
294 // boost and a cut wind opposite ways around it, which is exactly
295 // what makes both of them fill and the flat parts stay empty.
296 let mut area = PathBuilder::fill();
297 area.move_to(point(o.x, o.y + s.height / 2.));
298 for at in &points {
299 area.line_to(*at);
300 }
301 area.line_to(point(o.x + s.width, o.y + s.height / 2.));
302 area.close();
303 if let Ok(area) = area.build() {
304 window.paint_path(area, rgba(EQ_FILL_INK()));
305 }
306 let mut path = PathBuilder::stroke(px(2.));
307 for (step, at) in points.into_iter().enumerate() {
308 match step {
309 0 => path.move_to(at),
310 _ => path.line_to(at),
311 }
312 }
313 if let Ok(path) = path.build() {
314 window.paint_path(path, rgb(ACCENT_PRIMARY()));
315 }
316 },
317 )
318 .absolute()
319 .size_full()
320}