forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-acc043846df9c329a'

Browse files at this commit

288c31b296ceffdcea76e80092b1eb0b99511592Ahmet Kaan GümüşParent: cbb8a50df00890
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.
@@ -832,15 +858,34 @@ impl Player {
832 }858 }
833 }859 }
834 860
835- /// Where the pointer sits along a band's bar, as a gain: the middle is flat861+ /// Where the pointer sits down the graph, as a gain on the picked band: the
836- /// and the two ends are the limit either way.862+ /// middle is flat and the top and bottom edges are the limit either way.
837- fn drag_band(&mut self, x: Pixels, cx: &mut Context<Self>) {863+ /// Called on every pointer sample, so the curve bends under the hand; the
838- let gain = (frac_along(x, self.eq_bar.get()) * 2. - 1.) * EQ_GAIN_LIMIT;864+ /// write is the release's ([`commit_eq`](Player::commit_eq)).
865+ fn drag_band(&mut self, y: Pixels, cx: &mut Context<Self>) {
866+ let gain = (0.5 - frac_down(y, self.eq_graph.get())) * 2. * EQ_GAIN_LIMIT;
839 if self.set_band(self.eq_band, gain) {867 if self.set_band(self.eq_band, gain) {
840 cx.notify();868 cx.notify();
841 }869 }
842 }870 }
843 871
872+ /// Which band a press on the graph grabs: the nearest one along the
873+ /// frequency axis, so the whole box is the handle rather than a 10 px dot
874+ /// -- and a press that misses every dot still moves the band it is under.
875+ fn nearest_band(&self, x: Pixels) -> usize {
876+ let at = frac_along(x, self.eq_graph.get());
877+ self.eq_params
878+ .bands
879+ .iter()
880+ .enumerate()
881+ .min_by(|(_, a), (_, b)| {
882+ (eq_x(a.freq_hz) - at)
883+ .abs()
884+ .total_cmp(&(eq_x(b.freq_hz) - at).abs())
885+ })
886+ .map_or(0, |(i, _)| i)
887+ }
888+
844 /// Jumps the timeline.889 /// Jumps the timeline.
845 fn seek(&mut self, t: f64, cx: &mut Context<Self>) {890 fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
846 if self.exporting().is_some() {891 if self.exporting().is_some() {
@@ -1783,11 +1828,11 @@ impl Render for Player {
1783 // 6 px ruler on the first drag and its own listeners then stop1828 // 6 px ruler on the first drag and its own listeners then stop
1784 // firing; the root's hitbox is the whole window.1829 // firing; the root's hitbox is the whole window.
1785 .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {1830 .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {
1786- // A band's bar is 6 px tall and the pointer leaves it at once,1831+ // A handle is 10 px across and the pointer leaves it at once, so
1787- // so the equalizer drag is tracked here for the ruler's reason.1832+ // the equalizer drag is tracked here for the ruler's reason.
1788 if this.eq_dragging {1833 if this.eq_dragging {
1789 if event.pressed_button == Some(MouseButton::Left) {1834 if event.pressed_button == Some(MouseButton::Left) {
1790- this.drag_band(event.position.x, cx);1835+ this.drag_band(event.position.y, cx);
1791 } else {1836 } else {
1792 // Released outside the window: the up below never came,1837 // Released outside the window: the up below never came,
1793 // so this is where the gesture ends -- and it still owes1838 // so this is where the gesture ends -- and it still owes
@@ -1815,7 +1860,7 @@ impl Render for Player {
1815 if std::mem::take(&mut this.eq_dragging) {1860 if std::mem::take(&mut this.eq_dragging) {
1816 // The release lands exactly, then the gesture is written1861 // The release lands exactly, then the gesture is written
1817 // once -- the append-only table's whole reason.1862 // once -- the append-only table's whole reason.
1818- this.drag_band(event.position.x, cx);1863+ this.drag_band(event.position.y, cx);
1819 this.commit_eq(cx);1864 this.commit_eq(cx);
1820 return;1865 return;
1821 }1866 }
@@ -2798,11 +2843,15 @@ impl Player {
2798 )2843 )
2799 }2844 }
2800 2845
2801- /// The equalizer of one audio clip: a row per band, each a bar that reads2846+ /// The equalizer of one audio clip: its frequency response drawn as a
2802- /// flat in the middle and is dragged either way, and a row that flattens2847+ /// curve, a handle per band sitting on it, and a row that flattens them
2803- /// them all. The same scrim, width and rows as the other two cards, and the2848+ /// all. The curve is the clip's actual filter (`EqParams::response_db`
2804- /// same plain divs -- nothing here takes focus, so the root keeps the2849+ /// reads the coefficients the samples go through), and it is redrawn on
2805- /// keyboard and the card's own strokes (`1`–`5`, up, down, `r`) reach it.2850+ /// every pointer sample of a drag, so the shape bends under the hand.
2851+ ///
2852+ /// The same scrim and width as the other two cards, and the same plain divs
2853+ /// -- nothing here takes focus, so the root keeps the keyboard and the
2854+ /// card's own strokes (`1`–`5`, up, down, `r`) reach it.
2806 ///2855 ///
2807 /// Every change is written at the clip as it is made2856 /// Every change is written at the clip as it is made
2808 /// ([`Player::commit_eq`]), so what the card shows is always what is2857 /// ([`Player::commit_eq`]), so what the card shows is always what is
@@ -2810,72 +2859,90 @@ impl Player {
2810 /// nothing. What takes a curve back off is undo, like every other edit.2859 /// nothing. What takes a curve back off is undo, like every other edit.
2811 fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {2860 fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2812 let (lane, idx) = self.eq_open?;2861 let (lane, idx) = self.eq_open?;
2813- let rows: Vec<_> = self2862+ // The rate the engine filters this timeline at, so the drawn curve is
2863+ // the one those coefficients make -- near the top of the axis a 44.1 kHz
2864+ // clip and a 48 kHz one are not the same shape.
2865+ let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate);
2866+ let picked = self.eq_params.bands.get(self.eq_band);
2867+ let handles: Vec<_> = self
2814 .eq_params2868 .eq_params
2815 .bands2869 .bands
2816 .iter()2870 .iter()
2817 .enumerate()2871 .enumerate()
2818 .map(|(i, band)| {2872 .map(|(i, band)| {
2819- let (left, width) = eq_fill(band.gain_db);
2820 div()2873 div()
2821- .id(("eq-band", i))2874+ .absolute()
2822- .flex()2875+ .left(relative(eq_x(band.freq_hz)))
2823- .min_h(px(KEYS_ROW_H))2876+ .top(relative(eq_y(band.gain_db)))
2824- .items_center()2877+ // Centred on its own point: it hangs off the graph's corner,
2825- .gap(px(12.))2878+ // so it is pulled back by half of itself both ways.
2826- .px(px(6.))2879+ .ml(px(-EQ_HANDLE / 2.))
2827- .rounded(px(3.))2880+ .mt(px(-EQ_HANDLE / 2.))
2828- .cursor_pointer()2881+ .w(px(EQ_HANDLE))
2829- .when(i == self.eq_band, |d| d.bg(rgb(SELECTED)))2882+ .h(px(EQ_HANDLE))
2830- .hover(|s| s.bg(rgb(HOVER)))2883+ .rounded(px(EQ_HANDLE / 2.))
2831- // The press picks the band *and* is already the first2884+ .bg(rgb(match i == self.eq_band {
2832- // sample of the drag, so a plain click sets a value.2885+ true => ACCENT,
2833- .on_mouse_down(2886+ false => INK_DIM,
2834- MouseButton::Left,2887+ }))
2835- cx.listener(move |this, event: &MouseDownEvent, _, cx| {
2836- this.eq_band = i;
2837- this.eq_dragging = true;
2838- this.drag_band(event.position.x, cx);
2839- }),
2840- )
2841- .child(
2842- div()
2843- .flex_none()
2844- // Wide enough for "12 kHz high shelf", so the bars
2845- // below each other all start at the same pixel.
2846- .w(px(112.))
2847- .text_size(px(11.))
2848- .child(format!("{} {}", i + 1, band_label(band))),
2849- )
2850- .child(
2851- div()
2852- .flex_1()
2853- .h(px(EQ_BAR_H))
2854- .rounded(px(3.))
2855- .bg(rgb(SURFACE))
2856- .child(bounds_probe(self.eq_bar.clone()))
2857- .child(
2858- div()
2859- .absolute()
2860- .left(relative(left))
2861- .w(relative(width))
2862- .h_full()
2863- .rounded(px(3.))
2864- .bg(rgb(ACCENT)),
2865- ),
2866- )
2867- .child(
2868- div()
2869- .flex_none()
2870- // Fixed, so a sign or a second digit appearing does
2871- // not shift the bar beside it mid-drag.
2872- .w(px(56.))
2873- .text_size(px(11.))
2874- .text_color(rgb(INK_DIM))
2875- .child(format!("{:+.1} dB", band.gain_db)),
2876- )
2877 })2888 })
2878 .collect();2889 .collect();
2890+ let graph = div()
2891+ // Ided like the band rows it replaces: what the pointer presses on
2892+ // is one element with its own hitbox, which is what a drag is
2893+ // tracked from.
2894+ .id("eq-graph")
2895+ .relative()
2896+ .flex_none()
2897+ .h(px(EQ_GRAPH_H))
2898+ .rounded(px(3.))
2899+ .bg(rgb(HOVER_DIM))
2900+ .cursor_pointer()
2901+ // The press picks the band under it *and* is already the first
2902+ // sample of the drag, so a plain click sets a value.
2903+ .on_mouse_down(
2904+ MouseButton::Left,
2905+ cx.listener(|this, event: &MouseDownEvent, _, cx| {
2906+ this.eq_band = this.nearest_band(event.position.x);
2907+ this.eq_dragging = true;
2908+ this.drag_band(event.position.y, cx);
2909+ }),
2910+ )
2911+ .child(bounds_probe(self.eq_graph.clone()))
2912+ // 0 dB: the line a boost is a boost *from*.
2913+ .child(
2914+ div()
2915+ .absolute()
2916+ .top(relative(0.5))
2917+ .w_full()
2918+ .h(px(1.))
2919+ .bg(rgb(HOVER)),
2920+ )
2921+ .child(eq_curve(self.eq_params.clone(), sample_rate))
2922+ .children(handles)
2923+ .children(EQ_TICKS.map(|(freq, label)| {
2924+ div()
2925+ .absolute()
2926+ .left(relative(eq_x(freq)))
2927+ // Pulled back so the mark reads as sitting *at* its
2928+ // frequency; the two ends then hug the corners.
2929+ .ml(px(-12.))
2930+ .bottom(px(1.))
2931+ .w(px(24.))
2932+ .text_align(TextAlign::Center)
2933+ .text_size(px(9.))
2934+ .text_color(rgb(INK_DIM))
2935+ .child(label)
2936+ }))
2937+ .child(
2938+ div()
2939+ .absolute()
2940+ .top(px(2.))
2941+ .left(px(4.))
2942+ .text_size(px(9.))
2943+ .text_color(rgb(INK_DIM))
2944+ .child(format!("+{EQ_GAIN_LIMIT:.0} dB")),
2945+ );
2879 Some(2946 Some(
2880 div()2947 div()
2881 .absolute()2948 .absolute()
@@ -2910,22 +2977,24 @@ impl Player {
2910 .text_size(px(11.))2977 .text_size(px(11.))
2911 .text_color(rgb(INK_DIM))2978 .text_color(rgb(INK_DIM))
2912 .child(self.notice.clone().unwrap_or_else(|| {2979 .child(self.notice.clone().unwrap_or_else(|| {
2913- "drag a band, or 1–5 then up/down — esc closes".into()2980+ "drag the curve, or 1–5 then up/down — esc closes".into()
2914 })),2981 })),
2915 )2982 )
2916- // Five rows fit a 360 px window, but the layout is data2983+ .child(graph)
2917- // (a file may carry any number of bands), so the list2984+ // Which band the keyboard is holding and what it is set
2918- // scrolls like the other two cards' do.2985+ // to: the curve shows the sum, and a band pushed against
2919- .child(2986+ // one pulling the other way is not readable off it.
2920- div()2987+ .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(
2921- .id("eq-rows")2988+ match picked {
2922- .flex()2989+ Some(band) => format!(
2923- .flex_col()2990+ "{} {} {:+.1} dB",
2924- .gap(px(2.))2991+ self.eq_band + 1,
2925- .max_h(px(EXPORT_ROWS_H))2992+ band_label(band),
2926- .overflow_y_scroll()2993+ band.gain_db
2927- .children(rows),2994+ ),
2928- )2995+ None => "no bands".into(),
2996+ },
2997+ ))
2929 .child(2998 .child(
2930 div()2999 div()
2931 .id("eq-reset")3000 .id("eq-reset")
@@ -3737,18 +3806,22 @@ fn frame_at(secs: f64, fps: f64) -> u32 {
3737 (secs * fps + 1e-6).floor().max(0.) as u323806 (secs * fps + 1e-6).floor().max(0.) as u32
3738 }3807 }
3739 3808
3740-/// A band's bar as `(left, width)` in fractions of the track: the fill grows3809+/// Where a frequency sits across the graph, 0..1. Log, because an octave is an
3741-/// out of the *middle*, which is flat, towards whichever end the gain went --3810+/// octave whether it is 40 Hz wide or 10 kHz wide -- a linear axis would spend
3742-/// a bar that filled from the left would read a -12 dB cut as an empty control3811+/// three quarters of the card on the top two octaves and squeeze the bass, the
3743-/// and 0 dB as a half-off one. The inverse of [`Player::drag_band`]'s reading3812+/// half of the range people actually reach for, into nothing.
3744-/// of a click, and clamped like it, so a curve loaded from a file with a gain3813+fn eq_x(freq_hz: f32) -> f32 {
3745-/// past the card's limit paints at the end of the bar rather than outside it.3814+ let span = (EQ_FREQ_HIGH / EQ_FREQ_LOW).log10();
3746-fn eq_fill(gain_db: f32) -> (f32, f32) {3815+ ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.)
3747- let at = (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2. + 0.5;3816+}
3748- match at >= 0.5 {3817+
3749- true => (0.5, at - 0.5),3818+/// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle,
3750- false => (at, 0.5 - at),3819+/// so a cut reads as a dip below the line it is a cut from. The inverse of
3751- }3820+/// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a
3821+/// curve loaded from a file with a gain past the card's limit paints on the
3822+/// edge of the box rather than outside it.
3823+fn eq_y(gain_db: f32) -> f32 {
3824+ 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2.
3752 }3825 }
3753 3826
3754 /// What a band row calls itself: the corner or centre frequency, and for a3827 /// What a band row calls itself: the corner or centre frequency, and for a
@@ -4522,6 +4595,53 @@ fn frac_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
4522 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)4595 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
4523 }4596 }
4524 4597
4598+/// Where down an element a pointer sits, 0..1 from the top: the vertical twin
4599+/// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
4600+/// element that was never painted reads as its middle -- flat, the one answer
4601+/// that changes nothing -- rather than as a full boost.
4602+fn frac_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
4603+ if bounds.size.height <= px(0.) {
4604+ return 0.5;
4605+ }
4606+ ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)
4607+}
4608+
4609+/// The cascade's frequency response, drawn as one line across the graph.
4610+///
4611+/// Every point comes from `EqParams::response_db`, which reads the very
4612+/// coefficients the samples are filtered through: the curve cannot drift from
4613+/// what is heard, because there is no second copy of the maths.
4614+///
4615+/// ponytail: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the
4616+/// curve then rides the edge of the box; upgrade = a wider dB axis with the
4617+/// handles and [`Player::drag_band`] rescaled to it.
4618+fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement {
4619+ canvas(
4620+ |_, _, _| (),
4621+ move |bounds, _, window, _| {
4622+ let (o, s) = (bounds.origin, bounds.size);
4623+ let mut path = PathBuilder::stroke(px(2.));
4624+ for step in 0..=EQ_CURVE_STEPS {
4625+ let along = step as f32 / EQ_CURVE_STEPS as f32;
4626+ let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along);
4627+ let at = point(
4628+ o.x + s.width * along,
4629+ o.y + s.height * eq_y(params.response_db(freq, sample_rate)),
4630+ );
4631+ match step {
4632+ 0 => path.move_to(at),
4633+ _ => path.line_to(at),
4634+ }
4635+ }
4636+ if let Ok(path) = path.build() {
4637+ window.paint_path(path, rgb(ACCENT));
4638+ }
4639+ },
4640+ )
4641+ .absolute()
4642+ .size_full()
4643+}
4644+
4525 /// What a window with no file open is waiting for. Both ways in are already4645 /// What a window with no file open is waiting for. Both ways in are already
4526 /// built -- the whole window is the drop target and the Import chooser takes a4646 /// built -- the whole window is the drop target and the Import chooser takes a
4527 /// project as readily as media -- so this only has to say so.4647 /// project as readily as media -- so this only has to say so.
@@ -4591,16 +4711,17 @@ fn timecode(t: f64, fps: f64) -> String {
4591 #[cfg(test)]4711 #[cfg(test)]
4592 mod tests {4712 mod tests {
4593 use super::{4713 use super::{
4594- ACCENT, CONTROL_H, Clip, EQ_BAR_H, EQ_GAIN_LIMIT, EXPORT_ROWS_H, FORMATS, Format,4714+ ACCENT, CONTROL_H, Clip, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE,
4595- HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H,4715+ EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM,
4596- LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS,4716+ KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,
4597- MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE,4717+ LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,
4598- SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label,4718+ RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,
4599- can_add, cancels_export, envelope, eq_fill, export_path, export_settings, format_line,4719+ WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, envelope, eq_x,
4600- frac_along, frame_at, is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked,4720+ eq_y, export_path, export_settings, format_line, frac_along, frac_down, frame_at,
4601- menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due,4721+ is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked, menu_at, mp4_refusal,
4602- show_label, source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources,4722+ normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label,
4603- whole_take, width_frac, window_title,4723+ source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, whole_take,
4724+ width_frac, window_title,
4604 };4725 };
4605 use super::{file_name, file_uri, library_rows};4726 use super::{file_name, file_uri, library_rows};
4606 4727
@@ -5149,6 +5270,18 @@ mod tests {
5149 assert_eq!(frac_along(px(9999.), bar), 1.);5270 assert_eq!(frac_along(px(9999.), bar), 1.);
5150 // Never painted: no division by zero, no NaN reaching seek().5271 // Never painted: no division by zero, no NaN reaching seek().
5151 assert_eq!(frac_along(px(50.), Bounds::default()), 0.);5272 assert_eq!(frac_along(px(50.), Bounds::default()), 0.);
5273+
5274+ // The equalizer's axis is the other one, and reads the same way.
5275+ let graph: Bounds<Pixels> = Bounds {
5276+ origin: point(px(12.), px(60.)),
5277+ size: size(px(296.), px(EQ_GRAPH_H)),
5278+ };
5279+ assert_eq!(frac_down(px(60.), graph), 0.);
5280+ assert_eq!(frac_down(px(60. + EQ_GRAPH_H / 2.), graph), 0.5);
5281+ assert_eq!(frac_down(px(9999.), graph), 1.);
5282+ // Never painted reads as flat: an unpainted graph must not slam a band
5283+ // to +12 dB on the first press.
5284+ assert_eq!(frac_down(px(50.), Bounds::default()), 0.5);
5152 }5285 }
5153 5286
5154 #[test]5287 #[test]
@@ -5354,36 +5487,60 @@ mod tests {
5354 assert!(KEYS_ROW_H >= HIT_MIN);5487 assert!(KEYS_ROW_H >= HIT_MIN);
5355 }5488 }
5356 5489
5357- /// The equalizer card: what its bars paint, and that it fits the window the5490+ /// The equalizer card's graph: where a band lands on it, that a drag reads
5358- /// other two cards are sized for. The bar is the one bit of geometry in the5491+ /// back as the gain it painted -- the two are one mapping and its inverse,
5359- /// card, and it is signed -- a fill that grew from the left would read a cut5492+ /// which is what makes a handle follow the pointer -- and that the card
5360- /// as an empty control -- so it is checked against the reading of a click,5493+ /// still fits the window the other two are sized for.
5361- /// which is the same mapping backwards ([`Player::drag_band`]).
5362 #[test]5494 #[test]
5363- fn the_equalizer_bar_grows_out_of_flat_and_the_card_fits_the_smallest_window() {5495+ fn the_equalizer_graph_puts_a_band_where_a_drag_reads_it_and_fits_the_smallest_window() {
5364 use engine::eq::{Band, BandKind, EqParams};5496 use engine::eq::{Band, BandKind, EqParams};
5365- // Flat is the middle and paints nothing: a band nobody has touched must5497+ // Flat is the middle of the box: a band nobody has touched must not
5366- // not look like one that has been turned down.5498+ // look like one that has been turned down.
5367- assert_eq!(eq_fill(0.), (0.5, 0.));5499+ assert_eq!(eq_y(0.), 0.5);
5368- // Full boost fills the right half, full cut the left one.5500+ // Full boost is the top edge, full cut the bottom one -- y grows down.
5369- assert_eq!(eq_fill(EQ_GAIN_LIMIT), (0.5, 0.5));5501+ assert_eq!(eq_y(EQ_GAIN_LIMIT), 0.);
5370- assert_eq!(eq_fill(-EQ_GAIN_LIMIT), (0., 0.5));5502+ assert_eq!(eq_y(-EQ_GAIN_LIMIT), 1.);
5371- assert_eq!(eq_fill(EQ_GAIN_LIMIT / 2.), (0.5, 0.25));5503+ assert_eq!(eq_y(EQ_GAIN_LIMIT / 2.), 0.25);
5372- assert_eq!(eq_fill(-EQ_GAIN_LIMIT / 2.), (0.25, 0.25));
5373 // A file may carry a gain past what this card offers (the format writes5504 // A file may carry a gain past what this card offers (the format writes
5374- // any finite value): it paints at the end, never off the track.5505+ // any finite value): it paints on the edge, never off the box.
5375- assert_eq!(eq_fill(400.), (0.5, 0.5));5506+ assert_eq!(eq_y(400.), 0.);
5376- assert_eq!(eq_fill(-400.), (0., 0.5));5507+ assert_eq!(eq_y(-400.), 1.);
5377 5508
5378- // A click reads back as the gain that paints where it landed, which is5509+ // A pointer reads back as the gain that paints where it landed, which
5379- // what makes a drag land where the pointer is.5510+ // is what makes a drag land under the hand ([`Player::drag_band`]).
5380 for gain in [-12., -6., 0., 6., 12.] {5511 for gain in [-12., -6., 0., 6., 12.] {
5381- let (left, width) = eq_fill(gain);5512+ let read = (0.5 - eq_y(gain)) * 2. * EQ_GAIN_LIMIT;
5382- let at = if gain >= 0. { left + width } else { left };
5383- let read = (at * 2. - 1.) * EQ_GAIN_LIMIT;
5384 assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}");5513 assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}");
5385 }5514 }
5386 5515
5516+ // The frequency axis is logarithmic and spans the audible range: the
5517+ // ends are the ends, and the decade at 200 Hz is as wide as the one at
5518+ // 2 kHz -- the whole reason a bass band is reachable at all.
5519+ assert_eq!(eq_x(EQ_FREQ_LOW), 0.);
5520+ assert_eq!(eq_x(EQ_FREQ_HIGH), 1.);
5521+ assert!((eq_x(200.) - 1. / 3.).abs() < 1e-4);
5522+ assert!(((eq_x(2000.) - eq_x(200.)) - (eq_x(20000.) - eq_x(2000.))).abs() < 1e-4);
5523+ // Off either end clamps rather than painting outside the box.
5524+ assert_eq!(eq_x(1.), 0.);
5525+ assert_eq!(eq_x(96_000.), 1.);
5526+ // Every tick the card names is on the axis it is drawn against.
5527+ for (freq, label) in EQ_TICKS {
5528+ assert!(
5529+ (EQ_FREQ_LOW..=EQ_FREQ_HIGH).contains(&freq),
5530+ "tick {label} is off the axis"
5531+ );
5532+ }
5533+ // The default bands all land inside it too, spread out enough that the
5534+ // nearest-band pick (`Player::nearest_band`) has something to pick.
5535+ let xs: Vec<f32> = EqParams::default_layout()
5536+ .bands
5537+ .iter()
5538+ .map(|b| eq_x(b.freq_hz))
5539+ .collect();
5540+ for pair in xs.windows(2) {
5541+ assert!(pair[1] - pair[0] > 0.1, "bands too close to aim at: {xs:?}");
5542+ }
5543+
5387 // Every default band says what it is, and a shelf says so: "12 kHz"5544 // Every default band says what it is, and a shelf says so: "12 kHz"
5388 // alone would not tell anyone it tilts the whole top octave.5545 // alone would not tell anyone it tilts the whole top octave.
5389 let labels: Vec<String> = EqParams::default_layout()5546 let labels: Vec<String> = EqParams::default_layout()
@@ -5412,17 +5569,28 @@ mod tests {
5412 "rounded, because a band label is not a measurement"5569 "rounded, because a band label is not a measurement"
5413 );5570 );
5414 5571
5415- // The same shape as the other two cards, so it fits where they do.5572+ // The same shape as the other two cards, so it fits where they do: the
5416- let (title, status, gaps, padding) = (17., 28., 3. * 2., 24.);5573+ // graph stands where the export card's rows do, and is shorter than
5574+ // they are.
5575+ let (title, status, readout, gaps, padding) = (17., 28., 17., 4. * 2., 24.);
5417 assert!(5576 assert!(
5418- title + status + EXPORT_ROWS_H + gaps + padding + CONTROL_H <= 360.,5577+ title + status + EQ_GRAPH_H + readout + gaps + padding + CONTROL_H <= 360.,
5419 "card too tall"5578 "card too tall"
5420 );5579 );
5580+ assert!(
5581+ EQ_GRAPH_H <= EXPORT_ROWS_H,
5582+ "graph taller than a card of rows"
5583+ );
5421 assert!(KEYS_W <= 640., "card too wide");5584 assert!(KEYS_W <= 640., "card too wide");
5422- // The rows are dragged, so WCAG 2.5.8 binds them like every other5585+ // What is dragged is the whole graph -- the handle is a 10 px dot, but
5423- // target in this window -- the 6 px bar is inside a full-height row.5586+ // a press anywhere in the box takes the band nearest it -- so WCAG
5587+ // 2.5.8 is satisfied by the box, which is far past the minimum.
5588+ assert!(EQ_GRAPH_H >= HIT_MIN);
5589+ assert!(
5590+ EQ_HANDLE < HIT_MIN,
5591+ "a dot that size would want its own hitbox"
5592+ );
5424 assert!(KEYS_ROW_H >= HIT_MIN);5593 assert!(KEYS_ROW_H >= HIT_MIN);
5425- assert!(EQ_BAR_H < KEYS_ROW_H);
5426 }5594 }
5427 5595
5428 /// Mute and level are one control with two states, and the whole point is5596 /// Mute and level are one control with two states, and the whole point is
@@ -5954,7 +6122,7 @@ fn main() {
5954 eq_params: EqParams::default(),6122 eq_params: EqParams::default(),
5955 eq_band: 0,6123 eq_band: 0,
5956 eq_dragging: false,6124 eq_dragging: false,
5957- eq_bar: Rc::default(),6125+ eq_graph: Rc::default(),
5958 color_open: None,6126 color_open: None,
5959 color_band: 0,6127 color_band: 0,
5960 // What an export is until someone says otherwise: the6128 // 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();