diff --git a/Cargo.lock b/Cargo.lock index 990056d..cea3bff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1639,6 +1639,7 @@ dependencies = [ "flacenc", "hound", "image", + "libc", "libloading", "miniz_oxide", "mp4", diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 8033455..e8b5453 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -6,9 +6,23 @@ //! negative code: the caller's contract is "any failure means use the software //! codec". //! -//! corner-cut: that guarantee rests on `panic = "unwind"`. Building this crate with -//! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path -//! is running the decoder in a child process instead of in-process. +//! That guarantee rests on `panic = "unwind"`, and it has a floor it can never +//! 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 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 +//! faults, this box, 2026-08-13). The upgrade path is the seam that already +//! exists: give `vh_open_at`/`vh_next_frame` the message tags `vh_enc_*` have in +//! `hwproc` and let the same helper hold both. use std::collections::VecDeque; use std::ffi::{CStr, c_char, c_void}; diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 23b6059..a80cb5e 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -12,6 +12,12 @@ edition.workspace = true hound = "3.5.1" flacenc = { version = "0.5.1", default-features = false } libloading = "0.8" +# `memfd_create`, `mmap` and `SCM_RIGHTS` -- the three things std has no door to +# and the whole of what puts the video driver in another process +# (`crate::hwproc`). Not a new crate tree: it was already in this workspace's +# lock file, pulled in by half the dependencies here, so this line compiles +# nothing that was not compiled before. +libc = "0.2" # Still images, decoded once per placed clip (`decode::Still`). Pure Rust like # everything else here, and already in the app's tree (gpui pulls it), so this # costs the build nothing new. Exactly the formats `crate::is_image` admits: no diff --git a/crates/engine/src/bin/hw-encode-child.rs b/crates/engine/src/bin/hw-encode-child.rs new file mode 100644 index 0000000..ec589fa --- /dev/null +++ b/crates/engine/src/bin/hw-encode-child.rs @@ -0,0 +1,262 @@ +//! The process that holds the video driver, and therefore the process a video +//! driver is allowed to kill. +//! +//! It is started by [`engine::hwproc::Remote::spawn`] with the encode session's +//! parameters as argv and one end of a socket pair as its standard input. It +//! opens the plugin's encoder in *this* address space, hands the parent a shared +//! anonymous file to stage pictures in, and then answers one request at a time +//! until the socket closes. Nothing else lives here: no project, no muxer, no +//! window -- so an `abort()` out of Mesa's own worker thread costs the editor a +//! reply and a fallback rather than the session. +//! +//! Three environment variables exist only for the tests that prove that, and +//! each is read here and nowhere else, so an editor without them set runs the +//! path it always ran: +//! +//! * `VE_HW_TEST_FAKE` -- open a stand-in seat that touches no driver, so the +//! containment paths can be exercised on a machine whose GPU is wedged (which +//! is the only machine where they matter). Refuses to open unless one of the +//! two below is set with it, so it can never be a silently empty encoder. +//! * `VE_HW_TEST_ABORT=` -- call `abort()` from a worker thread of +//! our own, before opening, at the first drain, or before coding picture `N`. +//! A foreign C thread's `abort()` is what really happened on 2026-08-13; this +//! is the same shape without a hung ring. +//! * `VE_HW_TEST_HANG=` -- stop answering at that same point, +//! without dying, which is the other half of a wedged ring. + +use std::io::{Read, Write}; +use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd}; +use std::os::unix::net::UnixStream; + +use engine::hw::{DmaFrame, LocalEncoder, VhDma}; +use engine::hwproc::{Open, R_AU, R_ERR, R_NONE, Shm, T_DMA, T_DRAIN, T_ENCODE, T_GEOM, recv_tag, send_msg}; + +/// Where the encoder actually is: the plugin's, or the test stand-in that opens +/// no driver at all. +enum Seat { + Real(LocalEncoder), + Fake, +} + +impl Seat { + fn dma_geometry(&self) -> Option<(u32, u32)> { + match self { + Self::Real(encoder) => encoder.dma_geometry(), + // Nothing to import into, so the parent stages pictures instead -- + // which is the path the containment tests want anyway. + Self::Fake => None, + } + } +} + +/// One of the three injection points, named the same way in all three variables. +#[derive(PartialEq, Eq)] +enum At { + Init, + Drain, + Frame(u32), +} + +fn injected(var: &str) -> Option { + let value = std::env::var(var).ok()?; + Some(match value.as_str() { + "init" => At::Init, + "drain" => At::Drain, + _ => At::Frame(value.parse().ok()?), + }) +} + +/// The driver's own way of dying, reproduced: `abort()` called from a thread +/// that is not the one running the encode, because that is where +/// `amdgpu_ctx_set_sw_reset_status` calls it from and because a `catch_unwind` +/// around the encode call is exactly what cannot see it. +fn die() { + std::thread::spawn(|| { + // SAFETY: `abort` takes nothing, returns never, and is the whole point. + unsafe { libc::abort() } + }); + loop { + std::thread::park(); + } +} + +/// ...and the other half: alive, holding the socket open, answering nothing. +fn hang() -> ! { + loop { + std::thread::park(); + } +} + +fn reached(point: &At) { + if injected("VE_HW_TEST_ABORT").as_ref() == Some(point) { + die(); + } + if injected("VE_HW_TEST_HANG").as_ref() == Some(point) { + hang(); + } +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + let Some(open) = Open::from_argv(&args) else { + eprintln!("hw-encode-child: bad arguments"); + std::process::exit(2); + }; + // SAFETY: the parent handed this process one end of a socket pair as its + // standard input and holds the other; nothing else in this process reads + // descriptor 0. + let mut sock = unsafe { UnixStream::from_raw_fd(0) }; + + reached(&At::Init); + let seat = match std::env::var_os("VE_HW_TEST_FAKE").is_some() { + // A stand-in that no test forgot to arm: without an injection point it + // would be an encoder producing nothing, and that is a hang of its own + // kind rather than a test. + true => match injected("VE_HW_TEST_ABORT").is_some() || injected("VE_HW_TEST_HANG").is_some() + { + true => Some(Seat::Fake), + false => None, + }, + false => LocalEncoder::open_seat(open).map(Seat::Real), + }; + let Some(mut seat) = seat else { + // The plugin's own "no", carried back as a byte: no driver, no + // entrypoint, a size refused. The parent takes the software encoder. + let _ = sock.write_all(&[0u8]); + std::process::exit(1); + }; + + // The staging buffer for pictures that live in memory: made here because + // this side knows the session's size, and handed over with the "yes". + let (mut shm, fd) = match Shm::create(open.frame_bytes()) { + Ok(pair) => pair, + Err(e) => { + eprintln!("hw-encode-child: no staging buffer: {e}"); + let _ = sock.write_all(&[0u8]); + std::process::exit(1); + } + }; + if send_msg(&sock, &[1u8], &[fd.as_raw_fd()]).is_err() { + std::process::exit(1); + } + drop(fd); + + let mut coded = 0u32; + loop { + let Ok((tag, fds)) = recv_tag(&sock) else { + // The parent is gone (it closed, or it died): there is nothing left + // to encode for. + return; + }; + match tag { + T_GEOM => match seat.dma_geometry() { + Some((width, height)) => { + let mut reply = vec![R_AU]; + reply.extend_from_slice(&width.to_le_bytes()); + reply.extend_from_slice(&height.to_le_bytes()); + let _ = sock.write_all(&reply); + } + None => { + let _ = sock.write_all(&[R_NONE]); + } + }, + T_ENCODE => { + let mut head = [0u8; 9]; + if sock.read_exact(&mut head).is_err() { + return; + } + reached(&At::Frame(coded)); + coded += 1; + let width = u32::from_le_bytes(head[0..4].try_into().expect("four bytes")); + let height = u32::from_le_bytes(head[4..8].try_into().expect("four bytes")); + let force_key = head[8] != 0; + let (w, h) = (width as usize, height as usize); + let chroma = w.div_ceil(2) * h.div_ceil(2); + let answer = match &mut seat { + Seat::Real(encoder) => { + let bytes = shm.bytes(); + let (y, rest) = bytes.split_at(w * h); + let (u, rest) = rest.split_at(chroma); + encoder.encode(y, u, &rest[..chroma], width, height, force_key) + } + Seat::Fake => Ok(None), + }; + if !reply(&mut sock, answer) { + return; + } + } + T_DMA => { + let mut head = [0u8; 46]; + if sock.read_exact(&mut head).is_err() { + return; + } + reached(&At::Frame(coded)); + coded += 1; + let u32_at = |offset: usize| { + u32::from_le_bytes(head[offset..offset + 4].try_into().expect("four bytes")) + }; + let mut desc = VhDma { + fourcc: u32_at(0), + modifier: u64::from_le_bytes(head[4..12].try_into().expect("eight bytes")), + coded_width: u32_at(12), + coded_height: u32_at(16), + width: u32_at(20), + height: u32_at(24), + offset: [u32_at(28), u32_at(32)], + stride: [u32_at(36), u32_at(40)], + fd: [-1, -1], + }; + if fds.len() != head[44] as usize || fds.is_empty() { + let _ = write_error(&mut sock, "a buffer arrived without its descriptors"); + continue; + } + // Ownership passes to the frame, which closes them: the parent + // kept its own copies and these are ours. + for (slot, fd) in desc.fd.iter_mut().zip(fds) { + *slot = fd.into_raw_fd(); + } + let frame = DmaFrame::from_desc(desc); + let answer = match &mut seat { + Seat::Real(encoder) => encoder.encode_dma(&frame, head[45] != 0), + Seat::Fake => Ok(None), + }; + if !reply(&mut sock, answer) { + return; + } + } + T_DRAIN => { + reached(&At::Drain); + let answer = match &mut seat { + Seat::Real(encoder) => encoder.drain(), + Seat::Fake => Ok(None), + }; + if !reply(&mut sock, answer) { + return; + } + } + _ => return, + } + } +} + +/// Writes one answer back. `false` means the parent is gone and this process has +/// nothing left to do. +fn reply(sock: &mut UnixStream, answer: engine::Result>) -> bool { + match answer { + Ok(None) => sock.write_all(&[R_NONE]).is_ok(), + Ok(Some(au)) => { + let mut head = vec![R_AU]; + head.extend_from_slice(&(au.len() as u32).to_le_bytes()); + sock.write_all(&head).is_ok() && sock.write_all(au).is_ok() + } + // The encoder's own refusal, not a death: the parent raises it as the + // export error it is and this process stays open. + Err(e) => write_error(sock, &e.to_string()), + } +} + +fn write_error(sock: &mut UnixStream, message: &str) -> bool { + let mut head = vec![R_ERR]; + head.extend_from_slice(&(message.len() as u32).to_le_bytes()); + sock.write_all(&head).is_ok() && sock.write_all(message.as_bytes()).is_ok() +} diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index 433f800..0586f42 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -494,7 +494,33 @@ pub fn start( format.name() ) .into()), - format if format.has_video() => run(&project, &meta, &part, &worker, &settings), + format if format.has_video() => { + let first = run(&project, &meta, &part, &worker, &settings); + match first { + // The hardware encoder's *process* died under the driver + // ([`crate::hwproc`]) -- the editor is still here, and the + // file is still owed. Written again by the software encoder + // for this codec, from the first frame: the pictures the + // dead seat coded are not ones this one may continue from. + // + // Not where a person picked the GPU by name: that export + // refuses in words, the same answer [`hw_seat`] already + // gives a machine with no seat at all, rather than quietly + // spending an hour in an encoder nobody chose. + Err(e) + if crate::hwproc::is_lost(&e) + && settings.seat != EncoderSeat::Hardware => + { + eprintln!("export video: {e}; writing it again in software"); + let _ = std::fs::remove_file(&part); + worker.progress.store(0, Ordering::Relaxed); + let mut software = settings.clone(); + software.seat = EncoderSeat::Software; + run(&project, &meta, &part, &worker, &software) + } + other => other, + } + } _ => run_audio(&project, &meta, &part, &worker, &settings), }; let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); @@ -3587,7 +3613,9 @@ impl Enc { /// person picks it by name because the vendored encoder reset this project's GPU /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to /// widen. - fn dma_want(&self, meta: &VideoMeta) -> Option { + /// `&mut` because an isolated seat has to *ask* the process it lives in + /// ([`crate::hwproc`]), which is a round trip on its socket. + fn dma_want(&mut self, meta: &VideoMeta) -> Option { match self { Self::Hw(hw) | Self::HevcHw(hw) => hw.dma_want(meta.width, meta.height), _ => None, diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index cbed496..97d136d 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -123,6 +123,14 @@ impl Default for VhDma { pub struct DmaFrame(VhDma); impl DmaFrame { + /// Takes ownership of descriptors that arrived from somewhere other than a + /// decode session -- which is the `hw-encode-child` helper, receiving over + /// `SCM_RIGHTS` the very buffer the parent's decoder wrote into. + #[doc(hidden)] + pub fn from_desc(desc: VhDma) -> Self { + Self(desc) + } + pub fn width(&self) -> u32 { self.0.width } @@ -504,13 +512,39 @@ fn load_enc() -> Option { None } -/// An open hardware encode session. Dropping it closes the plugin session. -pub struct HwEncoder { +/// An open hardware encode session **in this process**, which is the one thing +/// an editor must not have: the driver's own C threads `abort()` the process +/// they are in when the video ring resets ([`crate::hwproc`]). Public only so +/// that the `hw-encode-child` helper -- the process whose whole job is to be the +/// one that dies -- can open it; every other caller goes through [`HwEncoder`], +/// which is this seat held at arm's length. +/// +/// Dropping it closes the plugin session. +#[doc(hidden)] +pub struct LocalEncoder { plugin: &'static EncPlugin, handle: *mut c_void, } -impl HwEncoder { +impl LocalEncoder { + /// The four seats behind one argument, which is how the helper is told + /// which of them to open. + pub fn open_seat(open: crate::hwproc::Open) -> Option { + let (w, h, n, d, b) = ( + open.width, + open.height, + open.fps_num, + open.fps_den, + open.bitrate, + ); + match open.seat { + crate::hwproc::Seat::H264 => Self::open(w, h, n, d, b), + crate::hwproc::Seat::Intra => Self::open_intra(w, h, n, d, b), + crate::hwproc::Seat::Av1 => Self::open_av1(w, h, n, d, b), + crate::hwproc::Seat::Hevc => Self::open_hevc(w, h, n, d, b, open.colour), + } + } + /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded /// at a constant `bitrate` bits per second. `None` whenever hardware encode /// is unavailable -- plugin missing, plugin too old to export the encode @@ -668,10 +702,10 @@ impl HwEncoder { }) } - /// What a decoded buffer must look like to reach this encoder without a - /// copy -- the surface size it codes in, plus the picture it was opened for - /// -- or `None` where the plugin has no zero-copy door at all. - pub fn dma_want(&self, width: u32, height: u32) -> Option { + /// The surface size this seat codes in, or `None` where the plugin has no + /// zero-copy door at all. What [`HwEncoder::dma_want`] turns into the whole + /// description a decoder is asked for. + pub fn dma_geometry(&self) -> Option<(u32, u32)> { let geometry = self.plugin.dma_geometry?; self.plugin.frame_dma?; let (mut coded_width, mut coded_height) = (0u32, 0u32); @@ -679,12 +713,7 @@ impl HwEncoder { if unsafe { geometry(self.handle, &mut coded_width, &mut coded_height) } != 1 { return None; } - Some(DmaWant { - coded_width, - coded_height, - width, - height, - }) + Some((coded_width, coded_height)) } /// Feeds one picture the decoder left on the GPU. Same answer and same @@ -733,7 +762,7 @@ impl HwEncoder { } } -impl Drop for HwEncoder { +impl Drop for LocalEncoder { fn drop(&mut self) { // SAFETY: `handle` came from `vh_enc_open` and is closed exactly once. unsafe { (self.plugin.close)(self.handle) } @@ -741,4 +770,229 @@ impl Drop for HwEncoder { } // As `HwSession`: used from one thread at a time (the export worker). -unsafe impl Send for HwEncoder {} +unsafe impl Send for LocalEncoder {} + +/// An open hardware encode session, **in a child process** wherever there is a +/// helper to run it in -- which is what keeps a driver's `abort()` off the +/// editor. See [`crate::hwproc`] for the whole of why. +/// +/// The API is the in-process one it replaced, call for call, so nothing in the +/// export loop knows which side of a process boundary the encoder is on. +pub enum HwEncoder { + /// The isolated seat, and the one every ordinary build takes. + Remote(crate::hwproc::Remote), + /// The seat as it was: taken only where there is no helper binary to run + /// (a build that produced the plugin and not the editor's own directory) or + /// where `VE_HW_INPROCESS` pins it, which is how the isolated path's cost is + /// measured against the path it replaced. + Local(LocalEncoder), +} + +impl HwEncoder { + /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded + /// at a constant `bitrate` bits per second. `None` whenever hardware encode + /// is unavailable -- plugin missing, plugin too old to export the encode + /// entry points, no driver, dimensions the driver refuses, *or a helper that + /// died opening any of it* -- and the caller falls back to the software + /// encoder. + pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option { + Self::seated( + crate::hwproc::Seat::H264, + width, + height, + fps_num, + fps_den, + bitrate, + ColorDescription::default(), + ) + } + + /// The same H.264 seat, **intra-only**: every picture comes back an IDR + /// with its own parameter sets, so every frame of the file is one a decoder + /// may be started from. What [`crate::proxy`] codes a stand-in with. + /// + /// `None` on everything [`HwEncoder::open`] answers `None` to *and* on a + /// plugin built before this seat existed -- and that `None` matters more + /// than the others: the caller must then take the software encoder, which + /// codes one frame a GOP, rather than the ordinary hardware seat, which + /// would write a long-GOP file under a name that promises otherwise. + pub fn open_intra( + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, + ) -> Option { + Self::seated( + crate::hwproc::Seat::Intra, + width, + height, + fps_num, + fps_den, + bitrate, + ColorDescription::default(), + ) + } + + /// The same, coding AV1 instead. `None` on everything [`HwEncoder::open`] + /// answers `None` to *and* on a plugin or a GPU with no AV1 encoder -- an + /// AV1 encode entrypoint is recent hardware, so this is the fallback that + /// really fires, and the caller's software AV1 encoder takes the export + /// without saying anything about it. + /// + /// The caller only reaches this when a person picked + /// [`crate::export::EncoderSeat::Hardware`] for an AV1 export: this is the + /// seat whose ring hang killed the editor on 2026-08-13, and it is now the + /// seat that kills a child instead. + pub fn open_av1( + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, + ) -> Option { + Self::seated( + crate::hwproc::Seat::Av1, + width, + height, + fps_num, + fps_den, + bitrate, + ColorDescription::default(), + ) + } + + /// The same, coding HEVC. Unlike the AV1 seat this is **not** behind an + /// opt-in: it is the default for an HEVC export, and what makes that safe is + /// that the pictures it codes are intra-only, which is the same file the + /// software seat writes ([`crate::export::Enc::open_hevc`]) and not the + /// GPU-resetting inter path AV1's opt-in exists for. + /// + /// `colour` is what the SPS will say the samples mean, and it is taken at + /// the open because the parameter sets are written when the sequence starts. + /// libavcodec's HEVC decoder overwrites a container's colour with the + /// bitstream's, so a seat that signalled nothing hands a player + /// "unspecified" -- BT.601 -- however the file is tagged. + pub fn open_hevc( + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, + colour: ColorDescription, + ) -> Option { + Self::seated( + crate::hwproc::Seat::Hevc, + width, + height, + fps_num, + fps_den, + bitrate, + colour, + ) + } + + /// Where the choice between the two seats is made, and the only place it is. + /// + /// A child is not started where there is nothing for it to open: with no + /// plugin on this machine the answer is `None` before a process is forked, + /// which is exactly what a plugin-less machine has always answered and at + /// the same cost. + fn seated( + seat: crate::hwproc::Seat, + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, + colour: ColorDescription, + ) -> Option { + let open = crate::hwproc::Open { + seat, + width, + height, + fps_num, + fps_den, + bitrate, + colour, + }; + if enc_plugin().is_none() && !crate::hwproc::faked() { + return None; + } + // corner-cut: a build with no helper beside the executable keeps the + // in-process seat rather than losing hardware encode outright, so a + // driver crash there is still fatal. The ceiling is packaging: ship + // `hw-encode-child` next to `edith` (cargo already does) and this arm is + // never taken. + if !crate::hwproc::available() || std::env::var_os("VE_HW_INPROCESS").is_some() { + return LocalEncoder::open_seat(open).map(Self::Local); + } + crate::hwproc::Remote::spawn(open).map(Self::Remote) + } + + /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has + /// not finished an access unit yet; the returned bytes are Annex-B and stay + /// valid until the next call on this session. + pub fn encode( + &mut self, + y: &[u8], + u: &[u8], + v: &[u8], + width: u32, + height: u32, + force_key: bool, + ) -> crate::Result> { + // Checked on this side of the boundary whichever seat has the picture: + // a caller's mistake is a caller's mistake, and the isolated seat must + // not turn one into a message about a dead child. + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch { + return Err("encode input is not a packed I420 frame".into()); + } + match self { + Self::Remote(remote) => remote.encode(y, u, v, width, height, force_key), + Self::Local(local) => local.encode(y, u, v, width, height, force_key), + } + } + + /// What a decoded buffer must look like to reach this encoder without a + /// copy -- the surface size it codes in, plus the picture it was opened for + /// -- or `None` where the plugin has no zero-copy door at all. + pub fn dma_want(&mut self, width: u32, height: u32) -> Option { + let (coded_width, coded_height) = match self { + Self::Remote(remote) => remote.dma_geometry()?, + Self::Local(local) => local.dma_geometry()?, + }; + Some(DmaWant { + coded_width, + coded_height, + width, + height, + }) + } + + /// Feeds one picture the decoder left on the GPU. Same answer and same + /// lifetime rule as [`HwEncoder::encode`]; an error here is a real one, the + /// caller having asked [`HwEncoder::dma_want`] what this seat takes before + /// the decoder handed the buffer over. + /// + /// The buffer does not move for the isolated seat either: its descriptors + /// go to the child over `SCM_RIGHTS` and the pixels stay where the decoder + /// wrote them. + pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result> { + match self { + Self::Remote(remote) => remote.encode_dma(&dma.0, force_key), + Self::Local(local) => local.encode_dma(dma, force_key), + } + } + + /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule + /// as [`HwEncoder::encode`]. + pub fn drain(&mut self) -> crate::Result> { + match self { + Self::Remote(remote) => remote.drain(), + Self::Local(local) => local.drain(), + } + } +} diff --git a/crates/engine/src/hwproc.rs b/crates/engine/src/hwproc.rs new file mode 100644 index 0000000..3c1c2c9 --- /dev/null +++ b/crates/engine/src/hwproc.rs @@ -0,0 +1,670 @@ +//! The hardware encoder, held in a **child process**. +//! +//! Every entry point of the plugin catches unwinds ([`crate::hw`]), and that +//! guarantee has a floor it cannot reach: Mesa's VA-API drivers run their own C +//! worker threads, and `radeonsi` calls libc `abort()` from +//! `amdgpu_ctx_set_sw_reset_status` when the video ring resets under it +//! (measured 2026-08-13, mesa 26.1.6, `vcn_unified_0` hung during an AV1 encode +//! submission). A foreign thread's `abort()` is not an unwind and no +//! `catch_unwind` in this address space can see it, so the editor died with the +//! driver and took the export -- and the session -- with it. +//! +//! So the driver is not in this address space any more. `HwEncoder` here is a +//! handle on a child running `hw-encode-child`, which is the one process that +//! `dlopen`s the plugin and therefore the only one a driver may kill. When it +//! dies -- by `abort()`, by any signal, or by going quiet past +//! [`Remote::timeout`] -- the parent sees a closed socket or a timed-out read, +//! reaps the child, and reports an error carrying [`HW_LOST`]. The export then +//! runs again on the software encoder ([`crate::export::start`]), or refuses in +//! words where a person picked the GPU by name. +//! +//! Two things cross between the processes and neither is a picture copied down a +//! pipe. Pictures that live in memory are written into a shared anonymous file +//! (`memfd`, mapped in both), so a frame costs one `memcpy` and a 10-byte +//! message. Pictures still on the GPU never move at all: the DRM-PRIME +//! descriptors travel as file descriptors over `SCM_RIGHTS`, so the zero-copy +//! export path stays zero-copy across the process boundary. + +use std::ffi::c_void; +use std::io::Read; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::process::{Child, Command, Stdio}; +use std::time::Duration; + +use crate::colorspace::{ColorDescription, Matrix, Transfer}; +use crate::hw::VhDma; + +/// The words every "the child is gone" error carries, and the only thing +/// [`crate::export`] matches on to decide that the software encoder should have +/// another go at the file. A message, not an error kind, because +/// [`crate::Error`] is a boxed `dyn Error` and a caller two crates away reads +/// its text. +pub const HW_LOST: &str = "the hardware encoder process"; + +/// Whether an error is one: a driver that took its process down, rather than a +/// picture this engine got wrong. +pub fn is_lost(error: &crate::Error) -> bool { + error.to_string().contains(HW_LOST) +} + +/// The helper's file name; it is built into the same directory as the editor. +const BIN: &str = "hw-encode-child"; + +/// Which encoder the child opens. Sent as argv, so the child needs no protocol +/// before it has one. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Seat { + H264, + Intra, + Av1, + Hevc, +} + +impl Seat { + pub fn code(self) -> u8 { + match self { + Self::H264 => 0, + Self::Intra => 1, + Self::Av1 => 2, + Self::Hevc => 3, + } + } + + pub fn from_code(code: u8) -> Option { + Some(match code { + 0 => Self::H264, + 1 => Self::Intra, + 2 => Self::Av1, + 3 => Self::Hevc, + _ => return None, + }) + } +} + +/// Everything an open needs, in one place because it travels as argv and comes +/// back as a struct on the other side. +#[derive(Clone, Copy)] +pub struct Open { + pub seat: Seat, + pub width: u32, + pub height: u32, + pub fps_num: u32, + pub fps_den: u32, + pub bitrate: u64, + /// What the sequence header will say the samples mean. Only the HEVC seat + /// takes one; the others ignore it. + pub colour: ColorDescription, +} + +impl Open { + fn argv(&self) -> Vec { + let (matrix, transfer) = ( + match self.colour.matrix { + Matrix::Bt709 => 0, + Matrix::Bt601 => 1, + Matrix::Bt2020Ncl => 2, + }, + match self.colour.transfer { + Transfer::Sdr => 0, + Transfer::Pq => 1, + Transfer::Hlg => 2, + }, + ); + [ + u32::from(self.seat.code()), + self.width, + self.height, + self.fps_num, + self.fps_den, + matrix, + transfer, + u32::from(self.colour.full_range), + ] + .iter() + .map(u32::to_string) + .chain(std::iter::once(self.bitrate.to_string())) + .collect() + } + + /// The other half of [`Open::argv`], in the child. + pub fn from_argv(args: &[String]) -> Option { + let n = |i: usize| args.get(i)?.parse::().ok(); + Some(Self { + seat: Seat::from_code(u8::try_from(n(0)?).ok()?)?, + width: n(1)?, + height: n(2)?, + fps_num: n(3)?, + fps_den: n(4)?, + bitrate: args.get(8)?.parse().ok()?, + colour: ColorDescription { + matrix: match n(5)? { + 0 => Matrix::Bt709, + 1 => Matrix::Bt601, + _ => Matrix::Bt2020Ncl, + }, + transfer: match n(6)? { + 0 => Transfer::Sdr, + 1 => Transfer::Pq, + _ => Transfer::Hlg, + }, + full_range: n(7)? != 0, + }, + }) + } + + /// How many bytes one packed I420 picture of this size takes -- the size of + /// the shared mapping, decided once at the open because the export feeds one + /// canvas size for the whole file. + pub fn frame_bytes(&self) -> usize { + let (w, h) = (self.width as usize, self.height as usize); + w * h + 2 * (w.div_ceil(2) * h.div_ceil(2)) + } +} + +// Requests, parent to child. +pub const T_ENCODE: u8 = 1; +pub const T_DMA: u8 = 2; +pub const T_DRAIN: u8 = 3; +pub const T_GEOM: u8 = 4; +// Replies, child to parent. +pub const R_NONE: u8 = 0; +pub const R_AU: u8 = 1; +pub const R_ERR: u8 = 2; + +/// A `memfd` mapped into this process: the staging buffer one picture is written +/// into and read out of without either side owning the other's memory. +pub struct Shm { + ptr: *mut u8, + len: usize, +} + +impl Shm { + /// Creates one of `len` bytes, returning it mapped plus the descriptor to + /// hand the other process. + pub fn create(len: usize) -> std::io::Result<(Self, OwnedFd)> { + // SAFETY: a NUL-terminated name and a flag word, which is the whole of + // this call's contract; the descriptor it returns is ours. + let fd = unsafe { libc::memfd_create(c"edith-hwenc".as_ptr(), libc::MFD_CLOEXEC) }; + if fd < 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: `fd` is a fresh descriptor nothing else holds. + let file = unsafe { std::fs::File::from_raw_fd(fd) }; + file.set_len(len as u64)?; + let shm = Self::map(fd, len)?; + Ok((shm, OwnedFd::from(file))) + } + + /// Maps a descriptor the other process created. + pub fn map(fd: RawFd, len: usize) -> std::io::Result { + // SAFETY: a shared mapping of a descriptor that is open for the call; + // the kernel picks the address and the length is the file's own. + let ptr = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + fd, + 0, + ) + }; + if ptr == libc::MAP_FAILED { + return Err(std::io::Error::last_os_error()); + } + Ok(Self { + ptr: ptr.cast(), + len, + }) + } + + /// A mapping of nothing, for the moment between spawning a child and + /// learning which buffer it made. + fn empty() -> Self { + Self { + ptr: std::ptr::null_mut(), + len: 0, + } + } + + /// The mapping as bytes. Both processes see the same store, and the protocol + /// -- one request, one reply, never overlapping -- is what keeps only one of + /// them looking at a time. + pub fn bytes(&mut self) -> &mut [u8] { + // SAFETY: the mapping is `len` bytes long and lives as long as `self`. + unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) } + } +} + +impl Drop for Shm { + fn drop(&mut self) { + if self.len == 0 { + return; + } + // SAFETY: the pair of the `mmap` above, unmapped exactly once. + unsafe { libc::munmap(self.ptr.cast(), self.len) }; + } +} + +// The mapping is used from one thread at a time (the export worker), as the +// session it belongs to is. +unsafe impl Send for Shm {} + +/// Sends one message with its file descriptors attached. +/// +/// `MSG_NOSIGNAL` is the point of writing this by hand rather than +/// [`Write::write_all`]: a child that has just died leaves a socket whose next +/// write raises `SIGPIPE`, and a crash-containment path that kills the editor +/// with a signal of its own would be no containment at all. +pub fn send_msg(sock: &UnixStream, bytes: &[u8], fds: &[RawFd]) -> std::io::Result<()> { + debug_assert!(!bytes.is_empty(), "ancillary data rides on a real byte"); + let mut iov = libc::iovec { + iov_base: bytes.as_ptr() as *mut c_void, + iov_len: bytes.len(), + }; + // Two descriptors is the most anything here sends (a two-object NV12 + // buffer); 64 bytes covers the header, the payload and the alignment. + let mut control = [0u8; 64]; + // SAFETY: every pointer below is into a local that outlives the call, the + // control buffer is larger than the `CMSG_SPACE` written into + // `msg_controllen`, and the descriptors are open for the duration. + let sent = unsafe { + let mut msg: libc::msghdr = std::mem::zeroed(); + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + if !fds.is_empty() { + let payload = (std::mem::size_of::() * fds.len()) as u32; + msg.msg_control = control.as_mut_ptr().cast(); + msg.msg_controllen = libc::CMSG_SPACE(payload) as _; + let cmsg = libc::CMSG_FIRSTHDR(&msg); + (*cmsg).cmsg_level = libc::SOL_SOCKET; + (*cmsg).cmsg_type = libc::SCM_RIGHTS; + (*cmsg).cmsg_len = libc::CMSG_LEN(payload) as _; + std::ptr::copy_nonoverlapping( + fds.as_ptr(), + libc::CMSG_DATA(cmsg).cast::(), + fds.len(), + ); + } + libc::sendmsg(sock.as_raw_fd(), &msg, libc::MSG_NOSIGNAL) + }; + match sent { + n if n < 0 => Err(std::io::Error::last_os_error()), + // Messages here are tens of bytes and a socket buffer is kilobytes, so a + // short send means the peer is gone rather than that we should loop. + n if n as usize != bytes.len() => Err(std::io::Error::new( + std::io::ErrorKind::WriteZero, + "short send", + )), + _ => Ok(()), + } +} + +/// Reads the one byte a message's descriptors ride on, and those descriptors. +/// +/// Ancillary data attaches to a position in the byte stream, so the tag is read +/// with `recvmsg` and everything after it with an ordinary read. +pub fn recv_tag(sock: &UnixStream) -> std::io::Result<(u8, Vec)> { + let mut byte = [0u8; 1]; + let mut iov = libc::iovec { + iov_base: byte.as_mut_ptr().cast(), + iov_len: 1, + }; + let mut control = [0u8; 64]; + let mut fds = Vec::new(); + // SAFETY: as `send` -- locals that outlive the call and a control buffer + // whose length is what `msg_controllen` claims. Every descriptor the kernel + // writes there is ours, and is taken by an `OwnedFd` exactly once. + let got = unsafe { + let mut msg: libc::msghdr = std::mem::zeroed(); + msg.msg_iov = &mut iov; + msg.msg_iovlen = 1; + msg.msg_control = control.as_mut_ptr().cast(); + msg.msg_controllen = control.len() as _; + let got = libc::recvmsg(sock.as_raw_fd(), &mut msg, libc::MSG_CMSG_CLOEXEC); + if got > 0 { + let mut cmsg = libc::CMSG_FIRSTHDR(&msg); + while !cmsg.is_null() { + if (*cmsg).cmsg_level == libc::SOL_SOCKET && (*cmsg).cmsg_type == libc::SCM_RIGHTS { + let bytes = (*cmsg).cmsg_len as usize - libc::CMSG_LEN(0) as usize; + let data = libc::CMSG_DATA(cmsg).cast::(); + for i in 0..bytes / std::mem::size_of::() { + fds.push(OwnedFd::from_raw_fd(data.add(i).read_unaligned())); + } + } + cmsg = libc::CMSG_NXTHDR(&msg, cmsg); + } + } + got + }; + match got { + n if n < 0 => Err(std::io::Error::last_os_error()), + 0 => Err(std::io::Error::new( + std::io::ErrorKind::UnexpectedEof, + "peer closed", + )), + _ => Ok((byte[0], fds)), + } +} + +/// One access unit, or the child's own error, read off the socket. +fn read_reply(sock: &mut UnixStream, au: &mut Vec) -> std::io::Result>> { + let (tag, _) = recv_tag(sock)?; + if tag == R_NONE { + return Ok(None); + } + let mut len = [0u8; 4]; + sock.read_exact(&mut len)?; + let len = u32::from_le_bytes(len) as usize; + au.clear(); + au.resize(len, 0); + sock.read_exact(au)?; + Ok(Some(match tag { + R_AU => Ok(()), + _ => Err(String::from_utf8_lossy(au).into_owned()), + })) +} + +/// Where the helper lives: told outright, or beside the running executable -- +/// which is `target//` for the editor and one directory up from +/// `deps/` for a test binary. +fn child_bin() -> Option { + if let Some(pinned) = std::env::var_os("VE_HW_CHILD_BIN") { + return Some(PathBuf::from(pinned)); + } + let exe = std::env::current_exe().ok()?; + let dir = exe.parent()?.to_path_buf(); + [dir.join(BIN), dir.parent()?.join(BIN)] + .into_iter() + .find(|candidate| candidate.is_file()) +} + +/// Whether an isolated encoder can be had at all -- a helper to run. `false` +/// leaves the caller on the in-process seat, which is what a build that did not +/// produce the helper has always had. +pub fn available() -> bool { + child_bin().is_some() +} + +/// The test-only stand-in seat: a child that opens no driver at all, so the +/// containment paths below can be exercised on a machine whose GPU is wedged -- +/// which is the only machine where they matter and the only one where the real +/// trigger cannot be pulled. +pub fn faked() -> bool { + std::env::var_os("VE_HW_TEST_FAKE").is_some() +} + +/// A hardware encode session living in another process. +pub struct Remote { + child: Child, + sock: UnixStream, + shm: Shm, + open: Open, + /// The last access unit, owned here: the child's buffer is in the child. + au: Vec, + /// Set the moment the child is known gone, so every later call refuses in + /// the same words instead of blocking on a socket nobody holds. + lost: Option, +} + +impl Remote { + /// How long the child may take over one call before it is treated as hung. + /// A wedged ring does not always `abort()` -- it can simply stop -- and a + /// timeout is the only thing that tells those apart from a slow frame. + fn timeout() -> Duration { + let ms = std::env::var("VE_HW_TIMEOUT_MS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(15_000); + Duration::from_millis(ms) + } + + /// Starts a child on this seat. `None` is the plugin's own "no" carried + /// across the process boundary -- no driver, no entrypoint, a size refused + /// -- and the caller takes the software encoder exactly as it always did. + pub fn spawn(open: Open) -> Option { + let bin = child_bin()?; + let (mine, theirs) = UnixStream::pair().ok()?; + mine.set_read_timeout(Some(Self::timeout())).ok()?; + // The socket is the child's stdin, which is how it crosses `exec` + // without a `pre_exec` of our own. Its stdout and stderr stay ours, so + // whatever the driver prints is still in the editor's log. + let child = Command::new(bin) + .args(open.argv()) + .stdin(Stdio::from(OwnedFd::from(theirs))) + .spawn() + .ok()?; + let mut remote = Self { + child, + sock: mine, + // Replaced by the child's own mapping below; a zero-length one + // allocates nothing and keeps the field non-optional. + shm: Shm::empty(), + open, + au: Vec::new(), + lost: None, + }; + // The child answers once its encoder is open: a byte, and with it the + // descriptor of the staging buffer it made for this session's size. + match recv_tag(&remote.sock) { + Ok((1, fds)) if fds.len() == 1 => { + remote.shm = Shm::map(fds[0].as_raw_fd(), open.frame_bytes()).ok()?; + Some(remote) + } + // Anything else is "no seat here", including a child that died + // opening the driver -- which is the crash this whole module exists + // for, and it costs an export nothing but the software encoder. + _ => None, + } + } + + /// 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 mut buf = [0u8; 8]; + 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. + pub fn encode( + &mut self, + y: &[u8], + u: &[u8], + v: &[u8], + width: u32, + height: u32, + force_key: bool, + ) -> crate::Result> { + let total = y.len() + u.len() + v.len(); + if total > self.shm.len { + return Err(format!( + "a {width}x{height} picture does not fit the staging buffer opened for {}x{}", + self.open.width, self.open.height + ) + .into()); + } + let bytes = self.shm.bytes(); + bytes[..y.len()].copy_from_slice(y); + bytes[y.len()..y.len() + u.len()].copy_from_slice(u); + bytes[y.len() + u.len()..total].copy_from_slice(v); + let mut msg = vec![T_ENCODE]; + msg.extend_from_slice(&width.to_le_bytes()); + msg.extend_from_slice(&height.to_le_bytes()); + msg.push(u8::from(force_key)); + self.round_trip(&msg, &[]) + } + + /// Feeds one picture the decoder left on the GPU. The descriptors go over + /// with the message, so the buffer itself never moves. + pub fn encode_dma(&mut self, dma: &VhDma, force_key: bool) -> crate::Result> { + let fds: Vec = dma.fd.iter().copied().filter(|&fd| fd >= 0).collect(); + let mut msg = vec![T_DMA]; + msg.extend_from_slice(&dma.fourcc.to_le_bytes()); + msg.extend_from_slice(&dma.modifier.to_le_bytes()); + for value in [ + dma.coded_width, + dma.coded_height, + dma.width, + dma.height, + dma.offset[0], + dma.offset[1], + dma.stride[0], + dma.stride[1], + ] { + msg.extend_from_slice(&value.to_le_bytes()); + } + msg.push(fds.len() as u8); + msg.push(u8::from(force_key)); + self.round_trip(&msg, &fds) + } + + /// Flushes the child's encoder; call until it answers `None`. + pub fn drain(&mut self) -> crate::Result> { + self.round_trip(&[T_DRAIN], &[]) + } + + /// One request and its reply, which is every call above: the child is fed, + /// then read, and anything that is not an answer is the child being gone. + fn round_trip(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result> { + self.request(msg, fds)?; + let mut au = std::mem::take(&mut self.au); + let read = read_reply(&mut self.sock, &mut au); + self.au = au; + // Every "no access unit" leaves through a `return`, so the borrow of the + // buffer below is the only one alive when it is taken. + match read { + Ok(None) => return Ok(None), + Ok(Some(Ok(()))) => {} + // The child's *own* refusal: it is alive and said no, so this is an + // ordinary encode error and the process stays as it is. + Ok(Some(Err(message))) => return Err(message.into()), + Err(e) => return Err(self.bury(&e.to_string())), + } + Ok(Some(&self.au)) + } + + fn request(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<()> { + if let Some(gone) = &self.lost { + return Err(gone.clone().into()); + } + match send_msg(&self.sock, msg, fds) { + Ok(()) => Ok(()), + Err(e) => Err(self.bury(&e.to_string())), + } + } + + /// Reaps the child and remembers why, so no later call waits on it. Kills + /// first: the child may be *stuck* rather than dead, which is the hang this + /// timeout exists to contain, and a stuck child is never waited for. + fn bury(&mut self, why: &str) -> crate::Error { + let _ = self.child.kill(); + let status = self.child.wait().ok(); + // The two shapes a wedged ring takes, told apart by who did the + // killing: a driver that called `abort()` leaves its own signal, while + // a child that merely stopped answering is still holding `SIGKILL` from + // the line above and the read's own timeout is the real reason. + let how = match status.and_then(|s| std::os::unix::process::ExitStatusExt::signal(&s)) { + Some(libc::SIGKILL) | None => format!("stopped answering ({why}) and was killed"), + Some(signal) => format!("was killed by signal {signal}"), + }; + let message = + format!("{HW_LOST} {how}; the driver took it down and not the editor"); + self.lost = Some(message.clone()); + message.into() + } +} + +impl Drop for Remote { + fn drop(&mut self) { + // Nothing is pending -- the export drains before it drops -- and a + // signal is the one exit a wedged child is guaranteed to take. + if self.lost.is_none() { + let _ = self.child.kill(); + let _ = self.child.wait(); + } + } +} + +// As the in-process session: one thread at a time (the export worker). +unsafe impl Send for Remote {} + +#[cfg(test)] +mod tests { + use super::*; + + /// Descriptors really cross the socket, and the mapping really is shared: + /// the two halves of the frame hand-off, checked without a driver. + #[test] + fn a_mapping_and_its_descriptor_cross_a_socket() { + let (a, b) = UnixStream::pair().expect("socketpair"); + let (mut mine, fd) = Shm::create(64).expect("memfd"); + mine.bytes()[..5].copy_from_slice(b"hello"); + send_msg(&a, &[7u8], &[fd.as_raw_fd()]).expect("send"); + let (tag, fds) = recv_tag(&b).expect("recv"); + assert_eq!(tag, 7); + assert_eq!(fds.len(), 1, "the descriptor came over"); + let mut theirs = Shm::map(fds[0].as_raw_fd(), 64).expect("map the received descriptor"); + assert_eq!(&theirs.bytes()[..5], b"hello", "one store, two mappings"); + theirs.bytes()[0] = b'j'; + assert_eq!(&mine.bytes()[..5], b"jello", "and it is shared both ways"); + } + + /// A dead peer must come back as an error, never as a `SIGPIPE` that kills + /// the process doing the sending -- the whole point of `MSG_NOSIGNAL`. + #[test] + fn sending_to_a_closed_socket_errors_instead_of_signalling() { + let (a, b) = UnixStream::pair().expect("socketpair"); + drop(b); + assert!(send_msg(&a, &[1u8, 2, 3], &[]).is_err()); + } + + /// The open crosses to the child as text and comes back the same struct. + #[test] + fn an_open_round_trips_through_argv() { + let open = Open { + seat: Seat::Hevc, + width: 1920, + height: 1080, + fps_num: 30000, + fps_den: 1001, + bitrate: 12_345_678, + colour: ColorDescription { + matrix: Matrix::Bt2020Ncl, + transfer: Transfer::Pq, + full_range: true, + }, + }; + let back = Open::from_argv(&open.argv()).expect("parse"); + assert!(back.seat == Seat::Hevc); + assert_eq!( + (back.width, back.height, back.fps_num, back.fps_den, back.bitrate), + (1920, 1080, 30000, 1001, 12_345_678) + ); + assert_eq!(back.colour, open.colour); + assert_eq!(back.frame_bytes(), 1920 * 1080 * 3 / 2); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 711ede7..be01647 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -13,6 +13,7 @@ pub mod edith; pub mod eq; pub mod export; pub mod hw; +pub mod hwproc; pub mod limiter; pub mod mux; pub mod playback; diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index fce57a4..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; }; @@ -1158,3 +1183,255 @@ fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() { assert!(!part_path(&out).exists(), "a cancelled proxy left its .part"); assert_eq!(engine::proxy::cached(&film), None); } + +// --------------------------------------------------------------------------- +// The hardware encoder's process dying under the driver. +// +// Mesa's radeonsi calls libc `abort()` from its own C worker thread when the +// video ring resets under it, which no `catch_unwind` in the process can see: +// on 2026-08-13 that killed the editor mid-export and took the session with it. +// The encoder now lives in a child (`engine::hwproc`), and these are the proof +// that its death is an inconvenience rather than a crash. +// +// None of them needs a GPU, and that is deliberate: the machine where this +// matters is the one whose ring is already wedged, and a test that had to hang a +// real ring to run could never be the oracle for the fix. `VE_HW_TEST_FAKE` +// 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 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 { + 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 + // answering and the wait is the thing under test. + std::env::set_var("VE_HW_TIMEOUT_MS", "1500"); + match abort { + Some(at) => std::env::set_var("VE_HW_TEST_ABORT", at), + None => std::env::remove_var("VE_HW_TEST_ABORT"), + } + match hang { + Some(at) => std::env::set_var("VE_HW_TEST_HANG", at), + None => std::env::remove_var("VE_HW_TEST_HANG"), + } + } + let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)); + unsafe { + for var in [ + "VE_HW_TEST_FAKE", + "VE_HW_CHILD_BIN", + "VE_HW_TIMEOUT_MS", + "VE_HW_TEST_ABORT", + "VE_HW_TEST_HANG", + ] { + 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, + Err(panic) => std::panic::resume_unwind(panic), + } +} + +/// The timeline these all export: short, and cut, so the export really runs a +/// span loop rather than copying one clip. +fn short_edit(source: &Path, frames: u32) -> (Project, engine::VideoMeta) { + let (meta, _) = engine::demux::Demuxer::open(source).expect("open source"); + let mut project = Project::single(source, meta.frame_count); + assert!(project.split(frames)); + assert!(project.delete(1)); + assert_eq!(project.timeline_frames(), frames); + (project, meta) +} + +/// A whole export whose hardware encoder is killed three frames in: the editor +/// is still here, and so is the file -- written again, from the first frame, by +/// the software encoder for the same codec, and clean enough that an outside +/// decoder reads every packet of it without a word. +/// +/// Invariant 1 at its entry surface: `export::start` is what the export card +/// 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() { + let source = asset("test_baseline.mp4"); + let (project, meta) = short_edit(&source, 20); + let out = out_path("hw_child_abort"); + + injected(Some("3"), None, || { + // `Auto` is what an untouched export card sends: the seat that *may* + // fall back, which is the whole question here. + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(180)).expect("the export survived its encoder"); + }); + + let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); + assert_eq!(written.frame_count, 20, "every timeline frame was written"); + assert_eq!(decode_all(&out).len(), 20, "and every one of them decodes"); + if let Some(said) = ffmpeg_complaints(&out) { + assert!( + said.is_empty(), + "ffmpeg read the fallback's file badly: {said}" + ); + } + assert!(!part_path(&out).exists(), "the .part outlived the export"); + std::fs::remove_file(&out).unwrap(); +} + +/// The same death at the *open*: the child never gets far enough to say yes, so +/// there is no hardware seat at all and the software one takes the export from +/// 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() { + let source = asset("test_baseline.mp4"); + let (project, meta) = short_edit(&source, 12); + let out = out_path("hw_child_abort_init"); + + injected(Some("init"), None, || { + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(180)).expect("the export survived the open"); + }); + + let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); + assert_eq!(written.frame_count, 12); + std::fs::remove_file(&out).unwrap(); +} + +/// ...and at the finalize, which is the third place a ring resets: every +/// 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() { + let source = asset("test_baseline.mp4"); + let (project, meta) = short_edit(&source, 12); + let out = out_path("hw_child_abort_drain"); + + injected(Some("drain"), None, || { + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(180)).expect("the export survived the drain"); + }); + + let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); + assert_eq!(written.frame_count, 12); + assert_eq!(decode_all(&out).len(), 12); + std::fs::remove_file(&out).unwrap(); +} + +/// Invariant 4: a ring can wedge *without* anything dying -- the child stays +/// alive and simply stops answering. The parent gives it `VE_HW_TIMEOUT_MS` and +/// then kills it, which lands on the same fallback a death does. "Contained" +/// here means bounded, so the wait is what is really being measured: an export +/// 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() { + let source = asset("test_baseline.mp4"); + let (project, meta) = short_edit(&source, 12); + let out = out_path("hw_child_hang"); + + let started = Instant::now(); + injected(None, Some("2"), || { + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); + wait(&handle, Duration::from_secs(180)).expect("the export outlived the wedge"); + }); + println!( + "hung child: contained in {:.2} s", + started.elapsed().as_secs_f64() + ); + + let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); + assert_eq!(written.frame_count, 12); + assert_eq!(decode_all(&out).len(), 12); + 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 +/// of blocking on a socket nobody holds, and the process doing the asking is +/// still running to be asked. +#[test] +fn a_dead_encoder_answers_every_later_call_the_same_way() { + let (width, height) = (320u32, 240u32); + injected(Some("1"), None, || { + let mut encoder = + HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened"); + let (y, u, v) = synthetic(0, width as usize, height as usize); + assert!( + encoder.encode(&y, &u, &v, width, height, false).is_ok(), + "the first picture is before the injection point" + ); + let died = encoder + .encode(&y, &u, &v, width, height, false) + .expect_err("the second picture kills the child"); + assert!( + engine::hwproc::is_lost(&died), + "an encoder death must say so: {died}" + ); + // The second ask is the one that would hang if the child were not + // reaped, and it must not spend the timeout answering either. + let again = Instant::now(); + let repeat = encoder.drain().expect_err("the seat stays dead"); + assert!(engine::hwproc::is_lost(&repeat), "{repeat}"); + assert!( + again.elapsed() < Duration::from_millis(500), + "a dead seat answered only after waiting" + ); + }); +} diff --git a/crates/engine/tests/hw_encode.rs b/crates/engine/tests/hw_encode.rs index 94eabda..7ffcaf9 100644 --- a/crates/engine/tests/hw_encode.rs +++ b/crates/engine/tests/hw_encode.rs @@ -216,6 +216,56 @@ fn a_decoded_buffer_is_encoded_without_ever_being_read_back() { } } +/// What the process boundary costs, at the size an export is really written at. +/// +/// The encoder lives in a child now ([`engine::hwproc`]) so that a driver's +/// `abort()` cannot take the editor with it, and the price of that has to be +/// small enough that nobody would trade it back: pictures reach the child +/// through a shared mapping rather than down a pipe, so a frame costs one +/// `memcpy` and a ten-byte message. `VE_HW_INPROCESS` pins the seat the way it +/// used to be, which is the only honest baseline there is. +/// +/// This is the *worst* case on purpose: an untouched clip's pictures never leave +/// the GPU at all (`a_decoded_buffer_is_encoded_without_ever_being_read_back`, +/// whose descriptors cross the same socket), so nothing an export really does is +/// slower than this. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with an H.264 encode entrypoint"] +fn isolating_the_encoder_costs_little_at_1080p() { + const FRAMES: u32 = 60; + let (width, height) = (1920u32, 1080u32); + let mut spent = Vec::new(); + for inprocess in [true, false] { + // SAFETY-of-a-sort: the ignored run is `--test-threads=1`, which is + // what this file's own header already requires of its env pins. + unsafe { + match inprocess { + true => std::env::set_var("VE_HW_INPROCESS", "1"), + false => std::env::remove_var("VE_HW_INPROCESS"), + } + } + let started = Instant::now(); + let Some((_, units)) = encode(width, height, FRAMES) else { + println!("no hardware encoder here -- skipping"); + return; + }; + assert_eq!(units, FRAMES, "one access unit per fed picture"); + spent.push(started.elapsed().as_secs_f64()); + } + let (local, remote) = (spent[0], spent[1]); + println!( + "1080p x{FRAMES}: in-process {:.1} fps, isolated {:.1} fps ({:.0}% of it)", + f64::from(FRAMES) / local, + f64::from(FRAMES) / remote, + 100.0 * local / remote + ); + assert!( + local / remote >= 0.85, + "isolation kept only {:.0}% of the in-process rate", + 100.0 * local / remote + ); +} + /// Decode and encode resolve through two independent symbol tables, so an /// encoder that cannot load must not cost us the decoder (and vice versa). ///