🔀 merge(T13): EQ graph — live spectrum, gridlines, band readout
Browse files at this commit3 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
| @@ -301,7 +301,7 @@ pub struct Fixed { | |||
| 301 | pub category: Category, | 301 | pub category: Category, |
| 302 | } | 302 | } |
| 303 | 303 | ||
| 304 | -pub const FIXED: [Fixed; 15] = [ | 304 | +pub const FIXED: [Fixed; 16] = [ |
| 305 | // Not a chord at all but a way of pressing one, and the only place the | 305 | // Not a chord at all but a way of pressing one, and the only place the |
| 306 | // editor can say so: holding a key that moves a *value* runs it, and | 306 | // editor can say so: holding a key that moves a *value* runs it, and |
| 307 | // holding anything else still does what one press did. | 307 | // holding anything else still does what one press did. |
| @@ -358,6 +358,11 @@ pub const FIXED: [Fixed; 15] = [ | |||
| 358 | label: "Flatten every band", | 358 | label: "Flatten every band", |
| 359 | category: Category::Audio, | 359 | category: Category::Audio, |
| 360 | }, | 360 | }, |
| 361 | + Fixed { | ||
| 362 | + chord: "s", | ||
| 363 | + label: "Show or hide the spectrum behind the curve", | ||
| 364 | + category: Category::Audio, | ||
| 365 | + }, | ||
| 361 | // The colour card's own three, which mean nothing outside it -- the same | 366 | // The colour card's own three, which mean nothing outside it -- the same |
| 362 | // card-local input the export card's digits are. | 367 | // card-local input the export card's digits are. |
| 363 | Fixed { | 368 | Fixed { |
crates/app/src/main.rsmodified+392 -38
| @@ -486,6 +486,36 @@ const EQ_TICKS: [(f32, &str); 5] = [ | |||
| 486 | (20000., "20k"), | 486 | (20000., "20k"), |
| 487 | ]; | 487 | ]; |
| 488 | 488 | ||
| 489 | +/// The gains the graph rules a line across, besides the 0 dB one it already | ||
| 490 | +/// had: half way to each limit, so a boost can be read as "about six" without | ||
| 491 | +/// counting pixels. The limits themselves are the box's own edges and are | ||
| 492 | +/// named at the corners instead. | ||
| 493 | +const EQ_DB_GRID: [f32; 2] = [6., -6.]; | ||
| 494 | + | ||
| 495 | +/// The grid's ink: above the card's background and below everything drawn on | ||
| 496 | +/// it, so the lines are a ruling rather than a thing to look at. | ||
| 497 | +const EQ_GRID: u32 = 0x3a3a3a; | ||
| 498 | + | ||
| 499 | +/// How many played samples one spectrum frame is transformed from. A power of | ||
| 500 | +/// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz | ||
| 501 | +/// is a 47 Hz bin, fine enough that the bass end is a shape and short enough | ||
| 502 | +/// (21 ms) that the analyser moves with the music. | ||
| 503 | +const EQ_FFT: usize = 1024; | ||
| 504 | + | ||
| 505 | +/// The level range the analyser is drawn across, floor to ceiling in dBFS: the | ||
| 506 | +/// bottom of the box is silence and the top is a bin at -12 dBFS, which is | ||
| 507 | +/// about where a mixed track's loudest band sits. A look, not a measurement -- | ||
| 508 | +/// the numbers on the axis are the curve's dB, never the analyser's. | ||
| 509 | +const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.); | ||
| 510 | + | ||
| 511 | +/// The analyser's fill, behind the curve: a dim blue-grey with enough alpha to | ||
| 512 | +/// read as a haze the accent line sits on top of. | ||
| 513 | +const EQ_SPECTRUM_INK: u32 = 0x7f95ad66; | ||
| 514 | + | ||
| 515 | +/// The area under the response curve, same accent as the line at a tenth of | ||
| 516 | +/// its weight: it is what makes a boost read as a hill rather than as a wire. | ||
| 517 | +const EQ_FILL_INK: u32 = 0x4a9eff26; | ||
| 518 | + | ||
| 489 | /// The colour card's four controls, in the order it lists them: what each is | 519 | /// The colour card's four controls, in the order it lists them: what each is |
| 490 | /// called and the range it moves in. The order is `ColorParams`' own, which is | 520 | /// called and the range it moves in. The order is `ColorParams`' own, which is |
| 491 | /// what [`color_band`] indexes. | 521 | /// what [`color_band`] indexes. |
| @@ -662,6 +692,11 @@ struct Player { | |||
| 662 | /// window position only, so this is what a press and a drag are read | 692 | /// window position only, so this is what a press and a drag are read |
| 663 | /// against ([`frac_along`], [`frac_down`]). | 693 | /// against ([`frac_along`], [`frac_down`]). |
| 664 | eq_graph: Rc<Cell<Bounds<Pixels>>>, | 694 | eq_graph: Rc<Cell<Bounds<Pixels>>>, |
| 695 | + /// Whether the analyser is drawn behind the curve. On by default -- what | ||
| 696 | + /// the curve is being *shaped against* is the point of drawing it -- and | ||
| 697 | + /// off with one press for anyone who would rather read the curve alone. | ||
| 698 | + /// Card state, not the project's: it changes nothing that plays. | ||
| 699 | + eq_spectrum: bool, | ||
| 665 | /// The colour card is up on this clip -- the lane it is on and its index | 700 | /// The colour card is up on this clip -- the lane it is on and its index |
| 666 | /// there. `None` when it is closed, which is the only place that state | 701 | /// there. `None` when it is closed, which is the only place that state |
| 667 | /// lives: the grade itself is the project's. | 702 | /// lives: the grade itself is the project's. |
| @@ -3004,6 +3039,11 @@ impl Render for Player { | |||
| 3004 | band.gain_db = 0.; | 3039 | band.gain_db = 0.; |
| 3005 | } | 3040 | } |
| 3006 | this.commit_eq(cx); | 3041 | this.commit_eq(cx); |
| 3042 | + } else if key == "s" { | ||
| 3043 | + // The analyser off and on. Nothing is committed: it is | ||
| 3044 | + // what the card *shows*, so it survives no further than | ||
| 3045 | + // this window. | ||
| 3046 | + this.eq_spectrum = !this.eq_spectrum; | ||
| 3007 | } else if let Ok(digit) = key.parse::<usize>() { | 3047 | } else if let Ok(digit) = key.parse::<usize>() { |
| 3008 | // 1-based, as the rows are numbered on screen; a digit | 3048 | // 1-based, as the rows are numbered on screen; a digit |
| 3009 | // past the last band picks nothing rather than panics. | 3049 | // past the last band picks nothing rather than panics. |
| @@ -4316,6 +4356,18 @@ impl Player { | |||
| 4316 | // clip and a 48 kHz one are not the same shape. | 4356 | // clip and a 48 kHz one are not the same shape. |
| 4317 | let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate); | 4357 | let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate); |
| 4318 | let picked = self.eq_params.bands.get(self.eq_band); | 4358 | let picked = self.eq_params.bands.get(self.eq_band); |
| 4359 | + // What is playing, drawn behind the curve -- and only while something | ||
| 4360 | + // *is* playing: the tap freezes with the device, and a still spectrum | ||
| 4361 | + // under a paused timeline would look like sound that is not there. | ||
| 4362 | + let spectrum = self | ||
| 4363 | + .eq_spectrum | ||
| 4364 | + .then_some(self.session.as_ref()) | ||
| 4365 | + .flatten() | ||
| 4366 | + .filter(|session| session.is_playing()) | ||
| 4367 | + .and_then(PlaybackSession::audio_tap) | ||
| 4368 | + .map(|(samples, rate)| eq_spectrum(&samples, rate)) | ||
| 4369 | + .filter(|levels| !levels.is_empty()) | ||
| 4370 | + .map(eq_spectrum_curve); | ||
| 4319 | let handles: Vec<_> = self | 4371 | let handles: Vec<_> = self |
| 4320 | .eq_params | 4372 | .eq_params |
| 4321 | .bands | 4373 | .bands |
| @@ -4361,6 +4413,44 @@ impl Player { | |||
| 4361 | }), | 4413 | }), |
| 4362 | ) | 4414 | ) |
| 4363 | .child(bounds_probe(self.eq_graph.clone())) | 4415 | .child(bounds_probe(self.eq_graph.clone())) |
| 4416 | + // The analyser first, so everything else is drawn on top of it. | ||
| 4417 | + .children(spectrum) | ||
| 4418 | + // The decades, so a hump can be read as "around 200 Hz" without | ||
| 4419 | + // dropping the eye to the labels along the bottom. The two ends | ||
| 4420 | + // are the box's own edges and rule nothing. | ||
| 4421 | + .children( | ||
| 4422 | + EQ_TICKS | ||
| 4423 | + .iter() | ||
| 4424 | + .filter(|(freq, _)| *freq > EQ_FREQ_LOW && *freq < EQ_FREQ_HIGH) | ||
| 4425 | + .map(|(freq, _)| { | ||
| 4426 | + div() | ||
| 4427 | + .absolute() | ||
| 4428 | + .left(relative(eq_x(*freq))) | ||
| 4429 | + .w(px(1.)) | ||
| 4430 | + .h_full() | ||
| 4431 | + .bg(rgb(EQ_GRID)) | ||
| 4432 | + }) | ||
| 4433 | + .collect::<Vec<_>>(), | ||
| 4434 | + ) | ||
| 4435 | + // Half way to each limit, each carrying its own number: the curve | ||
| 4436 | + // is a curve of decibels, and until now only one of them was drawn. | ||
| 4437 | + .children(EQ_DB_GRID.map(|db| { | ||
| 4438 | + div() | ||
| 4439 | + .absolute() | ||
| 4440 | + .top(relative(eq_y(db))) | ||
| 4441 | + .w_full() | ||
| 4442 | + .h(px(1.)) | ||
| 4443 | + .bg(rgb(EQ_GRID)) | ||
| 4444 | + .child( | ||
| 4445 | + div() | ||
| 4446 | + .absolute() | ||
| 4447 | + .left(px(4.)) | ||
| 4448 | + .top(px(-11.)) | ||
| 4449 | + .text_size(px(9.)) | ||
| 4450 | + .text_color(rgb(INK_DIM)) | ||
| 4451 | + .child(format!("{db:+.0}")), | ||
| 4452 | + ) | ||
| 4453 | + })) | ||
| 4364 | // 0 dB: the line a boost is a boost *from*. | 4454 | // 0 dB: the line a boost is a boost *from*. |
| 4365 | .child( | 4455 | .child( |
| 4366 | div() | 4456 | div() |
| @@ -4395,6 +4485,9 @@ impl Player { | |||
| 4395 | .text_color(rgb(INK_DIM)) | 4485 | .text_color(rgb(INK_DIM)) |
| 4396 | .child(format!("+{EQ_GAIN_LIMIT:.0} dB")), | 4486 | .child(format!("+{EQ_GAIN_LIMIT:.0} dB")), |
| 4397 | ); | 4487 | ); |
| 4488 | + // The bottom of the axis is not named: -12 dB would land in the same | ||
| 4489 | + // corner as the 20 Hz tick, and the two lines above it (+6 and -6) | ||
| 4490 | + // already say what the box is worth per pixel. | ||
| 4398 | Some( | 4491 | Some( |
| 4399 | div() | 4492 | div() |
| 4400 | .absolute() | 4493 | .absolute() |
| @@ -4429,7 +4522,7 @@ impl Player { | |||
| 4429 | .text_size(px(11.)) | 4522 | .text_size(px(11.)) |
| 4430 | .text_color(rgb(INK_DIM)) | 4523 | .text_color(rgb(INK_DIM)) |
| 4431 | .child(self.notice.clone().unwrap_or_else(|| { | 4524 | .child(self.notice.clone().unwrap_or_else(|| { |
| 4432 | - "drag the curve, or 1–5 then up/down — esc closes".into() | 4525 | + "drag the curve, or 1–5 then up/down — s hides the spectrum, esc closes".into() |
| 4433 | })), | 4526 | })), |
| 4434 | ) | 4527 | ) |
| 4435 | .child(graph) | 4528 | .child(graph) |
| @@ -4438,34 +4531,72 @@ impl Player { | |||
| 4438 | // one pulling the other way is not readable off it. | 4531 | // one pulling the other way is not readable off it. |
| 4439 | .child(div().flex_none().px(px(6.)).text_size(px(11.)).child( | 4532 | .child(div().flex_none().px(px(6.)).text_size(px(11.)).child( |
| 4440 | match picked { | 4533 | match picked { |
| 4534 | + // Q as well as the two the curve shows: it is | ||
| 4535 | + // how wide the hump under the handle is, and | ||
| 4536 | + // nothing else on the card says so. | ||
| 4441 | Some(band) => format!( | 4537 | Some(band) => format!( |
| 4442 | - "{} {} {:+.1} dB", | 4538 | + "{} {} {:+.1} dB — Q {:.2}", |
| 4443 | self.eq_band + 1, | 4539 | self.eq_band + 1, |
| 4444 | band_label(band), | 4540 | band_label(band), |
| 4445 | - band.gain_db | 4541 | + band.gain_db, |
| 4542 | + band.q | ||
| 4446 | ), | 4543 | ), |
| 4447 | None => "no bands".into(), | 4544 | None => "no bands".into(), |
| 4448 | }, | 4545 | }, |
| 4449 | )) | 4546 | )) |
| 4450 | .child( | 4547 | .child( |
| 4451 | div() | 4548 | div() |
| 4452 | - .id("eq-reset") | ||
| 4453 | .mt(px(4.)) | 4549 | .mt(px(4.)) |
| 4454 | .flex() | 4550 | .flex() |
| 4455 | - .h(px(CONTROL_H)) | 4551 | + .gap(px(4.)) |
| 4456 | - .items_center() | 4552 | + .child( |
| 4457 | - .justify_center() | 4553 | + div() |
| 4458 | - .rounded(px(3.)) | 4554 | + .id("eq-reset") |
| 4459 | - .bg(rgb(SELECTED)) | 4555 | + .flex() |
| 4460 | - .cursor_pointer() | 4556 | + .flex_1() |
| 4461 | - .hover(|s| s.bg(rgb(HOVER))) | 4557 | + .h(px(CONTROL_H)) |
| 4462 | - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { | 4558 | + .items_center() |
| 4463 | - for band in &mut this.eq_params.bands { | 4559 | + .justify_center() |
| 4464 | - band.gain_db = 0.; | 4560 | + .rounded(px(3.)) |
| 4465 | - } | 4561 | + .bg(rgb(SELECTED)) |
| 4466 | - this.commit_eq(cx); | 4562 | + .cursor_pointer() |
| 4467 | - })) | 4563 | + .hover(|s| s.bg(rgb(HOVER))) |
| 4468 | - .child("Flatten"), | 4564 | + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { |
| 4565 | + for band in &mut this.eq_params.bands { | ||
| 4566 | + band.gain_db = 0.; | ||
| 4567 | + } | ||
| 4568 | + this.commit_eq(cx); | ||
| 4569 | + })) | ||
| 4570 | + .child("Flatten"), | ||
| 4571 | + ) | ||
| 4572 | + // The analyser's switch, next to the one other | ||
| 4573 | + // button the card has: `s` does the same, and a | ||
| 4574 | + // toggle only a keystroke can reach is one most | ||
| 4575 | + // people never find. | ||
| 4576 | + .child( | ||
| 4577 | + div() | ||
| 4578 | + .id("eq-spectrum") | ||
| 4579 | + .flex() | ||
| 4580 | + .flex_1() | ||
| 4581 | + .h(px(CONTROL_H)) | ||
| 4582 | + .items_center() | ||
| 4583 | + .justify_center() | ||
| 4584 | + .rounded(px(3.)) | ||
| 4585 | + .bg(rgb(match self.eq_spectrum { | ||
| 4586 | + true => SELECTED, | ||
| 4587 | + false => HOVER_DIM, | ||
| 4588 | + })) | ||
| 4589 | + .cursor_pointer() | ||
| 4590 | + .hover(|s| s.bg(rgb(HOVER))) | ||
| 4591 | + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { | ||
| 4592 | + this.eq_spectrum = !this.eq_spectrum; | ||
| 4593 | + cx.notify(); | ||
| 4594 | + })) | ||
| 4595 | + .child(match self.eq_spectrum { | ||
| 4596 | + true => "Spectrum on", | ||
| 4597 | + false => "Spectrum off", | ||
| 4598 | + }), | ||
| 4599 | + ), | ||
| 4469 | ), | 4600 | ), |
| 4470 | ), | 4601 | ), |
| 4471 | ) | 4602 | ) |
| @@ -6945,6 +7076,131 @@ fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement { | |||
| 6945 | .size_full() | 7076 | .size_full() |
| 6946 | } | 7077 | } |
| 6947 | 7078 | ||
| 7079 | +/// In-place radix-2 FFT of `re`/`im`, whose length must be a power of two. | ||
| 7080 | +/// | ||
| 7081 | +/// Hand-written, and deliberately: a 1024-point transform once a frame is a | ||
| 7082 | +/// few tens of microseconds of plain arithmetic, and a dependency for it would | ||
| 7083 | +/// be a build cost this editor pays on every compile for one card's backdrop. | ||
| 7084 | +fn fft(re: &mut [f32], im: &mut [f32]) { | ||
| 7085 | + let n = re.len(); | ||
| 7086 | + // Decimation in time: the input is first put in bit-reversed order, after | ||
| 7087 | + // which the butterflies run over neighbours. | ||
| 7088 | + let mut j = 0usize; | ||
| 7089 | + for i in 1..n { | ||
| 7090 | + let mut bit = n >> 1; | ||
| 7091 | + while j & bit != 0 { | ||
| 7092 | + j ^= bit; | ||
| 7093 | + bit >>= 1; | ||
| 7094 | + } | ||
| 7095 | + j |= bit; | ||
| 7096 | + if i < j { | ||
| 7097 | + re.swap(i, j); | ||
| 7098 | + im.swap(i, j); | ||
| 7099 | + } | ||
| 7100 | + } | ||
| 7101 | + let mut span = 2; | ||
| 7102 | + while span <= n { | ||
| 7103 | + let step = std::f32::consts::TAU / span as f32; | ||
| 7104 | + for start in (0..n).step_by(span) { | ||
| 7105 | + for k in 0..span / 2 { | ||
| 7106 | + // e^{-i2πk/span}: the negative sign is the forward transform. | ||
| 7107 | + let (sin, cos) = (-step * k as f32).sin_cos(); | ||
| 7108 | + let (a, b) = (start + k, start + k + span / 2); | ||
| 7109 | + let (tr, ti) = (cos * re[b] - sin * im[b], cos * im[b] + sin * re[b]); | ||
| 7110 | + re[b] = re[a] - tr; | ||
| 7111 | + im[b] = im[a] - ti; | ||
| 7112 | + re[a] += tr; | ||
| 7113 | + im[a] += ti; | ||
| 7114 | + } | ||
| 7115 | + } | ||
| 7116 | + span <<= 1; | ||
| 7117 | + } | ||
| 7118 | +} | ||
| 7119 | + | ||
| 7120 | +/// The played signal as one height per curve point, 0 (silence) to 1 (the top | ||
| 7121 | +/// of the box) -- the analyser the response curve is drawn on top of. | ||
| 7122 | +/// | ||
| 7123 | +/// The newest [`EQ_FFT`] samples of the engine's tap, Hann-windowed so a tone | ||
| 7124 | +/// that does not land on a bin centre is one hump rather than a smear across | ||
| 7125 | +/// the axis. Each column takes the *loudest* bin between it and its | ||
| 7126 | +/// neighbours: the axis is logarithmic, so one column near 20 Hz is a fraction | ||
| 7127 | +/// of a bin while one near 20 kHz is hundreds, and averaging those would sink | ||
| 7128 | +/// every peak up there into the noise beside it. | ||
| 7129 | +/// | ||
| 7130 | +/// Empty -- nothing to draw -- for a tap too short to transform, which is what | ||
| 7131 | +/// a session has just after a seek. | ||
| 7132 | +/// | ||
| 7133 | +/// ponytail: one transform length for the whole axis, so the bass end is a bin | ||
| 7134 | +/// (47 Hz at 48 kHz) wide however many columns are drawn across it -- a 60 Hz | ||
| 7135 | +/// hum and an 80 Hz one are the same hump down there. Upgrade path is the | ||
| 7136 | +/// analyser every mastering EQ uses: two or three transforms of different | ||
| 7137 | +/// lengths, each drawn over the octaves it resolves. | ||
| 7138 | +fn eq_spectrum(samples: &[f32], sample_rate: u32) -> Vec<f32> { | ||
| 7139 | + if samples.len() < EQ_FFT { | ||
| 7140 | + return Vec::new(); | ||
| 7141 | + } | ||
| 7142 | + let tail = &samples[samples.len() - EQ_FFT..]; | ||
| 7143 | + let mut re: Vec<f32> = tail | ||
| 7144 | + .iter() | ||
| 7145 | + .enumerate() | ||
| 7146 | + .map(|(i, s)| { | ||
| 7147 | + let w = 0.5 * (1. - (std::f32::consts::TAU * i as f32 / EQ_FFT as f32).cos()); | ||
| 7148 | + s * w | ||
| 7149 | + }) | ||
| 7150 | + .collect(); | ||
| 7151 | + let mut im = vec![0.; EQ_FFT]; | ||
| 7152 | + fft(&mut re, &mut im); | ||
| 7153 | + // Magnitude per bin, scaled so a full-scale sine reads 0 dBFS: half the | ||
| 7154 | + // energy is in the mirrored half of the transform, and the Hann window | ||
| 7155 | + // takes another factor of two off. | ||
| 7156 | + let mags: Vec<f32> = (0..EQ_FFT / 2) | ||
| 7157 | + .map(|k| (re[k] * re[k] + im[k] * im[k]).sqrt() * 4. / EQ_FFT as f32) | ||
| 7158 | + .collect(); | ||
| 7159 | + let bin_hz = sample_rate as f32 / EQ_FFT as f32; | ||
| 7160 | + let (floor, ceiling) = EQ_SPECTRUM_DB; | ||
| 7161 | + let at = |along: f32| EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); | ||
| 7162 | + (0..=EQ_CURVE_STEPS) | ||
| 7163 | + .map(|step| { | ||
| 7164 | + let along = step as f32 / EQ_CURVE_STEPS as f32; | ||
| 7165 | + let half = 0.5 / EQ_CURVE_STEPS as f32; | ||
| 7166 | + // Bin 0 is DC and means nothing here, so the low end starts at 1. | ||
| 7167 | + let low = (at(along - half) / bin_hz).round().max(1.) as usize; | ||
| 7168 | + let high = (at(along + half) / bin_hz).round().max(1.) as usize; | ||
| 7169 | + let peak = (low..=high) | ||
| 7170 | + .filter_map(|k| mags.get(k)) | ||
| 7171 | + .fold(0f32, |a, &b| a.max(b)); | ||
| 7172 | + let db = 20. * peak.max(1e-9).log10(); | ||
| 7173 | + ((db - floor) / (ceiling - floor)).clamp(0., 1.) | ||
| 7174 | + }) | ||
| 7175 | + .collect() | ||
| 7176 | +} | ||
| 7177 | + | ||
| 7178 | +/// The analyser drawn as one filled shape from the floor of the box. | ||
| 7179 | +fn eq_spectrum_curve(levels: Vec<f32>) -> impl IntoElement { | ||
| 7180 | + canvas( | ||
| 7181 | + |_, _, _| (), | ||
| 7182 | + move |bounds, _, window, _| { | ||
| 7183 | + let (o, s) = (bounds.origin, bounds.size); | ||
| 7184 | + let last = levels.len().saturating_sub(1).max(1) as f32; | ||
| 7185 | + let mut path = PathBuilder::fill(); | ||
| 7186 | + path.move_to(point(o.x, o.y + s.height)); | ||
| 7187 | + for (i, level) in levels.iter().enumerate() { | ||
| 7188 | + path.line_to(point( | ||
| 7189 | + o.x + s.width * (i as f32 / last), | ||
| 7190 | + o.y + s.height * (1. - level), | ||
| 7191 | + )); | ||
| 7192 | + } | ||
| 7193 | + path.line_to(point(o.x + s.width, o.y + s.height)); | ||
| 7194 | + path.close(); | ||
| 7195 | + if let Ok(path) = path.build() { | ||
| 7196 | + window.paint_path(path, rgba(EQ_SPECTRUM_INK)); | ||
| 7197 | + } | ||
| 7198 | + }, | ||
| 7199 | + ) | ||
| 7200 | + .absolute() | ||
| 7201 | + .size_full() | ||
| 7202 | +} | ||
| 7203 | + | ||
| 6948 | /// The cascade's frequency response, drawn as one line across the graph. | 7204 | /// The cascade's frequency response, drawn as one line across the graph. |
| 6949 | /// | 7205 | /// |
| 6950 | /// Every point comes from `EqParams::response_db`, which reads the very | 7206 | /// Every point comes from `EqParams::response_db`, which reads the very |
| @@ -6959,14 +7215,31 @@ fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement { | |||
| 6959 | |_, _, _| (), | 7215 | |_, _, _| (), |
| 6960 | move |bounds, _, window, _| { | 7216 | move |bounds, _, window, _| { |
| 6961 | let (o, s) = (bounds.origin, bounds.size); | 7217 | let (o, s) = (bounds.origin, bounds.size); |
| 7218 | + let points: Vec<_> = (0..=EQ_CURVE_STEPS) | ||
| 7219 | + .map(|step| { | ||
| 7220 | + let along = step as f32 / EQ_CURVE_STEPS as f32; | ||
| 7221 | + let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); | ||
| 7222 | + point( | ||
| 7223 | + o.x + s.width * along, | ||
| 7224 | + o.y + s.height * eq_y(params.response_db(freq, sample_rate)), | ||
| 7225 | + ) | ||
| 7226 | + }) | ||
| 7227 | + .collect(); | ||
| 7228 | + // The area between the curve and 0 dB, closed along that line: a | ||
| 7229 | + // boost and a cut wind opposite ways around it, which is exactly | ||
| 7230 | + // what makes both of them fill and the flat parts stay empty. | ||
| 7231 | + let mut area = PathBuilder::fill(); | ||
| 7232 | + area.move_to(point(o.x, o.y + s.height / 2.)); | ||
| 7233 | + for at in &points { | ||
| 7234 | + area.line_to(*at); | ||
| 7235 | + } | ||
| 7236 | + area.line_to(point(o.x + s.width, o.y + s.height / 2.)); | ||
| 7237 | + area.close(); | ||
| 7238 | + if let Ok(area) = area.build() { | ||
| 7239 | + window.paint_path(area, rgba(EQ_FILL_INK)); | ||
| 7240 | + } | ||
| 6962 | let mut path = PathBuilder::stroke(px(2.)); | 7241 | let mut path = PathBuilder::stroke(px(2.)); |
| 6963 | - for step in 0..=EQ_CURVE_STEPS { | 7242 | + for (step, at) in points.into_iter().enumerate() { |
| 6964 | - let along = step as f32 / EQ_CURVE_STEPS as f32; | ||
| 6965 | - let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); | ||
| 6966 | - let at = point( | ||
| 6967 | - o.x + s.width * along, | ||
| 6968 | - o.y + s.height * eq_y(params.response_db(freq, sample_rate)), | ||
| 6969 | - ); | ||
| 6970 | match step { | 7243 | match step { |
| 6971 | 0 => path.move_to(at), | 7244 | 0 => path.move_to(at), |
| 6972 | _ => path.line_to(at), | 7245 | _ => path.line_to(at), |
| @@ -7050,20 +7323,20 @@ fn timecode(t: f64, fps: f64) -> String { | |||
| 7050 | #[cfg(test)] | 7323 | #[cfg(test)] |
| 7051 | mod tests { | 7324 | mod tests { |
| 7052 | use super::{ | 7325 | use super::{ |
| 7053 | - ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH, | 7326 | + ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_CURVE_STEPS, |
| 7054 | - EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS, | 7327 | + EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_SPECTRUM_DB, |
| 7055 | - Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, | 7328 | + EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, |
| 7056 | - INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, | 7329 | + HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, |
| 7057 | - LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, | 7330 | + LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, |
| 7058 | - Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, | 7331 | + MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, |
| 7059 | - SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, | 7332 | + SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, |
| 7060 | - Wave, | 7333 | + VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, |
| 7061 | - applicable, band_label, can_add, cancels_export, color_snap, envelope, eq_x, eq_y, | 7334 | + cancels_export, color_snap, envelope, eq_spectrum, eq_x, eq_y, export_path, |
| 7062 | - export_path, export_settings, format_key, format_line, format_refusal, frac_along, | 7335 | + export_settings, format_key, format_line, format_refusal, frac_along, frac_down, frame_at, |
| 7063 | - frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, | 7336 | + histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, normalise, |
| 7064 | - menu_at, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label, | 7337 | + nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due, show_label, |
| 7065 | silence_rate, source_tint, span_partner, speed_at, start_frac, timecode, unseen_paths, | 7338 | silence_rate, source_tint, span_partner, speed_at, start_frac, timecode, unseen_paths, |
| 7066 | - nothing_to_play, unseen_sources, whole_take, width_frac, window_title, | 7339 | + unseen_sources, whole_take, width_frac, window_title, |
| 7067 | }; | 7340 | }; |
| 7068 | use super::{LaneKind, Repeat, file_name, file_uri, library_rows, repeats, unscannable}; | 7341 | use super::{LaneKind, Repeat, file_name, file_uri, library_rows, repeats, unscannable}; |
| 7069 | 7342 | ||
| @@ -8265,6 +8538,86 @@ mod tests { | |||
| 8265 | assert!(KEYS_ROW_H >= HIT_MIN); | 8538 | assert!(KEYS_ROW_H >= HIT_MIN); |
| 8266 | } | 8539 | } |
| 8267 | 8540 | ||
| 8541 | + /// The analyser drawn behind the curve: a tone has to land on its own | ||
| 8542 | + /// frequency, or the backdrop is a decoration rather than a reading of what | ||
| 8543 | + /// is playing -- and someone shaping a band against it would be aiming at | ||
| 8544 | + /// the wrong octave. | ||
| 8545 | + #[test] | ||
| 8546 | + fn the_spectrum_puts_a_tone_under_its_own_frequency() { | ||
| 8547 | + use std::f32::consts::TAU; | ||
| 8548 | + let rate = 48_000u32; | ||
| 8549 | + let sine = |hz: f32, amp: f32| -> Vec<f32> { | ||
| 8550 | + (0..EQ_FFT) | ||
| 8551 | + .map(|i| amp * (TAU * hz * i as f32 / rate as f32).sin()) | ||
| 8552 | + .collect() | ||
| 8553 | + }; | ||
| 8554 | + | ||
| 8555 | + // Silence is the floor of the box everywhere, not a band of noise. | ||
| 8556 | + let quiet = eq_spectrum(&vec![0.; EQ_FFT], rate); | ||
| 8557 | + assert_eq!(quiet.len(), EQ_CURVE_STEPS + 1); | ||
| 8558 | + assert!(quiet.iter().all(|&l| l == 0.), "silence drew something"); | ||
| 8559 | + | ||
| 8560 | + // A tone peaks over its own frequency, and the columns two octaves | ||
| 8561 | + // either side of it are near the floor. "Over" to within a bin down low | ||
| 8562 | + // and a column up high, which is all a 1024-point transform on a log | ||
| 8563 | + // axis can promise: at 200 Hz a whole column is a fraction of a bin | ||
| 8564 | + // wide, so the peak sits on the bin the tone fell in. | ||
| 8565 | + let column = |freq: f32| (eq_x(freq) * EQ_CURVE_STEPS as f32).round() as usize; | ||
| 8566 | + let freq_at = |col: usize| { | ||
| 8567 | + let along = col as f32 / EQ_CURVE_STEPS as f32; | ||
| 8568 | + EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along) | ||
| 8569 | + }; | ||
| 8570 | + for hz in [200., 1000., 5000.] { | ||
| 8571 | + let levels = eq_spectrum(&sine(hz, 0.05), rate); | ||
| 8572 | + let (at, top) = | ||
| 8573 | + levels | ||
| 8574 | + .iter() | ||
| 8575 | + .enumerate() | ||
| 8576 | + .fold((0, 0f32), |best, (i, &l)| match l > best.1 { | ||
| 8577 | + true => (i, l), | ||
| 8578 | + false => best, | ||
| 8579 | + }); | ||
| 8580 | + let slack = 1.5 * rate as f32 / EQ_FFT as f32 + 0.04 * hz; | ||
| 8581 | + assert!( | ||
| 8582 | + (freq_at(at) - hz).abs() <= slack, | ||
| 8583 | + "{hz} Hz peaked at {:.0} Hz (column {at})", | ||
| 8584 | + freq_at(at) | ||
| 8585 | + ); | ||
| 8586 | + // -26 dBFS, which is where a 0.05 tone sits on the axis. | ||
| 8587 | + let want = | ||
| 8588 | + (20. * 0.05f32.log10() - EQ_SPECTRUM_DB.0) / (EQ_SPECTRUM_DB.1 - EQ_SPECTRUM_DB.0); | ||
| 8589 | + assert!( | ||
| 8590 | + (top - want).abs() < 0.05, | ||
| 8591 | + "a -26 dBFS tone drew {top} of the box, not {want}" | ||
| 8592 | + ); | ||
| 8593 | + // Two octaves off is far enough down the box that the hump reads as | ||
| 8594 | + // one hump: 0.4 of the axis is a little over 30 dB. | ||
| 8595 | + for off in [hz / 4., hz * 4.] { | ||
| 8596 | + let away = levels[column(off).min(EQ_CURVE_STEPS)]; | ||
| 8597 | + assert!( | ||
| 8598 | + top - away > 0.4, | ||
| 8599 | + "{hz} Hz drew {top} but still {away} at {off} Hz" | ||
| 8600 | + ); | ||
| 8601 | + } | ||
| 8602 | + } | ||
| 8603 | + | ||
| 8604 | + // Level reads as level: 40 dB quieter sits lower by the fraction of the | ||
| 8605 | + // axis those 40 dB are. | ||
| 8606 | + let loud = eq_spectrum(&sine(1000., 0.05), rate); | ||
| 8607 | + let soft = eq_spectrum(&sine(1000., 0.0005), rate); | ||
| 8608 | + let at = column(1000.); | ||
| 8609 | + let drop = loud[at] - soft[at]; | ||
| 8610 | + let (floor, ceiling) = EQ_SPECTRUM_DB; | ||
| 8611 | + assert!( | ||
| 8612 | + (drop - 40. / (ceiling - floor)).abs() < 0.05, | ||
| 8613 | + "40 dB quieter moved the analyser {drop} of the box" | ||
| 8614 | + ); | ||
| 8615 | + | ||
| 8616 | + // A tap the engine has not filled yet (right after a seek) draws | ||
| 8617 | + // nothing at all rather than a transform of half a window. | ||
| 8618 | + assert!(eq_spectrum(&[0.; 16], rate).is_empty()); | ||
| 8619 | + } | ||
| 8620 | + | ||
| 8268 | /// The speed bar is the same round trip -- pixels -> rate -> fill -- with | 8621 | /// The speed bar is the same round trip -- pixels -> rate -> fill -- with |
| 8269 | /// one thing the colour sliders do not have to promise: **exactly 1.00x has | 8622 | /// one thing the colour sliders do not have to promise: **exactly 1.00x has |
| 8270 | /// to be reachable**, by a hand as well as by the reset. A grid that missed | 8623 | /// to be reachable**, by a hand as well as by the reset. A grid that missed |
| @@ -9211,6 +9564,7 @@ fn main() { | |||
| 9211 | eq_band: 0, | 9564 | eq_band: 0, |
| 9212 | eq_dragging: false, | 9565 | eq_dragging: false, |
| 9213 | eq_graph: Rc::default(), | 9566 | eq_graph: Rc::default(), |
| 9567 | + eq_spectrum: true, | ||
| 9214 | speed_open: None, | 9568 | speed_open: None, |
| 9215 | speed_bar: Rc::default(), | 9569 | speed_bar: Rc::default(), |
| 9216 | speed_dragging: false, | 9570 | 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 { |
| @@ -1500,6 +1525,21 @@ impl PlaybackSession { | |||
| 1500 | } | 1525 | } |
| 1501 | } | 1526 | } |
| 1502 | 1527 | ||
| 1528 | + /// A copy of the most recent mono samples the device was handed, and the | ||
| 1529 | + /// rate they play at: the signal *after* every clip's equalizer, speed and | ||
| 1530 | + /// the mix, which is what an analyser drawn behind an EQ curve has to show. | ||
| 1531 | + /// `None` with no audio output at all, and empty until the feeder has | ||
| 1532 | + /// written once (right after a seek, for instance). | ||
| 1533 | + /// | ||
| 1534 | + /// Never blocks anything that matters: the feeder holds this lock for one | ||
| 1535 | + /// memcpy and the device's own callback lives in the plugin, on the far | ||
| 1536 | + /// side of a ring buffer, where it cannot see this at all. | ||
| 1537 | + pub fn audio_tap(&self) -> Option<(Vec<f32>, u32)> { | ||
| 1538 | + let audio = self.audio.as_ref()?; | ||
| 1539 | + let tap = audio.tap.lock().unwrap().clone(); | ||
| 1540 | + Some((tap, audio.sample_rate)) | ||
| 1541 | + } | ||
| 1542 | + | ||
| 1503 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode | 1543 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode |
| 1504 | /// workers are replaced rather than steered: a fresh channel cannot hold a | 1544 | /// workers are replaced rather than steered: a fresh channel cannot hold a |
| 1505 | /// stale frame, and it works just as well after EOF, where the old workers | 1545 | /// stale frame, and it works just as well after EOF, where the old workers |
| @@ -1522,6 +1562,9 @@ impl PlaybackSession { | |||
| 1522 | // carrying can no longer reach the ring after this point. | 1562 | // carrying can no longer reach the ring after this point. |
| 1523 | audio.epoch.fetch_add(1, Ordering::Release); | 1563 | audio.epoch.fetch_add(1, Ordering::Release); |
| 1524 | ao.flush(); | 1564 | ao.flush(); |
| 1565 | + // The flushed samples are not being played any more, so nothing may | ||
| 1566 | + // still be drawn from them. | ||
| 1567 | + audio.tap.lock().unwrap().clear(); | ||
| 1525 | } | 1568 | } |
| 1526 | 1569 | ||
| 1527 | // Cancel first, drop second: the old worker may be parked in `send` on | 1570 | // Cancel first, drop second: the old worker may be parked in `send` on |
| @@ -1839,6 +1882,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) { | |||
| 1839 | fed_all: Arc::new(AtomicBool::new(false)), | 1882 | fed_all: Arc::new(AtomicBool::new(false)), |
| 1840 | died: Arc::new(AtomicBool::new(false)), | 1883 | died: Arc::new(AtomicBool::new(false)), |
| 1841 | epoch: Arc::new(AtomicU64::new(0)), | 1884 | epoch: Arc::new(AtomicU64::new(0)), |
| 1885 | + tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))), | ||
| 1842 | }; | 1886 | }; |
| 1843 | (audio.spawn_feeder(rx).then_some(audio), None) | 1887 | (audio.spawn_feeder(rx).then_some(audio), None) |
| 1844 | } | 1888 | } |
| @@ -1873,6 +1917,7 @@ fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) { | |||
| 1873 | } | 1917 | } |
| 1874 | }; | 1918 | }; |
| 1875 | audio.fed.fetch_add(accepted as u64, Ordering::Relaxed); | 1919 | audio.fed.fetch_add(accepted as u64, Ordering::Relaxed); |
| 1920 | + audio.note_tap(&pending[..accepted]); | ||
| 1876 | pending.drain(..accepted); | 1921 | pending.drain(..accepted); |
| 1877 | if !pending.is_empty() { | 1922 | if !pending.is_empty() { |
| 1878 | // Ring full: nothing to do but let the device drain it. | 1923 | // Ring full: nothing to do but let the device drain it. |