The equalizer shows the sound it is shaping
Browse files at this commit540bbfd36f0268dc3a16952f90dc736e8a22c379Parent: 88fbed0- feat
- the equalizer shows the sound it is shaping
3 changed files +443 -39
- crates/app/src/keymap.rs +6 -1
- crates/app/src/main.rs +392 -38
- crates/engine/src/playback.rs +45 -0
crates/app/src/keymap.rsmodified+6 -1
| @@ -291,7 +291,7 @@ pub struct Fixed { | |||
| 291 | pub category: Category, | 291 | pub category: Category, |
| 292 | } | 292 | } |
| 293 | 293 | ||
| 294 | -pub const FIXED: [Fixed; 14] = [ | 294 | +pub const FIXED: [Fixed; 15] = [ |
| 295 | Fixed { | 295 | Fixed { |
| 296 | chord: "esc", | 296 | chord: "esc", |
| 297 | label: "Close this card or menu, or cancel a capture", | 297 | label: "Close this card or menu, or cancel a capture", |
| @@ -340,6 +340,11 @@ pub const FIXED: [Fixed; 14] = [ | |||
| 340 | label: "Flatten every band", | 340 | label: "Flatten every band", |
| 341 | category: Category::Audio, | 341 | category: Category::Audio, |
| 342 | }, | 342 | }, |
| 343 | + Fixed { | ||
| 344 | + chord: "s", | ||
| 345 | + label: "Show or hide the spectrum behind the curve", | ||
| 346 | + category: Category::Audio, | ||
| 347 | + }, | ||
| 343 | // The colour card's own three, which mean nothing outside it -- the same | 348 | // The colour card's own three, which mean nothing outside it -- the same |
| 344 | // card-local input the export card's digits are. | 349 | // card-local input the export card's digits are. |
| 345 | Fixed { | 350 | Fixed { |
crates/app/src/main.rsmodified+392 -38
| @@ -451,6 +451,36 @@ const EQ_TICKS: [(f32, &str); 5] = [ | |||
| 451 | (20000., "20k"), | 451 | (20000., "20k"), |
| 452 | ]; | 452 | ]; |
| 453 | 453 | ||
| 454 | +/// The gains the graph rules a line across, besides the 0 dB one it already | ||
| 455 | +/// had: half way to each limit, so a boost can be read as "about six" without | ||
| 456 | +/// counting pixels. The limits themselves are the box's own edges and are | ||
| 457 | +/// named at the corners instead. | ||
| 458 | +const EQ_DB_GRID: [f32; 2] = [6., -6.]; | ||
| 459 | + | ||
| 460 | +/// The grid's ink: above the card's background and below everything drawn on | ||
| 461 | +/// it, so the lines are a ruling rather than a thing to look at. | ||
| 462 | +const EQ_GRID: u32 = 0x3a3a3a; | ||
| 463 | + | ||
| 464 | +/// How many played samples one spectrum frame is transformed from. A power of | ||
| 465 | +/// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz | ||
| 466 | +/// is a 47 Hz bin, fine enough that the bass end is a shape and short enough | ||
| 467 | +/// (21 ms) that the analyser moves with the music. | ||
| 468 | +const EQ_FFT: usize = 1024; | ||
| 469 | + | ||
| 470 | +/// The level range the analyser is drawn across, floor to ceiling in dBFS: the | ||
| 471 | +/// bottom of the box is silence and the top is a bin at -12 dBFS, which is | ||
| 472 | +/// about where a mixed track's loudest band sits. A look, not a measurement -- | ||
| 473 | +/// the numbers on the axis are the curve's dB, never the analyser's. | ||
| 474 | +const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.); | ||
| 475 | + | ||
| 476 | +/// The analyser's fill, behind the curve: a dim blue-grey with enough alpha to | ||
| 477 | +/// read as a haze the accent line sits on top of. | ||
| 478 | +const EQ_SPECTRUM_INK: u32 = 0x7f95ad66; | ||
| 479 | + | ||
| 480 | +/// The area under the response curve, same accent as the line at a tenth of | ||
| 481 | +/// its weight: it is what makes a boost read as a hill rather than as a wire. | ||
| 482 | +const EQ_FILL_INK: u32 = 0x4a9eff26; | ||
| 483 | + | ||
| 454 | /// The colour card's four controls, in the order it lists them: what each is | 484 | /// The colour card's four controls, in the order it lists them: what each is |
| 455 | /// called and the range it moves in. The order is `ColorParams`' own, which is | 485 | /// called and the range it moves in. The order is `ColorParams`' own, which is |
| 456 | /// what [`color_band`] indexes. | 486 | /// what [`color_band`] indexes. |
| @@ -622,6 +652,11 @@ struct Player { | |||
| 622 | /// window position only, so this is what a press and a drag are read | 652 | /// window position only, so this is what a press and a drag are read |
| 623 | /// against ([`frac_along`], [`frac_down`]). | 653 | /// against ([`frac_along`], [`frac_down`]). |
| 624 | eq_graph: Rc<Cell<Bounds<Pixels>>>, | 654 | eq_graph: Rc<Cell<Bounds<Pixels>>>, |
| 655 | + /// Whether the analyser is drawn behind the curve. On by default -- what | ||
| 656 | + /// the curve is being *shaped against* is the point of drawing it -- and | ||
| 657 | + /// off with one press for anyone who would rather read the curve alone. | ||
| 658 | + /// Card state, not the project's: it changes nothing that plays. | ||
| 659 | + eq_spectrum: bool, | ||
| 625 | /// The colour card is up on this clip -- the lane it is on and its index | 660 | /// The colour card is up on this clip -- the lane it is on and its index |
| 626 | /// there. `None` when it is closed, which is the only place that state | 661 | /// there. `None` when it is closed, which is the only place that state |
| 627 | /// lives: the grade itself is the project's. | 662 | /// lives: the grade itself is the project's. |
| @@ -2816,6 +2851,11 @@ impl Render for Player { | |||
| 2816 | band.gain_db = 0.; | 2851 | band.gain_db = 0.; |
| 2817 | } | 2852 | } |
| 2818 | this.commit_eq(cx); | 2853 | this.commit_eq(cx); |
| 2854 | + } else if key == "s" { | ||
| 2855 | + // The analyser off and on. Nothing is committed: it is | ||
| 2856 | + // what the card *shows*, so it survives no further than | ||
| 2857 | + // this window. | ||
| 2858 | + this.eq_spectrum = !this.eq_spectrum; | ||
| 2819 | } else if let Ok(digit) = key.parse::<usize>() { | 2859 | } else if let Ok(digit) = key.parse::<usize>() { |
| 2820 | // 1-based, as the rows are numbered on screen; a digit | 2860 | // 1-based, as the rows are numbered on screen; a digit |
| 2821 | // past the last band picks nothing rather than panics. | 2861 | // past the last band picks nothing rather than panics. |
| @@ -4096,6 +4136,18 @@ impl Player { | |||
| 4096 | // clip and a 48 kHz one are not the same shape. | 4136 | // clip and a 48 kHz one are not the same shape. |
| 4097 | let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate); | 4137 | let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate); |
| 4098 | let picked = self.eq_params.bands.get(self.eq_band); | 4138 | let picked = self.eq_params.bands.get(self.eq_band); |
| 4139 | + // What is playing, drawn behind the curve -- and only while something | ||
| 4140 | + // *is* playing: the tap freezes with the device, and a still spectrum | ||
| 4141 | + // under a paused timeline would look like sound that is not there. | ||
| 4142 | + let spectrum = self | ||
| 4143 | + .eq_spectrum | ||
| 4144 | + .then_some(self.session.as_ref()) | ||
| 4145 | + .flatten() | ||
| 4146 | + .filter(|session| session.is_playing()) | ||
| 4147 | + .and_then(PlaybackSession::audio_tap) | ||
| 4148 | + .map(|(samples, rate)| eq_spectrum(&samples, rate)) | ||
| 4149 | + .filter(|levels| !levels.is_empty()) | ||
| 4150 | + .map(eq_spectrum_curve); | ||
| 4099 | let handles: Vec<_> = self | 4151 | let handles: Vec<_> = self |
| 4100 | .eq_params | 4152 | .eq_params |
| 4101 | .bands | 4153 | .bands |
| @@ -4141,6 +4193,44 @@ impl Player { | |||
| 4141 | }), | 4193 | }), |
| 4142 | ) | 4194 | ) |
| 4143 | .child(bounds_probe(self.eq_graph.clone())) | 4195 | .child(bounds_probe(self.eq_graph.clone())) |
| 4196 | + // The analyser first, so everything else is drawn on top of it. | ||
| 4197 | + .children(spectrum) | ||
| 4198 | + // The decades, so a hump can be read as "around 200 Hz" without | ||
| 4199 | + // dropping the eye to the labels along the bottom. The two ends | ||
| 4200 | + // are the box's own edges and rule nothing. | ||
| 4201 | + .children( | ||
| 4202 | + EQ_TICKS | ||
| 4203 | + .iter() | ||
| 4204 | + .filter(|(freq, _)| *freq > EQ_FREQ_LOW && *freq < EQ_FREQ_HIGH) | ||
| 4205 | + .map(|(freq, _)| { | ||
| 4206 | + div() | ||
| 4207 | + .absolute() | ||
| 4208 | + .left(relative(eq_x(*freq))) | ||
| 4209 | + .w(px(1.)) | ||
| 4210 | + .h_full() | ||
| 4211 | + .bg(rgb(EQ_GRID)) | ||
| 4212 | + }) | ||
| 4213 | + .collect::<Vec<_>>(), | ||
| 4214 | + ) | ||
| 4215 | + // Half way to each limit, each carrying its own number: the curve | ||
| 4216 | + // is a curve of decibels, and until now only one of them was drawn. | ||
| 4217 | + .children(EQ_DB_GRID.map(|db| { | ||
| 4218 | + div() | ||
| 4219 | + .absolute() | ||
| 4220 | + .top(relative(eq_y(db))) | ||
| 4221 | + .w_full() | ||
| 4222 | + .h(px(1.)) | ||
| 4223 | + .bg(rgb(EQ_GRID)) | ||
| 4224 | + .child( | ||
| 4225 | + div() | ||
| 4226 | + .absolute() | ||
| 4227 | + .left(px(4.)) | ||
| 4228 | + .top(px(-11.)) | ||
| 4229 | + .text_size(px(9.)) | ||
| 4230 | + .text_color(rgb(INK_DIM)) | ||
| 4231 | + .child(format!("{db:+.0}")), | ||
| 4232 | + ) | ||
| 4233 | + })) | ||
| 4144 | // 0 dB: the line a boost is a boost *from*. | 4234 | // 0 dB: the line a boost is a boost *from*. |
| 4145 | .child( | 4235 | .child( |
| 4146 | div() | 4236 | div() |
| @@ -4175,6 +4265,9 @@ impl Player { | |||
| 4175 | .text_color(rgb(INK_DIM)) | 4265 | .text_color(rgb(INK_DIM)) |
| 4176 | .child(format!("+{EQ_GAIN_LIMIT:.0} dB")), | 4266 | .child(format!("+{EQ_GAIN_LIMIT:.0} dB")), |
| 4177 | ); | 4267 | ); |
| 4268 | + // The bottom of the axis is not named: -12 dB would land in the same | ||
| 4269 | + // corner as the 20 Hz tick, and the two lines above it (+6 and -6) | ||
| 4270 | + // already say what the box is worth per pixel. | ||
| 4178 | Some( | 4271 | Some( |
| 4179 | div() | 4272 | div() |
| 4180 | .absolute() | 4273 | .absolute() |
| @@ -4209,7 +4302,7 @@ impl Player { | |||
| 4209 | .text_size(px(11.)) | 4302 | .text_size(px(11.)) |
| 4210 | .text_color(rgb(INK_DIM)) | 4303 | .text_color(rgb(INK_DIM)) |
| 4211 | .child(self.notice.clone().unwrap_or_else(|| { | 4304 | .child(self.notice.clone().unwrap_or_else(|| { |
| 4212 | - "drag the curve, or 1–5 then up/down — esc closes".into() | 4305 | + "drag the curve, or 1–5 then up/down — s hides the spectrum, esc closes".into() |
| 4213 | })), | 4306 | })), |
| 4214 | ) | 4307 | ) |
| 4215 | .child(graph) | 4308 | .child(graph) |
| @@ -4218,34 +4311,72 @@ impl Player { | |||
| 4218 | // one pulling the other way is not readable off it. | 4311 | // one pulling the other way is not readable off it. |
| 4219 | .child(div().flex_none().px(px(6.)).text_size(px(11.)).child( | 4312 | .child(div().flex_none().px(px(6.)).text_size(px(11.)).child( |
| 4220 | match picked { | 4313 | match picked { |
| 4314 | + // Q as well as the two the curve shows: it is | ||
| 4315 | + // how wide the hump under the handle is, and | ||
| 4316 | + // nothing else on the card says so. | ||
| 4221 | Some(band) => format!( | 4317 | Some(band) => format!( |
| 4222 | - "{} {} {:+.1} dB", | 4318 | + "{} {} {:+.1} dB — Q {:.2}", |
| 4223 | self.eq_band + 1, | 4319 | self.eq_band + 1, |
| 4224 | band_label(band), | 4320 | band_label(band), |
| 4225 | - band.gain_db | 4321 | + band.gain_db, |
| 4322 | + band.q | ||
| 4226 | ), | 4323 | ), |
| 4227 | None => "no bands".into(), | 4324 | None => "no bands".into(), |
| 4228 | }, | 4325 | }, |
| 4229 | )) | 4326 | )) |
| 4230 | .child( | 4327 | .child( |
| 4231 | div() | 4328 | div() |
| 4232 | - .id("eq-reset") | ||
| 4233 | .mt(px(4.)) | 4329 | .mt(px(4.)) |
| 4234 | .flex() | 4330 | .flex() |
| 4235 | - .h(px(CONTROL_H)) | 4331 | + .gap(px(4.)) |
| 4236 | - .items_center() | 4332 | + .child( |
| 4237 | - .justify_center() | 4333 | + div() |
| 4238 | - .rounded(px(3.)) | 4334 | + .id("eq-reset") |
| 4239 | - .bg(rgb(SELECTED)) | 4335 | + .flex() |
| 4240 | - .cursor_pointer() | 4336 | + .flex_1() |
| 4241 | - .hover(|s| s.bg(rgb(HOVER))) | 4337 | + .h(px(CONTROL_H)) |
| 4242 | - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { | 4338 | + .items_center() |
| 4243 | - for band in &mut this.eq_params.bands { | 4339 | + .justify_center() |
| 4244 | - band.gain_db = 0.; | 4340 | + .rounded(px(3.)) |
| 4245 | - } | 4341 | + .bg(rgb(SELECTED)) |
| 4246 | - this.commit_eq(cx); | 4342 | + .cursor_pointer() |
| 4247 | - })) | 4343 | + .hover(|s| s.bg(rgb(HOVER))) |
| 4248 | - .child("Flatten"), | 4344 | + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { |
| 4345 | + for band in &mut this.eq_params.bands { | ||
| 4346 | + band.gain_db = 0.; | ||
| 4347 | + } | ||
| 4348 | + this.commit_eq(cx); | ||
| 4349 | + })) | ||
| 4350 | + .child("Flatten"), | ||
| 4351 | + ) | ||
| 4352 | + // The analyser's switch, next to the one other | ||
| 4353 | + // button the card has: `s` does the same, and a | ||
| 4354 | + // toggle only a keystroke can reach is one most | ||
| 4355 | + // people never find. | ||
| 4356 | + .child( | ||
| 4357 | + div() | ||
| 4358 | + .id("eq-spectrum") | ||
| 4359 | + .flex() | ||
| 4360 | + .flex_1() | ||
| 4361 | + .h(px(CONTROL_H)) | ||
| 4362 | + .items_center() | ||
| 4363 | + .justify_center() | ||
| 4364 | + .rounded(px(3.)) | ||
| 4365 | + .bg(rgb(match self.eq_spectrum { | ||
| 4366 | + true => SELECTED, | ||
| 4367 | + false => HOVER_DIM, | ||
| 4368 | + })) | ||
| 4369 | + .cursor_pointer() | ||
| 4370 | + .hover(|s| s.bg(rgb(HOVER))) | ||
| 4371 | + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { | ||
| 4372 | + this.eq_spectrum = !this.eq_spectrum; | ||
| 4373 | + cx.notify(); | ||
| 4374 | + })) | ||
| 4375 | + .child(match self.eq_spectrum { | ||
| 4376 | + true => "Spectrum on", | ||
| 4377 | + false => "Spectrum off", | ||
| 4378 | + }), | ||
| 4379 | + ), | ||
| 4249 | ), | 4380 | ), |
| 4250 | ), | 4381 | ), |
| 4251 | ) | 4382 | ) |
| @@ -6599,6 +6730,131 @@ fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement { | |||
| 6599 | .size_full() | 6730 | .size_full() |
| 6600 | } | 6731 | } |
| 6601 | 6732 | ||
| 6733 | +/// In-place radix-2 FFT of `re`/`im`, whose length must be a power of two. | ||
| 6734 | +/// | ||
| 6735 | +/// Hand-written, and deliberately: a 1024-point transform once a frame is a | ||
| 6736 | +/// few tens of microseconds of plain arithmetic, and a dependency for it would | ||
| 6737 | +/// be a build cost this editor pays on every compile for one card's backdrop. | ||
| 6738 | +fn fft(re: &mut [f32], im: &mut [f32]) { | ||
| 6739 | + let n = re.len(); | ||
| 6740 | + // Decimation in time: the input is first put in bit-reversed order, after | ||
| 6741 | + // which the butterflies run over neighbours. | ||
| 6742 | + let mut j = 0usize; | ||
| 6743 | + for i in 1..n { | ||
| 6744 | + let mut bit = n >> 1; | ||
| 6745 | + while j & bit != 0 { | ||
| 6746 | + j ^= bit; | ||
| 6747 | + bit >>= 1; | ||
| 6748 | + } | ||
| 6749 | + j |= bit; | ||
| 6750 | + if i < j { | ||
| 6751 | + re.swap(i, j); | ||
| 6752 | + im.swap(i, j); | ||
| 6753 | + } | ||
| 6754 | + } | ||
| 6755 | + let mut span = 2; | ||
| 6756 | + while span <= n { | ||
| 6757 | + let step = std::f32::consts::TAU / span as f32; | ||
| 6758 | + for start in (0..n).step_by(span) { | ||
| 6759 | + for k in 0..span / 2 { | ||
| 6760 | + // e^{-i2πk/span}: the negative sign is the forward transform. | ||
| 6761 | + let (sin, cos) = (-step * k as f32).sin_cos(); | ||
| 6762 | + let (a, b) = (start + k, start + k + span / 2); | ||
| 6763 | + let (tr, ti) = (cos * re[b] - sin * im[b], cos * im[b] + sin * re[b]); | ||
| 6764 | + re[b] = re[a] - tr; | ||
| 6765 | + im[b] = im[a] - ti; | ||
| 6766 | + re[a] += tr; | ||
| 6767 | + im[a] += ti; | ||
| 6768 | + } | ||
| 6769 | + } | ||
| 6770 | + span <<= 1; | ||
| 6771 | + } | ||
| 6772 | +} | ||
| 6773 | + | ||
| 6774 | +/// The played signal as one height per curve point, 0 (silence) to 1 (the top | ||
| 6775 | +/// of the box) -- the analyser the response curve is drawn on top of. | ||
| 6776 | +/// | ||
| 6777 | +/// The newest [`EQ_FFT`] samples of the engine's tap, Hann-windowed so a tone | ||
| 6778 | +/// that does not land on a bin centre is one hump rather than a smear across | ||
| 6779 | +/// the axis. Each column takes the *loudest* bin between it and its | ||
| 6780 | +/// neighbours: the axis is logarithmic, so one column near 20 Hz is a fraction | ||
| 6781 | +/// of a bin while one near 20 kHz is hundreds, and averaging those would sink | ||
| 6782 | +/// every peak up there into the noise beside it. | ||
| 6783 | +/// | ||
| 6784 | +/// Empty -- nothing to draw -- for a tap too short to transform, which is what | ||
| 6785 | +/// a session has just after a seek. | ||
| 6786 | +/// | ||
| 6787 | +/// ponytail: one transform length for the whole axis, so the bass end is a bin | ||
| 6788 | +/// (47 Hz at 48 kHz) wide however many columns are drawn across it -- a 60 Hz | ||
| 6789 | +/// hum and an 80 Hz one are the same hump down there. Upgrade path is the | ||
| 6790 | +/// analyser every mastering EQ uses: two or three transforms of different | ||
| 6791 | +/// lengths, each drawn over the octaves it resolves. | ||
| 6792 | +fn eq_spectrum(samples: &[f32], sample_rate: u32) -> Vec<f32> { | ||
| 6793 | + if samples.len() < EQ_FFT { | ||
| 6794 | + return Vec::new(); | ||
| 6795 | + } | ||
| 6796 | + let tail = &samples[samples.len() - EQ_FFT..]; | ||
| 6797 | + let mut re: Vec<f32> = tail | ||
| 6798 | + .iter() | ||
| 6799 | + .enumerate() | ||
| 6800 | + .map(|(i, s)| { | ||
| 6801 | + let w = 0.5 * (1. - (std::f32::consts::TAU * i as f32 / EQ_FFT as f32).cos()); | ||
| 6802 | + s * w | ||
| 6803 | + }) | ||
| 6804 | + .collect(); | ||
| 6805 | + let mut im = vec![0.; EQ_FFT]; | ||
| 6806 | + fft(&mut re, &mut im); | ||
| 6807 | + // Magnitude per bin, scaled so a full-scale sine reads 0 dBFS: half the | ||
| 6808 | + // energy is in the mirrored half of the transform, and the Hann window | ||
| 6809 | + // takes another factor of two off. | ||
| 6810 | + let mags: Vec<f32> = (0..EQ_FFT / 2) | ||
| 6811 | + .map(|k| (re[k] * re[k] + im[k] * im[k]).sqrt() * 4. / EQ_FFT as f32) | ||
| 6812 | + .collect(); | ||
| 6813 | + let bin_hz = sample_rate as f32 / EQ_FFT as f32; | ||
| 6814 | + let (floor, ceiling) = EQ_SPECTRUM_DB; | ||
| 6815 | + let at = |along: f32| EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); | ||
| 6816 | + (0..=EQ_CURVE_STEPS) | ||
| 6817 | + .map(|step| { | ||
| 6818 | + let along = step as f32 / EQ_CURVE_STEPS as f32; | ||
| 6819 | + let half = 0.5 / EQ_CURVE_STEPS as f32; | ||
| 6820 | + // Bin 0 is DC and means nothing here, so the low end starts at 1. | ||
| 6821 | + let low = (at(along - half) / bin_hz).round().max(1.) as usize; | ||
| 6822 | + let high = (at(along + half) / bin_hz).round().max(1.) as usize; | ||
| 6823 | + let peak = (low..=high) | ||
| 6824 | + .filter_map(|k| mags.get(k)) | ||
| 6825 | + .fold(0f32, |a, &b| a.max(b)); | ||
| 6826 | + let db = 20. * peak.max(1e-9).log10(); | ||
| 6827 | + ((db - floor) / (ceiling - floor)).clamp(0., 1.) | ||
| 6828 | + }) | ||
| 6829 | + .collect() | ||
| 6830 | +} | ||
| 6831 | + | ||
| 6832 | +/// The analyser drawn as one filled shape from the floor of the box. | ||
| 6833 | +fn eq_spectrum_curve(levels: Vec<f32>) -> impl IntoElement { | ||
| 6834 | + canvas( | ||
| 6835 | + |_, _, _| (), | ||
| 6836 | + move |bounds, _, window, _| { | ||
| 6837 | + let (o, s) = (bounds.origin, bounds.size); | ||
| 6838 | + let last = levels.len().saturating_sub(1).max(1) as f32; | ||
| 6839 | + let mut path = PathBuilder::fill(); | ||
| 6840 | + path.move_to(point(o.x, o.y + s.height)); | ||
| 6841 | + for (i, level) in levels.iter().enumerate() { | ||
| 6842 | + path.line_to(point( | ||
| 6843 | + o.x + s.width * (i as f32 / last), | ||
| 6844 | + o.y + s.height * (1. - level), | ||
| 6845 | + )); | ||
| 6846 | + } | ||
| 6847 | + path.line_to(point(o.x + s.width, o.y + s.height)); | ||
| 6848 | + path.close(); | ||
| 6849 | + if let Ok(path) = path.build() { | ||
| 6850 | + window.paint_path(path, rgba(EQ_SPECTRUM_INK)); | ||
| 6851 | + } | ||
| 6852 | + }, | ||
| 6853 | + ) | ||
| 6854 | + .absolute() | ||
| 6855 | + .size_full() | ||
| 6856 | +} | ||
| 6857 | + | ||
| 6602 | /// The cascade's frequency response, drawn as one line across the graph. | 6858 | /// The cascade's frequency response, drawn as one line across the graph. |
| 6603 | /// | 6859 | /// |
| 6604 | /// Every point comes from `EqParams::response_db`, which reads the very | 6860 | /// Every point comes from `EqParams::response_db`, which reads the very |
| @@ -6613,14 +6869,31 @@ fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement { | |||
| 6613 | |_, _, _| (), | 6869 | |_, _, _| (), |
| 6614 | move |bounds, _, window, _| { | 6870 | move |bounds, _, window, _| { |
| 6615 | let (o, s) = (bounds.origin, bounds.size); | 6871 | let (o, s) = (bounds.origin, bounds.size); |
| 6872 | + let points: Vec<_> = (0..=EQ_CURVE_STEPS) | ||
| 6873 | + .map(|step| { | ||
| 6874 | + let along = step as f32 / EQ_CURVE_STEPS as f32; | ||
| 6875 | + let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); | ||
| 6876 | + point( | ||
| 6877 | + o.x + s.width * along, | ||
| 6878 | + o.y + s.height * eq_y(params.response_db(freq, sample_rate)), | ||
| 6879 | + ) | ||
| 6880 | + }) | ||
| 6881 | + .collect(); | ||
| 6882 | + // The area between the curve and 0 dB, closed along that line: a | ||
| 6883 | + // boost and a cut wind opposite ways around it, which is exactly | ||
| 6884 | + // what makes both of them fill and the flat parts stay empty. | ||
| 6885 | + let mut area = PathBuilder::fill(); | ||
| 6886 | + area.move_to(point(o.x, o.y + s.height / 2.)); | ||
| 6887 | + for at in &points { | ||
| 6888 | + area.line_to(*at); | ||
| 6889 | + } | ||
| 6890 | + area.line_to(point(o.x + s.width, o.y + s.height / 2.)); | ||
| 6891 | + area.close(); | ||
| 6892 | + if let Ok(area) = area.build() { | ||
| 6893 | + window.paint_path(area, rgba(EQ_FILL_INK)); | ||
| 6894 | + } | ||
| 6616 | let mut path = PathBuilder::stroke(px(2.)); | 6895 | let mut path = PathBuilder::stroke(px(2.)); |
| 6617 | - for step in 0..=EQ_CURVE_STEPS { | 6896 | + for (step, at) in points.into_iter().enumerate() { |
| 6618 | - let along = step as f32 / EQ_CURVE_STEPS as f32; | ||
| 6619 | - let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); | ||
| 6620 | - let at = point( | ||
| 6621 | - o.x + s.width * along, | ||
| 6622 | - o.y + s.height * eq_y(params.response_db(freq, sample_rate)), | ||
| 6623 | - ); | ||
| 6624 | match step { | 6897 | match step { |
| 6625 | 0 => path.move_to(at), | 6898 | 0 => path.move_to(at), |
| 6626 | _ => path.line_to(at), | 6899 | _ => path.line_to(at), |
| @@ -6704,19 +6977,19 @@ fn timecode(t: f64, fps: f64) -> String { | |||
| 6704 | #[cfg(test)] | 6977 | #[cfg(test)] |
| 6705 | mod tests { | 6978 | mod tests { |
| 6706 | use super::{ | 6979 | use super::{ |
| 6707 | - ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH, | 6980 | + ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_CURVE_STEPS, |
| 6708 | - EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS, | 6981 | + EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_SPECTRUM_DB, |
| 6709 | - Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, | 6982 | + EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, |
| 6710 | - INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, | 6983 | + HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, |
| 6711 | - LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, | 6984 | + LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, |
| 6712 | - Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, | 6985 | + MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, |
| 6713 | - SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, | 6986 | + SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, |
| 6714 | - applicable, band_label, can_add, cancels_export, color_snap, envelope, eq_x, eq_y, | 6987 | + Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, |
| 6715 | - export_path, export_settings, format_key, format_line, format_refusal, frac_along, | 6988 | + color_snap, envelope, eq_spectrum, eq_x, eq_y, export_path, export_settings, format_key, |
| 6716 | - frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, | 6989 | + format_line, format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, |
| 6717 | - menu_at, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label, | 6990 | + is_project, keymap, lanes_h, marked, menu_at, normalise, panel_h, project_path, push_digit, |
| 6718 | - silence_rate, source_tint, span_partner, speed_at, start_frac, timecode, unseen_paths, | 6991 | + retarget, scrub_due, show_label, silence_rate, source_tint, span_partner, speed_at, |
| 6719 | - unseen_sources, whole_take, width_frac, window_title, | 6992 | + start_frac, timecode, unseen_paths, unseen_sources, whole_take, width_frac, window_title, |
| 6720 | }; | 6993 | }; |
| 6721 | use super::{LaneKind, file_name, file_uri, library_rows, unscannable}; | 6994 | use super::{LaneKind, file_name, file_uri, library_rows, unscannable}; |
| 6722 | 6995 | ||
| @@ -7918,6 +8191,86 @@ mod tests { | |||
| 7918 | assert!(KEYS_ROW_H >= HIT_MIN); | 8191 | assert!(KEYS_ROW_H >= HIT_MIN); |
| 7919 | } | 8192 | } |
| 7920 | 8193 | ||
| 8194 | + /// The analyser drawn behind the curve: a tone has to land on its own | ||
| 8195 | + /// frequency, or the backdrop is a decoration rather than a reading of what | ||
| 8196 | + /// is playing -- and someone shaping a band against it would be aiming at | ||
| 8197 | + /// the wrong octave. | ||
| 8198 | + #[test] | ||
| 8199 | + fn the_spectrum_puts_a_tone_under_its_own_frequency() { | ||
| 8200 | + use std::f32::consts::TAU; | ||
| 8201 | + let rate = 48_000u32; | ||
| 8202 | + let sine = |hz: f32, amp: f32| -> Vec<f32> { | ||
| 8203 | + (0..EQ_FFT) | ||
| 8204 | + .map(|i| amp * (TAU * hz * i as f32 / rate as f32).sin()) | ||
| 8205 | + .collect() | ||
| 8206 | + }; | ||
| 8207 | + | ||
| 8208 | + // Silence is the floor of the box everywhere, not a band of noise. | ||
| 8209 | + let quiet = eq_spectrum(&vec![0.; EQ_FFT], rate); | ||
| 8210 | + assert_eq!(quiet.len(), EQ_CURVE_STEPS + 1); | ||
| 8211 | + assert!(quiet.iter().all(|&l| l == 0.), "silence drew something"); | ||
| 8212 | + | ||
| 8213 | + // A tone peaks over its own frequency, and the columns two octaves | ||
| 8214 | + // either side of it are near the floor. "Over" to within a bin down low | ||
| 8215 | + // and a column up high, which is all a 1024-point transform on a log | ||
| 8216 | + // axis can promise: at 200 Hz a whole column is a fraction of a bin | ||
| 8217 | + // wide, so the peak sits on the bin the tone fell in. | ||
| 8218 | + let column = |freq: f32| (eq_x(freq) * EQ_CURVE_STEPS as f32).round() as usize; | ||
| 8219 | + let freq_at = |col: usize| { | ||
| 8220 | + let along = col as f32 / EQ_CURVE_STEPS as f32; | ||
| 8221 | + EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along) | ||
| 8222 | + }; | ||
| 8223 | + for hz in [200., 1000., 5000.] { | ||
| 8224 | + let levels = eq_spectrum(&sine(hz, 0.05), rate); | ||
| 8225 | + let (at, top) = | ||
| 8226 | + levels | ||
| 8227 | + .iter() | ||
| 8228 | + .enumerate() | ||
| 8229 | + .fold((0, 0f32), |best, (i, &l)| match l > best.1 { | ||
| 8230 | + true => (i, l), | ||
| 8231 | + false => best, | ||
| 8232 | + }); | ||
| 8233 | + let slack = 1.5 * rate as f32 / EQ_FFT as f32 + 0.04 * hz; | ||
| 8234 | + assert!( | ||
| 8235 | + (freq_at(at) - hz).abs() <= slack, | ||
| 8236 | + "{hz} Hz peaked at {:.0} Hz (column {at})", | ||
| 8237 | + freq_at(at) | ||
| 8238 | + ); | ||
| 8239 | + // -26 dBFS, which is where a 0.05 tone sits on the axis. | ||
| 8240 | + let want = | ||
| 8241 | + (20. * 0.05f32.log10() - EQ_SPECTRUM_DB.0) / (EQ_SPECTRUM_DB.1 - EQ_SPECTRUM_DB.0); | ||
| 8242 | + assert!( | ||
| 8243 | + (top - want).abs() < 0.05, | ||
| 8244 | + "a -26 dBFS tone drew {top} of the box, not {want}" | ||
| 8245 | + ); | ||
| 8246 | + // Two octaves off is far enough down the box that the hump reads as | ||
| 8247 | + // one hump: 0.4 of the axis is a little over 30 dB. | ||
| 8248 | + for off in [hz / 4., hz * 4.] { | ||
| 8249 | + let away = levels[column(off).min(EQ_CURVE_STEPS)]; | ||
| 8250 | + assert!( | ||
| 8251 | + top - away > 0.4, | ||
| 8252 | + "{hz} Hz drew {top} but still {away} at {off} Hz" | ||
| 8253 | + ); | ||
| 8254 | + } | ||
| 8255 | + } | ||
| 8256 | + | ||
| 8257 | + // Level reads as level: 40 dB quieter sits lower by the fraction of the | ||
| 8258 | + // axis those 40 dB are. | ||
| 8259 | + let loud = eq_spectrum(&sine(1000., 0.05), rate); | ||
| 8260 | + let soft = eq_spectrum(&sine(1000., 0.0005), rate); | ||
| 8261 | + let at = column(1000.); | ||
| 8262 | + let drop = loud[at] - soft[at]; | ||
| 8263 | + let (floor, ceiling) = EQ_SPECTRUM_DB; | ||
| 8264 | + assert!( | ||
| 8265 | + (drop - 40. / (ceiling - floor)).abs() < 0.05, | ||
| 8266 | + "40 dB quieter moved the analyser {drop} of the box" | ||
| 8267 | + ); | ||
| 8268 | + | ||
| 8269 | + // A tap the engine has not filled yet (right after a seek) draws | ||
| 8270 | + // nothing at all rather than a transform of half a window. | ||
| 8271 | + assert!(eq_spectrum(&[0.; 16], rate).is_empty()); | ||
| 8272 | + } | ||
| 8273 | + | ||
| 7921 | /// The speed bar is the same round trip -- pixels -> rate -> fill -- with | 8274 | /// The speed bar is the same round trip -- pixels -> rate -> fill -- with |
| 7922 | /// one thing the colour sliders do not have to promise: **exactly 1.00x has | 8275 | /// one thing the colour sliders do not have to promise: **exactly 1.00x has |
| 7923 | /// to be reachable**, by a hand as well as by the reset. A grid that missed | 8276 | /// to be reachable**, by a hand as well as by the reset. A grid that missed |
| @@ -8716,6 +9069,7 @@ fn main() { | |||
| 8716 | eq_band: 0, | 9069 | eq_band: 0, |
| 8717 | eq_dragging: false, | 9070 | eq_dragging: false, |
| 8718 | eq_graph: Rc::default(), | 9071 | eq_graph: Rc::default(), |
| 9072 | + eq_spectrum: true, | ||
| 8719 | speed_open: None, | 9073 | speed_open: None, |
| 8720 | speed_bar: Rc::default(), | 9074 | speed_bar: Rc::default(), |
| 8721 | speed_dragging: false, | 9075 | speed_dragging: false, |
crates/engine/src/playback.rsmodified+45 -0
| @@ -90,8 +90,18 @@ struct Audio { | |||
| 90 | /// Bumped by every seek. A feeder only owns the device while this still | 90 | /// Bumped by every seek. A feeder only owns the device while this still |
| 91 | /// matches the value it started with; see [`feed`]. | 91 | /// matches the value it started with; see [`feed`]. |
| 92 | epoch: Arc<AtomicU64>, | 92 | epoch: Arc<AtomicU64>, |
| 93 | + /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest | ||
| 94 | + /// first: what a meter or an analyser draws. Written by the feeder, which | ||
| 95 | + /// is not the device's own callback -- the plugin's RT thread never sees | ||
| 96 | + /// this lock, and the feeder holds it for one memcpy per write. | ||
| 97 | + tap: Arc<Mutex<Vec<f32>>>, | ||
| 93 | } | 98 | } |
| 94 | 99 | ||
| 100 | +/// How much of the played signal the tap keeps. A power of two, because what | ||
| 101 | +/// reads it transforms it, and long enough that the lowest band the editor | ||
| 102 | +/// draws (20 Hz) has a whole cycle in the window at any rate we open. | ||
| 103 | +const TAP_SAMPLES: usize = 2048; | ||
| 104 | + | ||
| 95 | impl Audio { | 105 | impl Audio { |
| 96 | /// Whether the device has played everything there will ever be, i.e. the | 106 | /// Whether the device has played everything there will ever be, i.e. the |
| 97 | /// audio clock is about to stop meaning anything. | 107 | /// audio clock is about to stop meaning anything. |
| @@ -100,6 +110,21 @@ impl Audio { | |||
| 100 | && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) | 110 | && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) |
| 101 | } | 111 | } |
| 102 | 112 | ||
| 113 | + /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to | ||
| 114 | + /// mono. Called from the feeder only, once per accepted write. | ||
| 115 | + fn note_tap(&self, accepted: &[f32]) { | ||
| 116 | + let channels = self.channels.max(1) as usize; | ||
| 117 | + let mut tap = self.tap.lock().unwrap(); | ||
| 118 | + // Only the tail can survive anyway: a big write replaces the window | ||
| 119 | + // outright rather than being summed into it and then thrown away. | ||
| 120 | + let from = accepted.len().saturating_sub(TAP_SAMPLES * channels); | ||
| 121 | + for frame in accepted[from..].chunks_exact(channels) { | ||
| 122 | + tap.push(frame.iter().sum::<f32>() / channels as f32); | ||
| 123 | + } | ||
| 124 | + let over = tap.len().saturating_sub(TAP_SAMPLES); | ||
| 125 | + tap.drain(..over); | ||
| 126 | + } | ||
| 127 | + | ||
| 103 | /// Starts a feeder for the current epoch, draining `rx` into the device. | 128 | /// Starts a feeder for the current epoch, draining `rx` into the device. |
| 104 | /// `false` if the thread would not start, i.e. nothing will ever be fed. | 129 | /// `false` if the thread would not start, i.e. nothing will ever be fed. |
| 105 | fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool { | 130 | fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool { |
| @@ -1493,6 +1518,21 @@ impl PlaybackSession { | |||
| 1493 | } | 1518 | } |
| 1494 | } | 1519 | } |
| 1495 | 1520 | ||
| 1521 | + /// A copy of the most recent mono samples the device was handed, and the | ||
| 1522 | + /// rate they play at: the signal *after* every clip's equalizer, speed and | ||
| 1523 | + /// the mix, which is what an analyser drawn behind an EQ curve has to show. | ||
| 1524 | + /// `None` with no audio output at all, and empty until the feeder has | ||
| 1525 | + /// written once (right after a seek, for instance). | ||
| 1526 | + /// | ||
| 1527 | + /// Never blocks anything that matters: the feeder holds this lock for one | ||
| 1528 | + /// memcpy and the device's own callback lives in the plugin, on the far | ||
| 1529 | + /// side of a ring buffer, where it cannot see this at all. | ||
| 1530 | + pub fn audio_tap(&self) -> Option<(Vec<f32>, u32)> { | ||
| 1531 | + let audio = self.audio.as_ref()?; | ||
| 1532 | + let tap = audio.tap.lock().unwrap().clone(); | ||
| 1533 | + Some((tap, audio.sample_rate)) | ||
| 1534 | + } | ||
| 1535 | + | ||
| 1496 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode | 1536 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode |
| 1497 | /// workers are replaced rather than steered: a fresh channel cannot hold a | 1537 | /// workers are replaced rather than steered: a fresh channel cannot hold a |
| 1498 | /// stale frame, and it works just as well after EOF, where the old workers | 1538 | /// stale frame, and it works just as well after EOF, where the old workers |
| @@ -1515,6 +1555,9 @@ impl PlaybackSession { | |||
| 1515 | // carrying can no longer reach the ring after this point. | 1555 | // carrying can no longer reach the ring after this point. |
| 1516 | audio.epoch.fetch_add(1, Ordering::Release); | 1556 | audio.epoch.fetch_add(1, Ordering::Release); |
| 1517 | ao.flush(); | 1557 | ao.flush(); |
| 1558 | + // The flushed samples are not being played any more, so nothing may | ||
| 1559 | + // still be drawn from them. | ||
| 1560 | + audio.tap.lock().unwrap().clear(); | ||
| 1518 | } | 1561 | } |
| 1519 | 1562 | ||
| 1520 | // Cancel first, drop second: the old worker may be parked in `send` on | 1563 | // Cancel first, drop second: the old worker may be parked in `send` on |
| @@ -1832,6 +1875,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) { | |||
| 1832 | fed_all: Arc::new(AtomicBool::new(false)), | 1875 | fed_all: Arc::new(AtomicBool::new(false)), |
| 1833 | died: Arc::new(AtomicBool::new(false)), | 1876 | died: Arc::new(AtomicBool::new(false)), |
| 1834 | epoch: Arc::new(AtomicU64::new(0)), | 1877 | epoch: Arc::new(AtomicU64::new(0)), |
| 1878 | + tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))), | ||
| 1835 | }; | 1879 | }; |
| 1836 | (audio.spawn_feeder(rx).then_some(audio), None) | 1880 | (audio.spawn_feeder(rx).then_some(audio), None) |
| 1837 | } | 1881 | } |
| @@ -1866,6 +1910,7 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) { | |||
| 1866 | } | 1910 | } |
| 1867 | }; | 1911 | }; |
| 1868 | audio.fed.fetch_add(accepted as u64, Ordering::Relaxed); | 1912 | audio.fed.fetch_add(accepted as u64, Ordering::Relaxed); |
| 1913 | + audio.note_tap(&pending[..accepted]); | ||
| 1869 | pending.drain(..accepted); | 1914 | pending.drain(..accepted); |
| 1870 | if !pending.is_empty() { | 1915 | if !pending.is_empty() { |
| 1871 | // Ring full: nothing to do but let the device drain it. | 1916 | // Ring full: nothing to do but let the device drain it. |