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..d4e4425 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -6,9 +6,21 @@ //! 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 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)). +//! +//! 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 50f1ed8..352d6f3 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)); @@ -583,7 +609,14 @@ 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> { - if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") { + // `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()) + { return Ok(None); } let opened = open_hw_seat(meta, settings); @@ -3547,7 +3580,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..a8b33c6 --- /dev/null +++ b/crates/engine/src/hwproc.rs @@ -0,0 +1,657 @@ +//! 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. + 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()?), + )) + } + + /// 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..8809147 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -1158,3 +1158,206 @@ 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 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. +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()); + unsafe { + 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); + } + } + 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() { + pin_software(); + 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() { + pin_software(); + 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() { + pin_software(); + 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() { + pin_software(); + 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(); +} + +/// 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). ///