diff --git a/Cargo.lock b/Cargo.lock index 8c2ea8e..bc63ce6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1637,8 +1637,11 @@ dependencies = [ "mp4", "oxideav-ac3", "oxideav-core", + "oxideav-h265", "rav1e", + "rusty_aac", "rusty_h264", + "rusty_mp3", "symphonia", "symphonia-codec-aac", "symphonia-core", @@ -3948,6 +3951,13 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "oxideav-h265" +version = "0.0.9" +dependencies = [ + "oxideav-core", +] + [[package]] name = "parking" version = "2.2.1" @@ -4880,6 +4890,10 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty_aac" +version = "0.5.0" + [[package]] name = "rusty_h264" version = "0.8.0" @@ -4919,6 +4933,12 @@ dependencies = [ "rusty_h264-common", ] +[[package]] +name = "rusty_mp3" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a99f339ec9a2d84eec8fc2a42baa92426966b25238c498e79d57b4e49b14fbad" + [[package]] name = "rustybuzz" version = "0.14.1" @@ -5600,6 +5620,7 @@ dependencies = [ "symphonia-codec-vorbis", "symphonia-core", "symphonia-format-isomp4", + "symphonia-format-mkv", "symphonia-format-ogg", "symphonia-format-riff", "symphonia-metadata", @@ -5709,6 +5730,18 @@ dependencies = [ "symphonia-metadata", ] +[[package]] +name = "symphonia-format-mkv" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb17713e134f5ad316c2690fa3104590ccc85842cdbcf82c3cd1a845cb08aa74" +dependencies = [ + "lazy_static", + "log", + "symphonia-common", + "symphonia-core", +] + [[package]] name = "symphonia-format-ogg" version = "0.6.0" diff --git a/Cargo.toml b/Cargo.toml index 920d015..2fb73a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,17 +2,41 @@ resolver = "3" members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"] # Vendored third-party (see [patch.crates-io]); not ours to build or test. -exclude = ["vendor/cros-libva", "vendor/cros-codecs"] +exclude = [ + "vendor/cros-libva", + "vendor/cros-codecs", + "vendor/rusty_aac", + "vendor/oxideav-h265", +] [workspace.package] version = "0.1.0" edition = "2024" -# Two upstream crates vendored verbatim except for one clearly marked fix each, -# both blockers on this machine and both still unfixed upstream as of 0.0.6/0.0.13: +# Four upstream crates vendored verbatim except for one clearly marked fix each, +# all blockers on this machine and all still unfixed upstream as of +# 0.0.6/0.0.13/0.5.0/0.0.9: # cros-libva - fails to build against libva >= 1.23 headers -# cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses -# Drop `vendor/` entirely once released versions handle both. +# cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses; +# and creates every decode context as 8-bit 4:2:0, which no HEVC +# Main 10 stream can decode into (its own TODO, its own answer) +# rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per +# term (the fast path in the same file serves the encoder only), +# which is 4x slower than real time for 5.1 and therefore not +# playable at all; the patch caches the cosine matrix +# oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and +# refuses any dimension that is not a multiple of the 16-sample +# CTB, so 1920x1080 could not be written at all; the patch adds +# the §7.4.3.2.1 conformance window (`SpsCfg::conf_win`, one +# marked block in `encoder/intra.rs`) so the picture is coded +# padded to 1920x1088 and *displayed* at 1920x1080. Taken from +# git master rather than the registry -- crates.io 0.0.9 is the +# pre-encoder release -- at rev d35963a02c872d12e6878b4ed3cf17a +# 69bde5a6e, and it is a plain path dependency (no +# `[patch.crates-io]` line) because nothing else in the tree +# asks for it. +# Drop `vendor/` entirely once released versions handle all four. [patch.crates-io] cros-libva = { path = "vendor/cros-libva" } cros-codecs = { path = "vendor/cros-codecs" } +rusty_aac = { path = "vendor/rusty_aac" } diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index a617a54..35cc538 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -63,22 +63,28 @@ pub enum ActionId { Color, Fit, Resolution, + ZoomIn, + ZoomOut, + ZoomFit, Undo, AddVideoLane, AddAudioLane, + RemoveVideoLane, + RemoveAudioLane, ToggleMute, VolumeUp, VolumeDown, Equalizer, Speed, Silence, + Mix, CancelExport, } 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; 39] = [ ActionId::Play, ActionId::StepBack, ActionId::StepForward, @@ -102,15 +108,21 @@ 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, ActionId::Equalizer, ActionId::Speed, ActionId::Silence, + ActionId::Mix, ActionId::CancelExport, ]; @@ -140,15 +152,21 @@ 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", ActionId::Equalizer => "Equalizer", ActionId::Speed => "Speed (tape)…", ActionId::Silence => "Silences: cut or speed up…", + ActionId::Mix => "Mix: track volumes and the limiter…", ActionId::CancelExport => "Cancel export", } } @@ -180,15 +198,21 @@ 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", ActionId::Equalizer => "equalizer", ActionId::Speed => "speed", ActionId::Silence => "silence", + ActionId::Mix => "mix", ActionId::CancelExport => "cancel-export", } } @@ -228,18 +252,29 @@ 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 - | ActionId::Equalizer => Category::Audio, + | ActionId::Equalizer + // The mix is the project's sound -- what every track plays at and + // what the whole of it is held under -- where the three above it + // are this machine's monitoring. Both are audio, and the card says + // which is which. + | ActionId::Mix => Category::Audio, ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File, } } @@ -291,7 +326,15 @@ pub struct Fixed { pub category: Category, } -pub const FIXED: [Fixed; 14] = [ +pub const FIXED: [Fixed; 21] = [ + // 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", @@ -303,8 +346,38 @@ pub const FIXED: [Fixed; 14] = [ category: Category::File, }, Fixed { - chord: "m / a / w / f", - label: "Pick the export format: MP4, AV1, WAV or FLAC", + chord: "m / a / h / w / f / p", + label: "Pick the export codec: H.264, AV1, HEVC, WAV, FLAC or MP3", + category: Category::File, + }, + // The rest of the export card's own rows, each on the letter its row is + // named after. They shadow the clip keys of the same letter while the card + // is up, exactly as its digits shadow nothing and its arrows would: a modal + // card owns the keyboard, and cutting a clip under it is not a thing that + // can happen anyway. + Fixed { + chord: "c", + label: "Switch the export container: Matroska or MP4", + category: Category::File, + }, + Fixed { + chord: "q", + label: "Step through the export quality rows", + category: Category::File, + }, + Fixed { + chord: "d", + label: "Choose where the export is written", + category: Category::File, + }, + Fixed { + chord: "g", + label: "Export card: sections or one flat list", + category: Category::File, + }, + Fixed { + chord: "r", + label: "Export card: the formats with no encoder as rows or as one line", category: Category::File, }, Fixed { @@ -340,6 +413,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 +599,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 +614,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 @@ -547,6 +640,11 @@ impl Keymap { // delete (x and delete) -- what it opens is a card that can cut // forty places at once. b(ActionId::Silence, "u", false), + // The mix card takes "f", for the faders on it: "m" would be + // the word but it is the monitoring mute, which is this + // machine's volume and not the project's -- two things one key + // must not mean. + b(ActionId::Mix, "f", false), b(ActionId::CancelExport, "escape", false), ], } @@ -809,7 +907,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(), 41); 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 +941,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 +1083,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 +1141,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(), 39); + assert_eq!(k.display(ActionId::ZoomIn), "ctrl+="); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 30482e8..20be25f 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -11,17 +11,19 @@ use std::time::{Duration, Instant}; use engine::audio::StreamInfo; use engine::color::ColorParams; +use engine::decode::Backend; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{ExportSettings, Format}; +use engine::limiter::Limiter; use engine::project::{Edge, Lane, LaneKind, Source, Speed}; use engine::scale::FitPolicy; -use engine::{Clip, ExportHandle, Frame, PlaybackSession}; +use engine::{Clip, Codec, 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 +76,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 +102,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. @@ -107,16 +117,39 @@ const KEYS_ROW_H: f32 = HIT_MIN; /// keeps the card inside the smallest window no matter how many actions the /// editor grows -- ten rows fit here, and the eleventh is a scroll away. const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; -/// The same for the export card, which carries a fixed-format line and a button -/// under its list and so has less room: destination, nine formats and five -/// qualities are fifteen rows, eight of them on screen. +/// The same for the export card, which carries two summary lines and a button +/// under its list and so has less room: a section header, six codecs, the +/// container, five qualities and the destination are more rows than a 360 px +/// window holds. Eight on screen, which is the whole format section and its +/// header -- what a user picks first is never behind a scroll. const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; +/// The export card is wider than the keybindings one: its rows carry a key, a +/// name *and* what the choice means, and the two summary lines under them state +/// the whole file. At `KEYS_W` every one of those wrapped to two lines, which is +/// the card the user called unfriendly. Still inside the 640 px floor with the +/// scrim showing either side of it. +const EXPORT_W: f32 = 420.; +/// The column the key of a row is printed in, wide enough for `0–9`: every row +/// in the export card says what picks it, so the card is drivable by keyboard +/// without a legend to memorise. +const EXPORT_KEY_W: f32 = 26.; +/// Everything in the export card that is *not* the row list: the title, the +/// status line, the head and tail of the summary, the button, the gaps between +/// them and the padding around the lot. What the list may be is the window +/// minus this -- and never less than [`EXPORT_ROWS_H`], which is the number +/// that makes the card fit the 360 px floor. +const EXPORT_FIXED_H: f32 = 17. + 28. + 15. + 30. + CONTROL_H + 4. + 10. + 24.; /// The menu a right-click on a clip opens: wide enough for the longest label /// beside the stroke that does the same thing, with the click targets `HIT_MIN` /// binds like every other list here. 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 +161,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 +191,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 { @@ -209,8 +270,9 @@ struct AssetDrag(PathBuf, usize); /// A clip already on the timeline being dragged: the lane it is on and its index /// there, which is how every other edit names a clip. Unlike an [`AssetDrag`] -/// nothing is inserted -- the same clip changes lane and keeps its frames -- so -/// where along the bed it is let go says nothing here either. +/// nothing is inserted -- the same clip changes lane and keeps the frames it +/// plays -- but where along the bed it is let go is exactly where it lands, less +/// the offset the hand grabbed it at ([`Player::grab`]). #[derive(Clone, Copy)] struct ClipDrag { lane: Lane, @@ -242,6 +304,12 @@ struct Trim { /// still the body. const EDGE_W: f32 = 6.; +/// How close to an edge a dragged clip has to be let go for it to land *on* it: +/// the snap every timeline has, in pixels rather than frames so that it feels +/// the same at every zoom. Narrower than [`EDGE_W`] -- a hand aiming between two +/// takes must still be able to leave a gap of a few frames there. +const SNAP_PX: f64 = 5.; + /// An open clip menu: which clip it was opened on, where it hangs, and whether /// it has been turned over to show what that clip *is* instead of what can be /// done to it. The lane and index are the ones the same click selected, so @@ -311,8 +379,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 +393,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 +435,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,11 +486,24 @@ 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.); +/// One press of a nudge key on the mix card, in dB: the step every fader and +/// the limiter's ceiling moves by. A whole decibel, the smallest move anyone +/// hears as a move -- and it lands on round numbers, so a track set by ear +/// still reads as a number a person would say. +const MIX_DB_STEP: f32 = 1.; + +/// The mix card's rows below the faders: the limiter's ceiling and its switch. +/// One fader per audio track comes first, however many there are. +const MIX_MASTER_ROWS: usize = 2; + /// The speed-up rate is bounded *below* by real time: a "speed-up" that slows /// the silence down would make the timeline longer, which is the one thing /// neither button may do. The top is [`Speed::MAX`]. @@ -451,6 +542,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 +636,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 @@ -549,6 +674,19 @@ struct Player { /// `None` is a file with no picture to report (every source that is not an /// image, and one whose header would not read). sizes: HashMap>, + /// Which decoder each source will run on, probed once at import and kept: + /// the codec (`None` for a still) and the seat the engine picked for it. + /// What a library row says *before* anything plays; the running answer is + /// the session's own (`PlaybackSession::decode_backend`), which follows a + /// fallback this cannot. Filled like `sizes`: presence means "asked", and + /// `None` is a source with no decoder to name -- a song, or one the probe + /// refused -- which must stay in the map or every repaint would ask again. + decoders: HashMap, Backend)>>, + /// Which encoder an export of the picked settings would open, and what it + /// was asked about: the probe opens a real VA-API encoder (~100 ms), so it + /// runs off the render thread and only while the export card is up. The + /// inner `None` is "asked, not answered yet". + export_seat: Option<(ExportSettings, (u32, u32), Option<&'static str>)>, /// The copied clip. Frame ranges only, so it survives the clip it was taken /// from being deleted -- and it outlives the selection. clipboard: Option, @@ -559,6 +697,13 @@ struct Player { /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See /// [`Trim`]. trim: Option, + /// How far into the clip the last press on a box landed, in timeline + /// frames: what a drag lets go of is the *point that was grabbed*, so the + /// head lands that much in front of the pointer and the clip does not jump + /// under the hand. Recorded at the press because gpui hands the drop only + /// the value being dragged, and stale between drags, which costs nothing -- + /// no drag starts without a press on the box it moves. + grab: u32, last_scrub: Instant, last_target: u32, /// The running export. While it owns the UI the editor is read-only. @@ -584,6 +729,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. @@ -593,6 +743,15 @@ struct Player { /// time -- opening either closes the other, since both are the whole window /// and two stacked scrims say nothing about which one is listening. export_open: bool, + /// How the card lays its rows out, and where the formats this program + /// cannot write are said. Two shapes of the same card, kept behind `g` and + /// `r` so the choice between them can be made by looking at both rather + /// than by argument: sections with headers against one flat list, and a + /// collapsed "cannot write" footer against a dimmed row each. The defaults + /// are grouped and collapsed -- the five dead rows used to eat the fold. + /// Not persisted: this is a look, not a setting. + export_grouped: bool, + export_refusals_inline: bool, /// Which quality row the card has picked, and the megabits typed against /// the custom one. Kept across closes, so a second export offers what the /// first one chose. @@ -622,6 +781,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. @@ -637,6 +801,14 @@ struct Player { /// The bar is being dragged. On the root like the colour card's, for the /// same reason: the pointer leaves a 4 px bar on the first move. speed_dragging: bool, + /// The mix card is up: every audio track's own volume and the master + /// limiter, which are project settings and not any clip's -- so unlike the + /// four clip cards there is no handle to hold, only whether it is open. + mix_open: bool, + /// Which of its rows the arrow keys move -- a fader, the limiter's ceiling + /// or its switch. The card's own focus, since nothing in it takes gpui's + /// (ledger:182). + mix_field: usize, /// The silence card is up on this clip -- the lane it is on and its index /// there, exactly as the speed card's handle is. silence_open: Option<(Lane, usize)>, @@ -652,6 +824,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,15 +999,27 @@ 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), ActionId::Equalizer => self.open_eq(cx), ActionId::Speed => self.open_speed(cx), ActionId::Silence => self.open_silence(cx), + ActionId::Mix => self.open_mix(None, cx), // Nothing to cancel while nothing is exporting; the export guard in // the key handler is what answers this one while there is. ActionId::CancelExport => {} @@ -937,6 +1129,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). @@ -1216,6 +1428,82 @@ impl Player { cx.notify(); } + /// Opens the mix card. `lane` is the row it lands on -- the track whose + /// header was clicked -- and `None` starts at the top, which is what the + /// stroke means. + /// + /// Nothing here is a clip's, so nothing is refused for want of a selection: + /// a timeline with no audio track at all still has a limiter to set, and a + /// fader on an empty track is the level the next take lands at. + fn open_mix(&mut self, lane: Option, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + self.mix_open = true; + self.mix_field = lane + .and_then(|lane| self.mix_lanes().iter().position(|&l| l == lane)) + .unwrap_or(0); + // One card at a time, the rule the other five follow. + self.keys_open = false; + self.export_open = false; + self.eq_open = None; + self.color_open = None; + self.speed_open = None; + self.close_silence(); + self.context_menu = None; + cx.notify(); + } + + /// The audio tracks the card shows a fader for, top to bottom: *every* one + /// of them, empty ones included -- what the timeline lays out, not what the + /// mixer happens to open (`Project::audio_lanes` leaves an empty track out, + /// and a fader that disappeared when a track was cleared would be a setting + /// nobody could reach). + fn mix_lanes(&self) -> Vec { + self.session.as_ref().map_or_else(Vec::new, |session| { + session + .lanes() + .into_iter() + .filter(|l| l.kind == LaneKind::Audio) + .collect() + }) + } + + /// Moves the row the card has picked: a fader by [`MIX_DB_STEP`], the + /// ceiling by the same, and the switch either way (a ring of two, like the + /// silence card's unit row). + /// + /// Every one of them goes through the session, so it reseeks: what the ear + /// hears while the arrow is held is the mix that is being set. + fn nudge_mix(&mut self, steps: i32, cx: &mut Context) { + let lanes = self.mix_lanes(); + let Some(session) = self.session.as_mut() else { + return; + }; + match lanes.get(self.mix_field) { + Some(&lane) => { + let at = session.lane_gain_db(lane) + steps as f32 * MIX_DB_STEP; + session.set_lane_gain_db(lane, at); + } + None => { + let limiter = session.limiter(); + let at = match self.mix_field - lanes.len() { + 0 => Limiter { + on: limiter.on, + ..limiter + } + .with_ceiling(limiter.ceiling_db + steps as f32 * MIX_DB_STEP), + _ => Limiter { + on: !limiter.on, + ..limiter + }, + }; + session.set_limiter(at); + } + } + cx.notify(); + } + /// Closes it and drops the preview with it: marks left on the lane after /// the card is gone would name frames the next edit has already moved. fn close_silence(&mut self) { @@ -1314,9 +1602,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 +1699,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 +1738,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!( @@ -1466,7 +1766,32 @@ impl Player { || self.color_open.is_some() || self.speed_open.is_some() || self.silence_open.is_some() + || self.mix_open + || 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() + || self.mix_open + { + Repeat::Card + } else { + Repeat::Keymap + } } /// Opens the equalizer on the selected clip. Audio only, and it says so @@ -1825,6 +2150,28 @@ impl Player { }) .detach(); } + // Which decoder each file will run on, for the row that says so before + // a frame of it plays. Off the render thread like the streams above: a + // stream the plugin takes costs one VA-API init (~90 ms) to answer. + for path in unseen_paths(session.sources(), &self.decoders) { + self.decoders.insert(path.clone(), None); + let probed = cx.background_executor().spawn({ + let path = path.clone(); + // A song and a source no decoder here takes are both `None`: + // the row says nothing about them rather than guessing, and + // import refused the second at the door anyway. + async move { engine::decode::probe(&path).ok() } + }); + cx.spawn(async move |this, cx| { + let probed = probed.await; + this.update(cx, |this, cx| { + this.decoders.insert(path, probed); + cx.notify(); + }) + .ok(); + }) + .detach(); + } for key in unseen_sources(session.sources(), &self.waves) { self.waves.insert(key.clone(), Wave::Loading); let decoded = cx.background_executor().spawn({ @@ -1857,6 +2204,59 @@ impl Player { } } + /// Probes the encoder an export would open, once per (settings, + /// resolution) and only while the export card is up -- it opens the very + /// VA-API encoder the export would, which is what makes the card's line a + /// measurement instead of a promise, and also what makes it too slow for + /// the render thread. Written before the spawn, like the probes above, so + /// the repaints during it start no second one. + fn cache_export_seat(&mut self, cx: &mut Context) { + let Some(session) = &self.session else { + return; + }; + let settings = export_settings(self.quality, self.custom_mbps, self.format); + if !self.export_open { + return; + } + // A format with no picture has no seat to probe -- and the *last* + // format's is not its answer: cleared rather than left standing, or + // picking MP3 after AV1 would read "SW encode (rav1e) · MP3 · SW + // (rusty_mp3)", which names an encoder that will not run. + if !settings.format.has_video() { + self.export_seat = None; + return; + } + let meta = *session.meta(); + let key = (settings, (meta.width, meta.height)); + if self + .export_seat + .is_some_and(|(asked, size, _)| (asked, size) == key) + { + return; + } + self.export_seat = Some((key.0, key.1, None)); + let probed = cx + .background_executor() + .spawn(async move { engine::export::planned_video(&meta, &settings) }); + cx.spawn(async move |this, cx| { + let probed = probed.await; + this.update(cx, |this, cx| { + // Only if the card is still asking the same question: a format + // changed while the plugin opened has a probe of its own. + if let Some(seat) = this + .export_seat + .as_mut() + .filter(|(asked, size, _)| (*asked, *size) == key) + { + seat.2 = probed; + } + cx.notify(); + }) + .ok(); + }) + .detach(); + } + /// The group id of the clicked clip, which is what marks the other half. fn selected_link(&self) -> Option { let (lane, idx) = self.selected?; @@ -1878,19 +2278,29 @@ impl Player { cx.notify(); } - /// A clip dragged off one lane and let go over another: it changes track and - /// keeps the frames it covers, as one undo step. Dropped back on its own - /// lane it is not an edit at all, so nothing is said about it. The engine - /// reseeks, so all this owes is the flag reset -- and the selection, whose - /// index was that lane's own and now names a different clip there. - fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, cx: &mut Context) { - if self.exporting().is_some() || from == to { + /// A clip let go at window `x` over lane `to`: it lands with its head where + /// the hand is carrying it ([`Player::drop_frame`]), on the track it was + /// dropped on, taking its whole take with it -- one undo step for the + /// gesture. Dropped back where it was picked up it is not an edit at all, so + /// nothing is said about it. The engine reseeks, so all this owes is the + /// flag reset -- and the selection, whose index was that lane's own and now + /// names a different clip there. + fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, x: Pixels, cx: &mut Context) { + if self.exporting().is_some() { return; } + let (Some(start), Some(was)) = ( + self.drop_frame(from, idx, to, x), + self.session + .as_ref() + .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)), + ) else { + return; + }; let moved = self .session .as_mut() - .is_some_and(|session| session.move_clip_to_lane(from, idx, to)); + .is_some_and(|session| session.move_clip_to(from, idx, to, start)); let (kind, lanes) = match from.kind { LaneKind::Video => ("picture", "video"), LaneKind::Audio => ("sound", "audio"), @@ -1900,9 +2310,10 @@ impl Player { self.selected = None; self.reset_after_reseek(); } - // The two ways a drag is refused, told apart by the one thing the - // front-end already knows: a lane's kind. Everything else that - // could refuse (a clip that is not there) cannot be dragged. + // The three ways a drag is refused, told apart by what the + // front-end already knows: a lane's kind, and where the clip was. + // Everything else that could refuse (a clip that is not there) + // cannot be dragged. false if from.kind != to.kind => { self.notice = Some( format!( @@ -1912,6 +2323,9 @@ impl Player { .into(), ) } + // Picked up and put back down where it was: a click, and a click + // says nothing. + false if from == to && start == was => {} false => { self.notice = Some( format!( @@ -1925,6 +2339,55 @@ impl Player { cx.notify(); } + /// Where a clip let go at window `x` over lane `to` wants its head: the + /// frame under the pointer, less however far into the box the hand grabbed + /// it (so the clip does not jump under the pointer), pulled onto a + /// neighbouring edge when it lands within [`SNAP_PX`] of one. `None` when + /// there is no such clip to move. The engine has the last word on where it + /// may actually go -- this is the ask, not the answer. + /// + /// ponytail: the bed ends where the timeline does, so a clip cannot be + /// dragged *past* the last frame -- the pointer has no pixel out there to + /// name and [`View::time_at`] clamps to the duration. Room to the right is + /// made by pulling a tail out first ([`Player::drawn_duration`] already + /// lengthens the bed for exactly that gesture). The upgrade is to draw the + /// bed past the end while a clip drag is in flight, the way a trim already + /// does: `drawn_duration` would take the dragged clip's length the same way + /// it takes a trim's reach. + fn drop_frame(&self, from: Lane, idx: usize, to: Lane, x: Pixels) -> Option { + let session = self.session.as_ref()?; + let clip = session.lane_clips(from).get(idx).copied()?; + let raw = self.frame_under(x).saturating_sub(self.grab); + // The edges worth landing on: both ends of every clip already on the + // lane it is being let go over, the playhead, and the head of the + // timeline. Never the group's own boxes -- a clip does not snap to + // where it already is. + let mut marks: Vec = session + .lane_clips(to) + .iter() + .enumerate() + .filter(|&(i, c)| { + (to, i) != (from, idx) && !(clip.link.is_some() && c.link == clip.link) + }) + .flat_map(|(_, c)| [c.start, c.end()]) + .collect(); + marks.push(frame_at(session.now(), self.fps)); + marks.push(0); + Some(snapped(raw, clip.frames(), self.snap_frames(), &marks)) + } + + /// [`SNAP_PX`] in timeline frames at the zoom the bed is drawn at: a snap is + /// a distance on screen, so zoomed right in it is worth less than a frame + /// (no snap at all, which is what a hand placing single frames wants) and + /// zoomed out to the whole timeline it is worth many. + fn snap_frames(&self) -> u32 { + let bed = f64::from(f32::from(self.ruler.get().size.width)); + if bed <= 0. { + return 0; + } + (SNAP_PX / bed * self.view.span(self.drawn_duration()) * self.fps) as u32 + } + /// Opens the clip menu on the box under the pointer, from the right button /// wherever it was pressed on that box -- its middle or one of its edge /// strips, which cover the middle's own listener. Selecting first is part of @@ -1979,18 +2442,30 @@ impl Player { /// against the same duration the boxes are drawn to, so the edge tracks the /// 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.frame_under(x); 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 = at.clamp(lo, hi); cx.notify(); } + /// The timeline frame a pointer at window x is on: along the same bed the + /// ruler is measured on, through the same [`View`] every box is drawn + /// through, so a zoomed-in panel answers with the frame under the pointer + /// and not with the one that would have been there unzoomed. The one + /// question a trim, a grab and a drop all ask. + fn frame_under(&self, x: Pixels) -> u32 { + let duration = self.drawn_duration(); + frame_at( + self.view.time_at(frac_along(x, self.ruler.get()), duration), + self.fps, + ) + } + /// The release: the whole drag reaches the engine as one edit, so it is one /// undo step. The selection survives it -- a trim inserts and removes /// nothing, so every index a lane had still names the clip it named. @@ -2018,6 +2493,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,18 +2548,35 @@ 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 - /// grouped take -- the same insert a paste makes, so everything after it - /// moves along rather than being painted over. Reseeks like every other - /// edit, and drops the timeline's selection with it: the insert has just - /// moved the indices it pointed at. + /// "add this source" does. The whole source goes in as one grouped take at + /// `at` -- the frame the pointer let it go on, or the playhead for the + /// button, which names no place. It is the same insert a paste makes, so + /// everything after it moves along rather than being painted over. Reseeks + /// like every other edit, and drops the timeline's selection with it: the + /// insert has just moved the indices it pointed at. fn insert_source( &mut self, path: &Path, stream: usize, onto: Option, + at: Option, cx: &mut Context, ) { if self.exporting().is_some() { @@ -2100,8 +2611,16 @@ impl Player { // in: a row that has never been on a lane is placeable at its full // length, which is the whole point of an import that only fills the // library. + let fps = self.fps; let placed = match &mut self.session { - Some(session) => session.place_stream_at(session.now(), path, stream, onto), + // Seconds, because that is what the engine's own door takes: the + // frame the pointer named goes back through the same rate every box + // on the bed is drawn at, so it lands on the frame it was let go on + // rather than a neighbouring one. + Some(session) => { + let at = at.map_or_else(|| session.now(), |frame| f64::from(frame) / fps); + session.place_stream_at(at, path, stream, onto) + } None => Ok(false), }; match placed { @@ -2133,20 +2652,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 +2697,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. @@ -2170,7 +2770,7 @@ impl Player { } RowItem::Add => { self.library_menu = None; - self.insert_source(&menu.path, menu.stream, None, cx); + self.insert_source(&menu.path, menu.stream, None, None, cx); } RowItem::Remove => { self.library_menu = None; @@ -2188,11 +2788,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 +3008,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 +3121,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 +3154,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 { @@ -2545,6 +3239,38 @@ impl Player { self.export_path = retarget(&self.export_path, format); } + /// The container row: the same codec in the other box, which retargets the + /// destination exactly as picking a codec does -- and does nothing at all + /// for a codec with only one box, so the stroke cannot invent a choice the + /// card is not offering. + fn cycle_container(&mut self) { + self.set_format(next_container(self.format)); + } + + /// The quality rows by keyboard, wrapping. Refused by name where the format + /// has no bitrate to pick: a key that silently does nothing is the card + /// looking broken. + fn cycle_quality(&mut self) { + if let Some(why) = bitrate_refusal(self.format) { + self.notice = Some(why.into()); + return; + } + let at = Quality::ALL + .iter() + .position(|&q| q == self.quality) + .unwrap_or(0); + self.quality = Quality::ALL[(at + 1) % Quality::ALL.len()]; + } + + /// The custom bitrate by pointer: the typed digits were the only control in + /// this card a mouse could not reach. Clamped to the range the row states + /// (the engine's own 1..20 Mbps), and picking the row is part of the step -- + /// a stepper that moves a number nobody is using would move nothing. + fn nudge_mbps(&mut self, step: i32) { + self.custom_mbps = (self.custom_mbps as i32 + step).clamp(1, 20) as u32; + self.quality = Quality::Custom; + } + /// The card's Destination row: the desktop's save dialog, on a background /// thread like the import chooser -- the user may sit in it and the window /// behind must not freeze. No chooser at all leaves the default path, which @@ -2672,6 +3398,7 @@ impl Render for Player { // has been through a repaint by the time its clips are drawn, so this // is the one place that has to notice a new one. self.cache_media(cx); + self.cache_export_seat(cx); // What the compositor calls this window. Pushed only when it changes: // it is a protocol round trip and this runs at vsync. let title = window_title(&self.name); @@ -2699,24 +3426,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 +3458,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 +3466,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 +3475,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. @@ -2778,16 +3509,35 @@ impl Render for Player { // The card's own button, by keyboard: the one thing in // it that writes a file must not be pointer-only either. this.start_export(cx); - } else if let Some(format) = format_key(key) { - // The format rows by their initial, so the card can be + } else if let Some(format) = format_key(key, this.format) { + // The codec rows by their own letter, so the card can be // driven without a mouse -- the same card-local input // the typed bitrate is, and for the same reason: a // choice reachable only by pointer is not reachable by // everyone. Not a keymap binding: it means nothing // outside this card, exactly like the digits. this.set_format(format); + } else if key == "c" { + this.cycle_container(); + } else if key == "q" { + this.cycle_quality(); + } else if key == "d" { + // The save dialog, which was the one row here a + // keyboard could not open. + this.pick_destination(cx); + } else if key == "g" { + this.export_grouped = !this.export_grouped; + } else if key == "r" { + this.export_refusals_inline = !this.export_refusals_inline; } else if let Ok(digit) = key.parse::() { - this.custom_mbps = push_digit(this.custom_mbps, digit); + let next = push_digit(this.custom_mbps, digit); + // A refused third digit says so: it used to be dropped + // in silence, which left the card showing a number the + // user had already typed past. + if next == this.custom_mbps && this.custom_mbps > 0 { + this.notice = Some("1–20 Mbps — a third digit is refused".into()); + } + this.custom_mbps = next; this.quality = Quality::Custom; } else if key == "backspace" { this.custom_mbps /= 10; @@ -2816,6 +3566,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. @@ -2899,6 +3654,25 @@ impl Render for Player { cx.notify(); return; } + // The mix card, the same way again: ↑↓ pick a row -- a track's + // fader, the limiter's ceiling or its switch -- and ←→ move it, + // held or pressed. Card-local like the four above it. + if this.mix_open { + let rows = this.mix_lanes().len() + MIX_MASTER_ROWS; + if key == ESCAPE { + this.mix_open = false; + } else if key == "down" { + this.mix_field = (this.mix_field + 1) % rows; + } else if key == "up" { + this.mix_field = (this.mix_field + rows - 1) % rows; + } else if key == "right" { + this.nudge_mix(1, cx); + } else if key == "left" { + this.nudge_mix(-1, cx); + } + cx.notify(); + return; + } // A clip menu names an index, and every edit below moves // indices -- so a stroke closes it before it acts. Escape means // that and nothing else, which is the `esc` the keys menu @@ -2991,6 +3765,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 +3815,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); } @@ -3106,11 +3894,12 @@ impl Render for Player { // Last, so they are over everything -- they take no room in the // column, and only one of the two is ever up. .children(self.keys_overlay(cx)) - .children(self.export_card(cx)) + .children(self.export_card(window.viewport_size(), cx)) .children(self.eq_card(cx)) .children(self.color_card(cx)) .children(self.speed_card(cx)) .children(self.silence_card(cx)) + .children(self.mix_card(cx)) } } @@ -3139,11 +3928,17 @@ impl Player { // Its own length, not one derived from what is on the lanes: a row // imported and never placed is a row with a length, and it is the // length a drag would put down. - let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| { - self.session - .as_ref() - .map_or(0, |session| session.file_frames(path)) - }) + let rows: Vec<_> = library_rows( + sources, + &self.streams, + &self.decoders, + self.timeline_audio(), + |path| { + self.session + .as_ref() + .map_or(0, |session| session.file_frames(path)) + }, + ) .into_iter() .enumerate() .map(|(i, row)| { @@ -3174,12 +3969,18 @@ impl Player { None => String::new(), } ), + // The file's *own* frame rate, not the timeline's: a clip shot + // at another rate plays at the speed it was shot at, and the + // row that says where it came from has to say which rate that + // was. (None, Some(meta)) => format!( - "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead", + "{} — {}x{} @ {:.2} fps · drag it where you want it, or Add at playhead", row.path.display(), meta.width, meta.height, - meta.frame_rate + self.session + .as_ref() + .map_or(meta.frame_rate, |session| session.file_fps(&row.path)) ), (None, None) => row.path.display().to_string(), }; @@ -3357,7 +4158,7 @@ impl Player { "Add at playhead", match self.selected_asset { Some(_) => "inserts the picked file at the playhead".to_string(), - None => "click a file above first — or drag one onto a lane".to_string(), + None => "click a file above first — or drag one where you want it".to_string(), }, can_add( self.selected_asset.as_ref(), @@ -3368,12 +4169,36 @@ impl Player { if let Some((path, stream)) = this.selected_asset.clone() { // No lane: the button means "wherever this belongs", // which for a file with no picture is the audio lane. - this.insert_source(&path, stream, None, cx); + this.insert_source(&path, stream, None, None, cx); } }), )) } + /// What is decoding the picture right now, for the transport line: the + /// backend is the running worker's own (it is written where a hardware + /// session falls back to software, so this follows reality), and the codec + /// comes from the clip under the playhead. Empty when nothing is playing -- + /// the question is about what is happening, not about what would. + fn live_decode(&self, position: f64, playing: bool) -> String { + let Some(session) = self.session.as_ref().filter(|_| playing) else { + return String::new(); + }; + let backend = session.decode_backend(); + let codec = session + .video_clip_at(position) + .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| clip.source)) + .and_then(|source| session.sources().get(source)) + .and_then(|source| self.decoders.get(&source.path).copied().flatten()) + .and_then(|(codec, _)| codec); + match backend { + // Neither is a decode, and saying "SW" of them would be a lie. + Backend::Gap => "gap · nothing to decode".to_string(), + Backend::Still => "still · one decode, held".to_string(), + _ => format!("{} decode", decode_label(codec, backend)), + } + } + /// Transport, edit and file buttons, timecode, playhead, clips lane. fn panel( &self, @@ -3382,11 +4207,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 +4219,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. @@ -3411,8 +4240,16 @@ impl Player { let progress = export.progress(); ( format!( - "EXPORTING {}% — {} cancels", + "EXPORTING {}% · {} · {} — {} cancels", (progress * 100.) as u32, + // The row that was picked; the engine's line below names the + // seats alone, since the library is what identifies a codec. + format_label(self.format), + // What the worker actually opened, so a fallback to the + // software encoder shows here rather than being invisible. + export + .encoders() + .unwrap_or_else(|| "opening the encoder".to_string()), key(ActionId::CancelExport) ), progress, @@ -3422,12 +4259,19 @@ impl Player { // tooltips. Keys first: at a 640 px window the tail is what a // truncation eats, and the two hints at the end are also on the // ruler's and Import's tooltips. + // While it plays, what is decoding it goes first: it is the + // answer that changes as the playhead crosses a cut, and the tail + // of this line is what a narrow window truncates. ( - format!( - "{} copy · {} paste · {} undo · click the bar to seek · drop a file to import", - key(ActionId::Copy), - key(ActionId::Paste), - key(ActionId::Undo) + join_detail( + &self.live_decode(position, playing), + &format!( + "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \ + import", + key(ActionId::Copy), + key(ActionId::Paste), + key(ActionId::Undo) + ), ), filled, ) @@ -3443,18 +4287,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 +4342,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 +4401,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 +4587,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| { @@ -3885,16 +4877,33 @@ impl Player { ) } - /// What an export is going to be, before there is one: the destination, the - /// quality rows, and the two things that are not a choice at all. The same - /// scrim, width and row shape as the keybindings overlay -- two cards of - /// different builds over one window read as two different programs -- and - /// the same plain divs, so the root keeps the keyboard and a typed digit - /// reaches the custom row. - fn export_card(&self, cx: &mut Context) -> Option { + /// What an export is going to be, before there is one: the codec, the box + /// it goes into, the bitrate, where it lands -- and, above the button, the + /// two lines that state the file all of that adds up to. The same scrim and + /// row shape as the keybindings overlay (two cards of different builds over + /// one window read as two different programs) and the same plain divs, so + /// the root keeps the keyboard and a typed digit reaches the custom row. + /// + /// Every row carries the key that picks it, so the card is drivable end to + /// end without a pointer *and* without a legend to memorise -- and every + /// row is clickable, the bitrate's steppers included, so it is drivable end + /// to end without a keyboard as well. + /// + /// Two shapes of it, behind `g` and `r`: sections against one flat list, + /// and the codecs with no encoder collapsed into a footer against a dimmed + /// row each. Grouped and collapsed is what opens. + fn export_card( + &self, + viewport: Size, + cx: &mut Context, + ) -> Option { if !self.export_open { return None; } + // The cap is what keeps the card inside the smallest window; a taller + // one gets a taller list rather than a scroll past empty space, and the + // card is still only as tall as the rows it has. + let rows_h = (f32::from(viewport.height) - EXPORT_FIXED_H - 24.).max(EXPORT_ROWS_H); let row = |id: (&'static str, usize)| { div() .id(id) @@ -3911,70 +4920,261 @@ impl Player { // A row that cannot be picked is dimmed and takes no click, exactly as // an inapplicable item in the clip menu is: it still says its piece. let live = |d: Stateful
, enabled: bool| { - d.when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) - .when(enabled, |d| d.cursor_pointer().hover(|s| s.bg(rgb(HOVER)))) + d.when(!enabled, |d| { + d.cursor_not_allowed().text_color(rgb(INK_DIM)) + }) + .when(enabled, |d| d.cursor_pointer().hover(|s| s.bg(rgb(HOVER)))) }; - // The formats first: the quality rows below are *video* bitrate, so - // which file is being written decides whether they mean anything. - // An mp4 this timeline cannot be written as reads exactly like the - // formats there is no encoder for: dimmed, unclickable, and carrying its - // own reason instead of the detail line. - let formats: Vec<_> = FORMATS - .into_iter() - .enumerate() - .map(|(i, (format, label, detail))| { - // Per row, because the two picture formats are refused by - // different things: an audio-only timeline greys both, a second - // audio lane only the mp4. - let refused = format - .zip(self.session.as_ref()) - .and_then(|(f, s)| format_refusal(s, f)); - let blocked = refused.is_some(); - let detail: SharedString = match &refused { - Some(why) => why.clone().into(), - None => detail.into(), - }; - let picked = format == Some(self.format) && !blocked; - let format = format.filter(|_| !blocked); - live(row(("format", i)), format.is_some()) - .when(picked, |d| d.bg(rgb(SELECTED))) - .when_some(format, |d, format| { - d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.set_format(format); - cx.notify(); + // A row as this card writes them: the mark saying which one is picked, + // the key that picks it, its name, and what the choice means. The mark + // is a glyph and not only a colour -- a background alone is gone the + // moment a hover lands on the row, and invisible to anyone who cannot + // tell the two greys apart (WCAG 1.4.1). + let entry = |id: (&'static str, usize), + key: &str, + label: SharedString, + detail: SharedString, + picked: bool, + enabled: bool| { + // The small print of a picked row sits on the highlight, where the + // dim ink is only 3.3:1 -- the row it lands on lifts it (WCAG + // 1.4.3, and the fit test pins both numbers). + let ink = match picked { + true => INK, + false => INK_DIM, + }; + live(row(id), enabled) + .when(picked, |d| d.bg(rgb(SELECTED))) + .child( + div() + .flex() + .flex_none() + .items_center() + .gap(px(8.)) + .child(div().w(px(10.)).child(match picked { + true => "✓", + false => " ", })) - }) - .child(label) - .child( - div() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(detail), + .child( + div() + .w(px(EXPORT_KEY_W)) + .text_size(px(11.)) + .text_color(rgb(ink)) + .child(SharedString::from(key.to_string())), + ) + .child(label), + ) + // Wraps rather than runs off the row: a refusal is the longest + // thing in this column and the half of it past the edge is the + // half that says what to do instead. + .child( + div() + .min_w(px(0.)) + .flex_shrink() + .text_size(px(11.)) + .text_color(rgb(ink)) + .child(detail), + ) + }; + let header = |text: &'static str| { + div() + .flex_none() + .px(px(6.)) + .pt(px(4.)) + .text_size(px(10.)) + .text_color(rgb(INK_DIM)) + .child(text) + .into_any_element() + }; + let mut list: Vec = Vec::new(); + if self.export_grouped { + list.push(header("FORMAT")); + } + // The codecs first: which one is being written decides whether every + // row under it means anything. One a *this* timeline cannot be written + // as (an audio-only edit, for a picture codec) reads exactly like one + // there is no encoder for -- dimmed, unclickable, and carrying its own + // reason where its detail was, with nothing to click to find that out. + let mut refusals: Vec = Vec::new(); + for (i, (boxes, key, label, detail)) in FORMATS.into_iter().enumerate() { + let format = same_box(boxes, self.format); + let refused = format + .zip(self.session.as_ref()) + .and_then(|(f, s)| format_refusal(s, f)); + // A codec with no encoder here at all is the other kind of refusal, + // and the one the footer collects: it can never become pickable, so + // a row each is dead rows above the fold. + if format.is_none() { + refusals.push(format!("{label} — {detail}")); + if !self.export_refusals_inline { + continue; + } + } + let detail: SharedString = match &refused { + Some(why) => why.clone().into(), + None => detail.into(), + }; + let format = format.filter(|_| refused.is_none()); + let mut r = entry( + ("format", i), + key, + label.into(), + detail, + boxes.contains(&self.format), + format.is_some(), + ); + if let Some(format) = format { + r = r.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.set_format(format); + cx.notify(); + })); + } + list.push(r.into_any_element()); + } + if self.export_grouped { + list.push(header("DETAILS")); + } + // The container, and only where the picked codec has more than one box: + // a row offering a single choice reads as a choice. + let boxes = containers(self.format); + if boxes.len() > 1 { + let next = next_container(self.format); + list.push( + entry( + ("container", 0), + "c", + "Container".into(), + format!( + "{} — c for {}", + self.format.ext().to_uppercase(), + next.ext().to_uppercase() ) - }) - .collect(); - let video = self.format.has_video(); - let rows: Vec<_> = Quality::ALL - .into_iter() - .enumerate() - .map(|(i, quality)| { - live(row(("quality", i)), video) - .when(video && self.quality == quality, |d| d.bg(rgb(SELECTED))) - .when(video, |d| { - d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + .into(), + false, + true, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.cycle_container(); + cx.notify(); + })) + .into_any_element(), + ); + } + match bitrate_refusal(self.format) { + // One dimmed row carrying the reason, rather than five rows of a + // figure that will not be written: the quality rows are the + // *picture's* bitrate, and this file has no picture in it. + Some(why) => list.push( + entry( + ("quality", 0), + "q", + "Quality".into(), + why.into(), + false, + false, + ) + .into_any_element(), + ), + None => { + for (i, quality) in Quality::ALL.into_iter().enumerate() { + let mut r = entry( + ("quality", i), + match quality { + // The one row a key does not step to but types + // into, which is what its key column says. + Quality::Custom => "0–9", + _ => "q", + }, + quality.label().into(), + quality.detail(self.custom_mbps).into(), + self.quality == quality, + true, + ) + .on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { this.quality = quality; cx.notify(); - })) - }) - .child(quality.label()) - .child( - div() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(quality.detail(self.custom_mbps)), - ) - }) - .collect(); + }, + )); + if quality == Quality::Custom { + r = r.child(self.mbps_steppers(cx)); + } + list.push(r.into_any_element()); + } + } + } + let destination = entry( + ("destination", 0), + "d", + "Destination".into(), + file_name(&self.export_path).into(), + false, + true, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.pick_destination(cx))) + .into_any_element(); + match self.export_grouped { + true => list.push(destination), + // Flat: the same rows with no headers over them, and the + // destination back at the top where the card used to open with it. + false => list.insert(0, destination), + } + if !self.export_refusals_inline && !refusals.is_empty() { + // Last, and one line: the reason travels with the name (a footer + // that only listed them would be the "why not?" the rows exist to + // answer), but nothing here can ever be picked, so it sits under + // every row that can rather than above them. + list.push( + div() + .flex_none() + .px(px(6.)) + .py(px(2.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(format!("cannot write: {}", refusals.join(" · "))) + .into_any_element(), + ); + } + // What the rows add up to, which is the one thing that has to be right: + // codec, box, size, rate, sound, where it goes and about how big. Two + // lines, outside the scrolling list, so it is on screen whatever the + // list is scrolled to and whatever is picked. + let picture = self + .session + .as_ref() + .map(|s| (s.resolution(), s.meta().frame_rate)); + let audio = self + .session + .as_ref() + .map_or("", |s| s.planned_audio(self.format)); + let settings = export_settings(self.quality, self.custom_mbps, self.format); + let mb = estimated_mb( + settings.bitrate.filter(|_| self.format.has_video()), + self.session + .as_ref() + .map_or(0., PlaybackSession::timeline_duration), + ); + let head = summary_head(self.format, picture, audio); + let tail = summary_tail( + &self.export_path, + mb, + self.export_seat.and_then(|(.., seat)| seat), + self.format.has_video(), + ); + // The button says the refusal *before* it is pressed: the picked codec + // can go invalid one edit after it was picked (a cleared video lane), + // and a button that looks ready until it is pressed is the lie the + // dimmed rows above it are there to avoid. + let blocked = self + .session + .as_ref() + .and_then(|s| format_refusal(s, self.format)); + let action: SharedString = match &blocked { + Some(why) => { + format!("Cannot export — {}", why.split(" — ").next().unwrap_or(why)).into() + } + None => "Export".into(), + }; Some( div() .absolute() @@ -3988,7 +5188,7 @@ impl Player { }) .child( div() - .w(px(KEYS_W)) + .w(px(EXPORT_W)) .flex() .flex_col() .gap(px(2.)) @@ -3998,7 +5198,9 @@ impl Player { .child(div().flex_none().px(px(6.)).child("Export")) // The status line, where a refusal from the save dialog // lands: the notice bar it would otherwise take is under - // the scrim. + // the scrim. The keys are on the rows, so this says how + // the card as a whole is answered rather than listing + // them a second time. .child( div() .flex_none() @@ -4006,51 +5208,33 @@ impl Player { .text_size(px(11.)) .text_color(rgb(INK_DIM)) .child(self.notice.clone().unwrap_or_else(|| { - "pick a format (m/a/w/f), then Export — esc closes".into() + "the keys are on the rows · enter exports · esc closes · \ + g/r change the layout" + .into() })), ) // Capped and scrolling like the keybindings list: the - // destination, nine formats and five qualities are more - // rows than a 360 px window has room for, and it is the - // list that scrolls, never the card that grows. + // rows are more than a 360 px window has room for, and + // it is the list that scrolls, never the card that + // grows -- the summary and the button below stay put. .child( div() .id("export-rows") .flex() .flex_col() .gap(px(2.)) - .max_h(px(EXPORT_ROWS_H)) + .max_h(px(rows_h)) .overflow_y_scroll() - .child( - live(row(("destination", 0)), true) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.pick_destination(cx) - })) - .child("Destination") - .child( - div() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(file_name(&self.export_path)), - ), - ) - .children(formats) - .children(rows), + .children(list), ) - // What the picked row really writes. `moov` last is the - // muxer's own shape -- an mp4 is playable only once it - // is finished. The project's resolution is on the same - // line because it *is* what the file comes out at, - // whatever size the media on the timeline are: this is - // the one place the number is shown, and ctrl+r is what - // changes it. + .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(head)) .child( div() .flex_none() .px(px(6.)) .text_size(px(11.)) .text_color(rgb(INK_DIM)) - .child(export_line(self.format, self.session.as_ref())), + .child(tail), ) .child( div() @@ -4061,7 +5245,10 @@ impl Player { .items_center() .justify_center() .rounded(px(3.)) - .bg(rgb(SELECTED)) + .bg(rgb(match blocked.is_some() { + true => CHROME, + false => SELECTED, + })) .cursor_pointer() .hover(|s| s.bg(rgb(HOVER))) .on_click( @@ -4069,12 +5256,42 @@ impl Player { this.start_export(cx) }), ) - .child("Export"), + .child(action), ), ), ) } + /// The custom bitrate's two pointer buttons. The typed digits were the last + /// control in this card a mouse could not reach at all -- and a number that + /// can only be typed is a number a hand on the pointer has to leave the + /// card to change. `HIT_MIN` square, like every other target here. + fn mbps_steppers(&self, cx: &mut Context) -> impl IntoElement { + let step = |id: &'static str, label: &'static str, by: i32, cx: &mut Context| { + div() + .id(id) + .flex() + .w(px(HIT_MIN)) + .h(px(HIT_MIN)) + .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| { + this.nudge_mbps(by); + cx.notify(); + })) + .child(label) + }; + div() + .flex() + .gap(px(4.)) + .child(step("mbps-down", "−", -1, cx)) + .child(step("mbps-up", "+", 1, cx)) + } + /// The equalizer of one audio clip: its frequency response drawn as a /// curve, a handle per band sitting on it, and a row that flattens them /// all. The curve is the clip's actual filter (`EqParams::response_db` @@ -4096,6 +5313,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 +5370,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 +5442,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 +5479,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 +5488,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", + }), + ), ), ), ) @@ -4478,60 +5786,228 @@ impl Player { .text_size(px(11.)) .text_color(rgb(INK_DIM)) .child( - "drag the bar or ←→ moves it, r is 1.00x — the pitch moves with the rate; esc closes", + "drag the bar or ←→ moves it, r is 1.00x — the pitch moves with the rate; esc closes", + ), + ) + .child( + // 4 px to look at and a whole row to hit (WCAG + // 2.5.8), the split the colour sliders and the ruler + // both make. + div() + .id("speed-bar") + .relative() + .w_full() + .h(px(KEYS_ROW_H)) + .flex() + .items_center() + .cursor_pointer() + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + this.speed_dragging = true; + this.drag_speed(event.position.x, true, cx); + }), + ) + .child(bounds_probe(self.speed_bar.clone())) + .child( + div() + .w_full() + .h(px(4.)) + .rounded(px(2.)) + .bg(rgb(CHROME)) + .child( + div() + .h_full() + .w(relative(frac)) + .rounded(px(2.)) + .bg(rgb(ACCENT)), + ), + ), + ) + .child(div().flex().gap(px(4.)).children(presets)) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + // What the choice *is*, in the numbers the + // timeline is measured in: the source range + // never moves, the room it takes does. + .child(format!( + "{speed} — {} source frames over {} on the timeline ({})", + clip.len(), + clip.frames(), + timecode(f64::from(clip.frames()) / self.fps, self.fps) + )), + ), + ), + ) + } + + /// The mix card: one fader per audio track and the master limiter under + /// them -- the two settings that belong to the *sound of the whole + /// timeline* rather than to any clip on it. + /// + /// A track's fader moves everything on that track by the same amount, + /// every frequency of it: it is not the equalizer (one take, one band) and + /// it is not the volume in the panel, which is what this machine monitors + /// at and is written to no file. The limiter is over the sum of them all, + /// which is where a mix can pass full scale and where a clamp used to + /// square it off. + /// + /// The silence card's shape, down to the steppers: a row is a label, a + /// value and the two presses that move it, and the arrows pick a row and + /// move it too. The rows scroll rather than the card growing past the + /// window -- a timeline may hold more tracks than a 360 px window has room + /// for faders. + fn mix_card(&self, cx: &mut Context) -> Option { + if !self.mix_open { + return None; + } + let session = self.session.as_ref(); + let lanes = self.mix_lanes(); + let limiter = session.map_or_else(Limiter::default, PlaybackSession::limiter); + let mut rows: Vec<(String, String)> = lanes + .iter() + .map(|&lane| { + let db = session.map_or(0., |s| s.lane_gain_db(lane)); + (format!("{} plays at", lane.label()), format!("{db:+.0} dB")) + }) + .collect(); + // The ceiling in dBFS and the faders in dB, the silence card's rule: + // a ceiling is a level below full scale, a fader is a change. + rows.push(( + "Limiter ceiling".into(), + format!("{:+.0} dBFS", limiter.ceiling_db), + )); + rows.push(( + "Limiter".into(), + match limiter.on { + true => "on".into(), + false => "off".into(), + }, + )); + let rows: Vec<_> = rows + .into_iter() + .enumerate() + .map(|(n, (label, value))| { + div() + .id(("mix-row", n)) + .flex() + .flex_none() + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_between() + .px(px(6.)) + .rounded(px(3.)) + .bg(rgb(match n == self.mix_field { + true => SELECTED, + false => CHROME, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mix_field = n; + cx.notify(); + })) + .child(div().text_color(rgb(INK_DIM)).child(label)) + .child( + div() + .flex() + .items_center() + .gap(px(4.)) + .child(value) + .children([-1, 1].map(|steps: i32| { + div() + .id(("mix-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 silence + // card's rule: the row a press lands on + // is the row the arrows carry on from. + this.mix_field = n; + this.nudge_mix(steps, cx); + })) + .child(match steps > 0 { + true => "+", + false => "−", + }) + })), + ) + }) + .collect(); + Some( + div() + .absolute() + .inset_0() + .flex() + .justify_center() + .items_center() + .bg(rgba(0x101010cc)) + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .child( + div() + .w(px(COLOR_W)) + .max_h(px(360. - 24.)) + .flex() + .flex_col() + .gap(px(6.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(SURFACE)) + .child( + div() + .flex_none() + .px(px(6.)) + .child("Mix — track volumes and the master limiter"), + ) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child( + "− and + move a setting, or ↑↓ picks one and ←→ moves it (hold to run it) — a track fader moves everything on that track; esc closes", ), ) .child( - // 4 px to look at and a whole row to hit (WCAG - // 2.5.8), the split the colour sliders and the ruler - // both make. div() - .id("speed-bar") - .relative() - .w_full() - .h(px(KEYS_ROW_H)) + .id("mix-rows") .flex() - .items_center() - .cursor_pointer() - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this, event: &MouseDownEvent, _, cx| { - this.speed_dragging = true; - this.drag_speed(event.position.x, true, cx); - }), - ) - .child(bounds_probe(self.speed_bar.clone())) - .child( - div() - .w_full() - .h(px(4.)) - .rounded(px(2.)) - .bg(rgb(CHROME)) - .child( - div() - .h_full() - .w(relative(frac)) - .rounded(px(2.)) - .bg(rgb(ACCENT)), - ), - ), + .flex_col() + .gap(px(6.)) + .overflow_y_scroll() + .children(rows), ) - .child(div().flex().gap(px(4.)).children(presets)) .child( div() .flex_none() .px(px(6.)) .text_size(px(11.)) .text_color(rgb(INK_DIM)) - // What the choice *is*, in the numbers the - // timeline is measured in: the source range - // never moves, the room it takes does. - .child(format!( - "{speed} — {} source frames over {} on the timeline ({})", - clip.len(), - clip.frames(), - timecode(f64::from(clip.frames()) / self.fps, self.fps) - )), + // What the choice *is*: the limiter's own line, + // because "on" alone says nothing about what it + // does to a mix that never reaches the ceiling. + .child(match limiter.on { + true => format!( + "the mix is held under {:+.0} dBFS — quieter passages are untouched", + limiter.ceiling_db + ), + false => "the limiter is out of circuit — a hot mix clips at full scale".to_string(), + }), ), ), ) @@ -4548,9 +6024,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 +6077,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 +6173,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 +6454,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 +6501,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 +6559,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 +6597,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,14 +6618,33 @@ 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() .map_or(&[][..], PlaybackSession::sources); let (sel, sel_link) = (self.selected, self.selected_link()); let audio = lane.kind == LaneKind::Audio; + // What this track plays at, on the header it belongs to: shown only + // when it is not unity, because a column 40 px wide has room for a + // number or for a name, and the name is what a header is for. The + // press opens the mix card on this very track. + let gain_db = self + .session + .as_ref() + .map_or(0., |session| session.lane_gain_db(lane)); + let gain_tip: SharedString = format!( + "{name} plays at {gain_db:+.0} dB — opens the mix ({}); the whole track, every frequency, unlike the equalizer", + self.keymap.display(ActionId::Mix) + ) + .into(); let tip: SharedString = format!( - "Select (or {} under the playhead, {}/{} along the lane) — drag an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut", + "Select (or {} under the playhead, {}/{} along the lane) — drag it to move it, an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut", self.keymap.display(ActionId::Select), self.keymap.display(ActionId::SelectPrev), self.keymap.display(ActionId::SelectNext), @@ -5106,13 +6666,65 @@ 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(match audio { + // A button, not a label: the one setting a track has of + // its own used to be reachable from nowhere. + true => div() + .id(("mix-lane", lane.ord)) + .flex_1() + .w_full() + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .tooltip(move |_, cx| cx.new(|_| Tip(gain_tip.clone())).into()) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.open_mix(Some(lane), cx) + })) + .child(match gain_db == 0. { + true => name.clone(), + false => format!("{name} {gain_db:+.0}"), + }) + .into_any_element(), + false => div() + .flex_1() + .flex() + .items_center() + .child(name.clone()) + .into_any_element(), + }) + // 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 @@ -5127,18 +6739,23 @@ impl Player { .bg(rgb(LETTERBOX)) .overflow_hidden() // A library row let go over a lane is the same insert the - // Add button makes, through the same call -- at the - // playhead, not at the pointer: clips here are placed end - // to end, so where along the bed it landed says nothing. - .on_drop(cx.listener(move |this, drag: &AssetDrag, _, cx| { - this.insert_source(&drag.0.clone(), drag.1, Some(lane), cx) + // Add button makes, through the same call -- but where the + // pointer let it go, not at the playhead: a hand that + // carried a file to a place on the bed named that place. + // gpui hands a drop no event, so the pointer is read off + // the window, which took it from the release that fired + // this (gpui window.rs:3602). + .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| { + let at = this.frame_under(window.mouse_position().x); + this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx) })) .drag_over::(|s, _, _, _| s.bg(rgb(HOVER_DIM))) - // A clip let go over another lane changes track and keeps - // the frames it covers -- the pointer's position along the - // bed says nothing here either, for the reason above. - .on_drop(cx.listener(move |this, drag: &ClipDrag, _, cx| { - this.move_clip(drag.lane, drag.idx, lane, cx) + // ...and a clip let go over a lane lands the same way: on + // the track it was dropped on, at the frame it was carried + // to -- its own included, which is the drag that moves a + // take along its track. + .on_drop(cx.listener(move |this, drag: &ClipDrag, window, cx| { + this.move_clip(drag.lane, drag.idx, lane, window.mouse_position().x, cx) })) .drag_over::(|s, _, _, _| s.bg(rgb(HOVER_DIM))) .children(clips.iter().enumerate().map(|(i, clip)| { @@ -5166,7 +6783,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) @@ -5183,6 +6800,10 @@ impl Player { // says what is moving. let ghost: SharedString = label.clone().unwrap_or_else(|| lane.label()).into(); + // Its head in frames, for the press below: the `start` + // above is the same moment in seconds, which is what + // the box is *drawn* from. + let head = clip.start; div() // Named per lane: two rows numbering their clips // from zero would hand gpui the same id twice. @@ -5190,7 +6811,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.)) @@ -5206,16 +6831,23 @@ impl Player { .cursor_pointer() .hover(|s| s.border_color(rgb(ACCENT))) .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) - // Dragged onto another lane it *moves* there; the - // click that starts the drag still selects, so - // picking a clip up and putting it back down where - // it was is exactly a click. + // Dragged, it *moves*: to the frame it was let go on + // and to the lane it was let go over. The click that + // starts the drag still selects, so picking a clip + // up and putting it back down where it was is + // exactly a click. .on_drag(ClipDrag { lane, idx: i }, move |_, _, _, cx| { cx.new(|_| Tip(ghost.clone())) }) .on_mouse_down( MouseButton::Left, - cx.listener(move |this, _: &MouseDownEvent, _, cx| { + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + // Where in the box the hand took hold of it, + // for the drag this press may become: the + // clip has to move with the pointer rather + // than jump its head under it. + this.grab = + this.frame_under(event.position.x).saturating_sub(head); this.select((lane, i), cx); }), ) @@ -5339,8 +6971,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 +7286,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)] @@ -5683,6 +7341,7 @@ struct Row { fn library_rows( sources: &[Source], streams: &HashMap>, + decoders: &HashMap, Backend)>>, timeline_audio: Option<(u32, u16)>, frames: impl Fn(&Path) -> u32, ) -> Vec { @@ -5698,12 +7357,22 @@ fn library_rows( path: source.path.clone(), stream: source.audio_stream, name: row_name(&source.path, source.audio_stream, of_file.len() > 1), - // Only where there is a choice to describe: a file with one audio - // track is the row it has always been, name and length, and the - // length is what would be squeezed out at the panel's least width. - detail: info - .filter(|_| of_file.len() > 1) - .map_or_else(String::new, stream_detail), + // The decoder first: it is the same for every row of a file and + // it is what a person opening the panel is asking about. The + // stream half only where there is a choice to describe -- a file + // with one audio track is the row it has always been, name and + // length, and the length is what would be squeezed out at the + // panel's least width. + detail: join_detail( + &decoders + .get(&source.path) + .copied() + .flatten() + .map_or_else(String::new, |(codec, backend)| decode_label(codec, backend)), + &info + .filter(|_| of_file.len() > 1) + .map_or_else(String::new, stream_detail), + ), // A stream already on the timeline is playing: whatever a probe // would say about it now, it is usable by demonstration. unusable: None, @@ -5740,9 +7409,20 @@ fn library_rows( /// why it cannot be used, with the separator only where both halves exist (a /// single-stream file says nothing about its stream). fn join_detail(detail: &str, tail: &str) -> String { - match detail.is_empty() { - true => tail.to_string(), - false => format!("{detail} · {tail}"), + match (detail.is_empty(), tail.is_empty()) { + (true, _) => tail.to_string(), + (false, true) => detail.to_string(), + (false, false) => format!("{detail} · {tail}"), + } +} + +/// How a source's decoder reads: the codec and which seat has it, or the seat +/// alone for a still, which has no coded stream to name. The one place either +/// answer is spelled, so a row, a transport line and a card cannot disagree. +fn decode_label(codec: Option, backend: Backend) -> String { + match codec { + Some(codec) => format!("{} · {}", codec.name(), backend.label()), + None => backend.label().to_string(), } } @@ -5881,48 +7561,115 @@ impl Quality { } } -/// The export card's format rows: what this program can write, and what it -/// cannot with the reason it cannot. A format with no entry at all would read -/// as an oversight, and a menu of three as a claim that nothing else exists -- -/// so the refusals are rows too, dimmed and unclickable. +/// The export card's format rows: the key that picks one, its name, and what it +/// writes -- or, where this program cannot write it, the reason it cannot. A +/// format with no entry at all would read as an oversight, and a menu of three +/// as a claim that nothing else exists -- so the refusals are rows too, dimmed +/// and unclickable. /// -/// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a -/// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a -/// decision about this project rather than about the code, and the row says so -/// instead of pretending the encoder does not exist. HEVC and VP9 are the two -/// this program *reads* and cannot write -- the plugin decodes both and there is -/// no encoder for either here -- so they are rows for the same reason: a codec -/// 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"), +/// `None` is exactly that kind of row, and there are two left. MP3 stopped +/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL +/// `shine-rs` was the licence question, and it is not the only encoder any +/// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an +/// encoder — an *intra-only* one, which the rows say rather than let a user +/// find out from the size of the file. VP9 is the one this program still only +/// *reads*: the plugin decodes it and there is no encoder for it here, so it is +/// a row for the reason the refusals are rows at all — a codec that opens but +/// never comes back out is exactly the gap a user would otherwise go looking +/// for. AAC is not a row at all: it is what both containers' sound *is*, never a +/// file of its own. +/// +/// A codec is one row, and the boxes it can be written into are the row's +/// containers: the same AV1 picture and the same AAC track go into a Matroska +/// file or into an mp4, and which one a user needs is about what has to play +/// the file, not about the encode. So the container is asked *once*, in a row +/// of its own, and only where there is more than one to ask about -- five +/// picture rows to read past were four of them saying the same codec twice. +const FORMATS: [(&[Format], &str, &str, &str); 8] = [ + ( + &[Format::Mp4], + "m", + "H.264", + "plays everywhere · AAC sound · MP4 only", + ), ( - Some(Format::Av1), + &[Format::Av1, Format::Av1Mp4], + "a", "AV1", - "AV1 picture in .mkv — no sound: export WAV or FLAC for that", + "smallest file for the picture · AAC sound", ), - (Some(Format::Wav), "WAV", "16-bit PCM — audio only"), - (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", "no pure-Rust AAC encoder"), ( - None, + &[Format::Hevc, Format::HevcMp4], + "h", "HEVC", - "no encoder in this stack, and patent-encumbered", + "intra-only, every frame a cut point — large files", + ), + (&[Format::Wav], "w", "WAV", "16-bit PCM — audio only"), + (&[Format::Flac], "f", "FLAC", "lossless — audio only"), + ( + &[Format::Mp3], + "p", + "MP3", + "MPEG-1 Layer III, 256 kbps — audio only", ), - (None, "VP9", "superseded by AV1, which is the row above"), + (&[], "", "OGG", "no pure-Rust Vorbis or Opus encoder"), + (&[], "", "VP9", "AV1 above replaces it"), ]; -/// The format a key picks while the export card is up: the row's own initial, -/// which is unambiguous across the three that can be picked. `None` for -/// everything else, digits included -- those are the bitrate's. -fn format_key(key: &str) -> Option { +/// The codec row a key picks, landed in the container already chosen: pressing +/// `a` after an mp4 gives AV1 *in mp4*, because a box decided once is not a +/// question again. A letter of the row's own name, spelled out in the table +/// rather than taken from the initial (`MP4` and `MP3` share one). Never a +/// digit -- those are the bitrate's. `None` for every other stroke, the rows +/// that cannot be picked included. +fn format_key(key: &str, current: Format) -> Option { + FORMATS + .into_iter() + .filter(|(_, stroke, ..)| !stroke.is_empty() && stroke.eq_ignore_ascii_case(key)) + .find_map(|(row, ..)| same_box(row, current)) +} + +/// The boxes one codec may be written into, in the order its container row +/// cycles them. Empty for a codec this program cannot write at all. +fn containers(format: Format) -> &'static [Format] { FORMATS .into_iter() - .filter_map(|(format, label, _)| format.zip(label.get(..1))) - .find(|(_, initial)| initial.eq_ignore_ascii_case(key)) - .map(|(format, _)| format) + .map(|(row, ..)| row) + .find(|row| row.contains(&format)) + .unwrap_or(&[]) +} + +/// This row's format under the container `current` is already in, or the row's +/// first when it has no such box: an AV1 picked from a WAV lands in Matroska, +/// and picked from an mp4 stays in the mp4. +fn same_box(row: &[Format], current: Format) -> Option { + row.iter() + .copied() + .find(|f| f.ext() == current.ext()) + .or_else(|| row.first().copied()) +} + +/// The next box for the same codec, wrapping -- what the container row's key +/// does. The format itself for a codec with only one, so the stroke cannot +/// change what it is not offering. +fn next_container(format: Format) -> Format { + let row = containers(format); + let at = row.iter().position(|&f| f == format).unwrap_or(0); + row.get((at + 1) % row.len().max(1)) + .copied() + .unwrap_or(format) +} + +/// Why the quality rows say nothing about this format, or `None` where they +/// decide the picture. Only a picture encoder is given a bitrate here: the two +/// lossless audio formats have none to give and MP3 is written at one fixed +/// figure, so a live row over either would be a control that changes nothing. +fn bitrate_refusal(format: Format) -> Option<&'static str> { + match format { + Format::Wav | Format::Flac => Some("lossless audio — no bitrate to pick"), + Format::Mp3 => Some("MP3 is written at a fixed 256 kbps"), + _ => None, + } } /// What one of the colour card's own strokes does. Its keys are card-local -- @@ -6057,36 +7804,85 @@ fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) { sizes[at.map_or(0, |at| (at + 1) % sizes.len())] } -/// [`format_line`] plus the project's resolution, which is what a video export -/// is written at however many sizes the media on the timeline are. Only for the -/// formats that carry a picture -- a WAV has no resolution to state. -fn export_line(format: Format, session: Option<&PlaybackSession>) -> String { - let line = format_line(format); - match session.filter(|_| format.has_video()) { - Some(session) => { - let (w, h) = session.resolution(); - format!("{line} · project {w}x{h}") - } - None => line.to_string(), +/// The first of the two lines the card keeps above its button: what will be +/// *inside* the file. [`format_line`]'s codec and box, then the project's own +/// picture size and rate -- which is what a video export is written at however +/// many sizes and rates the media on the timeline are -- and last what the +/// sound will be, or that there is none. Every field here is one `ffprobe` +/// reads back off the finished file, so the line is checkable rather than a +/// promise. +fn summary_head(format: Format, picture: Option<((u32, u32), f64)>, audio: &str) -> String { + let line = match picture.filter(|_| format.has_video()) { + Some(((w, h), fps)) => { + format!("{} · {w}x{h} · {} fps", format_line(format), fps_label(fps)) + } + None => format_line(format).to_string(), + }; + join_detail(&line, audio) +} + +/// The second: where it lands, roughly how big, and what will encode the +/// picture -- the seat as the probe found it (`…` until it lands, never a +/// guess), which is what the running export then names on its progress line. +fn summary_tail(path: &Path, mb: Option, seat: Option<&'static str>, video: bool) -> String { + let size = mb.map_or_else(String::new, |mb| format!("≈ {mb} MB")); + let seat = match (video, seat) { + (true, Some(seat)) => seat, + (true, None) => "encoder …", + (false, _) => "", + }; + join_detail(&join_detail(&file_name(path), &size), seat) +} + +/// A frame rate as a person writes it: `30`, not `30.000`, and `23.976` for the +/// rate that is a ratio. +fn fps_label(fps: f64) -> String { + match (fps - fps.round()).abs() < 0.001 { + true => format!("{fps:.0}"), + false => format!("{fps:.3}") + .trim_end_matches('0') + .trim_end_matches('.') + .to_string(), } } +/// About how big a *chosen* bitrate makes the file: the picture's megabits over +/// the timeline's length. `None` for `Auto`, whose figure is the encoder's to +/// decide, and for a format with no bitrate at all -- a number nobody picked is +/// not an estimate. The sound and the container's own overhead are not in it, +/// which is why the card says "≈". +fn estimated_mb(bitrate: Option, duration: f64) -> Option { + let bitrate = bitrate.filter(|&b| b > 0 && duration > 0.)?; + Some((bitrate as f64 * duration / 8e6).round() as u64) +} + +/// What is in the file and what box it is in, which is the head of the summary. +/// Terse on purpose: the fields after it (size, rate, sound) are what the line +/// is *for*, and a head that spent its width on prose used to push the whole +/// summary onto a second line -- what each codec means is on its row. fn format_line(format: Format) -> &'static str { match format { - Format::Mp4 => "H.264 · MP4 · moov at end", - Format::Av1 => "AV1 · Matroska · picture only, no audio track", - Format::Wav => "16-bit PCM · WAV · timeline audio only", - Format::Flac => "FLAC · lossless · timeline audio only", + Format::Mp4 => "H.264 · MP4", + Format::Av1 => "AV1 · MKV", + Format::Av1Mp4 => "AV1 · MP4", + Format::Hevc => "HEVC intra · MKV", + Format::HevcMp4 => "HEVC intra · MP4", + // The three whose codec *is* their box: naming it twice would be the + // only field on this line that says nothing. + Format::Wav => "16-bit PCM · WAV", + Format::Flac => "FLAC · lossless", + Format::Mp3 => "MP3 · 256 kbps", } } -/// The row a format is picked by, which is what a refusal calls it: `MP4`, not -/// the `mkv` an AV1 file is named with. +/// The row a format is picked by, which is what a refusal calls it: the codec, +/// since the container is a row of its own now -- `AV1`, not the `mkv` such a +/// file is named with. fn format_label(format: Format) -> &'static str { FORMATS .iter() - .find(|(row, ..)| *row == Some(format)) - .map_or("EXPORT", |(_, label, _)| *label) + .find(|(row, ..)| row.contains(&format)) + .map_or("EXPORT", |(_, _, label, _)| *label) } /// The destination under a format: `take.export.mp4` becomes `take.export.wav`. @@ -6142,6 +7938,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 -- @@ -6162,11 +8002,12 @@ fn is_bare_modifier(key: &str) -> bool { /// refuses it too (`export::start`); this is what greys the row before a /// destination has been picked. /// -/// The second reason is the mp4 path's alone: it *copies* one AAC track and -/// there is no encoder here to mix several with, so a timeline whose sound is -/// spread over more than one audio lane is refused by the engine -/// (`export::run`). An AV1 export carries no sound at all -- said on its row as -/// its detail, not as a refusal -- so no count of audio lanes stops it. +/// It is the *only* reason left. A second audio lane, a speeded clip, a source +/// no mp4 sample table holds: each of those used to grey the MP4 row, because +/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy +/// cannot say what the timeline says (`export::copy_audio`), so none of them is +/// a refusal any more -- and every video format carries the sound, so there is +/// nothing here that is one format's alone. fn format_refusal(session: &PlaybackSession, format: Format) -> Option { if !format.has_video() { return None; @@ -6175,43 +8016,13 @@ fn format_refusal(session: &PlaybackSession, format: Format) -> Option { .lanes() .into_iter() .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty()); - if !picture { - return Some(format!( - "no picture — {} would be black; export WAV or FLAC", + match picture { + true => None, + false => Some(format!( + "no picture — {} would be black; export WAV, FLAC or MP3", format.name() - )); - } - if format != Format::Mp4 { - return None; + )), } - let audio: Vec = session - .lanes() - .into_iter() - .filter(|&lane| lane.kind == LaneKind::Audio && !session.lane_clips(lane).is_empty()) - .collect(); - if audio.len() > 1 { - return Some(format!("{} audio lanes — an mp4 copies one", audio.len())); - } - // ...and the third reason, the same path's: a copied AAC packet carries no - // rate, so a speeded clip on the lane being copied would come back at 1.00x - // under a picture the export *does* re-time. The engine refuses it by name - // (`export::copy_audio`); this greys the row before anyone picks a - // destination. The picture's own rate is no reason at all -- the export walk - // honours that -- so only this one lane is asked. - audio - .first() - .and_then(|&lane| { - session - .lane_clips(lane) - .iter() - .find(|c| !c.speed.is_normal()) - }) - .map(|c| { - format!( - "sound at {} — an mp4 copies packets, which carry no rate", - c.speed - ) - }) } /// How tall a column of `lanes` rows is, gaps included -- the panel's own gap @@ -6235,14 +8046,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 +8364,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() @@ -6521,6 +8498,28 @@ fn frac_along(x: Pixels, bounds: Bounds) -> f32 { ((x - bounds.left()) / bounds.size.width).clamp(0., 1.) } +/// The frame a dropped clip's head lands on: `raw`, unless one of `marks` is +/// within `tol` frames of where its head -- or its tail, `len` frames along -- +/// would come to rest, in which case that edge wins. The snap every timeline +/// has: clips meet exactly instead of a frame apart, and the hand does not have +/// to aim. The nearest mark wins, and a head landing on one beats a tail at the +/// same distance -- what was dragged is the head. +fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 { + let mut best: Option<(u32, u32)> = None; + for &mark in marks { + // Head on the mark, then tail on it -- a clip dragged up against the + // take in front of it snaps by whichever end reaches first. + for start in [Some(mark), mark.checked_sub(len)] { + let Some(start) = start else { continue }; + let d = start.abs_diff(raw); + if d <= tol && best.is_none_or(|(near, _)| d < near) { + best = Some((d, start)); + } + } + } + best.map_or(raw, |(_, start)| start) +} + /// Where down an element a pointer sits, 0..1 from the top: the vertical twin /// of [`frac_along`], for the equalizer, whose gain axis is the y one. An /// element that was never painted reads as its middle -- flat, the one answer @@ -6599,6 +8598,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 +8737,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 +8845,27 @@ 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, - 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, + 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, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, 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, bitrate_refusal, can_add, cancels_export, + clipboard_after_remove, color_snap, containers, envelope, eq_spectrum, eq_x, eq_y, + estimated_mb, export_path, export_settings, format_key, format_line, format_refusal, + fps_label, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, + keymap, lanes_h, marked, menu_at, next_container, normalise, nothing_to_play, panel_h, + project_path, push_digit, retarget, scrub_due, show_label, silence_rate, snapped, + source_tint, span_partner, speed_at, summary_head, summary_tail, timecode, unseen_paths, unseen_sources, whole_take, width_frac, window_title, }; - use super::{LaneKind, file_name, file_uri, library_rows, unscannable}; + use super::{ + LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows, + repeats, 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. @@ -6791,9 +8938,13 @@ mod tests { ); // The rows the panel draws: one per source, each its file's own length // -- source 1 has no clip anywhere and is still 4 s at 30 fps. - let rows = library_rows(session.sources(), &HashMap::new(), None, |path| { - session.file_frames(path) - }); + let rows = library_rows( + session.sources(), + &HashMap::new(), + &HashMap::new(), + None, + |path| session.file_frames(path), + ); assert_eq!(rows.len(), 2); assert_eq!(rows[0].frames, 150, "5 s at 30 fps"); assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed"); @@ -6832,7 +8983,9 @@ mod tests { .find(|s| s.index == session.sources()[0].audio_stream) .map(|s| (s.sample_rate, s.channels)); let frames = session.file_frames(&path); - let rows = library_rows(session.sources(), &streams, rate, |_| frames); + let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| { + frames + }); assert_eq!(rows.len(), 1); assert_eq!(rows[0].name, "test_tone.mp3"); assert_eq!(rows[0].unusable, None, "the row is placeable"); @@ -6854,14 +9007,19 @@ mod tests { // and are never refused. assert_eq!( format_refusal(&session, Format::Mp4).as_deref(), - Some("no picture — an mp4 would be black; export WAV or FLAC") + Some("no picture — an mp4 would be black; export WAV, FLAC or MP3") ); assert_eq!( format_refusal(&session, Format::Av1).as_deref(), - Some("no picture — an AV1 export would be black; export WAV or FLAC") + Some("no picture — an AV1 Matroska would be black; export WAV, FLAC or MP3") + ); + assert_eq!( + format_refusal(&session, Format::Av1Mp4).as_deref(), + Some("no picture — an AV1 mp4 would be black; export WAV, FLAC or MP3") ); assert_eq!(format_refusal(&session, Format::Wav), None); assert_eq!(format_refusal(&session, Format::Flac), None); + assert_eq!(format_refusal(&session, Format::Mp3), None); } fn info( @@ -6899,7 +9057,13 @@ mod tests { info(3, 0, 0, None, false), ], ); - let rows = library_rows(&sources, &streams, Some((44_100, 2)), |_| 90); + let rows = library_rows( + &sources, + &streams, + &HashMap::new(), + Some((44_100, 2)), + |_| 90, + ); assert_eq!( rows.iter().map(|r| r.stream).collect::>(), [0, 1, 2, 3], @@ -6937,7 +9101,7 @@ mod tests { PathBuf::from("/m/plain.mp4"), vec![info(0, 44_100, 2, None, true)], ); - let rows = library_rows(&plain, &one, Some((44_100, 2)), |_| 90); + let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90); assert_eq!(rows.len(), 1); assert_eq!(rows[0].name, "plain.mp4"); assert_eq!( @@ -6948,7 +9112,7 @@ mod tests { let mut silent = HashMap::new(); silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new()); for probe in [silent, HashMap::new()] { - let rows = library_rows(&plain, &probe, None, |_| 90); + let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90); assert_eq!(rows.len(), 1); assert_eq!(rows[0].name, "plain.mp4"); assert_eq!(rows[0].detail, ""); @@ -6966,7 +9130,13 @@ mod tests { PathBuf::from("/m/other.mp4"), vec![info(0, 44_100, 2, None, true)], ); - let rows = library_rows(&placed, &streams, Some((44_100, 2)), |_| 90); + let rows = library_rows( + &placed, + &streams, + &HashMap::new(), + Some((44_100, 2)), + |_| 90, + ); assert_eq!( rows.iter() .map(|r| (file_name(&r.path), r.stream)) @@ -7067,6 +9237,98 @@ 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"), + // The fader on every audio track's own header, which is + // also what opens the card the limiter is on. + ActionId::Mix => element("mix-lane"), + 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", + "mix-row", + "mix-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 @@ -7282,7 +9544,7 @@ mod tests { ); let streams = HashMap::new(); let rows = |session: &PlaybackSession| { - library_rows(session.sources(), &streams, None, |_| 0).len() + library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len() }; assert_eq!(rows(&session), 2, "a row per source"); @@ -7306,17 +9568,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 @@ -7392,7 +9708,7 @@ mod tests { let v2 = session.add_lane(LaneKind::Video); assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0))); - assert!(session.move_clip_to_lane(Lane::V1, 0, v2), "V1 -> V2"); + assert!(session.move_clip_to(Lane::V1, 0, v2, 0), "V1 -> V2"); assert!(session.lane_clips(Lane::V1).is_empty(), "it left V1"); assert_eq!(session.lane_clips(v2).len(), 1, "and landed on V2"); assert_eq!( @@ -7405,11 +9721,11 @@ mod tests { // Dropped on a lane of the other kind it is refused and nothing moves -- // the notice the front-end shows for it says which kind of lane to use. // (The other refusal, landing on another clip, is the engine's own test - // `move_to_lane_keeps_the_frames_and_refuses_the_rest`.) - assert!(!session.move_clip_to_lane(v2, 0, Lane::A1), "picture on A1"); + // `move_clip_keeps_the_frames_and_refuses_the_rest`.) + assert!(!session.move_clip_to(v2, 0, Lane::A1, 0), "picture on A1"); assert_eq!(session.lane_clips(v2).len(), 1, "and it stayed on V2"); assert!( - session.move_clip_to_lane(v2, 0, Lane::V1), + session.move_clip_to(v2, 0, Lane::V1, 0), "dragged back down" ); @@ -7460,28 +9776,24 @@ mod tests { assert!(session.lane_clips(v2).is_empty()); assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put"); - // A second audio lane carrying sound is what an mp4 export cannot - // write, so the card greys that row before a destination is picked. + // A second audio lane used to be what an mp4 export could not write -- + // it copied one AAC track and a mix is not a copy. It mixes now + // (`export::copy_audio`), so no row is greyed by a count of lanes. assert_eq!(format_refusal(&session, Format::Mp4), None); let a2 = session.add_lane(LaneKind::Audio); assert_eq!(a2.label(), "A2"); - assert_eq!( - format_refusal(&session, Format::Mp4), - None, - "an empty lane carries nothing" - ); assert!( session .place_stream_at(0.0, &path, 0, Some(a2)) .expect("its own file is on this timeline") ); - assert_eq!( - format_refusal(&session, Format::Mp4).as_deref(), - Some("2 audio lanes — an mp4 copies one") - ); - // ...and the one thing that does not stop an AV1 export, which carries - // no sound to have too much of. - assert_eq!(format_refusal(&session, Format::Av1), None); + for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] { + assert_eq!( + format_refusal(&session, format), + None, + "two audio lanes are a mix, not a refusal" + ); + } // Undo, one edit at a time and backwards: the drop on A2, the lane A2 // itself, the lift, the drop on V2, and last the lane V2 -- an added @@ -7609,6 +9921,70 @@ mod tests { assert_eq!(frac_down(px(50.), Bounds::default()), 0.5); } + /// What a drop reads: the frame under the pointer, through the same view + /// the boxes are drawn through. Zoomed in, the same pixel is a different + /// frame -- which is the whole reason `Player::frame_under` goes through + /// [`View`] rather than through the duration alone. + #[test] + fn a_drop_reads_the_frame_under_the_pointer_at_every_zoom() { + // A 200 px bed inset by the panel's padding, 10 seconds at 30 fps. + let bed: Bounds = Bounds { + origin: point(px(12.), px(400.)), + size: size(px(200.), px(6.)), + }; + let (duration, fps) = (10., 30.); + // The frame a pointer at window `x` names, exactly as `frame_under` + // composes it. + let under = + |view: View, x: f32| frame_at(view.time_at(frac_along(px(x), bed), duration), fps); + + // The whole timeline across the bed: halfway along is frame 150. + let fit = View::default(); + assert_eq!(under(fit, 12.), 0); + assert_eq!(under(fit, 112.), 150); + assert_eq!(under(fit, 212.), 300); + + // Four times in, starting at second 5: the same middle pixel is now the + // frame in the middle of seconds 5..7.5, and the left edge is not 0. + let zoomed = View { + zoom: 4., + start: 5., + }; + assert_eq!(under(zoomed, 12.), 150); + assert_eq!(under(zoomed, 112.), 187); + assert_eq!(under(zoomed, 212.), 225); + // ...and a drop past either end of the bed lands on the timeline, never + // outside it: `time_at` clamps. + assert_eq!(under(zoomed, 0.), 150); + assert_eq!(under(fit, 9999.), 300); + } + + /// The snap: a clip let go a few frames off a neighbour's edge lands *on* + /// it, by whichever of its own ends is nearer, and a clip let go in open bed + /// stays exactly where the hand left it. + #[test] + fn a_dropped_clip_snaps_to_the_edges_worth_landing_on() { + // A neighbour covering [100, 160) and the playhead at 300. + let marks = [100, 160, 300, 0]; + // Head a frame short of the neighbour's tail: laid end to end with it. + assert_eq!(snapped(158, 40, 4, &marks), 160); + // Tail a frame into its head: pulled back so the two meet exactly. + assert_eq!(snapped(62, 40, 4, &marks), 60); + // The playhead is an edge like any other. + assert_eq!(snapped(298, 40, 4, &marks), 300); + // Outside the tolerance nothing moves -- a gap the hand meant to leave + // is a gap. + assert_eq!(snapped(150, 40, 4, &marks), 150); + // No tolerance at all (zoomed right in, where a few pixels are worth + // less than a frame) is no snap: single frames are placed by hand. + assert_eq!(snapped(158, 40, 0, &marks), 158); + // The nearer edge wins when two are in reach. + assert_eq!(snapped(101, 40, 8, &marks), 100); + // ...and a mark closer to the head than `len` cannot pull the clip to a + // negative start. + assert_eq!(snapped(2, 40, 4, &marks), 0); + } + #[test] fn timecode_counts_frames_inside_the_second() { assert_eq!(timecode(0., 30.), "00:00:00:00"); @@ -7743,6 +10119,169 @@ 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 +10457,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 +10845,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 +10911,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, @@ -8262,80 +10929,265 @@ mod tests { #[test] fn the_export_card_fits_the_smallest_window() { // Same 640x360 floor the keybindings card is measured against: the - // capped row list, the fixed-format line and the confirm button, under + // capped row list, the two summary lines and the confirm button, under // a title and a status line. let title = 17.; let status = 28.; - let fixed = 17.; - let gaps = 4. * 2.; + // The head is one line of 11 px at this width -- every field of it, + // worst case, is 71 characters against the 76 that fit. The tail is + // budgeted for two: the destination's name is the user's and a long one + // wraps. + let summary = 15. + 30.; + // Six children in the column, so five gaps. + let gaps = 5. * 2.; let padding = 24.; - assert!( - title + status + EXPORT_ROWS_H + fixed + CONTROL_H + 4. + gaps + padding <= 360., - "card too tall" + assert_eq!( + EXPORT_FIXED_H, + title + status + summary + CONTROL_H + 4. + gaps + padding ); + assert!(EXPORT_FIXED_H + EXPORT_ROWS_H <= 360., "card too tall"); + // The list grows with a window that has the room -- and never shrinks + // below the cap that made the floor fit, whatever arithmetic the window + // hands it. + let cap = |h: f32| (h - EXPORT_FIXED_H - 24.).max(EXPORT_ROWS_H); + assert_eq!(cap(360.), EXPORT_ROWS_H); + assert_eq!(cap(0.), EXPORT_ROWS_H); + assert!(cap(720.) > EXPORT_ROWS_H); + assert!(EXPORT_FIXED_H + cap(720.) <= 720.); + // ...and inside the 640 px floor with the scrim showing either side. + assert!(EXPORT_W + 2. * 12. <= 640.); // The cap is only honest if enough of the list is on screen to read as - // one -- the destination and the first formats, not a slot. - assert!(EXPORT_ROWS_H / KEYS_ROW_H >= 6.); - // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's. + // one -- and the whole format section is: its header and every codec + // row, so nothing that is picked *first* is behind a scroll. + let codecs = FORMATS.iter().filter(|(row, ..)| !row.is_empty()).count(); + assert!(EXPORT_ROWS_H / KEYS_ROW_H >= 1. + codecs as f32); + // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's -- + // and the bitrate steppers are `HIT_MIN` squares sitting inside a row, + // which only fits while the row is at least as tall as one. assert!(KEYS_ROW_H >= HIT_MIN); assert!(CONTROL_H >= HIT_MIN); + // The dimmed text on the card -- every refusal, every detail, every key + // in its column -- is body text on `SURFACE` and WCAG 1.4.3 binds it. + // A dimmed row is drawn in this ink rather than at an opacity, which is + // what a refusal used to be readable through. + assert!( + contrast(INK_DIM, SURFACE) >= 4.5, + "refusal ink {:.2}", + contrast(INK_DIM, SURFACE) + ); + // On the picked row that ink would only be 3.3:1 against the highlight, + // so the row it lands on lifts its key and detail to `INK`. + assert!(contrast(INK, SELECTED) >= 4.5); + assert!( + contrast(INK_DIM, SELECTED) < 4.5, + "the lift is still needed" + ); } #[test] - fn every_format_row_is_offered_or_says_why_not() { - // The four this program can write are rows that pick. Three are named - // after their own extension, so a destination cannot disagree with its - // bytes; the fourth is named after its *codec*, because AV1 arrives and - // leaves in a Matroska file and "MKV" would name the box rather than - // what is in it. - let offered: Vec = FORMATS.iter().filter_map(|&(f, ..)| f).collect(); + fn every_codec_row_is_offered_or_says_why_not() { + // One row per codec, and the boxes it can go in are the container row's + // business: six rows that pick, two that say why they cannot. A codec + // twice over (AV1 · MKV beside AV1 · MP4) was two rows asking the same + // question, and five picture rows above the fold is what the card was + // called unfriendly for. + let offered: Vec<&[Format]> = FORMATS + .iter() + .map(|&(row, ..)| row) + .filter(|row| !row.is_empty()) + .collect(); assert_eq!( offered, - vec![Format::Mp4, Format::Av1, Format::Wav, Format::Flac] + vec![ + &[Format::Mp4][..], + &[Format::Av1, Format::Av1Mp4][..], + &[Format::Hevc, Format::HevcMp4][..], + &[Format::Wav][..], + &[Format::Flac][..], + &[Format::Mp3][..], + ] ); + // Every format the engine writes is on exactly one row: one the card + // cannot reach is one nobody can pick. + for format in [ + Format::Mp4, + Format::Av1, + Format::Av1Mp4, + Format::Hevc, + Format::HevcMp4, + Format::Wav, + Format::Flac, + Format::Mp3, + ] { + assert_eq!( + FORMATS + .iter() + .filter(|(row, ..)| row.contains(&format)) + .count(), + 1, + "{format:?}" + ); + } + // The boxes the container row offers, and what the extension of each is + // -- the destination follows the format, so these are what a file gets + // named with. + assert_eq!(containers(Format::Av1), [Format::Av1, Format::Av1Mp4]); + assert_eq!(containers(Format::HevcMp4), [Format::Hevc, Format::HevcMp4]); + assert_eq!(containers(Format::Mp3), [Format::Mp3]); assert_eq!(Format::Av1.ext(), "mkv"); - for (format, label, _) in FORMATS { - match format { - Some(Format::Av1) => assert_eq!(label, "AV1"), - Some(format) => assert_eq!(format.ext(), label.to_lowercase()), - // A refused format is a row with a reason, never a hidden one: - // an empty detail column would read as an oversight. - None => assert!(!label.is_empty()), + assert_eq!(Format::Av1Mp4.ext(), "mp4"); + assert_eq!(Format::Hevc.ext(), "mkv"); + assert_eq!(Format::HevcMp4.ext(), "mp4"); + // The container key walks the row and wraps, and does nothing at all + // where there is only one box -- a stroke must not invent a choice the + // card is not offering. + assert_eq!(next_container(Format::Av1), Format::Av1Mp4); + assert_eq!(next_container(Format::Av1Mp4), Format::Av1); + assert_eq!(next_container(Format::Hevc), Format::HevcMp4); + assert_eq!(next_container(Format::Mp4), Format::Mp4); + assert_eq!(next_container(Format::Wav), Format::Wav); + for (row, stroke, label, detail) in FORMATS { + assert!(!label.is_empty(), "a row with no name"); + // A refused row is a row with a reason, never a hidden one: an + // empty detail column would read as an oversight. + assert!(!detail.is_empty(), "{label} says nothing"); + // Every row that can be picked has a key of its own, and no row + // that cannot has one: the card is drivable without a pointer. + assert_eq!(!row.is_empty(), !stroke.is_empty(), "{label}"); + if let Some(&first) = row.first() { + assert_eq!( + format_key(stroke, first), + Some(first), + "{label} keys to itself" + ); + assert!( + stroke.parse::().is_err(), + "{label} takes a digit the bitrate needs" + ); + // Every box on one row is the same codec, so the quality rows + // do not change meaning when the container does. + assert!(row.iter().all(|f| f.has_video() == first.has_video())); + assert!( + row.iter() + .all(|f| bitrate_refusal(*f) == bitrate_refusal(first)) + ); } } - for (format, label, detail) in FORMATS { - assert!(!detail.is_empty(), "{label} says nothing"); - // Only the two picture formats leave the bitrate rows live -- the - // card dims them off exactly this. - assert_eq!( - format.is_some_and(Format::has_video), - matches!(format, Some(Format::Mp4 | Format::Av1)) + // No two rows share a key, and none of them is a stroke the card already + // answers to itself -- an ambiguous key is a key that picks the wrong + // thing on a card that has no other input. + let keys: Vec<&str> = FORMATS + .iter() + .map(|&(_, stroke, ..)| stroke) + .filter(|stroke| !stroke.is_empty()) + .collect(); + for (i, key) in keys.iter().enumerate() { + assert!(!keys[i + 1..].contains(key), "{key} picks two rows"); + assert!( + !["c", "q", "d", "g", "r", "enter", "backspace", ESCAPE].contains(key), + "{key} is already the card's own" ); } - // The two codecs this program reads and cannot write are rows of their - // own, refused by name rather than absent -- HEVC for want of an encoder - // (and for its patents), VP9 because AV1 is the row that replaced it. - for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] { - let (format, _, detail) = FORMATS + assert_eq!( + format_key("a", Format::Mp4), + Some(Format::Av1Mp4), + "the box already chosen is kept" + ); + assert_eq!( + format_key("a", Format::Wav), + Some(Format::Av1), + "and a codec with no such box takes its first" + ); + assert_eq!(format_key("h", Format::Av1Mp4), Some(Format::HevcMp4)); + assert_eq!(format_key("p", Format::Mp4), Some(Format::Mp3)); + assert_eq!( + format_key("m", Format::Mp3), + Some(Format::Mp4), + "not MP3, which is p" + ); + assert_eq!( + format_key("x", Format::Mp4), + None, + "a stroke no row carries" + ); + // The codec this program reads and cannot write is a row of its own, + // refused by name rather than absent: VP9, because AV1 is the row that + // replaced it. Its reason travels with it, in the row or in the footer + // line that collects them -- either way it is on screen without a click. + for (label, word) in [("VP9", "replaces it"), ("OGG", "no pure-Rust")] { + let (row, _, _, detail) = FORMATS .into_iter() - .find(|(_, row, _)| *row == label) + .find(|(_, _, name, _)| *name == label) .unwrap_or_else(|| panic!("{label} has no row")); - assert!(format.is_none(), "{label} is not offered"); + assert!(row.is_empty(), "{label} is not offered"); assert!(detail.contains(word), "{label}: {detail}"); } - // The AV1 row says on the row itself that it carries no sound, which is - // the one thing a user could otherwise only find out by playing the file. - let (_, _, av1) = FORMATS - .into_iter() - .find(|(f, ..)| *f == Some(Format::Av1)) - .expect("an AV1 row"); - assert!(av1.contains("no sound"), "{av1}"); - assert!(format_line(Format::Av1).contains("picture only")); - assert_eq!( - format_key("a"), - Some(Format::Av1), - "its own initial picks it" + // Both AV1 boxes say they carry sound: the file used to be picture only, + // and a line that still said so would be the lie a user plays the file + // to find out about. HEVC says intra-only before anyone waits on one -- + // a file several times the size, which the disk would otherwise say. + for format in [Format::Av1, Format::Av1Mp4] { + assert!(format_line(format).starts_with("AV1 · ")); + } + for format in [Format::Hevc, Format::HevcMp4] { + assert!(format_line(format).starts_with("HEVC intra · ")); + } + // The head names the box every format goes in, which is what the + // destination is then named after. + for format in [ + Format::Mp4, + Format::Av1, + Format::Av1Mp4, + Format::Hevc, + Format::HevcMp4, + ] { + assert!( + format_line(format).contains(&format.ext().to_uppercase()), + "{format:?}: {}", + format_line(format) + ); + } + // ...and it stays inside the one line the card budgets for it: the + // longest of them, with every field after it, against the 76 characters + // that fit at `EXPORT_W`. + let longest = summary_head( + Format::Hevc, + Some(((1920, 1080), 23.976)), + "AAC · SW encode (rusty_aac)", + ); + assert!( + longest.chars().count() <= 76, + "{longest} is {} long", + longest.chars().count() + ); + assert!( + FORMATS + .into_iter() + .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra")) ); + // Only a picture encoder is given a bitrate, and the quality rows dim + // with the reason for every format that is not one. + for format in [ + Format::Mp4, + Format::Av1, + Format::Av1Mp4, + Format::Hevc, + Format::HevcMp4, + ] { + assert!( + format.has_video() && bitrate_refusal(format).is_none(), + "{format:?}" + ); + } + for format in [Format::Wav, Format::Flac, Format::Mp3] { + assert!(!format.has_video()); + assert!( + bitrate_refusal(format).is_some(), + "{format:?} dims silently" + ); + } + assert!(bitrate_refusal(Format::Wav).unwrap().contains("lossless")); + assert!(bitrate_refusal(Format::Mp3).unwrap().contains("256 kbps")); // The destination follows the format and keeps the stem, mp4 included. assert_eq!( retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), @@ -8345,7 +11197,59 @@ mod tests { retarget(std::path::Path::new("/a/take.export.wav"), Format::Mp4), std::path::Path::new("/a/take.export.mp4") ); - assert!(format_line(Format::Flac).contains("audio only")); + assert!(format_line(Format::Flac).contains("lossless")); + } + + /// The one line the card is answerable for: what it says is on screen before + /// the button is pressed, and every field of it is one `ffprobe` reads back + /// off the file that comes out. + #[test] + fn the_summary_states_the_file_before_it_is_written() { + let head = summary_head(Format::Mp4, Some(((1920, 1080), 30.)), "AAC copy"); + for field in ["H.264", "MP4", "1920x1080", "30 fps", "AAC copy"] { + assert!(head.contains(field), "{field} missing from {head}"); + } + // The rate as a person writes it, and the ratio one spelled out rather + // than rounded to a rate nothing is written at. + assert_eq!(fps_label(30.), "30"); + assert_eq!(fps_label(24000. / 1001.), "23.976"); + assert_eq!(fps_label(29.97002997), "29.97"); + // A format with no picture states no size and no rate it does not write. + let audio = summary_head(Format::Wav, Some(((1920, 1080), 30.)), "PCM · SW (hound)"); + assert!( + !audio.contains("1920x1080") && !audio.contains("fps"), + "{audio}" + ); + assert!(audio.contains("PCM · SW (hound)")); + // ...and one with no sound on the timeline says that, rather than + // leaving the field out and reading as a file with sound in it. + assert!( + summary_head(Format::Mp4, Some(((640, 360), 25.)), "no sound to write") + .contains("no sound to write") + ); + // The tail: where it lands, about how big, and what will encode it -- + // never a guessed seat, and no seat at all for a format with no picture. + let tail = summary_tail( + Path::new("/a/take.export.mp4"), + Some(45), + Some("VA-API"), + true, + ); + assert!(tail.starts_with("take.export.mp4"), "{tail}"); + assert!( + tail.contains("≈ 45 MB") && tail.contains("VA-API"), + "{tail}" + ); + assert!(summary_tail(Path::new("/a/x.mp4"), None, None, true).contains("encoder …")); + assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("encoder")); + assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("MB")); + // 6 Mbps over a minute is 45 MB. `Auto` has no figure to estimate from + // and an empty timeline no length: neither invents one. + assert_eq!(estimated_mb(Some(6_000_000), 60.), Some(45)); + assert_eq!(estimated_mb(Some(2_000_000), 90.), Some(23)); + assert_eq!(estimated_mb(None, 60.), None); + assert_eq!(estimated_mb(Some(6_000_000), 0.), None); + assert_eq!(estimated_mb(Some(0), 60.), None); } #[test] @@ -8434,10 +11338,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 +11464,119 @@ 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 +11697,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 +11708,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, @@ -8697,9 +11718,12 @@ fn main() { waves: HashMap::new(), streams: HashMap::new(), sizes: HashMap::new(), + decoders: HashMap::new(), + export_seat: None, clipboard: None, scrubbing: false, trim: None, + grab: 0, last_scrub: Instant::now(), last_target: 0, export: None, @@ -8709,6 +11733,8 @@ fn main() { keymap: keymap.clone(), keys_open: false, export_open: false, + export_grouped: true, + export_refusals_inline: false, eq_open: None, // Replaced by the clip's own curve the moment the card // opens; nothing reads it before that. @@ -8716,9 +11742,12 @@ 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, + mix_open: false, + mix_field: 0, silence_open: None, // The conservative defaults the engine documents: a first // scan that leaves a little too much is one nobody undoes. @@ -8728,6 +11757,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-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index c5d2229..c4e4b4b 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -35,7 +35,8 @@ use cros_codecs::encoder::{ }; use cros_codecs::image_processing::nv12_to_i420; use cros_codecs::libva::{ - Display, Image, Surface, VA_FOURCC_NV12, VAEntrypoint, VAImageFormat, VAProfile, + Display, Image, Surface, VA_FOURCC_NV12, VA_FOURCC_P010, VAEntrypoint, VAImageFormat, + VAProfile, }; use cros_codecs::video_frame::VideoFrame; use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame}; @@ -58,11 +59,16 @@ type Handle = as StatelessVideoDecoder>::Handle; /// still loads and still decodes H.264 (it simply refuses the newer codecs' /// files at `Demuxer`). /// -/// ponytail: 8-bit 4:2:0 only -- VP9 profile 0, HEVC Main, AV1 Main. VP9 -/// profile 2, HEVC Main 10 and AV1 Professional decode 10-bit, which the NV12 -/// pool and the `vaGetImage` read-back here cannot carry (`Demuxer` refuses -/// both HEVC Main 10 and 10-bit AV1 by name); the upgrade path is a P010 pool -/// selected from the stream info. +/// 4:2:0 only, 8- or 10-bit: HEVC Main and Main 10, VP9 profile 0, AV1 Main. +/// A 10-bit stream decodes into a P010 pool and is read back down to the 8-bit +/// I420 every frame here is ([`Session::emit`]). +/// +/// ponytail: 10-bit is *carried* 8-bit, because [`VhFrame`] is a byte-per-sample +/// interface all the way to the renderer. That costs the low two bits of a Main +/// 10 source; the upgrade path is a 16-bit `VhFrame`, which is a change to every +/// stage between here and the texture upload, not to this file. +/// VP9 profile 2 and 10-bit AV1 are still refused by `Demuxer`: neither codec +/// states its depth where this reads it. enum Decoder { H264(Dec), Hevc(Dec), @@ -97,8 +103,12 @@ const STALL_LIMIT: u32 = 10_000; struct Session { decoder: Decoder, - /// NV12 descriptor for `vaGetImage`, queried once at open. + /// NV12 (or, for a 10-bit stream, P010) descriptor for `vaGetImage`, + /// queried once at open. nv12_format: VAImageFormat, + /// Whether the surfaces are P010 rather than NV12, which is the one thing + /// the read-back has to do differently. + ten_bit: bool, pool: FramePool, demuxer: Demuxer, meta: VhMeta, @@ -122,23 +132,35 @@ struct Session { /// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object /// with two planes at known offsets, which is exactly what the descriptor in /// `GenericDmaVideoFrame` emits. +/// +/// `ten_bit` asks for the same thing in P010: the very same two-plane 4:2:0 +/// shape with 16-bit samples, so the buffer is simply twice as wide. fn alloc_nv12( gbm: &gbm::Device, coded: Resolution, + ten_bit: bool, ) -> Result { let rows = coded.height + coded.height.div_ceil(2); + let width = coded.width * if ten_bit { 2 } else { 1 }; let bo = gbm - .create_buffer_object::<()>(coded.width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR) - .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?; + .create_buffer_object::<()>(width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR) + .map_err(|e| format!("gbm R8 {width}x{rows} allocation failed: {e}"))?; let pitch = bo.stride().map_err(|e| e.to_string())? as usize; let fd = bo.fd().map_err(|e| e.to_string())?; - GenericDmaVideoFrame::new(vec![std::fs::File::from(fd)], nv12_layout(coded, pitch)) + GenericDmaVideoFrame::new( + vec![std::fs::File::from(fd)], + nv12_layout(coded, pitch, ten_bit), + ) } -/// Two NV12 planes packed one after the other in a single buffer object. -fn nv12_layout(coded: Resolution, pitch: usize) -> FrameLayout { +/// Two NV12 (or P010) planes packed one after the other in a single buffer +/// object. +fn nv12_layout(coded: Resolution, pitch: usize, ten_bit: bool) -> FrameLayout { FrameLayout { - format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */), + format: ( + Fourcc::from(if ten_bit { b"P010" } else { b"NV12" }), + 0, /* DRM_FORMAT_MOD_LINEAR */ + ), size: coded, planes: vec![ PlaneLayout { @@ -186,11 +208,21 @@ impl Session { fn open(path: &Path) -> Option { let (meta, demuxer) = Demuxer::open(path).ok()?; let (display, gbm) = open_devices()?; + // A 10-bit stream decodes into P010 surfaces and is read back through a + // P010 image; a driver that has no such image format is one this cannot + // read 10-bit off at all, which is a null session and a software + // fallback like any other refusal here. + let ten_bit = demuxer.bit_depth() > 8; + let want = if ten_bit { + VA_FOURCC_P010 + } else { + VA_FOURCC_NV12 + }; let nv12_format = display .query_image_formats() .ok()? .into_iter() - .find(|f| f.fourcc == VA_FOURCC_NV12)?; + .find(|f| f.fourcc == want)?; let decoder = match meta.codec { Codec::H264 => { Decoder::H264(Dec::::new_vaapi(display, BlockingMode::Blocking).ok()?) @@ -206,11 +238,12 @@ impl Session { } }; let pool = FramePool::new(move |info: &StreamInfo| { - alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed") + alloc_nv12(&gbm, info.coded_resolution, ten_bit).expect("output frame allocation failed") }); Some(Self { decoder, nv12_format, + ten_bit, pool, demuxer, meta: VhMeta { @@ -350,6 +383,20 @@ impl Session { let (dst_y, rest) = self.out.split_at_mut(self.luma); let (dst_u, dst_v) = rest.split_at_mut(self.chroma); + if self.ten_bit { + p010_to_i420( + &data[va.offsets[Y_PLANE] as usize..], + va.pitches[Y_PLANE] as usize, + dst_y, + &data[va.offsets[UV_PLANE] as usize..], + va.pitches[UV_PLANE] as usize, + dst_u, + dst_v, + w, + h, + ); + return; + } nv12_to_i420( &data[va.offsets[Y_PLANE] as usize..], va.pitches[Y_PLANE] as usize, @@ -383,6 +430,43 @@ impl Session { } } +/// One P010 picture down to packed 8-bit I420: [`nv12_to_i420`] for a surface +/// whose samples are 16-bit little-endian with the value in the **high** bits, +/// which is what P010 means. The high byte of each pair is therefore the 10-bit +/// sample shifted down by two, i.e. the 8-bit one -- no rounding, because a +/// second read of the low byte costs more than the half-bit it would buy. +fn p010_to_i420( + src_y: &[u8], + src_y_pitch: usize, + dst_y: &mut [u8], + src_uv: &[u8], + src_uv_pitch: usize, + dst_u: &mut [u8], + dst_v: &mut [u8], + width: usize, + height: usize, +) { + for row in 0..height { + let src = &src_y[row * src_y_pitch..]; + let dst = &mut dst_y[row * width..row * width + width]; + for (x, out) in dst.iter_mut().enumerate() { + *out = src[2 * x + 1]; + } + } + let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); + for row in 0..ch { + let src = &src_uv[row * src_uv_pitch..]; + let (u, v) = ( + &mut dst_u[row * cw..row * cw + cw], + &mut dst_v[row * cw..row * cw + cw], + ); + for x in 0..cw { + u[x] = src[4 * x + 1]; + v[x] = src[4 * x + 3]; + } + } +} + /// Opens `path` for hardware decode, positioned so the first /// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean /// the start of the stream). Returns null on any failure at all: no libva @@ -657,8 +741,8 @@ impl EncSession { }; // Allocated at the aligned size, so the buffer's pitch is never smaller // than a padded row. - let frame = alloc_nv12(&gbm, coded).ok()?; - let layout = nv12_layout(coded, frame.get_plane_pitch()[0]); + let frame = alloc_nv12(&gbm, coded, false).ok()?; + let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false); Some(Self { encoder, h264: !av1, diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 77dc2ff..418d61b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -23,12 +23,31 @@ 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" +# The MP3 encoder, so that format is a row a user can pick rather than a licence +# note: pure Rust, Apache-2.0, CBR and VBR. The decoder side of mp3 is +# symphonia's below -- an mp3 has always been importable here, and until this it +# was the one format the editor could read and never write. +rusty_mp3 = "0.6" symphonia-core = "0.6" symphonia-codec-aac = "0.6" # The umbrella crate for the standalone audio files: one dependency instead of # seven, and its `default::get_probe`/`get_codecs` are the registries this would # otherwise hand-build. Explicit feature list rather than the default one -- no -# mkv, no ape, no adpcm: what is listed here is exactly what `is_audio` admits. +# ape, no adpcm: what is listed here is exactly what `is_audio` admits, plus +# `mkv`, which is not an `is_audio` container at all -- it is how the *sound* of +# a Matroska video file is read, the picture having its own demuxer here. # There is no opus/ac3/dts feature at any symphonia version, which is why those # are refused rather than promised. symphonia = { version = "0.6", default-features = false, features = [ @@ -38,6 +57,7 @@ symphonia = { version = "0.6", default-features = false, features = [ "id3v1", "id3v2", "isomp4", + "mkv", "mp3", "ogg", "pcm", @@ -54,6 +74,14 @@ oxideav-core = "0.1.34" # inside rav1e itself and is what keeps an export minutes rather than tens of # minutes; the cost of no assembly is measured in `export::Enc::open_av1`. rav1e = { version = "0.8.1", default-features = false, features = ["threading"] } +# The software HEVC encoder, intra-only: OxideAV's pure-Rust H.265, MIT, no C +# and no FFI like everything else here. Its *inter* modes run at 0.81 fps on +# 1080p across 12 cores (measured 2026-08-11) and are therefore not an export +# anyone would wait for; its intra AU is a stateless free function that fans out +# across cores at 4.30 fps for the same picture, which is the export this +# project offers -- an intraframe master, ProRes-shaped, large files and all. +# Built from `vendor/oxideav-h265`; see the note in the workspace manifest. +oxideav-h265 = { path = "../../vendor/oxideav-h265" } [dev-dependencies] # The still-image suite compares what the timeline shows against the file's own diff --git a/crates/engine/src/audio.rs b/crates/engine/src/audio.rs index 483b7f9..a705a26 100644 --- a/crates/engine/src/audio.rs +++ b/crates/engine/src/audio.rs @@ -6,7 +6,9 @@ //! it always has -- that path also yields the raw access units the export //! copies, which is the only reason it is kept separate -- and a standalone //! audio file (`crate::is_audio`: mp3, wav, flac, ogg, ALAC, ADTS) goes through -//! symphonia's own format probe. An mp4's **AC-3** track is the third: the same +//! symphonia's own format probe, as does the AAC track of a **Matroska** file: +//! same reader, `mkv` instead of `isomp4`, and a 5.1 film soundtrack folded to +//! stereo on the way out ([`SymDecoder`]). An mp4's **AC-3** track is the third: the same //! sample tables, decoded by `oxideav-ac3` and downmixed to stereo by the //! decoder itself, which is what lets a 5.1 BluRay remux play on a stereo //! timeline. Everything downstream of [`Track`] sees the @@ -48,6 +50,7 @@ use symphonia_core::units; use symphonia_core::units::{Time, TimeBase}; use crate::eq::{EqParams, EqState}; +use crate::limiter::{Limiter, LimiterState}; /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.) @@ -264,14 +267,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()?, @@ -282,7 +294,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 @@ -438,11 +450,41 @@ impl AudioSession { lanes: &[Vec<(Option, f64, f64)>], eqs: &[Vec>], speeds: &[Vec>], + ) -> crate::Result)>> { + Self::open_mixed_streams_master(sources, lanes, eqs, speeds, &[], Limiter::default()) + } + + /// [`open_mixed_streams_speed`](Self::open_mixed_streams_speed) with the two + /// settings that belong to the *mix* rather than to a clip: what each lane + /// is turned up or down by on its way into the sum (`gains[i]`, an + /// amplitude, [`crate::Project::audio_gains`] builds it) and the master + /// limiter the sum comes out through. + /// + /// Both live at the sum and nowhere else, which is what makes a lane volume + /// a *lane* volume and a limiter a master one: a gain applied per segment + /// would have to agree with itself across a lane's cuts, and a limiter + /// applied per lane would pump each lane against the others. A short or + /// empty gain list means the rest play as they are, exactly as a short eq + /// list means flat. + /// + /// Flat settings take the same path the mixer always took, down to the bit: + /// one lane at unity with the limiter off is still `open_multi_streams` + /// verbatim, with no mixer thread at all. A lane that is *not* at unity, or + /// a limiter that is on, is what puts a single-lane timeline through the + /// mixer -- a sum of one, which is where both settings live. + pub fn open_mixed_streams_master( + sources: &[(PathBuf, usize)], + lanes: &[Vec<(Option, f64, f64)>], + eqs: &[Vec>], + speeds: &[Vec>], + gains: &[f32], + limiter: Limiter, ) -> crate::Result)>> { let [first, rest @ ..] = lanes else { return Ok(None); }; - if rest.is_empty() { + let mastered = limiter.is_active() || gains.iter().any(|&g| g != 1.0); + if rest.is_empty() && !mastered { let flat = Vec::new(); let plain = Vec::new(); return Self::open_multi_streams_speed( @@ -455,8 +497,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( @@ -471,12 +514,20 @@ impl AudioSession { meta = Some(lane_meta); rxs.push(rx); } - let meta = meta.expect("at least two lanes opened above"); + let meta = meta.expect("at least one lane opened above"); let (tx, rx) = sync_channel(32); let channels = usize::from(meta.channels); + // One per lane, in the lanes' own order, padded with unity: a short + // list is "as it is from here on", the eq list's rule. + let mut gains = gains.to_vec(); + gains.resize(lanes.len(), 1.0); + // Built here, off the thread that will run it, where the rate is known. + let limiter = limiter + .is_active() + .then(|| LimiterState::new(&limiter, meta.sample_rate, channels)); thread::Builder::new() .name("audio-mix".into()) - .spawn(move || mix(&rxs, channels, &tx))?; + .spawn(move || mix(&rxs, channels, &gains, limiter, &tx))?; Ok(Some((meta, rx))) } @@ -486,24 +537,24 @@ impl AudioSession { /// -- nothing to tell the user there. Header only, and only worth calling /// once the open has already returned no audio. pub fn unsupported(path: impl AsRef) -> crate::Result> { - // Matroska: the demuxer reads its picture and its AC-3 sound, so a file - // whose audio is in any other codec is told so by name rather than - // playing silent with no reason given. A Matroska file with no audio - // track at all returns `None` here like any other silent file. + // Matroska: what symphonia reads out of one ([`Track::open`]) plus the + // AC-3 and E-AC-3 whose blocks are handed to the Dolby decoder + // ([`MkvAc3Track`]); everything else -- Opus, DTS, which no decoder here + // has at any version -- is named rather than left playing silent with no + // reason given. A Matroska file with no audio track at all returns + // `None` here like any other silent file. if crate::demux::is_matroska(path.as_ref()) { let Some(codec) = crate::demux::matroska_audio_codec(path.as_ref())? else { return Ok(None); }; - // ...except AC-3 and E-AC-3, which are read out of the blocks - // themselves now ([`MkvAc3Track`]). If one of those still came up - // silent it is the track that could not be read, and the reader's - // own words -- a laced block, an unreadable syncframe -- are the - // ones worth showing. + // An AC-3 track that came up silent all the same is one that could + // not be read -- a laced block, an unreadable syncframe -- and the + // reader's own words are the ones worth showing. return Ok(Some(match MkvAc3Track::open(path.as_ref()) { Ok(Some(_)) => return Ok(None), - Ok(None) => { - format!("{codec} audio in a Matroska file is not wired to the decoder yet") - } + Ok(None) => format!( + "the {codec} track of this Matroska file cannot be decoded (AAC and AC-3 only)" + ), Err(e) => format!("the {codec} track of this Matroska file cannot be decoded: {e}"), })); } @@ -552,26 +603,36 @@ impl AudioSession { /// and an ALAC `.m4a` only half is. pub fn probe_streams(path: impl AsRef) -> crate::Result> { let path = path.as_ref(); - // A Matroska file offers the one AC-3 / E-AC-3 track [`MkvAc3Track`] - // reads, in the shape it decodes to (stereo, per the §7.8 downmix), and - // nothing else: a stream nothing can open is not one to offer, so an - // mkv whose sound is in any other codec still lists as the silent - // source it currently is. + // A Matroska file has exactly one readable audio stream here -- the + // reader's default track ([`SymTrack::open`]), or the AC-3 / E-AC-3 one + // symphonia has no decoder for ([`MkvAc3Track`]) -- so it lists like a + // standalone audio file rather than like an mp4, and one with no + // readable track at all lists as the silent source it is. if crate::demux::is_matroska(path) { - return Ok(MkvAc3Track::open(path) - .ok() - .flatten() - .map(|track| { - vec![StreamInfo { - index: 0, - codec: if track.mkv.codec == "eac3" { "e-ac-3" } else { "ac-3" }.into(), - channels: track.channels, - sample_rate: track.sample_rate, - lang: None, - decodable: matches!(track.channels, 1 | 2), - }] - }) - .unwrap_or_default()); + // The AC-3 row describes what the decoder *emits*, which is the + // stereo the §7.8 downmix hands the timeline, not the 5.1 the file + // carries -- exactly as the mp4 AC-3 rows do. + if let Ok(Some(track)) = MkvAc3Track::open(path) { + return Ok(vec![StreamInfo { + index: 0, + codec: if track.mkv.codec == "eac3" { "e-ac-3" } else { "ac-3" }.into(), + channels: track.channels, + sample_rate: track.sample_rate, + lang: None, + decodable: matches!(track.channels, 1 | 2), + }]); + } + let Ok(track) = SymTrack::open(path) else { + return Ok(Vec::new()); + }; + return Ok(vec![StreamInfo { + index: 0, + codec: track.codec.into(), + channels: track.channels, + sample_rate: track.sample_rate, + lang: None, + decodable: matches!(track.channels, 1 | 2) && track.decoder().is_ok(), + }]); } if crate::is_audio(path) { let track = SymTrack::open(path)?; @@ -668,8 +729,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 (no pure-Rust AAC encoder exists). + /// 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 @@ -798,8 +860,9 @@ impl AudioSession { } /// One AAC-LC access unit of silence, for the gaps in an exported timeline — -/// the export copies packets and has no AAC encoder, so the only silence it can -/// write is one spelled out by hand. +/// this is the *copy* path, which never encodes anything, so the only silence it +/// can write is one spelled out by hand. (The re-encode path next door has a +/// real encoder and needs none of this: its gaps are zero samples.) /// /// It is the shortest legal `raw_data_block` there is: one element carrying /// `max_sfb = 0`, which is "no scalefactor bands", which is a frame with no @@ -844,30 +907,52 @@ fn source_at<'a>( /// A source's track for the *copy* path, which needs raw AAC access units. /// -/// An mp3, a wav, a flac — anything the export cannot copy — is refused here by -/// name and by format rather than exported silent or, worse, exported as noise: -/// there is no AAC encoder in this project (see [`AudioSession::copy_segments`]), -/// so a timeline carrying one of those simply cannot become an mp4 today. The -/// wording is what a front-end shows. +/// An mp3, a wav, a flac — anything this cannot copy — is an `Err` here, by name +/// and by format. That is no longer the end of the road: `export::copy_audio` +/// takes it as the answer "not copyable" and decodes and re-encodes the timeline +/// instead, so these words are a fallback's reason rather than a user's refusal. +/// They are still worded for a person, because a caller with no encoder to fall +/// back on shows them verbatim. /// /// `Ok(None)` for a file with no audio at all, which is a silent export. fn copy_track(path: &Path, stream: usize) -> crate::Result> { match Track::open(path, stream)? { None => Ok(None), Some(Track::Aac(track)) => Ok(Some(track)), + // A Matroska source gets its own words: its packets *are* AAC, so + // "export needs AAC audio today" would read as a contradiction. What + // they are not is packets of an mp4 sample table, which is what the + // copy walks. The export decodes such a source and encodes it again + // rather than showing this, so a film's sound reaches an mp4 either way; + // the words stay for a caller that copies and cannot re-encode. + // + // ponytail: the ceiling is the copy path being written against the mp4 + // reader, not anything about the bytes. Upgrade path is a + // `copy_segments` that walks a Matroska track, which would make this a + // copy again instead of a re-encode. + Some(Track::Sym(_)) if crate::demux::is_matroska(path) => Err(format!( + "{}'s sound is AAC inside a Matroska file, which no packet copy reaches: \ + a copy walks an mp4's own sample table. It is decoded and encoded again \ + instead", + path.file_name() + .unwrap_or(path.as_os_str()) + .to_string_lossy(), + ) + .into()), Some(Track::Sym(track)) => Err(uncopyable(path, track.codec)), // Decoded, never copied: an AC-3 syncframe is not something an `mp4a` - // sample table can hold, and there is no AAC encoder here to turn it - // into one. A WAV/FLAC export of the same timeline decodes fine. + // sample table can hold. The export decodes it and encodes AAC, exactly + // as it does for every other source no copy reaches. Some(Track::Ac3(_) | Track::Mkv(_)) => Err(uncopyable(path, "AC-3")), } } -/// The one wording for "this source's audio cannot be copied into an mp4", -/// shared by every format that cannot be: a front-end shows it verbatim. +/// The one wording for "this source's audio cannot be *copied* into an mp4", +/// shared by every format that cannot be. What the export does about it is +/// decode and re-encode; this is the reason it had to. fn uncopyable(path: &Path, codec: &str) -> crate::Error { format!( - "export needs AAC audio today; {} is {codec}", + "a packet copy needs AAC in an mp4; {} is {codec}", path.file_name() .unwrap_or(path.as_os_str()) .to_string_lossy(), @@ -902,18 +987,26 @@ impl Track { /// has exactly one, so any `stream` above 0 there is a promise the file /// cannot keep — an `Err`, the same as naming a stream an mp4 does not have. fn open(path: &Path, stream: usize) -> crate::Result> { - // A Matroska file's sound reaches neither mp4 reader: its AC-3 and - // E-AC-3 tracks come out of the blocks themselves and everything else - // in one is still a silent source -- which `AudioSession::unsupported` - // puts into words for the user. A track that *is* AC-3 and will not - // open (a laced block, an unreadable syncframe) stays a silent source - // too rather than failing the import: an mkv has never been refused - // over its sound, and `unsupported` says what went wrong. + // A Matroska file goes to symphonia, whose `mkv` reader is the one thing + // here that reads its packets -- neither mp4 reader can open the file at + // all -- except for the two codecs symphonia has no decoder for at any + // version and this project does: AC-3 and E-AC-3 are handed to the Dolby + // decoder straight out of the blocks ([`MkvAc3Track`]). Sound neither + // one can decode (Opus, DTS) leaves the source the silent one it always + // was, which `AudioSession::unsupported` puts into words, rather than + // failing the import of a file whose picture is fine -- and so does an + // AC-3 track that will not open, a laced block say. if crate::demux::is_matroska(path) { - return Ok((stream == 0) - .then(|| MkvAc3Track::open(path).ok().flatten()) - .flatten() - .map(Self::Mkv)); + if stream > 0 { + return Err(format!("{}: audio stream {stream} of 1 stream", path.display()).into()); + } + if let Ok(Some(track)) = MkvAc3Track::open(path) { + return Ok(Some(Self::Mkv(track))); + } + return Ok(SymTrack::open(path) + .ok() + .filter(|t| t.decoder().is_ok()) + .map(Self::Sym)); } let audio_file = crate::is_audio(path); // Ahead of the AAC reader, because that one answers "not AAC" for a @@ -1040,7 +1133,12 @@ struct SymTrack { reader: Box, track_id: u32, sample_rate: u32, + /// What reaches the timeline: the file's own layout, or 2 for a 5.1 track, + /// which is folded down by [`SymDecoder`] exactly as the AC-3 reader's + /// decoder folds its own. channels: u16, + /// What the decoder emits, which is what the fold reads. + source_channels: u16, /// Frames per channel of audible audio, `None` when the header does not say. total_samples: Option, /// Encoder delay: the same role [`AacTrack::priming`] plays, taken from the @@ -1095,7 +1193,11 @@ impl SymTrack { reader, track_id, sample_rate, - channels, + // 5.1 arrives as a stereo source, whatever it was stored as; every + // other layout is passed through and refused above stereo by + // [`Track::channels`], where it always was. + channels: if channels == 6 { 2 } else { channels }, + source_channels: channels, total_samples: num_frames, priming: u64::from(delay.unwrap_or(0)), time_base, @@ -1106,9 +1208,28 @@ impl SymTrack { /// A fresh decoder: seeking mid-stream leaves state that belongs to the /// packets we skipped, exactly as on the AAC path. - fn decoder(&self) -> crate::Result> { - Ok(symphonia::default::get_codecs() - .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?) + /// + /// Which decoder is not the caller's business, and it is not always + /// symphonia's: its AAC decoder refuses anything wider than stereo outright + /// (`aac/mod.rs:93`, "aac: aac too complex"), which is exactly the 5.1 track + /// of a film in an mkv, so that one goes to `rusty_aac` instead. + fn decoder(&self) -> crate::Result { + let fold = self.source_channels != self.channels; + if self.params.codec == CODEC_ID_AAC && self.source_channels > 2 { + let asc = self + .params + .extra_data + .as_deref() + .ok_or("a multichannel AAC track with no AudioSpecificConfig")?; + let decoder = rusty_aac::AacDecoder::with_config_bytes(asc) + .map_err(|e| format!("multichannel AAC decoder init failed: {e}"))?; + return Ok(SymDecoder::Aac(Box::new(decoder), fold)); + } + Ok(SymDecoder::Sym( + symphonia::default::get_codecs() + .make_audio_decoder(&self.params, &AudioDecoderOptions::default())?, + fold, + )) } /// `secs` on this source's audible timeline into media samples (priming @@ -1124,6 +1245,65 @@ impl SymTrack { } } +/// One packet in, interleaved f32 out — whichever library did the decoding, and +/// already folded to the layout [`SymTrack::channels`] promised. The flag is +/// that fold: `true` for a 5.1 track, and there is nothing else it can be. +enum SymDecoder { + Sym(Box, bool), + /// Boxed because the decoder carries its own IMDCT tables and this enum is + /// moved into the worker. + Aac(Box, bool), +} + +impl SymDecoder { + fn decode(&mut self, packet: &Packet, out: &mut Vec) -> crate::Result<()> { + match self { + Self::Sym(decoder, fold) => { + decoder.decode(packet)?.copy_to_vec_interleaved::(out); + fold_5_1(out, *fold); + } + Self::Aac(decoder, fold) => { + let pcm = decoder + .decode(&packet.data, None) + .map_err(|e| format!("AAC decode failed: {e}"))?; + *out = pcm.samples; + fold_5_1(out, *fold); + } + } + Ok(()) + } +} + +/// 5.1 down to stereo, in place. ITU-R BS.775: the centre and the surround of +/// each side join that side at -3 dB, and the LFE is dropped -- it carries no +/// programme a stereo pair could put anywhere. Both outputs are divided by the +/// sum of their own coefficients, so a source at full scale cannot come out +/// clipped; that is what every player does by default. +/// +/// The layout is FL, FR, FC, LFE, BL, BR, which is what symphonia's decoders +/// and `rusty_aac` both hand back (the latter reorders AAC's own C, L, R, Ls, +/// Rs, LFE element order into it: `decode.rs:779`). +/// +/// ponytail: that normalisation costs 7.7 dB against what ffmpeg's `-ac 2` hands +/// out, which does not normalise and can overload -- so a film plays quieter +/// here than in a player beside it. It is the loudness the AC-3 5.1 path already +/// has (measured within 1.3 dB), so the two agree; the upgrade path is a +/// limiter on the output, at which point the coefficients can go back to 1.0. +fn fold_5_1(samples: &mut Vec, fold: bool) { + if !fold { + return; + } + const CENTRE: f32 = std::f32::consts::FRAC_1_SQRT_2; + const NORM: f32 = 1.0 / (1.0 + 2.0 * CENTRE); + for frame in 0..samples.len() / 6 { + let [fl, fr, fc, _lfe, bl, br] = <[f32; 6]>::try_from(&samples[frame * 6..frame * 6 + 6]) + .expect("six samples of a 5.1 frame"); + samples[2 * frame] = (fl + CENTRE * (fc + bl)) * NORM; + samples[2 * frame + 1] = (fr + CENTRE * (fc + br)) * NORM; + } + samples.truncate(samples.len() / 6 * 2); +} + /// One source's AC-3 track: the same mp4 sample tables the AAC track is read /// from, decoded through `oxideav-ac3` and **downmixed to stereo by the decoder /// itself** (ATSC A/52 §7.8, `channels: Some(2)`), because one output device and @@ -1866,7 +2046,13 @@ struct Worker { /// The accumulator is reused across turns; the one allocation per chunk is the /// buffer the channel takes ownership of, and none of this is the RT path (the /// device callback reads the ring the feeder has already filled). -fn mix(rxs: &[Receiver], channels: usize, tx: &SyncSender) { +fn mix( + rxs: &[Receiver], + channels: usize, + gains: &[f32], + mut limiter: Option, + tx: &SyncSender, +) { let mut pending: Vec> = rxs.iter().map(|_| Vec::new()).collect(); let mut live: Vec = rxs.iter().map(|_| true).collect(); // Numbering follows lane 0, whose first chunk says where it starts. @@ -1901,11 +2087,31 @@ fn mix(rxs: &[Receiver], channels: usize, tx: &SyncSender= seg.media_end { return true; // segment done, on to the next one } - let buf = match decoder.decode(&packet) { - Ok(buf) => buf, - Err(e) => { - eprintln!("audio decode error at sample {pos}: {e}"); - return true; - } - }; - buf.copy_to_vec_interleaved::(&mut interleaved); + if let Err(e) = decoder.decode(&packet, &mut interleaved) { + eprintln!("audio decode error at sample {pos}: {e}"); + return true; + } let next = pos + (interleaved.len() / channels) as u64; // Reborrowed per packet: the filter memory has to carry across the // packet boundary, so this is one `EqState` for the whole segment. @@ -2343,7 +2545,43 @@ fn run_sym( #[cfg(test)] mod tests { - use super::{PRE_ROLL, SAMPLES_PER_PACKET, packet_at, packet_run}; + use super::{PRE_ROLL, SAMPLES_PER_PACKET, fold_5_1, packet_at, packet_run}; + + /// The 5.1 fold: each side keeps its own front channel, takes the centre + /// and its own surround at -3 dB, drops the LFE, and comes out unable to + /// clip a full-scale source. The channel order is FL, FR, FC, LFE, BL, BR. + #[test] + fn five_one_folds_to_stereo_without_clipping() { + // One frame per channel at full scale, one channel at a time. + for (channel, (left, right)) in [ + (0, (1.0, 0.0)), // FL + (1, (0.0, 1.0)), // FR + (2, (std::f32::consts::FRAC_1_SQRT_2, std::f32::consts::FRAC_1_SQRT_2)), // FC + (3, (0.0, 0.0)), // LFE, dropped + (4, (std::f32::consts::FRAC_1_SQRT_2, 0.0)), // BL + (5, (0.0, std::f32::consts::FRAC_1_SQRT_2)), // BR + ] { + let mut frame = vec![0.0f32; 6]; + frame[channel] = 1.0; + fold_5_1(&mut frame, true); + let norm = 1.0 / (1.0 + 2.0 * std::f32::consts::FRAC_1_SQRT_2); + assert_eq!(frame.len(), 2, "one 5.1 frame is one stereo frame"); + assert!((frame[0] - left * norm).abs() < 1e-6, "ch{channel}: {frame:?}"); + assert!((frame[1] - right * norm).abs() < 1e-6, "ch{channel}: {frame:?}"); + } + // Every channel at once is what a normalised fold exists for. + let mut loud = vec![1.0f32; 12]; + fold_5_1(&mut loud, true); + assert_eq!(loud.len(), 4); + assert!( + loud.iter().all(|s| (*s - 1.0).abs() < 1e-6), + "full scale in, full scale out, never past it: {loud:?}" + ); + // A track that is not 5.1 is handed over untouched. + let mut stereo = vec![0.5f32, -0.5]; + fold_5_1(&mut stereo, false); + assert_eq!(stereo, [0.5, -0.5]); + } /// A real AAC track: one stts entry, N packets of 1024. fn aac(count: u32) -> impl IntoIterator { diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 5a8b170..c26256e 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::thread; @@ -25,6 +25,106 @@ pub struct Frame { pub bgra: Vec, } +/// Which decoder a source is really running on. Read-only introspection: it +/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose -- +/// a hardware session that opened and then failed before its first picture +/// falls back to software and this says so, because it is written where the +/// fallback happens rather than where it was hoped for. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Backend { + /// The worker has not reached its decoder yet: the plugin's VA-API init is + /// ~90 ms, and this is what a caller reads in that window. + #[default] + Opening, + /// The VA-API plugin (`libengine_hw.so`). + Hardware, + /// `rusty_h264`, in this process. + Software, + /// A still image: one `image` decode, no stream and no decoder to pick. + Still, + /// A gap: black frames, nothing decoded at all. + Gap, +} + +impl Backend { + /// Short enough for a library row and a transport line. + pub fn label(self) -> &'static str { + match self { + Self::Opening => "opening", + Self::Hardware => "HW", + Self::Software => "SW", + Self::Still => "still", + Self::Gap => "gap", + } + } + + fn code(self) -> u8 { + match self { + Self::Opening => 0, + Self::Hardware => 1, + Self::Software => 2, + Self::Still => 3, + Self::Gap => 4, + } + } + + fn from_code(code: u8) -> Self { + match code { + 1 => Self::Hardware, + 2 => Self::Software, + 3 => Self::Still, + 4 => Self::Gap, + _ => Self::Opening, + } + } +} + +/// Where a worker publishes the decoder it opened, for whoever holds the other +/// end of its channel. One atomic byte, written once at open (and once more if +/// hardware hands the range back to software), read whenever a caller repaints +/// -- never per frame on either side. +#[derive(Clone, Default)] +pub struct BackendCell(Arc); + +impl BackendCell { + fn new(backend: Backend) -> Self { + Self(Arc::new(AtomicU8::new(backend.code()))) + } + + fn set(&self, backend: Backend) { + self.0.store(backend.code(), Ordering::Relaxed); + } + + pub fn get(&self) -> Backend { + Backend::from_code(self.0.load(Ordering::Relaxed)) + } +} + +/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`] +/// decides it: the same `VE_SW` pin and the same plugin probe against this very +/// file. What lets a front-end name the decoder *before* anything plays. +/// +/// The codec is `None` for a still image, which has no coded stream. A stream +/// no decoder here can take is an `Err` naming the plugin, exactly as opening +/// it would be -- the same refusal, one VA-API init earlier. +/// +/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per +/// file, off a render thread, and keep the answer. +pub fn probe(path: &Path) -> crate::Result<(Option, Backend)> { + if crate::is_image(path) { + return Ok((None, Backend::Still)); + } + let path = path.to_path_buf(); + let (meta, _demuxer) = Demuxer::open(&path)?; + if open_hw(&path, 0).is_some() { + return Ok((Some(meta.codec), Backend::Hardware)); + } + if meta.codec != Codec::H264 { + return Err(meta.codec.needs_plugin().into()); + } + Ok((Some(meta.codec), Backend::Software)) +} + /// A running decode worker: the flag that stops it, and the handle to wait on. /// /// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize` @@ -85,6 +185,9 @@ impl Drop for Worker { pub(crate) struct FrameStream { pub(crate) frames: Receiver, pub(crate) worker: Worker, + /// What this stream's pictures are being decoded by. Dropped last and read + /// by the caller, so it outlives nothing and blocks nothing. + pub(crate) backend: BackendCell, } pub struct DecodeSession; @@ -152,6 +255,7 @@ impl DecodeSession { cancel, handle: None, }, + backend: BackendCell::new(Backend::Gap), }; } let worker_cancel = Arc::clone(&cancel); @@ -180,6 +284,7 @@ impl DecodeSession { FrameStream { frames: rx, worker: Worker { cancel, handle }, + backend: BackendCell::new(Backend::Gap), } } @@ -209,6 +314,7 @@ impl DecodeSession { cancel, handle: None, }, + backend: BackendCell::new(Backend::Still), }); } // The one conversion, on this thread: it is a few milliseconds and the @@ -245,6 +351,7 @@ impl DecodeSession { Ok(FrameStream { frames: rx, worker: Worker { cancel, handle }, + backend: BackendCell::new(Backend::Still), }) } @@ -285,6 +392,9 @@ impl DecodeSession { // decoder run ahead of the display without limit. let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); + // Written by the worker below the moment it knows, so a caller reading + // it sees what opened rather than what was hoped for. + let backend = BackendCell::default(); if end_frame <= start_frame { // Nothing to decode: dropping `tx` here closes the channel cleanly, // so the caller sees an immediate end of stream rather than an error. @@ -296,10 +406,12 @@ impl DecodeSession { cancel, handle: None, }, + backend, }, )); } let worker_cancel = Arc::clone(&cancel); + let worker_backend = backend.clone(); let handle = thread::Builder::new() .name("decode".into()) .spawn(move || { @@ -320,6 +432,7 @@ impl DecodeSession { return; } eprintln!("decode backend: hardware (VA-API plugin)"); + worker_backend.set(Backend::Hardware); if run_hw(hw, &tx, start_frame, end_frame, &mut render, &worker_cancel) { return; } @@ -334,6 +447,7 @@ impl DecodeSession { return; } eprintln!("decode backend: software (rusty_h264)"); + worker_backend.set(Backend::Software); run( demuxer, tx, @@ -351,6 +465,7 @@ impl DecodeSession { cancel, handle: Some(handle), }, + backend, }, )) } diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 144ed01..7e7c8d0 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -6,7 +6,11 @@ //! Two containers, one interface: mp4 through the `mp4` crate, Matroska //! (`.mkv`/`.webm`) walked here as EBML. AV1 is why the second one exists -- //! `mp4 0.14` has no `av01` sample entry at all, and AV1 ships in Matroska in -//! practice. +//! practice -- and HEVC rides the same walk, because that is the other codec a +//! `.mkv` off a disc arrives in. An AV1 *mp4* is read here too, its sample entry +//! picked out of the `stsd` by hand for the same reason `mux` writes it by hand: +//! this project exports one, and a file this cannot reopen is a file it had no +//! business writing. use std::fs::File; use std::io::{BufReader, Read, Seek, SeekFrom}; @@ -97,12 +101,24 @@ impl Demuxer { Self::Mkv(d) => d.seek_to_sync_at_or_before(frame), } } + + /// Bits per luma sample the stream is coded at: 8 for everything but an + /// HEVC Main 10 track, which decodes into a P010 surface rather than an + /// NV12 one. Not part of [`VideoMeta`] because nothing above the plugin has + /// a use for it -- what comes out of the read-back is 8-bit either way. + pub fn bit_depth(&self) -> u8 { + match self { + Self::Mp4(d) => d.bit_depth, + Self::Mkv(d) => d.bit_depth, + } + } } -/// Whether a path names a Matroska file, which is where AV1 arrives. Extension -/// only, like [`crate::is_audio`]: the demuxer is what really decides, but the -/// audio path has to know before it opens anything that this file's sound is -/// not one it reads (see [`crate::audio::AudioSession::unsupported`]). +/// Whether a path names a Matroska file, which is where AV1 arrives and where a +/// film off a disc arrives as HEVC. Extension only, like [`crate::is_audio`]: +/// the demuxer is what really decides, but the audio path has to know before it +/// opens anything that this file's sound is read by symphonia's `mkv` reader +/// and not by either mp4 one (see [`crate::audio::Track::open`]). pub fn is_matroska(path: &Path) -> bool { path.extension() .and_then(|e| e.to_str()) @@ -118,9 +134,9 @@ pub struct Mp4Demuxer { /// (`audio::priming_samples`), and frame indices count from there. first_sample: u32, codec: Codec, - /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), - /// re-injected ahead of every sync sample. Empty for VP9, which carries no - /// out-of-band parameter sets. + /// Annex-B parameter sets (SPS+PPS for H.264, VPS+SPS+PPS for HEVC), or + /// the sequence header OBU for AV1, re-injected ahead of every sync sample. + /// Empty for VP9, which carries no out-of-band parameter sets. parameter_sets: Vec, /// Bytes of the NAL length prefix each sample is written with, off `avcC` /// or `hvcC`. Unused by VP9. @@ -129,6 +145,8 @@ pub struct Mp4Demuxer { /// at all, i.e. every sample is a sync sample. sync_samples: Vec, next_sample: u32, + /// Bits per luma sample; see [`Demuxer::bit_depth`]. + bit_depth: u8, } impl Mp4Demuxer { @@ -145,20 +163,26 @@ impl Mp4Demuxer { Ok(MediaType::H265) => Some((t, Codec::Hevc)), Ok(MediaType::VP9) => Some((t, Codec::Vp9)), // `mp4 0.14`'s `stsd` parser knows only a `hev1` sample entry - // (`stsd.rs:107`), so an `hvc1`-tagged HEVC track -- what Apple - // and ffmpeg's mov muxer write in practice -- reports no media - // type at all, and the file used to read back as having no - // video. Its sample tables (`stts`/`stsz`/`stsc`/`stss`) are - // parsed regardless of the entry the crate dropped, so only the - // fourcc has to be read here by hand. hvc1 differs from hev1 in - // that the parameter sets may not repeat in-band, which costs - // nothing: they are re-injected out of `hvcC` ahead of every - // sync sample either way. - _ => (matches!(t.track_type(), Ok(TrackType::Video)) - && sample_entry(path, t.track_id()).is_ok_and(|(kind, _)| &kind == b"hvc1")) - .then_some((t, Codec::Hevc)), + // (`stsd.rs:107`) and no `av01` at all, so an `hvc1`-tagged HEVC + // track -- what Apple and ffmpeg's mov muxer write in practice + // -- and every AV1 track report no media type, and such a file + // used to read back as having no video. Its sample tables + // (`stts`/`stsz`/`stsc`/`stss`) are parsed regardless of the + // entry the crate dropped, so only the fourcc has to be read + // here by hand. hvc1 differs from hev1 in that the parameter + // sets may not repeat in-band, which costs nothing: they are + // re-injected out of `hvcC` ahead of every sync sample either + // way, exactly as an AV1 sequence header is out of `av1C`. + _ => matches!(t.track_type(), Ok(TrackType::Video)) + .then(|| sample_entry(path, t.track_id()).ok()) + .flatten() + .and_then(|(kind, _)| match &kind { + b"hvc1" => Some((t, Codec::Hevc)), + b"av01" => Some((t, Codec::Av1)), + _ => None, + }), }) - .ok_or("no H.264, HEVC or VP9 video track in file")?; + .ok_or("no H.264, HEVC, VP9 or AV1 video track in file")?; let (track, codec) = track; let track_id = track.track_id(); @@ -172,6 +196,7 @@ impl Mp4Demuxer { let first_sample = first_frame_sample(stts_pairs(track), trim_ticks(track)); let mut parameter_sets = Vec::new(); let mut nal_length = 4; + let mut bit_depth = 8; match codec { Codec::H264 => { let avcc = &track @@ -195,14 +220,24 @@ impl Mp4Demuxer { // start without are read out of the file by hand. Codec::Hevc => { let hvcc = hvcc_record(path, track_id)?; - let (len, sets) = parse_hvcc(&hvcc)?; + let (len, sets, depth) = parse_hvcc(&hvcc)?; nal_length = len; parameter_sets = sets; + bit_depth = depth; } - // No parameter sets: a VP9 sample is self-contained, and AV1 never - // reaches this arm at all -- `mp4 0.14` knows no `av01` sample - // entry, so AV1 only ever arrives through [`MkvDemuxer`]. - Codec::Vp9 | Codec::Av1 => {} + // The sequence header OBU out of `av1C`, re-injected ahead of every + // sync sample exactly as [`MkvDemuxer`] does it off `CodecPrivate` -- + // the same record in the same bytes, which is what makes an AV1 mp4 + // written here and an AV1 Matroska written here one stream in two + // containers. + Codec::Av1 => { + let (_, entry) = sample_entry(path, track_id)?; + let av1c = child(entry.get(78..).unwrap_or_default(), b"av1C") + .ok_or("no av1C box in the AV1 sample entry")?; + parameter_sets = parse_av1c(av1c)?; + } + // No parameter sets: a VP9 sample is self-contained. + Codec::Vp9 => {} } let sync_samples = track .trak @@ -235,6 +270,7 @@ impl Mp4Demuxer { nal_length, sync_samples, next_sample, + bit_depth, }, )) } @@ -255,6 +291,16 @@ impl Mp4Demuxer { if self.codec == Codec::Vp9 { return Ok(Some(sample.bytes.to_vec())); } + // An AV1 one is a whole temporal unit, likewise unframed -- with the + // sequence header in front of it where a decoder may start. + if self.codec == Codec::Av1 { + let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len()); + if sample.is_sync { + au.extend_from_slice(&self.parameter_sets); + } + au.extend_from_slice(&sample.bytes); + return Ok(Some(au)); + } let mut au = Vec::with_capacity(self.parameter_sets.len() + sample.bytes.len() + 16); if sample.is_sync { @@ -294,7 +340,7 @@ struct Block { ts: i64, } -/// AV1 out of a Matroska file (`.mkv`/`.webm`). +/// AV1 or HEVC out of a Matroska file (`.mkv`/`.webm`). /// /// The whole segment is walked once at open -- element *headers* only, the block /// payloads are seeked over -- because Matroska carries no sample table: the @@ -303,12 +349,26 @@ struct Block { pub struct MkvDemuxer { file: File, blocks: Vec, + codec: Codec, /// The `av1C` configuration OBUs (the sequence header), re-injected ahead of /// every keyframe exactly as the H.264 parameter sets are. An AV1 stream /// repeats its sequence header at every keyframe anyway, and cros-codecs /// ignores one identical to the sequence in force (`av1.rs:381`), so this is /// free when the encoder already wrote one and load-bearing when it did not. + /// + /// For HEVC this is the Annex-B VPS/SPS/PPS off the `CodecPrivate`, which is + /// an `hvcC` record verbatim -- the same blob, re-injected for the same + /// reason, as the one [`Mp4Demuxer`] carries. config: Vec, + /// Bytes of the NAL length prefix an HEVC block is written with; unused by + /// AV1, whose block is one temporal unit and carries no prefixes. + nal_length: usize, + /// Bits per luma sample; see [`Demuxer::bit_depth`]. + bit_depth: u8, + /// One block's bytes, reused across access units: a 4K HEVC keyframe is a + /// megabyte and it is reframed, not handed over, so the read needs a + /// landing place of its own. + scratch: Vec, next: usize, } @@ -317,13 +377,28 @@ impl MkvDemuxer { let mut file = File::open(path)?; let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; - let (video, _, _) = mkv_tracks(&mut file, segment)?; - let video = video.ok_or( - "no AV1 video track in this Matroska file — AV1 is the only codec read from one", - )?; + let (video, _, other, _) = mkv_tracks(&mut file, segment)?; + let video = match video { + Some(video) => video, + // Named, because "no video track" is a lie about a file that has one + // in a codec this does not read. + None => { + return Err(match other { + Some(codec) => format!( + "{codec} video in a Matroska file is not supported — AV1 and HEVC are" + ), + None => "this Matroska file has no video track".to_string(), + } + .into()); + } + }; let (blocks, span) = mkv_blocks(&mut file, segment, video.number)?; if blocks.is_empty() { - return Err("the AV1 track in this Matroska file has no frames".into()); + return Err(format!( + "the {} track in this Matroska file has no frames", + video.codec.name() + ) + .into()); } // Timing, in this order: what the track declares, then what its own // timestamps say. `DefaultDuration` is nanoseconds and exact -- 33333333 @@ -353,28 +428,44 @@ impl MkvDemuxer { height: video.height, frame_rate, frame_count: blocks.len() as u32, - codec: Codec::Av1, + codec: video.codec, }; Ok(( meta, Self { file, blocks, + codec: video.codec, config: video.config, + nal_length: video.nal_length, + bit_depth: video.bit_depth, + scratch: Vec::new(), next: 0, }, )) } + /// Next access unit in decode order: the block verbatim for AV1, which is + /// one temporal unit already, and Annex-B for HEVC, whose block holds the + /// same length-prefixed NALs an mp4 sample does. fn next_access_unit(&mut self) -> crate::Result>> { let Some(&block) = self.blocks.get(self.next) else { return Ok(None); }; self.next += 1; let head = if block.key { self.config.len() } else { 0 }; - let mut au = vec![0u8; head + block.len]; - au[..head].copy_from_slice(&self.config[..head]); - read_exact_at(&mut self.file, block.at, &mut au[head..])?; + if self.codec == Codec::Av1 { + let mut au = vec![0u8; head + block.len]; + au[..head].copy_from_slice(&self.config[..head]); + read_exact_at(&mut self.file, block.at, &mut au[head..])?; + return Ok(Some(au)); + } + let Self { file, scratch, .. } = self; + scratch.resize(block.len, 0); + read_exact_at(file, block.at, scratch)?; + let mut au = Vec::with_capacity(head + block.len + 16); + au.extend_from_slice(&self.config[..head]); + append_annex_b(&self.scratch, self.nal_length, &mut au)?; Ok(Some(au)) } @@ -395,8 +486,9 @@ impl MkvDemuxer { /// The codec id of `path`'s first audio track (`A_AAC`, `A_OPUS`, ...), or /// `None` for a Matroska file with no sound at all. Header only, and only worth -/// calling once a session has come up silent: no audio track of a Matroska file -/// is decoded yet, so this exists to say which one is being left out. +/// calling once a session has come up silent: a Matroska file's sound is read +/// by symphonia, or by the Dolby decoder where it is AC-3 ([`MkvAudio`]), and +/// this exists to say which codec neither of them took. pub fn matroska_audio_codec(path: &Path) -> crate::Result> { let mut file = File::open(path)?; let end = file.metadata()?.len(); @@ -431,7 +523,7 @@ impl MkvAudio { let mut file = File::open(path)?; let end = file.metadata()?.len(); let segment = mkv_segment(&mut file, end)?; - let (_, audio, timestamp_scale) = mkv_tracks(&mut file, segment)?; + let (_, audio, _, timestamp_scale) = mkv_tracks(&mut file, segment)?; let Some((number, codec)) = audio else { return Ok(None); }; @@ -489,14 +581,17 @@ impl MkvAudio { } } -/// What the `Tracks` element says about the AV1 track. +/// What the `Tracks` element says about the video track. struct MkvVideo { number: u64, width: u32, height: u32, default_duration: Option, timestamp_scale: u64, + codec: Codec, config: Vec, + nal_length: usize, + bit_depth: u8, } // Matroska element IDs, written with the leading length marker they carry in @@ -533,18 +628,20 @@ fn mkv_segment(file: &mut File, end: u64) -> crate::Result<(u64, u64)> { Err("no Segment element: not a Matroska file".into()) } -/// The AV1 video track of `segment`, the number and codec id of its first audio -/// track, and the segment's `TimestampScale` in nanoseconds. The audio pair is -/// what [`MkvAudio`] reads a sound track from and what tells a user why a file -/// with sound plays silent ([`crate::audio::AudioSession::unsupported`]). +/// The video track of `segment`, the number and codec id of its first audio +/// track, the codec id of a video track this cannot read, and the segment's +/// `TimestampScale` in nanoseconds. The audio pair is what [`MkvAudio`] reads a +/// sound track from; it and the other codec id are what tell a user why a file +/// plays silent ([`crate::audio::AudioSession::unsupported`]) or refuses to +/// open at all. /// /// Header only: the walk stops at the first `Cluster`, so this costs a handful /// of seeks whatever the file weighs. fn mkv_tracks( file: &mut File, segment: (u64, u64), -) -> crate::Result<(Option, Option<(u64, String)>, u64)> { - let (mut video, mut audio) = (None, None); +) -> crate::Result<(Option, Option<(u64, String)>, Option, u64)> { + let (mut video, mut audio, mut other) = (None, None, None); let mut timestamp_scale = 1_000_000; let mut at = segment.0; while let Some((id, body, stop)) = ebml_element(file, at, segment.1)? { @@ -564,8 +661,11 @@ fn mkv_tracks( while let Some(e) = ebml_element(file, at, stop)? { if e.0 == TRACK_ENTRY { match mkv_track_entry(file, e.1, e.2, timestamp_scale)? { - (Some(track), _) if video.is_none() => video = Some(track), - (_, Some(track)) if audio.is_none() => audio = Some(track), + MkvEntry::Video(track) if video.is_none() => video = Some(track), + MkvEntry::OtherVideo(codec) if other.is_none() => other = Some(codec), + MkvEntry::Audio(number, codec) if audio.is_none() => { + audio = Some((number, codec)) + } _ => {} } } @@ -576,17 +676,28 @@ fn mkv_tracks( } at = stop; } - Ok((video, audio, timestamp_scale)) + Ok((video, audio, other, timestamp_scale)) +} + +/// What one `TrackEntry` turned out to be. +enum MkvEntry { + Video(MkvVideo), + /// A video track in a codec this does not read, by the name it gives itself. + OtherVideo(String), + /// An audio track: its track number, which is what [`MkvAudio`] indexes the + /// blocks of, and its codec id (`A_AAC`, `A_EAC3`, ...). + Audio(u64, String), + /// Subtitles, buttons: nobody's here. + Other, } -/// One `TrackEntry`: `Some` video only for an 8-bit AV1 track, and the number -/// and codec id of an audio track otherwise. +/// One `TrackEntry`, read for what it is. fn mkv_track_entry( file: &mut File, body: u64, end: u64, timestamp_scale: u64, -) -> crate::Result<(Option, Option<(u64, String)>)> { +) -> crate::Result { let (mut number, mut kind, mut codec, mut default_duration) = (0, 0, String::new(), None); let (mut width, mut height, mut config) = (0, 0, Vec::new()); let mut at = body; @@ -617,21 +728,30 @@ fn mkv_track_entry( at = stop; } // 1 is video, 2 is audio; the rest (subtitles, buttons) are nobody's here. - match (kind, codec.as_str()) { - (1, "V_AV1") => Ok(( - Some(MkvVideo { - number, - width, - height, - default_duration, - timestamp_scale, - config: parse_av1c(&config)?, - }), - None, - )), - (2, _) => Ok((None, Some((number, codec)))), - _ => Ok((None, None)), - } + // A Matroska `CodecPrivate` is the codec's own configuration record -- + // `av1C` for AV1 and an `hvcC` for HEVC, byte for byte the one an mp4 + // sample entry carries, so it parses with the very same reader. + let (codec, nal_length, config, bit_depth) = match (kind, codec.as_str()) { + (1, "V_AV1") => (Codec::Av1, 4, parse_av1c(&config)?, 8), + (1, "V_MPEGH/ISO/HEVC") => { + let (nal_length, sets, bit_depth) = parse_hvcc(&config)?; + (Codec::Hevc, nal_length, sets, bit_depth) + } + (1, _) => return Ok(MkvEntry::OtherVideo(codec)), + (2, _) => return Ok(MkvEntry::Audio(number, codec)), + _ => return Ok(MkvEntry::Other), + }; + Ok(MkvEntry::Video(MkvVideo { + number, + width, + height, + default_duration, + timestamp_scale, + codec, + config, + nal_length, + bit_depth, + })) } /// The configuration OBUs of an `AV1CodecConfigurationRecord` (AV1-ISOBMFF @@ -994,21 +1114,22 @@ pub(crate) fn sample_entry(path: &Path, track_id: u32) -> crate::Result<([u8; 4] } /// HEVCDecoderConfigurationRecord (ISO 14496-15 §8.3.3.1) -> the NAL length -/// prefix width and the VPS/SPS/PPS arrays as one Annex-B blob. -fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec)> { +/// prefix width, the VPS/SPS/PPS arrays as one Annex-B blob, and the luma bit +/// depth the plugin picks its surface pool from. +fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec, u8)> { // 0 configurationVersion .. 21 lengthSizeMinusOne, 22 numOfArrays. let (&flags, &arrays) = rec .get(21) .zip(rec.get(22)) .ok_or("hvcC box shorter than its fixed header")?; - // 17 is bit_depth_luma_minus8 in its low 3 bits: the plugin's NV12 pool and - // its vaGetImage read-back are 8-bit, so a Main 10 stream would decode into - // a surface nothing here can carry -- refused by name instead of shown as - // garbage. Upgrade path: a P010 pool chosen from the stream info. - if rec[17] & 0x7 != 0 { + // 17 is bit_depth_luma_minus8 in its low 3 bits. 8-bit decodes into the + // plugin's NV12 pool and 10-bit (Main 10) into its P010 one; 12-bit has + // neither a pool here nor, on the hardware this was written against, a + // VA-API profile -- refused by name rather than shown as garbage. + let bit_depth = 8 + (rec[17] & 0x7); + if bit_depth > 10 { return Err(format!( - "10-bit HEVC (Main 10) is not supported yet — this file is {}-bit", - 8 + (rec[17] & 0x7) + "{bit_depth}-bit HEVC is not supported — 8- and 10-bit are what the decoder carries" ) .into()); } @@ -1043,7 +1164,7 @@ fn parse_hvcc(rec: &[u8]) -> crate::Result<(usize, Vec)> { if sets.is_empty() { return Err("hvcC box carries no VPS/SPS/PPS".into()); } - Ok((usize::from(flags & 0x3) + 1, sets)) + Ok((usize::from(flags & 0x3) + 1, sets, bit_depth)) } /// Payload of the first top-level box of type `want`, or `None` if the file has @@ -1083,7 +1204,7 @@ fn read_top_level(path: &Path, want: &[u8; 4]) -> crate::Result>> /// The ISO-BMFF boxes in `buf`, as (type, payload). Stops at the first /// malformed header rather than erroring: every caller is looking for one box /// and reports its own absence. -fn boxes(mut buf: &[u8]) -> impl Iterator { +pub(crate) fn boxes(mut buf: &[u8]) -> impl Iterator { std::iter::from_fn(move || { let header: &[u8; 8] = buf.get(..8)?.try_into().ok()?; let (size, header_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) as usize @@ -1148,8 +1269,9 @@ mod tests { rec.extend_from_slice(&2u16.to_be_bytes()); // nalUnitLength rec.extend_from_slice(&[kind << 1, nal]); } - let (len, sets) = parse_hvcc(&rec).unwrap(); + let (len, sets, depth) = parse_hvcc(&rec).unwrap(); assert_eq!(len, 2); + assert_eq!(depth, 8); assert_eq!( sets, [ @@ -1159,11 +1281,16 @@ mod tests { ] ); - // 10-bit is refused by name rather than decoded into an 8-bit surface. + // Main 10 is read, and read as 10-bit: that is what picks the P010 + // surface pool over the NV12 one. let mut main10 = rec.clone(); main10[17] = 0xf8 | 2; - let refused = parse_hvcc(&main10).unwrap_err().to_string(); - assert!(refused.contains("10-bit"), "{refused}"); + assert_eq!(parse_hvcc(&main10).unwrap().2, 10); + // 12-bit has no pool and no profile here, and is refused by name. + let mut main12 = rec.clone(); + main12[17] = 0xf8 | 4; + let refused = parse_hvcc(&main12).unwrap_err().to_string(); + assert!(refused.contains("12-bit"), "{refused}"); // Nothing is read past the end of a truncated box. assert!(parse_hvcc(&rec[..20]).is_err()); assert!(parse_hvcc(&rec[..rec.len() - 1]).is_err()); diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 0d4ef79..52461ef 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1,9 +1,11 @@ //! The project file: a line of text per thing, and nothing else. //! //! ```text -//! edith 8 +//! edith 9 //! playhead 90 //! resolution 1920 1080 +//! fps 30.0 +//! limiter -1.0 on //! source 0 test_av.mp4 //! source 1 /elsewhere/test_av2.mp4 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk @@ -12,8 +14,27 @@ //! audio 1 0 0 120 0 0 0 - fit 1000 //! video 2 120 0 120 1 - - - fill 2000 //! audio 2 +//! gain audio 1 -3.0 //! ``` //! +//! The `fps` line is the rate the timeline was cut at, printed so it reads back +//! bit-exactly. A file without one (every dialect before v9) means "whatever +//! the scaffolding source runs at", which is what such a project always was and +//! is an answer only a project holding a video has +//! ([`crate::PlaybackSession::open_project`]). +//! +//! The `limiter` line is the master limiter over the whole mix +//! ([`crate::limiter`]): its ceiling in dBFS and whether it is in circuit, +//! spelled `on` or `off`. Left out when it is the default, which is off. +//! +//! A `gain` line is `gain `: how loud that whole lane plays, +//! everything on it and every frequency of it -- a different thing from a +//! clip's `eq` line, which is one take and one band. It names its lane the way +//! a clip line does and comes *after* the lanes, because a lane is declared by +//! its clips and a gain declares nothing. Only a lane somebody has turned gets +//! one; the rest are at 0 dB, which is where every lane of every dialect before +//! v9 is. +//! //! The `resolution` line is the **project's** picture size, which is a //! different thing from any source's: media of other sizes are placed on it. //! It belongs once, beside the playhead, and a file without one (every dialect @@ -58,7 +79,10 @@ //! is the only way an empty lane could still be there on the way back. A lane //! number may not skip one of its kind. //! -//! **Version 7** was this without the clip's speed field -- every clip of such +//! **Version 8** was this without the `fps` and `limiter` lines and without +//! the `gain` ones: such a project mixes every lane at unity, limits nothing, +//! and comes back at the rate its scaffolding source runs at. +//! **Version 7** was that without the clip's speed field -- every clip of such //! a project plays at real time, which is the only rate there was. //! **Version 6** was that without the `resolution` line and without the clip's //! fit field -- such a project is the size of its first source and letterboxes @@ -72,9 +96,9 @@ //! `. All six still load -- a v1 file's clips are laid out //! cumulatively and copied onto both lanes as one group each, which is exactly //! what a v1 timeline meant, and an older file simply equalizes and grades -//! nothing, and an older one plays everything at real time -- and saving any of -//! them writes v8. An older reader refuses a newer -//! file by name. +//! nothing, and an older one plays everything at real time, and an older one +//! mixes flat -- and saving any of them writes v9. An older reader refuses a +//! newer file by name. //! //! Text because an edit list is a few integers and a path, and a path is //! *bytes* on this platform -- a JSON string would have to lossily decode one. @@ -102,12 +126,14 @@ use std::path::{Path, PathBuf}; use crate::color::ColorParams; use crate::eq::{Band, BandKind, EqParams}; +use crate::limiter::Limiter; use crate::project::{Clip, Lane, LaneKind, Source, Speed}; use crate::scale::FitPolicy; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. -const MAGIC: &[u8] = b"edith 8"; +const MAGIC: &[u8] = b"edith 9"; +const MAGIC_V8: &[u8] = b"edith 8"; const MAGIC_V7: &[u8] = b"edith 7"; const MAGIC_V6: &[u8] = b"edith 6"; const MAGIC_V5: &[u8] = b"edith 5"; @@ -136,18 +162,37 @@ pub struct Document { /// The project's own picture size. `None` for every dialect before v7 and /// for a v7 file that leaves it out, which both mean "source 0's picture". pub resolution: Option<(u32, u32)>, + /// Every lane's own volume in dB, in the order `lanes` is in and as long as + /// it; `0.0` for a lane nobody has turned, which is every lane of every + /// dialect before v9. + pub gains: Vec, + /// The master limiter. Off for every dialect before v9, and for a v9 file + /// that leaves the line out. + pub limiter: Limiter, + /// The timeline's frame rate. `None` for every dialect before v9 and for a + /// v9 file that leaves it out, which both mean "whatever the scaffolding + /// source runs at" -- the inference a project of nothing but stills and + /// songs has no answer for (see + /// [`crate::PlaybackSession::open_project`]). + pub fps: Option, pub playhead: u32, } /// Writes the project to `path`, atomically. `sources`, `eq` and `color` should -/// already be orphan-free ([`crate::Project::without_orphan_sources`]). +/// already be orphan-free ([`crate::Project::without_orphan_sources`]); +/// `gains` is one dB per lane in the same order the lanes are in +/// ([`crate::Project::lane_gains`]). +#[allow(clippy::too_many_arguments)] pub fn save( path: &Path, sources: &[Source], lanes: &[(LaneKind, Vec)], + gains: &[f32], eq: &[EqParams], color: &[ColorParams], resolution: (u32, u32), + fps: Option, + limiter: Limiter, playhead: u32, ) -> crate::Result<()> { let dir = project_dir(path); @@ -160,7 +205,9 @@ pub fn save( // the second one puts the name itself there. let result = std::fs::File::create(&part) .and_then(|mut f| { - f.write_all(&emit(&dir, sources, lanes, eq, color, resolution, playhead))?; + f.write_all(&emit( + &dir, sources, lanes, gains, eq, color, resolution, fps, limiter, playhead, + ))?; f.sync_all() }) .and_then(|()| std::fs::rename(&part, path)) @@ -190,13 +237,17 @@ fn project_dir(path: &Path) -> PathBuf { dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()) } +#[allow(clippy::too_many_arguments)] fn emit( dir: &Path, sources: &[Source], lanes: &[(LaneKind, Vec)], + gains: &[f32], eq: &[EqParams], color: &[ColorParams], resolution: (u32, u32), + fps: Option, + limiter: Limiter, playhead: u32, ) -> Vec { let mut out = Vec::new(); @@ -204,6 +255,26 @@ fn emit( out.push(b'\n'); out.extend_from_slice(format!("playhead {playhead}\n").as_bytes()); out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes()); + // `{:?}`, the eq table's rule: the rate a timeline was cut at has to read + // back as the very number, or every clip on it lands on another frame. + if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) { + out.extend_from_slice(format!("fps {fps:?}\n").as_bytes()); + } + // Written only when it is not the default, so a project nobody has limited + // is the same bytes it was in v8 bar the version line. + if limiter != Limiter::default() { + out.extend_from_slice( + format!( + "limiter {:?} {}\n", + limiter.ceiling_db, + match limiter.on { + true => "on", + false => "off", + } + ) + .as_bytes(), + ); + } for s in sources { out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes()); escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); @@ -276,6 +347,25 @@ fn emit( ); } } + // After the lanes, not before them: a gain line names a lane that has to be + // there already, and a lane is declared by its own lines. Only the lanes + // somebody has turned get one. + let (mut video, mut audio) = (0, 0); + for ((kind, _), &db) in lanes.iter().zip(gains) { + let (keyword, ord) = match kind { + LaneKind::Video => { + video += 1; + ("video", video) + } + LaneKind::Audio => { + audio += 1; + ("audio", audio) + } + }; + if db != 0.0 { + out.extend_from_slice(format!("gain {keyword} {ord} {db:?}\n").as_bytes()); + } + } out } @@ -289,8 +379,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The dialects that wrote a source line without its stream field. Reading // one is the whole of what "an old project still opens" means here. let streamless = v1 || first == MAGIC_V2; - // The one that carries a per-clip speed... - let v8 = first == MAGIC; + // The one that carries the mix -- lane volumes, the master limiter and the + // rate the timeline was cut at... + let v9 = first == MAGIC; + // ...the ones that carry a per-clip speed... + let v8 = v9 || first == MAGIC_V8; // ...the ones that carry a project resolution and per-clip fit policies... let v7 = v8 || first == MAGIC_V7; // ...the ones that carry colour grades... @@ -322,6 +415,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // Nothing before v7 has a resolution of its own: source 0's picture is // what those projects were, and `None` is how the loader is told so. resolution: None, + // ...and nothing before v9 carries a mix or a rate: every lane at unity, + // no limiter, and the rate inferred from the scaffold as it always was. + gains: Vec::new(), + limiter: Limiter::default(), + fps: None, playhead: 0, }; let mut playhead_seen = false; @@ -360,6 +458,76 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } doc.resolution = Some((width, height)); } + b"fps" if v9 => { + if doc.fps.is_some() || !doc.sources.is_empty() { + return Err(format!("line {n}: fps belongs once, before the sources").into()); + } + let f = fields(rest, 1, "fps", n)?; + let fps = std::str::from_utf8(f[0]) + .ok() + .and_then(|s| s.parse::().ok()) + .filter(|f| f.is_finite() && *f > 0.0 && *f <= 1000.0) + .ok_or_else(|| { + format!( + "line {n}: {:?} is not a frame rate", + String::from_utf8_lossy(f[0]) + ) + })?; + doc.fps = Some(fps); + } + b"limiter" if v9 => { + if !doc.sources.is_empty() { + return Err( + format!("line {n}: limiter belongs once, before the sources").into(), + ); + } + let f = fields(rest, 2, "limiter", n)?; + let on = match f[1] { + b"on" => true, + b"off" => false, + other => { + return Err(format!( + "line {n}: limiter is on or off, not {:?}", + String::from_utf8_lossy(other) + ) + .into()); + } + }; + // Through the same clamp a nudge goes through: a hand-written + // ceiling above full scale is a ceiling that limits nothing. + doc.limiter = Limiter { + on, + ..Limiter::default() + } + .with_ceiling(float(f[0], n)?); + } + // After the lanes it names, which is where `emit` writes it: a lane + // is declared by its own lines, and a gain declares nothing. + b"gain" if v9 => { + let f = fields(rest, 3, "gain", n)?; + let kind = match f[0] { + b"video" => LaneKind::Video, + b"audio" => LaneKind::Audio, + other => { + return Err(format!( + "line {n}: gain names {:?}, not a lane kind", + String::from_utf8_lossy(other) + ) + .into()); + } + }; + let ord = number(f[1], n)?; + let at = doc + .lanes + .iter() + .enumerate() + .filter(|(_, (k, _))| *k == kind) + .nth(ord.saturating_sub(1) as usize) + .map(|(at, _)| at) + .ok_or_else(|| format!("line {n}: gain names a lane that is not there"))?; + doc.gains.resize(doc.lanes.len(), 0.0); + doc.gains[at] = float(f[2], n)?; + } b"source" => { if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { return Err(format!("line {n}: source after a clip").into()); @@ -518,6 +686,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } } } + // One per lane whatever the file said, so a caller may zip the two. + doc.gains.resize(doc.lanes.len(), 0.0); // A file whose lanes are all empty *is* a project -- the emptied timeline, // saved. What it may not be is laneless; [`crate::Project::from_parts`] // refuses that one, by the name it has there. @@ -773,6 +943,35 @@ fn unescape(field: &[u8], line: usize) -> crate::Result { mod tests { use super::*; + /// [`super::emit`] for a project whose mix is flat: every lane at unity, no + /// limiter, no rate written. Shadows the real one for the tests that were + /// written before there was a mix to write -- the dialect they are about is + /// the one this emits, and a v9 file with flat settings is a v8 file bar + /// its version line, which is exactly what they assert. + #[allow(clippy::too_many_arguments)] + fn emit( + dir: &Path, + sources: &[Source], + lanes: &[(LaneKind, Vec)], + eq: &[EqParams], + color: &[ColorParams], + resolution: (u32, u32), + playhead: u32, + ) -> Vec { + super::emit( + dir, + sources, + lanes, + &[], + eq, + color, + resolution, + None, + Limiter::default(), + playhead, + ) + } + fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option) -> Clip { Clip { start, @@ -833,7 +1032,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -870,7 +1069,7 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 4 - - fit 1000\naudio 1\n\ video 2 40 0 10 0 - - - fit 1000\naudio 2 0 0 30 0 4 - - fit 1000\n", "an empty lane is a line of its own; everything else is its clips" @@ -978,7 +1177,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 16777215.0:-0.1:3.918315e-39:hs\n\ eq\n\ @@ -1082,7 +1281,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ color 0.1:1.2:0.9:-0.3\n\ color -1e-7:16777215.0:3.918315e-39:-0.0\n\ color 0.0:1.0:1.0:0.0\n\ @@ -1147,7 +1346,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls\n\ video 1 0 0 30 0 0 0 - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); @@ -1185,7 +1384,7 @@ mod tests { let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 - - - fit 2000\nvideo 1 15 30 40 0 - - - fit 250\n\ audio 1 0 0 30 0 - - - fit 2000\n", "the rate is the clip line's last field, in thousandths" @@ -1214,7 +1413,7 @@ mod tests { (1280, 720), old.playhead )), - "edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\naudio 1 0 0 30 0 0 - - fit 1000\n" ); // A rate outside what the editor can set is a corrupt line, by name. @@ -1225,6 +1424,105 @@ mod tests { ); } + /// The whole of the v9 bump, the speed test's twin: the mix a project was + /// left at -- every track's own volume and the master limiter -- plus the + /// rate it was cut at, all written, all read back as the very numbers, and + /// a v8 file (which has none of them) loading flat and unlimited. + #[test] + fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() { + let dir = PathBuf::from("/proj"); + let sources = vec![Source::new("/proj/a.mp4", 0)]; + let lanes = vec![ + (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]), + (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]), + // A second audio track, turned down: the gain lines are per lane, + // so the two must not run into one another. + (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]), + ]; + let limiter = Limiter { + ceiling_db: -1.5, + on: true, + }; + let bytes = super::emit( + &dir, + &sources, + &lanes, + &[0.0, 3.0, -6.5], + &[], + &[], + (1280, 720), + Some(23.976023976023978), + limiter, + 0, + ); + assert_eq!( + String::from_utf8_lossy(&bytes), + "edith 9\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\ + limiter -1.5 on\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n\ + audio 2 0 0 30 0 - - - fit 1000\n\ + gain audio 1 3.0\ngain audio 2 -6.5\n", + "the mix is lines of its own, the gains after the lanes they name" + ); + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!(back.lanes, lanes); + assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order"); + assert_eq!(back.limiter, limiter); + assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976"); + + // ...and the dialect before it, which carried none of the three: a v8 + // file mixes flat, limits nothing, and says nothing about its rate. + let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n"; + let old = parse(v8, &dir).expect("v8 parses"); + assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity"); + assert_eq!(old.limiter, Limiter::default()); + assert_eq!(old.fps, None); + // A v9 file may leave all three out too, and means the same thing. + assert_eq!( + String::from_utf8_lossy(&emit( + &dir, + &old.sources, + &old.lanes, + &old.eq, + &old.color, + (1280, 720), + old.playhead + )), + "edith 9\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" + ); + + // Each of the three refuses by name, on its own line. + for (text, want) in [ + ( + "edith 9\nfps nope\nsource 0 a.mp4\n", + "line 2: \"nope\" is not a frame rate", + ), + ( + "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n", + "line 2: limiter is on or off, not \"maybe\"", + ), + ( + "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n", + "line 4: gain names a lane that is not there", + ), + ( + "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n", + "line 4: gain names \"lane\", not a lane kind", + ), + ] { + assert_eq!( + parse(text.as_bytes(), &dir).unwrap_err().to_string(), + want, + "{text:?}" + ); + } + // A hand-written ceiling nothing could limit at is clamped, not taken. + let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses"); + assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB); + } + /// The refusals the colour grammar adds, each naming its line. #[test] fn a_malformed_colour_names_its_line() { @@ -1355,7 +1653,7 @@ mod tests { assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); assert_eq!( String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), - "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 2 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n" @@ -1408,7 +1706,7 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 8\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ + "edith 9\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\ source 0 /elsewhere/b.mp4\n\ video 1 0 0 30 0 0 - - fit 1000\nvideo 1 30 10 20 1 1 - - fit 1000\n\ audio 1 0 0 30 0 0 - - fit 1000\n", @@ -1440,7 +1738,7 @@ mod tests { // Saved again it is the current version, which round-trips to the // same document. let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v5.starts_with(b"edith 8\n")); + assert!(v5.starts_with(b"edith 9\n")); let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.lanes, back.lanes); // A dialect may not be mixed: lane lines under v1, `clip` under v2. @@ -1535,14 +1833,17 @@ mod tests { &two(one.to_vec(), one.to_vec()), &[], &[], + &[], (1280, 720), + None, + Limiter::default(), 0, ) .expect("save"); let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 8\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ + "edith 9\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\ video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n" ); // Loading rejoins the *given* directory, so the file is reached by the @@ -1587,10 +1888,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 9\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 10\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 9"); + assert_eq!(err, "line 1: unsupported version 10"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 21cbeee..08aa301 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1,23 +1,43 @@ -//! Export: the edit list rendered back out as one mp4 or one AV1-in-Matroska — -//! or, picture left behind, as one WAV or FLAC of the timeline's audio alone. +//! Export: the edit list rendered back out as one mp4 (H.264, AV1 or HEVC) or +//! one Matroska file (AV1 or HEVC) — or, picture left behind, as one WAV, FLAC +//! or MP3 of the timeline's audio alone. +//! +//! The HEVC pair is **intra-only**, and says so wherever it is offered: every +//! frame is a self-contained IDR from the vendored `oxideav-h265`, which is the +//! only shape of a pure-Rust HEVC encode fast enough to wait for (its inter +//! modes code 1080p at 0.81 fps across 12 cores against the intra path's 4.30). +//! That makes it an intraframe master in the family of ProRes and DNxHD — large +//! files, every frame a cut point — and not a delivery codec. //! //! 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 -//! pure-Rust AAC encoder 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* — a second audio lane to mix in, a speeded clip, an +//! equalized one, a source that is not AAC inside an mp4's own sample table — +//! the sound is decoded, mixed and encoded again with `rusty_aac` +//! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes +//! PCM, `flacenc` encodes FLAC and `rusty_mp3` encodes MP3, 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. +//! +//! **Every video format here carries the timeline's sound**, in whichever +//! container: the mp4 muxer writes an AAC track and so does the Matroska one. +//! Nothing is written picture-only and nothing is left silent without saying so +//! — the only sound that does not come out is sound this engine cannot decode at +//! all (Opus and AC-3 inside a Matroska file), and that is an error by name. //! //! 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. -//! 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. +//! decoding it twice. A clip whose *file* was shot at another rate than the +//! timeline goes through the same walk with one more conversion on the end +//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at. +//! The sound is *copied* unless something forces a decode, and a packet carries +//! no rate — so a speeded lane is one of the things that forces one +//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed +//! picture. WAV, FLAC and MP3 are decoded and resampled, so they honour a rate +//! like the picture does. //! //! Nothing partial survives a failure: the worker writes to `.part` and //! renames it onto `out` only once the file is closed and complete, so the @@ -27,6 +47,8 @@ //! behind (only in-process cleanup is promised), which is an orphan a user can //! delete rather than a file that plays for two seconds and stops. +use std::fs::File; +use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; @@ -40,8 +62,8 @@ use flacenc::error::Verify; use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; -use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams}; -use crate::project::{LaneKind, Project}; +use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, VideoParams}; +use crate::project::{LaneKind, Project, Rate}; use crate::scale::Composer; /// Progress is reported in permille: an atomic integer the render loop can read @@ -58,30 +80,65 @@ const MAX_BITRATE: u64 = 20_000_000; /// on a build with no assembly, which is what this one is. 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. +/// The HEVC coding tree block this encoder is fixed at: the coded picture is a +/// whole number of them, which is what the conformance window crops back. +const CTB: usize = 16; +/// How many frames the intra HEVC encoder codes at once. Twelve is where the +/// 2026-08-11 bench stopped scaling on this box (4.30 fps at 1080p); more lanes +/// only holds more decoded frames in memory. +const HEVC_LANES: usize = 12; +/// Bits per pixel the intra encoder spends at QP 27, measured on the same bench: +/// 0.607 at 720p and 0.586 at 1080p. What [`hevc_qp`] maps a bitrate row through. +const HEVC_BPP_AT_27: f64 = 0.6; +/// The band [`hevc_qp`] is clamped into, for the reason stated there. +const HEVC_QP_MIN: i32 = 22; +const HEVC_QP_MAX: i32 = 40; + +/// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in +/// Matroska or in mp4, the user's pick of container -- are the *video* pairs +/// with both an encoder and a decoder under this project's no-install rule, and +/// WAV, FLAC and MP3 are the standalone audio formats with a pure-Rust encoder: +/// `hound`, `flacenc` and `rusty_mp3`. Vorbis and Opus have none. (AAC does -- +/// `rusty_aac`, which is what a re-encoded video track's sound leaves through -- +/// but AAC is a container's own audio, never a file of its own here.) VP9 is the +/// one codec left that comes in through the plugin and stops there, HEVC having +/// gained an encoder (an intra-only one, which the rows say). A front-end says +/// so rather than hiding the row. +/// +/// **Every video format carries sound.** Which way it carries it is the only +/// difference: copied packet for packet where a copy can say what the timeline +/// says, decoded and encoded again ([`encode_audio`]) where it cannot. #[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 (a second audio lane to mix in, a + /// speeded clip, an equalized one, a source no mp4 sample table holds). #[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 an AAC - /// track copied in would be one *this engine's own reader* leaves silent - /// (`audio::AudioSession::open` refuses Matroska audio). The sound of an AV1 - /// export is a WAV or FLAC beside it, which a front-end says up front. + /// AV1 in Matroska, with the timeline's AAC beside it: this engine's + /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its + /// reader reads one back, symphonia's `mkv` reader being what + /// `audio::Track::open` opens it with. Av1, - /// The audio lane alone, 16-bit PCM. + /// The same AV1 stream in an mp4, for everything that plays mp4 and not + /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand + /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own, + /// unchanged. + Av1Mp4, + /// HEVC in Matroska, **intra-only**: every frame is a self-contained IDR + /// picture ([`Enc::open_hevc`]), which is what makes a pure-Rust HEVC + /// encoder fast enough to be an export at all. An intraframe master, like + /// ProRes or DNxHD -- large files, and every frame a cut point. + Hevc, + /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4 + /// and not Matroska -- the AV1 pair's split, for the same reason. + HevcMp4, + /// The audio lanes alone, 16-bit PCM. Wav, - /// The audio lane alone, losslessly compressed. + /// The audio lanes alone, losslessly compressed. Flac, + /// The audio lanes alone, MPEG-1 Layer III at 256 kbps CBR (`rusty_mp3`). + Mp3, } impl Format { @@ -89,26 +146,47 @@ impl Format { /// the destination path from it, so the name never disagrees with the bytes. pub fn ext(self) -> &'static str { match self { - Self::Mp4 => "mp4", - Self::Av1 => "mkv", + Self::Mp4 | Self::Av1Mp4 | Self::HevcMp4 => "mp4", + Self::Av1 | Self::Hevc => "mkv", Self::Wav => "wav", Self::Flac => "flac", + Self::Mp3 => "mp3", } } /// Whether this format carries the picture. The bitrate settings are video - /// settings and mean nothing to the audio two. + /// settings and mean nothing to the audio-only ones. pub fn has_video(self) -> bool { - matches!(self, Self::Mp4 | Self::Av1) + matches!( + self, + Self::Mp4 | Self::Av1 | Self::Av1Mp4 | Self::Hevc | Self::HevcMp4 + ) + } + + /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs + /// and which of the two AV1 containers is being written are separate + /// questions, and this is the first. + fn is_av1(self) -> bool { + matches!(self, Self::Av1 | Self::Av1Mp4) + } + + /// The same question for HEVC, and the same answer for both its containers: + /// one encoder, two boxes to put its stream in. + fn is_hevc(self) -> bool { + matches!(self, Self::Hevc | Self::HevcMp4) } /// What the format is called where a refusal names it. pub fn name(self) -> &'static str { match self { Self::Mp4 => "an mp4", - Self::Av1 => "an AV1 export", + Self::Av1 => "an AV1 Matroska", + Self::Av1Mp4 => "an AV1 mp4", + Self::Hevc => "an HEVC Matroska", + Self::HevcMp4 => "an HEVC mp4", Self::Wav => "a WAV", Self::Flac => "a FLAC", + Self::Mp3 => "an MP3", } } } @@ -134,6 +212,10 @@ struct Shared { cancel: AtomicBool, finished: AtomicBool, outcome: Mutex>>, + /// The encoders this job really opened, published the moment they are + /// chosen and never changed after -- one seat for the whole file, which is + /// what [`Enc`] states. `None` until then. + encoders: Mutex>, } /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per @@ -162,6 +244,13 @@ impl ExportHandle { self.shared.finished.load(Ordering::Acquire) } + /// What this export is encoding with -- the video seat and what the sound + /// is doing -- as the worker chose them, hardware fallback included. + /// `None` for the first instants of a job, before the encoder is open. + pub fn encoders(&self) -> Option { + self.shared.encoders.lock().unwrap().clone() + } + /// The outcome, once — taken out of the handle, so a caller that already /// reported it sees `None` afterwards. `None` while the export is running. pub fn result(&self) -> Option> { @@ -185,6 +274,7 @@ pub fn start( cancel: AtomicBool::new(false), finished: AtomicBool::new(false), outcome: Mutex::new(None), + encoders: Mutex::new(None), }); let worker = Arc::clone(&shared); let out = out.to_path_buf(); @@ -217,12 +307,12 @@ pub fn start( Err("the timeline is empty: there is nothing to export".into()) } format if format.has_video() && !has_picture(&project) => Err(format!( - "the timeline has no picture: {} would be black. Export WAV or \ - FLAC, which are the sound itself", + "the timeline has no picture: {} would be black. Export WAV, \ + FLAC or MP3, which are the sound itself", format.name() ) .into()), - Format::Mp4 | Format::Av1 => run(&project, &meta, &part, &worker, &settings), + format if format.has_video() => run(&project, &meta, &part, &worker, &settings), format => run_audio(&project, &meta, &part, &worker, format), }; let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); @@ -249,23 +339,185 @@ fn has_picture(project: &Project) -> bool { .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty()) } +/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a +/// timeline whose export will carry sound from one whose file has none. +fn has_sound(project: &Project) -> bool { + project + .lanes() + .into_iter() + .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty()) +} + +/// Whether any equalizer on the sound is doing something -- the one edit a +/// packet copy cannot carry, so an mp4 whose lane has one is decoded and +/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane: +/// the copy path has exactly one by the time it asks, and [`planned_audio`] is +/// asked before that is settled. +fn equalized(project: &Project) -> bool { + project.audio_lanes().into_iter().any(|lane| { + (0..project.lane(lane).len()) + .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity())) + }) +} + +/// Whether the *mix* is doing something -- a lane turned off unity, or a +/// limiter in circuit. [`equalized`]'s pair, and a copy cannot carry either of +/// them: both live where the lanes are summed +/// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never +/// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded. +fn mastered(project: &Project) -> bool { + project.limiter().is_active() || project.audio_gains().iter().any(|&g| g != 1.0) +} + +/// The bitrate an export codes at: the caller's number through the same clamp +/// as the computed one, for the reason [`Enc::open`] states. +fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 { + settings + .bitrate + .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)) +} + +/// The hardware seat for these settings, opened exactly as the export opens it +/// -- the same pins, the same AV1 opt-in, the same dimensions a driver may +/// refuse -- or `None` where the software encoder takes the file. The single +/// place that choice is made, which is what lets [`planned_video`] *measure* it +/// instead of promising it. +fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { + if settings.force_sw || forced("VE_SW_ENC") { + return None; + } + let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; + let bitrate = bitrate_of(meta, settings); + match settings.format { + // The HEVC pair is software only, and not for want of a GPU: the plugin + // has no HEVC *encode* entry point at all (`hw::HwEncoder` opens H.264 + // and AV1), so there is no seat to probe. Said here rather than left to + // a failed open, which would read as a driver refusal. + format if format.is_hevc() => None, + // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both + // AV1 formats sit on it: the container is not the encoder's business. + format if format.is_av1() && !forced("VE_HW_AV1") => None, + format if format.is_av1() => { + HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) + } + _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate), + } +} + +/// How a front-end names a video seat: which of the two encoders has the file, +/// and which library that is. Not the codec -- a caller shows this beside the +/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One +/// place, so what a card says before an export and what its progress line says +/// during one cannot drift apart. +fn video_label(format: Format, hw: bool) -> &'static str { + match (format, hw) { + (_, true) => "HW encode (VA-API)", + (Format::Hevc | Format::HevcMp4, false) => "SW encode (oxideav-h265 intra)", + (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)", + (_, false) => "SW encode (rusty_h264)", + } +} + +/// The cheap half of "does this timeline's sound have to be re-encoded": what +/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a +/// copy; a speeded lane is resampled; an equalizer is sample math. The other +/// half -- whether the sources can be copied out of at all -- costs a file open +/// each and belongs to [`copy_audio`], which may re-encode where this says copy. +fn forces_encode(project: &Project) -> bool { + let lanes: Vec<_> = project + .audio_lanes() + .into_iter() + .filter(|&lane| !project.lane(lane).is_empty()) + .collect(); + lanes.len() > 1 + || lanes + .iter() + .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal())) + || equalized(project) + || mastered(project) +} + +/// What the sound is written by. Every audio encoder here is software -- there +/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and +/// whether a container escapes encoding altogether by copying the packets it was +/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the +/// timeline's sound too, so leaving it unnamed would be the old lie. +/// +/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a +/// card asking before the export has no way to know (a source that cannot be +/// copied out of is only found by opening it). `None` predicts from the edit +/// alone. +fn audio_label( + project: &Project, + format: Format, + sound: bool, + copied: Option, +) -> &'static str { + if !sound { + return "no sound to write"; + } + match format { + Format::Wav => "PCM · SW (hound)", + Format::Flac => "FLAC · SW (flacenc)", + Format::Mp3 => "MP3 · SW (rusty_mp3)", + _ => match copied.unwrap_or(!forces_encode(project)) { + true => "AAC copy", + false => "AAC · SW encode (rusty_aac)", + }, + } +} + +/// What [`start`] would write this timeline's sound with, before one is +/// started. Pure: no probe and no file opened, so a card may ask it per repaint. +pub fn planned_audio(project: &Project, format: Format) -> &'static str { + audio_label(project, format, has_sound(project), None) +} + +/// What [`start`] would encode the picture with, probed the way the export +/// probes it -- the very encoder is opened and closed again -- so this is a +/// measurement and not a promise. `None` for a format that carries no picture. +/// +/// Costs that open (~100 ms here): ask it off a render thread and keep the +/// answer until the format, the resolution or the bitrate changes. +pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> { + settings + .format + .has_video() + .then(|| video_label(settings.format, hw_seat(meta, settings).is_some())) +} + fn settle(shared: &Shared, result: crate::Result<()>) { *shared.outcome.lock().unwrap() = Some(result); // Published last: a caller that sees the flag is guaranteed the outcome. shared.finished.store(true, Ordering::Release); } -/// 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. +/// The audio track an export writes, and how it was made -- a copy is the +/// source's own packets, bit for bit, and anything else is this project's +/// encoder over the decoded mix. [`run`] publishes which of the two really +/// happened, so the encoder line a user reads is measured and not promised. +pub(crate) struct ExportAudio { + pub params: crate::AacTrackParams, + pub packets: Vec, + /// Whether those packets are the source's, untouched. + pub copied: bool, +} + +/// The timeline's audio track for a file that carries picture: copied packet for +/// packet where a copy says exactly what the timeline says, and decoded, mixed +/// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane, +/// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample +/// table. Nothing is refused for being uncopyable any more; the only refusals +/// left below the copy are about sound this engine cannot *decode* either, and +/// those come out of the decode path by name. +/// +/// The copy is still the default and still bit-exact: a timeline nobody has +/// touched leaves as the very packets its source holds. /// /// 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 /// `copy_segments` that yields packets instead of collecting them. -#[allow(clippy::type_complexity)] -fn copy_audio( - project: &Project, - meta: &VideoMeta, -) -> crate::Result)>> { +fn copy_audio(project: &Project, meta: &VideoMeta) -> crate::Result> { // The segments name their source, and the copy carries its packet-rounding // debt across a source join exactly as across a cut, so a timeline spanning // files stays in sync. A source whose AAC parameters disagree with the @@ -276,11 +528,10 @@ fn copy_audio( // is the same list `PlaybackSession::seek` hands the decoder, so an export // 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. + // One lane is the only shape a *copy* has: summing two means decoding both, + // and a sum is not a copy. Two or more go to [`encode_audio`], which is the + // very mix the WAV path writes -- it used to be a refusal, and a refusal is + // what a file missing half its sound deserves, not what a mix does. // // *Which* lane is the same question `audio_segments_from` answers for // playback, and it is asked here rather than assumed: the lane that holds @@ -290,67 +541,151 @@ fn copy_audio( // whole comment is about. let lanes = project.audio_segments_from(0, meta.frame_rate); 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", - lanes.len() - ) - .into()); + return encode_audio(project, meta); }; - // ...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 + // rate other than the one it was recorded at. A copy hands the muxer 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. Decoded and resampled instead, by the same worker + // playback feeds from. // - // 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. - if let Some((at, speed)) = project - .lane(lane) - .iter() - .find(|c| !c.speed.is_normal()) - .map(|c| (c.start, c.speed)) - { - return Err(format!( - "the clip at {} plays at {speed} and an mp4 export copies AAC packets, which carry \ - no rate: export WAV or FLAC, which are decoded and resampled, or set it back to 1.00x", - timecode(at, meta.frame_rate) - ) - .into()); + // ...and whether any clip on it carries an equalizer, which is sample math a + // copy never reaches: copying such a lane would write the clip *flat*, + // silently. + // + // A frame *rate* of its own is not one of those, and that is deliberate: do + // not "fix" this into a re-encode. A clip counts the **timeline's** frames + // whatever its file was shot at ([`crate::project::Rate`]), so the window + // this copy trims a source's sound to is `start..end` in whole timeline + // frames -- exactly the seconds the picture covers -- and the file is read + // at the pitch it was recorded at, which is what playing at the rate it was + // shot at means. There is no per-clip stretch to express, so the packets are + // already the right sound in the right place; re-encoding a conformed lane + // would buy nothing and cost a generation of loss on every mixed-rate export + // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot` + // measures the copied sound against the picture). A *speed* is different + // because it resamples, which is why it leaves through the re-encode above. + // + // Only these: a timeline nobody has touched still leaves through the copy + // below, packet for packet, so no passthrough quietly becomes a generation + // of loss. + // ...and whether the mix itself does anything a packet never went through: + // a lane volume is applied at the sum and a limiter over it, so copying + // such a lane would write it at unity and unlimited, silently. + let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal()); + if speeded || equalized(project) || mastered(project) { + return encode_audio(project, meta); } - 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) + // What is left is a copy the *sources* may still not be able to give: AAC + // inside a Matroska file (readable, but not out of a sample table this walks + // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two + // sources whose AAC parameters disagree. Every one of them decodes, and what + // decodes can be encoded again, so the copy's refusal is now a route: the + // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file, + // which symphonia has no decoder for at any version -- is the one that comes + // back, by name, from [`encode_audio`]. + match AudioSession::copy_multi_streams(&project.audio_sources(), segments) { + Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio { + params, + packets, + copied: true, + })), + Err(_) => encode_audio(project, meta), + } +} + +/// 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. +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_master( + &sources, + &segs, + &eqs, + &speeds, + &project.audio_gains(), + project.limiter(), + )? + 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, FLAC or MP3, which write it as \ + it is", + audio.sample_rate ) - .into()); + })?; + 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); } - AudioSession::copy_multi_streams(&project.audio_sources(), segments) + 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(ExportAudio { + params: 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, + copied: false, + })) } fn run( @@ -363,21 +698,44 @@ fn run( let total = project.timeline_frames(); let sources = project.sources(); // Audio first: a track has to be declared when the muxer is created, which - // happens as soon as the first coded picture arrives. None of it for AV1 -- - // that one is picture only, for the reason [`Format::Av1`] states -- and no - // refusal of it either: a timeline with sound is exported as the video it - // also is, and the front-end says the sound is not in the file *before* the - // export starts rather than failing it here. - let audio = match settings.format { - Format::Av1 => None, - _ => copy_audio(project, meta)?, - }; - let audio_params = audio.as_ref().map(|(track, _)| AudioParams { - freq_index: track.freq_index, - chan_conf: track.chan_conf, + // happens as soon as the first coded picture arrives -- and the Matroska + // muxer wants the packets themselves that early too, because it interleaves + // them into the clusters as it writes. Every video format gets the same + // track: none of them is picture-only any more. + let audio = copy_audio(project, meta)?; + let audio_params = audio.as_ref().map(|track| AudioParams { + freq_index: track.params.freq_index, + chan_conf: track.params.chan_conf, + sample_rate: track.params.sample_rate, }); + // What the track *is*, kept before the packets are handed to a muxer: the + // encoder line names a copy or an encode and only `copy_audio` knows which. + let sound = audio.as_ref().map(|track| track.copied); + // Taken by the Matroska muxer at creation; the mp4 one writes its track + // after the picture, so for that path this is still `Some` at the end. + let mut packets = audio.map(|track| track.packets); + + // One header parse per source, before any of them is decoded: what rate + // each file was shot at against the timeline's ([`Rate`]), which is how the + // clip's timeline frames below become frames of the file. Real time for a + // still, a song and a single-rate project, where every conversion below is + // the identity. + let rates: Vec = sources + .iter() + .map(|source| source_rate(&source.path, meta.frame_rate)) + .collect(); let mut encoder = Enc::open(meta, settings)?; + // What this file is really being written by, for a progress line to name. + // Published *after* the seat is open, so a hardware encoder the driver + // refused reads as the software one that took over rather than as the hope + // it replaced -- and the sound says whether it was copied or encoded, which + // `copy_audio` decided a few lines up. + *shared.encoders.lock().unwrap() = Some(format!( + "{} · {}", + encoder.label(), + audio_label(project, settings.format, sound.is_some(), sound) + )); let mut muxer = None; let mut done = 0u32; let black = Black::new(meta); @@ -391,14 +749,18 @@ fn run( // encoder is *not* reopened, so the export is one continuous stream // whose GOP boundaries need not line up with the cuts -- nor with the // file boundaries, which are just cuts that change the path. - let mut pictures = match span.from { + let (mut pictures, rate, in_frame) = match span.from { Some((source, in_frame)) => { let entry = sources .get(source) .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; - Some(ClipDecoder::open(&entry.path, in_frame)?) + let rate = rates[source]; + // Opened at the file's own frame, which is the only place the + // file's numbering is used -- the span's are the timeline's. + let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?; + (Some(pictures), rate, in_frame) } - None => None, + None => (None, Rate::REAL_TIME, 0), }; // What this span is graded by -- the same answer playback's decoder // carries, so the export is the picture that was watched. `None` for a @@ -429,10 +791,24 @@ fn run( let mut done_here = 0u32; // Source frames already taken out of this span's decoder. let mut taken = 0u32; + // The whole of the mapping, in the order it composes: the speed says + // which of the clip's (timeline-rate) frames a timeline frame shows, + // and the rate says which frame of the *file* that is -- counted from + // the one the decoder was opened at. At real time and at the timeline's + // own rate this is `Speed::source_at` and nothing else, which is the + // walk a single-rate project has always taken. + let opened_at = rate.source_at(in_frame); + let source_at = + |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at; while done_here < span.len { cancelled(shared)?; - let want = span.speed.source_at(done_here); - let repeats = span.speed.repeats(done_here, span.len); + let want = source_at(done_here); + // How many timeline frames from here show that same picture: one at + // real time, more when the clip is slowed or its file is slower + // than the timeline. Encoded again rather than decoded twice. + let repeats = (done_here..span.len) + .take_while(|&offset| source_at(offset) == want) + .count() as u32; let picture = match &mut pictures { Some(pictures) => { let mut ran_out = false; @@ -485,6 +861,7 @@ fn run( meta, settings, audio_params.as_ref(), + &mut packets, au, key, )?; @@ -504,6 +881,7 @@ fn run( meta, settings, audio_params.as_ref(), + &mut packets, au, key, )?; @@ -515,8 +893,10 @@ fn run( let Some(muxer) = muxer else { return Err("export produced no coded pictures".into()); }; - let muxer = match (muxer, audio) { - (Muxer::Mp4(mut mp4), Some((_, packets))) => { + // The mp4's audio track after its picture -- the Matroska one interleaved + // its own as it went and left `packets` empty behind it. + let muxer = match (muxer, packets) { + (Muxer::Mp4(mut mp4), Some(packets)) => { for packet in packets { mp4.write_audio_packet(&packet.bytes)?; } @@ -530,16 +910,22 @@ fn run( Ok(()) } -/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short -/// enough to sit inside a refusal and exact enough to go and find the clip. -/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a -/// `00:00:12:07` in the middle of a sentence is a serial number. -fn timecode(frame: u32, fps: f64) -> String { - let secs = match fps.is_finite() && fps > 0.0 { - true => (f64::from(frame) / fps) as u32, - false => 0, - }; - format!("{:02}:{:02}", secs / 60, secs % 60) +/// What rate `path` was shot at against a timeline at `timeline_fps` +/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own +/// -- a still, a song -- and for one that will not open here: the decoder is +/// opened a few lines later and fails the export by name, which is a better +/// error than this one could raise. +fn source_rate(path: &Path, timeline_fps: f64) -> Rate { + if crate::is_image(path) || crate::is_audio(path) { + return Rate::REAL_TIME; + } + match Demuxer::open(path) { + // ...and one whose rate cannot be named against the timeline's, which + // `matches_timeline` refuses at import, so nothing on a timeline is on + // this arm either. + Ok((meta, _)) => Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), + Err(_) => Rate::REAL_TIME, + } } /// The audio lanes alone, summed, as a WAV or a FLAC. @@ -576,11 +962,24 @@ fn run_audio( // 2x is half as long and holds the samples that were heard -- not a // second pass here that could disagree with what the ear got. let speeds = project.audio_speeds_from(0, meta.frame_rate); - let Some((audio, chunks)) = - AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)? + // ...and the mix over both: each lane's volume into the sum, the master + // limiter out of it. The same opener playback's feeder reads from, so a + // file is written at the levels it was heard at -- there is no second + // place here that could mix it differently. + let Some((audio, chunks)) = AudioSession::open_mixed_streams_master( + &sources, + &segs, + &eqs, + &speeds, + &project.audio_gains(), + project.limiter(), + )? else { return Err("this timeline has no audio to export".into()); }; + // The picture path's line, for a file that is sound alone: there is sound + // by the line above, so this names the encoder writing it. + *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string()); let channels = usize::from(audio.channels); let frames = (f64::from(project.timeline_frames()) / meta.frame_rate * f64::from(audio.sample_rate)) @@ -612,7 +1011,8 @@ fn run_audio( match format { Format::Wav => write_wav(out, &samples, &audio)?, Format::Flac => write_flac(out, &samples, &audio)?, - Format::Mp4 | Format::Av1 => unreachable!("the picture formats are `run`"), + Format::Mp3 => write_mp3(out, &samples, &audio)?, + _ => unreachable!("the picture formats are `run`"), } shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); Ok(()) @@ -639,6 +1039,42 @@ fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<() Ok(()) } +/// The same samples as MPEG-1 Layer III, `rusty_mp3` doing the encoding -- pure +/// Rust like every other encoder here, and the reason this format is a row at +/// all: the LGPL `shine-rs` was the only one when it was not. +/// +/// 256 kbps CBR, for [`encode_audio`]'s reason: an export is a master a person +/// edits from again, not a delivery file, and this is a lossy generation over +/// sources that may already have been one. The rate is snapped to a legal Layer +/// III value by the encoder, and a sample rate MPEG has no frame for (anything +/// but 8-48 kHz) is refused there by name rather than written as something else. +/// +/// ponytail: CBR only, and no rate is offered to the caller -- the export card +/// has one bitrate control and it is the *picture's*. Upgrade path is +/// `Mp3EncoderConfig::vbr_quality` behind a setting of its own. +fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { + let mut encoder = rusty_mp3::Mp3Encoder::new(rusty_mp3::Mp3EncoderConfig { + bitrate_kbps: 256, + vbr_quality: None, + }); + // The samples are the 16-bit ones a WAV of this timeline holds, so the two + // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this + // engine's own decoders do. + let pcm: Vec = samples.iter().map(|&s| s as i16).collect(); + encoder + .push_pcm_s16(&pcm, audio.channels, audio.sample_rate) + .map_err(|e| format!("mp3 encode: {e}"))?; + encoder.finish(); + let mut file = BufWriter::new(File::create(out)?); + // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info + // header first: the loop ends on the only error it can see. + while let Ok(frame) = encoder.next_packet() { + file.write_all(&frame)?; + } + file.flush()?; + Ok(()) +} + /// The same samples, losslessly compressed. `flacenc`'s errors are flattened to /// text: they are not `Send + Sync`, and every one of them fails the export the /// same way. @@ -739,34 +1175,113 @@ fn write_video( meta: &VideoMeta, settings: &ExportSettings, audio: Option<&AudioParams>, + packets: &mut Option>, au: &[u8], key: bool, ) -> crate::Result<()> { - if settings.format == Format::Av1 { + if settings.format.is_hevc() { + // The parameter sets are in the access unit -- every intra AU carries + // VPS, SPS and PPS -- and the record built from them is what *both* + // containers declare the track with: an mp4's `hvcC` box and a + // Matroska `CodecPrivate` are the same bytes, so the two files are one + // stream written twice rather than two. + let sample = + crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?; + if settings.format == Format::Hevc { + let muxer = match muxer { + Some(Muxer::Mkv(mkv)) => mkv, + Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), + none => { + let hvcc = hevc_params(au)?; + let sound = audio.zip(packets.take()); + let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc( + out, + &HevcParams { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + hvcc: &hvcc, + }, + sound, + )?)) else { + unreachable!("just inserted a Matroska muxer") + }; + mkv + } + }; + return muxer.write_frame(&sample, key); + } let muxer = match muxer { - Some(Muxer::Mkv(mkv)) => mkv, - Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), + Some(Muxer::Mp4(mp4)) => mp4, + Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), none => { - // Every AV1 stream opens on a keyframe, and a keyframe carries - // the sequence header the track has to declare: an encoder that - // handed back neither has produced nothing a decoder can start. - let config = crate::mux::av1_sequence_header(au) - .ok_or("the first coded picture carries no AV1 sequence header")?; - let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create( + let hvcc = hevc_params(au)?; + let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc( out, - &Av1Params { + &HevcParams { width: meta.width, height: meta.height, frame_rate: meta.frame_rate, - config, + hvcc: &hvcc, }, + audio, + )?)) else { + unreachable!("just inserted an mp4 muxer") + }; + mp4 + } + }; + return muxer.write_coded_sample(&sample, key); + } + if settings.format.is_av1() { + // Every AV1 stream opens on a keyframe, and a keyframe carries the + // sequence header the track has to declare: an encoder that handed back + // neither has produced nothing a decoder can start. The same header goes + // into a `CodecPrivate` and into an `av1C` -- one record, two containers. + fn params<'a>(meta: &VideoMeta, au: &'a [u8]) -> crate::Result> { + Ok(Av1Params { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + config: crate::mux::av1_sequence_header(au) + .ok_or("the first coded picture carries no AV1 sequence header")?, + }) + } + if settings.format == Format::Av1 { + let muxer = match muxer { + Some(Muxer::Mkv(mkv)) => mkv, + Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), + none => { + // The sound with it, all of it: the Matroska muxer writes the + // packets into the clusters of the pictures they play under. + let sound = audio.zip(packets.take()); + let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create( + out, + ¶ms(meta, au)?, + sound, + )?)) else { + unreachable!("just inserted a Matroska muxer") + }; + mkv + } + }; + return muxer.write_frame(au, key); + } + let muxer = match muxer { + Some(Muxer::Mp4(mp4)) => mp4, + Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), + none => { + let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1( + out, + ¶ms(meta, au)?, + audio, )?)) else { - unreachable!("just inserted a Matroska muxer") + unreachable!("just inserted an mp4 muxer") }; - mkv + mp4 } }; - return muxer.write_frame(au, key); + return muxer.write_coded_sample(au, key); } if !crate::mux::has_coded_slice(au) { return Ok(()); @@ -796,6 +1311,13 @@ fn write_video( muxer.write_video_au(au) } +/// The `hvcC` record of the first coded unit, or the refusal by name. Split out +/// because both HEVC containers ask it in the same words. +fn hevc_params(au: &[u8]) -> crate::Result> { + crate::mux::hvcc_record(au) + .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS")) +} + fn bitrate_for(meta: &VideoMeta) -> u64 { let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL; (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE) @@ -832,28 +1354,73 @@ enum Enc { au: Vec, flushed: bool, }, + /// HEVC, intra-only and software only: `encode_idr_intra_au_cropped` is a + /// *stateless* function of one picture, so a batch of frames is coded on as + /// many cores as there are lanes and collected back in order. + Hevc(HevcEnc), +} + +/// The intra HEVC seat. Frames arrive one at a time (the export walk is one +/// picture per timeline frame) and are held until there are [`lanes`] of them, +/// then coded in parallel and queued in **display order** -- fanning out is the +/// only thing that makes a pure-Rust HEVC export bearable (4.30 fps at 1080p on +/// 12 lanes against 0.55 fps on one, measured 2026-08-11), and an export whose +/// frames came back shuffled would be no export at all. +/// +/// ponytail: a batch of padded planes sits in memory (~3 MB a frame at 1080p, +/// so ~37 MB at 12 lanes) and the tail of a timeline is coded on fewer lanes +/// than the middle. Upgrade path is a pipeline that keeps every lane fed from a +/// decoder running ahead of the encoder rather than a batch barrier. +struct HevcEnc { + /// Padded I420 planes waiting for a lane, in display order. + pending: Vec<(Vec, Vec, Vec)>, + /// Coded access units not yet collected, in the same order. + ready: std::collections::VecDeque>, + /// The unit currently lent out, for the reason `Sw` owns one. + au: Vec, + /// The *coded* size: the picture's, rounded up to the 16-sample CTB grid. + width: usize, + height: usize, + /// Luma samples the conformance window crops off the right and the bottom, + /// so a decoder outputs the picture's own size ([`pad_to_ctb`]). + crop: (usize, usize), + qp: i32, + lanes: usize, } impl Enc { + /// Which seat this *is*, said the way [`video_label`] says it -- so the + /// name a running export shows is the name the card showed, or the honest + /// difference where the probe and the open disagreed. + fn label(&self) -> &'static str { + match self { + Self::Hw(_) => video_label(Format::Mp4, true), + Self::Sw { .. } => video_label(Format::Mp4, false), + Self::Av1Hw(_) => video_label(Format::Av1, true), + Self::Av1Sw { .. } => video_label(Format::Av1, false), + Self::Hevc(_) => video_label(Format::Hevc, false), + } + } + fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { - if settings.format == Format::Av1 { + // Which *codec* the picture is, not which container it goes in: both AV1 + // formats run the same encoder, and so do both HEVC ones. + if settings.format.is_av1() { return Self::open_av1(meta, settings); } + if settings.format.is_hevc() { + return Self::open_hevc(meta, settings); + } // A caller's number goes through the same clamp as the computed one: a // zero bitrate switches the software encoder's lookahead on, which would // break the one-picture-per-call contract `encode` documents below. - let bitrate = settings - .bitrate - .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); + let bitrate = bitrate_of(meta, settings); // The plugin wants an exact rational, and the muxer already picks one // that is exact at every rate we can read -- `fps * 1000 / 1000` would // hand 24000/1001 over as a rounded 23.976, which is the same // truncation the container timing had. - let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; - if !settings.force_sw - && !forced("VE_SW_ENC") - && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate) - { + crate::mux::frame_timing(meta.frame_rate)?; + if let Some(hw) = hw_seat(meta, settings) { eprintln!("export encoder: hardware (VA-API plugin)"); return Ok(Self::Hw(hw)); } @@ -894,19 +1461,12 @@ impl Enc { /// cros-codecs release that fixes it) plus a probe encode of one frame at /// open, after which this can prefer hardware the way H.264 does. fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { - let bitrate = settings - .bitrate - .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE)); + let bitrate = bitrate_of(meta, settings); let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; // Two seconds between keyframes, as the H.264 seat does: a seek may only // land on one, and this is what a cluster of the Matroska file is. let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64; - if forced("VE_HW_AV1") - && !settings.force_sw - && !forced("VE_SW_ENC") - && let Some(hw) = - HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) - { + if let Some(hw) = hw_seat(meta, settings) { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); return Ok(Self::Av1Hw(hw)); } @@ -942,6 +1502,53 @@ impl Enc { }) } + /// The intra HEVC seat, software and frame-parallel. There is no hardware + /// half: the plugin encodes H.264 and AV1 and nothing else, which + /// [`hw_seat`] says by refusing to probe one. + /// + /// **Intra-only, deliberately.** The vendored encoder's inter modes code + /// 1080p at 0.81 fps across 12 cores (measured 2026-08-11) -- a minute of + /// timeline in half an hour, which is not an export anybody waits for -- + /// while the intra path does 4.30 fps on the same picture and the same + /// cores. So every frame is an IDR, the file is an intraframe master in the + /// shape of ProRes or DNxHD, and the card says so where a user picks it. + /// + /// The picture is coded **padded** to the 16-sample CTB grid and the SPS + /// crops it back ([`pad_to_ctb`], the vendored conformance-window patch), so + /// 1920x1080 is a legal export rather than a refusal. + fn open_hevc(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { + // The muxers time by it and the mp4 one wants an exact rational: asked + // here so an impossible rate fails before a frame is coded. + crate::mux::frame_timing(meta.frame_rate)?; + // 4:2:0 addresses its conformance window in *chroma* samples, so an odd + // picture cannot be cropped back to itself -- and an odd dimension has + // no chroma plane of its own to begin with. Named rather than padded to + // something a decoder would then show a column of. + if meta.width % 2 != 0 || meta.height % 2 != 0 { + return Err(format!( + "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions", + meta.width, meta.height + ) + .into()); + } + let (width, height) = ( + (meta.width as usize).next_multiple_of(CTB), + (meta.height as usize).next_multiple_of(CTB), + ); + let lanes = std::thread::available_parallelism().map_or(1, |n| n.get()); + eprintln!("export encoder: software HEVC intra (oxideav-h265)"); + Ok(Self::Hevc(HevcEnc { + pending: Vec::new(), + ready: std::collections::VecDeque::new(), + au: Vec::new(), + width, + height, + crop: (width - meta.width as usize, height - meta.height as usize), + qp: hevc_qp(meta, settings), + lanes: lanes.min(HEVC_LANES), + })) + } + /// One picture in, at most one access unit out, and whether that unit is one /// a decoder may be started from -- which only the Matroska muxer asks, the /// mp4 one reading its own sync flag off the IDR slice. @@ -984,6 +1591,23 @@ impl Enc { collect_av1(context, ready)?; Ok(pop_av1(ready, au)) } + Self::Hevc(hevc) => { + hevc.pending.push(pad_to_ctb( + y, + u, + v, + width as usize, + height as usize, + hevc.width, + hevc.height, + )); + if hevc.pending.len() >= hevc.lanes { + hevc.code_batch()?; + } + // Every intra AU is an IDR, so every one of them is a key + // frame -- which is what an intraframe master means. + Ok(pop_hevc(hevc)) + } Self::Hw(hw) => Ok(hw .encode(y, u, v, width, height, false)? .map(|au| (au, false))), @@ -1023,6 +1647,14 @@ impl Enc { } Ok(pop_av1(ready, au)) } + Self::Hevc(hevc) => { + // The tail batch: fewer frames than lanes, coded on as many + // cores as there are frames left. + if !hevc.pending.is_empty() { + hevc.code_batch()?; + } + Ok(pop_hevc(hevc)) + } Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))), Self::Sw { encoder, @@ -1042,6 +1674,103 @@ impl Enc { } } +impl HevcEnc { + /// The whole pending batch, one frame per lane, collected back in the order + /// it went out -- `std::thread::scope`, because the encode borrows the + /// planes rather than copying them again. A panic inside a lane comes back + /// as an error rather than unwinding the export thread. + fn code_batch(&mut self) -> crate::Result<()> { + let (width, height, qp, crop) = (self.width, self.height, self.qp, self.crop); + let coded: Vec>> = std::thread::scope(|scope| { + let lanes: Vec<_> = self + .pending + .iter() + .map(|(y, cb, cr)| { + scope.spawn(move || { + oxideav_h265::encoder::intra::encode_idr_intra_au_cropped( + y, cb, cr, width, height, qp, crop.0, crop.1, + ) + .map(|coded| coded.au) + .map_err(|e| crate::Error::from(format!("HEVC intra encode: {e:?}"))) + }) + }) + .collect(); + lanes + .into_iter() + .map(|lane| { + lane.join() + .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into())) + }) + .collect() + }); + for au in coded { + self.ready.push_back(au?); + } + self.pending.clear(); + Ok(()) + } +} + +/// The oldest coded intra AU, lent out under the same "valid until the next +/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key flag +/// is not a guess. +fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> { + hevc.au = hevc.ready.pop_front()?; + Some((&hevc.au[..], true)) +} + +/// One I420 picture copied onto the padded plane sizes the CTB grid needs, the +/// added rows and columns filled by **replicating the edge** rather than with +/// black: the padding is coded and then cropped away, and a black border would +/// bleed into the last real column through the intra prediction and the +/// transform that straddles it. +fn pad_to_ctb( + y: &[u8], + u: &[u8], + v: &[u8], + width: usize, + height: usize, + padded_w: usize, + padded_h: usize, +) -> (Vec, Vec, Vec) { + let plane = |src: &[u8], w: usize, h: usize, pw: usize, ph: usize| { + let mut out = vec![0u8; pw * ph]; + for row in 0..ph { + let src_row = &src[row.min(h - 1) * w..][..w]; + let dst = &mut out[row * pw..][..pw]; + dst[..w].copy_from_slice(src_row); + dst[w..].fill(src_row[w - 1]); + } + out + }; + ( + plane(y, width, height, padded_w, padded_h), + plane(u, width / 2, height / 2, padded_w / 2, padded_h / 2), + plane(v, width / 2, height / 2, padded_w / 2, padded_h / 2), + ) +} + +/// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a +/// user picked -- the card has no QP control and this codec has no rate control, +/// so the two are joined by measurement rather than promised to each other. +/// +/// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured +/// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP +/// is a factor of two in rate, which is the classic HEVC relation. So the QP +/// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is +/// clamped, because this is a *quality* dial and not a rate controller: below QP +/// 22 the file grows without a picture to show for it, and past QP 40 an +/// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30 +/// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out +/// bigger than that, which is what "intra-only, large files" on the format row +/// means: the row buys quality, not a size. +fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 { + let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate; + let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0); + let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2(); + (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX) +} + /// Every temporal unit `rav1e` has finished, moved into the queue in display /// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is /// through) are the two ways it says there is nothing more; `Encoded` means a @@ -1198,4 +1927,100 @@ mod tests { assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny"); assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); } + + fn meta(width: u32, height: u32) -> VideoMeta { + VideoMeta { + width, + height, + frame_rate: 30.0, + frame_count: 1, + codec: crate::demux::Codec::H264, + } + } + + /// The bitrate row a user picked, read as the quality tier it is: a higher + /// row is a lower QP, the band is honoured at both ends, and the same + /// picture at the same rate gets the same number whatever its size (the + /// mapping is bits per *pixel*, which is what makes 720p and 1080p one + /// table). + #[test] + fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() { + let at = |width, height, mbps: Option| { + hevc_qp( + &meta(width, height), + &ExportSettings { + bitrate: mbps.map(|m| m * 1_000_000), + ..Default::default() + }, + ) + }; + // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at + // QP 27, which is just over half: five QP up, and QP is not an + // arithmetic scale, so this is the number the formula gives. + assert_eq!(at(1920, 1080, Some(20)), 32); + // Every step down the card is a step up in QP, never sideways. + let rows: Vec = [20, 12, 8, 4, 2, 1] + .into_iter() + .map(|mbps| at(1920, 1080, Some(mbps))) + .collect(); + assert!( + rows.windows(2).all(|w| w[0] <= w[1]), + "a lower bitrate row must never code at a lower QP: {rows:?}" + ); + assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped"); + // ...and the top of the range is the clamp, not an unbounded number: 20 + // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs. + assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN); + // The same bits per pixel is the same quantiser at any size: 1080p at + // 20 Mbps and 720p at 8.9 Mbps are one picture quality. + assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9))); + // The automatic bitrate is 0.1 bpp at every size, so it is one QP + // everywhere -- the honest end of "intra-only, large files": the file + // will be bigger than the row says, and the row buys quality. + assert_eq!(at(1920, 1080, None), at(1280, 720, None)); + } + + /// The padding a non-%16 picture is coded with replicates the edge instead + /// of filling black: the coded rows past the picture carry its last row, so + /// nothing bleeds into the last real line through the intra prediction. + #[test] + fn the_ctb_padding_replicates_the_edge() { + // 6x2 luma, values 1..=12, padded to 8x4 (CTB is 16, so this checks the + // copy itself with numbers small enough to read). + let y: Vec = (1..=12).collect(); + let u: Vec = vec![40, 41, 42]; + let v: Vec = vec![50, 51, 52]; + let (py, pu, pv) = pad_to_ctb(&y, &u, &v, 6, 2, 8, 4); + assert_eq!( + py, + vec![ + 1, 2, 3, 4, 5, 6, 6, 6, // the row, then its last sample twice + 7, 8, 9, 10, 11, 12, 12, 12, // + 7, 8, 9, 10, 11, 12, 12, 12, // the last row, replicated + 7, 8, 9, 10, 11, 12, 12, 12, + ] + ); + // Chroma is half of everything, padded the same way. + assert_eq!(pu, vec![40, 41, 42, 42, 40, 41, 42, 42]); + assert_eq!(pv, vec![50, 51, 52, 52, 50, 51, 52, 52]); + } + + /// An odd picture cannot be cropped back to itself in 4:2:0 -- the + /// conformance window is stated in chroma samples -- so it is refused by + /// name rather than written a column wider than the timeline. + #[test] + fn an_odd_picture_is_refused_an_hevc_export_by_name() { + let settings = ExportSettings { + format: Format::Hevc, + ..Default::default() + }; + let refused = Enc::open(&meta(1919, 1080), &settings) + .err() + .expect("an odd width has no chroma plane") + .to_string(); + assert!(refused.contains("1919x1080"), "{refused}"); + assert!(refused.contains("even"), "{refused}"); + // ...and the even one it neighbours opens. + assert!(Enc::open(&meta(1920, 1080), &settings).is_ok()); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 246839b..afca436 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -11,6 +11,7 @@ pub mod edith; pub mod eq; pub mod export; pub mod hw; +pub mod limiter; pub mod mux; pub mod playback; pub mod project; @@ -27,7 +28,7 @@ pub use demux::{Codec, VideoMeta}; pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; pub use playback::PlaybackSession; -pub use project::{Clip, Project, Speed}; +pub use project::{Clip, Project, Rate, Speed}; /// Whether a path names a standalone audio file -- a source with no picture, /// which belongs on the audio lane and nowhere else. Extension only, lowercased: diff --git a/crates/engine/src/limiter.rs b/crates/engine/src/limiter.rs new file mode 100644 index 0000000..61c5765 --- /dev/null +++ b/crates/engine/src/limiter.rs @@ -0,0 +1,259 @@ +//! The master limiter: one ceiling the whole mix is held under, applied where +//! the lanes are summed and nowhere else ([`crate::audio::mix`]). +//! +//! A mix is an add, and two lanes at full scale add past full scale: what used +//! to happen there was a hard `clamp`, which is a squared-off waveform and the +//! worst-sounding thing an editor can do to a hot timeline. This holds the sum +//! down *before* it reaches the clamp instead, and the clamp stays behind it as +//! the backstop it always was. +//! +//! Per sample, no FFT, no allocation while it runs: +//! +//! * **Lookahead.** The mix is written into a delay line [`LOOKAHEAD_MS`] long +//! and read out of it that much later, so the gain a peak needs is already in +//! force by the time the peak itself is emitted. No attack overshoot -- the +//! first sample over the ceiling is the first sample held under it, which is +//! what makes the peak of an exported file a *measurement* and not a hope. +//! * **Linked channels.** One gain for the frame, off the loudest channel in +//! it: a per-channel gain would move the stereo image every time one side +//! peaked. +//! * **Soft knee.** [`KNEE_DB`] wide and centred on the ceiling, so the gain +//! comes in gradually instead of switching on at one sample and off at the +//! next. The knee's own curve never lets the output past the ceiling (at the +//! centre it is already `KNEE_DB/8` under it), which is what keeps the +//! guarantee a hard knee would give. +//! * **Release**, not a per-sample snap back: `RELEASE_MS` of exponential +//! recovery, so one loud transient does not pump the whole bar around it. +//! +//! The latency is *taken out again*, not paid: the first `lookahead` frames of +//! output -- the empty delay line -- are dropped, so what comes out is sample +//! aligned with what went in and the sound stays locked to the picture. What +//! that costs is the last couple of milliseconds of the timeline's tail, which +//! is the trade every lookahead limiter makes. + +/// How far ahead the gain looks. 2 ms is ~96 frames at 48 kHz: long enough to +/// ride a transient in smoothly, short enough that the tail it eats is nothing. +const LOOKAHEAD_MS: f32 = 2.0; +/// How wide the knee is, centred on the ceiling. +const KNEE_DB: f32 = 6.0; +/// How fast the gain comes back once the loud part is over. +const RELEASE_MS: f32 = 120.0; + +/// What a project's master limiter is set to: a ceiling in dBFS and whether it +/// is in circuit at all. Off by default -- a timeline nobody has asked to limit +/// mixes exactly as it always did, down to the bit. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Limiter { + /// The level nothing may pass, in dBFS (0 dBFS is full scale). + pub ceiling_db: f32, + pub on: bool, +} + +impl Default for Limiter { + fn default() -> Self { + Self { + ceiling_db: -1.0, + on: false, + } + } +} + +impl Limiter { + /// The ceilings a front-end may set, and what a file may name: a limiter + /// above full scale would limit nothing, and one 24 dB down is already a + /// fader. + pub const MIN_DB: f32 = -24.0; + pub const MAX_DB: f32 = 0.0; + + /// The setting with `ceiling_db` put inside the range above, which is what + /// a nudge and a parsed line both go through. Not finite means the default. + pub fn with_ceiling(self, ceiling_db: f32) -> Self { + Self { + ceiling_db: match ceiling_db.is_finite() { + true => ceiling_db.clamp(Self::MIN_DB, Self::MAX_DB), + false => Self::default().ceiling_db, + }, + ..self + } + } + + /// Whether it is doing anything to the sound -- what an export asks before + /// it decides a packet copy would be a lie. + pub fn is_active(self) -> bool { + self.on + } +} + +/// dBFS as an amplitude. `db_to_linear(0.0)` is exactly 1.0, which is what +/// keeps a flat setting a bit-exact passthrough. +pub fn db_to_linear(db: f32) -> f32 { + match db == 0.0 { + true => 1.0, + false => 10f32.powf(db / 20.0), + } +} + +/// One running limiter: the delay line, the peak window and the gain. +pub struct LimiterState { + channels: usize, + /// The delayed mix, one frame per slot, `lookahead + 1` frames round. + line: Vec, + /// The loudest channel of each frame in `line`, same indexing. + peaks: Vec, + /// Where the next frame is written; the frame read out is the one after it. + at: usize, + /// Frames still to be swallowed before anything is emitted -- the empty + /// delay line, which is how the latency is paid back (module docs). + warm: usize, + gain: f32, + ceiling: f32, + /// Where the knee starts, as an amplitude: under this the fast path runs + /// and no logarithm is taken. + knee_floor: f32, + release: f32, +} + +impl LimiterState { + pub fn new(params: &Limiter, sample_rate: u32, channels: usize) -> Self { + let channels = channels.max(1); + let frames = ((LOOKAHEAD_MS / 1000.0 * sample_rate as f32) as usize).max(1) + 1; + let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db; + Self { + channels, + line: vec![0.0; frames * channels], + peaks: vec![0.0; frames], + at: 0, + warm: frames - 1, + gain: 1.0, + ceiling: db_to_linear(ceiling_db), + knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0), + // One time constant per sample: the gain covers 63% of the way back + // in `RELEASE_MS`. + release: 1.0 - (-1000.0 / (RELEASE_MS * sample_rate as f32)).exp(), + } + } + + /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than + /// what came in by the delay line's length, once, at the first call. + pub fn process(&mut self, buf: &mut Vec) { + let channels = self.channels; + let frames = buf.len() / channels; + let mut out: Vec = Vec::with_capacity(buf.len()); + for f in 0..frames { + let frame = &buf[f * channels..(f + 1) * channels]; + let peak = frame.iter().fold(0.0f32, |m, s| m.max(s.abs())); + self.line[self.at * channels..(self.at + 1) * channels].copy_from_slice(frame); + self.peaks[self.at] = peak; + self.at = (self.at + 1) % self.peaks.len(); + + // Every frame still in the line, the one about to leave included: + // the gain below is therefore never larger than what the *emitted* + // frame needs, which is the whole no-overshoot guarantee. + let window = self.peaks.iter().fold(0.0f32, |m, &p| m.max(p)); + let want = match window <= self.knee_floor { + true => 1.0, + false => self.reduction(window), + }; + // Up is the release, down is instant -- and instant is safe here + // only because the frame it is for has not been emitted yet. + self.gain += (want - self.gain).max(0.0) * self.release; + self.gain = self.gain.min(want); + + if self.warm > 0 { + self.warm -= 1; + continue; + } + for c in 0..channels { + out.push(self.line[self.at * channels + c] * self.gain); + } + } + *buf = out; + } + + /// The gain the loudest frame in the window needs: 1.0 under the knee, the + /// knee's own curve across it, `ceiling/peak` above it. + fn reduction(&self, peak: f32) -> f32 { + let level = 20.0 * peak.log10(); + let ceiling = 20.0 * self.ceiling.log10(); + let over = level - ceiling; + let out = match over >= KNEE_DB / 2.0 { + true => ceiling, + // The cookbook's quadratic knee. At `over == 0` this is already + // `KNEE_DB/8` under the ceiling and it never crosses it, so nothing + // the knee passes needs a clamp behind it. + false => level - (over + KNEE_DB / 2.0).powi(2) / (2.0 * KNEE_DB), + }; + 10f32.powf((out - level) / 20.0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The promise the whole file exists for: a sum well past full scale comes + /// out under the ceiling, sample for sample, and the quiet part of the same + /// stream is left where it was. + #[test] + fn a_hot_mix_comes_out_under_the_ceiling() { + let rate = 48_000; + let params = Limiter { + ceiling_db: -3.0, + on: true, + }; + let mut state = LimiterState::new(¶ms, rate, 2); + // Half a second of quiet, then half a second at 4x full scale: the + // join is where an attack overshoot would show. + let mut buf: Vec = (0..rate) + .flat_map(|i| { + let t = i as f32 / rate as f32; + let amp = match i < rate / 2 { + true => 0.05, + false => 4.0, + }; + let s = amp * (t * 440.0 * std::f32::consts::TAU).sin(); + [s, s] + }) + .collect(); + let quiet_in = buf[..rate as usize / 2].to_vec(); + state.process(&mut buf); + let ceiling = db_to_linear(-3.0); + let peak = buf.iter().fold(0.0f32, |m, s| m.max(s.abs())); + assert!( + peak <= ceiling + 1e-6, + "peak {peak} passed the {ceiling} ceiling" + ); + // ...and it is not simply silence: the loud half is right at the wall. + assert!( + peak > ceiling * 0.99, + "peak {peak} is nowhere near the wall" + ); + // The quiet half is untouched, bar the frames the lookahead eats and + // the ones where the gain has already started coming down for the loud + // part that is about to arrive. + let head = quiet_in.len() / 2; + for (a, b) in buf[..head].iter().zip(&quiet_in[..head]) { + assert!((a - b).abs() < 1e-6, "{a} != {b} under the knee"); + } + // The delay line is paid back, not carried: the output is shorter by + // exactly the lookahead and nothing else. + assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2); + } + + /// Flat settings are a passthrough, which is what the export invariant + /// rests on: 0 dB is exactly 1.0, never 0.9999999. + #[test] + fn zero_db_is_exactly_unity() { + assert_eq!(db_to_linear(0.0), 1.0); + assert!((db_to_linear(-6.0) - 0.5011872).abs() < 1e-6); + assert!(!Limiter::default().is_active(), "off until asked for"); + assert_eq!( + Limiter::default().with_ceiling(-99.0).ceiling_db, + Limiter::MIN_DB + ); + assert_eq!( + Limiter::default().with_ceiling(f32::NAN).ceiling_db, + Limiter::default().ceiling_db + ); + } +} diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 5344c58..6d6db49 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -5,10 +5,17 @@ //! same reason that half exists: `mp4 0.14` has no `av01` sample entry at all, //! so an AV1 export is written as EBML by hand exactly as an AV1 import is read //! as EBML by hand ([`MkvMuxer`]). +//! +//! AV1 goes into an **mp4** too, and the missing sample entry is written by hand +//! there as well ([`Mp4Muxer::create_av1`]): the crate writes the file with an +//! `avc1` entry and this patches that entry into the `av01` + `av1C` pair the +//! spec asks for, which is the only box in a whole mp4 the crate cannot spell. +//! Both containers carry the timeline's AAC, so no format here writes a picture +//! whose sound was silently left behind. -use std::fs::File; -use std::io::{BufWriter, Seek, SeekFrom, Write}; -use std::path::Path; +use std::fs::{File, OpenOptions}; +use std::io::{BufWriter, Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; use mp4::{ AacConfig, AudioObjectType, AvcConfig, Bytes, ChannelConfig, FourCC, MediaConfig, Mp4Config, @@ -41,20 +48,32 @@ pub struct VideoParams<'a> { pub pps: &'a [u8], } -/// Read straight off the source file's `esds`: export copies AAC packets, it -/// never re-encodes, so the decoder config is passed through unchanged. +/// What the audio track declares: read straight off the source file's `esds` +/// where the export copies packets, and off this project's own encoder where it +/// re-encodes ([`crate::export`] decides which). `sample_rate` says the same +/// thing `freq_index` does and is carried beside it because Matroska states the +/// rate as a number rather than as an index into the AAC table. pub struct AudioParams { pub freq_index: u8, pub chan_conf: u8, + pub sample_rate: u32, } -/// Writes one H.264 track plus an optional AAC track. mp4 0.14 ignores +/// Writes one H.264 *or* AV1 track plus an optional AAC track. mp4 0.14 ignores /// `Mp4Sample::start_time` and builds all timing by accumulating `duration`, so /// every sample handed over must carry an exact duration or the tracks drift. pub struct Mp4Muxer { writer: Mp4Writer>, frame_duration: u32, has_audio: bool, + /// The sample entry an AV1 or HEVC file's is patched into at + /// [`finish`](Mp4Muxer::finish) -- entry type, configuration box type and + /// its payload (`av01`/`av1C`, `hvc1`/`hvcC`). `None` for H.264, which the + /// crate spells itself. See [`create_av1`](Mp4Muxer::create_av1). + entry: Option<([u8; 4], [u8; 4], Vec)>, + /// Where the file is, for that patch: the writer owns the handle it wrote + /// through and the patch reopens the finished file. + path: PathBuf, } const VIDEO_TRACK: u32 = 1; @@ -65,6 +84,91 @@ impl Mp4Muxer { path: &Path, video: &VideoParams, audio: Option<&AudioParams>, + ) -> crate::Result { + Self::open(path, video, audio, None) + } + + /// The same file with an AV1 track in it. `mp4 0.14` writes no `av01` sample + /// entry -- it has no AV1 anything -- so the file is written with an `avc1` + /// entry of placeholder parameter sets and that one entry is rewritten at + /// [`finish`](Mp4Muxer::finish) into the `av01` + `av1C` pair AV1-ISOBMFF + /// §2.2 asks for. Everything else in an mp4 is codec-blind (the sample + /// tables, the audio track, the movie header), so the entry is the only box + /// this has to spell by hand -- and the `moov` it lives in is written *after* + /// `mdat`, so growing it moves no sample and invalidates no chunk offset. + /// + /// The record's layout is the one OxideAV's `oxideav-mp4` writes + /// (`src/sample_entries.rs`, MIT): a `VisualSampleEntry` header verbatim, + /// then `av1C` -- the very four bytes and sequence header OBU [`MkvMuxer`] + /// puts in `CodecPrivate`, which is what makes the two containers' AV1 one + /// stream written twice rather than two. + /// + /// ponytail: the ceiling is that one entry. A second video track, or an AV1 + /// track beside an H.264 one, would need the walk in [`patch_av01`] to be + /// told *which* track it is patching; the upgrade path is passing the track + /// id it already knows down that walk. + pub fn create_av1( + path: &Path, + video: &Av1Params, + audio: Option<&AudioParams>, + ) -> crate::Result { + if video.config.is_empty() { + return Err("no AV1 sequence header for the track's av1C record".into()); + } + let mut av1c = AV1C_HEAD.to_vec(); + av1c.extend_from_slice(video.config); + Self::open( + path, + &VideoParams { + width: video.width, + height: video.height, + frame_rate: video.frame_rate, + // Never read by anything: the entry that holds them is replaced + // whole at `finish`. Four bytes because `AvcCBox::new` indexes + // `sps[1..=3]` for the profile it will never be asked for. + sps: &[0x67, 0x42, 0x00, 0x1E], + pps: &[0x68, 0xCE, 0x3C, 0x80], + }, + audio, + Some((*b"av01", *b"av1C", av1c)), + ) + } + + /// ...and the same trick for HEVC, which `mp4 0.14` cannot spell either: + /// the file is written with an `avc1` entry and that entry is rewritten at + /// [`finish`](Mp4Muxer::finish) into the `hvc1` + `hvcC` pair ISO/IEC + /// 14496-15 §8.4.1 asks for -- the record being the very bytes the Matroska + /// file puts in `CodecPrivate`, so the two containers carry one stream. + /// `hvc1` rather than `hev1`: the samples this writes carry no parameter + /// sets (they are dropped into `hvcC`), which is exactly what the `hvc1` + /// name promises a reader. + pub fn create_hevc( + path: &Path, + video: &HevcParams, + audio: Option<&AudioParams>, + ) -> crate::Result { + if video.hvcc.is_empty() { + return Err("no hvcC record for the track's sample entry".into()); + } + Self::open( + path, + &VideoParams { + width: video.width, + height: video.height, + frame_rate: video.frame_rate, + sps: &[0x67, 0x42, 0x00, 0x1E], + pps: &[0x68, 0xCE, 0x3C, 0x80], + }, + audio, + Some((*b"hvc1", *b"hvcC", video.hvcc.to_vec())), + ) + } + + fn open( + path: &Path, + video: &VideoParams, + audio: Option<&AudioParams>, + entry: Option<([u8; 4], [u8; 4], Vec)>, ) -> crate::Result { if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { return Err(format!("bad frame rate {}", video.frame_rate).into()); @@ -88,10 +192,15 @@ impl Mp4Muxer { &Mp4Config { major_brand: FourCC::from(*b"isom"), minor_version: 512, + // The codec's own brand among them, so a reader that picks a + // parser off `ftyp` is told which of the two this is. compatible_brands: vec![ FourCC::from(*b"isom"), FourCC::from(*b"iso2"), - FourCC::from(*b"avc1"), + FourCC::from(match &entry { + Some((kind, ..)) => *kind, + None => *b"avc1", + }), FourCC::from(*b"mp41"), ], // The video track's own, deliberately: `mp4` converts every @@ -116,6 +225,9 @@ impl Mp4Muxer { })?; if let Some(audio) = audio { let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; + // The index's own rate, not `audio.sample_rate`: this is the clock + // an `stts` counts in and the `esds` states the index, so the two + // must not be able to disagree. let sample_rate = freq_index.freq(); writer.add_track(&TrackConfig { track_type: TrackType::Audio, @@ -134,6 +246,8 @@ impl Mp4Muxer { writer, frame_duration, has_audio: audio.is_some(), + entry, + path: path.to_path_buf(), }) } @@ -154,6 +268,29 @@ impl Mp4Muxer { Ok(()) } + /// One coded picture already framed the way its sample carries it: an AV1 + /// temporal unit is the low-overhead OBU stream the encoder handed over + /// (nothing to reframe, exactly as a Matroska block holds it), and an HEVC + /// sample is the length-prefixed NALs [`annex_b_to_hvcc`] made. `key` is the + /// encoder's own word for a unit a decoder may start on -- an mp4 says it in + /// `stss` where Matroska says it in the block flags. + pub fn write_coded_sample(&mut self, obus: &[u8], key: bool) -> crate::Result<()> { + if obus.is_empty() { + return Err("an empty coded picture".into()); + } + self.writer.write_sample( + VIDEO_TRACK, + &Mp4Sample { + start_time: 0, + duration: self.frame_duration, + rendering_offset: 0, + is_sync: key, + bytes: Bytes::copy_from_slice(obus), + }, + )?; + Ok(()) + } + /// One raw AAC packet (no ADTS header), copied verbatim from the source -- /// or one of the hand-written silent ones a gap is filled with. Every AAC-LC /// access unit is [`AAC_PACKET_SAMPLES`] frames, gap or not. @@ -178,10 +315,138 @@ impl Mp4Muxer { pub fn finish(mut self) -> crate::Result<()> { self.writer.write_end()?; - Ok(()) + let Self { + writer, + entry, + path, + .. + } = self; + // Not a `drop`: the buffered tail of `moov` has to be on disk before the + // patch below reads it back, and a `BufWriter` swallows the error of + // flushing it on drop. + writer.into_writer().flush()?; + match entry { + Some((kind, config_kind, config)) => patch_entry(&path, &kind, &config_kind, &config), + None => Ok(()), + } } } +/// Rewrites the finished file's one video sample entry from the `avc1` the crate +/// wrote into the `av01` + `av1C` an AV1 track declares -- or the `hvc1` + +/// `hvcC` an HEVC one does. Called once, on a complete file, and only for a file +/// [`Mp4Muxer::create_av1`] or [`Mp4Muxer::create_hevc`] opened. +/// +/// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only +/// ever rewrites the tail of the file: no sample moves and no chunk offset in +/// `co64` changes. The box tree is rebuilt rather than patched in place, which +/// is what keeps every ancestor's size right by construction. +fn patch_entry( + path: &Path, + kind: &[u8; 4], + config_kind: &[u8; 4], + config: &[u8], +) -> crate::Result<()> { + let mut file = OpenOptions::new().read(true).write(true).open(path)?; + let end = file.metadata()?.len(); + let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?; + let patched = swap_entry(&payload, 0, kind, config_kind, config) + .ok_or("no avc1 sample entry to rewrite")?; + let mut out = Vec::with_capacity(patched.len() + 8); + push_box(&mut out, b"moov", &patched); + file.seek(SeekFrom::Start(at))?; + file.write_all(&out)?; + file.set_len(at + out.len() as u64)?; + file.flush()?; + Ok(()) +} + +/// Offset and payload of the first top-level box of type `want`. +fn top_level(file: &mut File, end: u64, want: &[u8; 4]) -> crate::Result)>> { + let mut at = 0u64; + while at + 8 <= end { + let mut header = [0u8; 8]; + file.seek(SeekFrom::Start(at))?; + file.read_exact(&mut header)?; + let (size, head_len) = match u32::from_be_bytes(header[..4].try_into().unwrap()) { + 0 => (end - at, 8), + 1 => { + let mut large = [0u8; 8]; + file.read_exact(&mut large)?; + (u64::from_be_bytes(large), 16) + } + size => (u64::from(size), 8), + }; + if size < head_len || at + size > end { + return Err("truncated box in the file's top level".into()); + } + if &header[4..8] == want { + let mut payload = vec![0u8; (size - head_len) as usize]; + file.read_exact(&mut payload)?; + return Ok(Some((at, payload))); + } + at += size; + } + Ok(None) +} + +/// `moov` down to the sample descriptions, which is where the entry lives. +const STSD_PATH: [&[u8; 4]; 5] = [b"trak", b"mdia", b"minf", b"stbl", b"stsd"]; + +/// The box at `depth` of [`STSD_PATH`], rebuilt with its `avc1` entry replaced. +/// `None` where this branch holds no such entry -- an audio `trak` is walked +/// into and comes back untouched, which is how the *video* track is found +/// without being told which id it has. +fn swap_entry( + payload: &[u8], + depth: usize, + want: &[u8; 4], + config_kind: &[u8; 4], + config: &[u8], +) -> Option> { + if depth == STSD_PATH.len() { + // stsd is a FullBox (4) plus entry_count (4), then the sample entries. + let mut out = payload.get(..8)?.to_vec(); + let (kind, entry) = crate::demux::boxes(payload.get(8..)?).next()?; + if kind != b"avc1" { + return None; + } + // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and all) + // before its codec box, and `av01` and `hvc1` carry exactly the same + // ones -- so the header is kept and only the configuration box is + // swapped. + let mut swapped = entry.get(..78)?.to_vec(); + push_box(&mut swapped, config_kind, config); + push_box(&mut out, want, &swapped); + return Some(out); + } + let mut out = Vec::with_capacity(payload.len()); + let mut done = false; + for (kind, child) in crate::demux::boxes(payload) { + let patched = match !done && kind == STSD_PATH[depth] { + true => swap_entry(child, depth + 1, want, config_kind, config), + false => None, + }; + match patched { + Some(child) => { + push_box(&mut out, kind, &child); + done = true; + } + None => push_box(&mut out, kind, child), + } + } + done.then_some(out) +} + +/// One mp4 box: 32-bit size, four-character type, payload. Every box inside a +/// `moov` fits that form -- the 64-bit one exists for `mdat`, which this never +/// rewrites. +fn push_box(out: &mut Vec, kind: &[u8; 4], payload: &[u8]) { + out.extend_from_slice(&(payload.len() as u32 + 8).to_be_bytes()); + out.extend_from_slice(kind); + out.extend_from_slice(payload); +} + // Matroska element ids, written with the leading length marker they carry in the // file -- the same spelling `demux` reads them back with. const EBML: u32 = 0x1A45_DFA3; @@ -210,6 +475,10 @@ const DEFAULT_DURATION: u32 = 0x23E383; const VIDEO: u32 = 0xE0; const PIXEL_WIDTH: u32 = 0xB0; const PIXEL_HEIGHT: u32 = 0xBA; +const AUDIO: u32 = 0xE1; +const SAMPLING_FREQUENCY: u32 = 0xB5; +const CHANNELS: u32 = 0x9F; +const CODEC_DELAY: u32 = 0x56AA; const CLUSTER: u32 = 0x1F43_B675; const CLUSTER_TIMESTAMP: u32 = 0xE7; const SIMPLE_BLOCK: u32 = 0xA3; @@ -251,11 +520,29 @@ pub struct Av1Params<'a> { pub config: &'a [u8], } -/// Writes one AV1 video track as Matroska (`.mkv`). Picture only: this project -/// has no encoder for any sound Matroska carries, and copying the timeline's AAC -/// in would write a track its own reader refuses (`audio::AudioSession::open` -/// leaves a Matroska file silent) -- so the sound is named as left out by the -/// front-end rather than written unplayable. +/// What an HEVC track declares in either container: the `hvcC` record +/// [`hvcc_record`] built out of the encoder's own VPS/SPS/PPS. The dimensions +/// are the *displayed* ones -- the coded picture is padded up to the 16-sample +/// CTB grid and the SPS crops it back with a conformance window, which is the +/// size a decoder outputs and therefore the size the container states. +pub struct HevcParams<'a> { + pub width: u32, + pub height: u32, + pub frame_rate: f64, + pub hvcc: &'a [u8], +} + +/// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC +/// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the +/// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what +/// symphonia's `mkv` reader -- this project's own way back in -- configures its +/// decoder from. An AV1 export used to be picture alone; a video file whose +/// sound was silently left behind is exactly the failure nobody notices until +/// the file has gone somewhere. +/// +/// The sound is *interleaved*: each packet is written into the cluster of the +/// picture it plays under, so a player has both by the time it needs them rather +/// than a file it must read to the end of to hear. /// /// The file is patched twice at [`finish`](MkvMuxer::finish) -- the segment size /// and the duration -- so a killed process leaves an unfinished file rather than @@ -272,22 +559,96 @@ pub struct MkvMuxer { cluster: Vec, cluster_ts: i64, frames: u64, + /// The AAC track, if the timeline has sound, and how far it has been + /// written. + audio: Option, +} + +/// The sound waiting to be interleaved into the clusters. +struct MkvAudio { + packets: Vec, + /// Packets already written. + next: usize, + /// Frames already written, which is what the next packet's timestamp is + /// counted from: every AAC-LC packet says its own length and they are not + /// assumed equal here. + samples: u64, + sample_rate: u32, } impl MkvMuxer { - pub fn create(path: &Path, video: &Av1Params) -> crate::Result { - if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { - return Err(format!("bad frame rate {}", video.frame_rate).into()); + /// `audio` is the whole track at once -- the export has it before it has a + /// single coded picture, and interleaving needs to look ahead of the frame + /// being written. + /// + /// ponytail: that is the copy path's own ceiling reappearing (the track sits + /// in memory, ~500 MB an hour); the upgrade path is the same streaming + /// `copy_segments` `export::copy_audio` names. + pub fn create( + path: &Path, + video: &Av1Params, + audio: Option<(&AudioParams, Vec)>, + ) -> crate::Result { + if video.config.is_empty() { + return Err("no AV1 sequence header for the track's CodecPrivate".into()); } - if video.width == 0 || video.height == 0 { - return Err(format!("bad dimensions {}x{}", video.width, video.height).into()); + let mut av1c = AV1C_HEAD.to_vec(); + av1c.extend_from_slice(video.config); + Self::open( + path, + video.width, + video.height, + video.frame_rate, + b"V_AV1", + &av1c, + audio, + ) + } + + /// The same file with an HEVC track in it: `V_MPEGH/ISO/HEVC`, whose + /// `CodecPrivate` is the very `hvcC` record an mp4 puts in its sample entry + /// ([`hvcc_record`]) -- and whose blocks are therefore length-prefixed NALs + /// like an mp4 sample's, not Annex B. That is what this engine's own reader + /// expects back (`demux`'s Matroska branch parses `CodecPrivate` as `hvcC` + /// and reframes the blocks by the length it states), and what every other + /// Matroska reader expects too. + pub fn create_hevc( + path: &Path, + video: &HevcParams, + audio: Option<(&AudioParams, Vec)>, + ) -> crate::Result { + if video.hvcc.is_empty() { + return Err("no hvcC record for the track's CodecPrivate".into()); } - let frame_ns = (1e9 / video.frame_rate).round() as u64; - if frame_ns == 0 { - return Err(format!("frame rate {} is too fast to time", video.frame_rate).into()); + Self::open( + path, + video.width, + video.height, + video.frame_rate, + b"V_MPEGH/ISO/HEVC", + video.hvcc, + audio, + ) + } + + fn open( + path: &Path, + width: u32, + height: u32, + frame_rate: f64, + codec_id: &[u8], + codec_private: &[u8], + audio: Option<(&AudioParams, Vec)>, + ) -> crate::Result { + if !frame_rate.is_finite() || frame_rate <= 0.0 { + return Err(format!("bad frame rate {frame_rate}").into()); } - if video.config.is_empty() { - return Err("no AV1 sequence header for the track's CodecPrivate".into()); + if width == 0 || height == 0 { + return Err(format!("bad dimensions {width}x{height}").into()); + } + let frame_ns = (1e9 / frame_rate).round() as u64; + if frame_ns == 0 { + return Err(format!("frame rate {frame_rate} is too fast to time").into()); } let mut head = Vec::new(); @@ -324,17 +685,18 @@ impl MkvMuxer { uint(&mut entry, TRACK_UID, 1); uint(&mut entry, TRACK_TYPE, 1); // video uint(&mut entry, FLAG_LACING, 0); - elem(&mut entry, CODEC_ID, b"V_AV1"); - let mut av1c = AV1C_HEAD.to_vec(); - av1c.extend_from_slice(video.config); - elem(&mut entry, CODEC_PRIVATE, &av1c); + elem(&mut entry, CODEC_ID, codec_id); + elem(&mut entry, CODEC_PRIVATE, codec_private); uint(&mut entry, DEFAULT_DURATION, frame_ns); let mut dims = Vec::new(); - uint(&mut dims, PIXEL_WIDTH, u64::from(video.width)); - uint(&mut dims, PIXEL_HEIGHT, u64::from(video.height)); + uint(&mut dims, PIXEL_WIDTH, u64::from(width)); + uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); elem(&mut entry, VIDEO, &dims); let mut tracks = Vec::new(); elem(&mut tracks, TRACK_ENTRY, &entry); + if let Some((audio, _)) = &audio { + elem(&mut tracks, TRACK_ENTRY, &aac_track_entry(audio)?); + } elem(&mut head, TRACKS, &tracks); let mut file = File::create(path)?; @@ -347,6 +709,12 @@ impl MkvMuxer { cluster: Vec::new(), cluster_ts: 0, frames: 0, + audio: audio.map(|(params, packets)| MkvAudio { + packets, + next: 0, + samples: 0, + sample_rate: params.sample_rate.max(1), + }), }) } @@ -373,14 +741,58 @@ impl MkvMuxer { self.cluster_ts = ts; uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); } - let mut block = Vec::with_capacity(obus.len() + 4); - block.push(0x81); // track number 1, as a one-byte EBML integer + // The sound this picture plays under goes in first, into the cluster the + // picture opened: a player reads the two together. + self.drain_audio(ts)?; + self.block(1, ts, key, obus); + self.frames += 1; + Ok(()) + } + + /// Every audio packet whose timestamp has been reached, into the current + /// cluster. `i64::MAX` at [`finish`](MkvMuxer::finish) drains what is left -- + /// the sound of a timeline can outlast its last picture by a packet. + fn drain_audio(&mut self, until: i64) -> crate::Result<()> { + loop { + let Some(audio) = &mut self.audio else { + return Ok(()); + }; + let Some(packet) = audio.packets.get_mut(audio.next) else { + return Ok(()); + }; + // The packet's own start, in whole milliseconds: every AAC-LC packet + // states its length, so a track of them is counted rather than + // assumed to be 1024 frames each. + let rate = i64::from(audio.sample_rate); + let ts = (audio.samples as i64 * 1000 + rate / 2) / rate; + if ts > until { + return Ok(()); + } + // Taken, not copied: the packet is written once and the track can be + // hundreds of megabytes. + let bytes = std::mem::take(&mut packet.bytes); + audio.samples += u64::from(packet.samples); + audio.next += 1; + // A cluster of its own where the sound has run past what a 16-bit + // relative timestamp reaches, which only the tail drain can do. + if self.cluster.is_empty() || ts - self.cluster_ts >= CLUSTER_MS { + self.flush()?; + self.cluster_ts = ts; + uint(&mut self.cluster, CLUSTER_TIMESTAMP, ts as u64); + } + self.block(2, ts, true, &bytes); + } + } + + /// One `SimpleBlock` of `track`, timed against the open cluster. Every AAC + /// packet is a keyframe; a picture is one when the encoder said so. + fn block(&mut self, track: u8, ts: i64, key: bool, payload: &[u8]) { + let mut block = Vec::with_capacity(payload.len() + 4); + block.push(0x80 | track); // the track number as a one-byte EBML integer block.extend_from_slice(&((ts - self.cluster_ts) as i16).to_be_bytes()); block.push(if key { 0x80 } else { 0 }); - block.extend_from_slice(obus); + block.extend_from_slice(payload); elem(&mut self.cluster, SIMPLE_BLOCK, &block); - self.frames += 1; - Ok(()) } fn flush(&mut self) -> crate::Result<()> { @@ -399,6 +811,9 @@ impl MkvMuxer { /// Closes the last cluster and patches the two fields that could not be /// known while writing: the segment's size and the presentation duration. pub fn finish(mut self) -> crate::Result<()> { + // Whatever sound outlasts the last picture, before the last cluster is + // closed: a track cut short here is a file that goes silent at the end. + self.drain_audio(i64::MAX)?; self.flush()?; if self.frames == 0 { return Err("no frames were written to the Matroska file".into()); @@ -417,6 +832,52 @@ impl MkvMuxer { } } +/// The `TrackEntry` of the AAC track: `A_AAC`, whose `CodecPrivate` is the +/// two-byte `AudioSpecificConfig` an mp4 states inside its `esds` -- object type +/// 2 (AAC-LC), the sample rate as its index into the AAC table, and the channel +/// configuration. symphonia's `mkv` reader hands exactly these bytes to its AAC +/// decoder, which is how a file written here reads back here. +/// +/// `CodecDelay` is one packet: the first AAC access unit of both paths that +/// reach this -- a copy, whose head packet is the source's priming, and this +/// project's own encoder, whose delay is one 1024-frame block -- is that delay, +/// and an mp4 reader drops it by convention where Matroska has to be told in +/// nanoseconds. +fn aac_track_entry(audio: &AudioParams) -> crate::Result> { + let rate = audio.sample_rate; + if rate == 0 || audio.chan_conf == 0 { + return Err(format!( + "an AAC track at {rate} Hz with {} channels", + audio.chan_conf + ) + .into()); + } + let mut entry = Vec::new(); + uint(&mut entry, TRACK_NUMBER, 2); + uint(&mut entry, TRACK_UID, 2); + uint(&mut entry, TRACK_TYPE, 2); // audio + uint(&mut entry, FLAG_LACING, 0); + elem(&mut entry, CODEC_ID, b"A_AAC"); + // 5 bits object type, 4 bits sample rate index, 4 bits channel config, and + // three zero bits to the byte -- the whole of an AAC-LC AudioSpecificConfig. + let asc = (2u16 << 11) + | (u16::from(audio.freq_index & 0xF) << 7) + | (u16::from(audio.chan_conf & 0xF) << 3); + elem(&mut entry, CODEC_PRIVATE, &asc.to_be_bytes()); + uint( + &mut entry, + CODEC_DELAY, + u64::from(AAC_PACKET_SAMPLES) * 1_000_000_000 / u64::from(rate), + ); + let mut audio_elem = Vec::new(); + put_id(&mut audio_elem, SAMPLING_FREQUENCY); + put_size(&mut audio_elem, 8); + audio_elem.extend_from_slice(&f64::from(rate).to_be_bytes()); + uint(&mut audio_elem, CHANNELS, u64::from(audio.chan_conf)); + elem(&mut entry, AUDIO, &audio_elem); + Ok(entry) +} + /// The sequence header OBU of a coded temporal unit, for the track's /// `CodecPrivate`. `None` when the unit carries none, which the first keyframe /// of a stream never may -- no decoder can start without it. @@ -528,6 +989,91 @@ pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> { Some((sps, pps)) } +/// The `HEVCDecoderConfigurationRecord` an HEVC track declares, built out of the +/// parameter sets the encoder put in its first access unit -- the exact record +/// `demux::parse_hvcc` reads back, which is what makes an export of this +/// project's own something it can re-open. +/// +/// The 22 fixed bytes before the arrays: the 12-byte `profile_tier_level` is +/// copied straight out of the SPS (its first 12 bytes after the two-byte NAL +/// header and the four `sps_video_parameter_set_id`/`sps_max_sub_layers_minus1` +/// /`sps_temporal_id_nesting_flag` bits -- §7.3.2.2 puts the PTL there and the +/// hvcC header states the same fields in the same order), and the rest is what +/// this encoder is: 4:2:0, 8-bit, one temporal layer, 4-byte NAL lengths. Only +/// the *arrays* are read by anything here, but a record whose header lied about +/// the profile would be a file `ffprobe` disagrees with. +/// +/// `None` where the unit carries no VPS, SPS or PPS -- the first coded intra AU +/// always carries all three. +pub fn hvcc_record(annex_b: &[u8]) -> Option> { + let nals = split_annex_b(annex_b); + let of = |kind: u8| nals.iter().copied().find(|n| hevc_nal_type(n) == kind); + let (vps, sps, pps) = (of(HEVC_VPS)?, of(HEVC_SPS)?, of(HEVC_PPS)?); + // The SPS as a decoder reads it: the emulation-prevention bytes the encoder + // escaped it with are not part of the syntax, and a run of zeros in the + // constraint flags is exactly where one lands. + let rbsp = unescape(sps.get(2..)?); + let mut rec = vec![1u8]; // configurationVersion + rec.extend_from_slice(rbsp.get(1..13)?); // profile_tier_level, verbatim + rec.extend_from_slice(&[0xF0, 0x00]); // min_spatial_segmentation_idc = 0 + rec.push(0xFC); // parallelismType = 0 (unknown) + rec.push(0xFC | 1); // chroma_format_idc = 1 (4:2:0) + rec.push(0xF8); // bit_depth_luma_minus8 = 0 + rec.push(0xF8); // bit_depth_chroma_minus8 = 0 + rec.extend_from_slice(&0u16.to_be_bytes()); // avgFrameRate: unstated + // constantFrameRate 0, numTemporalLayers 1, temporalIdNested 1, + // lengthSizeMinusOne 3 -- the same 4-byte prefix `annex_b_to_hvcc` writes. + rec.push(0b00_001_1_11); + rec.push(3); // numOfArrays + for (kind, nal) in [(HEVC_VPS, vps), (HEVC_SPS, sps), (HEVC_PPS, pps)] { + rec.push(0x80 | kind); // array_completeness = 1, NAL_unit_type + rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus + rec.extend_from_slice(&(nal.len() as u16).to_be_bytes()); + rec.extend_from_slice(nal); + } + Some(rec) +} + +/// One HEVC access unit as a sample of both containers: 4-byte length prefixes, +/// parameter sets dropped (they are in the `hvcC`, which is what `hvc1` and a +/// Matroska `CodecPrivate` both promise). `None` where the unit holds no coded +/// slice at all. +pub(crate) fn annex_b_to_hvcc(annex_b: &[u8]) -> Option> { + let mut out = Vec::with_capacity(annex_b.len()); + for nal in split_annex_b(annex_b) { + // 32 VPS, 33 SPS, 34 PPS, 35 AUD -- and everything from 40 up is + // non-VCL padding no decoder needs to start. + if matches!(hevc_nal_type(nal), HEVC_VPS | HEVC_SPS | HEVC_PPS | 35) { + continue; + } + out.extend_from_slice(&(nal.len() as u32).to_be_bytes()); + out.extend_from_slice(nal); + } + (!out.is_empty()).then_some(out) +} + +/// §7.3.1.2 `nal_unit_type`, the six bits after the forbidden_zero_bit. +fn hevc_nal_type(nal: &[u8]) -> u8 { + nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F) +} + +const HEVC_VPS: u8 = 32; +const HEVC_SPS: u8 = 33; +const HEVC_PPS: u8 = 34; + +/// A coded NAL payload back to its RBSP: every `00 00 03` loses the `03` +/// (§7.3.1.1). Only ever asked of an SPS, which is short. +fn unescape(nal: &[u8]) -> Vec { + let mut out = Vec::with_capacity(nal.len()); + for (i, &byte) in nal.iter().enumerate() { + if byte == 3 && i >= 2 && nal[i - 1] == 0 && nal[i - 2] == 0 { + continue; + } + out.push(byte); + } + out +} + /// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that /// buffered instead of coding hands back an empty buffer, and one that emitted /// only parameter sets has no sample to write -- both are for the caller to skip @@ -750,6 +1296,7 @@ mod tests { Some(&AudioParams { freq_index: 4, // 44100 chan_conf: 2, + sample_rate: 44_100, }), ) .unwrap(); @@ -840,6 +1387,168 @@ mod tests { assert_eq!(id, [0x1F, 0x43, 0xB6, 0x75]); } + /// One second of a 440 Hz tone as AAC-LC packets, through the very encoder + /// an export re-encodes with: real bitstream, so a file written with it is + /// one a decoder either plays or does not. + fn tone_packets(rate: u32, channels: u16) -> Vec { + let frames = rate as usize; + let mut pcm = Vec::with_capacity(frames * usize::from(channels)); + for i in 0..frames { + let s = (i as f32 * 440.0 * std::f32::consts::TAU / rate as f32).sin() * 0.5; + for _ in 0..channels { + pcm.push(s); + } + } + let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig::default()); + encoder.push_pcm(&pcm, channels, rate).unwrap(); + encoder.finish(); + let mut packets = Vec::new(); + while let Ok(packet) = encoder.next_packet() { + packets.push(crate::AacPacket { + bytes: packet.data, + samples: packet.duration, + }); + } + assert!(packets.len() > 10, "a second of audio is many packets"); + packets + } + + /// The Matroska file carries **sound**, and this project's own reader is + /// what hears it: picture and an AAC track out through the muxer, then the + /// picture back through our EBML reader and the sound back through the + /// symphonia `mkv` reader `audio::Track::open` uses. An AV1 export used to be + /// picture alone, which is a file whose sound went missing with nobody told. + #[test] + fn a_matroska_file_carries_its_picture_and_its_sound() { + let sequence = obu(1, &[0x11, 0x22, 0x33]); + let mut key = sequence.clone(); + key.extend_from_slice(&obu(6, &[0xAA; 8])); + let inter = obu(6, &[0xBB; 5]); + let packets = tone_packets(48_000, 2); + let heard: usize = packets.iter().map(|p| p.samples as usize).sum(); + + let out = std::env::temp_dir().join(format!("ve_mkv_sound_{}.mkv", std::process::id())); + let mut muxer = MkvMuxer::create( + &out, + &Av1Params { + width: 640, + height: 360, + frame_rate: 30.0, + config: av1_sequence_header(&key).unwrap(), + }, + Some(( + &AudioParams { + freq_index: 3, // 48000 + chan_conf: 2, + sample_rate: 48_000, + }, + packets, + )), + ) + .unwrap(); + // Half a second of picture under a second of sound: the tail of the + // audio outlives the last frame and must still be in the file. + muxer.write_frame(&key, true).unwrap(); + for _ in 0..14 { + muxer.write_frame(&inter, false).unwrap(); + } + muxer.finish().unwrap(); + + // The picture is untouched by the sound beside it: same units, same + // count, same sequence header in front of the keyframe. + let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen"); + assert_eq!(meta.frame_count, 15); + assert_eq!(meta.codec, crate::demux::Codec::Av1); + let first = demuxer.next_access_unit().unwrap().unwrap(); + assert_eq!(&first[sequence.len()..], &key[..]); + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); + + // ...and the sound is there, by name and then by ear. + assert_eq!( + crate::demux::matroska_audio_codec(&out).unwrap().as_deref(), + Some("A_AAC") + ); + let probe = crate::audio::AudioSession::probe(&out, 0) + .unwrap() + .expect("the file has an audio track"); + assert_eq!((probe.sample_rate, probe.channels), (48_000, 2)); + let (audio, chunks) = crate::audio::AudioSession::open(&out) + .unwrap() + .expect("decodes through symphonia's mkv reader"); + assert_eq!((audio.sample_rate, audio.channels), (48_000, 2)); + let samples: Vec = chunks.into_iter().flat_map(|c| c.samples).collect(); + let frames = samples.len() / 2; + assert!( + frames + 1024 >= heard && frames <= heard + 2048, + "{frames} frames read back of {heard} written" + ); + let rms = (samples.iter().map(|s| s * s).sum::() / samples.len() as f32).sqrt(); + assert!(rms > 0.1, "the tone came back silent (rms {rms})"); + std::fs::remove_file(&out).unwrap(); + } + + /// The same stream in the other container: AV1 into an mp4, whose `av01` + /// sample entry is written by hand, read back through our own demuxer -- + /// which is the only test that the patched box tree is still an mp4. + #[test] + fn an_av1_track_round_trips_through_an_mp4() { + let sequence = obu(1, &[0x11, 0x22, 0x33]); + let mut key = sequence.clone(); + key.extend_from_slice(&obu(6, &[0xAA; 8])); + let inter = obu(6, &[0xBB; 5]); + let packets = tone_packets(48_000, 2); + + let out = std::env::temp_dir().join(format!("ve_mp4_av1_{}.mp4", std::process::id())); + let mut muxer = Mp4Muxer::create_av1( + &out, + &Av1Params { + width: 640, + height: 360, + frame_rate: 30.0, + config: av1_sequence_header(&key).unwrap(), + }, + Some(&AudioParams { + freq_index: 3, + chan_conf: 2, + sample_rate: 48_000, + }), + ) + .unwrap(); + muxer.write_coded_sample(&key, true).unwrap(); + muxer.write_coded_sample(&inter, false).unwrap(); + muxer.write_coded_sample(&inter, false).unwrap(); + for packet in &packets { + muxer.write_audio_packet(&packet.bytes).unwrap(); + } + muxer.finish().unwrap(); + + let (meta, mut demuxer) = crate::demux::Demuxer::open(&out).expect("reopen"); + assert_eq!(meta.codec, crate::demux::Codec::Av1, "read back as AV1"); + assert_eq!((meta.width, meta.height), (640, 360)); + assert!((meta.frame_rate - 30.0).abs() < 1e-6, "{}", meta.frame_rate); + assert_eq!(meta.frame_count, 3); + // The sequence header off `av1C` in front of the keyframe, exactly as + // the Matroska reader puts the one off `CodecPrivate` there. + let first = demuxer.next_access_unit().unwrap().unwrap(); + assert_eq!(&first[..sequence.len()], &sequence[..]); + assert_eq!(&first[sequence.len()..], &key[..]); + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); + assert_eq!(demuxer.next_access_unit().unwrap().unwrap(), inter); + assert!(demuxer.next_access_unit().unwrap().is_none()); + assert_eq!(demuxer.seek_to_sync_at_or_before(2), 0, "one keyframe"); + + // ...and the audio track beside it is the mp4 path's own, unchanged by + // the patch: same packets, playable through the same reader. + let (audio, chunks) = crate::audio::AudioSession::open(&out) + .unwrap() + .expect("the mp4's AAC track"); + assert_eq!((audio.sample_rate, audio.channels), (48_000, 2)); + let samples: Vec = chunks.into_iter().flat_map(|c| c.samples).collect(); + let rms = (samples.iter().map(|s| s * s).sum::() / samples.len() as f32).sqrt(); + assert!(rms > 0.1, "the tone came back silent (rms {rms})"); + std::fs::remove_file(&out).unwrap(); + } + /// The Matroska half of the round trip, with no encoder in it: three coded /// units out through the muxer and back in through our own demuxer, which is /// where the hand-written EBML meets the hand-written EBML reader. @@ -861,6 +1570,7 @@ mod tests { frame_rate: 30.0, config, }, + None, ) .unwrap(); muxer.write_frame(&key, true).unwrap(); @@ -903,6 +1613,7 @@ mod tests { frame_rate: 30.0, config: &[], }, + None, ) .is_err() ); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 19aa574..12b149d 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -22,10 +22,10 @@ use crate::ao::AoSession; use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::color::ColorParams; -use crate::decode::{DecodeSession, Frame, Worker}; +use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::eq::EqParams; -use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span, Speed}; +use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed}; use crate::scale::{Composer, FitPolicy}; /// How long the feeder waits out a full ring. The ring holds a second, so this @@ -40,10 +40,11 @@ const RING_FULL_WAIT: Duration = Duration::from_millis(10); /// honest; both are what a video imported onto such a timeline is held to /// ([`matches_timeline`]). /// -/// ponytail: a 25 fps video refused by an audio-only timeline it could have -/// defined is the ceiling here. Upgrade path is adopting the first *picture's* -/// rate and codec on import, which means retiming every audio clip already -/// placed in frames. +/// ponytail: a 25 fps video imported onto an audio-only timeline it could have +/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read +/// through [`Rate`] like any other file shot at another rate rather than +/// defining one. Upgrade path is adopting the first *picture's* rate and codec +/// on import, which means retiming every audio clip already placed in frames. const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); /// The frame rate a timeline scaffolded from a still image runs at, for @@ -90,8 +91,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 +111,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 { @@ -135,6 +161,11 @@ pub struct PlaybackSession { frames: Receiver, /// The current decode worker. worker: Worker, + /// What that worker opened -- hardware, software, a still, a gap -- written + /// by the worker itself and read by [`decode_backend`](Self::decode_backend). + /// Replaced with the stream at every seek, so it always describes the + /// pictures currently arriving and never the clip before them. + backend: BackendCell, /// Workers cancelled by a seek or a clip change, waiting to be reaped. /// Joining one inline costs whatever VA-API init it is still inside (98 ms /// measured worst case), which is a visible hitch on the caller's thread; @@ -168,6 +199,20 @@ pub struct PlaybackSession { /// not -- with the single exception `sources` itself has, /// [`Self::remove_source`], which takes the same entry out of both. counts: Vec, + /// What each source's own frame rate is against this timeline's, indexed + /// and grown exactly as [`Self::counts`] is (and shortened with it by + /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the + /// timeline's rate -- and for a still and a song, which have no rate of + /// their own -- so a single-rate project converts nothing anywhere. + /// + /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that + /// knows which frames of the file those are, and only + /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask. + rates: Vec, + /// The rate of the source the current worker is decoding, kept beside + /// [`Self::span`] because the frames coming back are numbered in *its* + /// file's frames and nothing else can put them back on the timeline. + span_rate: Rate, /// What the current video worker was opened for: where it sits on the /// timeline, how long it runs, and which source frame it started at -- /// together they rewrite a source frame index into a timeline one. Not a @@ -234,12 +279,16 @@ impl PlaybackSession { native: (meta.width, meta.height), frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), clock: PlaybackClock::new(source), audio, audio_disabled, project, counts: vec![meta.frame_count], + // Source 0 *is* the timeline's rate: it defined it. + rates: vec![Rate::REAL_TIME], + span_rate: Rate::REAL_TIME, span, eos: false, }) @@ -328,6 +377,7 @@ impl PlaybackSession { native: (width, height), frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), // The song keeps the clock, as a video's own sound does -- and wall // time keeps it on a machine with no device, where the picture @@ -340,6 +390,9 @@ impl PlaybackSession { audio_disabled, project, counts: vec![meta.frame_count], + // Source 0 *is* the timeline's rate: it defined it. + rates: vec![Rate::REAL_TIME], + span_rate: Rate::REAL_TIME, span, eos: false, }) @@ -400,12 +453,16 @@ impl PlaybackSession { native: (meta.width, meta.height), frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), clock: PlaybackClock::new(ClockSource::Wall), audio: None, audio_disabled: None, project, counts: vec![meta.frame_count], + // Source 0 *is* the timeline's rate: it defined it. + rates: vec![Rate::REAL_TIME], + span_rate: Rate::REAL_TIME, span, eos: false, }) @@ -417,10 +474,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 +487,38 @@ 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*. + // + // A v9 file says what rate it was cut at, and that answer beats the + // scaffold's *where the scaffold has none to give*: a still and a song + // are both given a made-up rate (`IMAGE_ONLY_RATE`, + // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come + // back at 30 fps however it was cut. A scaffold with a picture keeps + // defining the timeline as it always did -- it is the file every clip + // on the lane was conformed to, and the two agree by construction. + let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0); + 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 @@ -451,7 +533,8 @@ impl PlaybackSession { // like every other worker opened here. let (mut meta, stream) = match crate::is_audio(&first.path) { true => { - let (width, height, frame_rate) = AUDIO_ONLY_CANVAS; + let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS; + let frame_rate = saved_fps.unwrap_or(canvas_fps); let meta = VideoMeta { width, height, @@ -468,11 +551,12 @@ impl PlaybackSession { false if crate::is_image(&first.path) => { let still = crate::decode::Still::open(&first.path) .map_err(|e| format!("source {}: {e}", first.path.display()))?; + let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE); let meta = VideoMeta { width: still.width, height: still.height, - frame_rate: IMAGE_ONLY_RATE, - frame_count: image_frames(IMAGE_ONLY_RATE), + frame_rate, + frame_count: image_frames(frame_rate), codec: Codec::H264, }; let stream = DecodeSession::open_still( @@ -503,8 +587,22 @@ 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()); + // Beside it, one entry per source, grown at every `push` below: the + // scaffold defines the rate, so it is read frame for frame; every other + // one is however long it is *in this timeline's frames*, which is the + // length `import` noted for it and the wall the clip check below holds + // it to. + let mut rates = Vec::with_capacity(doc.sources.len()); + for (i, source) in doc.sources.iter().enumerate() { + if i == scaffold { + counts.push(meta.frame_count); + rates.push(Rate::REAL_TIME); + 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 @@ -513,6 +611,7 @@ impl PlaybackSession { crate::decode::image_size(&source.path) .map_err(|e| format!("source {}: {e}", source.path.display()))?; counts.push(image_frames(meta.frame_rate)); + rates.push(Rate::REAL_TIME); continue; } // A source with no picture is checked on what it does have, and @@ -522,13 +621,15 @@ impl PlaybackSession { audio_matches(source, &first_audio) .map_err(|e| format!("source {}: {e}", source.path.display()))?; counts.push(audio_frames(&source.path, meta.frame_rate)?); + rates.push(Rate::REAL_TIME); continue; } let (other, _) = Demuxer::open(&source.path) .map_err(|e| format!("source {}: {e}", source.path.display()))?; - matches_timeline(source, &other, &meta, &first_audio) + let rate = matches_timeline(source, &other, &meta, &first_audio) .map_err(|e| format!("source {}: {e}", source.path.display()))?; - counts.push(other.frame_count); + counts.push(rate.timeline_at(other.frame_count)); + rates.push(rate); } // The video lane can only play files that have pictures. Hand-written // (or hand-edited) project files are the one door this can come in @@ -572,19 +673,29 @@ impl PlaybackSession { } let playhead = doc.playhead; - let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?; + let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)? + .with_mix(&doc.gains, doc.limiter); let span = project.composite_span_at(0); // Last, because it is the one thing here that cannot be taken back: the // feeder thread outlives the `Audio` value (it holds its own clones) and // 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, frames: stream.frames, worker: stream.worker, + backend: stream.backend, retired: Vec::new(), clock: PlaybackClock::new(match audio { Some(_) => ClockSource::Audio, @@ -594,6 +705,8 @@ impl PlaybackSession { audio_disabled, project, counts, + rates, + span_rate: Rate::REAL_TIME, span, eos: false, }; @@ -610,6 +723,24 @@ impl PlaybackSession { &self.meta } + /// What the pictures now arriving are being decoded by: the clip under the + /// playhead, since one video worker feeds the composite at a time. An + /// atomic load -- a front-end may ask it every repaint -- and it is what + /// *opened*, so a clip whose hardware session fell back to software reads + /// [`Backend::Software`] from the frame that fallback happened. + pub fn decode_backend(&self) -> Backend { + self.backend.get() + } + + /// What an export of this timeline would encode the *sound* with, before + /// one is started: the copy an mp4 normally makes, or the software encoder + /// the format (or an equalized lane) forces. Pure -- no probe, no file + /// opened -- so a card may ask it per repaint; the picture's half costs a + /// plugin open and lives in [`crate::export::planned_video`]. + pub fn planned_audio(&self, format: crate::export::Format) -> &'static str { + crate::export::planned_audio(&self.project, format) + } + /// Why this session plays silent although the file has sound -- an audio /// track in a codec we cannot decode, or one the decoder refused. `None` /// when there is audio, and for a file that never had any. A front-end @@ -627,7 +758,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)); @@ -635,9 +775,19 @@ impl PlaybackSession { path, &sources, &lanes, + // The lane volumes and the limiter with them: a mix that vanished + // on a reload would be a mix nobody could keep, and both are the + // project's, not this machine's (the monitoring volume is not + // written and never will be). + &self.project.lane_gains(), &eq, &color, (self.meta.width, self.meta.height), + // ...and the rate it was cut at, which nothing else in the file + // says: a timeline of stills and songs used to come back at + // whatever its scaffold implied (`open_project`). + Some(self.meta.frame_rate), + self.project.limiter(), playhead, ) } @@ -662,9 +812,15 @@ impl PlaybackSession { // (`speed_maps_both_ways`). An empty timeline has no span, // and its one black frame is frame 0. Real time is the // arithmetic this always did, frame for frame. - frame.index = self - .span - .map_or(frame.index, |s| s.timeline_at(frame.index)); + // ...through the file's own rate first, which is the ceil + // half of *that* pair: the picture at source frame `i` is + // due at the first timeline-rate frame that shows it, and a + // slower file's picture is therefore held for the frames in + // between. Real time for a gap and for a single-rate + // project, where this is the identity. + frame.index = self.span.map_or(frame.index, |s| { + s.timeline_at(self.span_rate.timeline_at(frame.index)) + }); return Some(frame); } Err(TryRecvError::Empty) => return None, @@ -734,6 +890,14 @@ impl PlaybackSession { /// timeline still moves, there are simply no more pictures, and the /// disconnected receiver carries the session on to the next span. fn start_span(&mut self, span: Option) { + // Which file's frames the worker about to be opened will number its + // pictures in: the span's own source, and real time for a gap, whose + // black worker counts timeline frames already. Set before the open, + // because the open is the first thing that converts with it. + self.span_rate = match span.and_then(|s| s.from) { + Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME), + None => Rate::REAL_TIME, + }; let opened = match span { // The grade is the composite's at this frame -- the same clip the // span itself came from -- and it is constant across the span, so @@ -770,10 +934,17 @@ impl PlaybackSession { .. }) => DecodeSession::open_worker( &self.project.sources()[source].path, - in_frame, + // The file's own frames, which is the only place they exist: + // a clip counts the timeline's ([`Rate`]). + self.span_rate.source_at(in_frame), // Source frames, which a speed makes more (or fewer) than the - // timeline frames the span covers. - in_frame + span.expect("matched above").source_len(), + // timeline frames the span covers -- and which a file shot at + // another rate makes fewer (or more) again. One past the last + // frame this span shows, not one past its length: at another + // rate those are two different frames. + self.span_rate.source_at( + in_frame + span.expect("matched above").source_len().saturating_sub(1), + ) + 1, self.project .composite_color_at(start) .copied() @@ -804,6 +975,7 @@ impl PlaybackSession { // then can it return and be reaped by a later sweep. Nothing here // joins, so this ordering costs the seek nothing. self.frames = stream.frames; + self.backend = stream.backend; self.retire(stream.worker); } self.span = span; @@ -876,6 +1048,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 @@ -931,6 +1110,31 @@ impl PlaybackSession { self.edit(|p| p.set_eq(lane, idx, params)) } + /// How loud that lane plays, in dB -- everything on it, every frequency of + /// it. See [`Project::lane_gain_db`] for what it is *not*. + pub fn lane_gain_db(&self, lane: Lane) -> f32 { + self.project.lane_gain_db(lane) + } + + /// Sets it. One undo step and a reseek, the equalizer's rule for the + /// equalizer's reason: the mixer is rebuilt from the new volumes right + /// where the playhead is, so a track turned down during playback is heard + /// turned down from the next chunk on. + pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool { + self.edit(|p| p.set_lane_gain_db(lane, db)) + } + + /// The master limiter the whole mix is summed through. + pub fn limiter(&self) -> crate::limiter::Limiter { + self.project.limiter() + } + + /// Sets it, live like a lane volume and for the same reason -- the ceiling + /// a person is dragging has to be the ceiling they are hearing. + pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool { + self.edit(|p| p.set_limiter(limiter)) + } + /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, /// silence on the audio one, and nothing else moves. Reseeks, because what /// the playhead sits on has changed. `false` for a bad index -- the lift of @@ -940,14 +1144,20 @@ impl PlaybackSession { self.edit(|p| p.lift(lane, idx)) } - /// Moves that clip onto another lane of the same kind, keeping the frames it - /// covers -- the drag between tracks. One undo step, and it reseeks like - /// every other edit: which lane a clip sits on is what the compositor's - /// topmost-lane-wins rule reads, so the frame on screen is recomposed at - /// once. `false` for a bad index, for a move across kinds and for one that - /// would land on another clip; nothing changes. - pub fn move_clip_to_lane(&mut self, from: Lane, idx: usize, to: Lane) -> bool { - self.edit(|p| p.move_to_lane(from, idx, to)) + /// Moves that clip onto lane `to` with its head at timeline frame `start` -- + /// the drag that carries a take along its track or onto another one, and its + /// whole group with it. See [`Project::move_clip`] for the walls `start` is + /// clamped to and the ways a drop is refused. One undo step, and it reseeks + /// like every other edit: which lane a clip sits on is what the compositor's + /// topmost-lane-wins rule reads, and where it starts is what the playhead + /// reads, so the frame on screen is recomposed at once. + /// + /// A *frame*, where the rest of this type takes seconds, for + /// [`trim_clip`](Self::trim_clip)'s reason: the drag has already put the + /// pointer on a frame, and converting it back through seconds would be a + /// rounding step between the box let go of and the box committed. + pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { + self.edit(|p| p.move_clip(from, idx, to, start)) } /// Drags one end of that clip to timeline frame `to`, changing how much of @@ -1042,13 +1252,36 @@ impl PlaybackSession { self.project.trim_room(lane, idx, edge, &self.counts) } - /// Records how long a source is, for a source index that may be one - /// `Project::import` just made or one it handed back. See [`Self::counts`]. - fn note_frames(&mut self, source: usize, frames: u32) { + /// Records how long a source is and what rate it was shot at, for a source + /// index that may be one `Project::import` just made or one it handed back. + /// See [`Self::counts`] and [`Self::rates`], which are one table in two + /// vectors and grow together. + fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) { if source == self.counts.len() { self.counts.push(frames); + self.rates.push(rate); } debug_assert_eq!(self.counts.len(), self.project.sources().len()); + debug_assert_eq!(self.rates.len(), self.counts.len()); + } + + /// The rate noted for whichever source plays `path`, by + /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however + /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session + /// has never taken in. + fn file_rate(&self, path: &Path) -> Rate { + self.source_of(path) + .map_or(Rate::REAL_TIME, |i| self.rates[i]) + } + + /// Which source `path` is, canonicalising only if it has to: a source's own + /// path is canonical ([`Source::new`]), so a caller handing one back from + /// [`sources`](Self::sources) -- which is every library row -- hits on the + /// first walk and never pays for the `canonicalize` syscall the second one + /// makes. One rule, so a path that names a length names a rate too. + fn source_of(&self, path: &Path) -> Option { + let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); + at(path).or_else(|| at(&Source::new(path, 0).path)) } /// How long the whole of `path` is, in timeline frames: the length noted @@ -1060,14 +1293,20 @@ impl PlaybackSession { /// audio tracks it carries -- the picture's frame count for an mp4, the /// playing time for a song. pub fn file_frames(&self, path: &Path) -> u32 { - let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted); - // A source's own path is canonical ([`Source::new`]), so a caller - // handing one back from [`sources`](Self::sources) -- which is every - // library row -- hits on the first walk and never pays for the - // `canonicalize` syscall the second one makes. - at(path) - .or_else(|| at(&Source::new(path, 0).path)) - .map_or(0, |i| self.counts[i]) + self.source_of(path).map_or(0, |i| self.counts[i]) + } + + /// What rate the file at `path` was *shot* at, in frames per second -- which + /// is the timeline's own rate for every source that shares it, and is not + /// for one placed at another ([`Rate`]). By path like + /// [`file_frames`](Self::file_frames), and the timeline's rate for a file + /// this session has never taken in (and for a still and a song, which were + /// shot at no rate at all). + /// + /// What a library row names the file with: the timeline's rate there would + /// be a lie about a 23.976 fps file the moment one can join. + pub fn file_fps(&self, path: &Path) -> f64 { + self.file_rate(path).as_f64() * self.meta.frame_rate } /// The clip the picture is coming from at `timeline_secs`: the lane it sits @@ -1186,7 +1425,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. /// @@ -1226,8 +1465,9 @@ impl PlaybackSession { let first = self.first_audio()?; audio_matches(&wanted, &first)?; } + let rate = self.file_rate(&wanted.path); let source = self.project.import(path, stream); - self.note_frames(source, frames); + self.note_frames(source, frames, rate); let clip = Clip { start: 0, in_frame: 0, @@ -1286,7 +1526,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 @@ -1302,14 +1549,16 @@ impl PlaybackSession { // count one index late. if idx < self.counts.len() { self.counts.remove(idx); + self.rates.remove(idx); } 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()) } @@ -1355,11 +1604,14 @@ impl PlaybackSession { /// nothing playable, so there is nothing for [`undo`](Self::undo) to take /// back, and nothing reseeks. /// - /// Refused unless it can join the timeline -- same codec, same frame rate, - /// same audio parameters or both silent; the `Err` names the property that - /// disagrees, for a caller to show. Nothing is changed by a refusal. A - /// *resolution* of its own is not a refusal: the clip is placed on the - /// project canvas by its fit policy ([`PlaybackSession::set_fit`]). + /// Refused unless it can join the timeline -- same codec, same audio + /// parameters or both silent; the `Err` names the property that disagrees, + /// for a caller to show. Nothing is changed by a refusal. A *resolution* of + /// its own is not a refusal: the clip is placed on the project canvas by its + /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame + /// rate* of its own: the file is placed for the seconds it lasts and read at + /// [`Rate`] against the timeline's rate, so it plays at the speed it was + /// shot at. pub fn import(&mut self, path: &Path) -> crate::Result { if crate::is_audio(path) { return self.import_audio(path); @@ -1372,9 +1624,15 @@ impl PlaybackSession { // Stream 0: an import brings a file in on its first audio track, and // [`place_stream_at`](Self::place_stream_at) is how any other one of // its streams reaches the timeline afterwards. - matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; + // ...and the rate it will be read at comes back from the check that + // accepted it, so the number the refusal was decided on is the number + // the file is played by. + let rate = matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?; let source = self.project.import(path, 0); - self.note_frames(source, meta.frame_count); + // Its length *on this timeline*: a file shot slower than the timeline + // runs covers more frames than it holds, which is the whole of what + // placing it at another rate means ([`Rate`]). + self.note_frames(source, rate.timeline_at(meta.frame_count), rate); Ok(source) } @@ -1394,7 +1652,7 @@ impl PlaybackSession { audio_matches(&Source::new(path, 0), &first)?; let frames = audio_frames(path, self.meta.frame_rate)?; let source = self.project.import(path, 0); - self.note_frames(source, frames); + self.note_frames(source, frames, Rate::REAL_TIME); Ok(source) } @@ -1418,7 +1676,7 @@ impl PlaybackSession { .into()); } let source = self.project.import(path, 0); - self.note_frames(source, image_frames(self.meta.frame_rate)); + self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME); Ok(source) } @@ -1493,6 +1751,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 +1788,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 @@ -1562,11 +1838,18 @@ impl PlaybackSession { // Each source on the stream it was placed with: what plays is what // the library row said, and what an export copies (`export::run`). let sources = self.project.audio_sources(); - audio_running = - match AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds) { - Ok(Some((_, rx))) => audio.spawn_feeder(rx), - _ => false, - }; + // ...and the mix settings over the lot: each lane's own volume on + // its way into the sum and the master limiter over the sum, both + // rebuilt here like the curves above, which is what makes a lane + // fader and a ceiling audible while the timeline runs. + let gains = self.project.audio_gains(); + let limiter = self.project.limiter(); + audio_running = match AudioSession::open_mixed_streams_master( + &sources, &segs, &eqs, &speeds, &gains, limiter, + ) { + Ok(Some((_, rx))) => audio.spawn_feeder(rx), + _ => false, + }; if !audio_running { // Nothing will ever be fed again; let `tick` fall to wall time // instead of waiting on a device that has no more work coming. @@ -1662,15 +1945,16 @@ impl Drop for PlaybackSession { /// Whether `path`, already demuxed to `meta`, may join a timeline whose /// parameters are `timeline` and whose audio probes as `first`: same codec, -/// same frame rate, same audio parameters or both silent. +/// same audio parameters or both silent, and a frame rate that can be named +/// against the timeline's. The [`Rate`] it will be read at comes back with the +/// answer, so the number the check was decided on is the number it plays by. /// /// *Not* the same size any more. A project has its own resolution /// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its /// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a -/// letterboxed clip rather than a refusal. The frame rate stays refused on -/// purpose: mixing rates means resampling the *timeline*, which is a different -/// problem from resampling a picture, and a refusal is the honest answer until -/// it is solved. +/// letterboxed clip rather than a refusal, and so is a frame rate of its own: +/// the timeline keeps its own rate and the file is read at [`Rate`] against it +/// ([`PlaybackSession::import`] notes how long it is *here*). /// /// The `Err` names the property that disagrees, and those strings are what a /// front-end shows verbatim; [`PlaybackSession::import`] and @@ -1681,7 +1965,7 @@ fn matches_timeline( meta: &VideoMeta, timeline: &VideoMeta, first: &Option, -) -> crate::Result<()> { +) -> crate::Result { // Codec first: one timeline is one kind of source. Mixing them would decode // (every clip opens its own decoder) but on a machine without the VA-API // plugin the VP9 half would be black frames with the refusal only on @@ -1694,15 +1978,20 @@ fn matches_timeline( ) .into()); } - // Container frame rates are computed from timescales, so never `==`. - if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 { - return Err(format!( - "{:.3} fps does not match the timeline's {:.3} fps", - meta.frame_rate, timeline.frame_rate - ) - .into()); - } - audio_matches(source, first) + // The frame rate is *not* a refusal any more: a file shot at another rate is + // placed for the seconds it lasts and read through [`Rate`] at the + // decoder's door, so it plays at the speed it was shot at on a timeline + // that counts frames faster or slower. + // + // A rate that cannot be *named* still is, and this is the one place it is + // caught: `Rate::from_fps` builds itself out of the muxer's own timescales, + // and a file whose rate has none of those (a container that says nothing and + // holds one block, so the demuxer measures 0 fps) would otherwise be read + // 1:1 in silence -- the old rate gate refused those too, by arithmetic + // accident. The `Err` is `mux::frame_timing`'s own words. + let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?; + audio_matches(source, first)?; + Ok(rate) } /// Whether a candidate's audio may join a timeline whose first source probes as @@ -1729,12 +2018,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 +2135,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option