Merge branch 'worktree-agent-ab451a54bd7e67440'
Browse files at this commit10 changed files +1603 -40
- Cargo.lock +1 -0
- crates/engine-hw/src/lib.rs +17 -3
- crates/engine/Cargo.toml +6 -0
- crates/engine/src/bin/hw-encode-child.rs +262 -0
- crates/engine/src/export.rs +30 -2
- crates/engine/src/hw.rs +269 -15
- crates/engine/src/hwproc.rs +670 -0
- crates/engine/src/lib.rs +1 -0
- crates/engine/tests/export.rs +297 -20
- crates/engine/tests/hw_encode.rs +50 -0
Cargo.lockmodified+1 -0
| @@ -1639,6 +1639,7 @@ dependencies = [ | ||
| 1639 | 1639 | "flacenc", |
| 1640 | 1640 | "hound", |
| 1641 | 1641 | "image", |
| 1642 | + "libc", | |
| 1642 | 1643 | "libloading", |
| 1643 | 1644 | "miniz_oxide", |
| 1644 | 1645 | "mp4", |
crates/engine-hw/src/lib.rsmodified+17 -3
| @@ -6,9 +6,23 @@ | ||
| 6 | 6 | //! negative code: the caller's contract is "any failure means use the software |
| 7 | 7 | //! codec". |
| 8 | 8 | //! |
| 9 | -//! corner-cut: that guarantee rests on `panic = "unwind"`. Building this crate with | |
| 10 | -//! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path | |
| 11 | -//! is running the decoder in a child process instead of in-process. | |
| 9 | +//! That guarantee rests on `panic = "unwind"`, and it has a floor it can never | |
| 10 | +//! reach whatever the panic strategy is: Mesa runs its own C worker threads and | |
| 11 | +//! calls libc `abort()` from them when the video ring resets (measured | |
| 12 | +//! 2026-08-13, `vcn_unified_0`, mesa 26.1.6). No `catch_unwind` can see a | |
| 13 | +//! foreign thread's `abort`. So no *encode* entry point of this plugin is | |
| 14 | +//! called in the editor's process any more: the editor still `dlopen`s the | |
| 15 | +//! library to see whether the `vh_enc_*` symbols are there at all, which opens | |
| 16 | +//! no VA-API display and starts no driver thread, and every call through them is | |
| 17 | +//! made by the `hw-encode-child` helper, one process per session. A driver that | |
| 18 | +//! aborts now costs an export its seat rather than costing a person their | |
| 19 | +//! session ([`engine::hwproc`](../engine/hwproc/index.html)). | |
| 20 | +//! | |
| 21 | +//! corner-cut: *decode* is still in the editor's own address space, where the | |
| 22 | +//! same abort would still be fatal -- and the same ring hangs it (mmhub page | |
| 23 | +//! faults, this box, 2026-08-13). The upgrade path is the seam that already | |
| 24 | +//! exists: give `vh_open_at`/`vh_next_frame` the message tags `vh_enc_*` have in | |
| 25 | +//! `hwproc` and let the same helper hold both. | |
| 12 | 26 | |
| 13 | 27 | use std::collections::VecDeque; |
| 14 | 28 | use std::ffi::{CStr, c_char, c_void}; |
crates/engine/Cargo.tomlmodified+6 -0
| @@ -12,6 +12,12 @@ edition.workspace = true | ||
| 12 | 12 | hound = "3.5.1" |
| 13 | 13 | flacenc = { version = "0.5.1", default-features = false } |
| 14 | 14 | libloading = "0.8" |
| 15 | +# `memfd_create`, `mmap` and `SCM_RIGHTS` -- the three things std has no door to | |
| 16 | +# and the whole of what puts the video driver in another process | |
| 17 | +# (`crate::hwproc`). Not a new crate tree: it was already in this workspace's | |
| 18 | +# lock file, pulled in by half the dependencies here, so this line compiles | |
| 19 | +# nothing that was not compiled before. | |
| 20 | +libc = "0.2" | |
| 15 | 21 | # Still images, decoded once per placed clip (`decode::Still`). Pure Rust like |
| 16 | 22 | # everything else here, and already in the app's tree (gpui pulls it), so this |
| 17 | 23 | # costs the build nothing new. Exactly the formats `crate::is_image` admits: no |
crates/engine/src/bin/hw-encode-child.rsadded+262 -0
| @@ -0,0 +1,262 @@ | ||
| 1 | +//! The process that holds the video driver, and therefore the process a video | |
| 2 | +//! driver is allowed to kill. | |
| 3 | +//! | |
| 4 | +//! It is started by [`engine::hwproc::Remote::spawn`] with the encode session's | |
| 5 | +//! parameters as argv and one end of a socket pair as its standard input. It | |
| 6 | +//! opens the plugin's encoder in *this* address space, hands the parent a shared | |
| 7 | +//! anonymous file to stage pictures in, and then answers one request at a time | |
| 8 | +//! until the socket closes. Nothing else lives here: no project, no muxer, no | |
| 9 | +//! window -- so an `abort()` out of Mesa's own worker thread costs the editor a | |
| 10 | +//! reply and a fallback rather than the session. | |
| 11 | +//! | |
| 12 | +//! Three environment variables exist only for the tests that prove that, and | |
| 13 | +//! each is read here and nowhere else, so an editor without them set runs the | |
| 14 | +//! path it always ran: | |
| 15 | +//! | |
| 16 | +//! * `VE_HW_TEST_FAKE` -- open a stand-in seat that touches no driver, so the | |
| 17 | +//! containment paths can be exercised on a machine whose GPU is wedged (which | |
| 18 | +//! is the only machine where they matter). Refuses to open unless one of the | |
| 19 | +//! two below is set with it, so it can never be a silently empty encoder. | |
| 20 | +//! * `VE_HW_TEST_ABORT=<init|drain|N>` -- call `abort()` from a worker thread of | |
| 21 | +//! our own, before opening, at the first drain, or before coding picture `N`. | |
| 22 | +//! A foreign C thread's `abort()` is what really happened on 2026-08-13; this | |
| 23 | +//! is the same shape without a hung ring. | |
| 24 | +//! * `VE_HW_TEST_HANG=<init|drain|N>` -- stop answering at that same point, | |
| 25 | +//! without dying, which is the other half of a wedged ring. | |
| 26 | + | |
| 27 | +use std::io::{Read, Write}; | |
| 28 | +use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd}; | |
| 29 | +use std::os::unix::net::UnixStream; | |
| 30 | + | |
| 31 | +use engine::hw::{DmaFrame, LocalEncoder, VhDma}; | |
| 32 | +use engine::hwproc::{Open, R_AU, R_ERR, R_NONE, Shm, T_DMA, T_DRAIN, T_ENCODE, T_GEOM, recv_tag, send_msg}; | |
| 33 | + | |
| 34 | +/// Where the encoder actually is: the plugin's, or the test stand-in that opens | |
| 35 | +/// no driver at all. | |
| 36 | +enum Seat { | |
| 37 | + Real(LocalEncoder), | |
| 38 | + Fake, | |
| 39 | +} | |
| 40 | + | |
| 41 | +impl Seat { | |
| 42 | + fn dma_geometry(&self) -> Option<(u32, u32)> { | |
| 43 | + match self { | |
| 44 | + Self::Real(encoder) => encoder.dma_geometry(), | |
| 45 | + // Nothing to import into, so the parent stages pictures instead -- | |
| 46 | + // which is the path the containment tests want anyway. | |
| 47 | + Self::Fake => None, | |
| 48 | + } | |
| 49 | + } | |
| 50 | +} | |
| 51 | + | |
| 52 | +/// One of the three injection points, named the same way in all three variables. | |
| 53 | +#[derive(PartialEq, Eq)] | |
| 54 | +enum At { | |
| 55 | + Init, | |
| 56 | + Drain, | |
| 57 | + Frame(u32), | |
| 58 | +} | |
| 59 | + | |
| 60 | +fn injected(var: &str) -> Option<At> { | |
| 61 | + let value = std::env::var(var).ok()?; | |
| 62 | + Some(match value.as_str() { | |
| 63 | + "init" => At::Init, | |
| 64 | + "drain" => At::Drain, | |
| 65 | + _ => At::Frame(value.parse().ok()?), | |
| 66 | + }) | |
| 67 | +} | |
| 68 | + | |
| 69 | +/// The driver's own way of dying, reproduced: `abort()` called from a thread | |
| 70 | +/// that is not the one running the encode, because that is where | |
| 71 | +/// `amdgpu_ctx_set_sw_reset_status` calls it from and because a `catch_unwind` | |
| 72 | +/// around the encode call is exactly what cannot see it. | |
| 73 | +fn die() { | |
| 74 | + std::thread::spawn(|| { | |
| 75 | + // SAFETY: `abort` takes nothing, returns never, and is the whole point. | |
| 76 | + unsafe { libc::abort() } | |
| 77 | + }); | |
| 78 | + loop { | |
| 79 | + std::thread::park(); | |
| 80 | + } | |
| 81 | +} | |
| 82 | + | |
| 83 | +/// ...and the other half: alive, holding the socket open, answering nothing. | |
| 84 | +fn hang() -> ! { | |
| 85 | + loop { | |
| 86 | + std::thread::park(); | |
| 87 | + } | |
| 88 | +} | |
| 89 | + | |
| 90 | +fn reached(point: &At) { | |
| 91 | + if injected("VE_HW_TEST_ABORT").as_ref() == Some(point) { | |
| 92 | + die(); | |
| 93 | + } | |
| 94 | + if injected("VE_HW_TEST_HANG").as_ref() == Some(point) { | |
| 95 | + hang(); | |
| 96 | + } | |
| 97 | +} | |
| 98 | + | |
| 99 | +fn main() { | |
| 100 | + let args: Vec<String> = std::env::args().skip(1).collect(); | |
| 101 | + let Some(open) = Open::from_argv(&args) else { | |
| 102 | + eprintln!("hw-encode-child: bad arguments"); | |
| 103 | + std::process::exit(2); | |
| 104 | + }; | |
| 105 | + // SAFETY: the parent handed this process one end of a socket pair as its | |
| 106 | + // standard input and holds the other; nothing else in this process reads | |
| 107 | + // descriptor 0. | |
| 108 | + let mut sock = unsafe { UnixStream::from_raw_fd(0) }; | |
| 109 | + | |
| 110 | + reached(&At::Init); | |
| 111 | + let seat = match std::env::var_os("VE_HW_TEST_FAKE").is_some() { | |
| 112 | + // A stand-in that no test forgot to arm: without an injection point it | |
| 113 | + // would be an encoder producing nothing, and that is a hang of its own | |
| 114 | + // kind rather than a test. | |
| 115 | + true => match injected("VE_HW_TEST_ABORT").is_some() || injected("VE_HW_TEST_HANG").is_some() | |
| 116 | + { | |
| 117 | + true => Some(Seat::Fake), | |
| 118 | + false => None, | |
| 119 | + }, | |
| 120 | + false => LocalEncoder::open_seat(open).map(Seat::Real), | |
| 121 | + }; | |
| 122 | + let Some(mut seat) = seat else { | |
| 123 | + // The plugin's own "no", carried back as a byte: no driver, no | |
| 124 | + // entrypoint, a size refused. The parent takes the software encoder. | |
| 125 | + let _ = sock.write_all(&[0u8]); | |
| 126 | + std::process::exit(1); | |
| 127 | + }; | |
| 128 | + | |
| 129 | + // The staging buffer for pictures that live in memory: made here because | |
| 130 | + // this side knows the session's size, and handed over with the "yes". | |
| 131 | + let (mut shm, fd) = match Shm::create(open.frame_bytes()) { | |
| 132 | + Ok(pair) => pair, | |
| 133 | + Err(e) => { | |
| 134 | + eprintln!("hw-encode-child: no staging buffer: {e}"); | |
| 135 | + let _ = sock.write_all(&[0u8]); | |
| 136 | + std::process::exit(1); | |
| 137 | + } | |
| 138 | + }; | |
| 139 | + if send_msg(&sock, &[1u8], &[fd.as_raw_fd()]).is_err() { | |
| 140 | + std::process::exit(1); | |
| 141 | + } | |
| 142 | + drop(fd); | |
| 143 | + | |
| 144 | + let mut coded = 0u32; | |
| 145 | + loop { | |
| 146 | + let Ok((tag, fds)) = recv_tag(&sock) else { | |
| 147 | + // The parent is gone (it closed, or it died): there is nothing left | |
| 148 | + // to encode for. | |
| 149 | + return; | |
| 150 | + }; | |
| 151 | + match tag { | |
| 152 | + T_GEOM => match seat.dma_geometry() { | |
| 153 | + Some((width, height)) => { | |
| 154 | + let mut reply = vec![R_AU]; | |
| 155 | + reply.extend_from_slice(&width.to_le_bytes()); | |
| 156 | + reply.extend_from_slice(&height.to_le_bytes()); | |
| 157 | + let _ = sock.write_all(&reply); | |
| 158 | + } | |
| 159 | + None => { | |
| 160 | + let _ = sock.write_all(&[R_NONE]); | |
| 161 | + } | |
| 162 | + }, | |
| 163 | + T_ENCODE => { | |
| 164 | + let mut head = [0u8; 9]; | |
| 165 | + if sock.read_exact(&mut head).is_err() { | |
| 166 | + return; | |
| 167 | + } | |
| 168 | + reached(&At::Frame(coded)); | |
| 169 | + coded += 1; | |
| 170 | + let width = u32::from_le_bytes(head[0..4].try_into().expect("four bytes")); | |
| 171 | + let height = u32::from_le_bytes(head[4..8].try_into().expect("four bytes")); | |
| 172 | + let force_key = head[8] != 0; | |
| 173 | + let (w, h) = (width as usize, height as usize); | |
| 174 | + let chroma = w.div_ceil(2) * h.div_ceil(2); | |
| 175 | + let answer = match &mut seat { | |
| 176 | + Seat::Real(encoder) => { | |
| 177 | + let bytes = shm.bytes(); | |
| 178 | + let (y, rest) = bytes.split_at(w * h); | |
| 179 | + let (u, rest) = rest.split_at(chroma); | |
| 180 | + encoder.encode(y, u, &rest[..chroma], width, height, force_key) | |
| 181 | + } | |
| 182 | + Seat::Fake => Ok(None), | |
| 183 | + }; | |
| 184 | + if !reply(&mut sock, answer) { | |
| 185 | + return; | |
| 186 | + } | |
| 187 | + } | |
| 188 | + T_DMA => { | |
| 189 | + let mut head = [0u8; 46]; | |
| 190 | + if sock.read_exact(&mut head).is_err() { | |
| 191 | + return; | |
| 192 | + } | |
| 193 | + reached(&At::Frame(coded)); | |
| 194 | + coded += 1; | |
| 195 | + let u32_at = |offset: usize| { | |
| 196 | + u32::from_le_bytes(head[offset..offset + 4].try_into().expect("four bytes")) | |
| 197 | + }; | |
| 198 | + let mut desc = VhDma { | |
| 199 | + fourcc: u32_at(0), | |
| 200 | + modifier: u64::from_le_bytes(head[4..12].try_into().expect("eight bytes")), | |
| 201 | + coded_width: u32_at(12), | |
| 202 | + coded_height: u32_at(16), | |
| 203 | + width: u32_at(20), | |
| 204 | + height: u32_at(24), | |
| 205 | + offset: [u32_at(28), u32_at(32)], | |
| 206 | + stride: [u32_at(36), u32_at(40)], | |
| 207 | + fd: [-1, -1], | |
| 208 | + }; | |
| 209 | + if fds.len() != head[44] as usize || fds.is_empty() { | |
| 210 | + let _ = write_error(&mut sock, "a buffer arrived without its descriptors"); | |
| 211 | + continue; | |
| 212 | + } | |
| 213 | + // Ownership passes to the frame, which closes them: the parent | |
| 214 | + // kept its own copies and these are ours. | |
| 215 | + for (slot, fd) in desc.fd.iter_mut().zip(fds) { | |
| 216 | + *slot = fd.into_raw_fd(); | |
| 217 | + } | |
| 218 | + let frame = DmaFrame::from_desc(desc); | |
| 219 | + let answer = match &mut seat { | |
| 220 | + Seat::Real(encoder) => encoder.encode_dma(&frame, head[45] != 0), | |
| 221 | + Seat::Fake => Ok(None), | |
| 222 | + }; | |
| 223 | + if !reply(&mut sock, answer) { | |
| 224 | + return; | |
| 225 | + } | |
| 226 | + } | |
| 227 | + T_DRAIN => { | |
| 228 | + reached(&At::Drain); | |
| 229 | + let answer = match &mut seat { | |
| 230 | + Seat::Real(encoder) => encoder.drain(), | |
| 231 | + Seat::Fake => Ok(None), | |
| 232 | + }; | |
| 233 | + if !reply(&mut sock, answer) { | |
| 234 | + return; | |
| 235 | + } | |
| 236 | + } | |
| 237 | + _ => return, | |
| 238 | + } | |
| 239 | + } | |
| 240 | +} | |
| 241 | + | |
| 242 | +/// Writes one answer back. `false` means the parent is gone and this process has | |
| 243 | +/// nothing left to do. | |
| 244 | +fn reply(sock: &mut UnixStream, answer: engine::Result<Option<&[u8]>>) -> bool { | |
| 245 | + match answer { | |
| 246 | + Ok(None) => sock.write_all(&[R_NONE]).is_ok(), | |
| 247 | + Ok(Some(au)) => { | |
| 248 | + let mut head = vec![R_AU]; | |
| 249 | + head.extend_from_slice(&(au.len() as u32).to_le_bytes()); | |
| 250 | + sock.write_all(&head).is_ok() && sock.write_all(au).is_ok() | |
| 251 | + } | |
| 252 | + // The encoder's own refusal, not a death: the parent raises it as the | |
| 253 | + // export error it is and this process stays open. | |
| 254 | + Err(e) => write_error(sock, &e.to_string()), | |
| 255 | + } | |
| 256 | +} | |
| 257 | + | |
| 258 | +fn write_error(sock: &mut UnixStream, message: &str) -> bool { | |
| 259 | + let mut head = vec![R_ERR]; | |
| 260 | + head.extend_from_slice(&(message.len() as u32).to_le_bytes()); | |
| 261 | + sock.write_all(&head).is_ok() && sock.write_all(message.as_bytes()).is_ok() | |
| 262 | +} |
crates/engine/src/export.rsmodified+30 -2
| @@ -494,7 +494,33 @@ pub fn start( | ||
| 494 | 494 | format.name() |
| 495 | 495 | ) |
| 496 | 496 | .into()), |
| 497 | - format if format.has_video() => run(&project, &meta, &part, &worker, &settings), | |
| 497 | + format if format.has_video() => { | |
| 498 | + let first = run(&project, &meta, &part, &worker, &settings); | |
| 499 | + match first { | |
| 500 | + // The hardware encoder's *process* died under the driver | |
| 501 | + // ([`crate::hwproc`]) -- the editor is still here, and the | |
| 502 | + // file is still owed. Written again by the software encoder | |
| 503 | + // for this codec, from the first frame: the pictures the | |
| 504 | + // dead seat coded are not ones this one may continue from. | |
| 505 | + // | |
| 506 | + // Not where a person picked the GPU by name: that export | |
| 507 | + // refuses in words, the same answer [`hw_seat`] already | |
| 508 | + // gives a machine with no seat at all, rather than quietly | |
| 509 | + // spending an hour in an encoder nobody chose. | |
| 510 | + Err(e) | |
| 511 | + if crate::hwproc::is_lost(&e) | |
| 512 | + && settings.seat != EncoderSeat::Hardware => | |
| 513 | + { | |
| 514 | + eprintln!("export video: {e}; writing it again in software"); | |
| 515 | + let _ = std::fs::remove_file(&part); | |
| 516 | + worker.progress.store(0, Ordering::Relaxed); | |
| 517 | + let mut software = settings.clone(); | |
| 518 | + software.seat = EncoderSeat::Software; | |
| 519 | + run(&project, &meta, &part, &worker, &software) | |
| 520 | + } | |
| 521 | + other => other, | |
| 522 | + } | |
| 523 | + } | |
| 498 | 524 | _ => run_audio(&project, &meta, &part, &worker, &settings), |
| 499 | 525 | }; |
| 500 | 526 | let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)); |
| @@ -3587,7 +3613,9 @@ impl Enc { | ||
| 3587 | 3613 | /// person picks it by name because the vendored encoder reset this project's GPU |
| 3588 | 3614 | /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to |
| 3589 | 3615 | /// widen. |
| 3590 | - fn dma_want(&self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> { | |
| 3616 | + /// `&mut` because an isolated seat has to *ask* the process it lives in | |
| 3617 | + /// ([`crate::hwproc`]), which is a round trip on its socket. | |
| 3618 | + fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> { | |
| 3591 | 3619 | match self { |
| 3592 | 3620 | Self::Hw(hw) | Self::HevcHw(hw) => hw.dma_want(meta.width, meta.height), |
| 3593 | 3621 | _ => None, |
crates/engine/src/hw.rsmodified+269 -15
| @@ -123,6 +123,14 @@ impl Default for VhDma { | ||
| 123 | 123 | pub struct DmaFrame(VhDma); |
| 124 | 124 | |
| 125 | 125 | impl DmaFrame { |
| 126 | + /// Takes ownership of descriptors that arrived from somewhere other than a | |
| 127 | + /// decode session -- which is the `hw-encode-child` helper, receiving over | |
| 128 | + /// `SCM_RIGHTS` the very buffer the parent's decoder wrote into. | |
| 129 | + #[doc(hidden)] | |
| 130 | + pub fn from_desc(desc: VhDma) -> Self { | |
| 131 | + Self(desc) | |
| 132 | + } | |
| 133 | + | |
| 126 | 134 | pub fn width(&self) -> u32 { |
| 127 | 135 | self.0.width |
| 128 | 136 | } |
| @@ -504,13 +512,39 @@ fn load_enc() -> Option<EncPlugin> { | ||
| 504 | 512 | None |
| 505 | 513 | } |
| 506 | 514 | |
| 507 | -/// An open hardware encode session. Dropping it closes the plugin session. | |
| 508 | -pub struct HwEncoder { | |
| 515 | +/// An open hardware encode session **in this process**, which is the one thing | |
| 516 | +/// an editor must not have: the driver's own C threads `abort()` the process | |
| 517 | +/// they are in when the video ring resets ([`crate::hwproc`]). Public only so | |
| 518 | +/// that the `hw-encode-child` helper -- the process whose whole job is to be the | |
| 519 | +/// one that dies -- can open it; every other caller goes through [`HwEncoder`], | |
| 520 | +/// which is this seat held at arm's length. | |
| 521 | +/// | |
| 522 | +/// Dropping it closes the plugin session. | |
| 523 | +#[doc(hidden)] | |
| 524 | +pub struct LocalEncoder { | |
| 509 | 525 | plugin: &'static EncPlugin, |
| 510 | 526 | handle: *mut c_void, |
| 511 | 527 | } |
| 512 | 528 | |
| 513 | -impl HwEncoder { | |
| 529 | +impl LocalEncoder { | |
| 530 | + /// The four seats behind one argument, which is how the helper is told | |
| 531 | + /// which of them to open. | |
| 532 | + pub fn open_seat(open: crate::hwproc::Open) -> Option<Self> { | |
| 533 | + let (w, h, n, d, b) = ( | |
| 534 | + open.width, | |
| 535 | + open.height, | |
| 536 | + open.fps_num, | |
| 537 | + open.fps_den, | |
| 538 | + open.bitrate, | |
| 539 | + ); | |
| 540 | + match open.seat { | |
| 541 | + crate::hwproc::Seat::H264 => Self::open(w, h, n, d, b), | |
| 542 | + crate::hwproc::Seat::Intra => Self::open_intra(w, h, n, d, b), | |
| 543 | + crate::hwproc::Seat::Av1 => Self::open_av1(w, h, n, d, b), | |
| 544 | + crate::hwproc::Seat::Hevc => Self::open_hevc(w, h, n, d, b, open.colour), | |
| 545 | + } | |
| 546 | + } | |
| 547 | + | |
| 514 | 548 | /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded |
| 515 | 549 | /// at a constant `bitrate` bits per second. `None` whenever hardware encode |
| 516 | 550 | /// is unavailable -- plugin missing, plugin too old to export the encode |
| @@ -668,10 +702,10 @@ impl HwEncoder { | ||
| 668 | 702 | }) |
| 669 | 703 | } |
| 670 | 704 | |
| 671 | - /// What a decoded buffer must look like to reach this encoder without a | |
| 672 | - /// copy -- the surface size it codes in, plus the picture it was opened for | |
| 673 | - /// -- or `None` where the plugin has no zero-copy door at all. | |
| 674 | - pub fn dma_want(&self, width: u32, height: u32) -> Option<DmaWant> { | |
| 705 | + /// The surface size this seat codes in, or `None` where the plugin has no | |
| 706 | + /// zero-copy door at all. What [`HwEncoder::dma_want`] turns into the whole | |
| 707 | + /// description a decoder is asked for. | |
| 708 | + pub fn dma_geometry(&self) -> Option<(u32, u32)> { | |
| 675 | 709 | let geometry = self.plugin.dma_geometry?; |
| 676 | 710 | self.plugin.frame_dma?; |
| 677 | 711 | let (mut coded_width, mut coded_height) = (0u32, 0u32); |
| @@ -679,12 +713,7 @@ impl HwEncoder { | ||
| 679 | 713 | if unsafe { geometry(self.handle, &mut coded_width, &mut coded_height) } != 1 { |
| 680 | 714 | return None; |
| 681 | 715 | } |
| 682 | - Some(DmaWant { | |
| 683 | - coded_width, | |
| 684 | - coded_height, | |
| 685 | - width, | |
| 686 | - height, | |
| 687 | - }) | |
| 716 | + Some((coded_width, coded_height)) | |
| 688 | 717 | } |
| 689 | 718 | |
| 690 | 719 | /// Feeds one picture the decoder left on the GPU. Same answer and same |
| @@ -733,7 +762,7 @@ impl HwEncoder { | ||
| 733 | 762 | } |
| 734 | 763 | } |
| 735 | 764 | |
| 736 | -impl Drop for HwEncoder { | |
| 765 | +impl Drop for LocalEncoder { | |
| 737 | 766 | fn drop(&mut self) { |
| 738 | 767 | // SAFETY: `handle` came from `vh_enc_open` and is closed exactly once. |
| 739 | 768 | unsafe { (self.plugin.close)(self.handle) } |
| @@ -741,4 +770,229 @@ impl Drop for HwEncoder { | ||
| 741 | 770 | } |
| 742 | 771 | |
| 743 | 772 | // As `HwSession`: used from one thread at a time (the export worker). |
| 744 | -unsafe impl Send for HwEncoder {} | |
| 773 | +unsafe impl Send for LocalEncoder {} | |
| 774 | + | |
| 775 | +/// An open hardware encode session, **in a child process** wherever there is a | |
| 776 | +/// helper to run it in -- which is what keeps a driver's `abort()` off the | |
| 777 | +/// editor. See [`crate::hwproc`] for the whole of why. | |
| 778 | +/// | |
| 779 | +/// The API is the in-process one it replaced, call for call, so nothing in the | |
| 780 | +/// export loop knows which side of a process boundary the encoder is on. | |
| 781 | +pub enum HwEncoder { | |
| 782 | + /// The isolated seat, and the one every ordinary build takes. | |
| 783 | + Remote(crate::hwproc::Remote), | |
| 784 | + /// The seat as it was: taken only where there is no helper binary to run | |
| 785 | + /// (a build that produced the plugin and not the editor's own directory) or | |
| 786 | + /// where `VE_HW_INPROCESS` pins it, which is how the isolated path's cost is | |
| 787 | + /// measured against the path it replaced. | |
| 788 | + Local(LocalEncoder), | |
| 789 | +} | |
| 790 | + | |
| 791 | +impl HwEncoder { | |
| 792 | + /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded | |
| 793 | + /// at a constant `bitrate` bits per second. `None` whenever hardware encode | |
| 794 | + /// is unavailable -- plugin missing, plugin too old to export the encode | |
| 795 | + /// entry points, no driver, dimensions the driver refuses, *or a helper that | |
| 796 | + /// died opening any of it* -- and the caller falls back to the software | |
| 797 | + /// encoder. | |
| 798 | + pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> { | |
| 799 | + Self::seated( | |
| 800 | + crate::hwproc::Seat::H264, | |
| 801 | + width, | |
| 802 | + height, | |
| 803 | + fps_num, | |
| 804 | + fps_den, | |
| 805 | + bitrate, | |
| 806 | + ColorDescription::default(), | |
| 807 | + ) | |
| 808 | + } | |
| 809 | + | |
| 810 | + /// The same H.264 seat, **intra-only**: every picture comes back an IDR | |
| 811 | + /// with its own parameter sets, so every frame of the file is one a decoder | |
| 812 | + /// may be started from. What [`crate::proxy`] codes a stand-in with. | |
| 813 | + /// | |
| 814 | + /// `None` on everything [`HwEncoder::open`] answers `None` to *and* on a | |
| 815 | + /// plugin built before this seat existed -- and that `None` matters more | |
| 816 | + /// than the others: the caller must then take the software encoder, which | |
| 817 | + /// codes one frame a GOP, rather than the ordinary hardware seat, which | |
| 818 | + /// would write a long-GOP file under a name that promises otherwise. | |
| 819 | + pub fn open_intra( | |
| 820 | + width: u32, | |
| 821 | + height: u32, | |
| 822 | + fps_num: u32, | |
| 823 | + fps_den: u32, | |
| 824 | + bitrate: u64, | |
| 825 | + ) -> Option<Self> { | |
| 826 | + Self::seated( | |
| 827 | + crate::hwproc::Seat::Intra, | |
| 828 | + width, | |
| 829 | + height, | |
| 830 | + fps_num, | |
| 831 | + fps_den, | |
| 832 | + bitrate, | |
| 833 | + ColorDescription::default(), | |
| 834 | + ) | |
| 835 | + } | |
| 836 | + | |
| 837 | + /// The same, coding AV1 instead. `None` on everything [`HwEncoder::open`] | |
| 838 | + /// answers `None` to *and* on a plugin or a GPU with no AV1 encoder -- an | |
| 839 | + /// AV1 encode entrypoint is recent hardware, so this is the fallback that | |
| 840 | + /// really fires, and the caller's software AV1 encoder takes the export | |
| 841 | + /// without saying anything about it. | |
| 842 | + /// | |
| 843 | + /// The caller only reaches this when a person picked | |
| 844 | + /// [`crate::export::EncoderSeat::Hardware`] for an AV1 export: this is the | |
| 845 | + /// seat whose ring hang killed the editor on 2026-08-13, and it is now the | |
| 846 | + /// seat that kills a child instead. | |
| 847 | + pub fn open_av1( | |
| 848 | + width: u32, | |
| 849 | + height: u32, | |
| 850 | + fps_num: u32, | |
| 851 | + fps_den: u32, | |
| 852 | + bitrate: u64, | |
| 853 | + ) -> Option<Self> { | |
| 854 | + Self::seated( | |
| 855 | + crate::hwproc::Seat::Av1, | |
| 856 | + width, | |
| 857 | + height, | |
| 858 | + fps_num, | |
| 859 | + fps_den, | |
| 860 | + bitrate, | |
| 861 | + ColorDescription::default(), | |
| 862 | + ) | |
| 863 | + } | |
| 864 | + | |
| 865 | + /// The same, coding HEVC. Unlike the AV1 seat this is **not** behind an | |
| 866 | + /// opt-in: it is the default for an HEVC export, and what makes that safe is | |
| 867 | + /// that the pictures it codes are intra-only, which is the same file the | |
| 868 | + /// software seat writes ([`crate::export::Enc::open_hevc`]) and not the | |
| 869 | + /// GPU-resetting inter path AV1's opt-in exists for. | |
| 870 | + /// | |
| 871 | + /// `colour` is what the SPS will say the samples mean, and it is taken at | |
| 872 | + /// the open because the parameter sets are written when the sequence starts. | |
| 873 | + /// libavcodec's HEVC decoder overwrites a container's colour with the | |
| 874 | + /// bitstream's, so a seat that signalled nothing hands a player | |
| 875 | + /// "unspecified" -- BT.601 -- however the file is tagged. | |
| 876 | + pub fn open_hevc( | |
| 877 | + width: u32, | |
| 878 | + height: u32, | |
| 879 | + fps_num: u32, | |
| 880 | + fps_den: u32, | |
| 881 | + bitrate: u64, | |
| 882 | + colour: ColorDescription, | |
| 883 | + ) -> Option<Self> { | |
| 884 | + Self::seated( | |
| 885 | + crate::hwproc::Seat::Hevc, | |
| 886 | + width, | |
| 887 | + height, | |
| 888 | + fps_num, | |
| 889 | + fps_den, | |
| 890 | + bitrate, | |
| 891 | + colour, | |
| 892 | + ) | |
| 893 | + } | |
| 894 | + | |
| 895 | + /// Where the choice between the two seats is made, and the only place it is. | |
| 896 | + /// | |
| 897 | + /// A child is not started where there is nothing for it to open: with no | |
| 898 | + /// plugin on this machine the answer is `None` before a process is forked, | |
| 899 | + /// which is exactly what a plugin-less machine has always answered and at | |
| 900 | + /// the same cost. | |
| 901 | + fn seated( | |
| 902 | + seat: crate::hwproc::Seat, | |
| 903 | + width: u32, | |
| 904 | + height: u32, | |
| 905 | + fps_num: u32, | |
| 906 | + fps_den: u32, | |
| 907 | + bitrate: u64, | |
| 908 | + colour: ColorDescription, | |
| 909 | + ) -> Option<Self> { | |
| 910 | + let open = crate::hwproc::Open { | |
| 911 | + seat, | |
| 912 | + width, | |
| 913 | + height, | |
| 914 | + fps_num, | |
| 915 | + fps_den, | |
| 916 | + bitrate, | |
| 917 | + colour, | |
| 918 | + }; | |
| 919 | + if enc_plugin().is_none() && !crate::hwproc::faked() { | |
| 920 | + return None; | |
| 921 | + } | |
| 922 | + // corner-cut: a build with no helper beside the executable keeps the | |
| 923 | + // in-process seat rather than losing hardware encode outright, so a | |
| 924 | + // driver crash there is still fatal. The ceiling is packaging: ship | |
| 925 | + // `hw-encode-child` next to `edith` (cargo already does) and this arm is | |
| 926 | + // never taken. | |
| 927 | + if !crate::hwproc::available() || std::env::var_os("VE_HW_INPROCESS").is_some() { | |
| 928 | + return LocalEncoder::open_seat(open).map(Self::Local); | |
| 929 | + } | |
| 930 | + crate::hwproc::Remote::spawn(open).map(Self::Remote) | |
| 931 | + } | |
| 932 | + | |
| 933 | + /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has | |
| 934 | + /// not finished an access unit yet; the returned bytes are Annex-B and stay | |
| 935 | + /// valid until the next call on this session. | |
| 936 | + pub fn encode( | |
| 937 | + &mut self, | |
| 938 | + y: &[u8], | |
| 939 | + u: &[u8], | |
| 940 | + v: &[u8], | |
| 941 | + width: u32, | |
| 942 | + height: u32, | |
| 943 | + force_key: bool, | |
| 944 | + ) -> crate::Result<Option<&[u8]>> { | |
| 945 | + // Checked on this side of the boundary whichever seat has the picture: | |
| 946 | + // a caller's mistake is a caller's mistake, and the isolated seat must | |
| 947 | + // not turn one into a message about a dead child. | |
| 948 | + let (w, h) = (width as usize, height as usize); | |
| 949 | + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); | |
| 950 | + if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch { | |
| 951 | + return Err("encode input is not a packed I420 frame".into()); | |
| 952 | + } | |
| 953 | + match self { | |
| 954 | + Self::Remote(remote) => remote.encode(y, u, v, width, height, force_key), | |
| 955 | + Self::Local(local) => local.encode(y, u, v, width, height, force_key), | |
| 956 | + } | |
| 957 | + } | |
| 958 | + | |
| 959 | + /// What a decoded buffer must look like to reach this encoder without a | |
| 960 | + /// copy -- the surface size it codes in, plus the picture it was opened for | |
| 961 | + /// -- or `None` where the plugin has no zero-copy door at all. | |
| 962 | + pub fn dma_want(&mut self, width: u32, height: u32) -> Option<DmaWant> { | |
| 963 | + let (coded_width, coded_height) = match self { | |
| 964 | + Self::Remote(remote) => remote.dma_geometry()?, | |
| 965 | + Self::Local(local) => local.dma_geometry()?, | |
| 966 | + }; | |
| 967 | + Some(DmaWant { | |
| 968 | + coded_width, | |
| 969 | + coded_height, | |
| 970 | + width, | |
| 971 | + height, | |
| 972 | + }) | |
| 973 | + } | |
| 974 | + | |
| 975 | + /// Feeds one picture the decoder left on the GPU. Same answer and same | |
| 976 | + /// lifetime rule as [`HwEncoder::encode`]; an error here is a real one, the | |
| 977 | + /// caller having asked [`HwEncoder::dma_want`] what this seat takes before | |
| 978 | + /// the decoder handed the buffer over. | |
| 979 | + /// | |
| 980 | + /// The buffer does not move for the isolated seat either: its descriptors | |
| 981 | + /// go to the child over `SCM_RIGHTS` and the pixels stay where the decoder | |
| 982 | + /// wrote them. | |
| 983 | + pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> { | |
| 984 | + match self { | |
| 985 | + Self::Remote(remote) => remote.encode_dma(&dma.0, force_key), | |
| 986 | + Self::Local(local) => local.encode_dma(dma, force_key), | |
| 987 | + } | |
| 988 | + } | |
| 989 | + | |
| 990 | + /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule | |
| 991 | + /// as [`HwEncoder::encode`]. | |
| 992 | + pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> { | |
| 993 | + match self { | |
| 994 | + Self::Remote(remote) => remote.drain(), | |
| 995 | + Self::Local(local) => local.drain(), | |
| 996 | + } | |
| 997 | + } | |
| 998 | +} |
crates/engine/src/hwproc.rsadded+670 -0
| @@ -0,0 +1,670 @@ | ||
| 1 | +//! The hardware encoder, held in a **child process**. | |
| 2 | +//! | |
| 3 | +//! Every entry point of the plugin catches unwinds ([`crate::hw`]), and that | |
| 4 | +//! guarantee has a floor it cannot reach: Mesa's VA-API drivers run their own C | |
| 5 | +//! worker threads, and `radeonsi` calls libc `abort()` from | |
| 6 | +//! `amdgpu_ctx_set_sw_reset_status` when the video ring resets under it | |
| 7 | +//! (measured 2026-08-13, mesa 26.1.6, `vcn_unified_0` hung during an AV1 encode | |
| 8 | +//! submission). A foreign thread's `abort()` is not an unwind and no | |
| 9 | +//! `catch_unwind` in this address space can see it, so the editor died with the | |
| 10 | +//! driver and took the export -- and the session -- with it. | |
| 11 | +//! | |
| 12 | +//! So the driver is not in this address space any more. `HwEncoder` here is a | |
| 13 | +//! handle on a child running `hw-encode-child`, which is the one process that | |
| 14 | +//! `dlopen`s the plugin and therefore the only one a driver may kill. When it | |
| 15 | +//! dies -- by `abort()`, by any signal, or by going quiet past | |
| 16 | +//! [`Remote::timeout`] -- the parent sees a closed socket or a timed-out read, | |
| 17 | +//! reaps the child, and reports an error carrying [`HW_LOST`]. The export then | |
| 18 | +//! runs again on the software encoder ([`crate::export::start`]), or refuses in | |
| 19 | +//! words where a person picked the GPU by name. | |
| 20 | +//! | |
| 21 | +//! Two things cross between the processes and neither is a picture copied down a | |
| 22 | +//! pipe. Pictures that live in memory are written into a shared anonymous file | |
| 23 | +//! (`memfd`, mapped in both), so a frame costs one `memcpy` and a 10-byte | |
| 24 | +//! message. Pictures still on the GPU never move at all: the DRM-PRIME | |
| 25 | +//! descriptors travel as file descriptors over `SCM_RIGHTS`, so the zero-copy | |
| 26 | +//! export path stays zero-copy across the process boundary. | |
| 27 | + | |
| 28 | +use std::ffi::c_void; | |
| 29 | +use std::io::Read; | |
| 30 | +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; | |
| 31 | +use std::os::unix::net::UnixStream; | |
| 32 | +use std::path::PathBuf; | |
| 33 | +use std::process::{Child, Command, Stdio}; | |
| 34 | +use std::time::Duration; | |
| 35 | + | |
| 36 | +use crate::colorspace::{ColorDescription, Matrix, Transfer}; | |
| 37 | +use crate::hw::VhDma; | |
| 38 | + | |
| 39 | +/// The words every "the child is gone" error carries, and the only thing | |
| 40 | +/// [`crate::export`] matches on to decide that the software encoder should have | |
| 41 | +/// another go at the file. A message, not an error kind, because | |
| 42 | +/// [`crate::Error`] is a boxed `dyn Error` and a caller two crates away reads | |
| 43 | +/// its text. | |
| 44 | +pub const HW_LOST: &str = "the hardware encoder process"; | |
| 45 | + | |
| 46 | +/// Whether an error is one: a driver that took its process down, rather than a | |
| 47 | +/// picture this engine got wrong. | |
| 48 | +pub fn is_lost(error: &crate::Error) -> bool { | |
| 49 | + error.to_string().contains(HW_LOST) | |
| 50 | +} | |
| 51 | + | |
| 52 | +/// The helper's file name; it is built into the same directory as the editor. | |
| 53 | +const BIN: &str = "hw-encode-child"; | |
| 54 | + | |
| 55 | +/// Which encoder the child opens. Sent as argv, so the child needs no protocol | |
| 56 | +/// before it has one. | |
| 57 | +#[derive(Clone, Copy, PartialEq, Eq)] | |
| 58 | +pub enum Seat { | |
| 59 | + H264, | |
| 60 | + Intra, | |
| 61 | + Av1, | |
| 62 | + Hevc, | |
| 63 | +} | |
| 64 | + | |
| 65 | +impl Seat { | |
| 66 | + pub fn code(self) -> u8 { | |
| 67 | + match self { | |
| 68 | + Self::H264 => 0, | |
| 69 | + Self::Intra => 1, | |
| 70 | + Self::Av1 => 2, | |
| 71 | + Self::Hevc => 3, | |
| 72 | + } | |
| 73 | + } | |
| 74 | + | |
| 75 | + pub fn from_code(code: u8) -> Option<Self> { | |
| 76 | + Some(match code { | |
| 77 | + 0 => Self::H264, | |
| 78 | + 1 => Self::Intra, | |
| 79 | + 2 => Self::Av1, | |
| 80 | + 3 => Self::Hevc, | |
| 81 | + _ => return None, | |
| 82 | + }) | |
| 83 | + } | |
| 84 | +} | |
| 85 | + | |
| 86 | +/// Everything an open needs, in one place because it travels as argv and comes | |
| 87 | +/// back as a struct on the other side. | |
| 88 | +#[derive(Clone, Copy)] | |
| 89 | +pub struct Open { | |
| 90 | + pub seat: Seat, | |
| 91 | + pub width: u32, | |
| 92 | + pub height: u32, | |
| 93 | + pub fps_num: u32, | |
| 94 | + pub fps_den: u32, | |
| 95 | + pub bitrate: u64, | |
| 96 | + /// What the sequence header will say the samples mean. Only the HEVC seat | |
| 97 | + /// takes one; the others ignore it. | |
| 98 | + pub colour: ColorDescription, | |
| 99 | +} | |
| 100 | + | |
| 101 | +impl Open { | |
| 102 | + fn argv(&self) -> Vec<String> { | |
| 103 | + let (matrix, transfer) = ( | |
| 104 | + match self.colour.matrix { | |
| 105 | + Matrix::Bt709 => 0, | |
| 106 | + Matrix::Bt601 => 1, | |
| 107 | + Matrix::Bt2020Ncl => 2, | |
| 108 | + }, | |
| 109 | + match self.colour.transfer { | |
| 110 | + Transfer::Sdr => 0, | |
| 111 | + Transfer::Pq => 1, | |
| 112 | + Transfer::Hlg => 2, | |
| 113 | + }, | |
| 114 | + ); | |
| 115 | + [ | |
| 116 | + u32::from(self.seat.code()), | |
| 117 | + self.width, | |
| 118 | + self.height, | |
| 119 | + self.fps_num, | |
| 120 | + self.fps_den, | |
| 121 | + matrix, | |
| 122 | + transfer, | |
| 123 | + u32::from(self.colour.full_range), | |
| 124 | + ] | |
| 125 | + .iter() | |
| 126 | + .map(u32::to_string) | |
| 127 | + .chain(std::iter::once(self.bitrate.to_string())) | |
| 128 | + .collect() | |
| 129 | + } | |
| 130 | + | |
| 131 | + /// The other half of [`Open::argv`], in the child. | |
| 132 | + pub fn from_argv(args: &[String]) -> Option<Self> { | |
| 133 | + let n = |i: usize| args.get(i)?.parse::<u32>().ok(); | |
| 134 | + Some(Self { | |
| 135 | + seat: Seat::from_code(u8::try_from(n(0)?).ok()?)?, | |
| 136 | + width: n(1)?, | |
| 137 | + height: n(2)?, | |
| 138 | + fps_num: n(3)?, | |
| 139 | + fps_den: n(4)?, | |
| 140 | + bitrate: args.get(8)?.parse().ok()?, | |
| 141 | + colour: ColorDescription { | |
| 142 | + matrix: match n(5)? { | |
| 143 | + 0 => Matrix::Bt709, | |
| 144 | + 1 => Matrix::Bt601, | |
| 145 | + _ => Matrix::Bt2020Ncl, | |
| 146 | + }, | |
| 147 | + transfer: match n(6)? { | |
| 148 | + 0 => Transfer::Sdr, | |
| 149 | + 1 => Transfer::Pq, | |
| 150 | + _ => Transfer::Hlg, | |
| 151 | + }, | |
| 152 | + full_range: n(7)? != 0, | |
| 153 | + }, | |
| 154 | + }) | |
| 155 | + } | |
| 156 | + | |
| 157 | + /// How many bytes one packed I420 picture of this size takes -- the size of | |
| 158 | + /// the shared mapping, decided once at the open because the export feeds one | |
| 159 | + /// canvas size for the whole file. | |
| 160 | + pub fn frame_bytes(&self) -> usize { | |
| 161 | + let (w, h) = (self.width as usize, self.height as usize); | |
| 162 | + w * h + 2 * (w.div_ceil(2) * h.div_ceil(2)) | |
| 163 | + } | |
| 164 | +} | |
| 165 | + | |
| 166 | +// Requests, parent to child. | |
| 167 | +pub const T_ENCODE: u8 = 1; | |
| 168 | +pub const T_DMA: u8 = 2; | |
| 169 | +pub const T_DRAIN: u8 = 3; | |
| 170 | +pub const T_GEOM: u8 = 4; | |
| 171 | +// Replies, child to parent. | |
| 172 | +pub const R_NONE: u8 = 0; | |
| 173 | +pub const R_AU: u8 = 1; | |
| 174 | +pub const R_ERR: u8 = 2; | |
| 175 | + | |
| 176 | +/// A `memfd` mapped into this process: the staging buffer one picture is written | |
| 177 | +/// into and read out of without either side owning the other's memory. | |
| 178 | +pub struct Shm { | |
| 179 | + ptr: *mut u8, | |
| 180 | + len: usize, | |
| 181 | +} | |
| 182 | + | |
| 183 | +impl Shm { | |
| 184 | + /// Creates one of `len` bytes, returning it mapped plus the descriptor to | |
| 185 | + /// hand the other process. | |
| 186 | + pub fn create(len: usize) -> std::io::Result<(Self, OwnedFd)> { | |
| 187 | + // SAFETY: a NUL-terminated name and a flag word, which is the whole of | |
| 188 | + // this call's contract; the descriptor it returns is ours. | |
| 189 | + let fd = unsafe { libc::memfd_create(c"edith-hwenc".as_ptr(), libc::MFD_CLOEXEC) }; | |
| 190 | + if fd < 0 { | |
| 191 | + return Err(std::io::Error::last_os_error()); | |
| 192 | + } | |
| 193 | + // SAFETY: `fd` is a fresh descriptor nothing else holds. | |
| 194 | + let file = unsafe { std::fs::File::from_raw_fd(fd) }; | |
| 195 | + file.set_len(len as u64)?; | |
| 196 | + let shm = Self::map(fd, len)?; | |
| 197 | + Ok((shm, OwnedFd::from(file))) | |
| 198 | + } | |
| 199 | + | |
| 200 | + /// Maps a descriptor the other process created. | |
| 201 | + pub fn map(fd: RawFd, len: usize) -> std::io::Result<Self> { | |
| 202 | + // SAFETY: a shared mapping of a descriptor that is open for the call; | |
| 203 | + // the kernel picks the address and the length is the file's own. | |
| 204 | + let ptr = unsafe { | |
| 205 | + libc::mmap( | |
| 206 | + std::ptr::null_mut(), | |
| 207 | + len, | |
| 208 | + libc::PROT_READ | libc::PROT_WRITE, | |
| 209 | + libc::MAP_SHARED, | |
| 210 | + fd, | |
| 211 | + 0, | |
| 212 | + ) | |
| 213 | + }; | |
| 214 | + if ptr == libc::MAP_FAILED { | |
| 215 | + return Err(std::io::Error::last_os_error()); | |
| 216 | + } | |
| 217 | + Ok(Self { | |
| 218 | + ptr: ptr.cast(), | |
| 219 | + len, | |
| 220 | + }) | |
| 221 | + } | |
| 222 | + | |
| 223 | + /// A mapping of nothing, for the moment between spawning a child and | |
| 224 | + /// learning which buffer it made. | |
| 225 | + fn empty() -> Self { | |
| 226 | + Self { | |
| 227 | + ptr: std::ptr::null_mut(), | |
| 228 | + len: 0, | |
| 229 | + } | |
| 230 | + } | |
| 231 | + | |
| 232 | + /// The mapping as bytes. Both processes see the same store, and the protocol | |
| 233 | + /// -- one request, one reply, never overlapping -- is what keeps only one of | |
| 234 | + /// them looking at a time. | |
| 235 | + pub fn bytes(&mut self) -> &mut [u8] { | |
| 236 | + // SAFETY: the mapping is `len` bytes long and lives as long as `self`. | |
| 237 | + unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) } | |
| 238 | + } | |
| 239 | +} | |
| 240 | + | |
| 241 | +impl Drop for Shm { | |
| 242 | + fn drop(&mut self) { | |
| 243 | + if self.len == 0 { | |
| 244 | + return; | |
| 245 | + } | |
| 246 | + // SAFETY: the pair of the `mmap` above, unmapped exactly once. | |
| 247 | + unsafe { libc::munmap(self.ptr.cast(), self.len) }; | |
| 248 | + } | |
| 249 | +} | |
| 250 | + | |
| 251 | +// The mapping is used from one thread at a time (the export worker), as the | |
| 252 | +// session it belongs to is. | |
| 253 | +unsafe impl Send for Shm {} | |
| 254 | + | |
| 255 | +/// Sends one message with its file descriptors attached. | |
| 256 | +/// | |
| 257 | +/// `MSG_NOSIGNAL` is the point of writing this by hand rather than | |
| 258 | +/// [`Write::write_all`]: a child that has just died leaves a socket whose next | |
| 259 | +/// write raises `SIGPIPE`, and a crash-containment path that kills the editor | |
| 260 | +/// with a signal of its own would be no containment at all. | |
| 261 | +pub fn send_msg(sock: &UnixStream, bytes: &[u8], fds: &[RawFd]) -> std::io::Result<()> { | |
| 262 | + debug_assert!(!bytes.is_empty(), "ancillary data rides on a real byte"); | |
| 263 | + let mut iov = libc::iovec { | |
| 264 | + iov_base: bytes.as_ptr() as *mut c_void, | |
| 265 | + iov_len: bytes.len(), | |
| 266 | + }; | |
| 267 | + // Two descriptors is the most anything here sends (a two-object NV12 | |
| 268 | + // buffer); 64 bytes covers the header, the payload and the alignment. | |
| 269 | + let mut control = [0u8; 64]; | |
| 270 | + // SAFETY: every pointer below is into a local that outlives the call, the | |
| 271 | + // control buffer is larger than the `CMSG_SPACE` written into | |
| 272 | + // `msg_controllen`, and the descriptors are open for the duration. | |
| 273 | + let sent = unsafe { | |
| 274 | + let mut msg: libc::msghdr = std::mem::zeroed(); | |
| 275 | + msg.msg_iov = &mut iov; | |
| 276 | + msg.msg_iovlen = 1; | |
| 277 | + if !fds.is_empty() { | |
| 278 | + let payload = (std::mem::size_of::<RawFd>() * fds.len()) as u32; | |
| 279 | + msg.msg_control = control.as_mut_ptr().cast(); | |
| 280 | + msg.msg_controllen = libc::CMSG_SPACE(payload) as _; | |
| 281 | + let cmsg = libc::CMSG_FIRSTHDR(&msg); | |
| 282 | + (*cmsg).cmsg_level = libc::SOL_SOCKET; | |
| 283 | + (*cmsg).cmsg_type = libc::SCM_RIGHTS; | |
| 284 | + (*cmsg).cmsg_len = libc::CMSG_LEN(payload) as _; | |
| 285 | + std::ptr::copy_nonoverlapping( | |
| 286 | + fds.as_ptr(), | |
| 287 | + libc::CMSG_DATA(cmsg).cast::<RawFd>(), | |
| 288 | + fds.len(), | |
| 289 | + ); | |
| 290 | + } | |
| 291 | + libc::sendmsg(sock.as_raw_fd(), &msg, libc::MSG_NOSIGNAL) | |
| 292 | + }; | |
| 293 | + match sent { | |
| 294 | + n if n < 0 => Err(std::io::Error::last_os_error()), | |
| 295 | + // Messages here are tens of bytes and a socket buffer is kilobytes, so a | |
| 296 | + // short send means the peer is gone rather than that we should loop. | |
| 297 | + n if n as usize != bytes.len() => Err(std::io::Error::new( | |
| 298 | + std::io::ErrorKind::WriteZero, | |
| 299 | + "short send", | |
| 300 | + )), | |
| 301 | + _ => Ok(()), | |
| 302 | + } | |
| 303 | +} | |
| 304 | + | |
| 305 | +/// Reads the one byte a message's descriptors ride on, and those descriptors. | |
| 306 | +/// | |
| 307 | +/// Ancillary data attaches to a position in the byte stream, so the tag is read | |
| 308 | +/// with `recvmsg` and everything after it with an ordinary read. | |
| 309 | +pub fn recv_tag(sock: &UnixStream) -> std::io::Result<(u8, Vec<OwnedFd>)> { | |
| 310 | + let mut byte = [0u8; 1]; | |
| 311 | + let mut iov = libc::iovec { | |
| 312 | + iov_base: byte.as_mut_ptr().cast(), | |
| 313 | + iov_len: 1, | |
| 314 | + }; | |
| 315 | + let mut control = [0u8; 64]; | |
| 316 | + let mut fds = Vec::new(); | |
| 317 | + // SAFETY: as `send` -- locals that outlive the call and a control buffer | |
| 318 | + // whose length is what `msg_controllen` claims. Every descriptor the kernel | |
| 319 | + // writes there is ours, and is taken by an `OwnedFd` exactly once. | |
| 320 | + let got = unsafe { | |
| 321 | + let mut msg: libc::msghdr = std::mem::zeroed(); | |
| 322 | + msg.msg_iov = &mut iov; | |
| 323 | + msg.msg_iovlen = 1; | |
| 324 | + msg.msg_control = control.as_mut_ptr().cast(); | |
| 325 | + msg.msg_controllen = control.len() as _; | |
| 326 | + let got = libc::recvmsg(sock.as_raw_fd(), &mut msg, libc::MSG_CMSG_CLOEXEC); | |
| 327 | + if got > 0 { | |
| 328 | + let mut cmsg = libc::CMSG_FIRSTHDR(&msg); | |
| 329 | + while !cmsg.is_null() { | |
| 330 | + if (*cmsg).cmsg_level == libc::SOL_SOCKET && (*cmsg).cmsg_type == libc::SCM_RIGHTS { | |
| 331 | + let bytes = (*cmsg).cmsg_len as usize - libc::CMSG_LEN(0) as usize; | |
| 332 | + let data = libc::CMSG_DATA(cmsg).cast::<RawFd>(); | |
| 333 | + for i in 0..bytes / std::mem::size_of::<RawFd>() { | |
| 334 | + fds.push(OwnedFd::from_raw_fd(data.add(i).read_unaligned())); | |
| 335 | + } | |
| 336 | + } | |
| 337 | + cmsg = libc::CMSG_NXTHDR(&msg, cmsg); | |
| 338 | + } | |
| 339 | + } | |
| 340 | + got | |
| 341 | + }; | |
| 342 | + match got { | |
| 343 | + n if n < 0 => Err(std::io::Error::last_os_error()), | |
| 344 | + 0 => Err(std::io::Error::new( | |
| 345 | + std::io::ErrorKind::UnexpectedEof, | |
| 346 | + "peer closed", | |
| 347 | + )), | |
| 348 | + _ => Ok((byte[0], fds)), | |
| 349 | + } | |
| 350 | +} | |
| 351 | + | |
| 352 | +/// One access unit, or the child's own error, read off the socket. | |
| 353 | +fn read_reply(sock: &mut UnixStream, au: &mut Vec<u8>) -> std::io::Result<Option<Result<(), String>>> { | |
| 354 | + let (tag, _) = recv_tag(sock)?; | |
| 355 | + if tag == R_NONE { | |
| 356 | + return Ok(None); | |
| 357 | + } | |
| 358 | + let mut len = [0u8; 4]; | |
| 359 | + sock.read_exact(&mut len)?; | |
| 360 | + let len = u32::from_le_bytes(len) as usize; | |
| 361 | + au.clear(); | |
| 362 | + au.resize(len, 0); | |
| 363 | + sock.read_exact(au)?; | |
| 364 | + Ok(Some(match tag { | |
| 365 | + R_AU => Ok(()), | |
| 366 | + _ => Err(String::from_utf8_lossy(au).into_owned()), | |
| 367 | + })) | |
| 368 | +} | |
| 369 | + | |
| 370 | +/// Where the helper lives: told outright, or beside the running executable -- | |
| 371 | +/// which is `target/<profile>/` for the editor and one directory up from | |
| 372 | +/// `deps/` for a test binary. | |
| 373 | +fn child_bin() -> Option<PathBuf> { | |
| 374 | + if let Some(pinned) = std::env::var_os("VE_HW_CHILD_BIN") { | |
| 375 | + return Some(PathBuf::from(pinned)); | |
| 376 | + } | |
| 377 | + let exe = std::env::current_exe().ok()?; | |
| 378 | + let dir = exe.parent()?.to_path_buf(); | |
| 379 | + [dir.join(BIN), dir.parent()?.join(BIN)] | |
| 380 | + .into_iter() | |
| 381 | + .find(|candidate| candidate.is_file()) | |
| 382 | +} | |
| 383 | + | |
| 384 | +/// Whether an isolated encoder can be had at all -- a helper to run. `false` | |
| 385 | +/// leaves the caller on the in-process seat, which is what a build that did not | |
| 386 | +/// produce the helper has always had. | |
| 387 | +pub fn available() -> bool { | |
| 388 | + child_bin().is_some() | |
| 389 | +} | |
| 390 | + | |
| 391 | +/// The test-only stand-in seat: a child that opens no driver at all, so the | |
| 392 | +/// containment paths below can be exercised on a machine whose GPU is wedged -- | |
| 393 | +/// which is the only machine where they matter and the only one where the real | |
| 394 | +/// trigger cannot be pulled. | |
| 395 | +pub fn faked() -> bool { | |
| 396 | + std::env::var_os("VE_HW_TEST_FAKE").is_some() | |
| 397 | +} | |
| 398 | + | |
| 399 | +/// A hardware encode session living in another process. | |
| 400 | +pub struct Remote { | |
| 401 | + child: Child, | |
| 402 | + sock: UnixStream, | |
| 403 | + shm: Shm, | |
| 404 | + open: Open, | |
| 405 | + /// The last access unit, owned here: the child's buffer is in the child. | |
| 406 | + au: Vec<u8>, | |
| 407 | + /// Set the moment the child is known gone, so every later call refuses in | |
| 408 | + /// the same words instead of blocking on a socket nobody holds. | |
| 409 | + lost: Option<String>, | |
| 410 | +} | |
| 411 | + | |
| 412 | +impl Remote { | |
| 413 | + /// How long the child may take over one call before it is treated as hung. | |
| 414 | + /// A wedged ring does not always `abort()` -- it can simply stop -- and a | |
| 415 | + /// timeout is the only thing that tells those apart from a slow frame. | |
| 416 | + fn timeout() -> Duration { | |
| 417 | + let ms = std::env::var("VE_HW_TIMEOUT_MS") | |
| 418 | + .ok() | |
| 419 | + .and_then(|v| v.parse().ok()) | |
| 420 | + .unwrap_or(15_000); | |
| 421 | + Duration::from_millis(ms) | |
| 422 | + } | |
| 423 | + | |
| 424 | + /// Starts a child on this seat. `None` is the plugin's own "no" carried | |
| 425 | + /// across the process boundary -- no driver, no entrypoint, a size refused | |
| 426 | + /// -- and the caller takes the software encoder exactly as it always did. | |
| 427 | + pub fn spawn(open: Open) -> Option<Self> { | |
| 428 | + let bin = child_bin()?; | |
| 429 | + let (mine, theirs) = UnixStream::pair().ok()?; | |
| 430 | + mine.set_read_timeout(Some(Self::timeout())).ok()?; | |
| 431 | + // The socket is the child's stdin, which is how it crosses `exec` | |
| 432 | + // without a `pre_exec` of our own. Its stdout and stderr stay ours, so | |
| 433 | + // whatever the driver prints is still in the editor's log. | |
| 434 | + let child = Command::new(bin) | |
| 435 | + .args(open.argv()) | |
| 436 | + .stdin(Stdio::from(OwnedFd::from(theirs))) | |
| 437 | + .spawn() | |
| 438 | + .ok()?; | |
| 439 | + let mut remote = Self { | |
| 440 | + child, | |
| 441 | + sock: mine, | |
| 442 | + // Replaced by the child's own mapping below; a zero-length one | |
| 443 | + // allocates nothing and keeps the field non-optional. | |
| 444 | + shm: Shm::empty(), | |
| 445 | + open, | |
| 446 | + au: Vec::new(), | |
| 447 | + lost: None, | |
| 448 | + }; | |
| 449 | + // The child answers once its encoder is open: a byte, and with it the | |
| 450 | + // descriptor of the staging buffer it made for this session's size. | |
| 451 | + match recv_tag(&remote.sock) { | |
| 452 | + Ok((1, fds)) if fds.len() == 1 => { | |
| 453 | + remote.shm = Shm::map(fds[0].as_raw_fd(), open.frame_bytes()).ok()?; | |
| 454 | + Some(remote) | |
| 455 | + } | |
| 456 | + // Anything else is "no seat here", including a child that died | |
| 457 | + // opening the driver -- which is the crash this whole module exists | |
| 458 | + // for, and it costs an export nothing but the software encoder. | |
| 459 | + _ => None, | |
| 460 | + } | |
| 461 | + } | |
| 462 | + | |
| 463 | + /// What the child's encoder codes in, or `None` where it has no zero-copy | |
| 464 | + /// door. | |
| 465 | + /// | |
| 466 | + /// The two `None`s are not the same thing and only one of them is an | |
| 467 | + /// answer. A child that *says* it has no door costs the caller a read-back | |
| 468 | + /// and nothing else; a child that does not answer at all is gone, and is | |
| 469 | + /// reaped right here -- otherwise the next picture would spend a whole | |
| 470 | + /// second timeout discovering what this call already knows. | |
| 471 | + pub fn dma_geometry(&mut self) -> Option<(u32, u32)> { | |
| 472 | + self.request(&[T_GEOM], &[]).ok()?; | |
| 473 | + let mut buf = [0u8; 8]; | |
| 474 | + let answered = match recv_tag(&self.sock) { | |
| 475 | + Ok((R_AU, _)) => self.sock.read_exact(&mut buf).map(|()| true), | |
| 476 | + Ok(_) => Ok(false), | |
| 477 | + Err(e) => Err(e), | |
| 478 | + }; | |
| 479 | + match answered { | |
| 480 | + Ok(true) => Some(( | |
| 481 | + u32::from_le_bytes(buf[..4].try_into().ok()?), | |
| 482 | + u32::from_le_bytes(buf[4..].try_into().ok()?), | |
| 483 | + )), | |
| 484 | + Ok(false) => None, | |
| 485 | + Err(e) => { | |
| 486 | + self.bury(&e.to_string()); | |
| 487 | + None | |
| 488 | + } | |
| 489 | + } | |
| 490 | + } | |
| 491 | + | |
| 492 | + /// Feeds one packed I420 picture through the shared mapping. | |
| 493 | + pub fn encode( | |
| 494 | + &mut self, | |
| 495 | + y: &[u8], | |
| 496 | + u: &[u8], | |
| 497 | + v: &[u8], | |
| 498 | + width: u32, | |
| 499 | + height: u32, | |
| 500 | + force_key: bool, | |
| 501 | + ) -> crate::Result<Option<&[u8]>> { | |
| 502 | + let total = y.len() + u.len() + v.len(); | |
| 503 | + if total > self.shm.len { | |
| 504 | + return Err(format!( | |
| 505 | + "a {width}x{height} picture does not fit the staging buffer opened for {}x{}", | |
| 506 | + self.open.width, self.open.height | |
| 507 | + ) | |
| 508 | + .into()); | |
| 509 | + } | |
| 510 | + let bytes = self.shm.bytes(); | |
| 511 | + bytes[..y.len()].copy_from_slice(y); | |
| 512 | + bytes[y.len()..y.len() + u.len()].copy_from_slice(u); | |
| 513 | + bytes[y.len() + u.len()..total].copy_from_slice(v); | |
| 514 | + let mut msg = vec![T_ENCODE]; | |
| 515 | + msg.extend_from_slice(&width.to_le_bytes()); | |
| 516 | + msg.extend_from_slice(&height.to_le_bytes()); | |
| 517 | + msg.push(u8::from(force_key)); | |
| 518 | + self.round_trip(&msg, &[]) | |
| 519 | + } | |
| 520 | + | |
| 521 | + /// Feeds one picture the decoder left on the GPU. The descriptors go over | |
| 522 | + /// with the message, so the buffer itself never moves. | |
| 523 | + pub fn encode_dma(&mut self, dma: &VhDma, force_key: bool) -> crate::Result<Option<&[u8]>> { | |
| 524 | + let fds: Vec<RawFd> = dma.fd.iter().copied().filter(|&fd| fd >= 0).collect(); | |
| 525 | + let mut msg = vec![T_DMA]; | |
| 526 | + msg.extend_from_slice(&dma.fourcc.to_le_bytes()); | |
| 527 | + msg.extend_from_slice(&dma.modifier.to_le_bytes()); | |
| 528 | + for value in [ | |
| 529 | + dma.coded_width, | |
| 530 | + dma.coded_height, | |
| 531 | + dma.width, | |
| 532 | + dma.height, | |
| 533 | + dma.offset[0], | |
| 534 | + dma.offset[1], | |
| 535 | + dma.stride[0], | |
| 536 | + dma.stride[1], | |
| 537 | + ] { | |
| 538 | + msg.extend_from_slice(&value.to_le_bytes()); | |
| 539 | + } | |
| 540 | + msg.push(fds.len() as u8); | |
| 541 | + msg.push(u8::from(force_key)); | |
| 542 | + self.round_trip(&msg, &fds) | |
| 543 | + } | |
| 544 | + | |
| 545 | + /// Flushes the child's encoder; call until it answers `None`. | |
| 546 | + pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> { | |
| 547 | + self.round_trip(&[T_DRAIN], &[]) | |
| 548 | + } | |
| 549 | + | |
| 550 | + /// One request and its reply, which is every call above: the child is fed, | |
| 551 | + /// then read, and anything that is not an answer is the child being gone. | |
| 552 | + fn round_trip(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<Option<&[u8]>> { | |
| 553 | + self.request(msg, fds)?; | |
| 554 | + let mut au = std::mem::take(&mut self.au); | |
| 555 | + let read = read_reply(&mut self.sock, &mut au); | |
| 556 | + self.au = au; | |
| 557 | + // Every "no access unit" leaves through a `return`, so the borrow of the | |
| 558 | + // buffer below is the only one alive when it is taken. | |
| 559 | + match read { | |
| 560 | + Ok(None) => return Ok(None), | |
| 561 | + Ok(Some(Ok(()))) => {} | |
| 562 | + // The child's *own* refusal: it is alive and said no, so this is an | |
| 563 | + // ordinary encode error and the process stays as it is. | |
| 564 | + Ok(Some(Err(message))) => return Err(message.into()), | |
| 565 | + Err(e) => return Err(self.bury(&e.to_string())), | |
| 566 | + } | |
| 567 | + Ok(Some(&self.au)) | |
| 568 | + } | |
| 569 | + | |
| 570 | + fn request(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<()> { | |
| 571 | + if let Some(gone) = &self.lost { | |
| 572 | + return Err(gone.clone().into()); | |
| 573 | + } | |
| 574 | + match send_msg(&self.sock, msg, fds) { | |
| 575 | + Ok(()) => Ok(()), | |
| 576 | + Err(e) => Err(self.bury(&e.to_string())), | |
| 577 | + } | |
| 578 | + } | |
| 579 | + | |
| 580 | + /// Reaps the child and remembers why, so no later call waits on it. Kills | |
| 581 | + /// first: the child may be *stuck* rather than dead, which is the hang this | |
| 582 | + /// timeout exists to contain, and a stuck child is never waited for. | |
| 583 | + fn bury(&mut self, why: &str) -> crate::Error { | |
| 584 | + let _ = self.child.kill(); | |
| 585 | + let status = self.child.wait().ok(); | |
| 586 | + // The two shapes a wedged ring takes, told apart by who did the | |
| 587 | + // killing: a driver that called `abort()` leaves its own signal, while | |
| 588 | + // a child that merely stopped answering is still holding `SIGKILL` from | |
| 589 | + // the line above and the read's own timeout is the real reason. | |
| 590 | + let how = match status.and_then(|s| std::os::unix::process::ExitStatusExt::signal(&s)) { | |
| 591 | + Some(libc::SIGKILL) | None => format!("stopped answering ({why}) and was killed"), | |
| 592 | + Some(signal) => format!("was killed by signal {signal}"), | |
| 593 | + }; | |
| 594 | + let message = | |
| 595 | + format!("{HW_LOST} {how}; the driver took it down and not the editor"); | |
| 596 | + self.lost = Some(message.clone()); | |
| 597 | + message.into() | |
| 598 | + } | |
| 599 | +} | |
| 600 | + | |
| 601 | +impl Drop for Remote { | |
| 602 | + fn drop(&mut self) { | |
| 603 | + // Nothing is pending -- the export drains before it drops -- and a | |
| 604 | + // signal is the one exit a wedged child is guaranteed to take. | |
| 605 | + if self.lost.is_none() { | |
| 606 | + let _ = self.child.kill(); | |
| 607 | + let _ = self.child.wait(); | |
| 608 | + } | |
| 609 | + } | |
| 610 | +} | |
| 611 | + | |
| 612 | +// As the in-process session: one thread at a time (the export worker). | |
| 613 | +unsafe impl Send for Remote {} | |
| 614 | + | |
| 615 | +#[cfg(test)] | |
| 616 | +mod tests { | |
| 617 | + use super::*; | |
| 618 | + | |
| 619 | + /// Descriptors really cross the socket, and the mapping really is shared: | |
| 620 | + /// the two halves of the frame hand-off, checked without a driver. | |
| 621 | + #[test] | |
| 622 | + fn a_mapping_and_its_descriptor_cross_a_socket() { | |
| 623 | + let (a, b) = UnixStream::pair().expect("socketpair"); | |
| 624 | + let (mut mine, fd) = Shm::create(64).expect("memfd"); | |
| 625 | + mine.bytes()[..5].copy_from_slice(b"hello"); | |
| 626 | + send_msg(&a, &[7u8], &[fd.as_raw_fd()]).expect("send"); | |
| 627 | + let (tag, fds) = recv_tag(&b).expect("recv"); | |
| 628 | + assert_eq!(tag, 7); | |
| 629 | + assert_eq!(fds.len(), 1, "the descriptor came over"); | |
| 630 | + let mut theirs = Shm::map(fds[0].as_raw_fd(), 64).expect("map the received descriptor"); | |
| 631 | + assert_eq!(&theirs.bytes()[..5], b"hello", "one store, two mappings"); | |
| 632 | + theirs.bytes()[0] = b'j'; | |
| 633 | + assert_eq!(&mine.bytes()[..5], b"jello", "and it is shared both ways"); | |
| 634 | + } | |
| 635 | + | |
| 636 | + /// A dead peer must come back as an error, never as a `SIGPIPE` that kills | |
| 637 | + /// the process doing the sending -- the whole point of `MSG_NOSIGNAL`. | |
| 638 | + #[test] | |
| 639 | + fn sending_to_a_closed_socket_errors_instead_of_signalling() { | |
| 640 | + let (a, b) = UnixStream::pair().expect("socketpair"); | |
| 641 | + drop(b); | |
| 642 | + assert!(send_msg(&a, &[1u8, 2, 3], &[]).is_err()); | |
| 643 | + } | |
| 644 | + | |
| 645 | + /// The open crosses to the child as text and comes back the same struct. | |
| 646 | + #[test] | |
| 647 | + fn an_open_round_trips_through_argv() { | |
| 648 | + let open = Open { | |
| 649 | + seat: Seat::Hevc, | |
| 650 | + width: 1920, | |
| 651 | + height: 1080, | |
| 652 | + fps_num: 30000, | |
| 653 | + fps_den: 1001, | |
| 654 | + bitrate: 12_345_678, | |
| 655 | + colour: ColorDescription { | |
| 656 | + matrix: Matrix::Bt2020Ncl, | |
| 657 | + transfer: Transfer::Pq, | |
| 658 | + full_range: true, | |
| 659 | + }, | |
| 660 | + }; | |
| 661 | + let back = Open::from_argv(&open.argv()).expect("parse"); | |
| 662 | + assert!(back.seat == Seat::Hevc); | |
| 663 | + assert_eq!( | |
| 664 | + (back.width, back.height, back.fps_num, back.fps_den, back.bitrate), | |
| 665 | + (1920, 1080, 30000, 1001, 12_345_678) | |
| 666 | + ); | |
| 667 | + assert_eq!(back.colour, open.colour); | |
| 668 | + assert_eq!(back.frame_bytes(), 1920 * 1080 * 3 / 2); | |
| 669 | + } | |
| 670 | +} |
crates/engine/src/lib.rsmodified+1 -0
| @@ -13,6 +13,7 @@ pub mod edith; | ||
| 13 | 13 | pub mod eq; |
| 14 | 14 | pub mod export; |
| 15 | 15 | pub mod hw; |
| 16 | +pub mod hwproc; | |
| 16 | 17 | pub mod limiter; |
| 17 | 18 | pub mod mux; |
| 18 | 19 | pub mod playback; |
crates/engine/tests/export.rsmodified+297 -20
| @@ -53,23 +53,48 @@ fn part_path(out: &Path) -> PathBuf { | ||
| 53 | 53 | PathBuf::from(format!("{}.part", out.display())) |
| 54 | 54 | } |
| 55 | 55 | |
| 56 | +/// Which seat an export takes is decided by *process-wide* environment | |
| 57 | +/// variables, so it is a shared resource and every test in this binary borrows | |
| 58 | +/// it rather than assuming it. | |
| 59 | +/// | |
| 60 | +/// Readers share: the whole software suite wants the same pin and may run at | |
| 61 | +/// once, exactly as it always did. A test that has to *change* the pin -- | |
| 62 | +/// there is one family, the encoder-death ones at the end of this file -- takes | |
| 63 | +/// it exclusively, so no export is ever in flight while the seat is being | |
| 64 | +/// cycled underneath it. A borrow held only for the seat's opening would not do: | |
| 65 | +/// [`engine::export::start`] falls back and re-opens mid-run, so the pin has to | |
| 66 | +/// hold for the whole export. | |
| 67 | +static SEAT: std::sync::RwLock<()> = std::sync::RwLock::new(()); | |
| 68 | + | |
| 69 | +type Shared = std::sync::RwLockReadGuard<'static, ()>; | |
| 70 | + | |
| 56 | 71 | /// Pins both paths to software for the whole test binary, so the default suite |
| 57 | -/// proves the fallback that every machine has. | |
| 58 | -fn pin_software() { | |
| 72 | +/// proves the fallback that every machine has. Bind the guard: it is the borrow | |
| 73 | +/// above, and dropping it early puts the export back in the race this exists to | |
| 74 | +/// end. | |
| 75 | +#[must_use = "the seat pin holds only while its guard is alive"] | |
| 76 | +fn pin_software() -> Shared { | |
| 77 | + let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner()); | |
| 59 | 78 | static PIN: Once = Once::new(); |
| 60 | 79 | PIN.call_once(|| unsafe { |
| 61 | 80 | std::env::set_var("VE_SW", "1"); |
| 62 | 81 | std::env::set_var("VE_SW_ENC", "1"); |
| 63 | 82 | }); |
| 83 | + borrowed | |
| 64 | 84 | } |
| 65 | 85 | |
| 66 | -/// Removes both pins, for the hardware twins. | |
| 67 | -fn pin_hardware() { | |
| 86 | +/// Removes both pins, for the hardware twins -- which run in their own | |
| 87 | +/// `--ignored --test-threads=1` pass, so they never share this binary with the | |
| 88 | +/// software ones. | |
| 89 | +#[must_use = "the seat pin holds only while its guard is alive"] | |
| 90 | +fn pin_hardware() -> Shared { | |
| 91 | + let borrowed = SEAT.read().unwrap_or_else(|poisoned| poisoned.into_inner()); | |
| 68 | 92 | static PIN: Once = Once::new(); |
| 69 | 93 | PIN.call_once(|| unsafe { |
| 70 | 94 | std::env::remove_var("VE_SW"); |
| 71 | 95 | std::env::remove_var("VE_SW_ENC"); |
| 72 | 96 | }); |
| 97 | + borrowed | |
| 73 | 98 | } |
| 74 | 99 | |
| 75 | 100 | /// `[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) { | ||
| 180 | 205 | |
| 181 | 206 | #[test] |
| 182 | 207 | fn exports_an_edited_timeline_in_software() { |
| 183 | - pin_software(); | |
| 208 | + let _seat = pin_software(); | |
| 184 | 209 | round_trip("sw", Duration::from_secs(120)); |
| 185 | 210 | } |
| 186 | 211 | |
| @@ -189,7 +214,7 @@ fn exports_an_edited_timeline_in_software() { | ||
| 189 | 214 | #[test] |
| 190 | 215 | #[ignore] |
| 191 | 216 | fn exports_an_edited_timeline_in_hardware() { |
| 192 | - pin_hardware(); | |
| 217 | + let _seat = pin_hardware(); | |
| 193 | 218 | round_trip("hw", Duration::from_secs(60)); |
| 194 | 219 | } |
| 195 | 220 | |
| @@ -202,7 +227,7 @@ fn exports_an_edited_timeline_in_hardware() { | ||
| 202 | 227 | /// (`playback.rs: a_fitted_clip_is_letterboxed_and_a_filled_one_is_not`). |
| 203 | 228 | #[test] |
| 204 | 229 | fn exports_at_the_project_resolution_with_the_watched_geometry() { |
| 205 | - pin_software(); | |
| 230 | + let _seat = pin_software(); | |
| 206 | 231 | let clip = |source: usize, start: u32| engine::Clip { |
| 207 | 232 | start, |
| 208 | 233 | in_frame: 0, |
| @@ -282,7 +307,7 @@ fn exports_at_the_project_resolution_with_the_watched_geometry() { | ||
| 282 | 307 | /// header. Software only: the picture is beside the point here. |
| 283 | 308 | #[test] |
| 284 | 309 | fn exports_the_audio_stream_the_timeline_plays() { |
| 285 | - pin_software(); | |
| 310 | + let _seat = pin_software(); | |
| 286 | 311 | let multi = asset("test_multiaudio.mp4"); |
| 287 | 312 | let (meta, _) = engine::demux::Demuxer::open(&multi).expect("open the fixture"); |
| 288 | 313 | let whole = engine::Clip { |
| @@ -456,14 +481,14 @@ fn multi_source_round_trip(name: &str, limit: Duration) { | ||
| 456 | 481 | |
| 457 | 482 | #[test] |
| 458 | 483 | fn exports_two_sources_as_one_timeline_in_software() { |
| 459 | - pin_software(); | |
| 484 | + let _seat = pin_software(); | |
| 460 | 485 | multi_source_round_trip("multi_sw", Duration::from_secs(180)); |
| 461 | 486 | } |
| 462 | 487 | |
| 463 | 488 | #[test] |
| 464 | 489 | #[ignore] |
| 465 | 490 | fn exports_two_sources_as_one_timeline_in_hardware() { |
| 466 | - pin_hardware(); | |
| 491 | + let _seat = pin_hardware(); | |
| 467 | 492 | multi_source_round_trip("multi_hw", Duration::from_secs(60)); |
| 468 | 493 | } |
| 469 | 494 | |
| @@ -473,7 +498,7 @@ fn exports_two_sources_as_one_timeline_in_hardware() { | ||
| 473 | 498 | /// whose rate control is the one every machine has. |
| 474 | 499 | #[test] |
| 475 | 500 | fn a_higher_bitrate_writes_a_bigger_file() { |
| 476 | - pin_software(); | |
| 501 | + let _seat = pin_software(); | |
| 477 | 502 | let mut sizes = Vec::new(); |
| 478 | 503 | for bitrate in [1_000_000u64, 4_000_000, 8_000_000] { |
| 479 | 504 | let mut session = edited(&asset("test_baseline.mp4")); |
| @@ -503,7 +528,7 @@ fn a_higher_bitrate_writes_a_bigger_file() { | ||
| 503 | 528 | /// (the audio pass never touches the second file). |
| 504 | 529 | #[test] |
| 505 | 530 | fn a_vanished_source_fails_the_export() { |
| 506 | - pin_software(); | |
| 531 | + let _seat = pin_software(); | |
| 507 | 532 | let baseline = asset("test_baseline.mp4"); |
| 508 | 533 | let doomed = Scratch::file("ve_export_vanished_source", "mp4"); |
| 509 | 534 | std::fs::copy(&baseline, &doomed).expect("copy a second source"); |
| @@ -537,7 +562,7 @@ fn a_vanished_source_fails_the_export() { | ||
| 537 | 562 | /// thing a user would otherwise try to play. |
| 538 | 563 | #[test] |
| 539 | 564 | fn cancelling_leaves_no_file() { |
| 540 | - pin_software(); | |
| 565 | + let _seat = pin_software(); | |
| 541 | 566 | let mut session = edited(&asset("test_baseline.mp4")); |
| 542 | 567 | session.pause(); |
| 543 | 568 | let out = out_path("cancel"); |
| @@ -572,7 +597,7 @@ fn cancelling_leaves_no_file() { | ||
| 572 | 597 | /// file, never a `.part`. |
| 573 | 598 | #[test] |
| 574 | 599 | fn cancelling_after_the_last_frame_leaves_no_file() { |
| 575 | - pin_software(); | |
| 600 | + let _seat = pin_software(); | |
| 576 | 601 | let out = out_path("late"); |
| 577 | 602 | let part = part_path(&out); |
| 578 | 603 | for attempt in 1..=5 { |
| @@ -615,7 +640,7 @@ fn cancelling_after_the_last_frame_leaves_no_file() { | ||
| 615 | 640 | #[test] |
| 616 | 641 | #[ignore] |
| 617 | 642 | fn exports_audio_alongside_the_video() { |
| 618 | - pin_hardware(); | |
| 643 | + let _seat = pin_hardware(); | |
| 619 | 644 | let source = asset("test_av.mp4"); |
| 620 | 645 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 621 | 646 | // 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<u8>, Vec<u8>, Vec< | ||
| 749 | 774 | /// early, which is a lip sync error for the whole export. |
| 750 | 775 | #[test] |
| 751 | 776 | fn a_leading_audio_gap_keeps_the_sound_after_it_in_place() { |
| 752 | - pin_software(); | |
| 777 | + let _seat = pin_software(); | |
| 753 | 778 | let source = asset("test_av.mp4"); |
| 754 | 779 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 755 | 780 | 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() { | ||
| 797 | 822 | /// a second early. |
| 798 | 823 | #[test] |
| 799 | 824 | fn exports_a_gapped_timeline_as_black_and_silence() { |
| 800 | - pin_software(); | |
| 825 | + let _seat = pin_software(); | |
| 801 | 826 | let source = asset("test_av.mp4"); |
| 802 | 827 | let mut session = PlaybackSession::open(&source).expect("open source"); |
| 803 | 828 | assert!(session.cut_at(1.0), "split at 1 s"); |
| @@ -887,7 +912,7 @@ fn exports_a_gapped_timeline_as_black_and_silence() { | ||
| 887 | 912 | /// hardware one buys is speed, and that is the ignored test below. |
| 888 | 913 | #[test] |
| 889 | 914 | fn a_proxy_is_picture_only_every_frame_a_starting_point_and_cached() { |
| 890 | - pin_software(); | |
| 915 | + let _seat = pin_software(); | |
| 891 | 916 | let source = asset("test_av.mp4"); |
| 892 | 917 | let out = engine::proxy::path_for(&source).expect("a cache directory"); |
| 893 | 918 | // 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() { | ||
| 1021 | 1046 | #[test] |
| 1022 | 1047 | #[ignore = "needs the VA-API plugin"] |
| 1023 | 1048 | fn a_hardware_proxy_is_every_frame_a_starting_point_too() { |
| 1024 | - pin_hardware(); | |
| 1049 | + let _seat = pin_hardware(); | |
| 1025 | 1050 | let source = asset("test_av.mp4"); |
| 1026 | 1051 | let out = engine::proxy::path_for(&source).expect("a cache directory"); |
| 1027 | 1052 | let _ = std::fs::remove_file(&out); |
| @@ -1094,7 +1119,7 @@ fn a_hardware_proxy_is_every_frame_a_starting_point_too() { | ||
| 1094 | 1119 | #[test] |
| 1095 | 1120 | #[ignore = "needs the VA-API plugin and a real library"] |
| 1096 | 1121 | fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() { |
| 1097 | - pin_hardware(); | |
| 1122 | + let _seat = pin_hardware(); | |
| 1098 | 1123 | let Some(film) = engine::real_library::film("hevc_4k_hdr") else { |
| 1099 | 1124 | return; |
| 1100 | 1125 | }; |
| @@ -1158,3 +1183,255 @@ fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() { | ||
| 1158 | 1183 | assert!(!part_path(&out).exists(), "a cancelled proxy left its .part"); |
| 1159 | 1184 | assert_eq!(engine::proxy::cached(&film), None); |
| 1160 | 1185 | } |
| 1186 | + | |
| 1187 | +// --------------------------------------------------------------------------- | |
| 1188 | +// The hardware encoder's process dying under the driver. | |
| 1189 | +// | |
| 1190 | +// Mesa's radeonsi calls libc `abort()` from its own C worker thread when the | |
| 1191 | +// video ring resets under it, which no `catch_unwind` in the process can see: | |
| 1192 | +// on 2026-08-13 that killed the editor mid-export and took the session with it. | |
| 1193 | +// The encoder now lives in a child (`engine::hwproc`), and these are the proof | |
| 1194 | +// that its death is an inconvenience rather than a crash. | |
| 1195 | +// | |
| 1196 | +// None of them needs a GPU, and that is deliberate: the machine where this | |
| 1197 | +// matters is the one whose ring is already wedged, and a test that had to hang a | |
| 1198 | +// real ring to run could never be the oracle for the fix. `VE_HW_TEST_FAKE` | |
| 1199 | +// opens a stand-in seat in the child that touches no driver; | |
| 1200 | +// `VE_HW_TEST_ABORT` / `VE_HW_TEST_HANG` say where it dies or stops. | |
| 1201 | + | |
| 1202 | +/// The one place in this binary that *changes* the seat rather than reading it, | |
| 1203 | +/// so it takes [`SEAT`] exclusively: while it holds, no other export in this | |
| 1204 | +/// process is in flight, and every variable it set is gone again before it lets | |
| 1205 | +/// go. Which is the whole of the bug this shape exists to make impossible -- | |
| 1206 | +/// a stand-in encoder seat cycled underneath a software test that had already | |
| 1207 | +/// opened its own is a hang, not a failure, and it does not reproduce. | |
| 1208 | +/// | |
| 1209 | +/// It also lifts the software *encode* pin for its own exports, because the | |
| 1210 | +/// question here is what an export does when its hardware seat dies. Decode | |
| 1211 | +/// stays pinned to software: it is not what is under test and the fixture must | |
| 1212 | +/// decode the same way it does everywhere else in this file. | |
| 1213 | +fn injected<T>(abort: Option<&str>, hang: Option<&str>, body: impl FnOnce() -> T) -> T { | |
| 1214 | + let _exclusive = SEAT.write().unwrap_or_else(|poisoned| poisoned.into_inner()); | |
| 1215 | + let restore = std::env::var_os("VE_SW_ENC"); | |
| 1216 | + unsafe { | |
| 1217 | + std::env::set_var("VE_SW", "1"); | |
| 1218 | + std::env::remove_var("VE_SW_ENC"); | |
| 1219 | + std::env::set_var("VE_HW_TEST_FAKE", "1"); | |
| 1220 | + std::env::set_var("VE_HW_CHILD_BIN", env!("CARGO_BIN_EXE_hw-encode-child")); | |
| 1221 | + // Short, because one of these is waiting out a child that has stopped | |
| 1222 | + // answering and the wait is the thing under test. | |
| 1223 | + std::env::set_var("VE_HW_TIMEOUT_MS", "1500"); | |
| 1224 | + match abort { | |
| 1225 | + Some(at) => std::env::set_var("VE_HW_TEST_ABORT", at), | |
| 1226 | + None => std::env::remove_var("VE_HW_TEST_ABORT"), | |
| 1227 | + } | |
| 1228 | + match hang { | |
| 1229 | + Some(at) => std::env::set_var("VE_HW_TEST_HANG", at), | |
| 1230 | + None => std::env::remove_var("VE_HW_TEST_HANG"), | |
| 1231 | + } | |
| 1232 | + } | |
| 1233 | + let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)); | |
| 1234 | + unsafe { | |
| 1235 | + for var in [ | |
| 1236 | + "VE_HW_TEST_FAKE", | |
| 1237 | + "VE_HW_CHILD_BIN", | |
| 1238 | + "VE_HW_TIMEOUT_MS", | |
| 1239 | + "VE_HW_TEST_ABORT", | |
| 1240 | + "VE_HW_TEST_HANG", | |
| 1241 | + ] { | |
| 1242 | + std::env::remove_var(var); | |
| 1243 | + } | |
| 1244 | + // Put the software suite's pin back exactly as it was found -- it is | |
| 1245 | + // set once for the whole binary and this is the only thing that ever | |
| 1246 | + // takes it away. | |
| 1247 | + if let Some(pinned) = restore { | |
| 1248 | + std::env::set_var("VE_SW_ENC", pinned); | |
| 1249 | + } | |
| 1250 | + } | |
| 1251 | + match out { | |
| 1252 | + Ok(value) => value, | |
| 1253 | + Err(panic) => std::panic::resume_unwind(panic), | |
| 1254 | + } | |
| 1255 | +} | |
| 1256 | + | |
| 1257 | +/// The timeline these all export: short, and cut, so the export really runs a | |
| 1258 | +/// span loop rather than copying one clip. | |
| 1259 | +fn short_edit(source: &Path, frames: u32) -> (Project, engine::VideoMeta) { | |
| 1260 | + let (meta, _) = engine::demux::Demuxer::open(source).expect("open source"); | |
| 1261 | + let mut project = Project::single(source, meta.frame_count); | |
| 1262 | + assert!(project.split(frames)); | |
| 1263 | + assert!(project.delete(1)); | |
| 1264 | + assert_eq!(project.timeline_frames(), frames); | |
| 1265 | + (project, meta) | |
| 1266 | +} | |
| 1267 | + | |
| 1268 | +/// A whole export whose hardware encoder is killed three frames in: the editor | |
| 1269 | +/// is still here, and so is the file -- written again, from the first frame, by | |
| 1270 | +/// the software encoder for the same codec, and clean enough that an outside | |
| 1271 | +/// decoder reads every packet of it without a word. | |
| 1272 | +/// | |
| 1273 | +/// Invariant 1 at its entry surface: `export::start` is what the export card | |
| 1274 | +/// presses, and this is that same call with a driver dying under it. | |
| 1275 | +#[test] | |
| 1276 | +fn a_hardware_encoder_killed_mid_export_costs_the_file_nothing() { | |
| 1277 | + let source = asset("test_baseline.mp4"); | |
| 1278 | + let (project, meta) = short_edit(&source, 20); | |
| 1279 | + let out = out_path("hw_child_abort"); | |
| 1280 | + | |
| 1281 | + injected(Some("3"), None, || { | |
| 1282 | + // `Auto` is what an untouched export card sends: the seat that *may* | |
| 1283 | + // fall back, which is the whole question here. | |
| 1284 | + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); | |
| 1285 | + wait(&handle, Duration::from_secs(180)).expect("the export survived its encoder"); | |
| 1286 | + }); | |
| 1287 | + | |
| 1288 | + let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); | |
| 1289 | + assert_eq!(written.frame_count, 20, "every timeline frame was written"); | |
| 1290 | + assert_eq!(decode_all(&out).len(), 20, "and every one of them decodes"); | |
| 1291 | + if let Some(said) = ffmpeg_complaints(&out) { | |
| 1292 | + assert!( | |
| 1293 | + said.is_empty(), | |
| 1294 | + "ffmpeg read the fallback's file badly: {said}" | |
| 1295 | + ); | |
| 1296 | + } | |
| 1297 | + assert!(!part_path(&out).exists(), "the .part outlived the export"); | |
| 1298 | + std::fs::remove_file(&out).unwrap(); | |
| 1299 | +} | |
| 1300 | + | |
| 1301 | +/// The same death at the *open*: the child never gets far enough to say yes, so | |
| 1302 | +/// there is no hardware seat at all and the software one takes the export from | |
| 1303 | +/// the first frame. A refusal, not a crash, and the file is whole. | |
| 1304 | +#[test] | |
| 1305 | +fn a_hardware_encoder_killed_at_its_open_is_simply_no_seat() { | |
| 1306 | + let source = asset("test_baseline.mp4"); | |
| 1307 | + let (project, meta) = short_edit(&source, 12); | |
| 1308 | + let out = out_path("hw_child_abort_init"); | |
| 1309 | + | |
| 1310 | + injected(Some("init"), None, || { | |
| 1311 | + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); | |
| 1312 | + wait(&handle, Duration::from_secs(180)).expect("the export survived the open"); | |
| 1313 | + }); | |
| 1314 | + | |
| 1315 | + let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); | |
| 1316 | + assert_eq!(written.frame_count, 12); | |
| 1317 | + std::fs::remove_file(&out).unwrap(); | |
| 1318 | +} | |
| 1319 | + | |
| 1320 | +/// ...and at the finalize, which is the third place a ring resets: every | |
| 1321 | +/// picture is fed and the encoder is being flushed when it dies. | |
| 1322 | +#[test] | |
| 1323 | +fn a_hardware_encoder_killed_at_the_drain_costs_the_file_nothing() { | |
| 1324 | + let source = asset("test_baseline.mp4"); | |
| 1325 | + let (project, meta) = short_edit(&source, 12); | |
| 1326 | + let out = out_path("hw_child_abort_drain"); | |
| 1327 | + | |
| 1328 | + injected(Some("drain"), None, || { | |
| 1329 | + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); | |
| 1330 | + wait(&handle, Duration::from_secs(180)).expect("the export survived the drain"); | |
| 1331 | + }); | |
| 1332 | + | |
| 1333 | + let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); | |
| 1334 | + assert_eq!(written.frame_count, 12); | |
| 1335 | + assert_eq!(decode_all(&out).len(), 12); | |
| 1336 | + std::fs::remove_file(&out).unwrap(); | |
| 1337 | +} | |
| 1338 | + | |
| 1339 | +/// Invariant 4: a ring can wedge *without* anything dying -- the child stays | |
| 1340 | +/// alive and simply stops answering. The parent gives it `VE_HW_TIMEOUT_MS` and | |
| 1341 | +/// then kills it, which lands on the same fallback a death does. "Contained" | |
| 1342 | +/// here means bounded, so the wait is what is really being measured: an export | |
| 1343 | +/// that sat on a stuck child forever would be the hang this refuses. | |
| 1344 | +#[test] | |
| 1345 | +fn a_hardware_encoder_that_stops_answering_is_killed_and_replaced() { | |
| 1346 | + let source = asset("test_baseline.mp4"); | |
| 1347 | + let (project, meta) = short_edit(&source, 12); | |
| 1348 | + let out = out_path("hw_child_hang"); | |
| 1349 | + | |
| 1350 | + let started = Instant::now(); | |
| 1351 | + injected(None, Some("2"), || { | |
| 1352 | + let handle = engine::export::start(project, meta, &out, &ExportSettings::default()); | |
| 1353 | + wait(&handle, Duration::from_secs(180)).expect("the export outlived the wedge"); | |
| 1354 | + }); | |
| 1355 | + println!( | |
| 1356 | + "hung child: contained in {:.2} s", | |
| 1357 | + started.elapsed().as_secs_f64() | |
| 1358 | + ); | |
| 1359 | + | |
| 1360 | + let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file"); | |
| 1361 | + assert_eq!(written.frame_count, 12); | |
| 1362 | + assert_eq!(decode_all(&out).len(), 12); | |
| 1363 | + std::fs::remove_file(&out).unwrap(); | |
| 1364 | +} | |
| 1365 | + | |
| 1366 | +/// ...and the export that does **not** get written again: a person who picked | |
| 1367 | +/// the GPU on the export card asked for it by name, so a dead hardware seat is | |
| 1368 | +/// refused in words rather than answered with an hour in an encoder nobody | |
| 1369 | +/// chose. The same posture [`engine::export::start`] already takes for a machine | |
| 1370 | +/// with no hardware seat at all -- and the guard that separates the two is the | |
| 1371 | +/// one every test above depends on being narrow. | |
| 1372 | +/// | |
| 1373 | +/// The process is alive either way, which is the invariant; what differs is who | |
| 1374 | +/// is told. | |
| 1375 | +#[test] | |
| 1376 | +fn an_export_that_asked_for_the_gpu_by_name_refuses_instead_of_falling_back() { | |
| 1377 | + let source = asset("test_baseline.mp4"); | |
| 1378 | + let (project, meta) = short_edit(&source, 12); | |
| 1379 | + let out = out_path("hw_child_named_seat"); | |
| 1380 | + | |
| 1381 | + let error = injected(Some("2"), None, || { | |
| 1382 | + let settings = ExportSettings { | |
| 1383 | + seat: engine::export::EncoderSeat::Hardware, | |
| 1384 | + ..Default::default() | |
| 1385 | + }; | |
| 1386 | + let handle = engine::export::start(project, meta, &out, &settings); | |
| 1387 | + wait(&handle, Duration::from_secs(180)) | |
| 1388 | + .expect_err("a named hardware seat that died is not written again in software") | |
| 1389 | + }); | |
| 1390 | + | |
| 1391 | + println!("named hardware seat: {error}"); | |
| 1392 | + assert!( | |
| 1393 | + engine::hwproc::is_lost(&error), | |
| 1394 | + "the refusal has to name the hardware failure: {error}" | |
| 1395 | + ); | |
| 1396 | + assert!( | |
| 1397 | + !out.exists(), | |
| 1398 | + "a refused export still wrote {}", | |
| 1399 | + out.display() | |
| 1400 | + ); | |
| 1401 | + assert!(!part_path(&out).exists(), "the .part outlived the refusal"); | |
| 1402 | +} | |
| 1403 | + | |
| 1404 | +/// The seat's own contract, under the same injection and with no export around | |
| 1405 | +/// it: a killed child comes back as an error carrying | |
| 1406 | +/// [`engine::hwproc::HW_LOST`], every later call gives the same answer instead | |
| 1407 | +/// of blocking on a socket nobody holds, and the process doing the asking is | |
| 1408 | +/// still running to be asked. | |
| 1409 | +#[test] | |
| 1410 | +fn a_dead_encoder_answers_every_later_call_the_same_way() { | |
| 1411 | + let (width, height) = (320u32, 240u32); | |
| 1412 | + injected(Some("1"), None, || { | |
| 1413 | + let mut encoder = | |
| 1414 | + HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened"); | |
| 1415 | + let (y, u, v) = synthetic(0, width as usize, height as usize); | |
| 1416 | + assert!( | |
| 1417 | + encoder.encode(&y, &u, &v, width, height, false).is_ok(), | |
| 1418 | + "the first picture is before the injection point" | |
| 1419 | + ); | |
| 1420 | + let died = encoder | |
| 1421 | + .encode(&y, &u, &v, width, height, false) | |
| 1422 | + .expect_err("the second picture kills the child"); | |
| 1423 | + assert!( | |
| 1424 | + engine::hwproc::is_lost(&died), | |
| 1425 | + "an encoder death must say so: {died}" | |
| 1426 | + ); | |
| 1427 | + // The second ask is the one that would hang if the child were not | |
| 1428 | + // reaped, and it must not spend the timeout answering either. | |
| 1429 | + let again = Instant::now(); | |
| 1430 | + let repeat = encoder.drain().expect_err("the seat stays dead"); | |
| 1431 | + assert!(engine::hwproc::is_lost(&repeat), "{repeat}"); | |
| 1432 | + assert!( | |
| 1433 | + again.elapsed() < Duration::from_millis(500), | |
| 1434 | + "a dead seat answered only after waiting" | |
| 1435 | + ); | |
| 1436 | + }); | |
| 1437 | +} |
crates/engine/tests/hw_encode.rsmodified+50 -0
| @@ -216,6 +216,56 @@ fn a_decoded_buffer_is_encoded_without_ever_being_read_back() { | ||
| 216 | 216 | } |
| 217 | 217 | } |
| 218 | 218 | |
| 219 | +/// What the process boundary costs, at the size an export is really written at. | |
| 220 | +/// | |
| 221 | +/// The encoder lives in a child now ([`engine::hwproc`]) so that a driver's | |
| 222 | +/// `abort()` cannot take the editor with it, and the price of that has to be | |
| 223 | +/// small enough that nobody would trade it back: pictures reach the child | |
| 224 | +/// through a shared mapping rather than down a pipe, so a frame costs one | |
| 225 | +/// `memcpy` and a ten-byte message. `VE_HW_INPROCESS` pins the seat the way it | |
| 226 | +/// used to be, which is the only honest baseline there is. | |
| 227 | +/// | |
| 228 | +/// This is the *worst* case on purpose: an untouched clip's pictures never leave | |
| 229 | +/// the GPU at all (`a_decoded_buffer_is_encoded_without_ever_being_read_back`, | |
| 230 | +/// whose descriptors cross the same socket), so nothing an export really does is | |
| 231 | +/// slower than this. | |
| 232 | +#[test] | |
| 233 | +#[ignore = "needs libengine_hw.so and a VA-API driver with an H.264 encode entrypoint"] | |
| 234 | +fn isolating_the_encoder_costs_little_at_1080p() { | |
| 235 | + const FRAMES: u32 = 60; | |
| 236 | + let (width, height) = (1920u32, 1080u32); | |
| 237 | + let mut spent = Vec::new(); | |
| 238 | + for inprocess in [true, false] { | |
| 239 | + // SAFETY-of-a-sort: the ignored run is `--test-threads=1`, which is | |
| 240 | + // what this file's own header already requires of its env pins. | |
| 241 | + unsafe { | |
| 242 | + match inprocess { | |
| 243 | + true => std::env::set_var("VE_HW_INPROCESS", "1"), | |
| 244 | + false => std::env::remove_var("VE_HW_INPROCESS"), | |
| 245 | + } | |
| 246 | + } | |
| 247 | + let started = Instant::now(); | |
| 248 | + let Some((_, units)) = encode(width, height, FRAMES) else { | |
| 249 | + println!("no hardware encoder here -- skipping"); | |
| 250 | + return; | |
| 251 | + }; | |
| 252 | + assert_eq!(units, FRAMES, "one access unit per fed picture"); | |
| 253 | + spent.push(started.elapsed().as_secs_f64()); | |
| 254 | + } | |
| 255 | + let (local, remote) = (spent[0], spent[1]); | |
| 256 | + println!( | |
| 257 | + "1080p x{FRAMES}: in-process {:.1} fps, isolated {:.1} fps ({:.0}% of it)", | |
| 258 | + f64::from(FRAMES) / local, | |
| 259 | + f64::from(FRAMES) / remote, | |
| 260 | + 100.0 * local / remote | |
| 261 | + ); | |
| 262 | + assert!( | |
| 263 | + local / remote >= 0.85, | |
| 264 | + "isolation kept only {:.0}% of the in-process rate", | |
| 265 | + 100.0 * local / remote | |
| 266 | + ); | |
| 267 | +} | |
| 268 | + | |
| 219 | 269 | /// Decode and encode resolve through two independent symbol tables, so an |
| 220 | 270 | /// encoder that cannot load must not cost us the decoder (and vice versa). |
| 221 | 271 | /// |