forge
Explore
Log in

Don't you dare go Hollow

Software VP8 decode via dlopen'd libvpx seat in the plugin

Browse files at this commit

ba33df0b5f3eaee0f8a9510d96912d703202ae6aAhmet Kaan GümüşParent: 429bf04
  • feat
    • software VP8 decode via dlopen'd libvpx seat in the plugin
Show full message
✨ feat(engine): software VP8 decode via dlopen'd libvpx seat in the plugin

VP8 was refused by a stale UNSUPPORTED claim ('no VP8 decoder'); the
vendored cros-codecs VP8 decoder is VA-API-only and the test GPU
exposes no VP8 VA-API profile, so the real seat is software: libvpx.so.9
dlopen'd inside libengine_hw.so (vpx.rs), routed before any GPU device
opens, seek = destroy+re-init on the demuxer's keyframe contract,
CAP_VP8 reported as the plugin's seat. Codec::Vp8 plumbed through
demux (V_VP8 + mp4 vp08), colorspace, refusals; export UI gains a
truthful read-only VP8 row; test_vp8.{webm,mp4} fixtures + capability
row + tests/vp8.rs decode/export twins. Verified by the authoring
session: headless playloop 270 frames 0 dropped, 50/50 seeks, live
harness-driven UI playback, cross-provider review PASS (FFI layouts
against shipped libvpx DWARF, valgrind-clean).

24 changed files +1425 -131

