forge
Explore
Log in

Don't you dare go Hollow

The equalizer is a curve you drag, not five bars

Browse files at this commit

df008904c7da91e372337059340a877d3bbe0fa4Ahmet Kaan GümüşParent: 99fb07c
  • feat
    • the equalizer is a curve you drag, not five bars
Show full message
✨ feat(eq): the equalizer is a curve you drag, not five bars

The card now draws the clip's own frequency response across a log axis
(20 Hz - 20 kHz) with a handle per band on it: press anywhere in the box
and the nearest band follows the pointer up and down, and the curve
redraws on every sample of the drag, so the shape bends under the hand.
One undo step per gesture, as before -- the write is still the release's.

The curve is read from `EqParams::response_db`, which evaluates the very
biquad coefficients `EqState` filters with at z = e^jw. There is no
second copy of the maths, so a drawn curve cannot drift from what is
heard; a new test measures a sine through `process` at nine frequencies
and holds it to what the curve claimed, within half a dB.

The keyboard path is untouched: 1-5 pick a band, up/down move it, r
flattens, esc closes -- and a readout under the graph names the picked
band, which the sum of five curves cannot.
crates/app/src/main.rsmodified+313 -145
@@ -19,7 +19,7 @@ use engine::{Clip, ExportHandle, Frame, PlaybackSession};
19 use gpui::{19 use gpui::{
20 AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent,20 AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent,
21 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point,21 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point,
22- RenderImage, SharedString, Size, Stateful, TitlebarOptions, Window, WindowBounds,22+ RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, WindowBounds,
23 WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,23 WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,
24 };24 };
25 25
@@ -248,8 +248,33 @@ const EQ_GAIN_LIMIT: f32 = 12.;
248 /// single band.248 /// single band.
249 const EQ_STEP: f32 = 1.;249 const EQ_STEP: f32 = 1.;
250 250
251-/// The gain bar's height inside a band row.251+/// The graph's frequency axis: the range an ear works in, and the range every
252-const EQ_BAR_H: f32 = 6.;252+/// band a file can carry sits inside. Log-spaced, so an octave is an octave
253+/// wherever it falls.
254+const EQ_FREQ_LOW: f32 = 20.;
255+const EQ_FREQ_HIGH: f32 = 20_000.;
256+
257+/// The curve box. Tall enough that 1 dB is a visible move at the ±12 dB axis,
258+/// and short enough that the card still fits a 360 px window.
259+const EQ_GRAPH_H: f32 = 132.;
260+
261+/// How many points the curve is drawn from. One per ~3 px across the card:
262+/// past that the line is smooth and the extra biquad evaluations are wasted.
263+const EQ_CURVE_STEPS: usize = 96;
264+
265+/// A band's handle on the curve. Only the dot -- what is *grabbed* is the whole
266+/// graph (the nearest band along the frequency axis), so the target is the box.
267+const EQ_HANDLE: f32 = 10.;
268+
269+/// The frequencies the graph names, so the curve can be read as a curve *of
270+/// something*. The two ends label themselves at the edges.
271+const EQ_TICKS: [(f32, &str); 5] = [
272+ (20., "20 Hz"),
273+ (100., "100"),
274+ (1000., "1k"),
275+ (10000., "10k"),
276+ (20000., "20k"),
277+];
253 278
254 /// The colour card's four controls, in the order it lists them: what each is279 /// The colour card's four controls, in the order it lists them: what each is
255 /// called and the range it moves in. The order is `ColorParams`' own, which is280 /// called and the range it moves in. The order is `ColorParams`' own, which is
@@ -379,13 +404,14 @@ struct Player {
379 eq_params: EqParams,404 eq_params: EqParams,
380 /// Which band the keyboard moves, and which one a drag is holding.405 /// Which band the keyboard moves, and which one a drag is holding.
381 eq_band: usize,406 eq_band: usize,
382- /// A band's bar is being dragged. Tracked on the root like `scrubbing`, for407+ /// A handle on the curve is being dragged. Tracked on the root like
383- /// the same reason: the pointer leaves the 6 px bar immediately.408+ /// `scrubbing`, for the same reason: a hand pulling a band to +12 dB runs
409+ /// off the top of the graph long before it lets go.
384 eq_dragging: bool,410 eq_dragging: bool,
385- /// A band bar's own box, recorded at prepaint. One probe for five rows:411+ /// The curve box, recorded at prepaint: gpui hands a mouse listener the
386- /// they are laid out identically and only the *x* of a click is read412+ /// window position only, so this is what a press and a drag are read
387- /// ([`frac_along`]), so whichever row painted last answers for all of them.413+ /// against ([`frac_along`], [`frac_down`]).
388- eq_bar: Rc<Cell<Bounds<Pixels>>>,414+ eq_graph: Rc<Cell<Bounds<Pixels>>>,
389 /// The colour card is up on this clip -- the lane it is on and its index415 /// The colour card is up on this clip -- the lane it is on and its index
390 /// there. `None` when it is closed, which is the only place that state416 /// there. `None` when it is closed, which is the only place that state
391 /// lives: the grade itself is the project's.417 /// lives: the grade itself is the project's.
@@ -828,15 +854,34 @@ impl Player {
828 }854 }
829 }855 }
830 856
831- /// Where the pointer sits along a band's bar, as a gain: the middle is flat857+ /// Where the pointer sits down the graph, as a gain on the picked band: the
832- /// and the two ends are the limit either way.858+ /// middle is flat and the top and bottom edges are the limit either way.
833- fn drag_band(&mut self, x: Pixels, cx: &mut Context<Self>) {859+ /// Called on every pointer sample, so the curve bends under the hand; the
834- let gain = (frac_along(x, self.eq_bar.get()) * 2. - 1.) * EQ_GAIN_LIMIT;860+ /// write is the release's ([`commit_eq`](Player::commit_eq)).
861+ fn drag_band(&mut self, y: Pixels, cx: &mut Context<Self>) {
862+ let gain = (0.5 - frac_down(y, self.eq_graph.get())) * 2. * EQ_GAIN_LIMIT;
835 if self.set_band(self.eq_band, gain) {863 if self.set_band(self.eq_band, gain) {
836 cx.notify();864 cx.notify();
837 }865 }
838 }866 }
839 867
868+ /// Which band a press on the graph grabs: the nearest one along the
869+ /// frequency axis, so the whole box is the handle rather than a 10 px dot
870+ /// -- and a press that misses every dot still moves the band it is under.
871+ fn nearest_band(&self, x: Pixels) -> usize {
872+ let at = frac_along(x, self.eq_graph.get());
873+ self.eq_params
874+ .bands
875+ .iter()
876+ .enumerate()
877+ .min_by(|(_, a), (_, b)| {
878+ (eq_x(a.freq_hz) - at)
879+ .abs()
880+ .total_cmp(&(eq_x(b.freq_hz) - at).abs())
881+ })
882+ .map_or(0, |(i, _)| i)
883+ }
884+
840 /// Jumps the timeline.885 /// Jumps the timeline.
841 fn seek(&mut self, t: f64, cx: &mut Context<Self>) {886 fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
842 if self.exporting().is_some() {887 if self.exporting().is_some() {
@@ -1774,11 +1819,11 @@ impl Render for Player {
1774 // 6 px ruler on the first drag and its own listeners then stop1819 // 6 px ruler on the first drag and its own listeners then stop
1775 // firing; the root's hitbox is the whole window.1820 // firing; the root's hitbox is the whole window.
1776 .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {1821 .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {
1777- // A band's bar is 6 px tall and the pointer leaves it at once,1822+ // A handle is 10 px across and the pointer leaves it at once, so
1778- // so the equalizer drag is tracked here for the ruler's reason.1823+ // the equalizer drag is tracked here for the ruler's reason.
1779 if this.eq_dragging {1824 if this.eq_dragging {
1780 if event.pressed_button == Some(MouseButton::Left) {1825 if event.pressed_button == Some(MouseButton::Left) {
1781- this.drag_band(event.position.x, cx);1826+ this.drag_band(event.position.y, cx);
1782 } else {1827 } else {
1783 // Released outside the window: the up below never came,1828 // Released outside the window: the up below never came,
1784 // so this is where the gesture ends -- and it still owes1829 // so this is where the gesture ends -- and it still owes
@@ -1806,7 +1851,7 @@ impl Render for Player {
1806 if std::mem::take(&mut this.eq_dragging) {1851 if std::mem::take(&mut this.eq_dragging) {
1807 // The release lands exactly, then the gesture is written1852 // The release lands exactly, then the gesture is written
1808 // once -- the append-only table's whole reason.1853 // once -- the append-only table's whole reason.
1809- this.drag_band(event.position.x, cx);1854+ this.drag_band(event.position.y, cx);
1810 this.commit_eq(cx);1855 this.commit_eq(cx);
1811 return;1856 return;
1812 }1857 }
@@ -2762,11 +2807,15 @@ impl Player {
2762 )2807 )
2763 }2808 }
2764 2809
2765- /// The equalizer of one audio clip: a row per band, each a bar that reads2810+ /// The equalizer of one audio clip: its frequency response drawn as a
2766- /// flat in the middle and is dragged either way, and a row that flattens2811+ /// curve, a handle per band sitting on it, and a row that flattens them
2767- /// them all. The same scrim, width and rows as the other two cards, and the2812+ /// all. The curve is the clip's actual filter (`EqParams::response_db`
2768- /// same plain divs -- nothing here takes focus, so the root keeps the2813+ /// reads the coefficients the samples go through), and it is redrawn on
2769- /// keyboard and the card's own strokes (`1`–`5`, up, down, `r`) reach it.2814+ /// every pointer sample of a drag, so the shape bends under the hand.
2815+ ///
2816+ /// The same scrim and width as the other two cards, and the same plain divs
2817+ /// -- nothing here takes focus, so the root keeps the keyboard and the
2818+ /// card's own strokes (`1`–`5`, up, down, `r`) reach it.
2770 ///2819 ///
2771 /// Every change is written at the clip as it is made2820 /// Every change is written at the clip as it is made
2772 /// ([`Player::commit_eq`]), so what the card shows is always what is2821 /// ([`Player::commit_eq`]), so what the card shows is always what is
@@ -2774,72 +2823,90 @@ impl Player {
2774 /// nothing. What takes a curve back off is undo, like every other edit.2823 /// nothing. What takes a curve back off is undo, like every other edit.
2775 fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {2824 fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2776 let (lane, idx) = self.eq_open?;2825 let (lane, idx) = self.eq_open?;
2777- let rows: Vec<_> = self2826+ // The rate the engine filters this timeline at, so the drawn curve is
2827+ // the one those coefficients make -- near the top of the axis a 44.1 kHz
2828+ // clip and a 48 kHz one are not the same shape.
2829+ let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate);
2830+ let picked = self.eq_params.bands.get(self.eq_band);
2831+ let handles: Vec<_> = self
2778 .eq_params2832 .eq_params
2779 .bands2833 .bands
2780 .iter()2834 .iter()
2781 .enumerate()2835 .enumerate()
2782 .map(|(i, band)| {2836 .map(|(i, band)| {
2783- let (left, width) = eq_fill(band.gain_db);
2784 div()2837 div()
2785- .id(("eq-band", i))2838+ .absolute()
2786- .flex()2839+ .left(relative(eq_x(band.freq_hz)))
2787- .min_h(px(KEYS_ROW_H))2840+ .top(relative(eq_y(band.gain_db)))
2788- .items_center()2841+ // Centred on its own point: it hangs off the graph's corner,
2789- .gap(px(12.))2842+ // so it is pulled back by half of itself both ways.
2790- .px(px(6.))2843+ .ml(px(-EQ_HANDLE / 2.))
2791- .rounded(px(3.))2844+ .mt(px(-EQ_HANDLE / 2.))
2792- .cursor_pointer()2845+ .w(px(EQ_HANDLE))
2793- .when(i == self.eq_band, |d| d.bg(rgb(SELECTED)))2846+ .h(px(EQ_HANDLE))
2794- .hover(|s| s.bg(rgb(HOVER)))2847+ .rounded(px(EQ_HANDLE / 2.))
2795- // The press picks the band *and* is already the first2848+ .bg(rgb(match i == self.eq_band {
2796- // sample of the drag, so a plain click sets a value.2849+ true => ACCENT,
2797- .on_mouse_down(2850+ false => INK_DIM,
2798- MouseButton::Left,2851+ }))
2799- cx.listener(move |this, event: &MouseDownEvent, _, cx| {
2800- this.eq_band = i;
2801- this.eq_dragging = true;
2802- this.drag_band(event.position.x, cx);
2803- }),
2804- )
2805- .child(
2806- div()
2807- .flex_none()
2808- // Wide enough for "12 kHz high shelf", so the bars
2809- // below each other all start at the same pixel.
2810- .w(px(112.))
2811- .text_size(px(11.))
2812- .child(format!("{} {}", i + 1, band_label(band))),
2813- )
2814- .child(
2815- div()
2816- .flex_1()
2817- .h(px(EQ_BAR_H))
2818- .rounded(px(3.))
2819- .bg(rgb(SURFACE))
2820- .child(bounds_probe(self.eq_bar.clone()))
2821- .child(
2822- div()
2823- .absolute()
2824- .left(relative(left))
2825- .w(relative(width))
2826- .h_full()
2827- .rounded(px(3.))
2828- .bg(rgb(ACCENT)),
2829- ),
2830- )
2831- .child(
2832- div()
2833- .flex_none()
2834- // Fixed, so a sign or a second digit appearing does
2835- // not shift the bar beside it mid-drag.
2836- .w(px(56.))
2837- .text_size(px(11.))
2838- .text_color(rgb(INK_DIM))
2839- .child(format!("{:+.1} dB", band.gain_db)),
2840- )
2841 })2852 })
2842 .collect();2853 .collect();
2854+ let graph = div()
2855+ // Ided like the band rows it replaces: what the pointer presses on
2856+ // is one element with its own hitbox, which is what a drag is
2857+ // tracked from.
2858+ .id("eq-graph")
2859+ .relative()
2860+ .flex_none()
2861+ .h(px(EQ_GRAPH_H))
2862+ .rounded(px(3.))
2863+ .bg(rgb(HOVER_DIM))
2864+ .cursor_pointer()
2865+ // The press picks the band under it *and* is already the first
2866+ // sample of the drag, so a plain click sets a value.
2867+ .on_mouse_down(
2868+ MouseButton::Left,
2869+ cx.listener(|this, event: &MouseDownEvent, _, cx| {
2870+ this.eq_band = this.nearest_band(event.position.x);
2871+ this.eq_dragging = true;
2872+ this.drag_band(event.position.y, cx);
2873+ }),
2874+ )
2875+ .child(bounds_probe(self.eq_graph.clone()))
2876+ // 0 dB: the line a boost is a boost *from*.
2877+ .child(
2878+ div()
2879+ .absolute()
2880+ .top(relative(0.5))
2881+ .w_full()
2882+ .h(px(1.))
2883+ .bg(rgb(HOVER)),
2884+ )
2885+ .child(eq_curve(self.eq_params.clone(), sample_rate))
2886+ .children(handles)
2887+ .children(EQ_TICKS.map(|(freq, label)| {
2888+ div()
2889+ .absolute()
2890+ .left(relative(eq_x(freq)))
2891+ // Pulled back so the mark reads as sitting *at* its
2892+ // frequency; the two ends then hug the corners.
2893+ .ml(px(-12.))
2894+ .bottom(px(1.))
2895+ .w(px(24.))
2896+ .text_align(TextAlign::Center)
2897+ .text_size(px(9.))
2898+ .text_color(rgb(INK_DIM))
2899+ .child(label)
2900+ }))
2901+ .child(
2902+ div()
2903+ .absolute()
2904+ .top(px(2.))
2905+ .left(px(4.))
2906+ .text_size(px(9.))
2907+ .text_color(rgb(INK_DIM))
2908+ .child(format!("+{EQ_GAIN_LIMIT:.0} dB")),
2909+ );
2843 Some(2910 Some(
2844 div()2911 div()
2845 .absolute()2912 .absolute()
@@ -2874,22 +2941,24 @@ impl Player {
2874 .text_size(px(11.))2941 .text_size(px(11.))
2875 .text_color(rgb(INK_DIM))2942 .text_color(rgb(INK_DIM))
2876 .child(self.notice.clone().unwrap_or_else(|| {2943 .child(self.notice.clone().unwrap_or_else(|| {
2877- "drag a band, or 1–5 then up/down — esc closes".into()2944+ "drag the curve, or 1–5 then up/down — esc closes".into()
2878 })),2945 })),
2879 )2946 )
2880- // Five rows fit a 360 px window, but the layout is data2947+ .child(graph)
2881- // (a file may carry any number of bands), so the list2948+ // Which band the keyboard is holding and what it is set
2882- // scrolls like the other two cards' do.2949+ // to: the curve shows the sum, and a band pushed against
2883- .child(2950+ // one pulling the other way is not readable off it.
2884- div()2951+ .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(
2885- .id("eq-rows")2952+ match picked {
2886- .flex()2953+ Some(band) => format!(
2887- .flex_col()2954+ "{} {} {:+.1} dB",
2888- .gap(px(2.))2955+ self.eq_band + 1,
2889- .max_h(px(EXPORT_ROWS_H))2956+ band_label(band),
2890- .overflow_y_scroll()2957+ band.gain_db
2891- .children(rows),2958+ ),
2892- )2959+ None => "no bands".into(),
2960+ },
2961+ ))
2893 .child(2962 .child(
2894 div()2963 div()
2895 .id("eq-reset")2964 .id("eq-reset")
@@ -3646,18 +3715,22 @@ fn frame_at(secs: f64, fps: f64) -> u32 {
3646 (secs * fps + 1e-6).floor().max(0.) as u323715 (secs * fps + 1e-6).floor().max(0.) as u32
3647 }3716 }
3648 3717
3649-/// A band's bar as `(left, width)` in fractions of the track: the fill grows3718+/// Where a frequency sits across the graph, 0..1. Log, because an octave is an
3650-/// out of the *middle*, which is flat, towards whichever end the gain went --3719+/// octave whether it is 40 Hz wide or 10 kHz wide -- a linear axis would spend
3651-/// a bar that filled from the left would read a -12 dB cut as an empty control3720+/// three quarters of the card on the top two octaves and squeeze the bass, the
3652-/// and 0 dB as a half-off one. The inverse of [`Player::drag_band`]'s reading3721+/// half of the range people actually reach for, into nothing.
3653-/// of a click, and clamped like it, so a curve loaded from a file with a gain3722+fn eq_x(freq_hz: f32) -> f32 {
3654-/// past the card's limit paints at the end of the bar rather than outside it.3723+ let span = (EQ_FREQ_HIGH / EQ_FREQ_LOW).log10();
3655-fn eq_fill(gain_db: f32) -> (f32, f32) {3724+ ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.)
3656- let at = (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2. + 0.5;3725+}
3657- match at >= 0.5 {3726+
3658- true => (0.5, at - 0.5),3727+/// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle,
3659- false => (at, 0.5 - at),3728+/// so a cut reads as a dip below the line it is a cut from. The inverse of
3660- }3729+/// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a
3730+/// curve loaded from a file with a gain past the card's limit paints on the
3731+/// edge of the box rather than outside it.
3732+fn eq_y(gain_db: f32) -> f32 {
3733+ 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2.
3661 }3734 }
3662 3735
3663 /// What a band row calls itself: the corner or centre frequency, and for a3736 /// What a band row calls itself: the corner or centre frequency, and for a
@@ -4431,6 +4504,53 @@ fn frac_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
4431 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)4504 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
4432 }4505 }
4433 4506
4507+/// Where down an element a pointer sits, 0..1 from the top: the vertical twin
4508+/// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
4509+/// element that was never painted reads as its middle -- flat, the one answer
4510+/// that changes nothing -- rather than as a full boost.
4511+fn frac_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
4512+ if bounds.size.height <= px(0.) {
4513+ return 0.5;
4514+ }
4515+ ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)
4516+}
4517+
4518+/// The cascade's frequency response, drawn as one line across the graph.
4519+///
4520+/// Every point comes from `EqParams::response_db`, which reads the very
4521+/// coefficients the samples are filtered through: the curve cannot drift from
4522+/// what is heard, because there is no second copy of the maths.
4523+///
4524+/// ponytail: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the
4525+/// curve then rides the edge of the box; upgrade = a wider dB axis with the
4526+/// handles and [`Player::drag_band`] rescaled to it.
4527+fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement {
4528+ canvas(
4529+ |_, _, _| (),
4530+ move |bounds, _, window, _| {
4531+ let (o, s) = (bounds.origin, bounds.size);
4532+ let mut path = PathBuilder::stroke(px(2.));
4533+ for step in 0..=EQ_CURVE_STEPS {
4534+ let along = step as f32 / EQ_CURVE_STEPS as f32;
4535+ let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along);
4536+ let at = point(
4537+ o.x + s.width * along,
4538+ o.y + s.height * eq_y(params.response_db(freq, sample_rate)),
4539+ );
4540+ match step {
4541+ 0 => path.move_to(at),
4542+ _ => path.line_to(at),
4543+ }
4544+ }
4545+ if let Ok(path) = path.build() {
4546+ window.paint_path(path, rgb(ACCENT));
4547+ }
4548+ },
4549+ )
4550+ .absolute()
4551+ .size_full()
4552+}
4553+
4434 /// What a window with no file open is waiting for. Both ways in are already4554 /// What a window with no file open is waiting for. Both ways in are already
4435 /// built -- the whole window is the drop target and the Import chooser takes a4555 /// built -- the whole window is the drop target and the Import chooser takes a
4436 /// project as readily as media -- so this only has to say so.4556 /// project as readily as media -- so this only has to say so.
@@ -4500,16 +4620,17 @@ fn timecode(t: f64, fps: f64) -> String {
4500 #[cfg(test)]4620 #[cfg(test)]
4501 mod tests {4621 mod tests {
4502 use super::{4622 use super::{
4503- ACCENT, CONTROL_H, Clip, EQ_BAR_H, EQ_GAIN_LIMIT, EXPORT_ROWS_H, FORMATS, Format,4623+ ACCENT, CONTROL_H, Clip, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE,
4504- HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H,4624+ EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM,
4505- LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS,4625+ KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,
4506- MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE,4626+ LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,
4507- SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label,4627+ RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,
4508- can_add, cancels_export, envelope, eq_fill, export_path, export_settings, format_line,4628+ WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, envelope, eq_x,
4509- frac_along, frame_at, is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked,4629+ eq_y, export_path, export_settings, format_line, frac_along, frac_down, frame_at,
4510- menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due,4630+ is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked, menu_at, mp4_refusal,
4511- show_label, source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources,4631+ normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label,
4512- whole_take, width_frac, window_title,4632+ source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, whole_take,
4633+ width_frac, window_title,
4513 };4634 };
4514 use super::{file_name, library_rows};4635 use super::{file_name, library_rows};
4515 use engine::PlaybackSession;4636 use engine::PlaybackSession;
@@ -5043,6 +5164,18 @@ mod tests {
5043 assert_eq!(frac_along(px(9999.), bar), 1.);5164 assert_eq!(frac_along(px(9999.), bar), 1.);
5044 // Never painted: no division by zero, no NaN reaching seek().5165 // Never painted: no division by zero, no NaN reaching seek().
5045 assert_eq!(frac_along(px(50.), Bounds::default()), 0.);5166 assert_eq!(frac_along(px(50.), Bounds::default()), 0.);
5167+
5168+ // The equalizer's axis is the other one, and reads the same way.
5169+ let graph: Bounds<Pixels> = Bounds {
5170+ origin: point(px(12.), px(60.)),
5171+ size: size(px(296.), px(EQ_GRAPH_H)),
5172+ };
5173+ assert_eq!(frac_down(px(60.), graph), 0.);
5174+ assert_eq!(frac_down(px(60. + EQ_GRAPH_H / 2.), graph), 0.5);
5175+ assert_eq!(frac_down(px(9999.), graph), 1.);
5176+ // Never painted reads as flat: an unpainted graph must not slam a band
5177+ // to +12 dB on the first press.
5178+ assert_eq!(frac_down(px(50.), Bounds::default()), 0.5);
5046 }5179 }
5047 5180
5048 #[test]5181 #[test]
@@ -5248,36 +5381,60 @@ mod tests {
5248 assert!(KEYS_ROW_H >= HIT_MIN);5381 assert!(KEYS_ROW_H >= HIT_MIN);
5249 }5382 }
5250 5383
5251- /// The equalizer card: what its bars paint, and that it fits the window the5384+ /// The equalizer card's graph: where a band lands on it, that a drag reads
5252- /// other two cards are sized for. The bar is the one bit of geometry in the5385+ /// back as the gain it painted -- the two are one mapping and its inverse,
5253- /// card, and it is signed -- a fill that grew from the left would read a cut5386+ /// which is what makes a handle follow the pointer -- and that the card
5254- /// as an empty control -- so it is checked against the reading of a click,5387+ /// still fits the window the other two are sized for.
5255- /// which is the same mapping backwards ([`Player::drag_band`]).
5256 #[test]5388 #[test]
5257- fn the_equalizer_bar_grows_out_of_flat_and_the_card_fits_the_smallest_window() {5389+ fn the_equalizer_graph_puts_a_band_where_a_drag_reads_it_and_fits_the_smallest_window() {
5258 use engine::eq::{Band, BandKind, EqParams};5390 use engine::eq::{Band, BandKind, EqParams};
5259- // Flat is the middle and paints nothing: a band nobody has touched must5391+ // Flat is the middle of the box: a band nobody has touched must not
5260- // not look like one that has been turned down.5392+ // look like one that has been turned down.
5261- assert_eq!(eq_fill(0.), (0.5, 0.));5393+ assert_eq!(eq_y(0.), 0.5);
5262- // Full boost fills the right half, full cut the left one.5394+ // Full boost is the top edge, full cut the bottom one -- y grows down.
5263- assert_eq!(eq_fill(EQ_GAIN_LIMIT), (0.5, 0.5));5395+ assert_eq!(eq_y(EQ_GAIN_LIMIT), 0.);
5264- assert_eq!(eq_fill(-EQ_GAIN_LIMIT), (0., 0.5));5396+ assert_eq!(eq_y(-EQ_GAIN_LIMIT), 1.);
5265- assert_eq!(eq_fill(EQ_GAIN_LIMIT / 2.), (0.5, 0.25));5397+ assert_eq!(eq_y(EQ_GAIN_LIMIT / 2.), 0.25);
5266- assert_eq!(eq_fill(-EQ_GAIN_LIMIT / 2.), (0.25, 0.25));
5267 // A file may carry a gain past what this card offers (the format writes5398 // A file may carry a gain past what this card offers (the format writes
5268- // any finite value): it paints at the end, never off the track.5399+ // any finite value): it paints on the edge, never off the box.
5269- assert_eq!(eq_fill(400.), (0.5, 0.5));5400+ assert_eq!(eq_y(400.), 0.);
5270- assert_eq!(eq_fill(-400.), (0., 0.5));5401+ assert_eq!(eq_y(-400.), 1.);
5271 5402
5272- // A click reads back as the gain that paints where it landed, which is5403+ // A pointer reads back as the gain that paints where it landed, which
5273- // what makes a drag land where the pointer is.5404+ // is what makes a drag land under the hand ([`Player::drag_band`]).
5274 for gain in [-12., -6., 0., 6., 12.] {5405 for gain in [-12., -6., 0., 6., 12.] {
5275- let (left, width) = eq_fill(gain);5406+ let read = (0.5 - eq_y(gain)) * 2. * EQ_GAIN_LIMIT;
5276- let at = if gain >= 0. { left + width } else { left };
5277- let read = (at * 2. - 1.) * EQ_GAIN_LIMIT;
5278 assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}");5407 assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}");
5279 }5408 }
5280 5409
5410+ // The frequency axis is logarithmic and spans the audible range: the
5411+ // ends are the ends, and the decade at 200 Hz is as wide as the one at
5412+ // 2 kHz -- the whole reason a bass band is reachable at all.
5413+ assert_eq!(eq_x(EQ_FREQ_LOW), 0.);
5414+ assert_eq!(eq_x(EQ_FREQ_HIGH), 1.);
5415+ assert!((eq_x(200.) - 1. / 3.).abs() < 1e-4);
5416+ assert!(((eq_x(2000.) - eq_x(200.)) - (eq_x(20000.) - eq_x(2000.))).abs() < 1e-4);
5417+ // Off either end clamps rather than painting outside the box.
5418+ assert_eq!(eq_x(1.), 0.);
5419+ assert_eq!(eq_x(96_000.), 1.);
5420+ // Every tick the card names is on the axis it is drawn against.
5421+ for (freq, label) in EQ_TICKS {
5422+ assert!(
5423+ (EQ_FREQ_LOW..=EQ_FREQ_HIGH).contains(&freq),
5424+ "tick {label} is off the axis"
5425+ );
5426+ }
5427+ // The default bands all land inside it too, spread out enough that the
5428+ // nearest-band pick (`Player::nearest_band`) has something to pick.
5429+ let xs: Vec<f32> = EqParams::default_layout()
5430+ .bands
5431+ .iter()
5432+ .map(|b| eq_x(b.freq_hz))
5433+ .collect();
5434+ for pair in xs.windows(2) {
5435+ assert!(pair[1] - pair[0] > 0.1, "bands too close to aim at: {xs:?}");
5436+ }
5437+
5281 // Every default band says what it is, and a shelf says so: "12 kHz"5438 // Every default band says what it is, and a shelf says so: "12 kHz"
5282 // alone would not tell anyone it tilts the whole top octave.5439 // alone would not tell anyone it tilts the whole top octave.
5283 let labels: Vec<String> = EqParams::default_layout()5440 let labels: Vec<String> = EqParams::default_layout()
@@ -5306,17 +5463,28 @@ mod tests {
5306 "rounded, because a band label is not a measurement"5463 "rounded, because a band label is not a measurement"
5307 );5464 );
5308 5465
5309- // The same shape as the other two cards, so it fits where they do.5466+ // The same shape as the other two cards, so it fits where they do: the
5310- let (title, status, gaps, padding) = (17., 28., 3. * 2., 24.);5467+ // graph stands where the export card's rows do, and is shorter than
5468+ // they are.
5469+ let (title, status, readout, gaps, padding) = (17., 28., 17., 4. * 2., 24.);
5311 assert!(5470 assert!(
5312- title + status + EXPORT_ROWS_H + gaps + padding + CONTROL_H <= 360.,5471+ title + status + EQ_GRAPH_H + readout + gaps + padding + CONTROL_H <= 360.,
5313 "card too tall"5472 "card too tall"
5314 );5473 );
5474+ assert!(
5475+ EQ_GRAPH_H <= EXPORT_ROWS_H,
5476+ "graph taller than a card of rows"
5477+ );
5315 assert!(KEYS_W <= 640., "card too wide");5478 assert!(KEYS_W <= 640., "card too wide");
5316- // The rows are dragged, so WCAG 2.5.8 binds them like every other5479+ // What is dragged is the whole graph -- the handle is a 10 px dot, but
5317- // target in this window -- the 6 px bar is inside a full-height row.5480+ // a press anywhere in the box takes the band nearest it -- so WCAG
5481+ // 2.5.8 is satisfied by the box, which is far past the minimum.
5482+ assert!(EQ_GRAPH_H >= HIT_MIN);
5483+ assert!(
5484+ EQ_HANDLE < HIT_MIN,
5485+ "a dot that size would want its own hitbox"
5486+ );
5318 assert!(KEYS_ROW_H >= HIT_MIN);5487 assert!(KEYS_ROW_H >= HIT_MIN);
5319- assert!(EQ_BAR_H < KEYS_ROW_H);
5320 }5488 }
5321 5489
5322 /// Mute and level are one control with two states, and the whole point is5490 /// Mute and level are one control with two states, and the whole point is
@@ -5848,7 +6016,7 @@ fn main() {
5848 eq_params: EqParams::default(),6016 eq_params: EqParams::default(),
5849 eq_band: 0,6017 eq_band: 0,
5850 eq_dragging: false,6018 eq_dragging: false,
5851- eq_bar: Rc::default(),6019+ eq_graph: Rc::default(),
5852 color_open: None,6020 color_open: None,
5853 color_band: 0,6021 color_band: 0,
5854 // What an export is until someone says otherwise: the6022 // What an export is until someone says otherwise: the
crates/engine/src/eq.rsmodified+64 -0
@@ -67,6 +67,18 @@ impl EqParams {
67 pub fn is_identity(&self) -> bool {67 pub fn is_identity(&self) -> bool {
68 self.bands.iter().all(|b| b.gain_db.abs() < 1e-4)68 self.bands.iter().all(|b| b.gain_db.abs() < 1e-4)
69 }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+ }
70 }82 }
71 83
72 /// Normalized biquad coefficients (a0 divided out).84 /// Normalized biquad coefficients (a0 divided out).
@@ -128,6 +140,25 @@ impl Coeffs {
128 a2: (a2 / a0) as f32,140 a2: (a2 / a0) as f32,
129 }141 }
130 }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+ }
131 }162 }
132 163
133 /// Anything smaller than this is inaudible at any gain we allow, and letting it164 /// Anything smaller than this is inaudible at any gain we allow, and letting it
@@ -289,6 +320,39 @@ mod tests {
289 }320 }
290 }321 }
291 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+
292 #[test]356 #[test]
293 fn ten_seconds_of_noise_through_every_band_boosted_stays_bounded() {357 fn ten_seconds_of_noise_through_every_band_boosted_stays_bounded() {
294 let mut params = EqParams::default_layout();358 let mut params = EqParams::default_layout();