diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 9bcb314..62181e5 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -51,13 +51,14 @@ pub enum ActionId { ToggleMute, VolumeUp, VolumeDown, + Equalizer, CancelExport, } impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 14] = [ + pub const ALL: [ActionId; 15] = [ ActionId::Play, ActionId::Export, ActionId::Save, @@ -71,6 +72,7 @@ impl ActionId { ActionId::ToggleMute, ActionId::VolumeUp, ActionId::VolumeDown, + ActionId::Equalizer, ActionId::CancelExport, ]; @@ -90,6 +92,7 @@ impl ActionId { ActionId::ToggleMute => "Mute / Unmute", ActionId::VolumeUp => "Volume up", ActionId::VolumeDown => "Volume down", + ActionId::Equalizer => "Equalizer", ActionId::CancelExport => "Cancel export", } } @@ -111,6 +114,7 @@ impl ActionId { ActionId::ToggleMute => "toggle-mute", ActionId::VolumeUp => "volume-up", ActionId::VolumeDown => "volume-down", + ActionId::Equalizer => "equalizer", ActionId::CancelExport => "cancel-export", } } @@ -127,7 +131,10 @@ impl ActionId { ActionId::Play => Category::Playback, ActionId::Copy | ActionId::Paste | ActionId::Delete | ActionId::Lift => Category::Clips, ActionId::Cut | ActionId::Regroup | ActionId::Undo => Category::Editing, - ActionId::ToggleMute | ActionId::VolumeUp | ActionId::VolumeDown => Category::Audio, + ActionId::ToggleMute + | ActionId::VolumeUp + | ActionId::VolumeDown + | ActionId::Equalizer => Category::Audio, ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File, } } @@ -179,7 +186,7 @@ pub struct Fixed { pub category: Category, } -pub const FIXED: [Fixed; 5] = [ +pub const FIXED: [Fixed; 9] = [ Fixed { chord: "esc", label: "Close this card or clip menu, or cancel a capture", @@ -205,6 +212,29 @@ pub const FIXED: [Fixed; 5] = [ label: "Erase a bitrate digit", category: Category::File, }, + // The equalizer card's own input, for the same reason the export card has + // its own: a band nothing but a drag can reach is a band half the users of + // this editor cannot move at all. Card-local, so none of them is bindable. + Fixed { + chord: "1–5", + label: "Pick an equalizer band", + category: Category::Audio, + }, + Fixed { + chord: "up", + label: "Raise the picked band 1 dB", + category: Category::Audio, + }, + Fixed { + chord: "down", + label: "Lower the picked band 1 dB", + category: Category::Audio, + }, + Fixed { + chord: "r", + label: "Flatten every band", + category: Category::Audio, + }, ]; /// A stroke as the key handler sees it: gpui's key name plus the one modifier @@ -316,6 +346,9 @@ impl Keymap { // player has, without asking for shift to make the "+". b(ActionId::VolumeUp, "=", false), b(ActionId::VolumeDown, "-", false), + // The one free letter that says the word: "e" is already the + // export and an equalizer is the q in nobody else's way. + b(ActionId::Equalizer, "q", false), b(ActionId::CancelExport, "escape", false), ], } @@ -542,7 +575,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 16); + assert_eq!(k.entries().len(), 17); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); assert_eq!(k.lookup("e", false), Some(ActionId::Export)); assert_eq!(k.lookup("s", true), Some(ActionId::Save)); @@ -556,6 +589,7 @@ mod tests { assert_eq!(k.lookup("z", false), Some(ActionId::Undo)); assert_eq!(k.lookup("z", true), Some(ActionId::Undo)); assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute)); + assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer)); // The volume pair is the unshifted one, so neither needs a modifier // and neither is the "+" gpui reports for shift+=. assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp)); @@ -565,7 +599,7 @@ mod tests { // The modifier is half the chord: ctrl+e is not e. assert_eq!(k.lookup("e", true), None); assert_eq!(k.lookup("space", true), None); - assert_eq!(k.lookup("q", false), None); + assert_eq!(k.lookup("j", false), None); // Nothing is bound twice, or lookup's first match would be a coin toss. for (i, a) in k.entries().iter().enumerate() { assert!( @@ -689,7 +723,7 @@ mod tests { ); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); - assert_eq!(ActionId::ALL.len(), 14); + assert_eq!(ActionId::ALL.len(), 15); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index cac41c9..c217d5d 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -10,6 +10,7 @@ use std::sync::Arc; use std::time::{Duration, Instant}; use engine::audio::StreamInfo; +use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; use engine::project::{Lane, LaneKind, Source}; use engine::{Clip, ExportHandle, Frame, PlaybackSession}; @@ -215,14 +216,28 @@ struct ContextMenu { /// action a stroke already reaches -- the menu is a second way *to* the actions /// and never a second version of them -- so both the label and the hint come /// out of the keymap registry and the two can never disagree. -const MENU_ITEMS: [ActionId; 5] = [ +const MENU_ITEMS: [ActionId; 6] = [ ActionId::Cut, ActionId::Delete, ActionId::Lift, ActionId::Regroup, + ActionId::Equalizer, ActionId::ToggleMute, ]; +/// How far a band may be pushed either way, in dB. The engine clamps nothing +/// here -- it will filter whatever it is given -- so this is a UI decision: +/// past about this a peaking band stops sounding like tone and starts sounding +/// like a fault. +const EQ_GAIN_LIMIT: f32 = 12.; + +/// One dB per keystroke, which is roughly the smallest step anyone hears on a +/// single band. +const EQ_STEP: f32 = 1.; + +/// The gain bar's height inside a band row. +const EQ_BAR_H: f32 = 6.; + struct Player { /// The timeline, once there is one. A run with no file opens without it and /// waits: the first media import or project load is what fills it, and @@ -317,6 +332,26 @@ struct Player { /// Which file the card will write. Kept across closes like the quality, and /// what [`Player::export_path`](Player) is named after. format: Format, + /// The equalizer card is up on this clip -- the lane and index it was + /// opened on. Held rather than re-read from `selected` every paint because + /// the card is modal: while it is up nothing else can move an index, and + /// the one edit it makes (`set_eq`) moves none. + eq_open: Option<(Lane, usize)>, + /// The curve the card is showing, which is the clip's own or the flat + /// five-band default. Edited live and written at the clip once per gesture + /// ([`Player::commit_eq`]): the project's equalizer table is append-only, so + /// a write per pointer sample would be a table entry -- and an undo step -- + /// per pixel. + eq_params: EqParams, + /// Which band the keyboard moves, and which one a drag is holding. + eq_band: usize, + /// A band's bar is being dragged. Tracked on the root like `scrubbing`, for + /// the same reason: the pointer leaves the 6 px bar immediately. + eq_dragging: bool, + /// A band bar's own box, recorded at prepaint. One probe for five rows: + /// they are laid out identically and only the *x* of a click is read + /// ([`frac_along`]), so whichever row painted last answers for all of them. + eq_bar: Rc>>, /// The action whose row is waiting for a stroke. The next key that is /// neither escape nor a lone modifier becomes the whole of what reaches it. rebinding: Option, @@ -431,6 +466,7 @@ impl Player { ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx), ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx), ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx), + ActionId::Equalizer => self.open_eq(cx), // Nothing to cancel while nothing is exporting; the export guard in // the key handler is what answers this one while there is. ActionId::CancelExport => {} @@ -441,7 +477,103 @@ impl Player { /// out of reach, so a right-click there opens no menu -- the same rule the /// key handler and the drop target already follow. fn modal(&self) -> bool { - self.keys_open || self.export_open || self.exporting().is_some() + self.keys_open || self.export_open || self.eq_open.is_some() || self.exporting().is_some() + } + + /// Opens the equalizer on the selected clip. Audio only, and it says so + /// rather than opening a card of bands that would reach nothing: a video + /// clip carries no sound of its own here (the sound is the audio lane's), + /// and the model would take the setting without anything ever playing it. + fn open_eq(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let refusal = match (self.selected, &self.session) { + (_, None) => Some("NO TIMELINE — open a file first"), + (None, _) => Some("NOTHING SELECTED — click an audio clip, then ask again"), + (Some((lane, _)), _) if lane.kind != LaneKind::Audio => Some( + "NOT AN AUDIO CLIP — the equalizer works on the sound, so pick a clip in an audio lane", + ), + _ => None, + }; + if let Some(refusal) = refusal { + self.notice = Some(refusal.into()); + cx.notify(); + return; + } + let (lane, idx) = self.selected.expect("checked above"); + let session = self.session.as_ref().expect("checked above"); + // What the clip already plays through, or the flat default -- so the + // card opens on the curve that is in force and a reopen shows the last + // drag rather than a fresh set of zeroes. + self.eq_params = session + .eq_of(lane, idx) + .cloned() + .unwrap_or_else(EqParams::default_layout); + self.eq_band = 0; + self.eq_dragging = false; + self.eq_open = Some((lane, idx)); + // One card at a time, the rule the other two already follow. + self.keys_open = false; + self.export_open = false; + self.context_menu = None; + cx.notify(); + } + + /// Writes what the card is showing at its clip: one undo step, one entry in + /// the append-only equalizer table, so this is called once per *gesture* -- + /// the end of a drag, a keystroke -- and never per pointer sample. + /// + /// A curve that moves nothing is stored as *no* equalizer at all, which is + /// what keeps a clip nobody has touched on the identity path through + /// playback and export (`engine::eq::EqParams::is_identity`). + fn commit_eq(&mut self, cx: &mut Context) { + let Some((lane, idx)) = self.eq_open else { + return; + }; + let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone()); + if let Some(session) = &mut self.session { + session.set_eq(lane, idx, params); + } + // `set_eq` reseeks inside the engine -- that is what makes the change + // audible at once -- and a reseek is what these flags are about. + self.reset_after_reseek(); + cx.notify(); + } + + /// Moves one band and says whether anything changed. Live only: the write + /// is [`commit_eq`](Player::commit_eq)'s. + fn set_band(&mut self, band: usize, gain_db: f32) -> bool { + let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT); + match self.eq_params.bands.get_mut(band) { + Some(b) if b.gain_db != gain_db => { + b.gain_db = gain_db; + true + } + _ => false, + } + } + + /// The keyboard's version of a drag: one step on the picked band, committed + /// straight away -- a keystroke has no release to wait for. + fn nudge_band(&mut self, by: f32, cx: &mut Context) { + let gain = self + .eq_params + .bands + .get(self.eq_band) + .map_or(0., |b| b.gain_db); + if self.set_band(self.eq_band, gain + by) { + self.commit_eq(cx); + } + } + + /// Where the pointer sits along a band's bar, as a gain: the middle is flat + /// and the two ends are the limit either way. + fn drag_band(&mut self, x: Pixels, cx: &mut Context) { + let gain = (frac_along(x, self.eq_bar.get()) * 2. - 1.) * EQ_GAIN_LIMIT; + if self.set_band(self.eq_band, gain) { + cx.notify(); + } } /// Jumps the timeline. @@ -1231,6 +1363,38 @@ impl Render for Player { cx.notify(); return; } + // And the equalizer card, the same way again. Its own strokes + // are the card's input, exactly as the export card's digits + // are: a band reachable only by dragging is a band a keyboard + // cannot move at all, and every one of them is listed in the + // keys menu (keymap.rs `FIXED`) rather than being a secret. + if this.eq_open.is_some() { + if key == ESCAPE { + // Nothing to undo: every change is already at the clip, + // and undo is undo's own key. + this.eq_open = None; + this.eq_dragging = false; + } else if key == "up" { + this.nudge_band(EQ_STEP, cx); + } else if key == "down" { + this.nudge_band(-EQ_STEP, cx); + } else if key == "r" { + for band in &mut this.eq_params.bands { + band.gain_db = 0.; + } + this.commit_eq(cx); + } else if let Ok(digit) = key.parse::() { + // 1-based, as the rows are numbered on screen; a digit + // past the last band picks nothing rather than panics. + if let Some(band) = digit.checked_sub(1) + && band < this.eq_params.bands.len() + { + this.eq_band = band; + } + } + cx.notify(); + return; + } // A clip menu names an index, and every edit below moves // indices -- so a stroke closes it before it acts. Escape means // that and nothing else, which is the `esc` the keys menu @@ -1256,7 +1420,7 @@ impl Render for Player { // sibling it can stop. The export card is over the timeline for // the same reason: importing under it would change the very // edit list the card is about to write out. - if this.keys_open || this.export_open { + if this.keys_open || this.export_open || this.eq_open.is_some() { return; } for path in paths.paths() { @@ -1272,6 +1436,20 @@ impl Render for Player { // 6 px ruler on the first drag and its own listeners then stop // firing; the root's hitbox is the whole window. .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| { + // A band's bar is 6 px tall and the pointer leaves it at once, + // so the equalizer drag is tracked here for the ruler's reason. + if this.eq_dragging { + if event.pressed_button == Some(MouseButton::Left) { + this.drag_band(event.position.x, cx); + } else { + // Released outside the window: the up below never came, + // so this is where the gesture ends -- and it still owes + // the one write the whole drag is worth. + this.eq_dragging = false; + this.commit_eq(cx); + } + return; + } if !this.scrubbing { return; } @@ -1287,6 +1465,13 @@ impl Render for Player { .on_mouse_up( MouseButton::Left, cx.listener(|this, event: &MouseUpEvent, _, cx| { + if std::mem::take(&mut this.eq_dragging) { + // The release lands exactly, then the gesture is written + // once -- the append-only table's whole reason. + this.drag_band(event.position.x, cx); + this.commit_eq(cx); + return; + } if std::mem::take(&mut this.scrubbing) { this.scrub_to(event.position.x, true, cx); } @@ -1359,6 +1544,7 @@ impl Render for Player { // column, and only one of the two is ever up. .children(self.keys_overlay(cx)) .children(self.export_card(cx)) + .children(self.eq_card(cx)) } } @@ -2167,6 +2353,158 @@ impl Player { ) } + /// The equalizer of one audio clip: a row per band, each a bar that reads + /// flat in the middle and is dragged either way, and a row that flattens + /// them all. The same scrim, width and rows as the other two cards, and the + /// same plain divs -- nothing here takes focus, so the root keeps the + /// keyboard and the card's own strokes (`1`–`5`, up, down, `r`) reach it. + /// + /// Every change is written at the clip as it is made + /// ([`Player::commit_eq`]), so what the card shows is always what is + /// playing: there is no OK button to forget, and closing it changes + /// nothing. What takes a curve back off is undo, like every other edit. + fn eq_card(&self, cx: &mut Context) -> Option { + let (lane, idx) = self.eq_open?; + let rows: Vec<_> = self + .eq_params + .bands + .iter() + .enumerate() + .map(|(i, band)| { + let (left, width) = eq_fill(band.gain_db); + div() + .id(("eq-band", i)) + .flex() + .min_h(px(KEYS_ROW_H)) + .items_center() + .gap(px(12.)) + .px(px(6.)) + .rounded(px(3.)) + .cursor_pointer() + .when(i == self.eq_band, |d| d.bg(rgb(SELECTED))) + .hover(|s| s.bg(rgb(HOVER))) + // The press picks the band *and* is already the first + // sample of the drag, so a plain click sets a value. + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + this.eq_band = i; + this.eq_dragging = true; + this.drag_band(event.position.x, cx); + }), + ) + .child( + div() + .flex_none() + // Wide enough for "12 kHz high shelf", so the bars + // below each other all start at the same pixel. + .w(px(112.)) + .text_size(px(11.)) + .child(format!("{} {}", i + 1, band_label(band))), + ) + .child( + div() + .flex_1() + .h(px(EQ_BAR_H)) + .rounded(px(3.)) + .bg(rgb(SURFACE)) + .child(bounds_probe(self.eq_bar.clone())) + .child( + div() + .absolute() + .left(relative(left)) + .w(relative(width)) + .h_full() + .rounded(px(3.)) + .bg(rgb(ACCENT)), + ), + ) + .child( + div() + .flex_none() + // Fixed, so a sign or a second digit appearing does + // not shift the bar beside it mid-drag. + .w(px(56.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(format!("{:+.1} dB", band.gain_db)), + ) + }) + .collect(); + Some( + div() + .absolute() + .inset_0() + .flex() + .justify_center() + .items_center() + .bg(rgba(0x101010cc)) + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .child( + div() + .w(px(KEYS_W)) + .flex() + .flex_col() + .gap(px(2.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(SURFACE)) + // Which clip, because the card is modal and the lane it + // was opened from is behind a scrim by the time it is up. + .child(div().flex_none().px(px(6.)).child(format!( + "Equalizer — {} clip {}", + lane.label(), + idx + 1 + ))) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(self.notice.clone().unwrap_or_else(|| { + "drag a band, or 1–5 then up/down — esc closes".into() + })), + ) + // Five rows fit a 360 px window, but the layout is data + // (a file may carry any number of bands), so the list + // scrolls like the other two cards' do. + .child( + div() + .id("eq-rows") + .flex() + .flex_col() + .gap(px(2.)) + .max_h(px(EXPORT_ROWS_H)) + .overflow_y_scroll() + .children(rows), + ) + .child( + div() + .id("eq-reset") + .mt(px(4.)) + .flex() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(SELECTED)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + for band in &mut this.eq_params.bands { + band.gain_db = 0.; + } + this.commit_eq(cx); + })) + .child("Flatten"), + ), + ), + ) + } + /// The menu a right-click on a clip opens: what that clip can be given, /// each item beside the stroke that does the very same thing, and a /// turn-over side that says what the clip *is*. An item that would do @@ -2242,7 +2580,7 @@ impl Player { } } else { for action in MENU_ITEMS { - let enabled = applicable(&clip, action, playhead); + let enabled = applicable(&clip, menu.lane, action, playhead); // The one item that is not about this clip says so, and says it // here rather than in the registry: the stroke is global too, // but its row in the keys menu is not sitting on a clip. @@ -2750,11 +3088,44 @@ fn frame_at(secs: f64, fps: f64) -> u32 { (secs * fps + 1e-6).floor().max(0.) as u32 } +/// A band's bar as `(left, width)` in fractions of the track: the fill grows +/// out of the *middle*, which is flat, towards whichever end the gain went -- +/// a bar that filled from the left would read a -12 dB cut as an empty control +/// and 0 dB as a half-off one. The inverse of [`Player::drag_band`]'s reading +/// of a click, and clamped like it, so a curve loaded from a file with a gain +/// past the card's limit paints at the end of the bar rather than outside it. +fn eq_fill(gain_db: f32) -> (f32, f32) { + let at = (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2. + 0.5; + match at >= 0.5 { + true => (0.5, at - 0.5), + false => (at, 0.5 - at), + } +} + +/// What a band row calls itself: the corner or centre frequency, and for a +/// shelf the fact that it tilts everything past it -- which is the difference +/// between "12 kHz" moving the last octave and moving one band inside it. +fn band_label(band: &Band) -> String { + let freq = match band.freq_hz >= 1000. { + true => format!("{:.0} kHz", band.freq_hz / 1000.), + false => format!("{:.0} Hz", band.freq_hz), + }; + match band.kind { + BandKind::LowShelf => format!("{freq} low shelf"), + BandKind::HighShelf => format!("{freq} high shelf"), + BandKind::Peak => freq, + } +} + /// Whether the clip menu offers `action` on the clip it was opened on. Two of /// the items act on the *playhead* rather than on the clip, so a menu opened -/// away from it dims them instead of looking broken when they are clicked. -fn applicable(clip: &Clip, action: ActionId, playhead: u32) -> bool { +/// away from it dims them instead of looking broken when they are clicked, and +/// one acts on sound, which only an audio lane's clip has. +fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool { match action { + // The equalizer filters samples, and a video clip has none of its own + // here: the sound is the audio lane's, clip for clip. + ActionId::Equalizer => lane.kind == LaneKind::Audio, // Splits this clip only from inside it: at either edge there is nothing // to split off (project.rs `splittable`). ActionId::Cut => clip.start < playhead && playhead < clip.end(), @@ -3427,15 +3798,15 @@ fn timecode(t: f64, fps: f64) -> String { #[cfg(test)] mod tests { use super::{ - ACCENT, CONTROL_H, Clip, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, - INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, - LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, - RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, - WAVE_BPS, WAVE_COL, Wave, applicable, can_add, cancels_export, envelope, export_path, - export_settings, format_line, frac_along, frame_at, is_bare_modifier, is_project, keymap, - lane_clips, marked, menu_at, normalise, project_path, push_digit, retarget, scrub_due, - show_label, source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, - width_frac, window_title, + ACCENT, CONTROL_H, Clip, EQ_BAR_H, EQ_GAIN_LIMIT, EXPORT_ROWS_H, FORMATS, Format, + HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, + LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, + NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, + Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, + cancels_export, envelope, eq_fill, export_path, export_settings, format_line, frac_along, + frame_at, is_bare_modifier, is_project, keymap, lane_clips, marked, menu_at, normalise, + project_path, push_digit, retarget, scrub_due, show_label, source_frames, source_tint, + start_frac, timecode, unseen_paths, unseen_sources, width_frac, window_title, }; use super::{file_name, library_rows}; use engine::PlaybackSession; @@ -3655,20 +4026,27 @@ mod tests { }; assert_eq!(clip.end(), 90); // Cut splits from inside only: neither edge has anything to split off. - assert!(applicable(&clip, ActionId::Cut, 31)); - assert!(applicable(&clip, ActionId::Cut, 89)); - assert!(!applicable(&clip, ActionId::Cut, 30)); - assert!(!applicable(&clip, ActionId::Cut, 90)); - assert!(!applicable(&clip, ActionId::Cut, 200)); + let a1 = Lane::A1; + let v1 = Lane::V1; + assert!(applicable(&clip, v1, ActionId::Cut, 31)); + assert!(applicable(&clip, v1, ActionId::Cut, 89)); + assert!(!applicable(&clip, v1, ActionId::Cut, 30)); + assert!(!applicable(&clip, v1, ActionId::Cut, 90)); + assert!(!applicable(&clip, v1, ActionId::Cut, 200)); // Regroup is the other way round: only where this clip meets another. - assert!(applicable(&clip, ActionId::Regroup, 30)); - assert!(applicable(&clip, ActionId::Regroup, 90)); - assert!(!applicable(&clip, ActionId::Regroup, 60)); + assert!(applicable(&clip, v1, ActionId::Regroup, 30)); + assert!(applicable(&clip, v1, ActionId::Regroup, 90)); + assert!(!applicable(&clip, v1, ActionId::Regroup, 60)); + // The equalizer is the one item the *lane* decides: it filters samples, + // and a video clip has none of its own. Never the playhead's business. + assert!(applicable(&clip, a1, ActionId::Equalizer, 0)); + assert!(applicable(&clip, a1, ActionId::Equalizer, 60)); + assert!(!applicable(&clip, v1, ActionId::Equalizer, 60)); // The rest act on the clip that was clicked, so they always mean // something -- the engine words its own refusals. for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] { - assert!(applicable(&clip, action, 0)); - assert!(applicable(&clip, action, 60)); + assert!(applicable(&clip, v1, action, 0)); + assert!(applicable(&clip, a1, action, 60)); } // The playhead frame is the engine's own rule, boundary included. assert_eq!(frame_at(1.0, 30.), 30); @@ -4090,6 +4468,77 @@ mod tests { assert!(KEYS_ROW_H >= HIT_MIN); } + /// The equalizer card: what its bars paint, and that it fits the window the + /// other two cards are sized for. The bar is the one bit of geometry in the + /// card, and it is signed -- a fill that grew from the left would read a cut + /// as an empty control -- so it is checked against the reading of a click, + /// which is the same mapping backwards ([`Player::drag_band`]). + #[test] + fn the_equalizer_bar_grows_out_of_flat_and_the_card_fits_the_smallest_window() { + use engine::eq::{Band, BandKind, EqParams}; + // Flat is the middle and paints nothing: a band nobody has touched must + // not look like one that has been turned down. + assert_eq!(eq_fill(0.), (0.5, 0.)); + // Full boost fills the right half, full cut the left one. + assert_eq!(eq_fill(EQ_GAIN_LIMIT), (0.5, 0.5)); + assert_eq!(eq_fill(-EQ_GAIN_LIMIT), (0., 0.5)); + assert_eq!(eq_fill(EQ_GAIN_LIMIT / 2.), (0.5, 0.25)); + assert_eq!(eq_fill(-EQ_GAIN_LIMIT / 2.), (0.25, 0.25)); + // A file may carry a gain past what this card offers (the format writes + // any finite value): it paints at the end, never off the track. + assert_eq!(eq_fill(400.), (0.5, 0.5)); + assert_eq!(eq_fill(-400.), (0., 0.5)); + + // A click reads back as the gain that paints where it landed, which is + // what makes a drag land where the pointer is. + for gain in [-12., -6., 0., 6., 12.] { + let (left, width) = eq_fill(gain); + let at = if gain >= 0. { left + width } else { left }; + let read = (at * 2. - 1.) * EQ_GAIN_LIMIT; + assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}"); + } + + // Every default band says what it is, and a shelf says so: "12 kHz" + // alone would not tell anyone it tilts the whole top octave. + let labels: Vec = EqParams::default_layout() + .bands + .iter() + .map(band_label) + .collect(); + assert_eq!( + labels, + [ + "80 Hz low shelf", + "250 Hz", + "1 kHz", + "4 kHz", + "12 kHz high shelf" + ] + ); + assert_eq!( + band_label(&Band { + freq_hz: 2600., + gain_db: 0., + q: 1., + kind: BandKind::Peak + }), + "3 kHz", + "rounded, because a band label is not a measurement" + ); + + // The same shape as the other two cards, so it fits where they do. + let (title, status, gaps, padding) = (17., 28., 3. * 2., 24.); + assert!( + title + status + EXPORT_ROWS_H + gaps + padding + CONTROL_H <= 360., + "card too tall" + ); + assert!(KEYS_W <= 640., "card too wide"); + // The rows are dragged, so WCAG 2.5.8 binds them like every other + // target in this window -- the 6 px bar is inside a full-height row. + assert!(KEYS_ROW_H >= HIT_MIN); + assert!(EQ_BAR_H < KEYS_ROW_H); + } + /// Mute and level are one control with two states, and the whole point is /// that mute keeps the level: the user gets back what they had, not 100%. #[test] @@ -4597,6 +5046,13 @@ fn main() { keymap: keymap.clone(), keys_open: false, export_open: false, + eq_open: None, + // Replaced by the clip's own curve the moment the card + // opens; nothing reads it before that. + eq_params: EqParams::default(), + eq_band: 0, + eq_dragging: false, + eq_bar: Rc::default(), // What an export is until someone says otherwise: the // bitrate the picture asks for. quality: Quality::Auto, diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 3b653a8..4260214 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -43,6 +43,8 @@ use symphonia_core::packet::Packet; use symphonia_core::units; use symphonia_core::units::{Time, TimeBase}; +use crate::eq::{EqParams, EqState}; + /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.) const DEFAULT_PRIMING: u64 = 1024; @@ -211,6 +213,26 @@ impl AudioSession { pub fn open_multi_streams( sources: &[(PathBuf, usize)], segs: &[(Option, f64, f64)], + ) -> crate::Result)>> { + Self::open_multi_streams_eq(sources, segs, &[]) + } + + /// [`open_multi_streams`](Self::open_multi_streams) with an equalizer per + /// segment: `eqs[i]` is what segment `i` plays through, `None` for one that + /// plays flat. Filtering happens **per segment**, inside the worker, before + /// anything is mixed -- two clips with different curves must not be blurred + /// into one another, and a segment's filter memory starts clean and dies + /// with it, which is also what makes a seek a reset for free. + /// + /// A parallel list, not a fourth tuple element: see + /// [`crate::Project::audio_eqs_from`], which is what builds it. A list + /// shorter than `segs` (the empty one every plain caller passes) means the + /// rest play flat, so a mismatch cannot panic and cannot silently shift a + /// curve onto the wrong clip. + pub fn open_multi_streams_eq( + sources: &[(PathBuf, usize)], + segs: &[(Option, f64, f64)], + eqs: &[Option], ) -> crate::Result)>> { let Some((path, stream)) = sources.first() else { return Ok(None); @@ -282,6 +304,20 @@ impl AudioSession { // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so // this bound is ~0.75 s of lookahead — enough to ride out decode jitter // without making a pause take a second to bite. + // One filter per segment, built here where the rate and the layout are + // known and off the thread that will run it. An identity curve costs a + // branch and nothing else ([`EqState::process`]), and a segment with no + // curve at all is not even that. + let eqs: Vec> = segments + .iter() + .enumerate() + .map(|(i, _)| { + eqs.get(i) + .and_then(Option::as_ref) + .map(|p| EqState::new(p, meta.sample_rate, meta.channels)) + }) + .collect(); + let (tx, rx) = sync_channel(32); thread::Builder::new() .name("audio-decode".into()) @@ -290,6 +326,7 @@ impl AudioSession { tracks, channels: meta.channels as usize, segments, + eqs, timeline, tx, }) @@ -317,19 +354,41 @@ impl AudioSession { pub fn open_mixed_streams( sources: &[(PathBuf, usize)], lanes: &[Vec<(Option, f64, f64)>], + ) -> crate::Result)>> { + Self::open_mixed_streams_eq(sources, lanes, &[]) + } + + /// [`open_mixed_streams`](Self::open_mixed_streams) with + /// [`open_multi_streams_eq`](Self::open_multi_streams_eq)'s per-segment + /// equalizers, one list per lane -- [`crate::Project::audio_eqs_from`] is + /// what shapes them. + /// + /// Filtering is each lane's worker's own business and therefore happens + /// **before** the sum: a clip's curve reaches that clip's samples and stops + /// there, where filtering the mix would smear every lane's curve over + /// everything playing at the same instant. A missing or short list plays + /// flat, as it does one lane down. + pub fn open_mixed_streams_eq( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], ) -> crate::Result)>> { let [first, rest @ ..] = lanes else { return Ok(None); }; if rest.is_empty() { - return Self::open_multi_streams(sources, first); + let flat = Vec::new(); + return Self::open_multi_streams_eq(sources, first, eqs.first().unwrap_or(&flat)); } let mut meta = None; let mut rxs = Vec::with_capacity(lanes.len()); - for segs in lanes { + for (i, segs) in lanes.iter().enumerate() { // Every lane probes the same source 0, so the metas agree by // construction; `None` from any of them is a silent timeline. - let Some((lane_meta, rx)) = Self::open_multi_streams(sources, segs)? else { + let flat = Vec::new(); + let Some((lane_meta, rx)) = + Self::open_multi_streams_eq(sources, segs, eqs.get(i).unwrap_or(&flat))? + else { return Ok(None); }; meta = Some(lane_meta); @@ -1240,6 +1299,11 @@ struct Worker { tracks: Vec>, channels: usize, segments: Vec, + /// One per entry of `segments`, in the same order: the filter that segment's + /// samples pass through on the way out, or `None` for one that plays flat. + /// Beside the segments rather than inside them so the emit path can hold the + /// window rules and the filter memory at once without splitting a borrow. + eqs: Vec>, /// `start_sample` of the first chunk. timeline: u64, tx: SyncSender, @@ -1317,8 +1381,12 @@ fn run(mut w: Worker) { // Chunk numbering is continuous across every join, source ones included. let mut timeline = w.timeline; let segments = std::mem::take(&mut w.segments); + let mut eqs = std::mem::take(&mut w.eqs); + // A short list is "flat from here on" (`open_multi_streams_eq`), which this + // pads out so the zip below still walks every segment. + eqs.resize_with(segments.len(), || None); - for seg in &segments { + for (seg, eq) in segments.iter().zip(eqs.iter_mut()) { let Some(source) = seg.source else { // A gap: hand the device real silence rather than nothing at all, // in the same packet-sized chunks decoding produces, so `fed` and @@ -1343,7 +1411,7 @@ fn run(mut w: Worker) { }; let track = match track { Track::Sym(track) => { - if !run_sym(track, seg, channels, &mut timeline, &w.tx) { + if !run_sym(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) { return; // consumer went away } continue; @@ -1391,6 +1459,7 @@ fn run(mut w: Worker) { &mut interleaved, channels, seg, + eq.as_mut(), pos, next, &mut timeline, @@ -1412,10 +1481,18 @@ fn run(mut w: Worker) { /// audio the caller asked for: it is dropped, splitting the buffer that /// straddles the target. The tail past the segment end goes too — on a short /// segment that is this same buffer, trimmed at both ends. +/// +/// The segment's equalizer runs here, on the trimmed buffer and nowhere else: +/// this is the one place both readers hand their samples over, so playback and +/// an audio export get the same filtered stream by construction rather than by +/// two call sites agreeing. Trimmed first, so the pre-roll a listener never +/// hears cannot ring the filter either. Nothing is allocated -- the device +/// callback is two hand-offs downstream of here in any case. fn emit( interleaved: &mut Vec, channels: usize, seg: &Segment, + eq: Option<&mut EqState>, pos: u64, next: u64, timeline: &mut u64, @@ -1435,6 +1512,9 @@ fn emit( if interleaved.is_empty() { return true; // nothing left of it; the loop head ends the segment } + if let Some(eq) = eq { + eq.process(interleaved); + } let chunk = AudioChunk { start_sample: *timeline, samples: std::mem::take(interleaved), @@ -1455,6 +1535,7 @@ fn emit( fn run_sym( track: &mut SymTrack, seg: &Segment, + mut eq: Option<&mut EqState>, channels: usize, timeline: &mut u64, tx: &SyncSender, @@ -1505,7 +1586,18 @@ fn run_sym( }; buf.copy_to_vec_interleaved::(&mut interleaved); let next = pos + (interleaved.len() / channels) as u64; - if !emit(&mut interleaved, channels, seg, pos, next, timeline, tx) { + // Reborrowed per packet: the filter memory has to carry across the + // packet boundary, so this is one `EqState` for the whole segment. + if !emit( + &mut interleaved, + channels, + seg, + eq.as_deref_mut(), + pos, + next, + timeline, + tx, + ) { return false; } } diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index c1f7136..204e386 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -235,6 +235,28 @@ fn run( ) .into()); }; + // ...and the same list decides which clips this would be copying, which is + // the only way to ask whether any of them carries an equalizer. An EQ is + // sample math and a copy never decodes: exporting it here would write the + // clip flat, silently -- the same failure a missing audio track is. Named by + // where it sits on the timeline, because "some clip" is not a thing a user + // can go and fix. + let lane = project.audio_lanes()[0]; + if let Some((at, _)) = project + .lane(lane) + .iter() + .enumerate() + .find(|(idx, _)| project.eq_of(lane, *idx).is_some()) + .map(|(idx, clip)| (clip.start, idx)) + { + return Err(format!( + "the clip at {} has an equalizer and an mp4 export copies AAC packets, \ + which no filter can reach: export WAV or FLAC, which are decoded and \ + mixed, or clear the equalizer", + timecode(at, meta.frame_rate) + ) + .into()); + } let audio = AudioSession::copy_multi_streams(&project.audio_sources(), segments)?; let audio_params = audio.as_ref().map(|(track, _)| AudioParams { freq_index: track.freq_index, @@ -303,6 +325,18 @@ fn run( Ok(()) } +/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short +/// enough to sit inside a refusal and exact enough to go and find the clip. +/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a +/// `00:00:12:07` in the middle of a sentence is a serial number. +fn timecode(frame: u32, fps: f64) -> String { + let secs = match fps.is_finite() && fps > 0.0 { + true => (f64::from(frame) / fps) as u32, + false => 0, + }; + format!("{:02}:{:02}", secs / 60, secs % 60) +} + /// The audio lanes alone, summed, as a WAV or a FLAC. /// /// Nothing here re-derives the edit: the play lists are @@ -326,7 +360,13 @@ fn run_audio( ) -> crate::Result<()> { let sources = project.audio_sources(); let segs = project.audio_segments_from(0, meta.frame_rate); - let Some((audio, chunks)) = AudioSession::open_mixed_streams(&sources, &segs)? else { + // The equalizers with them, so what is written is what is heard down to the + // filter: the worker applies them per segment before the lanes are summed + // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point + // playback's feeder reads from -- there is no second place here that could + // apply them differently. + let eqs = project.audio_eqs_from(0, meta.frame_rate); + let Some((audio, chunks)) = AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs)? else { return Err("this timeline has no audio to export".into()); }; let channels = usize::from(audio.channels); @@ -341,10 +381,8 @@ fn run_audio( let mut samples: Vec = Vec::with_capacity(total); for chunk in chunks { cancelled(shared)?; - // ponytail: the per-segment EQ goes here -- `EqState::process` on this - // same interleaved f32 buffer, before the quantisation below, which is - // the point playback's feeder will call it from too. Not wired: the EQ - // slice owns that, this is only the seat kept for it. + // Already equalized: the chunks come out of the per-lane workers, which + // filter each segment before the mix (`open_mixed_streams_eq` above). samples.extend( chunk .samples diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index ab62dbd..00da754 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -23,6 +23,7 @@ use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::decode::{DecodeSession, Frame, Worker}; use crate::demux::{Demuxer, VideoMeta}; +use crate::eq::EqParams; use crate::project::{Clip, Lane, LaneKind, Project, Source, Span}; /// How long the feeder waits out a full ring. The ring holds a second, so this @@ -472,6 +473,27 @@ impl PlaybackSession { .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate)) } + /// What the clip at `idx` of `lane` is equalized with, or `None` for one + /// that plays flat -- what a card shows before it lets anyone drag a band. + pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> { + self.project.eq_of(lane, idx) + } + + /// Gives that clip an equalizer, or takes it off with `None`. One undo step, + /// like every other edit -- and, like every other edit, it *reseeks*: the + /// audio workers are rebuilt from the new curves right where the playhead + /// is, so a band changed during playback is heard from the next chunk on + /// rather than at the next play. `false` for a bad index or a non-finite + /// band, and nothing changes. + /// + /// ponytail: the reseek is what makes it live, so the cost of a change is a + /// decoder restart -- inaudible at a drag's end, but too much to call once + /// per pointer sample (a caller commits one change per gesture). Upgrade + /// path is an `Arc` swap the running worker polls per chunk. + pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option) -> bool { + self.edit(|p| p.set_eq(lane, idx, params)) + } + /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, /// silence on the audio one, and nothing else moves. Reseeks, because what /// the playhead sits on has changed. `false` for a bad index and for the @@ -783,10 +805,17 @@ impl PlaybackSession { // hears is every lane at once, and a lane's own gaps are silence in // it rather than a hole in the count the master clock keeps. let segs = self.project.audio_segments_from(target, fps); + // The equalizers beside them, one per segment: the worker filters a + // segment's own samples before the mix, so a clip's curve reaches + // that clip and stops. Rebuilt on every seek, which is what makes an + // EQ edit audible at once -- `edit` reseeks, so the drag that + // changed a band restarts the workers with the new curve already in + // them, and no live channel has to reach into a running one. + let eqs = self.project.audio_eqs_from(target, fps); // Each source on the stream it was placed with: what plays is what // the library row said, and what an export copies (`export::run`). let sources = self.project.audio_sources(); - audio_running = match AudioSession::open_mixed_streams(&sources, &segs) { + audio_running = match AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs) { Ok(Some((_, rx))) => audio.spawn_feeder(rx), _ => false, }; diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index f82e3a4..a7cbef0 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -1070,16 +1070,70 @@ impl Project { timeline_frame: u32, fps: f64, ) -> Vec, f64, f64)>> { - let lists: Vec<_> = self + self.audio_lanes() + .into_iter() + .map(|lane| self.lane_segments_from(lane, timeline_frame, fps)) + .collect() + } + + /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from) + /// builds a play list for, in the same order. Public because everything + /// asked per audio lane -- which clip a segment's equalizer belongs to, + /// which lane an mp4 export would copy -- has to read the very list the + /// sound comes off, or the two answers drift apart (which is exactly how an + /// `A2`-only project once exported silently, ledger). + pub fn audio_lanes(&self) -> Vec { + let lanes: Vec = self .lanes() .into_iter() .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty()) - .map(|lane| self.lane_segments_from(lane, timeline_frame, fps)) .collect(); - match lists.is_empty() { - true => vec![self.lane_segments_from(Lane::A1, timeline_frame, fps)], - false => lists, + match lanes.is_empty() { + // The all-gap fallback: `A1`'s own (empty) list, so a timeline with + // no sound still plays silence against the master clock. + true => vec![Lane::A1], + false => lanes, + } + } + + /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s + /// segments plays through: the same lanes in the same order, one entry per + /// segment, `None` where the segment is a gap or its clip plays flat. + /// + /// A parallel list rather than a fourth element of the segment tuple: that + /// tuple is what every opener, the packet-copy path and a dozen tests speak, + /// and an effect is not part of *which samples* a segment names. A short + /// list therefore means "flat from here on" rather than a length mismatch -- + /// see [`crate::AudioSession::open_mixed_streams_eq`]. + pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec>> { + self.audio_lanes() + .into_iter() + .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps)) + .collect() + } + + /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching + /// [`lane_segments_from`](Project::lane_segments_from) entry for entry -- + /// same walk, same `fps` refusal, so the two lists cannot come out different + /// lengths. + pub fn lane_eqs_from( + &self, + lane: Lane, + timeline_frame: u32, + fps: f64, + ) -> Vec> { + if !(fps.is_finite() && fps > 0.0) { + return Vec::new(); } + self.spans_from(lane, timeline_frame) + .iter() + // A span off a clip covers that clip's frames and no others, so its + // own start names the clip -- the index a [`Span`] does not carry. + .map(|span| { + self.map(lane, span.start) + .and_then(|(idx, _)| self.eq_of(lane, idx).cloned()) + }) + .collect() } /// Pushes the undo snapshot. Every mutating method calls this once, *after* diff --git a/crates/engine/tests/eq_audio.rs b/crates/engine/tests/eq_audio.rs new file mode 100644 index 0000000..0a8f6db --- /dev/null +++ b/crates/engine/tests/eq_audio.rs @@ -0,0 +1,377 @@ +//! The per-clip equalizer where it has to be true: in the samples playback +//! feeds the device and in the samples an export writes, which are the same +//! samples by construction — both come off `AudioSession::open_mixed_streams_eq` +//! and the filter runs inside the per-lane worker, per segment, before the mix. +//! +//! Everything here goes through the *front door*: a `Project` is edited with +//! `set_eq` and then read exactly as `PlaybackSession::seek` reads it +//! (`audio_segments_from` + `audio_eqs_from` handed to the same opener), or +//! exported through `engine::export::start`. Nothing calls `EqState` directly — +//! `eq.rs`'s own unit tests own the filter maths; what is checked here is the +//! wiring: that a curve reaches its clip, only its clip, and reaches it the same +//! way in both directions. +//! +//! The fixtures are a 440 Hz / 880 Hz stereo tone (`gen_fixtures.sh`), so a low +//! shelf with its corner above both tones is a flat +12 dB on everything +//! audible: the expected RMS ratio is 10^(12/20) ≈ 3.98, and it is asserted as a +//! ratio, never as a level. +//! +//! No picture is decoded, so nothing here needs the hardware plugin. + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use engine::eq::{Band, BandKind, EqParams}; +use engine::export::{ExportSettings, Format}; +use engine::project::{Lane, LaneKind, Source}; +use engine::{AudioSession, Clip, ExportHandle, Project}; + +const RATE: u32 = 44_100; +const FPS: f64 = 30.0; + +/// +12 dB below 2 kHz: above both fixture tones, so every audible sample in +/// them is lifted by the shelf's full gain. +const BOOST_DB: f32 = 12.0; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn boost() -> EqParams { + EqParams { + bands: vec![Band { + freq_hz: 2000.0, + gain_db: BOOST_DB, + q: 0.707, + kind: BandKind::LowShelf, + }], + } +} + +fn clip(start: u32, source: usize, frames: u32) -> Clip { + Clip { + start, + in_frame: 0, + out_frame: frames, + source, + link: None, + eq: None, + color: None, + } +} + +/// One video clip and `audio` on `A1`, from `test_av.mp4` alone. +fn project(audio: Vec) -> Project { + let frames = audio.iter().map(Clip::end).max().unwrap_or(30); + Project::from_parts( + vec![Source::new(asset("test_av.mp4"), 0)], + vec![ + (LaneKind::Video, vec![clip(0, 0, frames)]), + (LaneKind::Audio, audio), + ], + Vec::new(), + Vec::new(), + ) + .expect("a one-source project") +} + +/// What the device would be fed: the exact call `PlaybackSession::seek` makes, +/// drained to the end. This *is* the feeder path minus the ring buffer. +fn play(project: &Project) -> Vec { + let sources = project.audio_sources(); + let segs = project.audio_segments_from(0, FPS); + let eqs = project.audio_eqs_from(0, FPS); + let (meta, chunks) = AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs) + .expect("open the timeline's audio") + .expect("the timeline has audio"); + assert_eq!((meta.sample_rate, meta.channels), (RATE, 2)); + let mut samples = Vec::new(); + for chunk in chunks { + samples.extend(chunk.samples); + } + samples +} + +/// Root mean square of `[from, to)` seconds of the interleaved stereo stream. +fn rms(samples: &[f32], from: f64, to: f64) -> f64 { + let at = |secs: f64| (secs * f64::from(RATE)) as usize * 2; + let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())]; + assert!(!window.is_empty(), "no samples in [{from}, {to})"); + (window + .iter() + .map(|s| f64::from(*s) * f64::from(*s)) + .sum::() + / window.len() as f64) + .sqrt() +} + +/// The shelf's own gain, to within a fifth of a dB either way -- the filter is +/// exact, the tone is not perfectly band-limited, and the fixtures' 1 Hz pulse +/// makes any window a mixture. +fn assert_boosted(ratio: f64, what: &str) { + let db = 20.0 * ratio.log10(); + println!("{what}: ratio {ratio:.3} = {db:+.2} dB"); + assert!( + (db - f64::from(BOOST_DB)).abs() < 0.5, + "{what} measured {db:+.2} dB, the band asks for {BOOST_DB:+.1}" + ); +} + +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < limit, + "export did not finish in {limit:?}" + ); + std::thread::sleep(Duration::from_millis(10)); + } + handle.result().expect("a finished export has an outcome") +} + +fn out_path(name: &str, ext: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!("ve_eq_{name}_{}.{ext}", std::process::id())); + let _ = std::fs::remove_file(&path); + path +} + +fn meta() -> engine::VideoMeta { + engine::demux::Demuxer::open(&asset("test_av.mp4")) + .expect("open test_av") + .0 +} + +/// Samples of a written file back through the engine's own reader. +fn decode(path: &Path) -> Vec { + let (_, chunks) = AudioSession::open(path) + .expect("reopen the export") + .expect("the export has audio"); + let mut samples = Vec::new(); + for chunk in chunks { + samples.extend(chunk.samples); + } + samples +} + +/// The whole claim in one line: a clip given a band comes out of the feeder +/// path that much louder than the same clip without it -- and a project nobody +/// has equalized comes out of the *new* opener bit for bit what the old one +/// gave, which is the identity promise the rest of the engine rests on. +#[test] +fn an_equalized_clip_plays_that_much_louder_and_a_flat_one_not_at_all() { + let flat = project(vec![clip(0, 0, 30)]); + let mut eqd = flat.clone(); + assert!(eqd.set_eq(Lane::A1, 0, Some(boost()))); + + let plain = play(&flat); + let boosted = play(&eqd); + assert_eq!( + plain.len(), + boosted.len(), + "the edit is a filter, not a trim" + ); + assert_boosted( + rms(&boosted, 0.05, 0.95) / rms(&plain, 0.05, 0.95), + "playback", + ); + + // No equalizer anywhere: the samples are the ones the opener gave before + // there was an equalizer at all, to the bit. + let sources = flat.audio_sources(); + let segs = flat.audio_segments_from(0, FPS); + let (_, chunks) = AudioSession::open_mixed_streams(&sources, &segs) + .expect("open") + .expect("has audio"); + let old: Vec = chunks.into_iter().flat_map(|c| c.samples).collect(); + assert_eq!(old, plain, "an EQ-less project must decode bit-identically"); + + // ...and so does one carrying a curve that moves nothing: `is_identity` + // short-circuits inside `EqState::process`, and this is the path that says + // the short-circuit is really on. + let mut identity = flat.clone(); + assert!(identity.set_eq(Lane::A1, 0, Some(EqParams::default_layout()))); + assert!(identity.eq_of(Lane::A1, 0).is_some(), "the curve is stored"); + assert_eq!( + play(&identity), + plain, + "a flat curve must not touch a sample" + ); +} + +/// The reason the filter lives in the worker and not over the mix: two clips +/// with different settings must not bleed into each other. One second boosted, +/// one second not, on one lane, out of one decoder. +#[test] +fn a_band_reaches_its_own_clip_and_stops_at_the_cut() { + let mut p = project(vec![clip(0, 0, 30), clip(30, 0, 30)]); + let plain = play(&p); + assert!(p.set_eq(Lane::A1, 1, Some(boost()))); + let boosted = play(&p); + + assert_boosted( + rms(&boosted, 1.05, 1.95) / rms(&plain, 1.05, 1.95), + "the equalized second clip", + ); + // The clip before it is untouched -- and untouched to the *bit*, not merely + // to a level: a filter whose memory carried across the join would show up + // here as a fraction of a dB and pass any ratio test. + let second = (1.0 * f64::from(RATE)) as usize * 2; + assert_eq!( + boosted[..second], + plain[..second], + "the flat clip before the cut moved" + ); +} + +/// Two lanes, a band on one of them: the sum must differ by exactly what that +/// lane's own samples changed by, which is only true if each lane is filtered +/// before it is added. Filtering the mix instead would smear the curve over the +/// other lane as well, and this is the difference that would show it. +#[test] +fn a_lane_is_equalized_before_the_mix_and_never_after_it() { + let mut p = Project::from_parts( + vec![Source::new(asset("test_av.mp4"), 0)], + vec![ + (LaneKind::Video, vec![clip(0, 0, 30)]), + (LaneKind::Audio, vec![clip(0, 0, 30)]), + (LaneKind::Audio, vec![clip(0, 0, 30)]), + ], + Vec::new(), + Vec::new(), + ) + .expect("a two-audio-lane project"); + assert_eq!(p.audio_lanes().len(), 2, "both lanes hold something"); + + let mixed = play(&p); + let a2 = Lane::new(LaneKind::Audio, 1); + assert!(p.set_eq(a2, 0, Some(boost()))); + let mixed_eqd = play(&p); + + // What A2 alone sounds like either way, taken off the single-lane path. + let lone = project(vec![clip(0, 0, 30)]); + let mut lone_eqd = lone.clone(); + assert!(lone_eqd.set_eq(Lane::A1, 0, Some(boost()))); + let (flat, boosted) = (play(&lone), play(&lone_eqd)); + + let n = mixed + .len() + .min(mixed_eqd.len()) + .min(flat.len()) + .min(boosted.len()); + let mut worst = 0.0f32; + for i in 0..n { + worst = worst.max(((mixed_eqd[i] - mixed[i]) - (boosted[i] - flat[i])).abs()); + } + println!("mix-vs-lane worst difference: {worst:e}"); + // Not zero: the two runs decode the same source twice and AAC's noise + // substitution reseeds per decoder (`open_segments`, measured below 1e-3). + assert!( + worst < 1e-3, + "the mix changed by {worst} more than the equalized lane did -- the filter is on the sum" + ); +} + +/// The export half of the same claim, through `export::start`: what is written +/// is what is heard, so the WAV carries the boost at the same ratio the feeder +/// path measured. +#[test] +fn a_wav_export_carries_the_same_boost_playback_does() { + let flat = project(vec![clip(0, 0, 30)]); + let mut eqd = flat.clone(); + assert!(eqd.set_eq(Lane::A1, 0, Some(boost()))); + + let mut written = Vec::new(); + for (name, project) in [("flat", &flat), ("eqd", &eqd)] { + let out = out_path(name, "wav"); + let handle = engine::export::start( + project.clone(), + meta(), + &out, + &ExportSettings { + format: Format::Wav, + ..Default::default() + }, + ); + wait(&handle, Duration::from_secs(60)).expect("wav export"); + written.push(decode(&out)); + std::fs::remove_file(&out).unwrap(); + } + let [plain, boosted] = &written[..] else { + unreachable!("two exports") + }; + assert_boosted( + rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95), + "wav export", + ); + // ...and the same number to the ear: the export is not a second, kinder + // filter run at a different point in the chain. + let played = rms(&play(&eqd), 0.05, 0.95) / rms(&play(&flat), 0.05, 0.95); + let exported = rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95); + assert!( + (played - exported).abs() < 0.05, + "playback boosted by {played:.3} and the export by {exported:.3}" + ); +} + +/// An mp4 export *copies* AAC packets, and no filter can reach a packet copy. +/// Refused by name, with the clip's own position in it -- silently writing the +/// clip flat is the one failure nobody would notice. +#[test] +fn an_mp4_export_refuses_an_equalized_clip_and_names_where_it_is() { + let mut p = project(vec![clip(0, 0, 30), clip(30, 0, 30)]); + assert!(p.set_eq(Lane::A1, 1, Some(boost()))); + + let out = out_path("refused", "mp4"); + let handle = engine::export::start(p.clone(), meta(), &out, &ExportSettings::default()); + let err = wait(&handle, Duration::from_secs(60)) + .expect_err("an equalized clip cannot leave through the copy path") + .to_string(); + println!("mp4 refusal: {err}"); + assert!(err.contains("00:01"), "the refusal names the clip: {err}"); + assert!(err.contains("equalizer"), "{err}"); + assert!(err.contains("WAV or FLAC"), "and the way out: {err}"); + assert!(!out.exists(), "a refused export leaves no file"); + + // Taking the curve off is all it takes -- the refusal is about the setting, + // never about the clip having once had one. + assert!(p.set_eq(Lane::A1, 1, None)); + let handle = engine::export::start(p, meta(), &out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(120)).expect("a flat timeline exports as mp4"); + std::fs::remove_file(&out).unwrap(); +} + +/// A band moved while the timeline is playing: `PlaybackSession::set_eq` writes +/// the project and reseeks, and a reseek rebuilds the workers from +/// `audio_eqs_from`. This is that mechanism without a sound device -- the edit, +/// then the very list the reopen is built from, then the samples it yields. +#[test] +fn a_band_changed_mid_play_is_in_the_next_chunk_the_worker_makes() { + let mut p = project(vec![clip(0, 0, 30)]); + assert!( + p.audio_eqs_from(0, FPS)[0][0].is_none(), + "flat to begin with" + ); + let before = play(&p); + + assert!(p.set_eq(Lane::A1, 0, Some(boost()))); + // The reopen list is rebuilt from the project every seek, so the edit is in + // it the moment it lands -- no channel has to reach into a running worker. + assert_eq!( + p.audio_eqs_from(0, FPS)[0][0].as_ref(), + Some(&boost()), + "the seek's own list carries the new curve" + ); + let after = play(&p); + assert_ne!(before, after, "the samples changed"); + assert_boosted( + rms(&after, 0.05, 0.95) / rms(&before, 0.05, 0.95), + "after the edit", + ); + + // And undo is the way back, one step, samples and all. + assert!(p.undo()); + assert!(p.audio_eqs_from(0, FPS)[0][0].is_none()); + assert_eq!(play(&p), before, "undo puts the flat samples back"); +}