Cargo.lockmodified+1 -0
@@ -1678,6 +1678,7 @@ dependencies = [
1678 "cros-codecs",1678 "cros-codecs",
1679 "engine",1679 "engine",
1680 "gbm",1680 "gbm",
1681+ "libloading",
1681 ]1682 ]
1682 1683
1683 [[package]]1684 [[package]]
crates/app/src/export_ui.rsmodified+8 -7
@@ -80,12 +80,12 @@ pub(crate) fn sample_rate_choices(current: Option<u32>) -> Vec<ChoiceRow> {
80 /// `shine-rs` was the licence question, and it is not the only encoder any80 /// `shine-rs` was the licence question, and it is not the only encoder any
81 /// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an81 /// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an
82 /// encoder — an *intra-only* one, which the rows say rather than let a user82 /// encoder — an *intra-only* one, which the rows say rather than let a user
83-/// find out from the size of the file. VP9 is the one this program still only83+/// find out from the size of the file. VP9 and VP8 are the ones this program
84-/// *reads*: the plugin decodes it and there is no encoder for it here, so it is84+/// still only *reads*: the plugin decodes them and there is no encoder for
85-/// a row for the reason the refusals are rows at all — a codec that opens but85+/// either here, so they are rows for the reason the refusals are rows at all —
86-/// never comes back out is exactly the gap a user would otherwise go looking86+/// a codec that opens but never comes back out is exactly the gap a user
87-/// for. AAC is not a row at all: it is what both containers' sound *is*, never a87+/// would otherwise go looking for. AAC is not a row at all: it is what both
88-/// file of its own.88+/// containers' sound *is*, never a file of its own.
89 ///89 ///
90 /// A codec is one row, and the boxes it can be written into are the row's90 /// A codec is one row, and the boxes it can be written into are the row's
91 /// containers: the same AV1 picture and the same AAC track go into a Matroska91 /// 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<u32>) -> Vec<ChoiceRow> {
93 /// the file, not about the encode. So the container is asked *once*, in a row93 /// the file, not about the encode. So the container is asked *once*, in a row
94 /// of its own, and only where there is more than one to ask about -- five94 /// of its own, and only where there is more than one to ask about -- five
95 /// picture rows to read past were four of them saying the same codec twice.95 /// picture rows to read past were four of them saying the same codec twice.
96-pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 8] = [96+pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 9] = [
97 (97 (
98 &[Format::Mp4],98 &[Format::Mp4],
99 "m",99 "m",
@@ -122,6 +122,7 @@ pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 8] = [
122 "Vorbis (rusty_vorbis) — quality-coded, stereo",122 "Vorbis (rusty_vorbis) — quality-coded, stereo",
123 ),123 ),
124 (&[], "", "VP9", "AV1 above replaces it"),124 (&[], "", "VP9", "AV1 above replaces it"),
125+ (&[], "", "VP8", "AV1 above replaces it"),
125 ];126 ];
126 127
127 /// The boxes one codec may be written into, in the order its container row128 /// The boxes one codec may be written into, in the order its container row
crates/app/src/main.rsmodified+28 -0
@@ -453,6 +453,14 @@ struct Player {
453 /// Where an export writes. Built once from the source path, which is not453 /// Where an export writes. Built once from the source path, which is not
454 /// otherwise kept.454 /// otherwise kept.
455 export_path: PathBuf,455 export_path: PathBuf,
456+ /// The export target this window itself last wrote or confirmed, so the
457+ /// overwrite question ([`Player::export_ask`]) can tell "the file exists"
458+ /// apart from "the file exists and is a stranger's": an export over a
459+ /// path this window never wrote asks first, a re-export over its own
460+ /// output does not (user 2026-09-11, "not just save but export too").
461+ /// Path equality, not a flag: retargeting the destination to somewhere
462+ /// else makes the answer foreign again.
463+ export_known: Option<PathBuf>,
456 /// Where the save action writes: the project this timeline was loaded from,464 /// Where the save action writes: the project this timeline was loaded from,
457 /// or the one derived beside the media it started as. Saving twice465 /// or the one derived beside the media it started as. Saving twice
458 /// overwrites the same file rather than making a second one.466 /// overwrites the same file rather than making a second one.
@@ -484,6 +492,23 @@ struct Player {
484 /// While it is up it owns the keyboard -- three answers and nothing else492 /// While it is up it owns the keyboard -- three answers and nothing else
485 /// ([`ui::stance`]'s root `on_key_down`).493 /// ([`ui::stance`]'s root `on_key_down`).
486 quit_ask: bool,494 quit_ask: bool,
495+ /// Whether the overwrite question is on screen: raised by Save's own
496+ /// door ([`Player::save_guarded`]) when the save's target exists on
497+ /// disk but `autosave_armed` says this window never loaded or wrote it
498+ /// -- a `.edith` the timeline only derives its name from beside an
499+ /// imported media file (user 2026-09-11, "saving over an existing file
500+ /// must warn first"). Same shape as `quit_ask` above: while it is up
501+ /// it owns the keyboard, and answering `enter` confirms the overwrite
502+ /// -- the save then arms `autosave_armed`, so later saves on this
503+ /// file are silent.
504+ save_ask: bool,
505+ /// Whether the export's overwrite question is on screen: raised inside
506+ /// [`Player::start_export`] -- after its refusals, so an export that
507+ /// cannot run never asks -- when `export_path` exists on disk and
508+ /// `export_known` says this window never wrote it. Same shape as
509+ /// `save_ask` above: while it is up it owns the keyboard, and answering
510+ /// `enter` marks the target known and starts the export.
511+ export_ask: bool,
487 /// Whether `project_path` names a file this window itself put there --512 /// Whether `project_path` names a file this window itself put there --
488 /// loaded from a `.edith` ([`Player::install_project`]) or written by a513 /// loaded from a `.edith` ([`Player::install_project`]) or written by a
489 /// manual save ([`Player::save_project`]) -- rather than one merely514 /// manual save ([`Player::save_project`]) -- rather than one merely
@@ -970,12 +995,15 @@ fn main() {
970 // `open_media`/`load_project` a drop goes through: an995 // `open_media`/`load_project` a drop goes through: an
971 // export beside the picture, a save beside it too.996 // export beside the picture, a save beside it too.
972 export_path: PathBuf::new(),997 export_path: PathBuf::new(),
998+ export_known: None,
973 project_path: PathBuf::new(),999 project_path: PathBuf::new(),
974 autosave_dirty: false,1000 autosave_dirty: false,
975 autosave_last_edit: None,1001 autosave_last_edit: None,
976 autosave_last_run: None,1002 autosave_last_run: None,
977 recovery_sidecar: None,1003 recovery_sidecar: None,
978 quit_ask: false,1004 quit_ask: false,
1005+ save_ask: false,
1006+ export_ask: false,
979 autosave_armed: false,1007 autosave_armed: false,
980 keymap: keymap.clone(),1008 keymap: keymap.clone(),
981 keys_open: false,1009 keys_open: false,
crates/app/src/player/actions.rsmodified+4 -1
@@ -85,7 +85,10 @@ impl Player {
85 cx.notify();85 cx.notify();
86 }86 }
87 ActionId::Export => self.open_export(cx),87 ActionId::Export => self.open_export(cx),
88- ActionId::Save => self.save_project(cx),88+ // Asked before the first overwrite of a file this window never
89+ // put there ([`Player::save_guarded`]); the window's own file
90+ // saves straight through.
91+ ActionId::Save => self.save_guarded(cx),
89 ActionId::Copy => self.copy_selected(),92 ActionId::Copy => self.copy_selected(),
90 ActionId::Paste => self.paste(cx),93 ActionId::Paste => self.paste(cx),
91 ActionId::Cut => self.cut(cx),94 ActionId::Cut => self.cut(cx),
crates/app/src/player/export.rsmodified+53 -0
@@ -558,6 +558,12 @@ impl Player {
558 /// with shift. Clamped to the engine's own bounds, so the number on the558 /// with shift. Clamped to the engine's own bounds, so the number on the
559 /// row is the number the encoder is given.559 /// row is the number the encoder is given.
560 pub(crate) fn nudge_budget(&mut self, steps: i32, coarse: bool) {560 pub(crate) fn nudge_budget(&mut self, steps: i32, coarse: bool) {
561+ // A video setting, like the field `n` opens: the sound-only moment
562+ // draws no row for the lever, so nothing moves what it does not
563+ // show -- the arrows, `+`/`-` and the wheel answer nothing there.
564+ if !self.format.has_video() {
565+ return;
566+ }
561 let step = i64::from(steps)567 let step = i64::from(steps)
562 * match coarse {568 * match coarse {
563 true => BPS_COARSE as i64,569 true => BPS_COARSE as i64,
@@ -592,6 +598,12 @@ impl Player {
592 /// (`850k`, `6.5M`, `6.5`, `1.2G` of file), not a way to edit digits, and598 /// (`850k`, `6.5M`, `6.5`, `1.2G` of file), not a way to edit digits, and
593 /// the number in force is still on the row until enter takes the new one.599 /// the number in force is still on the row until enter takes the new one.
594 pub(crate) fn edit_budget(&mut self) {600 pub(crate) fn edit_budget(&mut self) {
601+ // A video setting: the sound-only moment draws no row to type into,
602+ // so its door opens nothing either -- the chord stays swallowed (the
603+ // moment owns the keyboard) but no field opens under it.
604+ if !self.format.has_video() {
605+ return;
606+ }
595 self.budget_edit = Some(String::new());607 self.budget_edit = Some(String::new());
596 }608 }
597 609
@@ -755,6 +767,26 @@ impl Player {
755 }767 }
756 }768 }
757 769
770+ /// Whether an export has to be answered instead of started: the target
771+ /// exists on disk and is not a file this window wrote (or had confirmed)
772+ /// -- the same rule the save door keeps, with `export_known` playing
773+ /// `autosave_armed`'s part (user 2026-09-11, "not just save but export
774+ /// too": exporting over an existing file must warn first).
775+ pub(crate) fn export_needs_answer(&self) -> bool {
776+ Self::export_asks(
777+ self.export_path.exists(),
778+ self.export_known.as_deref() == Some(self.export_path.as_path()),
779+ )
780+ }
781+
782+ /// The export question as a value: a target that is there and not ours.
783+ /// Split out of [`Player::export_needs_answer`] so the rule can be read
784+ /// and tested without a window or a session -- the same shape
785+ /// [`Player::save_asks`] keeps for Save.
786+ pub(crate) fn export_asks(target_exists: bool, known: bool) -> bool {
787+ target_exists && !known
788+ }
789+
758 /// Writes the edit list out, at the settings the card was left at. Playback790 /// Writes the edit list out, at the settings the card was left at. Playback
759 /// stops first: the exporter opens its own decoder -- and, on the hardware791 /// stops first: the exporter opens its own decoder -- and, on the hardware
760 /// path, an encoder -- so a running player would only compete with it for792 /// path, an encoder -- so a running player would only compete with it for
@@ -777,6 +809,10 @@ impl Player {
777 // calls for the *estimate* and which nothing else needs a subtitle for.809 // calls for the *estimate* and which nothing else needs a subtitle for.
778 settings.subtitles = self.export_subs();810 settings.subtitles = self.export_subs();
779 settings.range = self.range;811 settings.range = self.range;
812+ // Asked here, before `session` borrows `self` mutably for the fences
813+ // below; nothing between here and the ask touches `export_path` or
814+ // `export_known`, so the answer cannot go stale on the way.
815+ let overwrite = self.export_needs_answer();
780 let Some(session) = &mut self.session else {816 let Some(session) = &mut self.session else {
781 self.notify_user("NOTHING TO EXPORT — no file open".into());817 self.notify_user("NOTHING TO EXPORT — no file open".into());
782 cx.notify();818 cx.notify();
@@ -801,8 +837,25 @@ impl Player {
801 cx.notify();837 cx.notify();
802 return;838 return;
803 }839 }
840+ // The last fence, after every refusal so an export that cannot run
841+ // never asks: writing over a file this window did not write is a
842+ // question, not a default. The card closes with the asking -- the
843+ // plate rises where notices rise and the moment is an overlay over
844+ // exactly that strip, so the two may not be on screen together.
845+ // `enter` there ([`ui::stance`]'s root handler) marks the target
846+ // known and comes back through this door, which then passes.
847+ if overwrite {
848+ self.close_card();
849+ self.export_ask = true;
850+ cx.notify();
851+ return;
852+ }
804 session.pause();853 session.pause();
805 self.export = Some(session.export_to_with(&self.export_path, &settings));854 self.export = Some(session.export_to_with(&self.export_path, &settings));
855+ // Ours from the first packet on: a re-export over this window's own
856+ // output is not a question (the plate's `enter` sets the same mark
857+ // before coming back through the door).
858+ self.export_known = Some(self.export_path.clone());
806 // The clock starts with the worker, not with the first repaint that859 // The clock starts with the worker, not with the first repaint that
807 // happens to notice it.860 // happens to notice it.
808 self.export_started = Some(Instant::now());861 self.export_started = Some(Instant::now());
crates/app/src/player/library.rsmodified+58 -2
@@ -1584,8 +1584,30 @@ impl Player {
1584 clips > 0 && dirty1584 clips > 0 && dirty
1585 }1585 }
1586 1586
1587- /// Writes the timeline back to its project file. Overwrites silently, like1587+ /// Whether a save has to be answered instead of obeyed: `project_path`
1588- /// an export: the path was chosen once and the notice is the confirmation.1588+ /// names a file on disk that this window itself did not put there --
1589+ /// neither loaded ([`Player::install_project`]) nor written
1590+ /// ([`Player::save_project`]) -- so the first ^s would clobber a
1591+ /// `.edith` this timeline only derives its name from beside an
1592+ /// imported media file (user 2026-09-11). `autosave_armed` is the
1593+ /// whole difference: once this window's own save has confirmed the
1594+ /// overwrite, later saves on the file are silent again.
1595+ pub(crate) fn save_needs_answer(&self) -> bool {
1596+ Self::save_asks(self.project_path.exists(), self.autosave_armed)
1597+ }
1598+
1599+ /// The overwrite question as a value: a target on disk and a window
1600+ /// that has not earned the write. Split out of
1601+ /// [`Player::save_needs_answer`] so the rule can be read and tested
1602+ /// without a window or a session, the way [`Player::close_asks`] is.
1603+ pub(crate) fn save_asks(target_exists: bool, armed: bool) -> bool {
1604+ target_exists && !armed
1605+ }
1606+
1607+ /// Writes the timeline back to its project file -- the confirmed write.
1608+ /// The overwrite question, when one is owed at all, was asked by Save's
1609+ /// door ([`Player::save_guarded`]) or already answered at the quit
1610+ /// plate; the notice here is the confirmation, not the permission.
1589 pub(crate) fn save_project(&mut self, cx: &mut Context<Self>) {1611 pub(crate) fn save_project(&mut self, cx: &mut Context<Self>) {
1590 let saved = self1612 let saved = self
1591 .session1613 .session
@@ -1617,6 +1639,22 @@ impl Player {
1617 cx.notify();1639 cx.notify();
1618 }1640 }
1619 1641
1642+ /// Save's door: asks before the first overwrite of a file this window
1643+ /// never put there, saves straight through once the file is the
1644+ /// window's own. Raising the question does not save -- the overwrite
1645+ /// plate (the root `on_key_down` in `ui::stance`) owns the keyboard
1646+ /// until it is answered, and only its `enter` comes back to
1647+ /// [`Player::save_project`], which is what arms `autosave_armed` and
1648+ /// makes every later save on the file silent.
1649+ pub(crate) fn save_guarded(&mut self, cx: &mut Context<Self>) {
1650+ if self.save_needs_answer() {
1651+ self.save_ask = true;
1652+ cx.notify();
1653+ return;
1654+ }
1655+ self.save_project(cx);
1656+ }
1657+
1620 /// Marks that an edit has landed since the sidecar last caught up, and1658 /// Marks that an edit has landed since the sidecar last caught up, and
1621 /// when: the door every edit that funnels through [`Player::act`] or a1659 /// when: the door every edit that funnels through [`Player::act`] or a
1622 /// timeline gesture calls on its way through. Cheap and safe to call on a1660 /// timeline gesture calls on its way through. Cheap and safe to call on a
@@ -1947,6 +1985,24 @@ mod autosave_tests {
1947 assert!(Player::close_asks(1, true));1985 assert!(Player::close_asks(1, true));
1948 }1986 }
1949 1987
1988+ /// The overwrite question Save's door asks: a target that exists on
1989+ /// disk but was never this window's (an import-derived `project_path`,
1990+ /// `autosave_armed` still false) warns before the first clobber; a
1991+ /// fresh path writes silently, and a file the window itself already
1992+ /// saved keeps every later ^s silent. The close rule's sibling.
1993+ #[test]
1994+ fn only_a_foreign_existing_file_asks_before_a_save_overwrites_it() {
1995+ assert!(Player::save_asks(true, false));
1996+ assert!(
1997+ !Player::save_asks(false, false),
1998+ "nothing on disk yet -- a first save needs no warning"
1999+ );
2000+ assert!(
2001+ !Player::save_asks(true, true),
2002+ "the window's own file -- later saves stay silent"
2003+ );
2004+ }
2005+
1950 /// The three answers [`Player::recovery_offer`] gives, off nothing but a2006 /// The three answers [`Player::recovery_offer`] gives, off nothing but a
1951 /// project file and a sidecar's mtimes: younger sidecar offers it, an2007 /// project file and a sidecar's mtimes: younger sidecar offers it, an
1952 /// older one or none at all offers nothing. Nowhere near a `Player` or a2008 /// older one or none at all offers nothing. Nowhere near a `Player` or a
crates/app/src/tests/cards.rsmodified+123 -2
@@ -877,7 +877,12 @@ fn the_budget_is_the_one_number_the_engine_gets() {
877 // One explicit rate, always: the Auto/Low/Medium/High/Exact ladder is877 // One explicit rate, always: the Auto/Low/Medium/High/Exact ladder is
878 // gone, so there is nothing left that sends `None` and lets the encoder878 // gone, so there is nothing left that sends `None` and lets the encoder
879 // pick a figure the row never showed.879 // pick a figure the row never showed.
880- let settings = export_settings(6_500_000, Format::Mp4, DEFAULT_AUDIO_KBPS, EncoderSeat::Auto);880+ let settings = export_settings(
881+ 6_500_000,
882+ Format::Mp4,
883+ DEFAULT_AUDIO_KBPS,
884+ EncoderSeat::Auto,
885+ );
881 assert_eq!(settings.bitrate, Some(6_500_000));886 assert_eq!(settings.bitrate, Some(6_500_000));
882 assert!(!settings.exact, "the copy path is off this surface");887 assert!(!settings.exact, "the copy path is off this surface");
883 assert_eq!(settings.audio_kbps, Some(DEFAULT_AUDIO_KBPS));888 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() {
980 2,985 2,
981 "one border for the plate and one for the chip: §4's single boxed chip"986 "one border for the plate and one for the chip: §4's single boxed chip"
982 );987 );
983- for gone in ["Advanced", "preset", "Quality", "Subtitles", "GPU: ", "Built in"] {988+ for gone in [
989+ "Advanced",
990+ "preset",
991+ "Quality",
992+ "Subtitles",
993+ "GPU: ",
994+ "Built in",
995+ ] {
984 assert!(!body.contains(gone), "the old card's {gone} is still here");996 assert!(!body.contains(gone), "the old card's {gone} is still here");
985 }997 }
986 // Row 1 is one line at every width: the stem ellipsizes and the998 // 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() {
1131 assert!(!sound_only.has_video() && sound_only != Format::Ogg);1143 assert!(!sound_only.has_video() && sound_only != Format::Ogg);
1132 }1144 }
1133 1145
1146+/// The budget is a video setting -- the engine's own word is that the bitrate
1147+/// settings "mean nothing to the audio-only ones" -- yet the moment drew the
1148+/// row, and answered `n` with a typing field, for a file that carries no
1149+/// picture. The row now mounts only where the format writes one, and both
1150+/// doors into the number answer the same gate: a row the moment does not
1151+/// show cannot have been changed.
1152+#[test]
1153+fn the_budget_row_and_its_doors_are_video_only() {
1154+ // The row: still built, mounted under the gate -- a video format sees
1155+ // exactly the rows it saw before.
1156+ let cards = src_text("ui/cards.rs");
1157+ let start = cards.find("fn export_card(").expect("the moment");
1158+ let body = &cards[start
1159+ ..start
1160+ + cards[start..]
1161+ .find("\n /// ")
1162+ .unwrap_or(cards.len() - start)];
1163+ assert!(
1164+ body.contains(".children(self.format.has_video().then(|| budget_row))"),
1165+ "the budget row is back on the sound-only moment"
1166+ );
1167+ // The `n` door: the moment's chord and the row's own click both funnel
1168+ // through `edit_budget`, so its gate is the one gate -- and it must sit
1169+ // ahead of the field it guards.
1170+ let typing = fn_body("edit_budget");
1171+ let (gate, _) = typing
1172+ .split_once("self.budget_edit = Some")
1173+ .expect("the typing field still opens");
1174+ assert!(
1175+ gate.contains("!self.format.has_video()"),
1176+ "`n` opens the budget field for a format that writes no picture"
1177+ );
1178+ // The value itself: arrows, `+`/`-` and the wheel all funnel through
1179+ // `nudge_budget` -- a lever nothing shows does not move either.
1180+ let lever = fn_body("nudge_budget");
1181+ let (gate, _) = lever
1182+ .split_once("self.custom_bps =")
1183+ .expect("the lever still sets the budget");
1184+ assert!(
1185+ gate.contains("!self.format.has_video()"),
1186+ "the hidden budget lever moves again"
1187+ );
1188+}
1189+
1190+/// Exporting over an existing file must warn first, "same pattern as the
1191+/// exit guard" (user 2026-09-11: "not just save but export too -- an export
1192+/// named like an existing video overrides it"). The question as a value: a
1193+/// target that is there and not this window's own asks; anything else just
1194+/// writes.
1195+#[test]
1196+fn only_a_foreign_existing_target_asks_before_an_export_overwrites_it() {
1197+ assert!(crate::Player::export_asks(true, false));
1198+ assert!(
1199+ !crate::Player::export_asks(false, false),
1200+ "nothing there to clobber"
1201+ );
1202+ assert!(!crate::Player::export_asks(false, true));
1203+ assert!(
1204+ !crate::Player::export_asks(true, true),
1205+ "a re-export over this window's own output is silent"
1206+ );
1207+}
1208+
1209+/// The guard's wiring: asked after every refusal (an export that cannot run
1210+/// never asks), before the worker starts; the moment closes with the asking
1211+/// (it overlays the strip the plate rises on); a started export marks the
1212+/// target this window's own so a re-export stays silent; and the plate's
1213+/// `enter` confirms the target before re-entering the door.
1214+#[test]
1215+fn the_export_overwrite_question_owns_the_door_and_the_keyboard() {
1216+ let body = fn_body("start_export");
1217+ assert!(
1218+ body.contains("self.export_needs_answer()"),
1219+ "start_export never asks before overwriting"
1220+ );
1221+ // The call is hoisted above the `&mut self.session` borrow (E0502); what
1222+ // must sit after the refusals is the *check* of its answer.
1223+ let (fences, rest) = body
1224+ .split_once("if overwrite {")
1225+ .expect("the guard's answer is never checked");
1226+ assert!(
1227+ fences.contains("format_refusal"),
1228+ "the question comes before the refusals: a refused export would ask"
1229+ );
1230+ let (guard, started) = rest
1231+ .split_once("export_to_with")
1232+ .expect("the worker is still started from start_export");
1233+ assert!(
1234+ guard.contains("self.close_card()") && guard.contains("self.export_ask = true"),
1235+ "asking leaves the moment up over the plate's strip"
1236+ );
1237+ assert!(
1238+ started.contains("self.export_known = Some(self.export_path.clone())"),
1239+ "a started export does not mark the target this window's own"
1240+ );
1241+ let stance = src_text("ui/stance.rs");
1242+ let (_, handler) = stance
1243+ .split_once("if this.export_ask {")
1244+ .expect("the export plate is up with no key answering it");
1245+ assert!(
1246+ handler.contains("this.export_known = Some(this.export_path.clone())"),
1247+ "the plate's enter does not confirm the target before re-entering the door"
1248+ );
1249+ assert!(
1250+ stance.contains("stance-export-ask") && stance.contains("file_name(&player.export_path)"),
1251+ "the export plate does not name the file it would overwrite"
1252+ );
1253+}
1254+
1134 /// One chord per thing, said the same on both surfaces: the moment's segments1255 /// One chord per thing, said the same on both surfaces: the moment's segments
1135 /// and the Settings room's EXPORT rows drive the same setters, so a chord that1256 /// and the Settings room's EXPORT rows drive the same setters, so a chord that
1136 /// drifted on one of them would teach the user a key the other refuses.1257 /// drifted on one of them would teach the user a key the other refuses.
crates/app/src/tests/layout.rsmodified+16 -0
@@ -3420,6 +3420,22 @@ fn one_name_per_source_one_stem_helper_and_one_save_door() {
3420 stance.contains("UNSAVED — save ↵ · discard d · stay esc"),3420 stance.contains("UNSAVED — save ↵ · discard d · stay esc"),
3421 "the decision plate speaks prose instead of state + verb·chord"3421 "the decision plate speaks prose instead of state + verb·chord"
3422 );3422 );
3423+ // The overwrite guard (user 2026-09-11: saving over an existing file
3424+ // must warn first, same pattern as the exit guard): Save no longer
3425+ // writes through the action directly -- it routes through the guarded
3426+ // door, which raises the plate with the target's own name, and the
3427+ // plate is answered by its own key block beside the quit plate's.
3428+ let actions = src_text("player/actions.rs");
3429+ assert!(
3430+ actions.contains("ActionId::Save => self.save_guarded(cx)")
3431+ && !actions.contains("ActionId::Save => self.save_project(cx)"),
3432+ "^s overwrites a foreign .edith without asking"
3433+ );
3434+ assert!(
3435+ stance.contains("if this.save_ask {")
3436+ && stance.contains("OVERWRITE {} — overwrite ↵ · keep esc"),
3437+ "the overwrite plate is up with no key answering it"
3438+ );
3423 assert!(3439 assert!(
3424 !src_text("ui/timeband_stance.rs").contains("ActionId::Save"),3440 !src_text("ui/timeband_stance.rs").contains("ActionId::Save"),
3425 "Save has two doors: the ledger's state word and the time band's ghost"3441 "Save has two doors: the ledger's state word and the time band's ghost"
crates/app/src/tests/media.rsmodified+10 -4
@@ -532,7 +532,7 @@ fn an_imports_subtitles_are_read_by_the_worker_and_only_pushed_here() {
532 #[test]532 #[test]
533 fn every_codec_row_is_offered_or_says_why_not() {533 fn every_codec_row_is_offered_or_says_why_not() {
534 // One row per codec, and the boxes it can go in are the container row's534 // One row per codec, and the boxes it can go in are the container row's
535- // business: seven rows that pick, one that says why it cannot. A codec535+ // business: seven rows that pick, two that say why they cannot. A codec
536 // twice over (AV1 · MKV beside AV1 · MP4) was two rows asking the same536 // twice over (AV1 · MKV beside AV1 · MP4) was two rows asking the same
537 // question, and five picture rows above the fold is what the card was537 // question, and five picture rows above the fold is what the card was
538 // called unfriendly for.538 // called unfriendly for.
@@ -626,9 +626,9 @@ fn every_codec_row_is_offered_or_says_why_not() {
626 "{key} is already the card's own"626 "{key} is already the card's own"
627 );627 );
628 }628 }
629- // The one codec left that this program reads and cannot write is a row629+ // The codecs this program reads and cannot write are rows of their own,
630- // of its own, refused by name rather than absent: VP9, because AV1 is630+ // refused by name rather than absent: VP9 and VP8, because AV1 is the
631- // the row that replaced it. Its reason travels with it, in the row or in631+ // row that replaced them. Their reason travels with them, in the row or
632 // the footer line that collects them -- either way it is on screen632 // the footer line that collects them -- either way it is on screen
633 // without a click. OGG was the other one until `rusty_vorbis` gave this633 // without a click. OGG was the other one until `rusty_vorbis` gave this
634 // project an encoder, and the row that says so is the row above.634 // 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() {
638 .expect("VP9 has a row");638 .expect("VP9 has a row");
639 assert!(row.is_empty(), "VP9 is not offered");639 assert!(row.is_empty(), "VP9 is not offered");
640 assert!(detail.contains("replaces it"), "VP9: {detail}");640 assert!(detail.contains("replaces it"), "VP9: {detail}");
641+ let (row, _, _, detail) = FORMATS
642+ .into_iter()
643+ .find(|(_, _, name, _)| *name == "VP8")
644+ .expect("VP8 has a row");
645+ assert!(row.is_empty(), "VP8 is not offered");
646+ assert!(detail.contains("replaces it"), "VP8: {detail}");
641 let (row, _, _, detail) = FORMATS647 let (row, _, _, detail) = FORMATS
642 .into_iter()648 .into_iter()
643 .find(|(_, _, name, _)| *name == "OGG")649 .find(|(_, _, name, _)| *name == "OGG")
crates/app/src/ui/cards.rsmodified+5 -1
@@ -827,7 +827,11 @@ impl Player {
827 .border_1()827 .border_1()
828 .border_color(rgba(DARK_SEAM()))828 .border_color(rgba(DARK_SEAM()))
829 .child(file_row)829 .child(file_row)
830- .child(budget_row)830+ // The budget is a video setting -- the engine takes
831+ // no bitrate for the sound-only formats -- so there
832+ // the moment mounts no row: a row it does not show
833+ // cannot have been changed.
834+ .children(self.format.has_video().then(|| budget_row))
831 .child(commit_row)835 .child(commit_row)
832 .into_any_element(),836 .into_any_element(),
833 )837 )
crates/app/src/ui/stance.rsmodified+94 -9
@@ -627,14 +627,16 @@ fn bench(
627 .child(bench_stance::render(player, bench_h - BENCH_CHROME_H, cx))627 .child(bench_stance::render(player, bench_h - BENCH_CHROME_H, cx))
628 }628 }
629 629
630-/// DESIGN §8's "needs a decision" notice, and the only one the room raises:630+/// DESIGN §8's "needs a decision" notice: a red 3px spine, the state word,
631-/// a red 3px spine, the state word, and the verbs that answer it -- state631+/// and the verbs that answer it -- state plus verb·chord, never a sentence.
632-/// plus verb·chord, never a sentence. It rises where notices rise, directly632+/// The room raises one per question that owns the keyboard (the
633-/// above the ledger, so it is never over the picture. The keys behind it live633+/// unsaved-work close guard, the overwrite guard on save), each passing its
634-/// in the root `on_key_down` above.634+/// own element id and line. It rises where notices rise, directly above the
635-fn decision_plate() -> impl IntoElement {635+/// ledger, so it is never over the picture. The keys behind it live in the
636+/// root `on_key_down` above.
637+fn decision_plate(id: &'static str, line: &str) -> impl IntoElement {
636 div()638 div()
637- .id("stance-quit-ask")639+ .id(id)
638 .flex_none()640 .flex_none()
639 .h(px(LEDGER_H))641 .h(px(LEDGER_H))
640 .bg(rgb(DARK_PANEL()))642 .bg(rgb(DARK_PANEL()))
@@ -655,7 +657,7 @@ fn decision_plate() -> impl IntoElement {
655 gpui::FontWeight::MEDIUM,657 gpui::FontWeight::MEDIUM,
656 ))658 ))
657 .text_color(rgb(INK1()))659 .text_color(rgb(INK1()))
658- .child("UNSAVED — save ↵ · discard d · stay esc"),660+ .child(line.to_owned()),
659 )661 )
660 }662 }
661 663
@@ -912,6 +914,7 @@ pub(crate) fn render(
912 // anywhere to route to (no file picker exists in the914 // anywhere to route to (no file picker exists in the
913 // tree), and every timeline with a clip on it got a915 // tree), and every timeline with a clip on it got a
914 // path from its first import (`project_path`).916 // path from its first import (`project_path`).
917+ // corner-cut: the overwrite guard is Save's door (`Player::save_guarded`), not this plate's -- this save was already answered.
915 this.save_project(cx);918 this.save_project(cx);
916 window.remove_window();919 window.remove_window();
917 }920 }
@@ -924,6 +927,61 @@ pub(crate) fn render(
924 }927 }
925 return;928 return;
926 }929 }
930+ // The overwrite question (user 2026-09-11: saving over an
931+ // existing file must warn first, "same pattern as the exit
932+ // guard"). Raised only by Save's own door
933+ // ([`Player::save_guarded`]) -- the target exists on disk and
934+ // `autosave_armed` says this window never loaded or wrote it --
935+ // so the ledger's unsaved ghost routes through the same ask.
936+ // Same ownership as the plate above: two answers and nothing
937+ // else -- `↵` overwrites and saves, `esc` keeps the file, any
938+ // other key does nothing at all.
939+ if this.save_ask {
940+ match key {
941+ "enter" => {
942+ // The answer IS the confirmation, so this goes
943+ // straight to the unconditional write and never
944+ // back through the guard; [`Player::save_project`]
945+ // arms `autosave_armed`, making later ^s on this
946+ // file silent again.
947+ this.save_project(cx);
948+ this.save_ask = false;
949+ cx.notify();
950+ }
951+ "escape" => {
952+ this.save_ask = false;
953+ cx.notify();
954+ }
955+ _ => {}
956+ }
957+ return;
958+ }
959+ // The export's own overwrite question (user 2026-09-11: "not just
960+ // save but export too"). Raised inside [`Player::start_export`]
961+ // after its refusals, with the export moment closed behind it --
962+ // the moment is an overlay over exactly the strip this plate
963+ // rises on. Same ownership as the plates above: `↵` marks the
964+ // target this window's own and goes back through the door, which
965+ // now passes the guard and starts the worker; `esc` keeps the
966+ // file; any other key does nothing at all.
967+ if this.export_ask {
968+ match key {
969+ "enter" => {
970+ // The answer IS the confirmation, so the target is
971+ // marked known *before* the door is re-entered --
972+ // the guard asks again otherwise.
973+ this.export_known = Some(this.export_path.clone());
974+ this.export_ask = false;
975+ this.start_export(cx);
976+ }
977+ "escape" => {
978+ this.export_ask = false;
979+ cx.notify();
980+ }
981+ _ => {}
982+ }
983+ return;
984+ }
927 // The recovery notice reads a key as more than "answered" (legacy985 // The recovery notice reads a key as more than "answered" (legacy
928 // `render.rs`'s own rule): `enter` loads the sidecar it named, any986 // `render.rs`'s own rule): `enter` loads the sidecar it named, any
929 // other key declines it. Asked before the generic dismiss below987 // other key declines it. Asked before the generic dismiss below
@@ -1123,7 +1181,34 @@ pub(crate) fn render(
1123 .child(time_band(player, position, cx))1181 .child(time_band(player, position, cx))
1124 .child(divider(Split::Bench, player.split_drag == Some(Split::Bench), cx))1182 .child(divider(Split::Bench, player.split_drag == Some(Split::Bench), cx))
1125 .child(bench(player, bench_h, window, cx))1183 .child(bench(player, bench_h, window, cx))
1126- .when(player.quit_ask, |el| el.child(decision_plate()))1184+ .when(player.quit_ask, |el| {
1185+ el.child(decision_plate(
1186+ "stance-quit-ask",
1187+ "UNSAVED — save ↵ · discard d · stay esc",
1188+ ))
1189+ })
1190+ .when(player.save_ask, |el| {
1191+ el.child(decision_plate(
1192+ "stance-save-ask",
1193+ &format!(
1194+ "OVERWRITE {} — overwrite ↵ · keep esc",
1195+ file_name(&player.project_path)
1196+ ),
1197+ ))
1198+ })
1199+ // The export overwrite plate sits with the other two, under
1200+ // the ledger: [`Player::start_export`] closes the export
1201+ // moment when it raises this, so the card that would cover
1202+ // the strip is never up together with the question.
1203+ .when(player.export_ask, |el| {
1204+ el.child(decision_plate(
1205+ "stance-export-ask",
1206+ &format!(
1207+ "OVERWRITE {} — overwrite ↵ · keep esc",
1208+ file_name(&player.export_path)
1209+ ),
1210+ ))
1211+ })
1127 .child(ledger(player, position, cx))1212 .child(ledger(player, position, cx))
1128 .when(player.settings_open, |el| {1213 .when(player.settings_open, |el| {
1129 el.child(settings_stance::render(player, window_size, cx))1214 el.child(settings_stance::render(player, window_size, cx))
crates/engine-hw/Cargo.tomlmodified+4 -0
@@ -14,3 +14,7 @@ engine = { path = "../engine" }
14 cros-codecs = { version = "0.0.6", features = ["vaapi"] }14 cros-codecs = { version = "0.0.6", features = ["vaapi"] }
15 # Same version cros-codecs already pulls in; we allocate output frames ourselves.15 # Same version cros-codecs already pulls in; we allocate output frames ourselves.
16 gbm = { version = "0.15", default-features = false, features = ["drm-support"] }16 gbm = { version = "0.15", default-features = false, features = ["drm-support"] }
17+# Same version `engine` pins for its own dlopens (`hw.rs`, `ao.rs`); this is
18+# the plugin's half of the same philosophy, one level down: `libvpx` for the
19+# software VP8 seat (`src/vpx.rs`), resolved at runtime like libva itself.
20+libloading = "0.8"
crates/engine-hw/src/lib.rsmodified+386 -66
@@ -1,7 +1,10 @@
1-//! VA-API decode (H.264, HEVC, VP9 and AV1) and encode (H.264 and HEVC, and AV11+//! VA-API decode (H.264, HEVC, VP9 and AV1) -- and VP8, which decodes on
2-//! where the GPU has an entrypoint for it), shipped as a2+//! `libvpx`, dlopen'd by this plugin in turn ([`vpx`], software, no VA-API
3+//! anything) -- and encode (H.264 and HEVC, and AV1 where the GPU has an
4+//! entrypoint for it), shipped as a
3 //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on5 //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on
4-//! libva/gbm/drm. Every entry point is6+//! libva/gbm/drm -- nor on libvpx, the same rule one level down. Every entry
7+//! point is
5 //! `extern "C"`, catches unwinds and reports failure as a null pointer or a8 //! `extern "C"`, catches unwinds and reports failure as a null pointer or a
6 //! negative code: the caller's contract is "any failure means use the software9 //! negative code: the caller's contract is "any failure means use the software
7 //! codec".10 //! codec".
@@ -25,6 +28,7 @@
25 //! `hwproc` and let the same helper hold both.28 //! `hwproc` and let the same helper hold both.
26 29
27 mod slice_fix;30 mod slice_fix;
31+mod vpx;
28 32
29 use std::collections::VecDeque;33 use std::collections::VecDeque;
30 use std::ffi::{CStr, c_char, c_void};34 use std::ffi::{CStr, c_char, c_void};
@@ -66,8 +70,11 @@ use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};
66 use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};70 use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
67 use gbm::{BufferObjectFlags, Format as GbmFormat};71 use gbm::{BufferObjectFlags, Format as GbmFormat};
68 72
69-use engine::demux::{Codec, Demuxer};73+use engine::demux::{Codec, Demuxer, VideoMeta};
70-use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta};74+use engine::hw::{
75+ CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP8, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta,
76+};
77+use vpx::VpxCtx;
71 78
72 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;79 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
73 type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;80 type Dec<C> = StatelessDecoder<C, VaapiBackend<PooledFrame>>;
@@ -335,8 +342,10 @@ fn open_devices() -> Option<(Rc<Display>, gbm::Device<std::fs::File>)> {
335 }342 }
336 343
337 impl Session {344 impl Session {
338- fn open(path: &Path) -> Option<Self> {345+ /// Assembles the VA-API half around a container that is already read --
339- let (meta, demuxer) = Demuxer::open(path).ok()?;346+ /// [`OpenSession::open_at`] owns the read and routes VP8 away from here
347+ /// before any device is opened.
348+ fn opened(meta: VideoMeta, demuxer: Demuxer) -> Option<Self> {
340 let (display, gbm) = open_devices()?;349 let (display, gbm) = open_devices()?;
341 // A 10-bit stream decodes into P010 surfaces and is read back through a350 // A 10-bit stream decodes into P010 surfaces and is read back through a
342 // P010 image; a driver that has no such image format is one this cannot351 // P010 image; a driver that has no such image format is one this cannot
@@ -366,6 +375,12 @@ impl Session {
366 Codec::Av1 => {375 Codec::Av1 => {
367 Decoder::Av1(Dec::<Av1>::new_vaapi(display, BlockingMode::Blocking).ok()?)376 Decoder::Av1(Dec::<Av1>::new_vaapi(display, BlockingMode::Blocking).ok()?)
368 }377 }
378+ Codec::Vp8 => {
379+ // Routed to [`VpxSession`] by [`OpenSession::open_at`] before
380+ // this half is ever built; the arm exists so the match stays
381+ // exhaustive about it.
382+ return None;
383+ }
369 };384 };
370 let pool = FramePool::new(move |info: &StreamInfo| {385 let pool = FramePool::new(move |info: &StreamInfo| {
371 alloc_nv12(&gbm, info.coded_resolution, ten_bit).expect("output frame allocation failed")386 alloc_nv12(&gbm, info.coded_resolution, ten_bit).expect("output frame allocation failed")
@@ -405,26 +420,9 @@ impl Session {
405 })420 })
406 }421 }
407 422
408- /// As [`Session::open`], but positioned so the first picture handed out is423+ /// Repositions an **open** session, exactly as [`OpenSession::open_at`]
409- /// sample `target_sample` (1-based): decode restarts at the sync sample at424+ /// positions a new one: the next [`Session::pump`] hands back sample
410- /// or before it and the pictures in between are dropped unread.425+ /// `target_sample`.
411- fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
412- let mut session = Self::open(path)?;
413- // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based
414- // display frames -- and answers with a signed one, since a sync sample
415- // inside what the edit list trims sits before frame 0.
416- let target_frame = target_sample.saturating_sub(1);
417- let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
418- session.skip = (i64::from(target_frame) - first).max(0) as u32;
419- session.position = first;
420- if target_frame > 0 {
421- session.leading = 0;
422- }
423- Some(session)
424- }
425-
426- /// Repositions an **open** session, exactly as [`Session::open_at`] positions
427- /// a new one: the next [`Session::pump`] hands back sample `target_sample`.
428 ///426 ///
429 /// This is what a seek costs when the session is kept, and most of it is427 /// This is what a seek costs when the session is kept, and most of it is
430 /// skippable: a target *ahead* of where the decoder stands, within428 /// skippable: a target *ahead* of where the decoder stands, within
@@ -789,10 +787,300 @@ fn p010_to_i420(
789 }787 }
790 }788 }
791 789
790+/// What the plugin is decoding a file on: the VA-API stateless decoders, or
791+/// -- for VP8 alone -- libvpx in this plugin's own address space. The split
792+/// is the codec's, decided once at [`OpenSession::open_at`]: VP8 opens no VA
793+/// display (this GPU has no VP8 profile to ask it for, and a machine with no
794+/// render node at all still decodes VP8), and the other four never touch
795+/// libvpx.
796+///
797+/// Everything past the split is written twice -- [`Session`] for the VA-API
798+/// decoders and [`VpxSession`] for libvpx -- rather than folded into one
799+/// shape: the halves share the *contract* (open at a sample, pump one
800+/// picture, fill a [`VhFrame`]) and nothing underneath it, and a trait over
801+/// "a `vaGetImage`" versus "a memcpy" is the kind of seam that hides which
802+/// path a measurement ran on.
803+enum OpenSession {
804+ Vaapi(Session),
805+ Vpx(VpxSession),
806+}
807+
808+impl OpenSession {
809+ /// Opens `path` for decode, positioned so the first picture handed out is
810+ /// sample `target_sample` (1-based): decode restarts at the sync sample at
811+ /// or before it and the pictures in between are dropped unread. The same
812+ /// landing for both halves; the codec's half is chosen here, where the
813+ /// container has been read and no device has been opened yet.
814+ fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
815+ let (meta, demuxer) = Demuxer::open(path).ok()?;
816+ let session = match meta.codec {
817+ Codec::Vp8 => Self::Vpx(VpxSession::opened(meta, demuxer)?),
818+ _ => Self::Vaapi(Session::opened(meta, demuxer)?),
819+ };
820+ // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based
821+ // display frames -- and answers with a signed one, since a sync sample
822+ // inside what the edit list trims sits before frame 0.
823+ let target_frame = target_sample.saturating_sub(1);
824+ match session {
825+ Self::Vaapi(mut session) => {
826+ let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
827+ session.skip = (i64::from(target_frame) - first).max(0) as u32;
828+ session.position = first;
829+ if target_frame > 0 {
830+ session.leading = 0;
831+ }
832+ Some(Self::Vaapi(session))
833+ }
834+ Self::Vpx(mut session) => {
835+ let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
836+ session.skip = (i64::from(target_frame) - first).max(0) as u32;
837+ session.position = first;
838+ Some(Self::Vpx(session))
839+ }
840+ }
841+ }
842+
843+ fn meta(&self) -> &VhMeta {
844+ match self {
845+ Self::Vaapi(session) => &session.meta,
846+ Self::Vpx(session) => &session.meta,
847+ }
848+ }
849+
850+ fn seek_to(&mut self, target_sample: u32) -> Result<(), String> {
851+ match self {
852+ Self::Vaapi(session) => session.seek_to(target_sample),
853+ Self::Vpx(session) => session.seek_to(target_sample),
854+ }
855+ }
856+
857+ /// Pumps the decoder until one picture is ready, delivered into the
858+ /// session's own buffer. `Ok(false)` is clean end of stream.
859+ fn pump(&mut self) -> Result<bool, String> {
860+ match self {
861+ Self::Vaapi(session) => session.pump(),
862+ Self::Vpx(session) => session.pump(),
863+ }
864+ }
865+
866+ /// Points `out` at the picture [`OpenSession::pump`] just delivered.
867+ fn fill(&self, out: &mut VhFrame) {
868+ match self {
869+ Self::Vaapi(session) => session.fill(out),
870+ Self::Vpx(session) => session.fill(out),
871+ }
872+ }
873+}
874+
875+/// One libvpx decode session: the VP8 half of the plugin, the whole of the
876+/// same job [`Session`] does for the VA-API codecs. No display, no GBM, no
877+/// surface pool -- libvpx hands the planes back in memory, and the only
878+/// shapes worth carrying over from the other half are the ones the caller
879+/// sees: [`VhMeta`], one picture per `pump`, the same [`VhFrame`] layout, the
880+/// same skip/position arithmetic a seek is.
881+///
882+/// VP8 reorders nothing: every access unit fed is one picture out, in feed
883+/// order, which is why `position` advances exactly as the VA-API half's does
884+/// without any of its drain machinery.
885+struct VpxSession {
886+ vpx: &'static vpx::Vpx,
887+ ctx: VpxCtx,
888+ demuxer: Demuxer,
889+ meta: VhMeta,
890+ flushed: bool,
891+ /// Pictures still to be decoded and thrown away to land on a seek target,
892+ /// exactly [`Session`]'s field of the same name.
893+ skip: u32,
894+ /// The display frame the next `pump` would hand out -- [`Session`]'s
895+ /// field, again: one further along for every picture pulled, skipped past
896+ /// and delivered alike.
897+ position: i64,
898+ /// Tightly packed I420 handed out through [`VhFrame`]; reused every
899+ /// frame, which is exactly why the pointers are only valid until the
900+ /// next call.
901+ out: Vec<u8>,
902+ luma: usize,
903+ chroma: usize,
904+}
905+
906+impl VpxSession {
907+ fn opened(meta: VideoMeta, demuxer: Demuxer) -> Option<Self> {
908+ let vpx = vpx::vpx()?;
909+ let mut session = Self {
910+ vpx,
911+ ctx: VpxCtx::default(),
912+ demuxer,
913+ meta: VhMeta {
914+ width: meta.width,
915+ height: meta.height,
916+ frame_rate: meta.frame_rate,
917+ frame_count: meta.frame_count,
918+ },
919+ flushed: false,
920+ skip: 0,
921+ position: 0,
922+ out: Vec::new(),
923+ luma: 0,
924+ chroma: 0,
925+ };
926+ if let Err(e) = session.init() {
927+ eprintln!("engine_hw: {e}");
928+ return None;
929+ }
930+ Some(session)
931+ }
932+
933+ /// (Re-)initialises the decoder. libvpx has no mid-stream reset, so this
934+ /// *is* the flush: a seek pays destroy + init, and what makes that safe
935+ /// is the demuxer's sync-sample seek, which restarts the feed where the
936+ /// reference chain restarts -- the same discipline [`Session`]'s VA-API
937+ /// flush leans on.
938+ fn init(&mut self) -> Result<(), String> {
939+ self.vpx.dec_init(&mut self.ctx)
940+ }
941+
942+ /// Feeds one access unit. VP8 emits at most one picture per unit, so the
943+ /// pull belongs to the `pump` loop, not here.
944+ fn decode(&mut self, au: &[u8]) -> Result<(), String> {
945+ if au.is_empty() {
946+ return Ok(());
947+ }
948+ self.vpx.decode(&mut self.ctx, au)
949+ }
950+
951+ fn pump(&mut self) -> Result<bool, String> {
952+ loop {
953+ // Whatever the last fed unit produced is the picture this call
954+ // hands back. The iterator starts fresh per feed because VP8
955+ // queues nothing: one unit in, at most one picture out.
956+ let mut iter: *const c_void = std::ptr::null();
957+ while let Some(img) = self.vpx.get_frame(&mut self.ctx, &mut iter) {
958+ // One picture further along, shown or skipped past alike --
959+ // the same walk [`Session::pump`] makes. The fields the copy
960+ // needs are taken by value, which ends the context's borrow
961+ // before `emit` may take the session again.
962+ let (planes, stride, (w, h)) = (img.planes, img.stride, img.display());
963+ self.position += 1;
964+ if self.skip > 0 {
965+ self.skip -= 1;
966+ continue;
967+ }
968+ self.emit(planes, stride, w, h);
969+ return Ok(true);
970+ }
971+ if self.flushed {
972+ return Ok(false);
973+ }
974+ match self.demuxer.next_access_unit() {
975+ Ok(Some(au)) => self.decode(&au)?,
976+ Ok(None) => {
977+ // End of the track: the empty `vpx_codec_decode` that
978+ // releases anything held back is this decoder's flush,
979+ // and it costs no iteration of its own -- the pull at the
980+ // top of the loop drains it.
981+ self.vpx.flush(&mut self.ctx)?;
982+ self.flushed = true;
983+ }
984+ Err(e) => return Err(e.to_string()),
985+ }
986+ }
987+ }
988+
989+ /// Copies one decoded I420 picture into `self.out` -- [`Session::emit`]
990+ /// for a decoder that hands the planes back in memory rather than behind
991+ /// a `vaGetImage`. VP8 output is always 8-bit 4:2:0, so there is no
992+ /// 10-bit branch to mirror.
993+ fn emit(&mut self, planes: [*mut u8; 4], stride: [std::ffi::c_int; 4], w: u32, h: u32) {
994+ let (w, h) = (w as usize, h as usize);
995+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
996+ if self.luma != w * h || self.chroma != cw * ch {
997+ self.luma = w * h;
998+ self.chroma = cw * ch;
999+ self.out = vec![0u8; self.luma + 2 * self.chroma];
1000+ }
1001+ self.meta.width = w as u32;
1002+ self.meta.height = h as u32;
1003+ let (dst_y, rest) = self.out.split_at_mut(self.luma);
1004+ let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
1005+ // SAFETY: libvpx guarantees the planes stride-cover the *display*
1006+ // size (4:2:0, so the chroma planes cover cw x ch) for the life of
1007+ // the image, which ends at this session's next `get_frame` -- after
1008+ // the copies below.
1009+ unsafe {
1010+ copy_plane(planes[0], stride[0] as usize, dst_y, w, h);
1011+ copy_plane(planes[1], stride[1] as usize, dst_u, cw, ch);
1012+ copy_plane(planes[2], stride[2] as usize, dst_v, cw, ch);
1013+ }
1014+ }
1015+
1016+ fn fill(&self, out: &mut VhFrame) {
1017+ let w = self.meta.width as usize;
1018+ let cw = w.div_ceil(2);
1019+ out.y = self.out.as_ptr();
1020+ // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`.
1021+ unsafe {
1022+ out.u = self.out.as_ptr().add(self.luma);
1023+ out.v = self.out.as_ptr().add(self.luma + self.chroma);
1024+ }
1025+ out.y_stride = w;
1026+ out.u_stride = cw;
1027+ out.v_stride = cw;
1028+ out.width = self.meta.width;
1029+ out.height = self.meta.height;
1030+ }
1031+
1032+ /// Repositions the session, exactly [`Session::seek_to`]: the same
1033+ /// forward walk within [`FORWARD_SECS`], the same demuxer seek to a sync
1034+ /// sample otherwise -- and for the decoder, destroy + re-init where the
1035+ /// VA-API half pays a flush, because VP8 is stateful to its last inter
1036+ /// frame and libvpx offers no softer reset.
1037+ fn seek_to(&mut self, target_sample: u32) -> Result<(), String> {
1038+ let target_frame = target_sample.saturating_sub(1);
1039+ if let Reposition::Forward(ahead) = reposition(
1040+ self.position,
1041+ i64::from(target_frame),
1042+ self.meta.frame_count,
1043+ forward_limit(self.meta.frame_rate),
1044+ ) {
1045+ self.skip = forward_skip(self.skip, ahead);
1046+ return Ok(());
1047+ }
1048+ // Dropping every reference the decoder holds. The destroy's answer is
1049+ // not checked against `Ok` because the init below re-zeroes the
1050+ // context either way; a destroy that failed has nothing to leak.
1051+ self.vpx.destroy(&mut self.ctx);
1052+ self.init()?;
1053+ self.flushed = false;
1054+ let first = self.demuxer.seek_to_sync_at_or_before(target_frame);
1055+ self.skip = (i64::from(target_frame) - first).max(0) as u32;
1056+ self.position = first;
1057+ Ok(())
1058+ }
1059+}
1060+
1061+impl Drop for VpxSession {
1062+ fn drop(&mut self) {
1063+ self.vpx.destroy(&mut self.ctx);
1064+ }
1065+}
1066+
1067+/// One strided plane down to tightly packed rows: the whole of the read-back
1068+/// a VP8 picture costs, where the VA-API half pays `vaGetImage` for the same.
1069+///
1070+/// # Safety
1071+/// `src` must stride-cover `w` x `h`, and `dst` must be `w` x `h`.
1072+unsafe fn copy_plane(src: *const u8, stride: usize, dst: &mut [u8], w: usize, h: usize) {
1073+ for row in 0..h {
1074+ let s = unsafe { std::slice::from_raw_parts(src.add(row * stride), w) };
1075+ dst[row * w..(row + 1) * w].copy_from_slice(s);
1076+ }
1077+}
1078+
792 /// Opens `path` for hardware decode, positioned so the first1079 /// Opens `path` for hardware decode, positioned so the first
793 /// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean1080 /// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean
794 /// the start of the stream). Returns null on any failure at all: no libva1081 /// the start of the stream). Returns null on any failure at all: no libva
795-/// runtime, no render node, unsupported profile, unreadable file.1082+/// runtime, no render node, no libvpx for a VP8 file, unsupported profile,
1083+/// unreadable file.
796 ///1084 ///
797 /// # Safety1085 /// # Safety
798 /// `path` must be a valid NUL-terminated C string.1086 /// `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) ->
807 let Ok(path) = path.to_str() else {1095 let Ok(path) = path.to_str() else {
808 return std::ptr::null_mut();1096 return std::ptr::null_mut();
809 };1097 };
810- match Session::open_at(Path::new(path), target_sample) {1098+ match OpenSession::open_at(Path::new(path), target_sample) {
811 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,1099 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
812 None => std::ptr::null_mut(),1100 None => std::ptr::null_mut(),
813 }1101 }
@@ -827,11 +1115,12 @@ pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32
827 }1115 }
828 // SAFETY: caller-guaranteed live session and writable destination.1116 // SAFETY: caller-guaranteed live session and writable destination.
829 unsafe {1117 unsafe {
830- let session = &*(session as *const Session);1118+ let session = &*(session as *const OpenSession);
831- (*out).width = session.meta.width;1119+ let meta = session.meta();
832- (*out).height = session.meta.height;1120+ (*out).width = meta.width;
833- (*out).frame_rate = session.meta.frame_rate;1121+ (*out).height = meta.height;
834- (*out).frame_count = session.meta.frame_count;1122+ (*out).frame_rate = meta.frame_rate;
1123+ (*out).frame_count = meta.frame_count;
835 }1124 }
836 01125 0
837 }))1126 }))
@@ -850,7 +1139,7 @@ pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame)
850 return -1;1139 return -1;
851 }1140 }
852 // SAFETY: caller-guaranteed live session and writable destination.1141 // SAFETY: caller-guaranteed live session and writable destination.
853- let session = unsafe { &mut *(session as *mut Session) };1142+ let session = unsafe { &mut *(session as *mut OpenSession) };
854 match session.pump() {1143 match session.pump() {
855 Ok(true) => {1144 Ok(true) => {
856 // SAFETY: `out` is non-null and writable per the contract.1145 // 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
881 return -1;1170 return -1;
882 }1171 }
883 // SAFETY: caller-guaranteed live session.1172 // SAFETY: caller-guaranteed live session.
884- let session = unsafe { &mut *(session as *mut Session) };1173+ let session = unsafe { &mut *(session as *mut OpenSession) };
885 match session.seek_to(target_sample) {1174 match session.seek_to(target_sample) {
886 Ok(()) => 0,1175 Ok(()) => 0,
887 Err(e) => {1176 Err(e) => {
@@ -923,38 +1212,57 @@ pub unsafe extern "C" fn vh_next_frame_dma(
923 return -1;1212 return -1;
924 }1213 }
925 // SAFETY: caller-guaranteed live session and writable destinations.1214 // SAFETY: caller-guaranteed live session and writable destinations.
926- let session = unsafe { &mut *(session as *mut Session) };1215+ let session = unsafe { &mut *(session as *mut OpenSession) };
927 // SAFETY: as above.1216 // SAFETY: as above.
928 unsafe { *dma = VhDma::default() };1217 unsafe { *dma = VhDma::default() };
929- // A pool sized without the reserve has nothing to lend: this session1218+ // A libvpx picture has no GPU buffer to hand over: this session reads
930- // has been read back from, so it stays that way.1219+ // back, exactly as `vh_next_frame` does, and the caller's `dma` keeps
931- if !session.sized || session.hold > 0 {1220+ // the fd-below-zero default that says so.
932- session.hold = DMA_HOLD;1221+ match session {
933- session.want = Some(VhDma {1222+ OpenSession::Vpx(session) => match session.pump() {
934- fourcc: VA_FOURCC_NV12,1223+ Ok(true) => {
935- coded_width,1224+ // SAFETY: `out` is non-null and writable per the contract.
936- coded_height,1225+ session.fill(unsafe { &mut *out });
937- width,1226+ 1
938- height,1227+ }
939- ..VhDma::default()1228+ Ok(false) => 0,
940- });1229+ Err(e) => {
941- }1230+ eprintln!("engine_hw: {e}");
942- let pumped = session.pump();1231+ -2
943- session.want = None;1232+ }
944- match pumped {1233+ },
945- Ok(true) => {1234+ OpenSession::Vaapi(session) => {
946- match session.dma.take() {1235+ // A pool sized without the reserve has nothing to lend: this
947- // SAFETY: `dma` is non-null and writable per the contract.1236+ // session has been read back from, so it stays that way.
948- Some(desc) => unsafe { *dma = desc },1237+ if !session.sized || session.hold > 0 {
949- // SAFETY: as above, for `out`.1238+ session.hold = DMA_HOLD;
950- None => session.fill(unsafe { &mut *out }),1239+ session.want = Some(VhDma {
1240+ fourcc: VA_FOURCC_NV12,
1241+ coded_width,
1242+ coded_height,
1243+ width,
1244+ height,
1245+ ..VhDma::default()
1246+ });
1247+ }
1248+ let pumped = session.pump();
1249+ session.want = None;
1250+ match pumped {
1251+ Ok(true) => {
1252+ match session.dma.take() {
1253+ // SAFETY: `dma` is non-null and writable per the contract.
1254+ Some(desc) => unsafe { *dma = desc },
1255+ // SAFETY: as above, for `out`.
1256+ None => session.fill(unsafe { &mut *out }),
1257+ }
1258+ 1
1259+ }
1260+ Ok(false) => 0,
1261+ Err(e) => {
1262+ eprintln!("engine_hw: {e}");
1263+ -2
1264+ }
951 }1265 }
952- 1
953- }
954- Ok(false) => 0,
955- Err(e) => {
956- eprintln!("engine_hw: {e}");
957- -2
958 }1266 }
959 }1267 }
960 }))1268 }))
@@ -970,7 +1278,7 @@ pub unsafe extern "C" fn vh_close(session: *mut c_void) {
970 let _ = catch_unwind(AssertUnwindSafe(|| {1278 let _ = catch_unwind(AssertUnwindSafe(|| {
971 if !session.is_null() {1279 if !session.is_null() {
972 // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`.1280 // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`.
973- drop(unsafe { Box::from_raw(session as *mut Session) });1281+ drop(unsafe { Box::from_raw(session as *mut OpenSession) });
974 }1282 }
975 }));1283 }));
976 }1284 }
@@ -1025,6 +1333,13 @@ const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option<VAProfile
1025 /// codecs this plugin actually implements can light up -- `CAP_TABLE` is that1333 /// codecs this plugin actually implements can light up -- `CAP_TABLE` is that
1026 /// half of the intersection.1334 /// half of the intersection.
1027 ///1335 ///
1336+/// VP8 is the one bit asked of nobody: it is this plugin's libvpx seat, lit
1337+/// when the library loads and nothing else -- no profile, no entrypoint, no
1338+/// display. It rides along only when the display *is* answerable, because
1339+/// this symbol's shape says a displayless machine has nothing to report at
1340+/// all; the decode path itself needs no display for it
1341+/// ([`OpenSession::open_at`] routes VP8 before any device opens).
1342+///
1028 /// `None` when there is no display to ask at all, which is the same "software1343 /// `None` when there is no display to ask at all, which is the same "software
1029 /// only" a missing plugin means.1344 /// only" a missing plugin means.
1030 fn query_caps() -> Option<VhCaps> {1345 fn query_caps() -> Option<VhCaps> {
@@ -1058,6 +1373,11 @@ fn query_caps() -> Option<VhCaps> {
1058 caps.encode |= bit;1373 caps.encode |= bit;
1059 }1374 }
1060 }1375 }
1376+ // The plugin's own software decoder, on its own account rather than the
1377+ // driver's -- the plugin's capability, never a GPU feat.
1378+ if vpx::vpx().is_some() {
1379+ caps.decode |= CAP_VP8;
1380+ }
1061 Some(caps)1381 Some(caps)
1062 }1382 }
1063 1383
crates/engine-hw/src/vpx.rsadded+273 -0
@@ -0,0 +1,273 @@
1+//! `libvpx`, dlopen'd: the software VP8 decoder, and the reason a VP8 file
2+//! decodes on a machine whose GPU has no VP8 profile -- or whose GPU is
3+//! absent altogether.
4+//!
5+//! The plugin's own libva linkage, one level down: this plugin keeps no
6+//! DT_NEEDED on `libvpx` any more than the main binary does. The symbols are
7+//! resolved lazily, once, and a machine without the library is a machine
8+//! without the codec -- answered as `None` at [`vpx`] before any file is
9+//! opened, which is what [`crate::query_caps`] reports as the absence of
10+//! `CAP_VP8`.
11+//!
12+//! The extern declarations are hand-written against `vpx_decoder.h`,
13+//! `vpx_codec.h` and `vpx_image.h` as this soname has carried them since
14+//! libvpx 1.14: `VPX_DECODER_ABI_VERSION` 12. A libvpx from another ABI
15+//! answers `vpx_codec_dec_init_ver` with `VPX_CODEC_ABI_MISMATCH`, which
16+//! surfaces as a refused session -- loudly, in the eprintln, never as a
17+//! wrong picture. The struct layouts below are the ABI, not an assumption:
18+//! `vpx_codec_ctx_t`'s fields have not moved since the library's first
19+//! release, and `vpx_image_t`'s prefix is what every decoder in the field
20+//! reads.
21+
22+use std::ffi::{CStr, c_char, c_int, c_long, c_uint, c_void};
23+use std::sync::LazyLock;
24+
25+use libloading::Library;
26+
27+/// `VPX_DECODER_ABI_VERSION`: `3 + VPX_CODEC_ABI_VERSION`, and
28+/// `VPX_CODEC_ABI_VERSION = 4 + VPX_IMAGE_ABI_VERSION` with
29+/// `VPX_IMAGE_ABI_VERSION = 5` -- the three headers this module mirrors.
30+const VPX_DECODER_ABI_VERSION: c_int = 12;
31+
32+/// `VPX_CODEC_OK`, the one return code that is not a refusal.
33+const VPX_CODEC_OK: c_int = 0;
34+
35+/// `VPX_DL_REALTIME`, the decode `deadline` argument -- which `vpx_decoder.h`
36+/// states this API ignores; passed because the type demands a value, and the
37+/// constant because it is the documented one.
38+const VPX_DL_REALTIME: c_long = 1;
39+
40+/// The decoder context, `vpx_codec_ctx_t` field for field. Nothing here is
41+/// read: the struct exists so the context is laid out exactly as libvpx
42+/// lays it out, and so the `&mut` handoffs to the C side are the whole of
43+/// the story.
44+#[repr(C)]
45+pub struct VpxCtx {
46+ name: *const c_char,
47+ iface: *const c_void,
48+ err: c_int,
49+ err_detail: *const c_char,
50+ init_flags: c_uint,
51+ config: *const c_void,
52+ priv_: *mut c_void,
53+}
54+
55+impl Default for VpxCtx {
56+ fn default() -> Self {
57+ // SAFETY: all-pointer/zero initialisation is what libvpx's own init
58+ // performs on the context before it fills it; `vpx_codec_dec_init_ver`
59+ // re-zeroes it anyway.
60+ unsafe { std::mem::zeroed() }
61+ }
62+}
63+
64+/// `vpx_codec_dec_cfg_t`: thread count and a best-known size the caller may
65+/// leave at zero.
66+#[repr(C)]
67+struct VpxDecCfg {
68+ threads: c_uint,
69+ w: c_uint,
70+ h: c_uint,
71+}
72+
73+/// `vpx_image_t` complete: the planes of one decoded picture and the strides
74+/// they sit at. The decoder owns the bytes -- they stay valid only until the
75+/// next `get_frame` or `decode` on the same context, which is exactly the
76+/// [`crate::VhFrame`] contract the caller already lives with.
77+#[repr(C)]
78+pub struct VpxImage {
79+ fmt: c_int,
80+ cs: c_int,
81+ range: c_int,
82+ w: c_uint,
83+ h: c_uint,
84+ bit_depth: c_uint,
85+ d_w: c_uint,
86+ d_h: c_uint,
87+ r_w: c_uint,
88+ r_h: c_uint,
89+ x_chroma_shift: c_uint,
90+ y_chroma_shift: c_uint,
91+ pub planes: [*mut u8; 4],
92+ pub stride: [c_int; 4],
93+ bps: c_int,
94+ user_priv: *mut c_void,
95+ img_data: *mut u8,
96+ img_data_owner: c_int,
97+ self_allocd: c_int,
98+ fb_priv: *mut c_void,
99+}
100+
101+impl VpxImage {
102+ /// Displayed dimensions: what [`crate::VhFrame`] describes, not the
103+ /// macroblock-padded storage the planes actually cover.
104+ pub fn display(&self) -> (u32, u32) {
105+ (self.d_w, self.d_h)
106+ }
107+}
108+
109+type Dx = unsafe extern "C" fn() -> *const c_void;
110+type DecInitVer =
111+ unsafe extern "C" fn(*mut VpxCtx, *const c_void, *const VpxDecCfg, c_uint, c_int) -> c_int;
112+type Decode = unsafe extern "C" fn(*mut VpxCtx, *const u8, c_uint, *mut c_void, c_long) -> c_int;
113+type GetFrame = unsafe extern "C" fn(*mut VpxCtx, *mut *const c_void) -> *mut VpxImage;
114+type Destroy = unsafe extern "C" fn(*mut VpxCtx) -> c_int;
115+type ErrorFn = unsafe extern "C" fn(*const VpxCtx) -> *const c_char;
116+
117+/// The resolved symbols, held with the library that carries them -- exactly
118+/// the shape `engine::hw`'s `Plugin` has on the other side of the ABI.
119+pub struct Vpx {
120+ vp8_dx: Dx,
121+ dec_init_ver: DecInitVer,
122+ decode: Decode,
123+ get_frame: GetFrame,
124+ destroy: Destroy,
125+ error: ErrorFn,
126+ // Never dropped (the struct lives in a static), so the pointers above
127+ // stay valid for the life of the process.
128+ _lib: Library,
129+}
130+
131+/// The library, loaded once per process. `None` -- no `libvpx.so` on this
132+/// machine, or one missing a symbol this module names -- is the one answer,
133+/// asked before any file is opened.
134+static VPX: LazyLock<Option<Vpx>> = LazyLock::new(load);
135+
136+/// The loaded library, or `None` on a machine without one this module can
137+/// use. Asked before any file is opened.
138+pub fn vpx() -> Option<&'static Vpx> {
139+ VPX.as_ref()
140+}
141+
142+fn load() -> Option<Vpx> {
143+ // The versioned soname first -- the name every distribution actually
144+ // ships -- then the unversioned development name for the odd link that
145+ // has it.
146+ for name in ["libvpx.so.9", "libvpx.so"] {
147+ let lib = match unsafe { Library::new(name) } {
148+ Ok(lib) => lib,
149+ Err(_) => continue,
150+ };
151+ // SAFETY: the symbols are type-checked against the declarations above;
152+ // a missing one unloads the library with the dropped closure and the
153+ // next candidate gets its turn.
154+ let vpx = unsafe {
155+ (|| {
156+ Some(Vpx {
157+ vp8_dx: *lib.get(b"vpx_codec_vp8_dx\0").ok()?,
158+ dec_init_ver: *lib.get(b"vpx_codec_dec_init_ver\0").ok()?,
159+ decode: *lib.get(b"vpx_codec_decode\0").ok()?,
160+ get_frame: *lib.get(b"vpx_codec_get_frame\0").ok()?,
161+ destroy: *lib.get(b"vpx_codec_destroy\0").ok()?,
162+ error: *lib.get(b"vpx_codec_error\0").ok()?,
163+ _lib: lib,
164+ })
165+ })()
166+ };
167+ if vpx.is_some() {
168+ return vpx;
169+ }
170+ }
171+ None
172+}
173+
174+impl Vpx {
175+ /// `vpx_codec_error`'s line about the context's last answer: what an init
176+ /// or decode refusal says instead of a bare `vpx_codec_err_t` number.
177+ fn last_error(&self, ctx: &VpxCtx) -> String {
178+ // SAFETY: `ctx` is a live libvpx context; the string it names is
179+ // static and read before anything else touches the context.
180+ let msg = unsafe { (self.error)(ctx) };
181+ if msg.is_null() {
182+ return "no description".to_string();
183+ }
184+ // SAFETY: non-null per the check above, NUL-terminated per libvpx.
185+ unsafe { CStr::from_ptr(msg) }.to_string_lossy().into_owned()
186+ }
187+
188+ /// The VP8 decoder interface, `vpx_codec_vp8_dx`: the argument every
189+ /// `dec_init_ver` on this context takes.
190+ fn iface(&self) -> *const c_void {
191+ // SAFETY: a pure lookup in libvpx's own tables.
192+ unsafe { (self.vp8_dx)() }
193+ }
194+
195+ /// `vpx_codec_dec_init_ver` with the ABI version this module was written
196+ /// against -- the check a mismatched libvpx fails rather than a call it
197+ /// misreads.
198+ pub(super) fn dec_init(&self, ctx: &mut VpxCtx) -> Result<(), String> {
199+ let cfg = VpxDecCfg {
200+ threads: threads(),
201+ w: 0,
202+ h: 0,
203+ };
204+ // SAFETY: the context is ours and live for the session; `cfg` is read
205+ // only during the call; the version pins the ABI.
206+ let rc = unsafe { (self.dec_init_ver)(ctx, self.iface(), &cfg, 0, VPX_DECODER_ABI_VERSION) };
207+ match rc {
208+ VPX_CODEC_OK => Ok(()),
209+ _ => Err(format!("libvpx init failed: {}", self.last_error(ctx))),
210+ }
211+ }
212+
213+ /// `vpx_codec_decode`: one access unit in. `VPX_DL_REALTIME` is the
214+ /// documented-but-ignored deadline.
215+ pub(super) fn decode(&self, ctx: &mut VpxCtx, au: &[u8]) -> Result<(), String> {
216+ // SAFETY: `au` outlives the call; the context is live and used from
217+ // the one thread the session lives on.
218+ let rc = unsafe {
219+ (self.decode)(
220+ ctx,
221+ au.as_ptr(),
222+ au.len() as c_uint,
223+ std::ptr::null_mut(),
224+ VPX_DL_REALTIME,
225+ )
226+ };
227+ match rc {
228+ VPX_CODEC_OK => Ok(()),
229+ _ => Err(format!("libvpx decode failed: {}", self.last_error(ctx))),
230+ }
231+ }
232+
233+ /// `vpx_codec_decode` with a null, empty frame: the end-of-stream signal
234+ /// that releases whatever the decoder held back.
235+ pub(super) fn flush(&self, ctx: &mut VpxCtx) -> Result<(), String> {
236+ // SAFETY: as `decode`, with the nulls libvpx reads as "no more data".
237+ let rc = unsafe {
238+ (self.decode)(ctx, std::ptr::null(), 0, std::ptr::null_mut(), VPX_DL_REALTIME)
239+ };
240+ match rc {
241+ VPX_CODEC_OK => Ok(()),
242+ _ => Err(format!("libvpx flush failed: {}", self.last_error(ctx))),
243+ }
244+ }
245+
246+ /// `vpx_codec_get_frame`: the next picture of the current iteration, or
247+ /// `None` when the iteration is done. The bytes belong to the decoder
248+ /// until the next `decode`/`flush`.
249+ pub(super) fn get_frame<'a>(
250+ &self,
251+ ctx: &'a mut VpxCtx,
252+ iter: &mut *const c_void,
253+ ) -> Option<&'a VpxImage> {
254+ // SAFETY: the context is live; the returned pointer is libvpx's own
255+ // image, borrowed for exactly as long as the lifetime above says.
256+ unsafe { (self.get_frame)(ctx, iter).as_ref() }
257+ }
258+
259+ /// `vpx_codec_destroy`: the context's half of `VpxSession`'s `Drop`.
260+ pub(super) fn destroy(&self, ctx: &mut VpxCtx) {
261+ // SAFETY: called once per live context; libvpx frees what the context
262+ // holds, and a context whose init never completed reads as an
263+ // `INVALID_PARAM` refusal rather than a crash.
264+ unsafe { (self.destroy)(ctx) };
265+ }
266+}
267+
268+/// VP8's row-based multithreaded decode stops paying past a handful of
269+/// threads -- the row sync costs what the parallelism buys -- so this is not
270+/// the machine's whole core count.
271+pub(super) fn threads() -> c_uint {
272+ std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as c_uint)
273+}
crates/engine/src/caps.rsmodified+27 -0
@@ -11,6 +11,11 @@
11 //! with the codecs the plugin implements. No plugin, an older plugin or no11 //! with the codecs the plugin implements. No plugin, an older plugin or no
12 //! driver all read the same way -- "software only" -- because that is what they12 //! driver all read the same way -- "software only" -- because that is what they
13 //! mean for the file a user is about to write.13 //! mean for the file a user is about to write.
14+//!
15+//! VP8 is deliberately on neither line: the plugin decodes it on libvpx,
16+//! dlopen'd at runtime, and reports `CAP_VP8` for it -- the plugin's seat,
17+//! never the GPU's. [`HW_CODECS`] does not carry the bit, because this file's
18+//! one job is not presenting a seat as a GPU feat that no GPU has.
14 19
15 use crate::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps};20 use crate::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps};
16 21
@@ -95,6 +100,7 @@ fn seats(decodes: bool, encodes: bool) -> &'static str {
95 #[cfg(test)]100 #[cfg(test)]
96 mod tests {101 mod tests {
97 use super::*;102 use super::*;
103+ use crate::hw::CAP_VP8;
98 104
99 #[test]105 #[test]
100 fn the_hardware_line_says_what_the_plugin_answered_and_nothing_more() {106 fn the_hardware_line_says_what_the_plugin_answered_and_nothing_more() {
@@ -128,6 +134,27 @@ mod tests {
128 assert_eq!(hw_line(Some(h264_only)), "H.264 dec");134 assert_eq!(hw_line(Some(h264_only)), "H.264 dec");
129 }135 }
130 136
137+ /// The plugin's VP8 bit is its own libvpx software decoder. However lit
138+ /// the mask is, the hardware line never reads it as a GPU seat -- and a
139+ /// mask holding nothing *but* it still reads as the nothing a driver
140+ /// without seats would answer.
141+ #[test]
142+ fn the_plugin_s_software_vp8_never_reads_as_a_gpu_seat() {
143+ let vpx_only = VhCaps {
144+ decode: CAP_VP8,
145+ ..Default::default()
146+ };
147+ assert!(hw_line(Some(vpx_only)).starts_with("none —"));
148+ let with_gpu = VhCaps {
149+ decode: CAP_H264 | CAP_VP8,
150+ encode: CAP_H264,
151+ ..Default::default()
152+ };
153+ assert_eq!(hw_line(Some(with_gpu)), "H.264 dec+enc");
154+ }
155+
156+ #[test]
157+
131 #[test]158 #[test]
132 fn the_software_line_names_every_encoder_this_build_carries() {159 fn the_software_line_names_every_encoder_this_build_carries() {
133 let line = software();160 let line = software();
crates/engine/src/colorspace.rsmodified+4 -3
@@ -373,9 +373,9 @@ impl Tags {
373 /// the demuxers already hold: the SPS VUI for H.264 and HEVC (Annex-B framed,373 /// the demuxers already hold: the SPS VUI for H.264 and HEVC (Annex-B framed,
374 /// which is how both demuxers keep them) and the sequence header OBU for AV1.374 /// which is how both demuxers keep them) and the sequence header OBU for AV1.
375 ///375 ///
376-/// Empty [`Tags`] for VP9, whose colour space lives in the uncompressed header376+/// Empty [`Tags`] for VP9 and VP8, which state no out-of-band colour in either
377-/// of every frame rather than out of band, and for anything malformed: this is377+/// container path, and for anything malformed: this is a middle tier, and the
378-/// a middle tier, and the tier below it always has an answer.378+/// tier below it always has an answer.
379 pub fn bitstream_tags(codec: Codec, sets: &[u8]) -> Tags {379 pub fn bitstream_tags(codec: Codec, sets: &[u8]) -> Tags {
380 match codec {380 match codec {
381 // 7 is an H.264 SPS, 33 an HEVC one (whose NAL header is two bytes and381 // 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 {
391 .unwrap_or_default(),391 .unwrap_or_default(),
392 Codec::Av1 => av1_sequence_header(sets),392 Codec::Av1 => av1_sequence_header(sets),
393 Codec::Vp9 => Tags::default(),393 Codec::Vp9 => Tags::default(),
394+ Codec::Vp8 => Tags::default(),
394 }395 }
395 }396 }
396 397
crates/engine/src/decode.rsmodified+3 -3
@@ -625,7 +625,7 @@ impl DecodeSession {
625 ) -> crate::Result<(VideoMeta, FrameStream)> {625 ) -> crate::Result<(VideoMeta, FrameStream)> {
626 let path = path.as_ref().to_path_buf();626 let path = path.as_ref().to_path_buf();
627 let (meta, demuxer) = Demuxer::open(&path)?;627 let (meta, demuxer) = Demuxer::open(&path)?;
628- // No software HEVC or VP9 decoder exists, so such a file the plugin will628+ // No software HEVC, VP9 or VP8 decoder exists, so such a file the plugin will
629 // not take is refused *here*, where the caller still has somewhere to629 // not take is refused *here*, where the caller still has somewhere to
630 // show it -- a worker that opened and then produced nothing is a black630 // show it -- a worker that opened and then produced nothing is a black
631 // screen with no explanation. The probe session is opened, made to631 // screen with no explanation. The probe session is opened, made to
@@ -1005,8 +1005,8 @@ fn run_span(
1005 opened.hw = None;1005 opened.hw = None;
1006 eprintln!("hardware decode failed before any frame, falling back to software");1006 eprintln!("hardware decode failed before any frame, falling back to software");
1007 }1007 }
1008- // ...except where there is nothing to fall back to. Feeding HEVC or VP91008+ // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or
1009- // bytes to `rusty_h264` would be garbage, not a fallback.1009+ // VP8 bytes to `rusty_h264` would be garbage, not a fallback.
1010 if opened.meta.codec != Codec::H264 {1010 if opened.meta.codec != Codec::H264 {
1011 eprintln!("{}", opened.meta.codec.needs_plugin());1011 eprintln!("{}", opened.meta.codec.needs_plugin());
1012 return;1012 return;
crates/engine/src/demux.rsmodified+43 -25
@@ -111,13 +111,15 @@ pub fn cancelled_read_error() -> crate::Error {
111 }111 }
112 112
113 /// What the video track is coded with. Not a decoder choice by itself: only113 /// What the video track is coded with. Not a decoder choice by itself: only
114-/// H.264 has a software decoder here, which is what [`Codec::needs_plugin`]114+/// H.264 has a software decoder in this binary, and VP8's (libvpx) lives
115-/// says for the others.115+/// inside the plugin -- which is what [`Codec::needs_plugin`] says for the
116+/// rest, per codec, in the words that stay true.
116 #[derive(Debug, Clone, Copy, PartialEq, Eq)]117 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
117 pub enum Codec {118 pub enum Codec {
118 H264,119 H264,
119 Hevc,120 Hevc,
120 Vp9,121 Vp9,
122+ Vp8,
121 Av1,123 Av1,
122 }124 }
123 125
@@ -128,19 +130,30 @@ impl Codec {
128 Self::H264 => "H.264",130 Self::H264 => "H.264",
129 Self::Hevc => "HEVC",131 Self::Hevc => "HEVC",
130 Self::Vp9 => "VP9",132 Self::Vp9 => "VP9",
133+ Self::Vp8 => "VP8",
131 Self::Av1 => "AV1",134 Self::Av1 => "AV1",
132 }135 }
133 }136 }
134 137
135- /// Why a file can be refused outright: `rusty_h264` is the only software138+ /// Why a file can be refused outright. Two true answers, one per shape of
136- /// decoder in the project and there is no pure-Rust HEVC or VP9 one to fall139+ /// "no decoder here": every codec but H.264 and VP8 has no software
137- /// back to, so without the plugin there is nothing to decode with. Shared140+ /// decoder at all, so the refusal names the plugin as the only way; VP8's
138- /// so playback and export refuse in the same words.141+ /// software decoder *is* libvpx inside the plugin, so "there is no
142+ /// software decoder" would be a lie the day the plugin grew that arm --
143+ /// the refusal keeps naming the plugin, because that is still the thing
144+ /// to make present. Shared so playback and export refuse in the same
145+ /// words.
139 pub fn needs_plugin(self) -> String {146 pub fn needs_plugin(self) -> String {
140- format!(147+ match self {
141- "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder",148+ Self::Vp8 => {
142- name = self.name()149+ "VP8 needs the VA-API plugin (libengine_hw.so) — its decoder is libvpx, inside the plugin"
143- )150+ .to_string()
151+ }
152+ other => format!(
153+ "{name} needs the VA-API plugin (libengine_hw.so) — there is no software {name} decoder",
154+ name = other.name()
155+ ),
156+ }
144 }157 }
145 158
146 /// The other refusal: the plugin *is* here and opened the file, and then159 /// The other refusal: the plugin *is* here and opened the file, and then
@@ -168,6 +181,7 @@ const CODEC_IDS: &[(Codec, &str, &[u8; 4])] = &[
168 (Codec::H264, "V_MPEG4/ISO/AVC", b"avc1"),181 (Codec::H264, "V_MPEG4/ISO/AVC", b"avc1"),
169 (Codec::Hevc, "V_MPEGH/ISO/HEVC", b"hvc1"),182 (Codec::Hevc, "V_MPEGH/ISO/HEVC", b"hvc1"),
170 (Codec::Vp9, "V_VP9", b"vp09"),183 (Codec::Vp9, "V_VP9", b"vp09"),
184+ (Codec::Vp8, "V_VP8", b"vp08"),
171 (Codec::Av1, "V_AV1", b"av01"),185 (Codec::Av1, "V_AV1", b"av01"),
172 ];186 ];
173 187
@@ -182,8 +196,6 @@ const UNSUPPORTED: &[(&str, &str)] = &[
182 // carries them in-band only; `mp4 0.14` parses no `avc3` sample entry at all196 // carries them in-band only; `mp4 0.14` parses no `avc3` sample entry at all
183 // either, so `sequence_parameter_set()` would come back empty-handed.197 // either, so `sequence_parameter_set()` would come back empty-handed.
184 ("avc3", "H.264 with parameter sets in-band only"),198 ("avc3", "H.264 with parameter sets in-band only"),
185- ("vp08", "no VP8 decoder: cros-codecs carries none"),
186- ("V_VP8", "no VP8 decoder: cros-codecs carries none"),
187 ("V_MPEG2", "no MPEG-2 decoder, hardware or software"),199 ("V_MPEG2", "no MPEG-2 decoder, hardware or software"),
188 (200 (
189 "V_MS/VFW/FOURCC",201 "V_MS/VFW/FOURCC",
@@ -764,8 +776,8 @@ impl Mp4Demuxer {
764 parameter_sets = sets;776 parameter_sets = sets;
765 bit_depth = depth;777 bit_depth = depth;
766 }778 }
767- // No parameter sets: a VP9 sample is self-contained.779+ // No parameter sets: a VP8 or VP9 sample is self-contained.
768- Codec::Vp9 => {}780+ Codec::Vp8 | Codec::Vp9 => {}
769 }781 }
770 let sync_samples = track782 let sync_samples = track
771 .trak783 .trak
@@ -841,9 +853,9 @@ impl Mp4Demuxer {
841 let Some(sample) = sample else {853 let Some(sample) = sample else {
842 return Ok(None);854 return Ok(None);
843 };855 };
844- // A VP9 mp4 sample is one (super)frame the decoder parses on its own:856+ // A VP8 or VP9 mp4 sample is one (super)frame the decoder parses on
845- // no length prefixes to strip, no parameter sets to re-inject.857+ // its own: no length prefixes to strip, no parameter sets to re-inject.
846- if self.codec == Codec::Vp9 {858+ if matches!(self.codec, Codec::Vp8 | Codec::Vp9) {
847 return Ok(Some(sample.bytes.to_vec()));859 return Ok(Some(sample.bytes.to_vec()));
848 }860 }
849 // An AV1 one is a whole temporal unit, likewise unframed -- with the861 // An AV1 one is a whole temporal unit, likewise unframed -- with the
@@ -1059,7 +1071,7 @@ impl MkvDemuxer {
1059 format!("{codec} video in a Matroska file is not supported — {why}")1071 format!("{codec} video in a Matroska file is not supported — {why}")
1060 }1072 }
1061 None => format!(1073 None => format!(
1062- "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264 and VP9 are"1074+ "{codec} video in a Matroska file is not supported — AV1, HEVC, H.264, VP9 and VP8 are"
1063 ),1075 ),
1064 }1076 }
1065 .into(),1077 .into(),
@@ -1418,9 +1430,9 @@ impl MkvDemuxer {
1418 }1430 }
1419 1431
1420 /// Next access unit in decode order: the block verbatim for AV1, which is1432 /// Next access unit in decode order: the block verbatim for AV1, which is
1421- /// one temporal unit already, and for VP9, whose block is one (super)frame;1433+ /// one temporal unit already, and for VP8 and VP9, whose blocks are one
1422- /// Annex-B for HEVC and H.264, whose blocks hold the same length-prefixed1434+ /// (super)frame each; Annex-B for HEVC and H.264, whose blocks hold the
1423- /// NALs an mp4 sample does.1435+ /// same length-prefixed NALs an mp4 sample does.
1424 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {1436 fn next_access_unit(&mut self) -> crate::Result<Option<Vec<u8>>> {
1425 // Reading off the end of the window is not the end of the track: it is1437 // Reading off the end of the window is not the end of the track: it is
1426 // the next cluster, not yet walked. The end of the track is the end of1438 // the next cluster, not yet walked. The end of the track is the end of
@@ -1449,7 +1461,7 @@ impl MkvDemuxer {
1449 // the bytes as a codec's: a stripped block is not a NAL and an inflated1461 // the bytes as a codec's: a stripped block is not a NAL and an inflated
1450 // one is not where it was read from.1462 // one is not where it was read from.
1451 unpack.frame(scratch)?;1463 unpack.frame(scratch)?;
1452- if matches!(self.codec, Codec::Av1 | Codec::Vp9) {1464+ if matches!(self.codec, Codec::Av1 | Codec::Vp8 | Codec::Vp9) {
1453 let mut au = Vec::with_capacity(head + self.scratch.len());1465 let mut au = Vec::with_capacity(head + self.scratch.len());
1454 au.extend_from_slice(&self.config[..head]);1466 au.extend_from_slice(&self.config[..head]);
1455 au.extend_from_slice(&self.scratch);1467 au.extend_from_slice(&self.scratch);
@@ -2377,6 +2389,12 @@ fn mkv_track_entry(
2377 // the container either, so it is read off the first keyframe by2389 // the container either, so it is read off the first keyframe by
2378 // [`Demuxer::fill_vp9_depth`]; 8 here is what that probe starts from.2390 // [`Demuxer::fill_vp9_depth`]; 8 here is what that probe starts from.
2379 Codec::Vp9 => (Codec::Vp9, 0, Vec::new(), 8),2391 Codec::Vp9 => (Codec::Vp9, 0, Vec::new(), 8),
2392+ // A VP8 block is one self-contained frame, exactly as a VP9 one: no
2393+ // length prefixes to strip, no configuration record to re-inject -- a
2394+ // `.webm` writes no `CodecPrivate` for it, and the `vp08` an mp4
2395+ // carries no record beside. 8 is not an assumption here but the
2396+ // format itself: VP8 has no depth but 8.
2397+ Codec::Vp8 => (Codec::Vp8, 0, Vec::new(), 8),
2380 };2398 };
2381 Ok(MkvEntry::Video(MkvVideo {2399 Ok(MkvEntry::Video(MkvVideo {
2382 number,2400 number,
@@ -2492,7 +2510,7 @@ fn mp4_no_video<R>(path: &Path, reader: &Mp4Reader<R>) -> crate::Error {
2492 Some(kind) => match UNSUPPORTED.iter().find(|(id, _)| *id == kind) {2510 Some(kind) => match UNSUPPORTED.iter().find(|(id, _)| *id == kind) {
2493 Some((_, why)) => format!("{kind} video in this mp4 is not supported — {why}"),2511 Some((_, why)) => format!("{kind} video in this mp4 is not supported — {why}"),
2494 None => {2512 None => {
2495- format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9 and AV1 are")2513+ format!("{kind} video in this mp4 is not supported — H.264, HEVC, VP9, AV1 and VP8 are")
2496 }2514 }
2497 }2515 }
2498 .into(),2516 .into(),
@@ -2500,7 +2518,7 @@ fn mp4_no_video<R>(path: &Path, reader: &Mp4Reader<R>) -> crate::Error {
2500 // which is a thing a person really does hand an editor. The Matroska2518 // which is a thing a person really does hand an editor. The Matroska
2501 // door's own answer, and the same type for the same reason.2519 // door's own answer, and the same type for the same reason.
2502 None => crate::Error::from(NoVideoTrack(2520 None => crate::Error::from(NoVideoTrack(
2503- "no H.264, HEVC, VP9 or AV1 video track in file".to_string(),2521+ "no H.264, HEVC, VP9, AV1 or VP8 video track in file".to_string(),
2504 )),2522 )),
2505 }2523 }
2506 }2524 }
@@ -4679,7 +4697,7 @@ mod tests {
4679 /// compile until it has been routed.4697 /// compile until it has been routed.
4680 #[test]4698 #[test]
4681 fn every_codec_is_reachable_from_both_containers() {4699 fn every_codec_is_reachable_from_both_containers() {
4682- for codec in [Codec::H264, Codec::Hevc, Codec::Vp9, Codec::Av1] {4700+ for codec in [Codec::H264, Codec::Hevc, Codec::Vp9, Codec::Vp8, Codec::Av1] {
4683 let row = CODEC_IDS4701 let row = CODEC_IDS
4684 .iter()4702 .iter()
4685 .find(|(c, ..)| *c == codec)4703 .find(|(c, ..)| *c == codec)
crates/engine/src/export.rsmodified+2 -2
@@ -157,8 +157,8 @@ const HEVC_QP_MAX: i32 = 40;
157 /// still has none -- `oxideav-opus` encodes CELT alone, which is half a codec.157 /// still has none -- `oxideav-opus` encodes CELT alone, which is half a codec.
158 /// (AAC has one too -- `rusty_aac`, which is what a re-encoded video track's158 /// (AAC has one too -- `rusty_aac`, which is what a re-encoded video track's
159 /// sound leaves through -- but AAC is a container's own audio, never a file of159 /// sound leaves through -- but AAC is a container's own audio, never a file of
160-/// its own here.) VP9 is the160+/// its own here.) VP9 and VP8 are the
161-/// one codec left that comes in through the plugin and stops there, HEVC having161+/// codecs that come in through the plugin and stop there, HEVC having
162 /// gained an encoder (an intra-only one, which the rows say). A front-end says162 /// gained an encoder (an intra-only one, which the rows say). A front-end says
163 /// so rather than hiding the row.163 /// so rather than hiding the row.
164 ///164 ///
crates/engine/src/hw.rsmodified+14 -1
@@ -155,7 +155,7 @@ impl Drop for DmaFrame {
155 }155 }
156 156
157 /// What *this machine* takes, as far as the plugin implements it: one bit per157 /// What *this machine* takes, as far as the plugin implements it: one bit per
158-/// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads158+/// codec ([`CAP_H264`] and its four neighbours) in each mask, so a caller reads
159 /// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s.159 /// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s.
160 ///160 ///
161 /// The intersection is the plugin's to compute, never the driver's alone: a GPU161 /// 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;
178 pub const CAP_VP9: u32 = 1 << 2;178 pub const CAP_VP9: u32 = 1 << 2;
179 pub const CAP_AV1: u32 = 1 << 3;179 pub const CAP_AV1: u32 = 1 << 3;
180 180
181+/// VP8 decodes on libvpx inside the plugin -- software, dlopen'd at runtime,
182+/// no GPU and no VA-API profile anywhere in it -- so this bit is the
183+/// *plugin's* seat, never the driver's. It lights up [`VhCaps::decode`] when
184+/// the library is present; the hardware line in [`crate::caps`] deliberately
185+/// keeps it off, being a line about what the GPU takes.
186+pub const CAP_VP8: u32 = 1 << 4;
187+
181 struct Plugin {188 struct Plugin {
182 open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,189 open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,
183 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,190 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,
@@ -255,6 +262,12 @@ fn load() -> Option<Plugin> {
255 /// decodes), no driver, a driver that refuses the query -- and a caller says262 /// decodes), no driver, a driver that refuses the query -- and a caller says
256 /// "software only" for all of them, which is what they mean.263 /// "software only" for all of them, which is what they mean.
257 ///264 ///
265+/// VP8 sits outside that reading on a driverless machine: its decoder is
266+/// libvpx inside the plugin, so the plugin may open a VP8 file where this
267+/// table answers `None`. Nothing here promises otherwise -- the decode path
268+/// asks the plugin, not this table -- and the one display-dependent half the
269+/// front-end draws from this stays exactly as truthful as it was.
270+///
258 /// Costs one VA-API init (~90 ms) the first time: ask it off a render thread.271 /// Costs one VA-API init (~90 ms) the first time: ask it off a render thread.
259 pub fn caps() -> Option<VhCaps> {272 pub fn caps() -> Option<VhCaps> {
260 static CAPS: OnceLock<Option<VhCaps>> = OnceLock::new();273 static CAPS: OnceLock<Option<VhCaps>> = OnceLock::new();
crates/engine/src/playback.rsmodified+6 -5
@@ -3964,11 +3964,12 @@ fn matches_timeline(
3964 ) -> crate::Result<Rate> {3964 ) -> crate::Result<Rate> {
3965 // The codec is *not* held to the timeline's -- every clip opens its own3965 // The codec is *not* held to the timeline's -- every clip opens its own
3966 // decoder, so an H.264 take and an HEVC one play on one timeline. What the3966 // decoder, so an H.264 take and an HEVC one play on one timeline. What the
3967- // codec gate was really protecting against stays, in the one place that can3967+ // codec gate was really protecting against stays, in the one place that
3968- // actually answer it: on a machine without the VA-API plugin an HEVC or VP93968+ // can actually answer it: on a machine without the VA-API plugin an HEVC,
3969- // clip would be black frames with the refusal on stderr alone, so the file3969+ // VP9 or VP8 clip would be black frames with the refusal on stderr alone,
3970- // is asked for a decoder *here*, at the door, where the `Err` is still3970+ // so the file is asked for a decoder *here*, at the door, where the `Err`
3971- // something a front-end can show. A zero-length range probes and starts no3971+ // is still something a front-end can show. A zero-length range probes and
3972+ // starts no
3972 // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]3973 // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]
3973 // only enters VA-API off that path.3974 // only enters VA-API off that path.
3974 DecodeSession::open_worker(3975 DecodeSession::open_worker(
crates/engine/tests/capability_matrix.rsmodified+1 -0
@@ -28,6 +28,7 @@ const MATRIX: &[(Codec, &str, &str)] = &[
28 (Codec::H264, "test_baseline.mp4", "test_h264.mkv"),28 (Codec::H264, "test_baseline.mp4", "test_h264.mkv"),
29 (Codec::Hevc, "test_hevc.mp4", "test_hevc.mkv"),29 (Codec::Hevc, "test_hevc.mp4", "test_hevc.mkv"),
30 (Codec::Vp9, "test_vp9.mp4", "test_vp9.webm"),30 (Codec::Vp9, "test_vp9.mp4", "test_vp9.webm"),
31+ (Codec::Vp8, "test_vp8.mp4", "test_vp8.webm"),
31 // `mp4 0.14` writes no `av01` sample entry, so there is no AV1 mp4 fixture32 // `mp4 0.14` writes no `av01` sample entry, so there is no AV1 mp4 fixture
32 // to open; the mp4 half of that row is `av01`'s presence in the dispatch33 // to open; the mp4 half of that row is `av01`'s presence in the dispatch
33 // table, which `demux::tests` holds.34 // table, which `demux::tests` holds.
crates/engine/tests/vp8.rsadded+143 -0
@@ -0,0 +1,143 @@
1+//! VP8 import: the container half, and the decode half -- software, on the
2+//! libvpx the plugin dlopens (`engine-hw`'s `vpx.rs`), which is why these
3+//! twins need a built `libengine_hw.so` and a `libvpx.so` but **no VA-API
4+//! VP8 profile**: no such profile exists on this GPU, and none is asked for.
5+//!
6+//! ```text
7+//! cargo build -p engine -p engine-hw --release
8+//! LD_LIBRARY_PATH=target/release \
9+//! cargo test -p engine --release --test vp8 -- --include-ignored --nocapture --test-threads=1
10+//! ```
11+//!
12+//! `VE_SW` is process-wide, hence `--test-threads=1`: the refusal test sets it
13+//! and puts it back.
14+use std::path::PathBuf;
15+use std::time::{Duration, Instant};
16+
17+use engine::demux::{Codec, Demuxer};
18+use engine::export::ExportSettings;
19+use engine::scratch::Scratch;
20+use engine::{AudioSession, DecodeSession, PlaybackSession, Project};
21+
22+/// 1280x720@30, 2 s -- see `scripts/gen_fixtures.sh`.
23+const FRAMES: u32 = 60;
24+
25+fn asset(name: &str) -> PathBuf {
26+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
27+ .join("../../assets")
28+ .join(name)
29+}
30+
31+/// The container half: a vp08 track is found and named as VP8 out of the mp4,
32+/// its `V_VP8` twin out of the `.webm`, and the AAC track is read exactly as
33+/// any other file's -- the audio path knows nothing about the video codec.
34+#[test]
35+fn the_demuxer_reports_a_vp8_track() {
36+ let (meta, _) = Demuxer::open(&asset("test_vp8.mp4")).expect("open test_vp8.mp4");
37+ assert_eq!(meta.codec, Codec::Vp8);
38+ assert_eq!((meta.width, meta.height), (1280, 720));
39+ assert!((meta.frame_rate - 30.0).abs() < 0.01, "{}", meta.frame_rate);
40+ assert_eq!(meta.frame_count, FRAMES);
41+
42+ let (webm, _) = Demuxer::open(&asset("test_vp8.webm")).expect("open test_vp8.webm");
43+ assert_eq!(webm.codec, Codec::Vp8);
44+
45+ let probe = AudioSession::probe(asset("test_vp8.mp4"), 0)
46+ .expect("probe")
47+ .expect("the fixture has an AAC track");
48+ assert_eq!(
49+ (probe.sample_rate, probe.channels),
50+ (44_100, 2),
51+ "audio is read the same whatever the picture is coded with"
52+ );
53+}
54+
55+/// There is no software VP8 decoder *in this binary*, so the software path
56+/// must refuse by name rather than feed VP8 bytes to `rusty_h264` -- and it
57+/// must refuse where a caller can still show it, i.e. out of `open`, not from
58+/// inside the worker. The decoder the refusal names is the plugin's libvpx
59+/// arm, which is why the sentence names the plugin and not a nonexistent
60+/// absence.
61+#[test]
62+fn the_software_path_refuses_vp8_by_name() {
63+ // SAFETY: the suite is documented to run with --test-threads=1.
64+ unsafe { std::env::set_var("VE_SW", "1") };
65+ let refused =
66+ DecodeSession::open(asset("test_vp8.mp4")).expect_err("software must not accept VP8");
67+ let refused = refused.to_string();
68+ // Restored immediately: the hardware tests in this binary share the process.
69+ unsafe { std::env::remove_var("VE_SW") };
70+
71+ assert!(refused.contains("VP8"), "{refused}");
72+ assert!(refused.contains("plugin"), "{refused}");
73+}
74+
75+/// The end-to-end user path: opening the file yields pictures, all of them,
76+/// through the plugin's libvpx arm. The `.webm` is the file this decodes,
77+/// the container half being the Matroska demuxer's `V_VP8` row.
78+#[test]
79+#[ignore = "needs a built libengine_hw.so and libvpx.so.9 -- no VA-API profile involved"]
80+fn the_plugin_decodes_every_vp8_frame() {
81+ let start = Instant::now();
82+ let (meta, frames) = DecodeSession::open(asset("test_vp8.webm")).expect("open test_vp8.webm");
83+ assert_eq!(meta.codec, Codec::Vp8);
84+ let frames: Vec<_> = frames.into_iter().collect();
85+ eprintln!(
86+ "test_vp8.webm: {} frames in {:?} ({:.1} fps)",
87+ frames.len(),
88+ start.elapsed(),
89+ frames.len() as f64 / start.elapsed().as_secs_f64().max(1e-9)
90+ );
91+
92+ assert_eq!(frames.len() as u32, FRAMES, "every sample decoded");
93+ for (i, frame) in frames.iter().enumerate() {
94+ assert_eq!((frame.width, frame.height), (1280, 720), "frame {i} dims");
95+ assert_eq!(frame.index, i as u32, "frames arrive in display order");
96+ assert_eq!(frame.bgra.len(), 1280 * 720 * 4, "frame {i} size");
97+ }
98+ // A picture, not a flat surface: a decoder handing back an untouched
99+ // buffer would satisfy every count above.
100+ let first = &frames[0].bgra;
101+ assert!(
102+ first.chunks_exact(4).any(|px| px != &first[..4]),
103+ "frame 0 is a single colour -- no picture was decoded"
104+ );
105+ // ...and a moving one, not one still: the fixture is a rendered clip, so
106+ // frame 30 disagrees with frame 0 however the two are sampled.
107+ let thumb = |f: &engine::Frame| -> Vec<u8> {
108+ (0..f.bgra.len()).step_by(6173).map(|i| f.bgra[i]).collect()
109+ };
110+ assert_ne!(
111+ thumb(&frames[0]),
112+ thumb(&frames[FRAMES as usize / 2]),
113+ "every frame identical -- nothing moved"
114+ );
115+}
116+
117+/// Export re-encodes to H.264 whatever the source was coded with: the packet
118+/// copy path is audio-only, so no VP8 byte can reach an `avc1` track.
119+#[test]
120+#[ignore = "needs a built libengine_hw.so and libvpx.so.9 -- no VA-API profile involved"]
121+fn a_vp8_source_exports_as_h264() {
122+ let session = PlaybackSession::open(asset("test_vp8.webm")).expect("open test_vp8.webm");
123+ let meta = *session.meta();
124+ let project = Project::single(asset("test_vp8.webm"), meta.frame_count);
125+ let out = Scratch::file("ve_export_vp8", "mp4");
126+
127+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default(), None);
128+ let started = Instant::now();
129+ while !handle.is_finished() {
130+ assert!(started.elapsed() < Duration::from_secs(120), "export hung");
131+ std::thread::sleep(Duration::from_millis(20));
132+ }
133+ handle.result().expect("outcome").expect("export");
134+
135+ let (written, _) = Demuxer::open(&out).expect("reopen the export");
136+ assert_eq!(written.codec, Codec::H264, "exports are always H.264");
137+ // The fixture's own length and rate, back again: 60 pictures at 30 fps,
138+ // which is the 2 s the source played.
139+ assert_eq!(written.frame_count, FRAMES, "every timeline frame written");
140+ assert!((written.frame_rate - 30.0).abs() < 0.01, "{}", written.frame_rate);
141+ assert_eq!((written.width, written.height), (1280, 720));
142+ let _ = std::fs::remove_file(&out);
143+}
scripts/gen_fixtures.shmodified+119 -0
@@ -98,6 +98,125 @@ ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
98 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \98 ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
99 -c:v libvpx-vp9 -b:v 2M -g 30 -profile:v 2 -pix_fmt yuv420p10le \99 -c:v libvpx-vp9 -b:v 2M -g 30 -profile:v 2 -pix_fmt yuv420p10le \
100 -an assets/test_vp9_10.webm100 -an assets/test_vp9_10.webm
101+# VP8 fixture pair, the twins of the VP9 ones. ffmpeg's mov muxer carries no
102+# VP8 tag for mp4 at all (and its VP9 path re-parses the frames it is handed,
103+# dropping them), so the mp4 half is assembled by hand: the picture is encoded
104+# to an IVF, the AAC sound to an mp4 of its own, and the video track is
105+# spliced in with the `vp08` sample entry written out byte for byte -- the
106+# very entry `demux::sample_entry` reads by hand, which is what this fixture
107+# exists to exercise. `-enc_time_base 1/30` keeps the IVF timestamps exact,
108+# which is what the mp4 stts and the 30 fps the tests assert come from.
109+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
110+ -c:v libvpx -b:v 2M -g 30 -enc_time_base 1/30 -pix_fmt yuv420p -an \
111+ assets/.test_vp8.ivf
112+ffmpeg -y -f lavfi -i "sine=frequency=440:duration=2" \
113+ -f lavfi -i "sine=frequency=880:duration=2" \
114+ -filter_complex "[0:a][1:a]join=inputs=2:channel_layout=stereo,volume='0.5+0.5*sin(2*PI*t)':eval=frame[a]" \
115+ -map "[a]" -c:a aac -b:a 128k assets/.test_vp8_audio.mp4
116+python3 - <<'SPLICE'
117+import struct
118+
119+def boxes(buf, start, end):
120+ res, at = [], start
121+ while at + 8 <= end:
122+ size = int.from_bytes(buf[at:at + 4], 'big')
123+ hdr = 8
124+ if size == 1:
125+ size = int.from_bytes(buf[at + 8:at + 16], 'big')
126+ hdr = 16
127+ if size == 0:
128+ size = end - at
129+ res.append((bytes(buf[at + 4:at + 8]), at, at + size, at + hdr))
130+ at += size
131+ return res
132+
133+def box(typ, payload):
134+ return struct.pack('>I', 8 + len(payload)) + typ + payload
135+
136+def full(typ, ver_flags, payload):
137+ return box(typ, struct.pack('>I', ver_flags) + payload)
138+
139+ivf = open('assets/.test_vp8.ivf', 'rb').read()
140+assert ivf[:4] == b'DKIF'
141+frames, at = [], 32
142+while at + 12 <= len(ivf):
143+ (n,) = struct.unpack_from('<I', ivf, at)
144+ frames.append(ivf[at + 12:at + 12 + n])
145+ at += 12 + n
146+assert len(frames) == 60, len(frames)
147+video = b''.join(frames)
148+
149+data = bytearray(open('assets/.test_vp8_audio.mp4', 'rb').read())
150+top = boxes(data, 0, len(data))
151+mdat = next(b for b in top if b[0] == b'mdat')
152+moov = next(b for b in top if b[0] == b'moov')
153+mvhd = next(b for b in boxes(data, moov[3], moov[2]) if b[0] == b'mvhd')
154+assert data[mvhd[3]] == 0
155+movie_ts = int.from_bytes(data[mvhd[3] + 12:mvhd[3] + 16], 'big')
156+next_id = int.from_bytes(data[mvhd[3] + 96:mvhd[3] + 100], 'big')
157+TIMESCALE, DELTA = 15360, 512 # exact 30 fps
158+vid_dur = len(frames) * DELTA
159+movie_dur = vid_dur * movie_ts // TIMESCALE
160+old_dur = int.from_bytes(data[mvhd[3] + 16:mvhd[3] + 20], 'big')
161+assert movie_dur >= old_dur, 'video shorter than audio'
162+splice_at = moov[1] # the video bytes go in right here, inside mdat
163+
164+UNITY = struct.pack('>9I', 0x10000, 0, 0, 0, 0x10000, 0, 0, 0, 0x40000000)
165+entry = box(b'vp08',
166+ b'\0' * 6 + struct.pack('>H', 1) # resv, data ref index
167+ + struct.pack('>HHI', 0, 0, 0) # pre_def, resv, pre_def
168+ + struct.pack('>HH', 1280, 720) # width, height
169+ + struct.pack('>II', 0x480000, 0x480000) # 72 dpi resolutions
170+ + b'\0' * 12 + struct.pack('>H', 1) # resv, frame_count
171+ + b'\0' * 32 # compressorname
172+ + struct.pack('>HH', 0x18, 0xFFFF)) # depth, pre_defined
173+assert len(entry) == 86
174+stco = bytearray(full(b'stco', 0, struct.pack('>II', 1, splice_at)))
175+tkhd = full(b'tkhd', 3,
176+ struct.pack('>IIIII', 0, 0, next_id, 0, movie_dur)
177+ + b'\0' * 8 + struct.pack('>HHHH', 0, 0, 0, 0) + UNITY
178+ + struct.pack('>II', 1280 << 16, 720 << 16))
179+mdhd = full(b'mdhd', 0,
180+ struct.pack('>IIII', 0, 0, TIMESCALE, vid_dur)
181+ + struct.pack('>HH', 0x55C4, 0)) # language und
182+hdlr = full(b'hdlr', 0, struct.pack('>I', 0) + b'vide' + b'\0' * 12 + b'\0')
183+minf = box(b'minf',
184+ full(b'vmhd', 1, struct.pack('>HHHH', 0, 0, 0, 0))
185+ + box(b'dinf', box(b'dref',
186+ struct.pack('>II', 0, 1) + full(b'url ', 1, b'')))
187+ + box(b'stbl',
188+ full(b'stsd', 0, struct.pack('>I', 1) + entry)
189+ + full(b'stts', 0, struct.pack('>III', 1, len(frames), DELTA))
190+ + full(b'stsc', 0, struct.pack('>IIII', 1, 1, len(frames), 1))
191+ + full(b'stsz', 0, struct.pack('>II', 0, len(frames))
192+ + b''.join(struct.pack('>I', len(f)) for f in frames))
193+ + bytes(stco)))
194+mdia = box(b'mdia', mdhd + full(b'hdlr', 0,
195+ struct.pack('>I', 0) + b'vide' + b'\0' * 12 + b'\0')
196+ + minf)
197+trak = box(b'trak', tkhd + mdia)
198+
199+new = bytearray(data[:moov[1]])
200+new += video
201+struct.pack_into('>I', new, mdat[1], (mdat[2] - mdat[1]) + len(video))
202+moov_new = bytearray(data[moov[1]:moov[2]])
203+m = next(b for b in boxes(moov_new, 8, len(moov_new)) if b[0] == b'mvhd')
204+struct.pack_into('>I', moov_new, m[3] + 16, max(old_dur, movie_dur))
205+struct.pack_into('>I', moov_new, m[3] + 96, next_id + 1)
206+moov_new += trak
207+struct.pack_into('>I', moov_new, 0, len(moov_new))
208+open('assets/test_vp8.mp4', 'wb').write(bytes(new + moov_new + data[moov[2]:]))
209+SPLICE
210+rm -f assets/.test_vp8.ivf assets/.test_vp8_audio.mp4
211+# ...and the Matroska twin, the recipe of test_vp9.webm with libvpx rather
212+# than libvpx-vp9 for the picture and the same Opus sound a `.webm` carries.
213+# The engine reads `V_VP8` since the demux dispatch learned it; the decode
214+# half is the plugin's (there is no software VP8 decoder here), so both files
215+# are container and refusal fixtures.
216+ffmpeg -y -f lavfi -i testsrc2=size=1280x720:rate=30:duration=2 \
217+ -f lavfi -i "sine=frequency=440:duration=2" \
218+ -c:v libvpx -b:v 2M -g 30 -pix_fmt yuv420p \
219+ -c:a libopus -b:a 96k assets/test_vp8.webm
101 # One Matroska file per audio codec the refusal string in `audio.rs` claims is220 # One Matroska file per audio codec the refusal string in `audio.rs` claims is
102 # decodable, as five tracks of one file: FLAC, MP3, Vorbis, ALAC and PCM. The221 # decodable, as five tracks of one file: FLAC, MP3, Vorbis, ALAC and PCM. The
103 # string said "AAC and AC-3 only" long after every one of these decoded, which is222 # string said "AAC and AC-3 only" long after every one of these decoded, which is