diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index a617a54..2cedaf1 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -63,9 +63,14 @@ pub enum ActionId { Color, Fit, Resolution, + ZoomIn, + ZoomOut, + ZoomFit, Undo, AddVideoLane, AddAudioLane, + RemoveVideoLane, + RemoveAudioLane, ToggleMute, VolumeUp, VolumeDown, @@ -78,7 +83,7 @@ pub enum ActionId { impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 33] = [ + pub const ALL: [ActionId; 38] = [ ActionId::Play, ActionId::StepBack, ActionId::StepForward, @@ -102,9 +107,14 @@ impl ActionId { ActionId::Color, ActionId::Fit, ActionId::Resolution, + ActionId::ZoomIn, + ActionId::ZoomOut, + ActionId::ZoomFit, ActionId::Undo, ActionId::AddVideoLane, ActionId::AddAudioLane, + ActionId::RemoveVideoLane, + ActionId::RemoveAudioLane, ActionId::ToggleMute, ActionId::VolumeUp, ActionId::VolumeDown, @@ -140,9 +150,14 @@ impl ActionId { ActionId::Color => "Colour…", ActionId::Fit => "Fit policy: fit → fill → stretch → centre", ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p", + ActionId::ZoomIn => "Zoom in on the timeline (around the playhead)", + ActionId::ZoomOut => "Zoom out of the timeline", + ActionId::ZoomFit => "Fit the whole timeline on screen", ActionId::Undo => "Undo", ActionId::AddVideoLane => "Add a video track", ActionId::AddAudioLane => "Add an audio track", + ActionId::RemoveVideoLane => "Remove the last video track (it must be empty)", + ActionId::RemoveAudioLane => "Remove the last audio track (it must be empty)", ActionId::ToggleMute => "Mute / Unmute", ActionId::VolumeUp => "Volume up", ActionId::VolumeDown => "Volume down", @@ -180,9 +195,14 @@ impl ActionId { ActionId::Color => "color", ActionId::Fit => "fit", ActionId::Resolution => "resolution", + ActionId::ZoomIn => "zoom-in", + ActionId::ZoomOut => "zoom-out", + ActionId::ZoomFit => "zoom-fit", ActionId::Undo => "undo", ActionId::AddVideoLane => "add-video-lane", ActionId::AddAudioLane => "add-audio-lane", + ActionId::RemoveVideoLane => "remove-video-lane", + ActionId::RemoveAudioLane => "remove-audio-lane", ActionId::ToggleMute => "toggle-mute", ActionId::VolumeUp => "volume-up", ActionId::VolumeDown => "volume-down", @@ -228,14 +248,20 @@ impl ActionId { | ActionId::Silence => Category::Clips, // The project's own picture size is not a clip's business, and not // a file operation either: it is what the viewer is looking at. - ActionId::Resolution => Category::View, + // Neither is how much of the timeline the panel shows: a zoom edits + // nothing, it magnifies. + ActionId::Resolution | ActionId::ZoomIn | ActionId::ZoomOut | ActionId::ZoomFit => { + Category::View + } ActionId::Cut | ActionId::Regroup | ActionId::Detach | ActionId::Group | ActionId::Undo | ActionId::AddVideoLane - | ActionId::AddAudioLane => Category::Editing, + | ActionId::AddAudioLane + | ActionId::RemoveVideoLane + | ActionId::RemoveAudioLane => Category::Editing, ActionId::ToggleMute | ActionId::VolumeUp | ActionId::VolumeDown @@ -291,7 +317,15 @@ pub struct Fixed { pub category: Category, } -pub const FIXED: [Fixed; 14] = [ +pub const FIXED: [Fixed; 16] = [ + // Not a chord at all but a way of pressing one, and the only place the + // editor can say so: holding a key that moves a *value* runs it, and + // holding anything else still does what one press did. + Fixed { + chord: "hold ← → ↑ ↓", + label: "Run a card's slider, or the volume and zoom keys, while held", + category: Category::View, + }, Fixed { chord: "esc", label: "Close this card or menu, or cancel a capture", @@ -340,6 +374,11 @@ pub const FIXED: [Fixed; 14] = [ label: "Flatten every band", category: Category::Audio, }, + Fixed { + chord: "s", + label: "Show or hide the spectrum behind the curve", + category: Category::Audio, + }, // The colour card's own three, which mean nothing outside it -- the same // card-local input the export card's digits are. Fixed { @@ -521,6 +560,14 @@ impl Keymap { // it changes what every clip is composed onto. b(ActionId::Fit, "p", false), b(ActionId::Resolution, "r", true), + // The zoom pair, on the chords every editor and every browser + // magnifies with. The bare "=" and "-" are the volume keys, so + // these take the ctrl versions of them -- and ctrl+0 is the + // "back to 100%" of the same family, which here is the whole + // timeline across the bed. + b(ActionId::ZoomIn, "=", true), + b(ActionId::ZoomOut, "-", true), + b(ActionId::ZoomFit, "0", true), b(ActionId::Undo, "z", false), b(ActionId::Undo, "z", true), // The unshifted initials of what they add. Both were free -- @@ -528,6 +575,13 @@ impl Keymap { // is added often enough to deserve a key that is one press. b(ActionId::AddVideoLane, "v", false), b(ActionId::AddAudioLane, "a", false), + // ...and the pair that takes one back, on ctrl chords: removing + // a track is not a stroke to hit by accident (the resolution key + // is out of the way for the same reason). Ctrl+v would be the + // matching initial and is the paste, so the video one takes the + // key beside it. + b(ActionId::RemoveVideoLane, "b", true), + b(ActionId::RemoveAudioLane, "a", true), b(ActionId::ToggleMute, "m", false), // The unshifted pair, which is what gpui reports for those two // keys ("=" and "-", platform.rs:862): the volume keys every @@ -809,7 +863,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 35); + assert_eq!(k.entries().len(), 40); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // The seek keys: bare arrows a frame, ctrl arrows a second, and the two // ends of the timeline. @@ -843,6 +897,10 @@ mod tests { // The track keys are the bare letters; the ctrl ones stay copy/paste. assert_eq!(k.lookup("v", false), Some(ActionId::AddVideoLane)); assert_eq!(k.lookup("a", false), Some(ActionId::AddAudioLane)); + // ...and the ctrl ones take a track away, out of the way of a stray + // press. Ctrl+v is the paste, so the video one sits beside it. + assert_eq!(k.lookup("b", true), Some(ActionId::RemoveVideoLane)); + assert_eq!(k.lookup("a", true), Some(ActionId::RemoveAudioLane)); 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 @@ -981,7 +1039,8 @@ mod tests { // A bindable chord is one `rebind_action` may keep: what it writes is // what the next load reads, for every stroke that passes here. let mut k = Keymap::defaults(); - k.rebind_action(ActionId::Play, chord("=", true)).unwrap(); + // Any free chord will do here; ctrl+= is the zoom's. + k.rebind_action(ActionId::Play, chord("w", true)).unwrap(); assert_eq!(whole(&emit(&k)), k); } @@ -1038,7 +1097,8 @@ mod tests { assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); // 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(), 33); + assert_eq!(ActionId::ALL.len(), 38); + assert_eq!(k.display(ActionId::ZoomIn), "ctrl+="); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index de6cf29..7ed6df1 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -19,9 +19,9 @@ use engine::{Clip, ExportHandle, Frame, PlaybackSession}; use gpui::{ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, - Point, RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, - WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, - size, + Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign, + TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, + relative, rgb, rgba, size, }; /// Editor chrome: three grays and one accent, all darker than the picture so the @@ -74,6 +74,11 @@ const LABEL_MIN_W: f32 = 36.; /// allocates one bucket per window, so a rate taken from anything the user can /// influence is an allocation bomb -- and 40 is already finer than the pixels a /// clip is ever given. +/// +/// ponytail: "finer than the pixels" stops being true once the timeline is +/// zoomed -- past ~25 ms per bucket the envelope reads as steps rather than as +/// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade +/// is a second, finer pass over the visible span only, cached like `waves` is. const WAVE_BPS: u32 = 40; /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape, /// and a path with a point per pixel is a path per repaint. @@ -95,6 +100,9 @@ const ROW_H: f32 = 32.; /// wear in the lanes, which is the whole of the panel<->timeline association. const SWATCH_W: f32 = 4.; const CONTROL_H: f32 = 28.; +/// The volume slider beside its button: a hundred steps across it, so a pixel +/// is finer than a step and the drag reads as continuous. +const VOLUME_W: f32 = 110.; const RULER_HIT_H: f32 = HIT_MIN; /// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits /// cannot push the layout around. @@ -117,6 +125,11 @@ const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; const MENU_W: f32 = 260.; const MENU_ROW_H: f32 = HIT_MIN; const MENU_PAD: f32 = 6.; +/// How much of the item list is on screen at once, capped and scrolling like the +/// keybindings and export lists: every action the pointer can reach is an item +/// here, and a menu taller than the 640x360 floor would hang its last items off +/// the bottom edge, where nobody can click them. +const MENU_ROWS_H: f32 = 12. * MENU_ROW_H; /// The one key name this file still spells out, and gpui's spelling of it: it /// is the way out of a capture and out of the overlay, and both have to work @@ -128,6 +141,18 @@ const ESCAPE: &str = "escape"; /// as a program name rather than as a file name. const NO_FILE: &str = "no file open"; +/// What a press of play says when there is nothing to play: no timeline at all +/// and an emptied one are the same answer to the user, so they are one line. +const NOTHING_TO_PLAY: &str = "NOTHING TO PLAY — put a clip on the timeline first"; + +/// Whether a press of play would have anything to play. No timeline at all and +/// one every clip has been taken off are the same state to a transport, and the +/// button and the key both have to give the same answer to it -- so there is +/// one of them, and it is free of the window so it can be checked without one. +fn nothing_to_play(session: Option<&PlaybackSession>) -> bool { + session.is_none_or(PlaybackSession::is_empty) +} + /// What the monitoring output is set to. Two things, not one: the level the /// user picked, and whether it is being held silent -- so unmuting comes back /// to the level rather than to a guess. @@ -146,29 +171,45 @@ struct Volume { } impl Volume { - /// 5% a press: twenty of them across the range. - const MAX_STEPS: u8 = 20; + /// One step is one percent: fine enough that a drag along the slider reads + /// as continuous, and still a count rather than a float. + const MAX_STEPS: u8 = 100; + + /// 5% a press: twenty presses across the range, which is what the keys have + /// always moved. The slider is what the finer grid is for. + const KEY_STEP: u8 = 5; /// What the device is set to: mute wins, and the level is what it returns /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts. fn gain(self) -> f32 { - if self.muted { - 0. - } else { - f32::from(self.steps) / f32::from(Self::MAX_STEPS) - } + if self.muted { 0. } else { self.along() } } /// One press up or down, clamped at both ends -- saturating, so the count /// cannot wrap past silence into full volume. fn step(&mut self, up: bool) { self.steps = if up { - self.steps.saturating_add(1).min(Self::MAX_STEPS) + self.steps.saturating_add(Self::KEY_STEP).min(Self::MAX_STEPS) } else { - self.steps.saturating_sub(1) + self.steps.saturating_sub(Self::KEY_STEP) }; } + /// Where the hand let go along the slider, 0..1 from silence to full. The + /// grid is the same one the keys land on, so a drag to the top and a key + /// held up reach the very same number -- and a drag never touches mute: + /// asking for a level while muted is not asking for sound. + fn set_along(&mut self, frac: f32) { + self.steps = (frac.clamp(0., 1.) * f32::from(Self::MAX_STEPS)).round() as u8; + } + + /// How full the slider is drawn, 0..1. The level and not the gain: a muted + /// slider still shows what unmuting comes back to, exactly as the label + /// does. + fn along(self) -> f32 { + f32::from(self.steps) / f32::from(Self::MAX_STEPS) + } + /// What the button reads. The level shows while muted too: it is what the /// next press of the mute key brings back. fn label(self) -> String { @@ -311,8 +352,13 @@ impl RowItem { /// 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; 11] = [ +const MENU_ITEMS: [ActionId; 14] = [ ActionId::Cut, + // The clipboard pair, which had no door but a chord: copy takes the clip the + // menu names, and paste is the timeline's rather than this clip's -- the + // same kind of global item the mute below already is. + ActionId::Copy, + ActionId::Paste, ActionId::Delete, ActionId::Lift, ActionId::Regroup, @@ -320,6 +366,10 @@ const MENU_ITEMS: [ActionId; 11] = [ ActionId::Group, ActionId::Equalizer, ActionId::Speed, + // The scan is a clip card like the two above it -- opened on whichever half + // was clicked -- and a card only a stroke could open is one a pointer never + // finds. + ActionId::Silence, ActionId::Color, ActionId::Fit, ActionId::ToggleMute, @@ -358,9 +408,10 @@ fn speed_at(permille: i32) -> Speed { } /// The silence card's rows, in the order it lists them: how wide the apply -/// reaches, the four settings a scan is told, and the rate the speed-up plays -/// at. What `silence_field` indexes and what [`Player::nudge_silence`] moves. -const SILENCE_ROWS: usize = 6; +/// reaches, the threshold and the unit it is read in, the three durations a +/// scan is told, and the rate the speed-up plays at. What `silence_field` +/// indexes and what [`Player::nudge_silence`] moves. +const SILENCE_ROWS: usize = 7; /// How wide a jumpcut reaches. A ripple used to be the whole timeline's /// business and nothing else; it is a *choice* now, because a podcast track's @@ -408,9 +459,12 @@ const SILENCE_DB_STEP: f32 = 1.; const SILENCE_SECS_STEP: f64 = 0.05; /// How far each of them may be pushed. UI decisions, all of them: the engine -/// takes any finite number, but a threshold at 0 dBFS calls a whole take silent -/// and a forgiveness of ten seconds finds nothing in a talking head. -const SILENCE_DB_RANGE: (f32, f32) = (-80., -10.); +/// takes any finite number, but a forgiveness of ten seconds finds nothing in a +/// talking head. The threshold reaches full scale, which calls a whole take +/// silent -- that is a thing someone may want to ask for (the preview on the +/// lane says what it would cost before anything is cut), so the top is 0 rather +/// than a number this card picked for them. +const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.); const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.); /// The speed-up rate is bounded *below* by real time: a "speed-up" that slows @@ -451,6 +505,36 @@ const EQ_TICKS: [(f32, &str); 5] = [ (20000., "20k"), ]; +/// The gains the graph rules a line across, besides the 0 dB one it already +/// had: half way to each limit, so a boost can be read as "about six" without +/// counting pixels. The limits themselves are the box's own edges and are +/// named at the corners instead. +const EQ_DB_GRID: [f32; 2] = [6., -6.]; + +/// The grid's ink: above the card's background and below everything drawn on +/// it, so the lines are a ruling rather than a thing to look at. +const EQ_GRID: u32 = 0x3a3a3a; + +/// How many played samples one spectrum frame is transformed from. A power of +/// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz +/// is a 47 Hz bin, fine enough that the bass end is a shape and short enough +/// (21 ms) that the analyser moves with the music. +const EQ_FFT: usize = 1024; + +/// The level range the analyser is drawn across, floor to ceiling in dBFS: the +/// bottom of the box is silence and the top is a bin at -12 dBFS, which is +/// about where a mixed track's loudest band sits. A look, not a measurement -- +/// the numbers on the axis are the curve's dB, never the analyser's. +const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.); + +/// The analyser's fill, behind the curve: a dim blue-grey with enough alpha to +/// read as a haze the accent line sits on top of. +const EQ_SPECTRUM_INK: u32 = 0x7f95ad66; + +/// The area under the response curve, same accent as the line at a tenth of +/// its weight: it is what makes a boost read as a hill rather than as a wire. +const EQ_FILL_INK: u32 = 0x4a9eff26; + /// The colour card's four controls, in the order it lists them: what each is /// called and the range it moves in. The order is `ColorParams`' own, which is /// what [`color_band`] indexes. @@ -515,6 +599,10 @@ struct Player { /// The ruler's own box, recorded at prepaint: a mouse listener is handed /// the window position and nothing else. ruler: Rc>>, + /// How much of the timeline the ruler and the lanes are showing. Held here + /// and nowhere else: every frame-to-pixel answer in the panel comes out of + /// it, so the boxes, the playhead and the pointer cannot disagree. + view: View, /// Which clip the edit keys act on: the lane it is in and its index there. /// The *clicked* half, not the group -- a group is what gets marked on /// screen, but Lift has to know which half it was aimed at. Indices move @@ -584,6 +672,11 @@ struct Player { /// also why it is not written to the project file and cannot reach an /// export. [`Player::apply_volume`] is what pushes it at a session. volume: Volume, + /// Where the volume slider was last painted, and whether a hand is on it -- + /// the speed bar's pair, for the speed bar's reason: the pointer moves + /// arrive at the root, so the bar's own geometry has to be readable there. + volume_bar: Rc>>, + volume_dragging: bool, /// The keybindings overlay is up. While it is, it owns the keyboard and the /// pointer: a stroke or a click meant for a row must not also cut the /// timeline. @@ -622,6 +715,11 @@ struct Player { /// window position only, so this is what a press and a drag are read /// against ([`frac_along`], [`frac_down`]). eq_graph: Rc>>, + /// Whether the analyser is drawn behind the curve. On by default -- what + /// the curve is being *shaped against* is the point of drawing it -- and + /// off with one press for anyone who would rather read the curve alone. + /// Card state, not the project's: it changes nothing that plays. + eq_spectrum: bool, /// The colour card is up on this clip -- the lane it is on and its index /// there. `None` when it is closed, which is the only place that state /// lives: the grade itself is the project's. @@ -652,6 +750,14 @@ struct Player { /// Which of the card's [`SILENCE_ROWS`] the arrow keys move. The card's own /// focus, since nothing in it takes gpui's (ledger:182). silence_field: usize, + /// Whether the threshold is *labelled* dBFS or dB. Display only, and the + /// number is the same either way: the setting is a level below full scale, + /// so 0 is the loudest sample a file can hold and -40 is forty decibels + /// under it -- "dBFS" names that reference out loud, "dB" leaves it unsaid. + /// No conversion is hiding behind the row (there is no reference here worth + /// inventing, and a made-up SPL would be a lie about what was measured); + /// what it changes is which of the two spellings a person reads. + silence_dbfs: bool, /// What the last scan found, in timeline frames: what the lane draws marks /// over and what an apply acts on -- *exactly* the previewed set, never a /// second scan at the moment of the press. @@ -819,9 +925,20 @@ impl Player { ActionId::Color => self.open_color(cx), ActionId::Fit => self.cycle_fit(cx), ActionId::Resolution => self.cycle_resolution(cx), + // The playhead is what a key zoom is aimed at: it is the one place + // on the timeline the user is certainly looking at, and keeping it + // still is what every editor does. + ActionId::ZoomIn => self.zoom(ZOOM_STEP, None, cx), + ActionId::ZoomOut => self.zoom(1. / ZOOM_STEP, None, cx), + ActionId::ZoomFit => self.zoom_fit(cx), ActionId::Undo => self.undo(cx), ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx), ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx), + // The last track of that kind: the one the add key put there, so the + // two strokes undo each other press for press. Any other track goes + // through the × in its own header. + ActionId::RemoveVideoLane => self.remove_last_lane(LaneKind::Video, cx), + ActionId::RemoveAudioLane => self.remove_last_lane(LaneKind::Audio, cx), 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), @@ -937,6 +1054,26 @@ impl Player { cx.notify(); } + /// Magnifies the timeline about a point that stays put: `anchor` is where + /// along the bed to hold still (a ctrl+wheel holds the pointer), and with + /// none it is the playhead -- so the frame being worked on is still the + /// frame on screen after the zoom. Clamped at both ends by [`View`]: out + /// stops at the whole timeline, in at a handful of frames. + fn zoom(&mut self, factor: f32, anchor: Option, cx: &mut Context) { + let duration = self.drawn_duration(); + let at = self.playhead(duration); + let anchor = anchor.unwrap_or_else(|| self.view.frac_at(at, duration).clamp(0., 1.)); + self.view = self.view.zoomed(factor, anchor, duration, self.fps); + cx.notify(); + } + + /// All the way back out: the whole timeline across the bed, which is what + /// the panel shows before anyone has zoomed at all. + fn zoom_fit(&mut self, cx: &mut Context) { + self.view = View::default(); + cx.notify(); + } + /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from /// the media's own -- the one size that must stay reachable, since a project /// moved off it has no other way back (the resolution is not an undo step). @@ -1314,9 +1451,12 @@ impl Player { + steps as f32 * SILENCE_DB_STEP) .clamp(SILENCE_DB_RANGE.0, SILENCE_DB_RANGE.1) } - 2 => self.silence.min_silence = secs(self.silence.min_silence), - 3 => self.silence.padding = secs(self.silence.padding), - 4 => self.silence.min_keep = secs(self.silence.min_keep), + // Two spellings of the same level, so either arrow flips it -- a + // ring of two, like the scope row's. + 2 => self.silence_dbfs = !self.silence_dbfs, + 3 => self.silence.min_silence = secs(self.silence.min_silence), + 4 => self.silence.padding = secs(self.silence.padding), + 5 => self.silence.min_keep = secs(self.silence.min_keep), _ => { self.silence_factor = silence_rate(i32::from(self.silence_factor.permille()) + steps * SPEED_STEP) @@ -1408,6 +1548,11 @@ impl Player { match session.cut_regions(®ions, &lanes) { Ok(()) => { self.close_silence(); + // Every hole closed moves the clips after it up a place, so the + // selection now names a different clip than the one that is + // highlighted -- dropped here as after every other edit that + // moves indexes (a delete, a paste, an undo). + self.selected = None; self.reset_after_reseek(); self.notice = Some( format!( @@ -1442,6 +1587,10 @@ impl Player { match session.speed_regions(®ions, rate, &lanes) { Ok(()) => { self.close_silence(); + // Splitting each silence out and closing the room it no longer + // needs moves indexes exactly as the cut does: the selection + // goes with them. + self.selected = None; self.reset_after_reseek(); self.notice = Some( format!( @@ -1469,6 +1618,29 @@ impl Player { || self.exporting().is_some() } + /// Which of [`Repeat`]'s three the window is in, for the hold gate at the + /// top of the key handler. Not [`Player::modal`]: that asks whether an + /// overlay is up at all, and here the cards with sliders in them are + /// exactly the ones that answer differently from the keys menu and the + /// export card. + fn repeat_scope(&self) -> Repeat { + if self.rebinding.is_some() + || self.keys_open + || self.export_open + || self.exporting().is_some() + { + Repeat::Nothing + } else if self.eq_open.is_some() + || self.color_open.is_some() + || self.speed_open.is_some() + || self.silence_open.is_some() + { + Repeat::Card + } else { + Repeat::Keymap + } + } + /// 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), @@ -1980,14 +2152,16 @@ impl Player { /// pointer exactly. fn trim_to(&mut self, x: Pixels, cx: &mut Context) { let (duration, fps) = (self.drawn_duration(), self.fps); - let frac = frac_along(x, self.ruler.get()); + let at = self + .view + .time_at(frac_along(x, self.ruler.get()), duration); let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else { return; }; let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else { return; }; - trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi); + trim.to = frame_at(at, fps).clamp(lo, hi); cx.notify(); } @@ -2018,6 +2192,25 @@ impl Player { return clip; }; match trim.edge { + // A still grows forward from source frame 0 instead, exactly as + // `Project::trim` writes it: with the in-point clamped at 0 the box + // below would slide left rather than stretch, and the release would + // then commit a wider clip than the drag drew. + Edge::Start + if self.session.as_ref().is_some_and(|session| { + session + .sources() + .get(clip.source) + .is_some_and(|s| engine::is_image(&s.path)) + }) => + { + Clip { + in_frame: 0, + out_frame: clip.end().saturating_sub(trim.to).max(1), + start: trim.to, + ..clip + } + } // The in-point follows the head, exactly as `Project::trim` moves // it: what stays on screen plays what it always played. Edge::Start => Clip { @@ -2054,6 +2247,21 @@ impl Player { } } + /// Where the playhead is, as the panel draws it. The clock keeps running + /// after the last frame (wall time takes over at audio EOF) while the + /// picture is frozen, so what the UI shows is the clamped one, pinned to + /// the out-point once playback is done. + fn playhead(&self, duration: f64) -> f64 { + if self.done { + duration + } else { + self.session + .as_ref() + .map_or(0., PlaybackSession::now) + .clamp(0., duration) + } + } + /// The one way a library row reaches the timeline: the Add button and a row /// dragged onto a lane both come here, so there is a single answer to what /// "add this source" does. The whole source goes in at the playhead as one @@ -2133,20 +2341,43 @@ impl Player { .as_mut() .map(|session| session.remove_source(path, stream)); let text = match removed { - Some(Ok(())) => { + Some(Ok(idx)) => { // The picked row may be the one that just went, and the engine // reseeks, so this owes the flag reset like every other edit. if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) { self.selected_asset = None; } + // A copied clip names its source by *index*, and every index + // past the one that went has just moved down: without this the + // next paste puts some other file on the timeline. + self.clipboard = clipboard_after_remove(self.clipboard, idx); self.reset_after_reseek(); - // The undo stack goes with it (`Project::remove_source`): said - // here, because a `z` that does nothing afterwards would - // otherwise read as a bug. - format!( - "REMOVED {} — there is nothing left to undo", - file_name(path) - ) + // The last row leaves a session naming no file: nothing to + // play, nothing to save and nothing to show, which is the empty + // window the editor launches as. The next import scaffolds a + // fresh timeline from whatever file it is, at that file's own + // rate -- which is why the session goes rather than lingering + // on with the gone file's parameters. + match self + .session + .as_ref() + .is_some_and(|s| s.sources().is_empty()) + { + true => { + self.close_session(); + format!( + "REMOVED {} — the library is empty; import a file to start again", + file_name(path) + ) + } + // The undo stack goes with it (`Project::remove_source`): + // said here, because a `z` that does nothing afterwards + // would otherwise read as a bug. + false => format!( + "REMOVED {} — there is nothing left to undo", + file_name(path) + ), + } } Some(Err(e)) => format!("NOT REMOVED — {e}"), None => "NO TIMELINE — open a file first".to_string(), @@ -2155,6 +2386,64 @@ impl Player { cx.notify(); } + /// Back to the window the editor launches as: no timeline, no library, no + /// picture -- and the hint that says to open a file. What removing the last + /// library row leaves, since a session whose library is empty has nothing + /// left to be ([`Player::remove_source`]). + /// + /// Everything a *loaded project* resets goes here for its reasons (an index + /// into a timeline that is gone names nothing), plus the three per-file + /// caches: they are keyed by path, and the next file to arrive fills them + /// again. + fn close_session(&mut self) { + self.session = None; + // The picture goes with it, or the empty window would keep showing the + // last frame of a timeline that no longer exists. + // + // ponytail: its atlas tile is not released -- `window.drop_image` wants + // a `&mut Window` this door has no other reason to take. One tile per + // emptied library, against one per displayed frame in `pump`; the + // upgrade path is threading the window through `act_on_row`. + self.image = None; + self.clipboard = None; + self.selected = None; + self.selected_asset = None; + self.context_menu = None; + self.library_menu = None; + self.eq_open = None; + self.color_open = None; + self.speed_open = None; + self.close_silence(); + self.waves.clear(); + self.streams.clear(); + self.sizes.clear(); + // Scanned off a source that is not in the library any more. + self.silence_levels = None; + // Every gesture in flight, dropped for `reset_after_reseek`'s reason + // (it drops the trim below): a drag holds a bar, a clip or a band of a + // timeline that has just stopped existing. + self.scrubbing = false; + self.volume_dragging = false; + self.eq_dragging = false; + self.speed_dragging = false; + self.color_dragging = false; + self.displayed = 0; + self.dropped = 0; + self.started = None; + // The empty window's own: no name in the titlebar, nowhere chosen to + // export or save to yet, and a rate that only keeps the timecode + // reading in frames until a file brings its own (`main`). + self.name = NO_FILE.into(); + self.export_path = PathBuf::new(); + self.project_path = PathBuf::new(); + self.fps = 30.; + // No decoder to wait for a frame from: the hint is what shows. + self.reset_after_reseek(); + self.pending_seek = false; + self.eos = false; + self.done = false; + } + /// One item of a library row's menu, done. Every one of them closes the /// menu first -- the list under it is about to be rebuilt -- except the one /// that turns the card over. @@ -2188,11 +2477,22 @@ impl Player { cx.notify(); } - /// The rate and layout the whole timeline's audio is, taken from source 0's - /// own stream: what a library row has to match to be placeable. `None` - /// until that file has been probed, and then nothing is greyed for it. + /// The rate and layout the whole timeline's audio is, taken from the stream + /// of the first source that could have one: what a library row has to match + /// to be placeable. `None` until that file has been probed, and then nothing + /// is greyed for it. + /// + /// The first source that is *not a still*, which is the rule the engine + /// holds every import to (`playback::audio_source_of`) -- a picture at the + /// head of the list (a removal moves indexes) has no stream to describe + /// anything with. fn timeline_audio(&self) -> Option<(u32, u16)> { - let first = self.session.as_ref()?.sources().first()?; + let first = self + .session + .as_ref()? + .sources() + .iter() + .find(|s| !engine::is_image(&s.path))?; let info = self .streams .get(&first.path)? @@ -2397,6 +2697,64 @@ impl Player { cx.notify(); } + /// The × in a track's header: the add taken back, one undo step, and the + /// engine's own words when it refuses -- those name the clips still on the + /// track, so the notice says what to delete first. A removal never deletes a + /// clip. + /// + /// Everything holding a `(lane, idx)` is dropped, because the tracks below + /// the one that went have just moved up an `ord` + /// ([`engine::Project::remove_lane`]): a selection or an open card kept + /// across it would be pointing at the *next* track's clip. + fn remove_lane(&mut self, lane: Lane, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let removed = self + .session + .as_mut() + .map(|session| session.remove_lane(lane)); + let text = match removed { + Some(Ok(())) => { + self.selected = None; + self.context_menu = None; + self.eq_open = None; + self.color_open = None; + self.speed_open = None; + self.close_silence(); + format!( + "{} REMOVED — {} brings it back", + lane.label(), + self.keymap.display(ActionId::Undo) + ) + } + Some(Err(e)) => format!("NO TRACK REMOVED — {e}"), + None => "NO TRACK REMOVED — open a file first".to_string(), + }; + self.notice = Some(text.into()); + cx.notify(); + } + + /// What the remove keys act on: the last track of that kind, which is the + /// one the matching add key appended. Nothing at all before a file is open, + /// where the timeline drawn is a placeholder pair. + fn remove_last_lane(&mut self, kind: LaneKind, cx: &mut Context) { + let last = self.session.as_ref().and_then(|session| { + session + .lanes() + .into_iter() + .filter(|l| l.kind == kind) + .next_back() + }); + match last { + Some(lane) => self.remove_lane(lane, cx), + None => { + self.notice = Some("NO TRACK REMOVED — open a file first".into()); + cx.notify(); + } + } + } + fn undo(&mut self, cx: &mut Context) { if self.session.as_mut().is_some_and(PlaybackSession::undo) { self.reset_after_reseek(); @@ -2452,7 +2810,9 @@ impl Player { let Some(session) = &self.session else { return; }; - let t = f64::from(frac_along(x, self.ruler.get())) * session.timeline_duration(); + let t = self + .view + .time_at(frac_along(x, self.ruler.get()), session.timeline_duration()); let target = (t * self.fps) as u32; if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) { self.last_target = target; @@ -2483,10 +2843,33 @@ impl Player { cx.notify(); } + /// Where the pointer sits along the slider, as a level. The press and every + /// sample after it come here, so the sound follows the hand rather than the + /// release -- there is nothing to undo about a monitoring level, which is + /// why this writes live and keeps no gesture state beyond the flag. + fn drag_volume(&mut self, x: Pixels, cx: &mut Context) { + let along = frac_along(x, self.volume_bar.get()); + self.set_volume(|volume| volume.set_along(along), cx); + } + fn toggle_or_restart(&mut self, cx: &mut Context) { if self.exporting().is_some() { return; } + // Nothing to play is a message, not a transport state. An empty + // timeline is `done` from its one black frame onward, so the restart + // below would start a clock against a zero-length timeline -- and it is + // `done` again by the next repaint, so no later press could ever stop + // it: the button would read "Pause" and never pause. A delete can empty + // the timeline mid-play, and that press must still stop it. + if nothing_to_play(self.session.as_ref()) { + match self.session.as_mut().filter(|s| s.is_playing()) { + Some(session) => session.pause(), + None => self.notice = Some(NOTHING_TO_PLAY.into()), + } + cx.notify(); + return; + } if self.done { self.seek(0., cx); if let Some(session) = &mut self.session { @@ -2699,24 +3082,29 @@ impl Render for Player { // timecode, the ruler and the clamp below all have to follow it -- and // so does the room a tail being dragged needs to grow into. let duration = self.drawn_duration(); - // The clock keeps running after the last frame (wall time takes over at - // audio EOF) while the picture is frozen, so the timeline the UI shows is - // the clamped one, pinned to the out-point once playback is done. - let position = if self.done { - duration - } else { - self.session - .as_ref() - .map_or(0., PlaybackSession::now) - .clamp(0., duration) - }; + let position = self.playhead(duration); + // Re-settled every frame against the duration this one is drawing: an + // edit that shortens the timeline moves the far end of the view, and a + // playhead that has run off the bed pulls the view after it -- which is + // what makes a zoomed-in timeline scroll while it plays. + self.view = self.view.following(position, duration, self.fps); div() .track_focus(&self.focus) .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { - // `is_held` filters auto-repeat, which would otherwise toggle - // playback -- or cut the timeline -- many times a second. - if event.is_held { + let key = event.keystroke.key.as_str(); + let ctrl = event.keystroke.modifiers.control; + // `is_held` is the auto-repeat, and a value is the one thing + // worth running on it: a held arrow on a card moves the slider + // it picked, and a held volume key runs the volume. Everything + // else is filtered exactly as it always was -- a repeat that + // toggled playback, or cut the timeline, many times a second is + // what this guard is for, and a row waiting for a stroke takes + // none of it either (it would bind the key, then fire what it + // just bound). See [`repeats`]. + if event.is_held + && !repeats(this.repeat_scope(), key, this.keymap.lookup(key, ctrl)) + { return; } // Any key retires the last message, whatever it was -- and owes @@ -2726,7 +3114,6 @@ impl Render for Player { if this.notice.take().is_some() { cx.notify(); } - let key = event.keystroke.key.as_str(); // A row is waiting for a stroke, and while it is, that stroke is // data: it means the binding and nothing else, which is why this // answers before the export guard and before the keymap is @@ -2735,7 +3122,7 @@ impl Render for Player { if key == ESCAPE { this.rebinding = None; } else if !is_bare_modifier(key) { - this.capture(action, key, event.keystroke.modifiers.control); + this.capture(action, key, ctrl); } cx.notify(); return; @@ -2744,7 +3131,7 @@ impl Render for Player { // control modifier set (the control code is mapped back), which // is why the keymap is keyed on the pair and never on the key // alone. - let action = this.keymap.lookup(key, event.keystroke.modifiers.control); + let action = this.keymap.lookup(key, ctrl); // An export is reading the edit list every other action here // would change, so cancelling is the only one that means // anything until it is over. @@ -2816,6 +3203,11 @@ impl Render for Player { band.gain_db = 0.; } this.commit_eq(cx); + } else if key == "s" { + // The analyser off and on. Nothing is committed: it is + // what the card *shows*, so it survives no further than + // this window. + this.eq_spectrum = !this.eq_spectrum; } 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. @@ -2991,6 +3383,16 @@ impl Render for Player { } return; } + // The volume slider, the same live writes: what the hand is on + // is what the speakers are doing, and there is nothing to undo. + if this.volume_dragging { + if event.pressed_button == Some(MouseButton::Left) { + this.drag_volume(event.position.x, cx); + } else { + this.volume_dragging = false; + } + return; + } if !this.scrubbing { return; } @@ -3031,6 +3433,10 @@ impl Render for Player { this.drag_speed(event.position.x, false, cx); return; } + if std::mem::take(&mut this.volume_dragging) { + this.drag_volume(event.position.x, cx); + return; + } if std::mem::take(&mut this.scrubbing) { this.scrub_to(event.position.x, true, cx); } @@ -3382,11 +3788,11 @@ impl Player { playing: bool, cx: &mut Context, ) -> impl IntoElement { - let filled = if duration > 0. { - (position / duration) as f32 - } else { - 0. - }; + // Where the playhead is *on the bed*, which at the fit is where along + // the timeline it is and zoomed in is where along the visible slice. + // Clamped because it is drawn as a width as well as an offset, and the + // view follows the playhead anyway, so it is never off the bed. + let filled = self.view.frac_at(position, duration).clamp(0., 1.); // An export owns the hint slot and the ruler while it runs: the // percentage and the accent bar are the same number, so the playhead // fill doubles as the progress bar for free. @@ -3394,6 +3800,10 @@ impl Player { // Everything but Import and Keys needs a timeline to act on: with none // open they are dimmed rather than silently doing nothing. let live = self.session.is_some() && !exporting; + // The project's own picture size, for the button that cycles it: read + // per render like everything else here, so a cycle shows on the button + // that made it. + let resolution = self.session.as_ref().map(PlaybackSession::resolution); let key = |action| self.keymap.display(action); // The lanes the project has, or the pair a fresh one starts with so the // panel reads the same before a file is open as after. @@ -3443,18 +3853,35 @@ impl Player { .bg(rgb(CHROME)) // Transport | edit | file: three groups, so the eye can skip two of // them. Every button says what it does; the tooltip adds its key. + // + // The row scrolls rather than losing its tail: at the 640 px floor + // this window is sized for it is wider than the panel, and a button + // off the right edge is a button a pointer cannot press. A plain + // wheel moves it -- gpui puts a vertical delta on the x axis when + // that is the only one scrolling (div.rs:2424). .child( div() + .id("controls") .flex_none() .flex() .items_center() .gap(px(8.)) + .overflow_x_scroll() .child(control( "transport", Some(transport_glyph(playing).into_any_element()), if playing { "Pause" } else { "Play" }, - key(ActionId::Play), - live, + if nothing_to_play(self.session.as_ref()) && !playing { + format!("{} — put a clip on a lane first", key(ActionId::Play)) + } else { + key(ActionId::Play) + }, + // An empty timeline has nothing to play, so the button + // says so by being dim rather than by starting a clock + // against nothing (the key press answers with the + // notice). Still live while it *is* playing: a delete + // can empty the timeline mid-play and that has to stop. + live && (playing || !nothing_to_play(self.session.as_ref())), cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)), )) .child(separator()) @@ -3481,6 +3908,17 @@ impl Player { live && self.selected.is_some(), cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)), )) + // The way back from every one of them. It was a stroke and + // nothing else, which made the whole edit group a one-way + // door for anyone working with a pointer. + .child(control( + "undo", + None, + "Undo", + format!("{} — takes the last edit back", key(ActionId::Undo)), + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.undo(cx)), + )) // With the edit group, beside the buttons that change the // edit list: a track is a row of it, and adding one is an // undoable edit like the rest. Two buttons rather than one @@ -3529,20 +3967,115 @@ impl Player { this.set_volume(|volume| volume.muted = !volume.muted, cx) }), )) + // The level itself, to drag. The button beside it stays the + // mute -- one gesture each -- and the label above is what + // this writes, live, so the number follows the hand. + .child(volume_slider( + self.volume, + self.volume_bar.clone(), + live, + cx, + )) .child(separator()) + // The size every clip is composed onto, which is also the + // size the export comes out at: the one project setting a + // stroke used to be the only way to. Cycles exactly as the + // key does, and says where it is now rather than opening a + // list to close again. + .child(control( + "resolution", + None, + resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")), + match resolution { + Some((w, h)) => format!( + "{} — the project is {w}x{h}; cycles source → 2160p → 1080p → 720p → 480p", + key(ActionId::Resolution) + ), + None => format!("{} — open a file first", key(ActionId::Resolution)), + }, + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.cycle_resolution(cx)), + )) + // How much of the timeline the panel below is showing -- + // beside the resolution, since neither of them edits + // anything: they are both what is being looked at. The + // middle one reads as the state (1.0x is the whole + // timeline) and is the way back to it. + .child(control( + "zoom-out", + None, + "−", + format!( + "{} — show more of the timeline; stops at the whole of it", + key(ActionId::ZoomOut) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.zoom(1. / ZOOM_STEP, None, cx) + }), + )) + .child(control( + "zoom-fit", + None, + format!("{:.1}x", self.view.zoom), + format!( + "{} — fit the whole timeline; showing {} to {}", + key(ActionId::ZoomFit), + timecode(self.view.start, self.fps), + timecode( + (self.view.start + self.view.span(duration)).min(duration), + self.fps + ) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.zoom_fit(cx)), + )) + .child(control( + "zoom-in", + None, + "+", + format!( + "{} — magnify around the playhead; ctrl+wheel on the bar zooms at the pointer", + key(ActionId::ZoomIn) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)), + )) // Import is not here: it belongs to the media list it adds // to, and two doors into one action is a question about // which one is the real one. + // + // While one runs, this button is the way out of it: the + // progress line promised esc and nothing else, which left a + // pointer no way to stop an export it had started. .child(control( "export", None, - "Export", - format!( - "{} — quality and destination, then writes the timeline out", - key(ActionId::Export) - ), - live && self.export.is_none(), - cx.listener(|this, _: &ClickEvent, _, cx| this.open_export(cx)), + if exporting { "Cancel" } else { "Export" }, + if exporting { + format!( + "{} — stops the export; the part-written file goes", + key(ActionId::CancelExport) + ) + } else { + format!( + "{} — quality and destination, then writes the timeline out", + key(ActionId::Export) + ) + }, + if exporting { + true + } else { + live && self.export.is_none() + }, + cx.listener(|this, _: &ClickEvent, _, cx| { + if this.exporting().is_some() { + this.cancel_export(); + cx.notify(); + } else { + this.open_export(cx); + } + }), )) .child(control( "save", @@ -3620,7 +4153,32 @@ impl Player { .hover(|s| s.bg(rgb(HOVER_DIM))) // The strip carries no text, so the tooltip is the only // place it can say what it is. - .tooltip(|_, cx| cx.new(|_| Tip("Seek — click or drag".into())).into()) + .tooltip(|_, cx| { + cx.new(|_| Tip("Seek — click or drag; ctrl+wheel zooms".into())) + .into() + }) + // Ctrl+wheel is what every timeline zooms with, and + // the point held still is the one under the pointer + // rather than the playhead. Only with ctrl: a bare + // wheel here is the window's to scroll, and the + // controls row above scrolls on exactly that. + .on_scroll_wheel(cx.listener( + |this, event: &ScrollWheelEvent, _, cx| { + if !event.modifiers.control { + return; + } + let dy = match event.delta { + ScrollDelta::Lines(d) => d.y, + ScrollDelta::Pixels(d) => f32::from(d.y), + }; + if dy == 0. { + return; + } + let anchor = frac_along(event.position.x, this.ruler.get()); + let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP }; + this.zoom(factor, Some(anchor), cx); + }, + )) .on_mouse_down( MouseButton::Left, cx.listener(|this, event: &MouseDownEvent, _, cx| { @@ -4096,6 +4654,18 @@ impl Player { // clip and a 48 kHz one are not the same shape. let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate); let picked = self.eq_params.bands.get(self.eq_band); + // What is playing, drawn behind the curve -- and only while something + // *is* playing: the tap freezes with the device, and a still spectrum + // under a paused timeline would look like sound that is not there. + let spectrum = self + .eq_spectrum + .then_some(self.session.as_ref()) + .flatten() + .filter(|session| session.is_playing()) + .and_then(PlaybackSession::audio_tap) + .map(|(samples, rate)| eq_spectrum(&samples, rate)) + .filter(|levels| !levels.is_empty()) + .map(eq_spectrum_curve); let handles: Vec<_> = self .eq_params .bands @@ -4141,6 +4711,44 @@ impl Player { }), ) .child(bounds_probe(self.eq_graph.clone())) + // The analyser first, so everything else is drawn on top of it. + .children(spectrum) + // The decades, so a hump can be read as "around 200 Hz" without + // dropping the eye to the labels along the bottom. The two ends + // are the box's own edges and rule nothing. + .children( + EQ_TICKS + .iter() + .filter(|(freq, _)| *freq > EQ_FREQ_LOW && *freq < EQ_FREQ_HIGH) + .map(|(freq, _)| { + div() + .absolute() + .left(relative(eq_x(*freq))) + .w(px(1.)) + .h_full() + .bg(rgb(EQ_GRID)) + }) + .collect::>(), + ) + // Half way to each limit, each carrying its own number: the curve + // is a curve of decibels, and until now only one of them was drawn. + .children(EQ_DB_GRID.map(|db| { + div() + .absolute() + .top(relative(eq_y(db))) + .w_full() + .h(px(1.)) + .bg(rgb(EQ_GRID)) + .child( + div() + .absolute() + .left(px(4.)) + .top(px(-11.)) + .text_size(px(9.)) + .text_color(rgb(INK_DIM)) + .child(format!("{db:+.0}")), + ) + })) // 0 dB: the line a boost is a boost *from*. .child( div() @@ -4175,6 +4783,9 @@ impl Player { .text_color(rgb(INK_DIM)) .child(format!("+{EQ_GAIN_LIMIT:.0} dB")), ); + // The bottom of the axis is not named: -12 dB would land in the same + // corner as the 20 Hz tick, and the two lines above it (+6 and -6) + // already say what the box is worth per pixel. Some( div() .absolute() @@ -4209,7 +4820,7 @@ impl Player { .text_size(px(11.)) .text_color(rgb(INK_DIM)) .child(self.notice.clone().unwrap_or_else(|| { - "drag the curve, or 1–5 then up/down — esc closes".into() + "drag the curve, or 1–5 then up/down — s hides the spectrum, esc closes".into() })), ) .child(graph) @@ -4218,34 +4829,72 @@ impl Player { // one pulling the other way is not readable off it. .child(div().flex_none().px(px(6.)).text_size(px(11.)).child( match picked { + // Q as well as the two the curve shows: it is + // how wide the hump under the handle is, and + // nothing else on the card says so. Some(band) => format!( - "{} {} {:+.1} dB", + "{} {} {:+.1} dB — Q {:.2}", self.eq_band + 1, band_label(band), - band.gain_db + band.gain_db, + band.q ), None => "no bands".into(), }, )) .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"), + .gap(px(4.)) + .child( + div() + .id("eq-reset") + .flex() + .flex_1() + .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 analyser's switch, next to the one other + // button the card has: `s` does the same, and a + // toggle only a keystroke can reach is one most + // people never find. + .child( + div() + .id("eq-spectrum") + .flex() + .flex_1() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(match self.eq_spectrum { + true => SELECTED, + false => HOVER_DIM, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.eq_spectrum = !this.eq_spectrum; + cx.notify(); + })) + .child(match self.eq_spectrum { + true => "Spectrum on", + false => "Spectrum off", + }), + ), ), ), ) @@ -4548,9 +5197,19 @@ impl Player { fn silence_card(&self, cx: &mut Context) -> Option { let (lane, idx) = self.silence_open?; let cfg = self.silence; + // The unit is a label, never a conversion: the threshold is a level + // below full scale whichever of the two the row says (`silence_dbfs`). + let unit = match self.silence_dbfs { + true => "dBFS", + false => "dB", + }; let rows = [ ("Apply to", self.silence_scope.label(&self.silence_lanes())), - ("Silence is under", format!("{:.0} dBFS", cfg.threshold_db)), + ( + "Silence is under", + format!("{:.0} {unit}", cfg.threshold_db), + ), + ("Level read in", format!("{unit} (0 = full scale)")), ( "Forgive quiet shorter than", format!("{:.2} s", cfg.min_silence), @@ -4591,7 +5250,45 @@ impl Player { cx.notify(); })) .child(div().text_color(rgb(INK_DIM)).child(label)) - .child(value) + // The value and the two steps that move it. Every other + // card has something to drag or press; this one had the + // arrow keys and nothing else, so a row was a setting a + // pointer could pick but never change. One press each, the + // same call the arrows make -- the hold-to-run is the + // keyboard's own and is not a thing a button has. + .child( + div() + .flex() + .items_center() + .gap(px(4.)) + .child(value) + .children([-1, 1].map(|steps: i32| { + div() + .id(("silence-step", n * 2 + usize::from(steps > 0))) + .flex_none() + .w(px(HIT_MIN)) + .h(px(KEYS_ROW_H)) + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(CHROME)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + // Picked as well as moved: the row a + // press lands on is the row the arrows + // carry on from. + this.silence_field = n; + this.nudge_silence(steps); + cx.notify(); + })) + .child(match steps > 0 { + true => "+", + false => "−", + }) + })), + ) }) .collect(); // The two buttons the ask names, side by side: a mode toggle would hide @@ -4649,7 +5346,7 @@ impl Player { .text_size(px(11.)) .text_color(rgb(INK_DIM)) .child( - "↑↓ picks a setting, ←→ moves it — the marks on the lane are what would go; esc closes", + "− and + move a setting, or ↑↓ picks one and ←→ moves it (hold to run it) — the marks on the lane are what would go; esc closes", ), ) .children(rows) @@ -4930,7 +5627,7 @@ impl Player { // 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. - let label = if action == ActionId::ToggleMute { + let label = if matches!(action, ActionId::ToggleMute | ActionId::Paste) { format!("{} (global)", action.label()) } else { action.label().to_string() @@ -4977,7 +5674,10 @@ impl Player { let (x, y) = menu_at( menu.at, viewport, - MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H, + // The cap once the list is longer than it: past that the list + // scrolls and the card stops growing, exactly as the keybindings and + // export lists do. + MENU_PAD * 2. + (rows.len() as f32 * MENU_ROW_H).min(MENU_ROWS_H), ); let full: SharedString = source.path.display().to_string().into(); Some( @@ -5032,7 +5732,18 @@ impl Player { .when(menu.details, |d| { d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into()) }) - .children(rows), + // The list scrolls where the card would otherwise grow + // past the window's floor -- an item hanging off the + // bottom edge is an item nobody can click. + .child( + div() + .id("menu-rows") + .flex() + .flex_col() + .max_h(px(MENU_ROWS_H)) + .overflow_y_scroll() + .children(rows), + ), ), ) } @@ -5059,6 +5770,9 @@ impl Player { // one probe answers for both. Zero before the first paint, which only // costs the labels one frame. let bed_w = f32::from(self.ruler.get().size.width); + // The slice being shown, copied out once: every box in the row is + // placed through it, so all of them move together when it does. + let view = self.view; let clips = self .session .as_ref() @@ -5077,6 +5791,12 @@ impl Player { }); let name = lane.label(); let row_id: SharedString = format!("{name}-clip").into(); + let remove_id: SharedString = format!("{name}-remove").into(); + let remove_tip: SharedString = format!( + "Remove {name} — it must be empty first, and {} brings it back", + self.keymap.display(ActionId::Undo) + ) + .into(); let sources = self .session .as_ref() @@ -5106,20 +5826,44 @@ impl Player { .w(px(HEADER_W)) .h_full() .flex() + .flex_col() .items_center() .justify_center() .rounded(px(3.)) .bg(rgb(SURFACE)) .text_size(px(11.)) .text_color(rgb(INK_DIM)) - .child(name), - ) - .child( - // Clips are placed at their own start rather than queued edge - // to edge: a lift leaves a hole in the lane, and the bare bed - // showing through it *is* how a gap looks. - div() - .relative() + .child(div().flex_1().flex().items_center().child(name)) + // The one thing a header does: take this track away again. + // A `HIT_MIN` target rather than a glyph-sized one, and it + // stays put on a track holding clips instead of hiding -- + // the refusal names them, and a control that vanishes + // teaches nothing. + .child( + div() + .id(remove_id) + .flex_none() + .w_full() + .h(px(HIT_MIN)) + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .tooltip(move |_, cx| cx.new(|_| Tip(remove_tip.clone())).into()) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.remove_lane(lane, cx) + })) + .child("×"), + ), + ) + .child( + // Clips are placed at their own start rather than queued edge + // to edge: a lift leaves a hole in the lane, and the bare bed + // showing through it *is* how a gap looks. + div() + .relative() .flex_1() .min_w(px(0.)) .h_full() @@ -5166,7 +5910,7 @@ impl Player { .and_then(|s| sources.iter().position(|o| o.path == s.path)) .unwrap_or(clip.source), ); - let width = width_frac(len, duration); + let width = view.width_frac(len, duration); let label = sources.get(clip.source).map(|s| file_name(&s.path)); let wave = sources .get(clip.source) @@ -5190,7 +5934,11 @@ impl Player { .absolute() .top_0() .h_full() - .left(relative(start_frac(start, duration))) + // Negative once the clip's head has been scrolled + // off the left edge: the bed clips what hangs out + // of it, so a half-visible clip is drawn as the + // half of itself that is on screen. + .left(relative(view.frac_at(start, duration))) .w(relative(width)) .overflow_hidden() .rounded(px(3.)) @@ -5339,8 +6087,12 @@ impl Player { .absolute() .top_0() .h_full() - .left(relative(start_frac(f64::from(at) / self.fps, duration))) - .w(relative(width_frac(f64::from(len) / self.fps, duration))) + .left(relative( + view.frac_at(f64::from(at) / self.fps, duration), + )) + .w(relative( + view.width_frac(f64::from(len) / self.fps, duration), + )) .bg(rgba(0x4a9effaa)) }), ) @@ -5650,6 +6402,28 @@ fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) - picked.is_some() && timeline && !exporting } +/// What is left on the clipboard after the library row at `removed` was taken +/// out. A copied clip names its file by *index* into the source list +/// (`engine::Clip::source`) and a removal renumbers that list +/// (`engine::Project::remove_source`), so a clipboard kept as it was would paste +/// **a different file** -- the next one along -- over the range it was copied +/// from. +/// +/// The clip's own file gone means there is nothing to paste: `None`, and the +/// next paste says the clipboard is empty rather than putting some other take +/// down. Every index past it moves down by one, exactly as the lanes' clips do. +fn clipboard_after_remove(clip: Option, removed: usize) -> Option { + let mut clip = clip?; + match clip.source.cmp(&removed) { + std::cmp::Ordering::Equal => None, + std::cmp::Ordering::Greater => { + clip.source -= 1; + Some(clip) + } + std::cmp::Ordering::Less => Some(clip), + } +} + /// One library row: a file and one of its audio streams. Plain data, planned /// before anything is drawn -- which rows exist at all is the branchy part. #[derive(Debug, PartialEq)] @@ -5895,7 +6669,7 @@ impl Quality { /// that opens but never comes back out is exactly the gap a user would other- /// wise go looking for. const FORMATS: [(Option, &str, &str); 9] = [ - (Some(Format::Mp4), "MP4", "H.264 picture + copied AAC"), + (Some(Format::Mp4), "MP4", "H.264 picture + AAC sound"), ( Some(Format::Av1), "AV1", @@ -5905,7 +6679,7 @@ const FORMATS: [(Option, &str, &str); 9] = [ (Some(Format::Flac), "FLAC", "lossless — audio only"), (None, "MP3", "encoder is LGPL — licence decision pending"), (None, "OGG", "no pure-Rust Vorbis or Opus encoder"), - (None, "AAC", "encoder exists (rusty_aac) but is not wired here yet"), + (None, "AAC", "an MP4's sound here, not a file of its own"), ( None, "HEVC", @@ -6142,6 +6916,50 @@ fn cancels_export(key: &str, action: Option) -> bool { key == ESCAPE || action == Some(ActionId::CancelExport) } +/// Where a held key would land, which is the whole of what auto-repeat has to +/// know. [`Player::repeat_scope`] answers it from the same state the handler +/// walks below itself. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Repeat { + /// A card with values in it owns the keyboard: equalizer, colour, speed or + /// silence. Its arrows are sliders. + Card, + /// Nobody does, so the keymap answers -- and only one pair of its actions + /// is a value being moved rather than a thing being done once. + Keymap, + /// A stroke is being captured, an export is running, or an overlay with no + /// value in it is up. Nothing there is worth a repeat. + Nothing, +} + +/// Whether a *held* stroke means it again. One press is always one action; a +/// hold is only ever a value running, so this is what tells the two apart. +/// +/// The cards' arrows, because that is what every one of them moves a slider +/// with -- and only the arrows, so the equalizer's `r` cannot flatten five +/// bands forty times a second and the silence card's `enter` cannot cut forty +/// places again on the next tick. Outside a card the volume pair and nothing +/// else: play, cut, delete, save, export and every other binding is a one-shot, +/// exactly as it was when the handler filtered every held key alike. +fn repeats(scope: Repeat, key: &str, action: Option) -> bool { + match scope { + Repeat::Card => matches!(key, "up" | "down" | "left" | "right"), + Repeat::Keymap => matches!( + action, + Some( + ActionId::VolumeUp + | ActionId::VolumeDown + // A zoom is a value being moved as much as a level is: + // held, it runs from the whole timeline down to a handful + // of frames and stops there. The fit is one press. + | ActionId::ZoomIn + | ActionId::ZoomOut + ) + ), + Repeat::Nothing => false, + } +} + /// The keys that are only ever half a chord. gpui delivers a lone modifier /// press as a keystroke of its own, and taking one as a binding would leave an /// action that fires the moment the user reaches for any chord that uses it -- @@ -6235,14 +7053,127 @@ fn width_frac(len: f64, total: f64) -> f32 { if total > 0. { (len / total) as f32 } else { 1. } } -/// Where along the lane a clip starts, 0..1. Unlike [`width_frac`] a timeline -/// with no length pins this to the left edge -- a full-width offset would push -/// the box out of the lane it belongs to. -fn start_frac(start: f64, total: f64) -> f32 { - if total > 0. { - (start / total).clamp(0., 1.) as f32 - } else { - 0. +/// One press of a zoom key, or one notch of ctrl+wheel. +const ZOOM_STEP: f32 = 1.25; + +/// How few frames the bed may be narrowed down to. Past this there is nothing +/// left to aim at -- a single frame across a whole window is a wall of colour, +/// not an edit surface. +const ZOOM_MIN_FRAMES: f64 = 8.; + +/// Which slice of the timeline the ruler and the lanes are showing: `zoom` is +/// how many times the whole of it the bed is now worth, and `start` the moment +/// at the bed's left edge. The one place frames become pixels -- every box, the +/// playhead, a seek and a trim all go through it, so none of them can drift +/// away from the others when the view moves. +/// +/// [`View::default`] is the whole timeline across the bed, which is what the +/// panel drew before there was a zoom at all: at zoom 1 `start` is pinned to 0 +/// and every fraction here is the one [`width_frac`] and `start_frac` gave. +#[derive(Clone, Copy, Debug, PartialEq)] +struct View { + zoom: f32, + start: f64, +} + +impl Default for View { + fn default() -> Self { + View { + zoom: 1., + start: 0., + } + } +} + +impl View { + /// How much of the timeline is on the bed, in seconds. + fn span(self, duration: f64) -> f64 { + duration / f64::from(self.zoom) + } + + /// The tightest this timeline may be zoomed: [`ZOOM_MIN_FRAMES`] across the + /// bed. Never under 1 -- a timeline shorter than that is already at its + /// floor, and a zoom that cannot fit the whole of it is not a zoom. + fn max_zoom(duration: f64, fps: f64) -> f32 { + let frames = duration * fps; + if frames > ZOOM_MIN_FRAMES { + (frames / ZOOM_MIN_FRAMES) as f32 + } else { + 1. + } + } + + /// Where a moment sits along the bed, 0 at its left edge and 1 at its + /// right. Outside that range for a moment scrolled off the view, which is + /// exactly the negative offset a half-visible clip is drawn at. + fn frac_at(self, at: f64, duration: f64) -> f32 { + let span = self.span(duration); + if span > 0. { + ((at - self.start) / span) as f32 + } else { + 0. + } + } + + /// How wide a stretch of `len` seconds is on the bed. More than the whole + /// bed once zoomed in, which is the point of zooming in. + fn width_frac(self, len: f64, duration: f64) -> f32 { + width_frac(len, self.span(duration)) + } + + /// The moment a pointer at `frac` along the bed is pointing at: the inverse + /// of [`View::frac_at`], and what every seek and every trim reads. + fn time_at(self, frac: f32, duration: f64) -> f64 { + (self.start + f64::from(frac) * self.span(duration)).clamp(0., duration) + } + + /// Zoomed by `factor` about `anchor` (0..1 along the bed): whatever moment + /// was under that point stays under it, so a zoom magnifies what was being + /// looked at rather than throwing it off the edge. + fn zoomed(self, factor: f32, anchor: f32, duration: f64, fps: f64) -> Self { + let at = self.start + f64::from(anchor) * self.span(duration); + // Clamped *before* the offset is worked out, not after: a press that + // runs into either stop must still leave the anchor where it is, and a + // start measured against a zoom the stop then took away would slide it. + let zoom = (self.zoom * factor).clamp(1., Self::max_zoom(duration, fps)); + let start = at - f64::from(anchor) * View { zoom, start: 0. }.span(duration); + View { zoom, start }.settled(duration, fps) + } + + /// Clamped to the timeline it draws: never wider than the whole of it (the + /// zoom-out floor is the fit), never tighter than [`View::max_zoom`], and + /// never scrolled past either end. + fn settled(self, duration: f64, fps: f64) -> Self { + let zoom = if self.zoom.is_finite() { + self.zoom.clamp(1., Self::max_zoom(duration, fps)) + } else { + 1. + }; + let span = View { zoom, start: 0. }.span(duration); + let start = if self.start.is_finite() { + self.start.clamp(0., (duration - span).max(0.)) + } else { + 0. + }; + View { zoom, start } + } + + /// The view a playhead at `at` needs: the same one while it is on the bed, + /// and one centred on it once it has run off -- which is how a zoomed-in + /// timeline scrolls, during playback and after a seek alike. At the fit + /// this can never fire, so an unzoomed panel is untouched by it. + fn following(self, at: f64, duration: f64, fps: f64) -> Self { + let view = self.settled(duration, fps); + let span = view.span(duration); + if at < view.start || at > view.start + span { + View { + start: at - span / 2., + ..view + } + .settled(duration, fps) + } else { + view + } } } @@ -6440,6 +7371,59 @@ fn control( }) } +/// The monitoring level as something to drag: 4 px of bar to look at and the +/// whole control's height to hit (WCAG 2.5.8), the split the speed bar and the +/// colour sliders both make. Only the level -- mute is the button beside it, so +/// a muted slider still shows what unmuting comes back to, drawn dim. +/// +/// Dimmed and inert without a timeline, like every other control that would +/// have nothing to act on. +fn volume_slider( + volume: Volume, + bar: Rc>>, + enabled: bool, + cx: &mut Context, +) -> impl IntoElement { + div() + .id("volume-bar") + .relative() + .flex_none() + .w(px(VOLUME_W)) + .h(px(CONTROL_H)) + .flex() + .items_center() + .tooltip(|_, cx| { + cx.new(|_| Tip("Volume — drag to set the level; the button mutes".into())) + .into() + }) + .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) + .when(enabled, |d| { + d.cursor_pointer() + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, event: &MouseDownEvent, _, cx| { + this.volume_dragging = true; + this.drag_volume(event.position.x, cx); + }), + ) + .child(bounds_probe(bar)) + }) + .child( + div() + .w_full() + .h(px(4.)) + .rounded(px(2.)) + .bg(rgb(SURFACE)) + .child( + div() + .h_full() + .w(relative(volume.along())) + .rounded(px(2.)) + .bg(rgb(if volume.muted { INK_DIM } else { ACCENT })), + ), + ) +} + /// The line between two groups of buttons. fn separator() -> impl IntoElement { div() @@ -6599,6 +7583,131 @@ fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement { .size_full() } +/// In-place radix-2 FFT of `re`/`im`, whose length must be a power of two. +/// +/// Hand-written, and deliberately: a 1024-point transform once a frame is a +/// few tens of microseconds of plain arithmetic, and a dependency for it would +/// be a build cost this editor pays on every compile for one card's backdrop. +fn fft(re: &mut [f32], im: &mut [f32]) { + let n = re.len(); + // Decimation in time: the input is first put in bit-reversed order, after + // which the butterflies run over neighbours. + let mut j = 0usize; + for i in 1..n { + let mut bit = n >> 1; + while j & bit != 0 { + j ^= bit; + bit >>= 1; + } + j |= bit; + if i < j { + re.swap(i, j); + im.swap(i, j); + } + } + let mut span = 2; + while span <= n { + let step = std::f32::consts::TAU / span as f32; + for start in (0..n).step_by(span) { + for k in 0..span / 2 { + // e^{-i2πk/span}: the negative sign is the forward transform. + let (sin, cos) = (-step * k as f32).sin_cos(); + let (a, b) = (start + k, start + k + span / 2); + let (tr, ti) = (cos * re[b] - sin * im[b], cos * im[b] + sin * re[b]); + re[b] = re[a] - tr; + im[b] = im[a] - ti; + re[a] += tr; + im[a] += ti; + } + } + span <<= 1; + } +} + +/// The played signal as one height per curve point, 0 (silence) to 1 (the top +/// of the box) -- the analyser the response curve is drawn on top of. +/// +/// The newest [`EQ_FFT`] samples of the engine's tap, Hann-windowed so a tone +/// that does not land on a bin centre is one hump rather than a smear across +/// the axis. Each column takes the *loudest* bin between it and its +/// neighbours: the axis is logarithmic, so one column near 20 Hz is a fraction +/// of a bin while one near 20 kHz is hundreds, and averaging those would sink +/// every peak up there into the noise beside it. +/// +/// Empty -- nothing to draw -- for a tap too short to transform, which is what +/// a session has just after a seek. +/// +/// ponytail: one transform length for the whole axis, so the bass end is a bin +/// (47 Hz at 48 kHz) wide however many columns are drawn across it -- a 60 Hz +/// hum and an 80 Hz one are the same hump down there. Upgrade path is the +/// analyser every mastering EQ uses: two or three transforms of different +/// lengths, each drawn over the octaves it resolves. +fn eq_spectrum(samples: &[f32], sample_rate: u32) -> Vec { + if samples.len() < EQ_FFT { + return Vec::new(); + } + let tail = &samples[samples.len() - EQ_FFT..]; + let mut re: Vec = tail + .iter() + .enumerate() + .map(|(i, s)| { + let w = 0.5 * (1. - (std::f32::consts::TAU * i as f32 / EQ_FFT as f32).cos()); + s * w + }) + .collect(); + let mut im = vec![0.; EQ_FFT]; + fft(&mut re, &mut im); + // Magnitude per bin, scaled so a full-scale sine reads 0 dBFS: half the + // energy is in the mirrored half of the transform, and the Hann window + // takes another factor of two off. + let mags: Vec = (0..EQ_FFT / 2) + .map(|k| (re[k] * re[k] + im[k] * im[k]).sqrt() * 4. / EQ_FFT as f32) + .collect(); + let bin_hz = sample_rate as f32 / EQ_FFT as f32; + let (floor, ceiling) = EQ_SPECTRUM_DB; + let at = |along: f32| EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); + (0..=EQ_CURVE_STEPS) + .map(|step| { + let along = step as f32 / EQ_CURVE_STEPS as f32; + let half = 0.5 / EQ_CURVE_STEPS as f32; + // Bin 0 is DC and means nothing here, so the low end starts at 1. + let low = (at(along - half) / bin_hz).round().max(1.) as usize; + let high = (at(along + half) / bin_hz).round().max(1.) as usize; + let peak = (low..=high) + .filter_map(|k| mags.get(k)) + .fold(0f32, |a, &b| a.max(b)); + let db = 20. * peak.max(1e-9).log10(); + ((db - floor) / (ceiling - floor)).clamp(0., 1.) + }) + .collect() +} + +/// The analyser drawn as one filled shape from the floor of the box. +fn eq_spectrum_curve(levels: Vec) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + let last = levels.len().saturating_sub(1).max(1) as f32; + let mut path = PathBuilder::fill(); + path.move_to(point(o.x, o.y + s.height)); + for (i, level) in levels.iter().enumerate() { + path.line_to(point( + o.x + s.width * (i as f32 / last), + o.y + s.height * (1. - level), + )); + } + path.line_to(point(o.x + s.width, o.y + s.height)); + path.close(); + if let Ok(path) = path.build() { + window.paint_path(path, rgba(EQ_SPECTRUM_INK)); + } + }, + ) + .absolute() + .size_full() +} + /// The cascade's frequency response, drawn as one line across the graph. /// /// Every point comes from `EqParams::response_db`, which reads the very @@ -6613,14 +7722,31 @@ fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement { |_, _, _| (), move |bounds, _, window, _| { let (o, s) = (bounds.origin, bounds.size); + let points: Vec<_> = (0..=EQ_CURVE_STEPS) + .map(|step| { + let along = step as f32 / EQ_CURVE_STEPS as f32; + let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); + point( + o.x + s.width * along, + o.y + s.height * eq_y(params.response_db(freq, sample_rate)), + ) + }) + .collect(); + // The area between the curve and 0 dB, closed along that line: a + // boost and a cut wind opposite ways around it, which is exactly + // what makes both of them fill and the flat parts stay empty. + let mut area = PathBuilder::fill(); + area.move_to(point(o.x, o.y + s.height / 2.)); + for at in &points { + area.line_to(*at); + } + area.line_to(point(o.x + s.width, o.y + s.height / 2.)); + area.close(); + if let Ok(area) = area.build() { + window.paint_path(area, rgba(EQ_FILL_INK)); + } let mut path = PathBuilder::stroke(px(2.)); - for step in 0..=EQ_CURVE_STEPS { - let along = step as f32 / EQ_CURVE_STEPS as f32; - let freq = EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along); - let at = point( - o.x + s.width * along, - o.y + s.height * eq_y(params.response_db(freq, sample_rate)), - ); + for (step, at) in points.into_iter().enumerate() { match step { 0 => path.move_to(at), _ => path.line_to(at), @@ -6704,21 +7830,25 @@ fn timecode(t: f64, fps: f64) -> String { #[cfg(test)] mod tests { use super::{ - ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH, - EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS, - Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, - INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, - LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, - Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, - SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, - applicable, band_label, can_add, cancels_export, color_snap, envelope, eq_x, eq_y, - export_path, export_settings, format_key, format_line, format_refusal, frac_along, + ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_CURVE_STEPS, + EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_SPECTRUM_DB, + EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, + HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, + LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, + MENU_PAD, MENU_ROW_H, MENU_ROWS_H, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, + SELECTED, SILENCE_ROWS, SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, + Speed, StreamInfo, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, + can_add, cancels_export, clipboard_after_remove, color_snap, envelope, eq_spectrum, eq_x, + eq_y, export_path, export_settings, format_key, format_line, format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, - menu_at, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label, - silence_rate, source_tint, span_partner, speed_at, start_frac, timecode, unseen_paths, - unseen_sources, whole_take, width_frac, window_title, + menu_at, normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, + scrub_due, show_label, silence_rate, source_tint, span_partner, speed_at, timecode, + unseen_paths, unseen_sources, whole_take, width_frac, window_title, + }; + use super::{ + LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows, + repeats, unscannable, }; - use super::{LaneKind, file_name, file_uri, library_rows, unscannable}; /// What the file manager is handed: the parts a path keeps as they are, and /// the ones the bus would otherwise read as something else. @@ -7067,6 +8197,93 @@ mod tests { assert!(ActionId::ALL.contains(&action), "{action:?} is not listed"); assert_ne!(keymap.display(action), "unbound", "{action:?}"); } + // ...and the whole card still fits the 640x360 floor, however many items + // it grows to: the list is what scrolls past the cap, never the card. + let items = MENU_ITEMS.len() + 1; // Properties + assert!(MENU_PAD * 2. + MENU_ROWS_H <= 360., "menu too tall"); + assert!( + MENU_ROWS_H / MENU_ROW_H >= 12., + "too few items visible to scan" + ); + assert_eq!( + menu_at(point(px(0.), px(0.)), size(px(640.), px(360.)), { + MENU_PAD * 2. + (items as f32 * MENU_ROW_H).min(MENU_ROWS_H) + }), + (0., 0.) + ); + } + + /// The other half of the keys menu's guarantee, and the audit this batch was + /// asked for kept as a test: no action may be a stroke and nothing else. + /// Either the clip menu offers it, or a control in the panel does -- named + /// here by the id [`control`] is handed, read out of this file's own source + /// like `no_stroke_is_missing_from_the_keys_menu` reads the key handler. + #[test] + fn every_action_is_reachable_without_the_keyboard() { + use keymap::ActionId; + let source = include_str!("main.rs") + .split("#[cfg(test)]") + .next() + .unwrap(); + let element = |id: &str| source.contains(&format!("\"{id}\"")); + for action in ActionId::ALL { + let by_pointer = MENU_ITEMS.contains(&action) + || match action { + ActionId::Play => element("transport"), + // One slot, two states: it starts an export and stops the + // one it started. + ActionId::Export | ActionId::CancelExport => element("export"), + ActionId::Save => element("save"), + ActionId::Undo => element("undo"), + ActionId::Resolution => element("resolution"), + // Three buttons beside it, and the ctrl+wheel on the bar. + ActionId::ZoomIn => element("zoom-in"), + ActionId::ZoomOut => element("zoom-out"), + ActionId::ZoomFit => element("zoom-fit"), + ActionId::AddVideoLane => element("add-video-lane"), + ActionId::AddAudioLane => element("add-audio-lane"), + // The × in a lane's own header, which takes any track and + // not only the last one. + ActionId::RemoveVideoLane | ActionId::RemoveAudioLane => { + source.contains("this.remove_lane(lane, cx)") + } + ActionId::ToggleMute => element("volume"), + ActionId::VolumeUp | ActionId::VolumeDown => element("volume-bar"), + // The ruler seeks anywhere the pointer points; the frame and + // the second are the keyboard's finer grain of that move. + ActionId::StepBack + | ActionId::StepForward + | ActionId::JumpBack + | ActionId::JumpForward + | ActionId::GoStart + | ActionId::GoEnd => element("ruler"), + // A press on a clip is the selection, group and all. + ActionId::Select | ActionId::SelectNext | ActionId::SelectPrev => { + source.contains("this.select((lane, i), cx)") + } + _ => false, + }; + assert!(by_pointer, "{action:?} is reachable by keyboard only"); + } + // The card-local strokes have the same rule, and each of them is a thing + // on its card: the graph and its two buttons, the colour bars and their + // reset, the speed bar and its presets, and the silence card's rows -- + // whose steppers are the pointer's only way to a threshold. + for id in [ + "eq-graph", + "eq-reset", + "eq-spectrum", + "color-bar", + "color-reset", + "speed-bar", + "speed-preset", + "silence-row", + "silence-step", + "silence-apply", + "export-confirm", + ] { + assert!(element(id), "{id} is not on any card"); + } } /// What the Detach and Group items do to a real timeline: a music video's @@ -7306,17 +8523,71 @@ mod tests { .expect("nothing plays av2 any more"); assert_eq!(rows(&session), 1, "the row went with it"); assert_eq!(session.sources().len(), 1); - // The one file left cannot go: a project that names none is not one - // that reopens. + // The one file left is held to the same rule and no other: its own take + // is still on the lanes, so it stays... + let first = session.sources()[0].path.clone(); let refusal = session - .remove_source(&session.sources()[0].path.clone(), 0) - .expect_err("the last file stays") + .remove_source(&first, 0) + .expect_err("its take is still on the timeline") .to_string(); - assert!(refusal.contains("only file"), "{refusal}"); + assert!(refusal.contains("still plays"), "{refusal}"); + // ...and once nothing plays it, the *last* row goes too. What is left + // is the empty library `Player::close_session` turns back into the + // window the editor launches as -- the user-reported bug was that this + // very removal was refused, leaving a row that could never be taken + // out. + assert!(session.delete_clip(Lane::V1, 0)); + session + .remove_source(&first, 0) + .expect("the only row goes like any other"); + assert_eq!(rows(&session), 0, "an empty library"); + assert!(session.sources().is_empty()); + // And it is still a session: silent, empty, and asked for its length + // rather than panicking on a source list that is not there. + assert_eq!(session.timeline_duration(), 0.0); + assert!( + session.save_project(&asset("nothing.edith")).is_err(), + "a project naming no file could never be opened again, so it is not written" + ); // A row this timeline never had is refused, not panicked on. assert!(session.remove_source(&second, 0).is_err()); } + /// The clipboard after a library removal. A copied clip names its file by + /// index and a removal renumbers the list, so this is the difference + /// between pasting the take that was copied and pasting **another file** + /// over the same range ([`clipboard_after_remove`], called by + /// [`Player::remove_source`]). + #[test] + fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() { + let clip = |source: usize| Clip { + start: 0, + in_frame: 0, + out_frame: 30, + source, + link: None, + eq: None, + color: None, + fit: Default::default(), + speed: Default::default(), + }; + // Copied from source 2, source 0 removed: the same file is source 1 now. + assert_eq!( + clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source), + Some(1), + "the clipboard follows its file down the list" + ); + // Copied from a source *before* the one that went: untouched. + assert_eq!( + clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source), + Some(0) + ); + // Copied from the row that was just removed: there is nothing left to + // paste, and pasting the next file along would be a lie. + assert!(clipboard_after_remove(Some(clip(1)), 1).is_none()); + assert!(clipboard_after_remove(None, 0).is_none()); + } + /// The trim-a-clip path through the doors the edge drag uses: /// [`Player::trim_to`] clamps the pointer with `trim_room` and /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less @@ -7743,6 +9014,161 @@ mod tests { } } + /// The mapping the whole panel is drawn and clicked through: a moment goes + /// to a fraction of the bed and comes back the same moment, at every zoom. + /// The fit is the invariant that matters most -- it must be the arithmetic + /// the panel did before there was a zoom at all. + #[test] + fn a_moment_and_the_place_it_is_drawn_are_the_same_at_every_zoom() { + let duration = 20.; + // The fit: what `start_frac`/`width_frac` used to answer, exactly. + let fit = View::default(); + for t in [0., 5., 12.5, 20.] { + assert_eq!(fit.frac_at(t, duration), (t / duration) as f32, "fit at {t}"); + } + assert_eq!(fit.width_frac(5., duration), width_frac(5., duration)); + for view in [ + fit, + View { + zoom: 2., + start: 4., + }, + View { + zoom: 8., + start: 12.5, + }, + View { + zoom: 37.5, + start: 19., + }, + ] { + let view = view.settled(duration, 30.); + for frac in [0., 0.25, 0.5, 1.] { + let at = view.time_at(frac, duration); + assert!( + (f64::from(view.frac_at(at, duration)) - f64::from(frac)).abs() < 1e-6, + "{view:?} round trip at {frac}" + ); + } + // A stretch is as wide as the share of the visible slice it takes. + assert!( + (f64::from(view.width_frac(view.span(duration), duration)) - 1.).abs() < 1e-6, + "{view:?} spans the bed" + ); + } + } + + /// The rule that makes a zoom usable: whatever was under the anchor is + /// still under it afterwards -- the playhead for a key, the pointer for a + /// ctrl+wheel. + #[test] + fn a_zoom_leaves_the_anchor_where_it_was_on_screen() { + let (duration, fps) = (20., 30.); + let mut view = View::default(); + for anchor in [0.5f32, 0.25, 0.9] { + // Well past the zoom-in stop: the anchor holds at the clamp too, + // which is where it used to slide (the clamp came after the offset). + for _ in 0..30 { + let at = view.time_at(anchor, duration); + let zoomed = view.zoomed(ZOOM_STEP, anchor, duration, fps); + // Only where the anchor is not pinned by an edge of the + // timeline: a view already against an end cannot slide further. + let pinned = zoomed.start <= 0. || zoomed.start + zoomed.span(duration) >= duration; + if !pinned { + assert!( + (f64::from(zoomed.frac_at(at, duration)) - f64::from(anchor)).abs() < 1e-6, + "{at} moved: {view:?} -> {zoomed:?}" + ); + } + assert!(zoomed.zoom >= view.zoom, "and it did zoom in"); + view = zoomed; + } + } + } + + /// Both stops: out is the whole timeline (which is where the panel starts, + /// so nothing regressed for anyone who never zooms), in is a handful of + /// frames -- and neither can scroll off an end. + #[test] + fn zoom_stops_at_the_whole_timeline_and_at_a_handful_of_frames() { + let (duration, fps) = (20., 30.); + let mut view = View::default(); + for _ in 0..200 { + view = view.zoomed(1. / ZOOM_STEP, 0.5, duration, fps); + } + assert_eq!(view, View::default(), "zoomed out is the fit"); + for _ in 0..200 { + view = view.zoomed(ZOOM_STEP, 0.5, duration, fps); + } + assert_eq!( + (view.span(duration) * fps).round(), + ZOOM_MIN_FRAMES, + "tightest is a handful of frames" + ); + // Against the far end, the slice still ends at the last frame. + let end = View { + zoom: view.zoom, + start: 1e6, + } + .settled(duration, fps); + assert!((end.start + end.span(duration) - duration).abs() < 1e-9); + assert!( + View { + zoom: view.zoom, + start: -5. + } + .settled(duration, fps) + .start + == 0. + ); + // A timeline too short to zoom into, and one with no length at all, + // both stay at the fit rather than dividing by nothing. + assert_eq!(View::max_zoom(0.1, fps), 1.); + assert_eq!(View::default().settled(0., fps), View::default()); + assert_eq!(View::default().frac_at(3., 0.), 0.); + assert_eq!(View::default().time_at(0.5, 0.), 0.); + } + + /// What makes a zoomed timeline follow the playing head: off the bed at + /// either end pulls the view onto it, and on the bed it never moves -- a + /// view that jumped every frame would be unreadable. + #[test] + fn the_view_follows_a_playhead_that_runs_off_the_bed() { + let (duration, fps) = (20., 30.); + let view = View { + zoom: 4., + start: 5., + } + .settled(duration, fps); + assert_eq!(view.span(duration), 5.); + // Inside: untouched, whichever part of the slice it is in. + for at in [5., 7.5, 10.] { + assert_eq!(view.following(at, duration, fps), view, "{at} is on the bed"); + } + // Past the right edge, as playback does it: the head comes back on the + // bed, and the zoom is not changed by the scroll. + let moved = view.following(12., duration, fps); + assert_eq!(moved.zoom, view.zoom); + assert!(moved.start > view.start, "scrolled forward"); + assert!( + moved.frac_at(12., duration) > 0. && moved.frac_at(12., duration) < 1., + "and the playhead is on screen" + ); + // A seek back behind the slice does the same the other way. + let back = view.following(1., duration, fps); + assert!(back.start < view.start); + assert!(back.frac_at(1., duration) >= 0.); + // At the fit there is nothing to follow: the whole timeline is on the + // bed already, so no playhead can move it. + for at in [0., 10., 20.] { + assert_eq!( + View::default().following(at, duration, fps), + View::default(), + "the fit never scrolls" + ); + } + } + #[test] fn clip_boxes_split_the_lane_by_duration() { // 1 s + 3 s of a 4 s timeline: a quarter and three quarters. @@ -7918,6 +9344,86 @@ mod tests { assert!(KEYS_ROW_H >= HIT_MIN); } + /// The analyser drawn behind the curve: a tone has to land on its own + /// frequency, or the backdrop is a decoration rather than a reading of what + /// is playing -- and someone shaping a band against it would be aiming at + /// the wrong octave. + #[test] + fn the_spectrum_puts_a_tone_under_its_own_frequency() { + use std::f32::consts::TAU; + let rate = 48_000u32; + let sine = |hz: f32, amp: f32| -> Vec { + (0..EQ_FFT) + .map(|i| amp * (TAU * hz * i as f32 / rate as f32).sin()) + .collect() + }; + + // Silence is the floor of the box everywhere, not a band of noise. + let quiet = eq_spectrum(&vec![0.; EQ_FFT], rate); + assert_eq!(quiet.len(), EQ_CURVE_STEPS + 1); + assert!(quiet.iter().all(|&l| l == 0.), "silence drew something"); + + // A tone peaks over its own frequency, and the columns two octaves + // either side of it are near the floor. "Over" to within a bin down low + // and a column up high, which is all a 1024-point transform on a log + // axis can promise: at 200 Hz a whole column is a fraction of a bin + // wide, so the peak sits on the bin the tone fell in. + let column = |freq: f32| (eq_x(freq) * EQ_CURVE_STEPS as f32).round() as usize; + let freq_at = |col: usize| { + let along = col as f32 / EQ_CURVE_STEPS as f32; + EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along) + }; + for hz in [200., 1000., 5000.] { + let levels = eq_spectrum(&sine(hz, 0.05), rate); + let (at, top) = + levels + .iter() + .enumerate() + .fold((0, 0f32), |best, (i, &l)| match l > best.1 { + true => (i, l), + false => best, + }); + let slack = 1.5 * rate as f32 / EQ_FFT as f32 + 0.04 * hz; + assert!( + (freq_at(at) - hz).abs() <= slack, + "{hz} Hz peaked at {:.0} Hz (column {at})", + freq_at(at) + ); + // -26 dBFS, which is where a 0.05 tone sits on the axis. + let want = + (20. * 0.05f32.log10() - EQ_SPECTRUM_DB.0) / (EQ_SPECTRUM_DB.1 - EQ_SPECTRUM_DB.0); + assert!( + (top - want).abs() < 0.05, + "a -26 dBFS tone drew {top} of the box, not {want}" + ); + // Two octaves off is far enough down the box that the hump reads as + // one hump: 0.4 of the axis is a little over 30 dB. + for off in [hz / 4., hz * 4.] { + let away = levels[column(off).min(EQ_CURVE_STEPS)]; + assert!( + top - away > 0.4, + "{hz} Hz drew {top} but still {away} at {off} Hz" + ); + } + } + + // Level reads as level: 40 dB quieter sits lower by the fraction of the + // axis those 40 dB are. + let loud = eq_spectrum(&sine(1000., 0.05), rate); + let soft = eq_spectrum(&sine(1000., 0.0005), rate); + let at = column(1000.); + let drop = loud[at] - soft[at]; + let (floor, ceiling) = EQ_SPECTRUM_DB; + assert!( + (drop - 40. / (ceiling - floor)).abs() < 0.05, + "40 dB quieter moved the analyser {drop} of the box" + ); + + // A tap the engine has not filled yet (right after a seek) draws + // nothing at all rather than a transform of half a window. + assert!(eq_spectrum(&[0.; 16], rate).is_empty()); + } + /// The speed bar is the same round trip -- pixels -> rate -> fill -- with /// one thing the colour sliders do not have to promise: **exactly 1.00x has /// to be reachable**, by a hand as well as by the reset. A grid that missed @@ -8226,11 +9732,56 @@ mod tests { ); } + /// The hold gate: a value runs, everything else still means one press one + /// action -- which is the whole invariant the blanket `is_held` filter used + /// to carry on its own. + #[test] + fn a_held_key_moves_a_value_and_nothing_else() { + use keymap::ActionId; + // A card's four arrows, whichever card it is. + for key in ["up", "down", "left", "right"] { + assert!(repeats(Repeat::Card, key, None), "{key} on a card"); + } + // The card's own one-shots: flatten every band, cut forty places, play + // them fast, close. None of them on a hold. + for key in ["r", "enter", "f", "1", "escape"] { + assert!(!repeats(Repeat::Card, key, None), "{key} on a card"); + } + // Outside a card the keymap answers, and only the volume pair is a + // value being moved. + assert!(repeats(Repeat::Keymap, "up", Some(ActionId::VolumeUp))); + assert!(repeats(Repeat::Keymap, "down", Some(ActionId::VolumeDown))); + // ...and the zoom pair, which runs the view the way they run the level. + assert!(repeats(Repeat::Keymap, "=", Some(ActionId::ZoomIn))); + assert!(!repeats(Repeat::Keymap, "0", Some(ActionId::ZoomFit))); + for action in ActionId::ALL { + let held = repeats(Repeat::Keymap, "k", Some(action)); + assert_eq!( + held, + matches!( + action, + ActionId::VolumeUp + | ActionId::VolumeDown + | ActionId::ZoomIn + | ActionId::ZoomOut + ), + "{action:?} on a hold" + ); + } + // An arrow with nothing bound to it moves nothing on the timeline. + assert!(!repeats(Repeat::Keymap, "left", None)); + // And a stroke being captured, an export, or the overlays: nothing at + // all, or the hold would bind a key and then fire what it just bound. + for key in ["up", "left", "escape", "5"] { + assert!(!repeats(Repeat::Nothing, key, Some(ActionId::VolumeUp))); + } + } + #[test] fn the_silence_card_fits_the_smallest_window_and_never_slows_a_silence_down() { // The same 640x360 floor, and this card starts below the header: a - // title and a hint over its five rows, the count line and the two - // buttons. + // title and a hint over its [`SILENCE_ROWS`] rows, the count line and + // the two buttons. let (title, hint, count) = (17., 17., 17.); let gaps = 6. * 5.; let padding = 24.; @@ -8247,8 +9798,11 @@ mod tests { <= 360., "card too tall" ); - // Its rows and buttons are clicked, so WCAG 2.5.8 binds them. + // Its rows, its steppers and its buttons are clicked, so WCAG 2.5.8 + // binds them: a stepper is `HIT_MIN` square inside a row of that height. assert!(KEYS_ROW_H >= HIT_MIN); + // ...and the pair of them fits beside the widest value the card prints. + assert!(2. * HIT_MIN + 4. < COLOR_W / 2., "steppers crowd the value"); // A "speed-up" is never a slow-down: the rate stops above real time at // one end and at what a clip can hold at the other, whatever the keys // ask for. A silence played *slower* would make the timeline longer, @@ -8434,10 +9988,9 @@ mod tests { assert!(show_label(400.)); assert!(!show_label(LABEL_MIN_W - 0.1)); // A timeline with no length must not put a box outside its lane. - assert_eq!(start_frac(3., 0.), 0.); - assert_eq!(start_frac(1., 4.), 0.25); - // Past the end clamps rather than running off the bed. - assert_eq!(start_frac(8., 4.), 1.); + let fit = View::default(); + assert_eq!(fit.frac_at(3., 0.), 0.); + assert_eq!(fit.frac_at(1., 4.), 0.25); } #[test] @@ -8561,6 +10114,116 @@ mod tests { assert_eq!(source_tint(9), source_tint(1)); assert_eq!(source_tint(usize::MAX), SOURCE_TINTS[usize::MAX % 4]); } + + /// The bug: an empty timeline is end-of-stream from its one black frame + /// onward, so the pump had `done` set before anything was ever pressed -- + /// and the transport's restart branch read that as "played out, start from + /// the top". It started a clock against a zero-length timeline, which was + /// `done` again by the next repaint, so every further press restarted it + /// too: the button read "Pause" and no press of it ever paused. + /// + /// What holds it now is one predicate, checked here against real sessions + /// on both sides -- the emptied one refuses, a timeline with clips on it + /// does not. + #[test] + fn an_empty_timeline_has_nothing_to_play() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + // Silent like the engine suite: this opens the real device. + session.set_gain(0.0); + // A timeline with clips on it plays, and always did: the guard must not + // touch that side. + assert!(!session.is_empty()); + assert!(!nothing_to_play(Some(&session))); + + // Every clip taken off, which is a state and not a failure. + while session.delete_clip(Lane::V1, 0) {} + while session.delete_clip(Lane::A1, 0) {} + assert!(session.is_empty(), "the timeline is empty"); + assert_eq!(session.timeline_duration(), 0.0); + + // What the pump does every render, and what set `done` before the fix: + // the black frame goes by and the session is at its end at once. + for _ in 0..40 { + while session.try_frame().is_some() {} + std::thread::sleep(Duration::from_millis(10)); + } + assert!(session.is_eos(), "an empty timeline is done before it starts"); + + // So the press is refused rather than sent down the restart branch -- + // and with no session at all it is the same refusal. + assert!(nothing_to_play(Some(&session))); + assert!(nothing_to_play(None)); + assert!(!session.is_playing(), "and nothing was started"); + } + + /// The slider writes the same numbers the keys do, and mute is not one of + /// them: dragging while muted picks the level unmuting comes back to. + #[test] + fn the_slider_lands_on_the_grid_the_keys_move_on() { + let mut volume = Volume::default(); + // Both ends exactly, and clamped past them. + volume.set_along(0.); + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Vol 0%"); + volume.set_along(1.5); + assert_eq!(volume.gain(), 1.0); + assert_eq!(volume.along(), 1.0); + + // Halfway is 50%, and a key press from there is 5% -- the same step + // count as before, on a finer grid. + volume.set_along(0.5); + assert_eq!(volume.label(), "Vol 50%"); + volume.step(true); + assert_eq!(volume.label(), "Vol 55%"); + volume.step(false); + assert_eq!(volume.gain(), 0.5); + + // A number no step lands on comes back as the nearest one, so the label + // and the fill are the same value the device was handed. + volume.set_along(0.333); + assert_eq!(volume.label(), "Vol 33%"); + assert_eq!(volume.along(), 0.33); + + // Muted, the drag moves the level and nothing comes out. + volume.muted = true; + volume.set_along(0.8); + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Muted 80%"); + volume.muted = false; + assert_eq!(volume.gain(), 0.8); + } + + /// The slider lands where it paints: the arithmetic `Player::drag_volume` + /// runs over the bar's own painted width, which is the one thing a test of + /// it can share without re-deriving it. + #[test] + fn the_volume_slider_lands_where_it_paints() { + let bar = Bounds { + origin: point(px(420.), px(508.)), + size: size(px(VOLUME_W), px(CONTROL_H)), + }; + let at = |x: f32| { + let mut volume = Volume::default(); + volume.set_along(frac_along(px(x), bar)); + volume + }; + assert_eq!(at(420.).gain(), 0.0, "the left end is silence"); + assert_eq!(at(420. + VOLUME_W).gain(), 1.0, "the right end is full"); + assert_eq!(at(-4000.).gain(), 0.0, "off the left clamps"); + assert_eq!(at(9999.).gain(), 1.0, "off the right clamps"); + // Every pixel along it: a level the keys could also reach, painted back + // where the hand pressed to within the half step the rounding costs. + for step in 0..=(VOLUME_W as u32) { + let along = step as f32 / VOLUME_W; + let volume = at(420. + along * VOLUME_W); + let painted = volume.along(); + let slack = 0.5 / f32::from(Volume::MAX_STEPS) + 1e-4; + assert!( + (painted - along).abs() <= slack, + "pressed at {along}, paints at {painted}" + ); + } + } } fn main() { @@ -8681,6 +10344,8 @@ fn main() { // Full and unmuted, which is what the session it was just // handed is already set to: nothing to push at startup. volume: Volume::default(), + volume_bar: Rc::default(), + volume_dragging: false, // Only ever used with a timeline; 30 keeps the empty // timecode reading in frames rather than in NaN. fps: meta.map_or(30., |meta| meta.frame_rate), @@ -8690,6 +10355,9 @@ fn main() { eos: false, done: false, ruler: Rc::default(), + // The whole timeline across the bed, which is where a + // project opens: zooming is something the user asks for. + view: View::default(), selected: None, context_menu: None, library_menu: None, @@ -8716,6 +10384,7 @@ fn main() { eq_band: 0, eq_dragging: false, eq_graph: Rc::default(), + eq_spectrum: true, speed_open: None, speed_bar: Rc::default(), speed_dragging: false, @@ -8728,6 +10397,9 @@ fn main() { // one a person can widen on purpose. silence_scope: Scope::Take, silence_field: 0, + // The reference named, which is what the card said before + // there was a choice about it. + silence_dbfs: true, silence_marks: Vec::new(), silence_levels: None, color_open: None, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 13dbbae..16efde8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -23,6 +23,18 @@ image = { version = "0.25", default-features = false, features = [ ] } mp4 = "0.14" rusty_h264 = { version = "0.8", default-features = false } +# Both halves of AAC, and the only crate here that is asked for both. The +# *encoder*, so an mp4's sound can be a mix rather than a copy: an equalized (or +# otherwise processed) lane has to be decoded, and what is decoded has to be +# encoded again. The *decoder*, because symphonia's own refuses anything wider +# than stereo outright (`aac/mod.rs:93`, "aac: aac too complex") and a 5.1 film +# soundtrack in an mkv is exactly that -- this one hands 5.1 back already +# reordered into FL, FR, FC, LFE, BL, BR, which is the order the downmix in +# `audio` folds. Pure Rust with no C or FFI, Apache-2.0, same family as +# `rusty_h264` above. Nothing else in the ecosystem encodes AAC without linking +# Fraunhofer's C library, which this project's no-install rule forbids. Built +# from `vendor/rusty_aac` -- see the patch table in the workspace manifest. +rusty_aac = "0.5" symphonia-core = "0.6" symphonia-codec-aac = "0.6" # The umbrella crate for the standalone audio files: one dependency instead of @@ -47,12 +59,6 @@ symphonia = { version = "0.6", default-features = false, features = [ "vorbis", "wav", ] } -# The AAC decoder symphonia is not: its own refuses anything wider than stereo -# outright (`aac/mod.rs:93`, "aac: aac too complex"), and a 5.1 film soundtrack -# in an mkv is exactly that. Pure Rust with no dependencies of its own, from the -# same family as `rusty_h264`, and it hands 5.1 back already reordered into -# FL, FR, FC, LFE, BL, BR -- which is the order the downmix here folds. -rusty_aac = "0.5" oxideav-ac3 = "=0.0.10" oxideav-core = "0.1.34" # The software AV1 encoder, and the only new name in this list that was already diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index cf5eb34..cc78fce 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -270,14 +270,23 @@ impl AudioSession { eqs: &[Option], speeds: &[Option], ) -> crate::Result)>> { - let Some((path, stream)) = sources.first() else { + // The first source that could have a track, which is not always index 0: + // a still image has none, and one at the front of the list (a save + // renumbers, a library removal moves indexes) would be opened as a + // broken audio file and take the whole timeline's sound down with it. + // The same rule `PlaybackSession` probes by (`audio_source_of`). + let Some((at, (path, stream))) = sources + .iter() + .enumerate() + .find(|(_, (path, _))| !crate::is_image(path)) + else { return Ok(None); }; let Some(first) = Track::open(path, *stream)? else { return Ok(None); }; - // The timeline's meta is the first source's: policy makes every other - // source match it, and the checks below hold them to that. + // The timeline's meta is that source's: policy makes every other source + // match it, and the checks below hold them to that. let meta = AudioMeta { sample_rate: first.sample_rate(), channels: first.channels()?, @@ -288,7 +297,7 @@ impl AudioSession { first.check_decoder()?; let mut tracks: Vec> = sources.iter().map(|_| None).collect(); - tracks[0] = Some(first); + tracks[at] = Some(first); for &(source, ..) in segs { let Some(source) = source else { continue; // a gap opens no file @@ -461,8 +470,9 @@ impl AudioSession { let mut meta = None; let mut rxs = Vec::with_capacity(lanes.len()); 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. + // Every lane takes its meta from the same source, so the metas + // agree by construction; `None` from any of them is a silent + // timeline. let flat = Vec::new(); let plain = Vec::new(); let Some((lane_meta, rx)) = Self::open_multi_streams_speed( @@ -661,9 +671,9 @@ impl AudioSession { /// The raw AAC packets covering `segs` — the same half-open source-second /// windows [`open_segments`](Self::open_segments) decodes — copied out /// byte for byte. Nothing is decoded and nothing is re-encoded: the bytes go - /// straight into an mp4 writer, which is the only way to keep audio in an - /// export at all (nothing here *encodes* AAC: the vendored `rusty_aac` has - /// an encoder, but no export path is wired to it). + /// straight into an mp4 writer, which is how an export keeps its sound exact + /// wherever the edit lets it (a lane carrying an equalizer cannot be copied + /// and is re-encoded instead -- `export::encode_audio`). /// /// Cut points do not land on 1024-sample boundaries, so each segment is /// rounded to whole packets against an error carried across the joins (see diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 7298211..eb8ee9b 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -2,20 +2,23 @@ //! or, picture left behind, as one WAV or FLAC of the timeline's audio alone. //! //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it -//! is impossible — while audio is copied packet for packet, because there is no -//! AAC encoder wired here to re-encode with. The audio-only formats have no such -//! trouble: `hound` writes PCM and `flacenc` encodes FLAC, both pure Rust, so -//! those are *decoded* out of the timeline instead of copied. The worker owns -//! everything: the caller gets an [`ExportHandle`] and polls it from its render -//! loop. +//! is impossible — while audio is copied packet for packet wherever a copy can +//! say what the timeline says: a copy is exact, free and never a generation of +//! loss. Where it *cannot* — an equalized lane, which is sample math no packet +//! copy can reach — that lane is decoded, mixed and encoded again with +//! `rusty_aac` ([`encode_audio`]). The audio-only formats have no such split: +//! `hound` writes PCM and `flacenc` encodes FLAC, so those are always *decoded* +//! out of the timeline. The worker owns everything: the caller gets an +//! [`ExportHandle`] and polls it from its render loop. //! //! A **speeded** clip splits along the same line, and for the same reason. The //! picture is re-encoded, so the frame walk honours a rate: it takes the source //! frame each timeline frame shows ([`crate::project::Speed::source_at`], the //! very frame preview holds there) and encodes a held one again rather than -//! decoding it twice. The sound is *copied*, and a packet carries no rate -- so -//! a speeded clip on the one audio lane an mp4 copies is refused by name -//! ([`copy_audio`]) rather than written out at 1.00x under a re-timed picture. +//! decoding it twice. The sound is *copied* unless a filter forces a decode, and +//! a packet carries no rate -- so a speeded clip on the one audio lane an mp4 +//! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x +//! under a re-timed picture. //! AV1 carries no audio at all and never meets that refusal; WAV and FLAC are //! decoded and resampled, so they honour a rate like the picture does. //! @@ -60,22 +63,27 @@ const AV1_SPEED: u8 = 10; /// What an export writes. Four, not more: H.264-in-mp4 and AV1-in-Matroska are /// the only *video* pairs with both an encoder and a decoder under this -/// project's no-install rule, and WAV and FLAC are the only audio formats with -/// a pure-Rust encoder at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is -/// a licensing decision this project has not taken; Vorbis, Opus and AAC have -/// none. HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import through -/// the plugin and stop there). A front-end says so rather than hiding the rows. +/// project's no-install rule, and WAV and FLAC are the only *standalone* audio +/// formats with a pure-Rust encoder at all. MP3 has one (`shine-rs`) under +/// LGPL-2.0, which is a licensing decision this project has not taken; Vorbis +/// and Opus have none. (AAC does -- `rusty_aac`, which is what an equalized mp4 +/// track is encoded with -- but AAC is an mp4's own audio, never a file of its +/// own here.) HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import +/// through the plugin and stop there). A front-end says so rather than hiding +/// the rows. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Format { - /// Picture and sound: video re-encoded, AAC copied. Copied, so it carries - /// **one** audio lane: a timeline whose sound is spread over two is refused - /// by name here and mixed by the other two formats, which decode. + /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too, + /// where a copy could not carry the edit (an equalized lane). Either way it + /// carries **one** audio lane: a timeline whose sound is spread over two is + /// refused by name here and mixed by the other two formats, which decode. #[default] Mp4, /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound - /// this project can *write*: there is no AAC or Opus encoder here, and the - /// copy path walks an mp4 sample table, which a Matroska file has none of. - /// (Reading one's AAC is a different question and the answer is yes -- + /// this project can *write*: this engine's Matroska writer has no audio + /// track at all, and the copy path walks an mp4 sample table, which a + /// Matroska file has none of. (*Reading* one's AAC is a different question, + /// and since this engine gained a Matroska demuxer the answer is yes -- /// `audio::Track::open` does it through symphonia's mkv reader.) The sound /// of an AV1 export is a WAV or FLAC beside it, which a front-end says up /// front. @@ -258,7 +266,9 @@ fn settle(shared: &Shared, result: crate::Result<()>) { } /// The timeline's one audio lane, copied packet for packet: the mp4 path's -/// sound, and the reason that path carries only one lane of it. +/// sound, and the reason that path carries only one lane of it. A lane an +/// equalizer has been put on cannot be *copied* at all and leaves through +/// [`encode_audio`] instead; every other timeline keeps this copy, bit for bit. /// /// ponytail: this holds the whole exported AAC track in memory (~3 kB per /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming @@ -279,10 +289,15 @@ fn copy_audio( // of a timeline playing a file's second audio track carries *that* track. // // One lane, because this path *copies* AAC packets and a mix is not a copy: - // summing two lanes means decoding both and encoding the result, and there - // is no AAC encoder here to encode it with. Refused by name rather than - // silently exporting the first lane -- a file missing half its sound is the - // one failure a user would not notice. + // summing two lanes means decoding both, and only the one thing a copy + // cannot express at all -- an equalizer -- is decoded here today. Refused by + // name rather than silently exporting the first lane, which is a file + // missing half its sound: the one failure a user would not notice. + // + // ponytail: the ceiling is this routing, not the codec any more. + // [`encode_audio`] already mixes *every* audio lane (it is the WAV path's + // own opener), so lifting this refusal is routing a second case to it -- + // deliberately not done here, where the change under test is the equalizer. // // *Which* lane is the same question `audio_segments_from` answers for // playback, and it is asked here rather than assumed: the lane that holds @@ -294,32 +309,29 @@ fn copy_audio( let [segments] = &lanes[..] else { return Err(format!( "this timeline has {} audio lanes and an mp4 export copies one: \ - there is no AAC encoder here to mix them with. Export WAV or FLAC, \ - which are mixed, or put the sound on one lane", + export WAV or FLAC, which are mixed, or put the sound on one lane", lanes.len() ) .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. + // ...and the same list names *which* lane those clips sit on, which is the + // only way to ask what has been done to them. let lane = project.audio_lanes()[0]; // ...and the same list decides whether any clip this would copy plays at a // rate other than the one it was recorded at. A copy hands the mp4 the very // AAC packets the source holds and there is no rate inside a packet to // change: the picture would come out re-timed (the walk in [`run`] honours // it) over sound at 1.00x, which is the drift a person finds only after the - // file has gone somewhere. Refused by name, exactly as the equalizer below - // is -- and only *here*, on the lane being copied: AV1 carries no audio at - // all and never reaches this, so it honours a speed like WAV and FLAC do. + // file has gone somewhere. Refused by name -- and only *here*, on the lane + // being copied: AV1 carries no audio at all and never reaches this, so it + // honours a speed like WAV and FLAC do. // - // ponytail: the ceiling is the packet copy itself, not the rate. Upgrade - // path is the same one the equalizer below wants -- an AAC encoder (or a - // decode-and-re-encode of this lane) -- at which point the resample the WAV - // path already runs feeds it and this refusal goes. + // ponytail: the ceiling is the packet copy itself, not the rate, and the way + // off it is now next door -- [`encode_audio`] resamples exactly as the WAV + // path does, so routing a speeded lane there is the one line the equalizer + // below takes. Left refused because this change is the equalizer's, and a + // speeded export turning silently from a copy into a re-encode is a change + // of its own to make on purpose. if let Some((at, speed)) = project .lane(lane) .iter() @@ -333,28 +345,106 @@ fn copy_audio( ) .into()); } - if let Some((at, _)) = project - .lane(lane) - .iter() - .enumerate() - .find(|(idx, _)| { - project - .eq_of(lane, *idx) - .is_some_and(|eq| !eq.is_identity()) - }) - .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()); + // ...and last, whether any clip on it carries an equalizer. An EQ is sample + // math and a copy never decodes, so copying such a lane would write the clip + // *flat*, silently -- the failure a missing audio track is. This lane is + // decoded, filtered, mixed and encoded again instead ([`encode_audio`]), and + // only this case is: a timeline nobody has equalized still leaves through + // the copy below, packet for packet, so no passthrough quietly becomes a + // generation of loss. + let equalized = (0..project.lane(lane).len()) + .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity())); + if equalized { + return encode_audio(project, meta); } AudioSession::copy_multi_streams(&project.audio_sources(), segments) } +/// The same lane, *decoded*: what a packet copy cannot carry comes out here as +/// AAC written by this project's own encoder. +/// +/// The samples are the very ones [`run_audio`] would put in a WAV -- the same +/// opener with the same equalizers, the same rates and the same resize onto the +/// timeline's own length -- so an mp4 and a WAV of one timeline are one mix, +/// not two that could disagree. +/// +/// AAC-LC's encoder delay is one 1024-frame block, which is exactly the priming +/// a reader drops when the file carries no edit list (`audio::DEFAULT_PRIMING`, +/// and [`crate::mux::Mp4Muxer`] writes none): the first packet is that delay, so +/// the sound starts at timeline frame 0 as a copied track's does. +/// +/// ponytail: the mix sits in memory as f32 before it is encoded (~46 MB a +/// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers +/// the whole stream anyway, since it encodes its frames in parallel. Upgrade +/// path is a chunked push once that encoder streams. +#[allow(clippy::type_complexity)] +fn encode_audio( + project: &Project, + meta: &VideoMeta, +) -> crate::Result)>> { + let sources = project.audio_sources(); + let segs = project.audio_segments_from(0, meta.frame_rate); + let eqs = project.audio_eqs_from(0, meta.frame_rate); + let speeds = project.audio_speeds_from(0, meta.frame_rate); + let Some((audio, chunks)) = + AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)? + else { + return Ok(None); // no audio to write, exactly as a copy of nothing is + }; + let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| { + format!( + "{} Hz is not an AAC sample rate: export WAV or FLAC, which write it as it is", + audio.sample_rate + ) + })?; + let channels = usize::from(audio.channels.max(1)); + // The timeline's length, not the mix's: a segment resolves its window to + // whole samples on its own, so the sum can miss by a sample or two and a + // source that ran out early would leave the track short under a picture + // that is not. One resize settles both, as [`run_audio`]'s does. + let total = (f64::from(project.timeline_frames()) / meta.frame_rate + * f64::from(audio.sample_rate)) + .round() as usize + * channels; + let mut samples: Vec = Vec::with_capacity(total); + for chunk in chunks { + samples.extend(chunk.samples); + } + samples.resize(total, 0.0); + + // 256 kbps, not the encoder's 128 default: this is a *second* generation of + // lossy coding over a source that was already AAC, and the export is a + // master a person edits from again, not a delivery file. Measured on the + // suite's fixtures, an untouched clip re-encoded here moves 0.15 dB at this + // rate against 0.46 dB at 128 -- and 32 KB/s beside a 2.76 Mbps picture is + // not a size anyone is counting. + let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig { + bitrate_bps: 256_000, + ..Default::default() + }); + encoder.push_pcm(&samples, audio.channels.max(1), audio.sample_rate)?; + encoder.finish(); + let mut packets = Vec::new(); + // `next_packet` after `finish` yields packets until `Eof` and nothing else, + // so the loop ends on the only error it can see. + while let Ok(packet) = encoder.next_packet() { + packets.push(crate::AacPacket { + bytes: packet.data, + samples: packet.duration, + }); + } + Ok(Some(( + crate::AacTrackParams { + freq_index, + // 1 and 2 are the ISO channel configurations for mono and stereo, + // and the opener refuses anything wider than stereo already. + chan_conf: audio.channels.max(1) as u8, + sample_rate: audio.sample_rate, + }, + packets, + ))) +} + fn run( project: &Project, meta: &VideoMeta, diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 19aa574..cc58c39 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -90,8 +90,18 @@ struct Audio { /// Bumped by every seek. A feeder only owns the device while this still /// matches the value it started with; see [`feed`]. epoch: Arc, + /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest + /// first: what a meter or an analyser draws. Written by the feeder, which + /// is not the device's own callback -- the plugin's RT thread never sees + /// this lock, and the feeder holds it for one memcpy per write. + tap: Arc>>, } +/// How much of the played signal the tap keeps. A power of two, because what +/// reads it transforms it, and long enough that the lowest band the editor +/// draws (20 Hz) has a whole cycle in the window at any rate we open. +const TAP_SAMPLES: usize = 2048; + impl Audio { /// Whether the device has played everything there will ever be, i.e. the /// audio clock is about to stop meaning anything. @@ -100,6 +110,21 @@ impl Audio { && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) } + /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to + /// mono. Called from the feeder only, once per accepted write. + fn note_tap(&self, accepted: &[f32]) { + let channels = self.channels.max(1) as usize; + let mut tap = self.tap.lock().unwrap(); + // Only the tail can survive anyway: a big write replaces the window + // outright rather than being summed into it and then thrown away. + let from = accepted.len().saturating_sub(TAP_SAMPLES * channels); + for frame in accepted[from..].chunks_exact(channels) { + tap.push(frame.iter().sum::() / channels as f32); + } + let over = tap.len().saturating_sub(TAP_SAMPLES); + tap.drain(..over); + } + /// Starts a feeder for the current epoch, draining `rx` into the device. /// `false` if the thread would not start, i.e. nothing will ever be fed. fn spawn_feeder(&self, rx: Receiver) -> bool { @@ -417,10 +442,12 @@ impl PlaybackSession { /// /// A *new* session rather than a reload of this one, so a load that fails /// leaves the caller's current session untouched -- atomic by - /// construction. Every named file is opened and checked here: source 0 - /// defines the timeline exactly as `open` does, every other source has to - /// match it the way [`import`](Self::import) demands, and every clip has to - /// still be inside the file it plays from. A source that vanished or + /// construction. Every named file is opened and checked here: the + /// *scaffolding* source -- the first that is not a still, since a picture + /// carries no rate -- defines the timeline exactly as `open` does, every + /// other source has to match it the way [`import`](Self::import) demands + /// (a save renumbers, so which index that is says nothing), and every clip + /// has to still be inside the file it plays from. A source that vanished or /// shrank since the save is a refusal naming it, not a silently shorter /// timeline -- the disappearing-file tolerance elsewhere in this type /// applies only *after* a project has loaded. @@ -428,15 +455,35 @@ impl PlaybackSession { /// The undo history is not saved: `undo` is `false` on a fresh load. pub fn open_project(path: &Path) -> crate::Result { let doc = crate::edith::load(path)?; + // *Which* source scaffolds it: the first that is not a still, and index + // 0 only when there is no other. A still defines no frame rate -- it is + // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps + // footage off a PNG that a save happened to renumber to index 0 + // (`Project::without_orphan_sources` numbers by first use, and a + // library removal moves indexes too) reads the timeline as 30 fps and + // then refuses every file on it for not matching. The rule this and + // [`audio_source_of`] share: nothing may assume what source 0 *is*. + // + // ponytail: a timeline of nothing but stills, or of stills and songs, + // still comes back at the rate its scaffold implies rather than the one + // it was cut at -- the rate is written nowhere in the file. The upgrade + // path is a dialect that writes it (`crate::edith`), which is also what + // a project naming no file at all would need. + let scaffold = doc + .sources + .iter() + .position(|s| !crate::is_image(&s.path)) + .unwrap_or(0); // Owned: the sources move into the `Project` below, and the device is // opened after that (see the comment there). let first = doc .sources - .first() + .get(scaffold) .cloned() .ok_or("the project names no sources")?; - // Source 0 both scaffolds the session and defines the timeline, so it - // is opened for playback rather than merely probed. + // The scaffolding source both defines the timeline and is what the + // playhead's first picture comes from, so it is opened for playback + // rather than merely probed. // One value, not two locals: everything below this line can refuse, and // locals drop in reverse declaration order -- a bare worker would join // its decode thread while the receiver next to it was still holding @@ -503,8 +550,15 @@ impl PlaybackSession { } let first_audio = first_audio_of(&doc.sources)?; - let mut counts = vec![meta.frame_count]; - for source in &doc.sources[1..] { + // In source order, with the scaffold's own count in its own slot: the + // clip check below indexes this list by source, so it must line up with + // `doc.sources` whichever entry the scaffolding came from. + let mut counts = Vec::with_capacity(doc.sources.len()); + for (i, source) in doc.sources.iter().enumerate() { + if i == scaffold { + counts.push(meta.frame_count); + continue; + } // A still has neither a rate to match nor a track to match with: // its length is the one it is held to, recomputed exactly as the // import that first noted it did ([`image_frames`]), which is what @@ -579,7 +633,15 @@ impl PlaybackSession { // only a session's `drop` retires it, so a refusal above this line would // leave a PipeWire stream and a thread behind for a project that never // opened. Nothing before it needs the device. - let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream); + // + // On the source the timeline's *sound* is defined by, which is the + // scaffold unless that one is a still ([`audio_source_of`]): opening a + // PNG as the device is a session with no audio at all, however many + // clips with sound are on its lanes. + let (audio, audio_disabled) = match audio_source_of(project.sources()) { + Some(source) => open_audio(&source.path, source.audio_stream), + None => (None, None), + }; let mut session = Self { meta, native, @@ -627,7 +689,16 @@ impl PlaybackSession { /// Writes the timeline to `path` as a `.edith`, atomically (see /// [`crate::edith`]). Sources no clip plays from are left out, and the /// playhead is saved with it so a reopened project resumes where it stood. + /// + /// Refused, writing nothing, for a session whose library is empty (every + /// row removed, [`Project::remove_source`]): a file naming no source has no + /// timeline in it and [`open_project`](Self::open_project) could only + /// refuse it, so the refusal belongs here, where nothing has been + /// overwritten yet. pub fn save_project(&self, path: &Path) -> crate::Result<()> { + if self.project.sources().is_empty() { + return Err("this project names no file: there is nothing to save".into()); + } let (sources, lanes, eq, color) = self.project.without_orphan_sources(); let playhead = secs_to_frame(self.now(), self.meta.frame_rate) .min(self.project.timeline_frames().saturating_sub(1)); @@ -876,6 +947,13 @@ impl PlaybackSession { self.project.add_lane(kind) } + /// Drops that empty lane again, in [`Project::remove_lane`]'s words when it + /// refuses. One undo step, and no reseek for the same reason the add needs + /// none: an empty lane was playing nothing. + pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> { + self.project.remove_lane(lane) + } + /// Splits every lane at `timeline_secs`, so the two sides become two /// groups. Metadata only: a split never changes the timeline->source /// mapping, so the running decoder stays correct and playback does not @@ -1186,7 +1264,7 @@ impl PlaybackSession { /// [`import`](Self::import) refuses a file with. One output device and one /// copied AAC track mean one set of audio parameters for the whole /// timeline, so a 22 kHz mono track cannot join a 44.1 kHz stereo one -- - /// there is no resampler here, and no AAC encoder to write the join with. + /// there is no resampler here to make one rate of two. /// A front-end greys such a row out; this is the backstop that keeps a /// stale one from making the whole timeline silent. /// @@ -1286,7 +1364,14 @@ impl PlaybackSession { /// Reseeks like an edit even though nothing playable changed: the clip /// indexes into the source list have just moved, and the running workers /// were opened against the old numbering. - pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<()> { + /// + /// The index that went, because everything past it moved down: a caller + /// holding a source index of its own (a clipboard) has to fix it up or drop + /// it, or it names a different file afterwards. The **last** row goes like + /// any other and leaves a session with an empty library -- silent, empty of + /// clips, and unsaveable ([`save_project`](Self::save_project)); a + /// front-end showing one is showing an empty window. + pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result { let wanted = Source::new(path, stream); let idx = self .project @@ -1305,11 +1390,12 @@ impl PlaybackSession { } let now = self.now(); self.seek(now); - Ok(()) + Ok(idx) } - /// What the timeline's audio *is*: source 0's chosen stream, probed. Every - /// other source is held to it. + /// What the timeline's audio *is*: the chosen stream of the first source + /// that could have any ([`audio_source_of`]), probed. Every other source is + /// held to it. fn first_audio(&self) -> crate::Result> { first_audio_of(self.project.sources()) } @@ -1493,6 +1579,21 @@ impl PlaybackSession { } } + /// A copy of the most recent mono samples the device was handed, and the + /// rate they play at: the signal *after* every clip's equalizer, speed and + /// the mix, which is what an analyser drawn behind an EQ curve has to show. + /// `None` with no audio output at all, and empty until the feeder has + /// written once (right after a seek, for instance). + /// + /// Never blocks anything that matters: the feeder holds this lock for one + /// memcpy and the device's own callback lives in the plugin, on the far + /// side of a ring buffer, where it cannot see this at all. + pub fn audio_tap(&self) -> Option<(Vec, u32)> { + let audio = self.audio.as_ref()?; + let tap = audio.tap.lock().unwrap().clone(); + Some((tap, audio.sample_rate)) + } + /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode /// workers are replaced rather than steered: a fresh channel cannot hold a /// stale frame, and it works just as well after EOF, where the old workers @@ -1515,6 +1616,9 @@ impl PlaybackSession { // carrying can no longer reach the ring after this point. audio.epoch.fetch_add(1, Ordering::Release); ao.flush(); + // The flushed samples are not being played any more, so nothing may + // still be drawn from them. + audio.tap.lock().unwrap().clear(); } // Cancel first, drop second: the old worker may be parked in `send` on @@ -1729,12 +1833,26 @@ fn matches_timeline( /// source 0 has always given. This function widens which source is asked, not /// what the answer means. fn first_audio_of(sources: &[Source]) -> crate::Result> { - match sources.iter().find(|s| !crate::is_image(&s.path)) { + match audio_source_of(sources) { Some(first) => AudioSession::probe(&first.path, first.audio_stream), None => Ok(None), } } +/// *Which* source that is: the first one that is not a still. The single answer +/// to "what does this timeline's sound come from", so that probing it +/// ([`first_audio_of`]) and opening the device on it +/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only +/// the scaffolding file until a save renumbers it or a library removal takes it +/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the +/// device is a timeline that plays silent although every clip on it has sound. +/// +/// `None` for a library of nothing but stills, and for one with no file at all: +/// both are silent timelines. +fn audio_source_of(sources: &[Source]) -> Option<&Source> { + sources.iter().find(|s| !crate::is_image(&s.path)) +} + fn audio_matches(source: &Source, first: &Option) -> crate::Result<()> { // Whole-probe equality: rate and layout, which the audio worker holds every // source to anyway. Both silent is a match. @@ -1832,6 +1950,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option