diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index d4e4425..e8b5453 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -10,11 +10,13 @@ //! reach whatever the panic strategy is: Mesa runs its own C worker threads and //! calls libc `abort()` from them when the video ring resets (measured //! 2026-08-13, `vcn_unified_0`, mesa 26.1.6). No `catch_unwind` can see a -//! foreign thread's `abort`. So the *encode* half of this plugin is no longer -//! loaded by the editor at all: it is `dlopen`ed by the `hw-encode-child` -//! helper, one process per session, and a driver that aborts now costs an export -//! its seat rather than costing a person their session -//! ([`engine::hwproc`](../engine/hwproc/index.html)). +//! foreign thread's `abort`. So no *encode* entry point of this plugin is +//! called in the editor's process any more: the editor still `dlopen`s the +//! library to see whether the `vh_enc_*` symbols are there at all, which opens +//! no VA-API display and starts no driver thread, and every call through them is +//! made by the `hw-encode-child` helper, one process per session. A driver that +//! aborts now costs an export its seat rather than costing a person their +//! session ([`engine::hwproc`](../engine/hwproc/index.html)). //! //! corner-cut: *decode* is still in the editor's own address space, where the //! same abort would still be fatal -- and the same ring hangs it (mmhub page diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 352d6f3..3d5e7d2 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -609,14 +609,7 @@ fn audio_kbps_of(settings: &ExportSettings) -> u32 { /// ([`Enc::open`] runs ahead of the muxer), which is what makes the refusal /// free. fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result> { - // `VE_HW_TEST_FAKE` is the containment tests' stand-in seat -- a child that - // opens no driver at all -- and it is not what a software pin is pinning - // away: the pin says "do not use this machine's GPU", and that seat is not - // this machine's GPU. Without this the suite could only prove the fallback - // on a run with no other export test in it. - if settings.seat == EncoderSeat::Software - || (forced("VE_SW_ENC") && !crate::hwproc::faked()) - { + if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") { return Ok(None); } let opened = open_hw_seat(meta, settings); diff --git a/crates/engine/src/hwproc.rs b/crates/engine/src/hwproc.rs index a8b33c6..3c1c2c9 100644 --- a/crates/engine/src/hwproc.rs +++ b/crates/engine/src/hwproc.rs @@ -462,18 +462,31 @@ impl Remote { /// What the child's encoder codes in, or `None` where it has no zero-copy /// door. + /// + /// The two `None`s are not the same thing and only one of them is an + /// answer. A child that *says* it has no door costs the caller a read-back + /// and nothing else; a child that does not answer at all is gone, and is + /// reaped right here -- otherwise the next picture would spend a whole + /// second timeout discovering what this call already knows. pub fn dma_geometry(&mut self) -> Option<(u32, u32)> { self.request(&[T_GEOM], &[]).ok()?; - let (tag, _) = recv_tag(&self.sock).ok()?; - if tag != R_AU { - return None; - } let mut buf = [0u8; 8]; - self.sock.read_exact(&mut buf).ok()?; - Some(( - u32::from_le_bytes(buf[..4].try_into().ok()?), - u32::from_le_bytes(buf[4..].try_into().ok()?), - )) + let answered = match recv_tag(&self.sock) { + Ok((R_AU, _)) => self.sock.read_exact(&mut buf).map(|()| true), + Ok(_) => Ok(false), + Err(e) => Err(e), + }; + match answered { + Ok(true) => Some(( + u32::from_le_bytes(buf[..4].try_into().ok()?), + u32::from_le_bytes(buf[4..].try_into().ok()?), + )), + Ok(false) => None, + Err(e) => { + self.bury(&e.to_string()); + None + } + } } /// Feeds one packed I420 picture through the shared mapping. diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 8809147..1622161 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -53,23 +53,48 @@ fn part_path(out: &Path) -> PathBuf { PathBuf::from(format!("{}.part", out.display())) } +/// Which seat an export takes is decided by *process-wide* environment +/// variables, so it is a shared resource and every test in this binary borrows +/// it rather than assuming it. +/// +/// Readers share: the whole software suite wants the same pin and may run at +/// once, exactly as it always did. A test that has to *change* the pin -- +/// there is one family, the encoder-death ones at the end of this file -- takes +/// it exclusively, so no export is ever in flight while the seat is being +/// cycled underneath it. A borrow held only for the seat's opening would not do: +/// [`engine::export::start`] falls back and re-opens mid-run, so the pin has to +/// hold for the whole export. +static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +type Shared = std::sync::RwLockReadGuard<'static, ()>; + /// Pins both paths to software for the whole test binary, so the default suite -/// proves the fallback that every machine has. -fn pin_software() { +/// proves the fallback that every machine has. Bind the guard: it is the borrow +/// above, and dropping it early puts the export back in the race this exists to +/// end. +#[must_use = "the seat pin holds only while its guard is alive"] +fn pin_software() -> Shared { + let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner()); static PIN: Once = Once::new(); PIN.call_once(|| unsafe { std::env::set_var("VE_SW", "1"); std::env::set_var("VE_SW_ENC", "1"); }); + borrowed } -/// Removes both pins, for the hardware twins. -fn pin_hardware() { +/// Removes both pins, for the hardware twins -- which run in their own +/// `--ignored --test-threads=1` pass, so they never share this binary with the +/// software ones. +#[must_use = "the seat pin holds only while its guard is alive"] +fn pin_hardware() -> Shared { + let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner()); static PIN: Once = Once::new(); PIN.call_once(|| unsafe { std::env::remove_var("VE_SW"); std::env::remove_var("VE_SW_ENC"); }); + borrowed } /// `[0,30) + [60,150)` of the source: two cuts and a delete, so the export has @@ -180,7 +205,7 @@ fn round_trip(name: &str, limit: Duration) { #[test] fn exports_an_edited_timeline_in_software() { - pin_software(); + let _seat = pin_software(); round_trip("sw", Duration::from_secs(120)); } @@ -189,7 +214,7 @@ fn exports_an_edited_timeline_in_software() { #[test] #[ignore] fn exports_an_edited_timeline_in_hardware() { - pin_hardware(); + let _seat = pin_hardware(); round_trip("hw", Duration::from_secs(60)); } @@ -202,7 +227,7 @@ fn exports_an_edited_timeline_in_hardware() { /// (`playback.rs: a_fitted_clip_is_letterboxed_and_a_filled_one_is_not`). #[test] fn exports_at_the_project_resolution_with_the_watched_geometry() { - pin_software(); + let _seat = pin_software(); let clip = |source: usize, start: u32| engine::Clip { start, in_frame: 0, @@ -282,7 +307,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() { /// header. Software only: the picture is beside the point here. #[test] fn exports_the_audio_stream_the_timeline_plays() { - pin_software(); + let _seat = pin_software(); let multi = asset("test_multiaudio.mp4"); let (meta, _) = engine::demux::Demuxer::open(&multi).expect("open the fixture"); let whole = engine::Clip { @@ -456,14 +481,14 @@ fn multi_source_round_trip(name: &str, limit: Duration) { #[test] fn exports_two_sources_as_one_timeline_in_software() { - pin_software(); + let _seat = pin_software(); multi_source_round_trip("multi_sw", Duration::from_secs(180)); } #[test] #[ignore] fn exports_two_sources_as_one_timeline_in_hardware() { - pin_hardware(); + let _seat = pin_hardware(); multi_source_round_trip("multi_hw", Duration::from_secs(60)); } @@ -473,7 +498,7 @@ fn exports_two_sources_as_one_timeline_in_hardware() { /// whose rate control is the one every machine has. #[test] fn a_higher_bitrate_writes_a_bigger_file() { - pin_software(); + let _seat = pin_software(); let mut sizes = Vec::new(); for bitrate in [1_000_000u64, 4_000_000, 8_000_000] { let mut session = edited(&asset("test_baseline.mp4")); @@ -503,7 +528,7 @@ fn a_higher_bitrate_writes_a_bigger_file() { /// (the audio pass never touches the second file). #[test] fn a_vanished_source_fails_the_export() { - pin_software(); + let _seat = pin_software(); let baseline = asset("test_baseline.mp4"); let doomed = Scratch::file("ve_export_vanished_source", "mp4"); std::fs::copy(&baseline, &doomed).expect("copy a second source"); @@ -537,7 +562,7 @@ fn a_vanished_source_fails_the_export() { /// thing a user would otherwise try to play. #[test] fn cancelling_leaves_no_file() { - pin_software(); + let _seat = pin_software(); let mut session = edited(&asset("test_baseline.mp4")); session.pause(); let out = out_path("cancel"); @@ -572,7 +597,7 @@ fn cancelling_leaves_no_file() { /// file, never a `.part`. #[test] fn cancelling_after_the_last_frame_leaves_no_file() { - pin_software(); + let _seat = pin_software(); let out = out_path("late"); let part = part_path(&out); for attempt in 1..=5 { @@ -615,7 +640,7 @@ fn cancelling_after_the_last_frame_leaves_no_file() { #[test] #[ignore] fn exports_audio_alongside_the_video() { - pin_hardware(); + let _seat = pin_hardware(); let source = asset("test_av.mp4"); let mut session = PlaybackSession::open(&source).expect("open source"); // One cut: the timeline is unchanged but the audio copy now runs as two @@ -749,7 +774,7 @@ fn synthetic(index: u32, width: usize, height: usize) -> (Vec, Vec, Vec< /// early, which is a lip sync error for the whole export. #[test] fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() { - pin_software(); + let _seat = pin_software(); let source = asset("test_av.mp4"); let mut session = PlaybackSession::open(&source).expect("open source"); assert!(session.cut_at(1.0), "cut at 1 s"); @@ -797,7 +822,7 @@ fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() { /// a second early. #[test] fn exports_a_gapped_timeline_as_black_and_silence() { - pin_software(); + let _seat = pin_software(); let source = asset("test_av.mp4"); let mut session = PlaybackSession::open(&source).expect("open source"); assert!(session.cut_at(1.0), "split at 1 s"); @@ -887,7 +912,7 @@ fn exports_a_gapped_timeline_as_black_and_silence() { /// hardware one buys is speed, and that is the ignored test below. #[test] fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() { - pin_software(); + let _seat = pin_software(); let source = asset("test_av.mp4"); let out = engine::proxy::path_for(&source).expect("a cache directory"); // A proxy left by an earlier run would make this test assert about a file @@ -1021,7 +1046,7 @@ fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() { #[test] #[ignore = "needs the VA-API plugin"] fn a_hardware_proxy_is_every_frame_a_starting_point_too() { - pin_hardware(); + let _seat = pin_hardware(); let source = asset("test_av.mp4"); let out = engine::proxy::path_for(&source).expect("a cache directory"); let _ = std::fs::remove_file(&out); @@ -1094,7 +1119,7 @@ fn a_hardware_proxy_is_every_frame_a_starting_point_too() { #[test] #[ignore = "needs the VA-API plugin and a real library"] fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() { - pin_hardware(); + let _seat = pin_hardware(); let Some(film) = engine::real_library::film("hevc_4k_hdr") else { return; }; @@ -1174,14 +1199,23 @@ fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() { // opens a stand-in seat in the child that touches no driver; // `VE_HW_TEST_ABORT` / `VE_HW_TEST_HANG` say where it dies or stops. -/// The stand-in-seat variables are process-wide, so the tests below take turns -/// with them; nothing else in this binary reads them, and every one is removed -/// again before the turn is given up. +/// The one place in this binary that *changes* the seat rather than reading it, +/// so it takes [`SEAT`] exclusively: while it holds, no other export in this +/// process is in flight, and every variable it set is gone again before it lets +/// go. Which is the whole of the bug this shape exists to make impossible -- +/// a stand-in encoder seat cycled underneath a software test that had already +/// opened its own is a hang, not a failure, and it does not reproduce. +/// +/// It also lifts the software *encode* pin for its own exports, because the +/// question here is what an export does when its hardware seat dies. Decode +/// stays pinned to software: it is not what is under test and the fixture must +/// decode the same way it does everywhere else in this file. fn injected(abort: Option<&str>, hang: Option<&str>, body: impl FnOnce() -> T) -> T { - use std::sync::Mutex; - static TURN: Mutex<()> = Mutex::new(()); - let _turn = TURN.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let _exclusive = SEAT.write().unwrap_or_else(|poisoned| poisoned.into_inner()); + let restore = std::env::var_os("VE_SW_ENC"); unsafe { + std::env::set_var("VE_SW", "1"); + std::env::remove_var("VE_SW_ENC"); std::env::set_var("VE_HW_TEST_FAKE", "1"); std::env::set_var("VE_HW_CHILD_BIN", env!("CARGO_BIN_EXE_hw-encode-child")); // Short, because one of these is waiting out a child that has stopped @@ -1207,6 +1241,12 @@ fn injected(abort: Option<&str>, hang: Option<&str>, body: impl FnOnce() -> T ] { std::env::remove_var(var); } + // Put the software suite's pin back exactly as it was found -- it is + // set once for the whole binary and this is the only thing that ever + // takes it away. + if let Some(pinned) = restore { + std::env::set_var("VE_SW_ENC", pinned); + } } match out { Ok(value) => value, @@ -1234,7 +1274,6 @@ fn short_edit(source: &Path, frames: u32) -> (Project, engine::VideoMeta) { /// presses, and this is that same call with a driver dying under it. #[test] fn a_hardware_encoder_killed_mid_export_costs_the_file_nothing() { - pin_software(); let source = asset("test_baseline.mp4"); let (project, meta) = short_edit(&source, 20); let out = out_path("hw_child_abort"); @@ -1264,7 +1303,6 @@ fn a_hardware_encoder_killed_mid_export_costs_the_file_nothing() { /// the first frame. A refusal, not a crash, and the file is whole. #[test] fn a_hardware_encoder_killed_at_its_open_is_simply_no_seat() { - pin_software(); let source = asset("test_baseline.mp4"); let (project, meta) = short_edit(&source, 12); let out = out_path("hw_child_abort_init"); @@ -1283,7 +1321,6 @@ fn a_hardware_encoder_killed_at_its_open_is_simply_no_seat() { /// picture is fed and the encoder is being flushed when it dies. #[test] fn a_hardware_encoder_killed_at_the_drain_costs_the_file_nothing() { - pin_software(); let source = asset("test_baseline.mp4"); let (project, meta) = short_edit(&source, 12); let out = out_path("hw_child_abort_drain"); @@ -1306,7 +1343,6 @@ fn a_hardware_encoder_killed_at_the_drain_costs_the_file_nothing() { /// that sat on a stuck child forever would be the hang this refuses. #[test] fn a_hardware_encoder_that_stops_answering_is_killed_and_replaced() { - pin_software(); let source = asset("test_baseline.mp4"); let (project, meta) = short_edit(&source, 12); let out = out_path("hw_child_hang"); @@ -1327,6 +1363,44 @@ fn a_hardware_encoder_that_stops_answering_is_killed_and_replaced() { std::fs::remove_file(&out).unwrap(); } +/// ...and the export that does **not** get written again: a person who picked +/// the GPU on the export card asked for it by name, so a dead hardware seat is +/// refused in words rather than answered with an hour in an encoder nobody +/// chose. The same posture [`engine::export::start`] already takes for a machine +/// with no hardware seat at all -- and the guard that separates the two is the +/// one every test above depends on being narrow. +/// +/// The process is alive either way, which is the invariant; what differs is who +/// is told. +#[test] +fn an_export_that_asked_for_the_gpu_by_name_refuses_instead_of_falling_back() { + let source = asset("test_baseline.mp4"); + let (project, meta) = short_edit(&source, 12); + let out = out_path("hw_child_named_seat"); + + let error = injected(Some("2"), None, || { + let settings = ExportSettings { + seat: engine::export::EncoderSeat::Hardware, + ..Default::default() + }; + let handle = engine::export::start(project, meta, &out, &settings); + wait(&handle, Duration::from_secs(180)) + .expect_err("a named hardware seat that died is not written again in software") + }); + + println!("named hardware seat: {error}"); + assert!( + engine::hwproc::is_lost(&error), + "the refusal has to name the hardware failure: {error}" + ); + assert!( + !out.exists(), + "a refused export still wrote {}", + out.display() + ); + assert!(!part_path(&out).exists(), "the .part outlived the refusal"); +} + /// The seat's own contract, under the same injection and with no export around /// it: a killed child comes back as an error carrying /// [`engine::hwproc::HW_LOST`], every later call gives the same answer instead