diff --git a/Cargo.lock b/Cargo.lock index 8e32099..7cd1f4e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1678,6 +1678,7 @@ dependencies = [ "cros-codecs", "engine", "gbm", + "libloading", ] [[package]] diff --git a/crates/app/src/export_ui.rs b/crates/app/src/export_ui.rs index 1eefd3b..1f22131 100644 --- a/crates/app/src/export_ui.rs +++ b/crates/app/src/export_ui.rs @@ -80,12 +80,12 @@ pub(crate) fn sample_rate_choices(current: Option) -> Vec { /// `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. +/// find out from the size of the file. VP9 and VP8 are the ones this program +/// still only *reads*: the plugin decodes them and there is no encoder for +/// either here, so they are rows 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 @@ -93,7 +93,7 @@ pub(crate) fn sample_rate_choices(current: Option) -> Vec { /// 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. -pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 8] = [ +pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 9] = [ ( &[Format::Mp4], "m", @@ -122,6 +122,7 @@ pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 8] = [ "Vorbis (rusty_vorbis) — quality-coded, stereo", ), (&[], "", "VP9", "AV1 above replaces it"), + (&[], "", "VP8", "AV1 above replaces it"), ]; /// The boxes one codec may be written into, in the order its container row diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 3298dfb..3830e62 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -453,6 +453,14 @@ struct Player { /// Where an export writes. Built once from the source path, which is not /// otherwise kept. export_path: PathBuf, + /// The export target this window itself last wrote or confirmed, so the + /// overwrite question ([`Player::export_ask`]) can tell "the file exists" + /// apart from "the file exists and is a stranger's": an export over a + /// path this window never wrote asks first, a re-export over its own + /// output does not (user 2026-09-11, "not just save but export too"). + /// Path equality, not a flag: retargeting the destination to somewhere + /// else makes the answer foreign again. + export_known: Option, /// Where the save action writes: the project this timeline was loaded from, /// or the one derived beside the media it started as. Saving twice /// overwrites the same file rather than making a second one. @@ -484,6 +492,23 @@ struct Player { /// While it is up it owns the keyboard -- three answers and nothing else /// ([`ui::stance`]'s root `on_key_down`). quit_ask: bool, + /// Whether the overwrite question is on screen: raised by Save's own + /// door ([`Player::save_guarded`]) when the save's target exists on + /// disk but `autosave_armed` says this window never loaded or wrote it + /// -- a `.edith` the timeline only derives its name from beside an + /// imported media file (user 2026-09-11, "saving over an existing file + /// must warn first"). Same shape as `quit_ask` above: while it is up + /// it owns the keyboard, and answering `enter` confirms the overwrite + /// -- the save then arms `autosave_armed`, so later saves on this + /// file are silent. + save_ask: bool, + /// Whether the export's overwrite question is on screen: raised inside + /// [`Player::start_export`] -- after its refusals, so an export that + /// cannot run never asks -- when `export_path` exists on disk and + /// `export_known` says this window never wrote it. Same shape as + /// `save_ask` above: while it is up it owns the keyboard, and answering + /// `enter` marks the target known and starts the export. + export_ask: bool, /// Whether `project_path` names a file this window itself put there -- /// loaded from a `.edith` ([`Player::install_project`]) or written by a /// manual save ([`Player::save_project`]) -- rather than one merely @@ -970,12 +995,15 @@ fn main() { // `open_media`/`load_project` a drop goes through: an // export beside the picture, a save beside it too. export_path: PathBuf::new(), + export_known: None, project_path: PathBuf::new(), autosave_dirty: false, autosave_last_edit: None, autosave_last_run: None, recovery_sidecar: None, quit_ask: false, + save_ask: false, + export_ask: false, autosave_armed: false, keymap: keymap.clone(), keys_open: false, diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 0185411..22e9915 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -85,7 +85,10 @@ impl Player { cx.notify(); } ActionId::Export => self.open_export(cx), - ActionId::Save => self.save_project(cx), + // Asked before the first overwrite of a file this window never + // put there ([`Player::save_guarded`]); the window's own file + // saves straight through. + ActionId::Save => self.save_guarded(cx), ActionId::Copy => self.copy_selected(), ActionId::Paste => self.paste(cx), ActionId::Cut => self.cut(cx), diff --git a/crates/app/src/player/export.rs b/crates/app/src/player/export.rs index 2d5e891..2f33f2a 100644 --- a/crates/app/src/player/export.rs +++ b/crates/app/src/player/export.rs @@ -558,6 +558,12 @@ impl Player { /// with shift. Clamped to the engine's own bounds, so the number on the /// row is the number the encoder is given. pub(crate) fn nudge_budget(&mut self, steps: i32, coarse: bool) { + // A video setting, like the field `n` opens: the sound-only moment + // draws no row for the lever, so nothing moves what it does not + // show -- the arrows, `+`/`-` and the wheel answer nothing there. + if !self.format.has_video() { + return; + } let step = i64::from(steps) * match coarse { true => BPS_COARSE as i64, @@ -592,6 +598,12 @@ impl Player { /// (`850k`, `6.5M`, `6.5`, `1.2G` of file), not a way to edit digits, and /// the number in force is still on the row until enter takes the new one. pub(crate) fn edit_budget(&mut self) { + // A video setting: the sound-only moment draws no row to type into, + // so its door opens nothing either -- the chord stays swallowed (the + // moment owns the keyboard) but no field opens under it. + if !self.format.has_video() { + return; + } self.budget_edit = Some(String::new()); } @@ -755,6 +767,26 @@ impl Player { } } + /// Whether an export has to be answered instead of started: the target + /// exists on disk and is not a file this window wrote (or had confirmed) + /// -- the same rule the save door keeps, with `export_known` playing + /// `autosave_armed`'s part (user 2026-09-11, "not just save but export + /// too": exporting over an existing file must warn first). + pub(crate) fn export_needs_answer(&self) -> bool { + Self::export_asks( + self.export_path.exists(), + self.export_known.as_deref() == Some(self.export_path.as_path()), + ) + } + + /// The export question as a value: a target that is there and not ours. + /// Split out of [`Player::export_needs_answer`] so the rule can be read + /// and tested without a window or a session -- the same shape + /// [`Player::save_asks`] keeps for Save. + pub(crate) fn export_asks(target_exists: bool, known: bool) -> bool { + target_exists && !known + } + /// Writes the edit list out, at the settings the card was left at. Playback /// stops first: the exporter opens its own decoder -- and, on the hardware /// path, an encoder -- so a running player would only compete with it for @@ -777,6 +809,10 @@ impl Player { // calls for the *estimate* and which nothing else needs a subtitle for. settings.subtitles = self.export_subs(); settings.range = self.range; + // Asked here, before `session` borrows `self` mutably for the fences + // below; nothing between here and the ask touches `export_path` or + // `export_known`, so the answer cannot go stale on the way. + let overwrite = self.export_needs_answer(); let Some(session) = &mut self.session else { self.notify_user("NOTHING TO EXPORT — no file open".into()); cx.notify(); @@ -801,8 +837,25 @@ impl Player { cx.notify(); return; } + // The last fence, after every refusal so an export that cannot run + // never asks: writing over a file this window did not write is a + // question, not a default. The card closes with the asking -- the + // plate rises where notices rise and the moment is an overlay over + // exactly that strip, so the two may not be on screen together. + // `enter` there ([`ui::stance`]'s root handler) marks the target + // known and comes back through this door, which then passes. + if overwrite { + self.close_card(); + self.export_ask = true; + cx.notify(); + return; + } session.pause(); self.export = Some(session.export_to_with(&self.export_path, &settings)); + // Ours from the first packet on: a re-export over this window's own + // output is not a question (the plate's `enter` sets the same mark + // before coming back through the door). + self.export_known = Some(self.export_path.clone()); // The clock starts with the worker, not with the first repaint that // happens to notice it. self.export_started = Some(Instant::now()); diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 94d5184..55e26d5 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -1584,8 +1584,30 @@ impl Player { clips > 0 && dirty } - /// Writes the timeline back to its project file. Overwrites silently, like - /// an export: the path was chosen once and the notice is the confirmation. + /// Whether a save has to be answered instead of obeyed: `project_path` + /// names a file on disk that this window itself did not put there -- + /// neither loaded ([`Player::install_project`]) nor written + /// ([`Player::save_project`]) -- so the first ^s would clobber a + /// `.edith` this timeline only derives its name from beside an + /// imported media file (user 2026-09-11). `autosave_armed` is the + /// whole difference: once this window's own save has confirmed the + /// overwrite, later saves on the file are silent again. + pub(crate) fn save_needs_answer(&self) -> bool { + Self::save_asks(self.project_path.exists(), self.autosave_armed) + } + + /// The overwrite question as a value: a target on disk and a window + /// that has not earned the write. Split out of + /// [`Player::save_needs_answer`] so the rule can be read and tested + /// without a window or a session, the way [`Player::close_asks`] is. + pub(crate) fn save_asks(target_exists: bool, armed: bool) -> bool { + target_exists && !armed + } + + /// Writes the timeline back to its project file -- the confirmed write. + /// The overwrite question, when one is owed at all, was asked by Save's + /// door ([`Player::save_guarded`]) or already answered at the quit + /// plate; the notice here is the confirmation, not the permission. pub(crate) fn save_project(&mut self, cx: &mut Context) { let saved = self .session @@ -1617,6 +1639,22 @@ impl Player { cx.notify(); } + /// Save's door: asks before the first overwrite of a file this window + /// never put there, saves straight through once the file is the + /// window's own. Raising the question does not save -- the overwrite + /// plate (the root `on_key_down` in `ui::stance`) owns the keyboard + /// until it is answered, and only its `enter` comes back to + /// [`Player::save_project`], which is what arms `autosave_armed` and + /// makes every later save on the file silent. + pub(crate) fn save_guarded(&mut self, cx: &mut Context) { + if self.save_needs_answer() { + self.save_ask = true; + cx.notify(); + return; + } + self.save_project(cx); + } + /// Marks that an edit has landed since the sidecar last caught up, and /// when: the door every edit that funnels through [`Player::act`] or a /// timeline gesture calls on its way through. Cheap and safe to call on a @@ -1947,6 +1985,24 @@ mod autosave_tests { assert!(Player::close_asks(1, true)); } + /// The overwrite question Save's door asks: a target that exists on + /// disk but was never this window's (an import-derived `project_path`, + /// `autosave_armed` still false) warns before the first clobber; a + /// fresh path writes silently, and a file the window itself already + /// saved keeps every later ^s silent. The close rule's sibling. + #[test] + fn only_a_foreign_existing_file_asks_before_a_save_overwrites_it() { + assert!(Player::save_asks(true, false)); + assert!( + !Player::save_asks(false, false), + "nothing on disk yet -- a first save needs no warning" + ); + assert!( + !Player::save_asks(true, true), + "the window's own file -- later saves stay silent" + ); + } + /// The three answers [`Player::recovery_offer`] gives, off nothing but a /// project file and a sidecar's mtimes: younger sidecar offers it, an /// older one or none at all offers nothing. Nowhere near a `Player` or a diff --git a/crates/app/src/tests/cards.rs b/crates/app/src/tests/cards.rs index d456ce4..3adb218 100644 --- a/crates/app/src/tests/cards.rs +++ b/crates/app/src/tests/cards.rs @@ -877,7 +877,12 @@ fn the_budget_is_the_one_number_the_engine_gets() { // One explicit rate, always: the Auto/Low/Medium/High/Exact ladder is // gone, so there is nothing left that sends `None` and lets the encoder // pick a figure the row never showed. - let settings = export_settings(6_500_000, Format::Mp4, DEFAULT_AUDIO_KBPS, EncoderSeat::Auto); + let settings = export_settings( + 6_500_000, + Format::Mp4, + DEFAULT_AUDIO_KBPS, + EncoderSeat::Auto, + ); assert_eq!(settings.bitrate, Some(6_500_000)); assert!(!settings.exact, "the copy path is off this surface"); assert_eq!(settings.audio_kbps, Some(DEFAULT_AUDIO_KBPS)); @@ -980,7 +985,14 @@ fn the_export_moment_is_three_rows_one_chip_and_no_list() { 2, "one border for the plate and one for the chip: §4's single boxed chip" ); - for gone in ["Advanced", "preset", "Quality", "Subtitles", "GPU: ", "Built in"] { + for gone in [ + "Advanced", + "preset", + "Quality", + "Subtitles", + "GPU: ", + "Built in", + ] { assert!(!body.contains(gone), "the old card's {gone} is still here"); } // Row 1 is one line at every width: the stem ellipsizes and the @@ -1131,6 +1143,115 @@ fn the_picture_cycle_wraps_out_of_the_sound_only_formats() { assert!(!sound_only.has_video() && sound_only != Format::Ogg); } +/// The budget is a video setting -- the engine's own word is that the bitrate +/// settings "mean nothing to the audio-only ones" -- yet the moment drew the +/// row, and answered `n` with a typing field, for a file that carries no +/// picture. The row now mounts only where the format writes one, and both +/// doors into the number answer the same gate: a row the moment does not +/// show cannot have been changed. +#[test] +fn the_budget_row_and_its_doors_are_video_only() { + // The row: still built, mounted under the gate -- a video format sees + // exactly the rows it saw before. + let cards = src_text("ui/cards.rs"); + let start = cards.find("fn export_card(").expect("the moment"); + let body = &cards[start + ..start + + cards[start..] + .find("\n /// ") + .unwrap_or(cards.len() - start)]; + assert!( + body.contains(".children(self.format.has_video().then(|| budget_row))"), + "the budget row is back on the sound-only moment" + ); + // The `n` door: the moment's chord and the row's own click both funnel + // through `edit_budget`, so its gate is the one gate -- and it must sit + // ahead of the field it guards. + let typing = fn_body("edit_budget"); + let (gate, _) = typing + .split_once("self.budget_edit = Some") + .expect("the typing field still opens"); + assert!( + gate.contains("!self.format.has_video()"), + "`n` opens the budget field for a format that writes no picture" + ); + // The value itself: arrows, `+`/`-` and the wheel all funnel through + // `nudge_budget` -- a lever nothing shows does not move either. + let lever = fn_body("nudge_budget"); + let (gate, _) = lever + .split_once("self.custom_bps =") + .expect("the lever still sets the budget"); + assert!( + gate.contains("!self.format.has_video()"), + "the hidden budget lever moves again" + ); +} + +/// Exporting over an existing file must warn first, "same pattern as the +/// exit guard" (user 2026-09-11: "not just save but export too -- an export +/// named like an existing video overrides it"). The question as a value: a +/// target that is there and not this window's own asks; anything else just +/// writes. +#[test] +fn only_a_foreign_existing_target_asks_before_an_export_overwrites_it() { + assert!(crate::Player::export_asks(true, false)); + assert!( + !crate::Player::export_asks(false, false), + "nothing there to clobber" + ); + assert!(!crate::Player::export_asks(false, true)); + assert!( + !crate::Player::export_asks(true, true), + "a re-export over this window's own output is silent" + ); +} + +/// The guard's wiring: asked after every refusal (an export that cannot run +/// never asks), before the worker starts; the moment closes with the asking +/// (it overlays the strip the plate rises on); a started export marks the +/// target this window's own so a re-export stays silent; and the plate's +/// `enter` confirms the target before re-entering the door. +#[test] +fn the_export_overwrite_question_owns_the_door_and_the_keyboard() { + let body = fn_body("start_export"); + assert!( + body.contains("self.export_needs_answer()"), + "start_export never asks before overwriting" + ); + // The call is hoisted above the `&mut self.session` borrow (E0502); what + // must sit after the refusals is the *check* of its answer. + let (fences, rest) = body + .split_once("if overwrite {") + .expect("the guard's answer is never checked"); + assert!( + fences.contains("format_refusal"), + "the question comes before the refusals: a refused export would ask" + ); + let (guard, started) = rest + .split_once("export_to_with") + .expect("the worker is still started from start_export"); + assert!( + guard.contains("self.close_card()") && guard.contains("self.export_ask = true"), + "asking leaves the moment up over the plate's strip" + ); + assert!( + started.contains("self.export_known = Some(self.export_path.clone())"), + "a started export does not mark the target this window's own" + ); + let stance = src_text("ui/stance.rs"); + let (_, handler) = stance + .split_once("if this.export_ask {") + .expect("the export plate is up with no key answering it"); + assert!( + handler.contains("this.export_known = Some(this.export_path.clone())"), + "the plate's enter does not confirm the target before re-entering the door" + ); + assert!( + stance.contains("stance-export-ask") && stance.contains("file_name(&player.export_path)"), + "the export plate does not name the file it would overwrite" + ); +} + /// One chord per thing, said the same on both surfaces: the moment's segments /// and the Settings room's EXPORT rows drive the same setters, so a chord that /// drifted on one of them would teach the user a key the other refuses. diff --git a/crates/app/src/tests/layout.rs b/crates/app/src/tests/layout.rs index 075f1b4..5c8b048 100644 --- a/crates/app/src/tests/layout.rs +++ b/crates/app/src/tests/layout.rs @@ -3420,6 +3420,22 @@ fn one_name_per_source_one_stem_helper_and_one_save_door() { stance.contains("UNSAVED — save ↵ · discard d · stay esc"), "the decision plate speaks prose instead of state + verb·chord" ); + // The overwrite guard (user 2026-09-11: saving over an existing file + // must warn first, same pattern as the exit guard): Save no longer + // writes through the action directly -- it routes through the guarded + // door, which raises the plate with the target's own name, and the + // plate is answered by its own key block beside the quit plate's. + let actions = src_text("player/actions.rs"); + assert!( + actions.contains("ActionId::Save => self.save_guarded(cx)") + && !actions.contains("ActionId::Save => self.save_project(cx)"), + "^s overwrites a foreign .edith without asking" + ); + assert!( + stance.contains("if this.save_ask {") + && stance.contains("OVERWRITE {} — overwrite ↵ · keep esc"), + "the overwrite plate is up with no key answering it" + ); assert!( !src_text("ui/timeband_stance.rs").contains("ActionId::Save"), "Save has two doors: the ledger's state word and the time band's ghost" diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index ee2d835..2b89ee9 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -532,7 +532,7 @@ fn an_imports_subtitles_are_read_by_the_worker_and_only_pushed_here() { #[test] 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: seven rows that pick, one that says why it cannot. A codec + // business: seven 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. @@ -626,9 +626,9 @@ fn every_codec_row_is_offered_or_says_why_not() { "{key} is already the card's own" ); } - // The one codec left that 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 codecs this program reads and cannot write are rows of their own, + // refused by name rather than absent: VP9 and VP8, because AV1 is the + // row that replaced them. Their reason travels with them, in the row or // the footer line that collects them -- either way it is on screen // without a click. OGG was the other one until `rusty_vorbis` gave this // project an encoder, and the row that says so is the row above. @@ -638,6 +638,12 @@ fn every_codec_row_is_offered_or_says_why_not() { .expect("VP9 has a row"); assert!(row.is_empty(), "VP9 is not offered"); assert!(detail.contains("replaces it"), "VP9: {detail}"); + let (row, _, _, detail) = FORMATS + .into_iter() + .find(|(_, _, name, _)| *name == "VP8") + .expect("VP8 has a row"); + assert!(row.is_empty(), "VP8 is not offered"); + assert!(detail.contains("replaces it"), "VP8: {detail}"); let (row, _, _, detail) = FORMATS .into_iter() .find(|(_, _, name, _)| *name == "OGG") diff --git a/crates/app/src/ui/cards.rs b/crates/app/src/ui/cards.rs index 040bcd4..6ab2ec8 100644 --- a/crates/app/src/ui/cards.rs +++ b/crates/app/src/ui/cards.rs @@ -827,7 +827,11 @@ impl Player { .border_1() .border_color(rgba(DARK_SEAM())) .child(file_row) - .child(budget_row) + // The budget is a video setting -- the engine takes + // no bitrate for the sound-only formats -- so there + // the moment mounts no row: a row it does not show + // cannot have been changed. + .children(self.format.has_video().then(|| budget_row)) .child(commit_row) .into_any_element(), ) diff --git a/crates/app/src/ui/stance.rs b/crates/app/src/ui/stance.rs index 47fb732..915ca16 100644 --- a/crates/app/src/ui/stance.rs +++ b/crates/app/src/ui/stance.rs @@ -627,14 +627,16 @@ fn bench( .child(bench_stance::render(player, bench_h - BENCH_CHROME_H, cx)) } -/// DESIGN §8's "needs a decision" notice, and the only one the room raises: -/// a red 3px spine, the state word, and the verbs that answer it -- state -/// plus verb·chord, never a sentence. It rises where notices rise, directly -/// above the ledger, so it is never over the picture. The keys behind it live -/// in the root `on_key_down` above. -fn decision_plate() -> impl IntoElement { +/// DESIGN §8's "needs a decision" notice: a red 3px spine, the state word, +/// and the verbs that answer it -- state plus verb·chord, never a sentence. +/// The room raises one per question that owns the keyboard (the +/// unsaved-work close guard, the overwrite guard on save), each passing its +/// own element id and line. It rises where notices rise, directly above the +/// ledger, so it is never over the picture. The keys behind it live in the +/// root `on_key_down` above. +fn decision_plate(id: &'static str, line: &str) -> impl IntoElement { div() - .id("stance-quit-ask") + .id(id) .flex_none() .h(px(LEDGER_H)) .bg(rgb(DARK_PANEL())) @@ -655,7 +657,7 @@ fn decision_plate() -> impl IntoElement { gpui::FontWeight::MEDIUM, )) .text_color(rgb(INK1())) - .child("UNSAVED — save ↵ · discard d · stay esc"), + .child(line.to_owned()), ) } @@ -912,6 +914,7 @@ pub(crate) fn render( // anywhere to route to (no file picker exists in the // tree), and every timeline with a clip on it got a // path from its first import (`project_path`). + // corner-cut: the overwrite guard is Save's door (`Player::save_guarded`), not this plate's -- this save was already answered. this.save_project(cx); window.remove_window(); } @@ -924,6 +927,61 @@ pub(crate) fn render( } return; } + // The overwrite question (user 2026-09-11: saving over an + // existing file must warn first, "same pattern as the exit + // guard"). Raised only by Save's own door + // ([`Player::save_guarded`]) -- the target exists on disk and + // `autosave_armed` says this window never loaded or wrote it -- + // so the ledger's unsaved ghost routes through the same ask. + // Same ownership as the plate above: two answers and nothing + // else -- `↵` overwrites and saves, `esc` keeps the file, any + // other key does nothing at all. + if this.save_ask { + match key { + "enter" => { + // The answer IS the confirmation, so this goes + // straight to the unconditional write and never + // back through the guard; [`Player::save_project`] + // arms `autosave_armed`, making later ^s on this + // file silent again. + this.save_project(cx); + this.save_ask = false; + cx.notify(); + } + "escape" => { + this.save_ask = false; + cx.notify(); + } + _ => {} + } + return; + } + // The export's own overwrite question (user 2026-09-11: "not just + // save but export too"). Raised inside [`Player::start_export`] + // after its refusals, with the export moment closed behind it -- + // the moment is an overlay over exactly the strip this plate + // rises on. Same ownership as the plates above: `↵` marks the + // target this window's own and goes back through the door, which + // now passes the guard and starts the worker; `esc` keeps the + // file; any other key does nothing at all. + if this.export_ask { + match key { + "enter" => { + // The answer IS the confirmation, so the target is + // marked known *before* the door is re-entered -- + // the guard asks again otherwise. + this.export_known = Some(this.export_path.clone()); + this.export_ask = false; + this.start_export(cx); + } + "escape" => { + this.export_ask = false; + cx.notify(); + } + _ => {} + } + return; + } // The recovery notice reads a key as more than "answered" (legacy // `render.rs`'s own rule): `enter` loads the sidecar it named, any // other key declines it. Asked before the generic dismiss below @@ -1123,7 +1181,34 @@ pub(crate) fn render( .child(time_band(player, position, cx)) .child(divider(Split::Bench, player.split_drag == Some(Split::Bench), cx)) .child(bench(player, bench_h, window, cx)) - .when(player.quit_ask, |el| el.child(decision_plate())) + .when(player.quit_ask, |el| { + el.child(decision_plate( + "stance-quit-ask", + "UNSAVED — save ↵ · discard d · stay esc", + )) + }) + .when(player.save_ask, |el| { + el.child(decision_plate( + "stance-save-ask", + &format!( + "OVERWRITE {} — overwrite ↵ · keep esc", + file_name(&player.project_path) + ), + )) + }) + // The export overwrite plate sits with the other two, under + // the ledger: [`Player::start_export`] closes the export + // moment when it raises this, so the card that would cover + // the strip is never up together with the question. + .when(player.export_ask, |el| { + el.child(decision_plate( + "stance-export-ask", + &format!( + "OVERWRITE {} — overwrite ↵ · keep esc", + file_name(&player.export_path) + ), + )) + }) .child(ledger(player, position, cx)) .when(player.settings_open, |el| { el.child(settings_stance::render(player, window_size, cx)) diff --git a/crates/engine-hw/Cargo.toml b/crates/engine-hw/Cargo.toml index 2c680d4..1d93546 100644 --- a/crates/engine-hw/Cargo.toml +++ b/crates/engine-hw/Cargo.toml @@ -14,3 +14,7 @@ engine = { path = "../engine" } cros-codecs = { version = "0.0.6", features = ["vaapi"] } # Same version cros-codecs already pulls in; we allocate output frames ourselves. gbm = { version = "0.15", default-features = false, features = ["drm-support"] } +# Same version `engine` pins for its own dlopens (`hw.rs`, `ao.rs`); this is +# the plugin's half of the same philosophy, one level down: `libvpx` for the +# software VP8 seat (`src/vpx.rs`), resolved at runtime like libva itself. +libloading = "0.8" diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index e65ac9b..2dd478a 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -1,7 +1,10 @@ -//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264 and HEVC, and AV1 -//! where the GPU has an entrypoint for it), shipped as a +//! VA-API decode (H.264, HEVC, VP9 and AV1) -- and VP8, which decodes on +//! `libvpx`, dlopen'd by this plugin in turn ([`vpx`], software, no VA-API +//! anything) -- and encode (H.264 and HEVC, and AV1 where the GPU has an +//! entrypoint for it), shipped as a //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on -//! libva/gbm/drm. Every entry point is +//! libva/gbm/drm -- nor on libvpx, the same rule one level down. Every entry +//! point is //! `extern "C"`, catches unwinds and reports failure as a null pointer or a //! negative code: the caller's contract is "any failure means use the software //! codec". @@ -25,6 +28,7 @@ //! `hwproc` and let the same helper hold both. mod slice_fix; +mod vpx; use std::collections::VecDeque; use std::ffi::{CStr, c_char, c_void}; @@ -66,8 +70,11 @@ use cros_codecs::video_frame::{UV_PLANE, Y_PLANE}; use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution}; use gbm::{BufferObjectFlags, Format as GbmFormat}; -use engine::demux::{Codec, Demuxer}; -use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta}; +use engine::demux::{Codec, Demuxer, VideoMeta}; +use engine::hw::{ + CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP8, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta, +}; +use vpx::VpxCtx; type PooledFrame = PooledVideoFrame; type Dec = StatelessDecoder>; @@ -335,8 +342,10 @@ fn open_devices() -> Option<(Rc, gbm::Device)> { } impl Session { - fn open(path: &Path) -> Option { - let (meta, demuxer) = Demuxer::open(path).ok()?; + /// Assembles the VA-API half around a container that is already read -- + /// [`OpenSession::open_at`] owns the read and routes VP8 away from here + /// before any device is opened. + fn opened(meta: VideoMeta, demuxer: Demuxer) -> Option { 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 @@ -366,6 +375,12 @@ impl Session { Codec::Av1 => { Decoder::Av1(Dec::::new_vaapi(display, BlockingMode::Blocking).ok()?) } + Codec::Vp8 => { + // Routed to [`VpxSession`] by [`OpenSession::open_at`] before + // this half is ever built; the arm exists so the match stays + // exhaustive about it. + return None; + } }; let pool = FramePool::new(move |info: &StreamInfo| { alloc_nv12(&gbm, info.coded_resolution, ten_bit).expect("output frame allocation failed") @@ -405,26 +420,9 @@ impl Session { }) } - /// As [`Session::open`], but positioned so the first picture handed out is - /// sample `target_sample` (1-based): decode restarts at the sync sample at - /// or before it and the pictures in between are dropped unread. - fn open_at(path: &Path, target_sample: u32) -> Option { - let mut session = Self::open(path)?; - // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based - // display frames -- and answers with a signed one, since a sync sample - // inside what the edit list trims sits before frame 0. - let target_frame = target_sample.saturating_sub(1); - let first = session.demuxer.seek_to_sync_at_or_before(target_frame); - session.skip = (i64::from(target_frame) - first).max(0) as u32; - session.position = first; - if target_frame > 0 { - session.leading = 0; - } - Some(session) - } - - /// Repositions an **open** session, exactly as [`Session::open_at`] positions - /// a new one: the next [`Session::pump`] hands back sample `target_sample`. + /// Repositions an **open** session, exactly as [`OpenSession::open_at`] + /// positions a new one: the next [`Session::pump`] hands back sample + /// `target_sample`. /// /// This is what a seek costs when the session is kept, and most of it is /// skippable: a target *ahead* of where the decoder stands, within @@ -789,10 +787,300 @@ fn p010_to_i420( } } +/// What the plugin is decoding a file on: the VA-API stateless decoders, or +/// -- for VP8 alone -- libvpx in this plugin's own address space. The split +/// is the codec's, decided once at [`OpenSession::open_at`]: VP8 opens no VA +/// display (this GPU has no VP8 profile to ask it for, and a machine with no +/// render node at all still decodes VP8), and the other four never touch +/// libvpx. +/// +/// Everything past the split is written twice -- [`Session`] for the VA-API +/// decoders and [`VpxSession`] for libvpx -- rather than folded into one +/// shape: the halves share the *contract* (open at a sample, pump one +/// picture, fill a [`VhFrame`]) and nothing underneath it, and a trait over +/// "a `vaGetImage`" versus "a memcpy" is the kind of seam that hides which +/// path a measurement ran on. +enum OpenSession { + Vaapi(Session), + Vpx(VpxSession), +} + +impl OpenSession { + /// Opens `path` for decode, positioned so the first picture handed out is + /// sample `target_sample` (1-based): decode restarts at the sync sample at + /// or before it and the pictures in between are dropped unread. The same + /// landing for both halves; the codec's half is chosen here, where the + /// container has been read and no device has been opened yet. + fn open_at(path: &Path, target_sample: u32) -> Option { + let (meta, demuxer) = Demuxer::open(path).ok()?; + let session = match meta.codec { + Codec::Vp8 => Self::Vpx(VpxSession::opened(meta, demuxer)?), + _ => Self::Vaapi(Session::opened(meta, demuxer)?), + }; + // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based + // display frames -- and answers with a signed one, since a sync sample + // inside what the edit list trims sits before frame 0. + let target_frame = target_sample.saturating_sub(1); + match session { + Self::Vaapi(mut session) => { + let first = session.demuxer.seek_to_sync_at_or_before(target_frame); + session.skip = (i64::from(target_frame) - first).max(0) as u32; + session.position = first; + if target_frame > 0 { + session.leading = 0; + } + Some(Self::Vaapi(session)) + } + Self::Vpx(mut session) => { + let first = session.demuxer.seek_to_sync_at_or_before(target_frame); + session.skip = (i64::from(target_frame) - first).max(0) as u32; + session.position = first; + Some(Self::Vpx(session)) + } + } + } + + fn meta(&self) -> &VhMeta { + match self { + Self::Vaapi(session) => &session.meta, + Self::Vpx(session) => &session.meta, + } + } + + fn seek_to(&mut self, target_sample: u32) -> Result<(), String> { + match self { + Self::Vaapi(session) => session.seek_to(target_sample), + Self::Vpx(session) => session.seek_to(target_sample), + } + } + + /// Pumps the decoder until one picture is ready, delivered into the + /// session's own buffer. `Ok(false)` is clean end of stream. + fn pump(&mut self) -> Result { + match self { + Self::Vaapi(session) => session.pump(), + Self::Vpx(session) => session.pump(), + } + } + + /// Points `out` at the picture [`OpenSession::pump`] just delivered. + fn fill(&self, out: &mut VhFrame) { + match self { + Self::Vaapi(session) => session.fill(out), + Self::Vpx(session) => session.fill(out), + } + } +} + +/// One libvpx decode session: the VP8 half of the plugin, the whole of the +/// same job [`Session`] does for the VA-API codecs. No display, no GBM, no +/// surface pool -- libvpx hands the planes back in memory, and the only +/// shapes worth carrying over from the other half are the ones the caller +/// sees: [`VhMeta`], one picture per `pump`, the same [`VhFrame`] layout, the +/// same skip/position arithmetic a seek is. +/// +/// VP8 reorders nothing: every access unit fed is one picture out, in feed +/// order, which is why `position` advances exactly as the VA-API half's does +/// without any of its drain machinery. +struct VpxSession { + vpx: &'static vpx::Vpx, + ctx: VpxCtx, + demuxer: Demuxer, + meta: VhMeta, + flushed: bool, + /// Pictures still to be decoded and thrown away to land on a seek target, + /// exactly [`Session`]'s field of the same name. + skip: u32, + /// The display frame the next `pump` would hand out -- [`Session`]'s + /// field, again: one further along for every picture pulled, skipped past + /// and delivered alike. + position: i64, + /// Tightly packed I420 handed out through [`VhFrame`]; reused every + /// frame, which is exactly why the pointers are only valid until the + /// next call. + out: Vec, + luma: usize, + chroma: usize, +} + +impl VpxSession { + fn opened(meta: VideoMeta, demuxer: Demuxer) -> Option { + let vpx = vpx::vpx()?; + let mut session = Self { + vpx, + ctx: VpxCtx::default(), + demuxer, + meta: VhMeta { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + frame_count: meta.frame_count, + }, + flushed: false, + skip: 0, + position: 0, + out: Vec::new(), + luma: 0, + chroma: 0, + }; + if let Err(e) = session.init() { + eprintln!("engine_hw: {e}"); + return None; + } + Some(session) + } + + /// (Re-)initialises the decoder. libvpx has no mid-stream reset, so this + /// *is* the flush: a seek pays destroy + init, and what makes that safe + /// is the demuxer's sync-sample seek, which restarts the feed where the + /// reference chain restarts -- the same discipline [`Session`]'s VA-API + /// flush leans on. + fn init(&mut self) -> Result<(), String> { + self.vpx.dec_init(&mut self.ctx) + } + + /// Feeds one access unit. VP8 emits at most one picture per unit, so the + /// pull belongs to the `pump` loop, not here. + fn decode(&mut self, au: &[u8]) -> Result<(), String> { + if au.is_empty() { + return Ok(()); + } + self.vpx.decode(&mut self.ctx, au) + } + + fn pump(&mut self) -> Result { + loop { + // Whatever the last fed unit produced is the picture this call + // hands back. The iterator starts fresh per feed because VP8 + // queues nothing: one unit in, at most one picture out. + let mut iter: *const c_void = std::ptr::null(); + while let Some(img) = self.vpx.get_frame(&mut self.ctx, &mut iter) { + // One picture further along, shown or skipped past alike -- + // the same walk [`Session::pump`] makes. The fields the copy + // needs are taken by value, which ends the context's borrow + // before `emit` may take the session again. + let (planes, stride, (w, h)) = (img.planes, img.stride, img.display()); + self.position += 1; + if self.skip > 0 { + self.skip -= 1; + continue; + } + self.emit(planes, stride, w, h); + return Ok(true); + } + if self.flushed { + return Ok(false); + } + match self.demuxer.next_access_unit() { + Ok(Some(au)) => self.decode(&au)?, + Ok(None) => { + // End of the track: the empty `vpx_codec_decode` that + // releases anything held back is this decoder's flush, + // and it costs no iteration of its own -- the pull at the + // top of the loop drains it. + self.vpx.flush(&mut self.ctx)?; + self.flushed = true; + } + Err(e) => return Err(e.to_string()), + } + } + } + + /// Copies one decoded I420 picture into `self.out` -- [`Session::emit`] + /// for a decoder that hands the planes back in memory rather than behind + /// a `vaGetImage`. VP8 output is always 8-bit 4:2:0, so there is no + /// 10-bit branch to mirror. + fn emit(&mut self, planes: [*mut u8; 4], stride: [std::ffi::c_int; 4], w: u32, h: u32) { + let (w, h) = (w as usize, h as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + if self.luma != w * h || self.chroma != cw * ch { + self.luma = w * h; + self.chroma = cw * ch; + self.out = vec![0u8; self.luma + 2 * self.chroma]; + } + self.meta.width = w as u32; + self.meta.height = h as u32; + let (dst_y, rest) = self.out.split_at_mut(self.luma); + let (dst_u, dst_v) = rest.split_at_mut(self.chroma); + // SAFETY: libvpx guarantees the planes stride-cover the *display* + // size (4:2:0, so the chroma planes cover cw x ch) for the life of + // the image, which ends at this session's next `get_frame` -- after + // the copies below. + unsafe { + copy_plane(planes[0], stride[0] as usize, dst_y, w, h); + copy_plane(planes[1], stride[1] as usize, dst_u, cw, ch); + copy_plane(planes[2], stride[2] as usize, dst_v, cw, ch); + } + } + + fn fill(&self, out: &mut VhFrame) { + let w = self.meta.width as usize; + let cw = w.div_ceil(2); + out.y = self.out.as_ptr(); + // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`. + unsafe { + out.u = self.out.as_ptr().add(self.luma); + out.v = self.out.as_ptr().add(self.luma + self.chroma); + } + out.y_stride = w; + out.u_stride = cw; + out.v_stride = cw; + out.width = self.meta.width; + out.height = self.meta.height; + } + + /// Repositions the session, exactly [`Session::seek_to`]: the same + /// forward walk within [`FORWARD_SECS`], the same demuxer seek to a sync + /// sample otherwise -- and for the decoder, destroy + re-init where the + /// VA-API half pays a flush, because VP8 is stateful to its last inter + /// frame and libvpx offers no softer reset. + fn seek_to(&mut self, target_sample: u32) -> Result<(), String> { + let target_frame = target_sample.saturating_sub(1); + if let Reposition::Forward(ahead) = reposition( + self.position, + i64::from(target_frame), + self.meta.frame_count, + forward_limit(self.meta.frame_rate), + ) { + self.skip = forward_skip(self.skip, ahead); + return Ok(()); + } + // Dropping every reference the decoder holds. The destroy's answer is + // not checked against `Ok` because the init below re-zeroes the + // context either way; a destroy that failed has nothing to leak. + self.vpx.destroy(&mut self.ctx); + self.init()?; + self.flushed = false; + let first = self.demuxer.seek_to_sync_at_or_before(target_frame); + self.skip = (i64::from(target_frame) - first).max(0) as u32; + self.position = first; + Ok(()) + } +} + +impl Drop for VpxSession { + fn drop(&mut self) { + self.vpx.destroy(&mut self.ctx); + } +} + +/// One strided plane down to tightly packed rows: the whole of the read-back +/// a VP8 picture costs, where the VA-API half pays `vaGetImage` for the same. +/// +/// # Safety +/// `src` must stride-cover `w` x `h`, and `dst` must be `w` x `h`. +unsafe fn copy_plane(src: *const u8, stride: usize, dst: &mut [u8], w: usize, h: usize) { + for row in 0..h { + let s = unsafe { std::slice::from_raw_parts(src.add(row * stride), w) }; + dst[row * w..(row + 1) * w].copy_from_slice(s); + } +} + /// 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 -/// runtime, no render node, unsupported profile, unreadable file. +/// runtime, no render node, no libvpx for a VP8 file, unsupported profile, +/// unreadable file. /// /// # Safety /// `path` must be a valid NUL-terminated C string. @@ -807,7 +1095,7 @@ pub unsafe extern "C" fn vh_open_at(path: *const c_char, target_sample: u32) -> let Ok(path) = path.to_str() else { return std::ptr::null_mut(); }; - match Session::open_at(Path::new(path), target_sample) { + match OpenSession::open_at(Path::new(path), target_sample) { Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, None => std::ptr::null_mut(), } @@ -827,11 +1115,12 @@ pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 } // SAFETY: caller-guaranteed live session and writable destination. unsafe { - let session = &*(session as *const Session); - (*out).width = session.meta.width; - (*out).height = session.meta.height; - (*out).frame_rate = session.meta.frame_rate; - (*out).frame_count = session.meta.frame_count; + let session = &*(session as *const OpenSession); + let meta = session.meta(); + (*out).width = meta.width; + (*out).height = meta.height; + (*out).frame_rate = meta.frame_rate; + (*out).frame_count = meta.frame_count; } 0 })) @@ -850,7 +1139,7 @@ pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) return -1; } // SAFETY: caller-guaranteed live session and writable destination. - let session = unsafe { &mut *(session as *mut Session) }; + let session = unsafe { &mut *(session as *mut OpenSession) }; match session.pump() { Ok(true) => { // SAFETY: `out` is non-null and writable per the contract. @@ -881,7 +1170,7 @@ pub unsafe extern "C" fn vh_seek(session: *mut c_void, target_sample: u32) -> i3 return -1; } // SAFETY: caller-guaranteed live session. - let session = unsafe { &mut *(session as *mut Session) }; + let session = unsafe { &mut *(session as *mut OpenSession) }; match session.seek_to(target_sample) { Ok(()) => 0, Err(e) => { @@ -923,38 +1212,57 @@ pub unsafe extern "C" fn vh_next_frame_dma( return -1; } // SAFETY: caller-guaranteed live session and writable destinations. - let session = unsafe { &mut *(session as *mut Session) }; + let session = unsafe { &mut *(session as *mut OpenSession) }; // SAFETY: as above. unsafe { *dma = VhDma::default() }; - // A pool sized without the reserve has nothing to lend: this session - // has been read back from, so it stays that way. - if !session.sized || session.hold > 0 { - session.hold = DMA_HOLD; - session.want = Some(VhDma { - fourcc: VA_FOURCC_NV12, - coded_width, - coded_height, - width, - height, - ..VhDma::default() - }); - } - let pumped = session.pump(); - session.want = None; - match pumped { - Ok(true) => { - match session.dma.take() { - // SAFETY: `dma` is non-null and writable per the contract. - Some(desc) => unsafe { *dma = desc }, - // SAFETY: as above, for `out`. - None => session.fill(unsafe { &mut *out }), + // A libvpx picture has no GPU buffer to hand over: this session reads + // back, exactly as `vh_next_frame` does, and the caller's `dma` keeps + // the fd-below-zero default that says so. + match session { + OpenSession::Vpx(session) => match session.pump() { + Ok(true) => { + // SAFETY: `out` is non-null and writable per the contract. + session.fill(unsafe { &mut *out }); + 1 + } + Ok(false) => 0, + Err(e) => { + eprintln!("engine_hw: {e}"); + -2 + } + }, + OpenSession::Vaapi(session) => { + // A pool sized without the reserve has nothing to lend: this + // session has been read back from, so it stays that way. + if !session.sized || session.hold > 0 { + session.hold = DMA_HOLD; + session.want = Some(VhDma { + fourcc: VA_FOURCC_NV12, + coded_width, + coded_height, + width, + height, + ..VhDma::default() + }); + } + let pumped = session.pump(); + session.want = None; + match pumped { + Ok(true) => { + match session.dma.take() { + // SAFETY: `dma` is non-null and writable per the contract. + Some(desc) => unsafe { *dma = desc }, + // SAFETY: as above, for `out`. + None => session.fill(unsafe { &mut *out }), + } + 1 + } + Ok(false) => 0, + Err(e) => { + eprintln!("engine_hw: {e}"); + -2 + } } - 1 - } - Ok(false) => 0, - Err(e) => { - eprintln!("engine_hw: {e}"); - -2 } } })) @@ -970,7 +1278,7 @@ pub unsafe extern "C" fn vh_close(session: *mut c_void) { let _ = catch_unwind(AssertUnwindSafe(|| { if !session.is_null() { // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`. - drop(unsafe { Box::from_raw(session as *mut Session) }); + drop(unsafe { Box::from_raw(session as *mut OpenSession) }); } })); } @@ -1025,6 +1333,13 @@ const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option Option { @@ -1058,6 +1373,11 @@ fn query_caps() -> Option { caps.encode |= bit; } } + // The plugin's own software decoder, on its own account rather than the + // driver's -- the plugin's capability, never a GPU feat. + if vpx::vpx().is_some() { + caps.decode |= CAP_VP8; + } Some(caps) } diff --git a/crates/engine-hw/src/vpx.rs b/crates/engine-hw/src/vpx.rs new file mode 100644 index 0000000..86003cb --- /dev/null +++ b/crates/engine-hw/src/vpx.rs @@ -0,0 +1,273 @@ +//! `libvpx`, dlopen'd: the software VP8 decoder, and the reason a VP8 file +//! decodes on a machine whose GPU has no VP8 profile -- or whose GPU is +//! absent altogether. +//! +//! The plugin's own libva linkage, one level down: this plugin keeps no +//! DT_NEEDED on `libvpx` any more than the main binary does. The symbols are +//! resolved lazily, once, and a machine without the library is a machine +//! without the codec -- answered as `None` at [`vpx`] before any file is +//! opened, which is what [`crate::query_caps`] reports as the absence of +//! `CAP_VP8`. +//! +//! The extern declarations are hand-written against `vpx_decoder.h`, +//! `vpx_codec.h` and `vpx_image.h` as this soname has carried them since +//! libvpx 1.14: `VPX_DECODER_ABI_VERSION` 12. A libvpx from another ABI +//! answers `vpx_codec_dec_init_ver` with `VPX_CODEC_ABI_MISMATCH`, which +//! surfaces as a refused session -- loudly, in the eprintln, never as a +//! wrong picture. The struct layouts below are the ABI, not an assumption: +//! `vpx_codec_ctx_t`'s fields have not moved since the library's first +//! release, and `vpx_image_t`'s prefix is what every decoder in the field +//! reads. + +use std::ffi::{CStr, c_char, c_int, c_long, c_uint, c_void}; +use std::sync::LazyLock; + +use libloading::Library; + +/// `VPX_DECODER_ABI_VERSION`: `3 + VPX_CODEC_ABI_VERSION`, and +/// `VPX_CODEC_ABI_VERSION = 4 + VPX_IMAGE_ABI_VERSION` with +/// `VPX_IMAGE_ABI_VERSION = 5` -- the three headers this module mirrors. +const VPX_DECODER_ABI_VERSION: c_int = 12; + +/// `VPX_CODEC_OK`, the one return code that is not a refusal. +const VPX_CODEC_OK: c_int = 0; + +/// `VPX_DL_REALTIME`, the decode `deadline` argument -- which `vpx_decoder.h` +/// states this API ignores; passed because the type demands a value, and the +/// constant because it is the documented one. +const VPX_DL_REALTIME: c_long = 1; + +/// The decoder context, `vpx_codec_ctx_t` field for field. Nothing here is +/// read: the struct exists so the context is laid out exactly as libvpx +/// lays it out, and so the `&mut` handoffs to the C side are the whole of +/// the story. +#[repr(C)] +pub struct VpxCtx { + name: *const c_char, + iface: *const c_void, + err: c_int, + err_detail: *const c_char, + init_flags: c_uint, + config: *const c_void, + priv_: *mut c_void, +} + +impl Default for VpxCtx { + fn default() -> Self { + // SAFETY: all-pointer/zero initialisation is what libvpx's own init + // performs on the context before it fills it; `vpx_codec_dec_init_ver` + // re-zeroes it anyway. + unsafe { std::mem::zeroed() } + } +} + +/// `vpx_codec_dec_cfg_t`: thread count and a best-known size the caller may +/// leave at zero. +#[repr(C)] +struct VpxDecCfg { + threads: c_uint, + w: c_uint, + h: c_uint, +} + +/// `vpx_image_t` complete: the planes of one decoded picture and the strides +/// they sit at. The decoder owns the bytes -- they stay valid only until the +/// next `get_frame` or `decode` on the same context, which is exactly the +/// [`crate::VhFrame`] contract the caller already lives with. +#[repr(C)] +pub struct VpxImage { + fmt: c_int, + cs: c_int, + range: c_int, + w: c_uint, + h: c_uint, + bit_depth: c_uint, + d_w: c_uint, + d_h: c_uint, + r_w: c_uint, + r_h: c_uint, + x_chroma_shift: c_uint, + y_chroma_shift: c_uint, + pub planes: [*mut u8; 4], + pub stride: [c_int; 4], + bps: c_int, + user_priv: *mut c_void, + img_data: *mut u8, + img_data_owner: c_int, + self_allocd: c_int, + fb_priv: *mut c_void, +} + +impl VpxImage { + /// Displayed dimensions: what [`crate::VhFrame`] describes, not the + /// macroblock-padded storage the planes actually cover. + pub fn display(&self) -> (u32, u32) { + (self.d_w, self.d_h) + } +} + +type Dx = unsafe extern "C" fn() -> *const c_void; +type DecInitVer = + unsafe extern "C" fn(*mut VpxCtx, *const c_void, *const VpxDecCfg, c_uint, c_int) -> c_int; +type Decode = unsafe extern "C" fn(*mut VpxCtx, *const u8, c_uint, *mut c_void, c_long) -> c_int; +type GetFrame = unsafe extern "C" fn(*mut VpxCtx, *mut *const c_void) -> *mut VpxImage; +type Destroy = unsafe extern "C" fn(*mut VpxCtx) -> c_int; +type ErrorFn = unsafe extern "C" fn(*const VpxCtx) -> *const c_char; + +/// The resolved symbols, held with the library that carries them -- exactly +/// the shape `engine::hw`'s `Plugin` has on the other side of the ABI. +pub struct Vpx { + vp8_dx: Dx, + dec_init_ver: DecInitVer, + decode: Decode, + get_frame: GetFrame, + destroy: Destroy, + error: ErrorFn, + // Never dropped (the struct lives in a static), so the pointers above + // stay valid for the life of the process. + _lib: Library, +} + +/// The library, loaded once per process. `None` -- no `libvpx.so` on this +/// machine, or one missing a symbol this module names -- is the one answer, +/// asked before any file is opened. +static VPX: LazyLock> = LazyLock::new(load); + +/// The loaded library, or `None` on a machine without one this module can +/// use. Asked before any file is opened. +pub fn vpx() -> Option<&'static Vpx> { + VPX.as_ref() +} + +fn load() -> Option { + // The versioned soname first -- the name every distribution actually + // ships -- then the unversioned development name for the odd link that + // has it. + for name in ["libvpx.so.9", "libvpx.so"] { + let lib = match unsafe { Library::new(name) } { + Ok(lib) => lib, + Err(_) => continue, + }; + // SAFETY: the symbols are type-checked against the declarations above; + // a missing one unloads the library with the dropped closure and the + // next candidate gets its turn. + let vpx = unsafe { + (|| { + Some(Vpx { + vp8_dx: *lib.get(b"vpx_codec_vp8_dx\0").ok()?, + dec_init_ver: *lib.get(b"vpx_codec_dec_init_ver\0").ok()?, + decode: *lib.get(b"vpx_codec_decode\0").ok()?, + get_frame: *lib.get(b"vpx_codec_get_frame\0").ok()?, + destroy: *lib.get(b"vpx_codec_destroy\0").ok()?, + error: *lib.get(b"vpx_codec_error\0").ok()?, + _lib: lib, + }) + })() + }; + if vpx.is_some() { + return vpx; + } + } + None +} + +impl Vpx { + /// `vpx_codec_error`'s line about the context's last answer: what an init + /// or decode refusal says instead of a bare `vpx_codec_err_t` number. + fn last_error(&self, ctx: &VpxCtx) -> String { + // SAFETY: `ctx` is a live libvpx context; the string it names is + // static and read before anything else touches the context. + let msg = unsafe { (self.error)(ctx) }; + if msg.is_null() { + return "no description".to_string(); + } + // SAFETY: non-null per the check above, NUL-terminated per libvpx. + unsafe { CStr::from_ptr(msg) }.to_string_lossy().into_owned() + } + + /// The VP8 decoder interface, `vpx_codec_vp8_dx`: the argument every + /// `dec_init_ver` on this context takes. + fn iface(&self) -> *const c_void { + // SAFETY: a pure lookup in libvpx's own tables. + unsafe { (self.vp8_dx)() } + } + + /// `vpx_codec_dec_init_ver` with the ABI version this module was written + /// against -- the check a mismatched libvpx fails rather than a call it + /// misreads. + pub(super) fn dec_init(&self, ctx: &mut VpxCtx) -> Result<(), String> { + let cfg = VpxDecCfg { + threads: threads(), + w: 0, + h: 0, + }; + // SAFETY: the context is ours and live for the session; `cfg` is read + // only during the call; the version pins the ABI. + let rc = unsafe { (self.dec_init_ver)(ctx, self.iface(), &cfg, 0, VPX_DECODER_ABI_VERSION) }; + match rc { + VPX_CODEC_OK => Ok(()), + _ => Err(format!("libvpx init failed: {}", self.last_error(ctx))), + } + } + + /// `vpx_codec_decode`: one access unit in. `VPX_DL_REALTIME` is the + /// documented-but-ignored deadline. + pub(super) fn decode(&self, ctx: &mut VpxCtx, au: &[u8]) -> Result<(), String> { + // SAFETY: `au` outlives the call; the context is live and used from + // the one thread the session lives on. + let rc = unsafe { + (self.decode)( + ctx, + au.as_ptr(), + au.len() as c_uint, + std::ptr::null_mut(), + VPX_DL_REALTIME, + ) + }; + match rc { + VPX_CODEC_OK => Ok(()), + _ => Err(format!("libvpx decode failed: {}", self.last_error(ctx))), + } + } + + /// `vpx_codec_decode` with a null, empty frame: the end-of-stream signal + /// that releases whatever the decoder held back. + pub(super) fn flush(&self, ctx: &mut VpxCtx) -> Result<(), String> { + // SAFETY: as `decode`, with the nulls libvpx reads as "no more data". + let rc = unsafe { + (self.decode)(ctx, std::ptr::null(), 0, std::ptr::null_mut(), VPX_DL_REALTIME) + }; + match rc { + VPX_CODEC_OK => Ok(()), + _ => Err(format!("libvpx flush failed: {}", self.last_error(ctx))), + } + } + + /// `vpx_codec_get_frame`: the next picture of the current iteration, or + /// `None` when the iteration is done. The bytes belong to the decoder + /// until the next `decode`/`flush`. + pub(super) fn get_frame<'a>( + &self, + ctx: &'a mut VpxCtx, + iter: &mut *const c_void, + ) -> Option<&'a VpxImage> { + // SAFETY: the context is live; the returned pointer is libvpx's own + // image, borrowed for exactly as long as the lifetime above says. + unsafe { (self.get_frame)(ctx, iter).as_ref() } + } + + /// `vpx_codec_destroy`: the context's half of `VpxSession`'s `Drop`. + pub(super) fn destroy(&self, ctx: &mut VpxCtx) { + // SAFETY: called once per live context; libvpx frees what the context + // holds, and a context whose init never completed reads as an + // `INVALID_PARAM` refusal rather than a crash. + unsafe { (self.destroy)(ctx) }; + } +} + +/// VP8's row-based multithreaded decode stops paying past a handful of +/// threads -- the row sync costs what the parallelism buys -- so this is not +/// the machine's whole core count. +pub(super) fn threads() -> c_uint { + std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as c_uint) +} diff --git a/crates/engine/src/caps.rs b/crates/engine/src/caps.rs index 27c5862..bef8edf 100644 --- a/crates/engine/src/caps.rs +++ b/crates/engine/src/caps.rs @@ -11,6 +11,11 @@ //! with the codecs the plugin implements. No plugin, an older plugin or no //! driver all read the same way -- "software only" -- because that is what they //! mean for the file a user is about to write. +//! +//! VP8 is deliberately on neither line: the plugin decodes it on libvpx, +//! dlopen'd at runtime, and reports `CAP_VP8` for it -- the plugin's seat, +//! never the GPU's. [`HW_CODECS`] does not carry the bit, because this file's +//! one job is not presenting a seat as a GPU feat that no GPU has. use crate::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps}; @@ -95,6 +100,7 @@ fn seats(decodes: bool, encodes: bool) -> &'static str { #[cfg(test)] mod tests { use super::*; + use crate::hw::CAP_VP8; #[test] fn the_hardware_line_says_what_the_plugin_answered_and_nothing_more() { @@ -128,6 +134,27 @@ mod tests { assert_eq!(hw_line(Some(h264_only)), "H.264 dec"); } + /// The plugin's VP8 bit is its own libvpx software decoder. However lit + /// the mask is, the hardware line never reads it as a GPU seat -- and a + /// mask holding nothing *but* it still reads as the nothing a driver + /// without seats would answer. + #[test] + fn the_plugin_s_software_vp8_never_reads_as_a_gpu_seat() { + let vpx_only = VhCaps { + decode: CAP_VP8, + ..Default::default() + }; + assert!(hw_line(Some(vpx_only)).starts_with("none —")); + let with_gpu = VhCaps { + decode: CAP_H264 | CAP_VP8, + encode: CAP_H264, + ..Default::default() + }; + assert_eq!(hw_line(Some(with_gpu)), "H.264 dec+enc"); + } + + #[test] + #[test] fn the_software_line_names_every_encoder_this_build_carries() { let line = software(); diff --git a/crates/engine/src/colorspace.rs b/crates/engine/src/colorspace.rs index 3c2d4f4..5af76be 100644 --- a/crates/engine/src/colorspace.rs +++ b/crates/engine/src/colorspace.rs @@ -373,9 +373,9 @@ impl Tags { /// the demuxers already hold: the SPS VUI for H.264 and HEVC (Annex-B framed, /// which is how both demuxers keep them) and the sequence header OBU for AV1. /// -/// Empty [`Tags`] for VP9, whose colour space lives in the uncompressed header -/// of every frame rather than out of band, and for anything malformed: this is -/// a middle tier, and the tier below it always has an answer. +/// Empty [`Tags`] for VP9 and VP8, which state no out-of-band colour in either +/// container path, and for anything malformed: this is a middle tier, and the +/// tier below it always has an answer. pub fn bitstream_tags(codec: Codec, sets: &[u8]) -> Tags { match codec { // 7 is an H.264 SPS, 33 an HEVC one (whose NAL header is two bytes and @@ -391,6 +391,7 @@ pub fn bitstream_tags(codec: Codec, sets: &[u8]) -> Tags { .unwrap_or_default(), Codec::Av1 => av1_sequence_header(sets), Codec::Vp9 => Tags::default(), + Codec::Vp8 => Tags::default(), } } diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 7fbca00..4911f24 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -625,7 +625,7 @@ impl DecodeSession { ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; - // No software HEVC or VP9 decoder exists, so such a file the plugin will + // No software HEVC, VP9 or VP8 decoder exists, so such a file the plugin will // not take is refused *here*, where the caller still has somewhere to // show it -- a worker that opened and then produced nothing is a black // screen with no explanation. The probe session is opened, made to @@ -1005,8 +1005,8 @@ fn run_span( opened.hw = None; eprintln!("hardware decode failed before any frame, falling back to software"); } - // ...except where there is nothing to fall back to. Feeding HEVC or VP9 - // bytes to `rusty_h264` would be garbage, not a fallback. + // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or + // VP8 bytes to `rusty_h264` would be garbage, not a fallback. if opened.meta.codec != Codec::H264 { eprintln!("{}", opened.meta.codec.needs_plugin()); return; diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 6581359..e2b6d2f 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -111,13 +111,15 @@ pub fn cancelled_read_error() -> crate::Error { } /// What the video track is coded with. Not a decoder choice by itself: only -/// H.264 has a software decoder here, which is what [`Codec::needs_plugin`] -/// says for the others. +/// H.264 has a software decoder in this binary, and VP8's (libvpx) lives +/// inside the plugin -- which is what [`Codec::needs_plugin`] says for the +/// rest, per codec, in the words that stay true. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Codec { H264, Hevc, Vp9, + Vp8, Av1, } @@ -128,19 +130,30 @@ impl Codec { Self::H264 => "H.264", Self::Hevc => "HEVC", Self::Vp9 => "VP9", + Self::Vp8 => "VP8", Self::Av1 => "AV1", } } - /// Why a file can be refused outright: `rusty_h264` is the only software - /// decoder in the project and there is no pure-Rust HEVC or VP9 one to fall - /// back to, so without the plugin there is nothing to decode with. Shared - /// so playback and export refuse in the same words. + /// Why a file can be refused outright. Two true answers, one per shape of + /// "no decoder here": every codec but H.264 and VP8 has no software + /// decoder at all, so the refusal names the plugin as the only way; VP8's + /// software decoder *is* libvpx inside the plugin, so "there is no + /// software decoder" would be a lie the day the plugin grew that arm -- + /// the refusal keeps naming the plugin, because that is still the thing + /// to make present. Shared so playback and export refuse in the same + /// words. pub fn needs_plugin(self) -> String { - format!( - "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder", - name = self.name() - ) + match self { + Self::Vp8 => { + "VP8 needs the VA-API plugin (libengine_hw.so) — its decoder is libvpx, inside the plugin" + .to_string() + } + other => format!( + "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder", + name = other.name() + ), + } } /// The other refusal: the plugin *is* here and opened the file, and then @@ -168,6 +181,7 @@ const CODEC_IDS: &[(Codec, &str, &[u8; 4])] = &[ (Codec::H264, "V_MPEG4/ISO/AVC", b"avc1"), (Codec::Hevc, "V_MPEGH/ISO/HEVC", b"hvc1"), (Codec::Vp9, "V_VP9", b"vp09"), + (Codec::Vp8, "V_VP8", b"vp08"), (Codec::Av1, "V_AV1", b"av01"), ]; @@ -182,8 +196,6 @@ const UNSUPPORTED: &[(&str, &str)] = &[ // carries them in-band only; `mp4 0.14` parses no `avc3` sample entry at all // either, so `sequence_parameter_set()` would come back empty-handed. ("avc3", "H.264 with parameter sets in-band only"), - ("vp08", "no VP8 decoder: cros-codecs carries none"), - ("V_VP8", "no VP8 decoder: cros-codecs carries none"), ("V_MPEG2", "no MPEG-2 decoder, hardware or software"), ( "V_MS/VFW/FOURCC", @@ -764,8 +776,8 @@ impl Mp4Demuxer { parameter_sets = sets; bit_depth = depth; } - // No parameter sets: a VP9 sample is self-contained. - Codec::Vp9 => {} + // No parameter sets: a VP8 or VP9 sample is self-contained. + Codec::Vp8 | Codec::Vp9 => {} } let sync_samples = track .trak @@ -841,9 +853,9 @@ impl Mp4Demuxer { let Some(sample) = sample else { return Ok(None); }; - // A VP9 mp4 sample is one (super)frame the decoder parses on its own: - // no length prefixes to strip, no parameter sets to re-inject. - if self.codec == Codec::Vp9 { + // A VP8 or VP9 mp4 sample is one (super)frame the decoder parses on + // its own: no length prefixes to strip, no parameter sets to re-inject. + if matches!(self.codec, Codec::Vp8 | Codec::Vp9) { return Ok(Some(sample.bytes.to_vec())); } // An AV1 one is a whole temporal unit, likewise unframed -- with the @@ -1059,7 +1071,7 @@ impl MkvDemuxer { format!("{codec} video in a Matroska file is not supported — {why}") } None => format!( - "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264 and VP9 are" + "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264, VP9 and VP8 are" ), } .into(), @@ -1418,9 +1430,9 @@ impl MkvDemuxer { } /// Next access unit in decode order: the block verbatim for AV1, which is - /// one temporal unit already, and for VP9, whose block is one (super)frame; - /// Annex-B for HEVC and H.264, whose blocks hold the same length-prefixed - /// NALs an mp4 sample does. + /// one temporal unit already, and for VP8 and VP9, whose blocks are one + /// (super)frame each; Annex-B for HEVC and H.264, whose blocks hold the + /// same length-prefixed NALs an mp4 sample does. fn next_access_unit(&mut self) -> crate::Result>> { // Reading off the end of the window is not the end of the track: it is // the next cluster, not yet walked. The end of the track is the end of @@ -1449,7 +1461,7 @@ impl MkvDemuxer { // the bytes as a codec's: a stripped block is not a NAL and an inflated // one is not where it was read from. unpack.frame(scratch)?; - if matches!(self.codec, Codec::Av1 | Codec::Vp9) { + if matches!(self.codec, Codec::Av1 | Codec::Vp8 | Codec::Vp9) { let mut au = Vec::with_capacity(head + self.scratch.len()); au.extend_from_slice(&self.config[..head]); au.extend_from_slice(&self.scratch); @@ -2377,6 +2389,12 @@ fn mkv_track_entry( // the container either, so it is read off the first keyframe by // [`Demuxer::fill_vp9_depth`]; 8 here is what that probe starts from. Codec::Vp9 => (Codec::Vp9, 0, Vec::new(), 8), + // A VP8 block is one self-contained frame, exactly as a VP9 one: no + // length prefixes to strip, no configuration record to re-inject -- a + // `.webm` writes no `CodecPrivate` for it, and the `vp08` an mp4 + // carries no record beside. 8 is not an assumption here but the + // format itself: VP8 has no depth but 8. + Codec::Vp8 => (Codec::Vp8, 0, Vec::new(), 8), }; Ok(MkvEntry::Video(MkvVideo { number, @@ -2492,7 +2510,7 @@ fn mp4_no_video(path: &Path, reader: &Mp4Reader) -> crate::Error { Some(kind) => match UNSUPPORTED.iter().find(|(id, _)| *id == kind) { Some((_, why)) => format!("{kind} video in this mp4 is not supported — {why}"), None => { - format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9 and AV1 are") + format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9, AV1 and VP8 are") } } .into(), @@ -2500,7 +2518,7 @@ fn mp4_no_video(path: &Path, reader: &Mp4Reader) -> crate::Error { // which is a thing a person really does hand an editor. The Matroska // door's own answer, and the same type for the same reason. None => crate::Error::from(NoVideoTrack( - "no H.264, HEVC, VP9 or AV1 video track in file".to_string(), + "no H.264, HEVC, VP9, AV1 or VP8 video track in file".to_string(), )), } } @@ -4679,7 +4697,7 @@ mod tests { /// compile until it has been routed. #[test] fn every_codec_is_reachable_from_both_containers() { - for codec in [Codec::H264, Codec::Hevc, Codec::Vp9, Codec::Av1] { + for codec in [Codec::H264, Codec::Hevc, Codec::Vp9, Codec::Vp8, Codec::Av1] { let row = CODEC_IDS .iter() .find(|(c, ..)| *c == codec) diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index f0816ee..f77c392 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -157,8 +157,8 @@ const HEVC_QP_MAX: i32 = 40; /// still has none -- `oxideav-opus` encodes CELT alone, which is half a codec. /// (AAC has one too -- `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 +/// its own here.) VP9 and VP8 are the +/// codecs that come in through the plugin and stop there, HEVC having /// gained an encoder (an intra-only one, which the rows say). A front-end says /// so rather than hiding the row. /// diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index 97d136d..d028937 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -155,7 +155,7 @@ impl Drop for DmaFrame { } /// What *this machine* takes, as far as the plugin implements it: one bit per -/// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads +/// codec ([`CAP_H264`] and its four neighbours) in each mask, so a caller reads /// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s. /// /// The intersection is the plugin's to compute, never the driver's alone: a GPU @@ -178,6 +178,13 @@ pub const CAP_HEVC: u32 = 1 << 1; pub const CAP_VP9: u32 = 1 << 2; pub const CAP_AV1: u32 = 1 << 3; +/// VP8 decodes on libvpx inside the plugin -- software, dlopen'd at runtime, +/// no GPU and no VA-API profile anywhere in it -- so this bit is the +/// *plugin's* seat, never the driver's. It lights up [`VhCaps::decode`] when +/// the library is present; the hardware line in [`crate::caps`] deliberately +/// keeps it off, being a line about what the GPU takes. +pub const CAP_VP8: u32 = 1 << 4; + struct Plugin { open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void, meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32, @@ -255,6 +262,12 @@ fn load() -> Option { /// decodes), no driver, a driver that refuses the query -- and a caller says /// "software only" for all of them, which is what they mean. /// +/// VP8 sits outside that reading on a driverless machine: its decoder is +/// libvpx inside the plugin, so the plugin may open a VP8 file where this +/// table answers `None`. Nothing here promises otherwise -- the decode path +/// asks the plugin, not this table -- and the one display-dependent half the +/// front-end draws from this stays exactly as truthful as it was. +/// /// Costs one VA-API init (~90 ms) the first time: ask it off a render thread. pub fn caps() -> Option { static CAPS: OnceLock> = OnceLock::new(); diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 3443381..423d9bc 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -3964,11 +3964,12 @@ fn matches_timeline( ) -> crate::Result { // The codec is *not* held to the timeline's -- every clip opens its own // decoder, so an H.264 take and an HEVC one play on one timeline. What the - // codec gate was really protecting against stays, in the one place that can - // actually answer it: on a machine without the VA-API plugin an HEVC or VP9 - // clip would be black frames with the refusal on stderr alone, so the file - // is asked for a decoder *here*, at the door, where the `Err` is still - // something a front-end can show. A zero-length range probes and starts no + // codec gate was really protecting against stays, in the one place that + // can actually answer it: on a machine without the VA-API plugin an HEVC, + // VP9 or VP8 clip would be black frames with the refusal on stderr alone, + // so the file is asked for a decoder *here*, at the door, where the `Err` + // is still something a front-end can show. A zero-length range probes and + // starts no // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`] // only enters VA-API off that path. DecodeSession::open_worker( diff --git a/crates/engine/tests/capability_matrix.rs b/crates/engine/tests/capability_matrix.rs index a1f71c5..4f45a43 100644 --- a/crates/engine/tests/capability_matrix.rs +++ b/crates/engine/tests/capability_matrix.rs @@ -28,6 +28,7 @@ const MATRIX: &[(Codec, &str, &str)] = &[ (Codec::H264, "test_baseline.mp4", "test_h264.mkv"), (Codec::Hevc, "test_hevc.mp4", "test_hevc.mkv"), (Codec::Vp9, "test_vp9.mp4", "test_vp9.webm"), + (Codec::Vp8, "test_vp8.mp4", "test_vp8.webm"), // `mp4 0.14` writes no `av01` sample entry, so there is no AV1 mp4 fixture // to open; the mp4 half of that row is `av01`'s presence in the dispatch // table, which `demux::tests` holds. diff --git a/crates/engine/tests/vp8.rs b/crates/engine/tests/vp8.rs new file mode 100644 index 0000000..1d14279 --- /dev/null +++ b/crates/engine/tests/vp8.rs @@ -0,0 +1,143 @@ +//! VP8 import: the container half, and the decode half -- software, on the +//! libvpx the plugin dlopens (`engine-hw`'s `vpx.rs`), which is why these +//! twins need a built `libengine_hw.so` and a `libvpx.so` but **no VA-API +//! VP8 profile**: no such profile exists on this GPU, and none is asked for. +//! +//! ```text +//! cargo build -p engine -p engine-hw --release +//! LD_LIBRARY_PATH=target/release \ +//! cargo test -p engine --release --test vp8 -- --include-ignored --nocapture --test-threads=1 +//! ``` +//! +//! `VE_SW` is process-wide, hence `--test-threads=1`: the refusal test sets it +//! and puts it back. +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use engine::demux::{Codec, Demuxer}; +use engine::export::ExportSettings; +use engine::scratch::Scratch; +use engine::{AudioSession, DecodeSession, PlaybackSession, Project}; + +/// 1280x720@30, 2 s -- see `scripts/gen_fixtures.sh`. +const FRAMES: u32 = 60; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// The container half: a vp08 track is found and named as VP8 out of the mp4, +/// its `V_VP8` twin out of the `.webm`, and the AAC track is read exactly as +/// any other file's -- the audio path knows nothing about the video codec. +#[test] +fn the_demuxer_reports_a_vp8_track() { + let (meta, _) = Demuxer::open(&asset("test_vp8.mp4")).expect("open test_vp8.mp4"); + assert_eq!(meta.codec, Codec::Vp8); + assert_eq!((meta.width, meta.height), (1280, 720)); + assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate); + assert_eq!(meta.frame_count, FRAMES); + + let (webm, _) = Demuxer::open(&asset("test_vp8.webm")).expect("open test_vp8.webm"); + assert_eq!(webm.codec, Codec::Vp8); + + let probe = AudioSession::probe(asset("test_vp8.mp4"), 0) + .expect("probe") + .expect("the fixture has an AAC track"); + assert_eq!( + (probe.sample_rate, probe.channels), + (44_100, 2), + "audio is read the same whatever the picture is coded with" + ); +} + +/// There is no software VP8 decoder *in this binary*, so the software path +/// must refuse by name rather than feed VP8 bytes to `rusty_h264` -- and it +/// must refuse where a caller can still show it, i.e. out of `open`, not from +/// inside the worker. The decoder the refusal names is the plugin's libvpx +/// arm, which is why the sentence names the plugin and not a nonexistent +/// absence. +#[test] +fn the_software_path_refuses_vp8_by_name() { + // SAFETY: the suite is documented to run with --test-threads=1. + unsafe { std::env::set_var("VE_SW", "1") }; + let refused = + DecodeSession::open(asset("test_vp8.mp4")).expect_err("software must not accept VP8"); + let refused = refused.to_string(); + // Restored immediately: the hardware tests in this binary share the process. + unsafe { std::env::remove_var("VE_SW") }; + + assert!(refused.contains("VP8"), "{refused}"); + assert!(refused.contains("plugin"), "{refused}"); +} + +/// The end-to-end user path: opening the file yields pictures, all of them, +/// through the plugin's libvpx arm. The `.webm` is the file this decodes, +/// the container half being the Matroska demuxer's `V_VP8` row. +#[test] +#[ignore = "needs a built libengine_hw.so and libvpx.so.9 -- no VA-API profile involved"] +fn the_plugin_decodes_every_vp8_frame() { + let start = Instant::now(); + let (meta, frames) = DecodeSession::open(asset("test_vp8.webm")).expect("open test_vp8.webm"); + assert_eq!(meta.codec, Codec::Vp8); + let frames: Vec<_> = frames.into_iter().collect(); + eprintln!( + "test_vp8.webm: {} frames in {:?} ({:.1} fps)", + frames.len(), + start.elapsed(), + frames.len() as f64 / start.elapsed().as_secs_f64().max(1e-9) + ); + + assert_eq!(frames.len() as u32, FRAMES, "every sample decoded"); + for (i, frame) in frames.iter().enumerate() { + assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims"); + assert_eq!(frame.index, i as u32, "frames arrive in display order"); + assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size"); + } + // A picture, not a flat surface: a decoder handing back an untouched + // buffer would satisfy every count above. + let first = &frames[0].bgra; + assert!( + first.chunks_exact(4).any(|px| px != &first[..4]), + "frame 0 is a single colour -- no picture was decoded" + ); + // ...and a moving one, not one still: the fixture is a rendered clip, so + // frame 30 disagrees with frame 0 however the two are sampled. + let thumb = |f: &engine::Frame| -> Vec { + (0..f.bgra.len()).step_by(6173).map(|i| f.bgra[i]).collect() + }; + assert_ne!( + thumb(&frames[0]), + thumb(&frames[FRAMES as usize / 2]), + "every frame identical -- nothing moved" + ); +} + +/// Export re-encodes to H.264 whatever the source was coded with: the packet +/// copy path is audio-only, so no VP8 byte can reach an `avc1` track. +#[test] +#[ignore = "needs a built libengine_hw.so and libvpx.so.9 -- no VA-API profile involved"] +fn a_vp8_source_exports_as_h264() { + let session = PlaybackSession::open(asset("test_vp8.webm")).expect("open test_vp8.webm"); + let meta = *session.meta(); + let project = Project::single(asset("test_vp8.webm"), meta.frame_count); + let out = Scratch::file("ve_export_vp8", "mp4"); + + let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None); + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < Duration::from_secs(120), "export hung"); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("outcome").expect("export"); + + let (written, _) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!(written.codec, Codec::H264, "exports are always H.264"); + // The fixture's own length and rate, back again: 60 pictures at 30 fps, + // which is the 2 s the source played. + assert_eq!(written.frame_count, FRAMES, "every timeline frame written"); + assert!((written.frame_rate - 30.0).abs() < 0.01, "{}", written.frame_rate); + assert_eq!((written.width, written.height), (1280, 720)); + let _ = std::fs::remove_file(&out); +} diff --git a/scripts/gen_fixtures.sh b/scripts/gen_fixtures.sh index 6f0b1b7..f6f723a 100755 --- a/scripts/gen_fixtures.sh +++ b/scripts/gen_fixtures.sh @@ -98,6 +98,125 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ -c:v libvpx-vp9 -b:v 2M -g 30 -profile:v 2 -pix_fmt yuv420p10le \ -an assets/test_vp9_10.webm +# VP8 fixture pair, the twins of the VP9 ones. ffmpeg's mov muxer carries no +# VP8 tag for mp4 at all (and its VP9 path re-parses the frames it is handed, +# dropping them), so the mp4 half is assembled by hand: the picture is encoded +# to an IVF, the AAC sound to an mp4 of its own, and the video track is +# spliced in with the `vp08` sample entry written out byte for byte -- the +# very entry `demux::sample_entry` reads by hand, which is what this fixture +# exists to exercise. `-enc_time_base 1/30` keeps the IVF timestamps exact, +# which is what the mp4 stts and the 30 fps the tests assert come from. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ + -c:v libvpx -b:v 2M -g 30 -enc_time_base 1/30 -pix_fmt yuv420p -an \ + assets/.test_vp8.ivf +ffmpeg -y -f lavfi -i "sine=frequency=440:duration=2" \ + -f lavfi -i "sine=frequency=880:duration=2" \ + -filter_complex "[0:a][1:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \ + -map "[a]" -c:a aac -b:a 128k assets/.test_vp8_audio.mp4 +python3 - <<'SPLICE' +import struct + +def boxes(buf, start, end): + res, at = [], start + while at + 8 <= end: + size = int.from_bytes(buf[at:at + 4], 'big') + hdr = 8 + if size == 1: + size = int.from_bytes(buf[at + 8:at + 16], 'big') + hdr = 16 + if size == 0: + size = end - at + res.append((bytes(buf[at + 4:at + 8]), at, at + size, at + hdr)) + at += size + return res + +def box(typ, payload): + return struct.pack('>I', 8 + len(payload)) + typ + payload + +def full(typ, ver_flags, payload): + return box(typ, struct.pack('>I', ver_flags) + payload) + +ivf = open('assets/.test_vp8.ivf', 'rb').read() +assert ivf[:4] == b'DKIF' +frames, at = [], 32 +while at + 12 <= len(ivf): + (n,) = struct.unpack_from('= old_dur, 'video shorter than audio' +splice_at = moov[1] # the video bytes go in right here, inside mdat + +UNITY = struct.pack('>9I', 0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000) +entry = box(b'vp08', + b'\0' * 6 + struct.pack('>H', 1) # resv, data ref index + + struct.pack('>HHI', 0, 0, 0) # pre_def, resv, pre_def + + struct.pack('>HH', 1280, 720) # width, height + + struct.pack('>II', 0x480000, 0x480000) # 72 dpi resolutions + + b'\0' * 12 + struct.pack('>H', 1) # resv, frame_count + + b'\0' * 32 # compressorname + + struct.pack('>HH', 0x18, 0xFFFF)) # depth, pre_defined +assert len(entry) == 86 +stco = bytearray(full(b'stco', 0, struct.pack('>II', 1, splice_at))) +tkhd = full(b'tkhd', 3, + struct.pack('>IIIII', 0, 0, next_id, 0, movie_dur) + + b'\0' * 8 + struct.pack('>HHHH', 0, 0, 0, 0) + UNITY + + struct.pack('>II', 1280 << 16, 720 << 16)) +mdhd = full(b'mdhd', 0, + struct.pack('>IIII', 0, 0, TIMESCALE, vid_dur) + + struct.pack('>HH', 0x55C4, 0)) # language und +hdlr = full(b'hdlr', 0, struct.pack('>I', 0) + b'vide' + b'\0' * 12 + b'\0') +minf = box(b'minf', + full(b'vmhd', 1, struct.pack('>HHHH', 0, 0, 0, 0)) + + box(b'dinf', box(b'dref', + struct.pack('>II', 0, 1) + full(b'url ', 1, b''))) + + box(b'stbl', + full(b'stsd', 0, struct.pack('>I', 1) + entry) + + full(b'stts', 0, struct.pack('>III', 1, len(frames), DELTA)) + + full(b'stsc', 0, struct.pack('>IIII', 1, 1, len(frames), 1)) + + full(b'stsz', 0, struct.pack('>II', 0, len(frames)) + + b''.join(struct.pack('>I', len(f)) for f in frames)) + + bytes(stco))) +mdia = box(b'mdia', mdhd + full(b'hdlr', 0, + struct.pack('>I', 0) + b'vide' + b'\0' * 12 + b'\0') + + minf) +trak = box(b'trak', tkhd + mdia) + +new = bytearray(data[:moov[1]]) +new += video +struct.pack_into('>I', new, mdat[1], (mdat[2] - mdat[1]) + len(video)) +moov_new = bytearray(data[moov[1]:moov[2]]) +m = next(b for b in boxes(moov_new, 8, len(moov_new)) if b[0] == b'mvhd') +struct.pack_into('>I', moov_new, m[3] + 16, max(old_dur, movie_dur)) +struct.pack_into('>I', moov_new, m[3] + 96, next_id + 1) +moov_new += trak +struct.pack_into('>I', moov_new, 0, len(moov_new)) +open('assets/test_vp8.mp4', 'wb').write(bytes(new + moov_new + data[moov[2]:])) +SPLICE +rm -f assets/.test_vp8.ivf assets/.test_vp8_audio.mp4 +# ...and the Matroska twin, the recipe of test_vp9.webm with libvpx rather +# than libvpx-vp9 for the picture and the same Opus sound a `.webm` carries. +# The engine reads `V_VP8` since the demux dispatch learned it; the decode +# half is the plugin's (there is no software VP8 decoder here), so both files +# are container and refusal fixtures. +ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \ + -f lavfi -i "sine=frequency=440:duration=2" \ + -c:v libvpx -b:v 2M -g 30 -pix_fmt yuv420p \ + -c:a libopus -b:a 96k assets/test_vp8.webm # One Matroska file per audio codec the refusal string in `audio.rs` claims is # decodable, as five tracks of one file: FLAC, MP3, Vorbis, ALAC and PCM. The # string said "AAC and AC-3 only" long after every one of these decoded, which is