forge
Explore
Log in

Don't you dare go Hollow

The driver that aborts kills a process nobody was editing in

Browse files at this commit

c0a18475483b5c830047f9951600692ec5d5dc22Ahmet Kaan GümüşParent: a0a2fa4
  • feat
    • the driver that aborts kills a process nobody was editing in
Show full message
✨ feat(engine): the driver that aborts kills a process nobody was editing in

Mesa's radeonsi calls libc abort() from its own C worker thread when the
video ring resets under it -- amdgpu_ctx_set_sw_reset_status, mesa 26.1.6,
vcn_unified_0 hung during an AV1 encode submission on 2026-08-13. A foreign
thread's abort is not an unwind, so every catch_unwind in the plugin was
structurally unable to see it: the editor died with the driver and took the
session's work with it.

So the encoder is not in the editor's address space any more. HwEncoder is a
handle on a `hw-encode-child` process that dlopens the plugin, and its death
-- by abort, by any signal, or by going quiet past VE_HW_TIMEOUT_MS -- comes
back as an error the export answers by writing the file again in software.
A person who picked the GPU by name still gets the refusal in words rather
than an encoder nobody chose.

Isolation that cost the speed would not be worth having, so pictures do not
travel down a pipe: in-memory ones go through a memfd mapped in both
processes, and pictures still on the GPU never move at all -- their
DRM-PRIME descriptors cross as file descriptors over SCM_RIGHTS, so the
zero-copy export path stays zero-copy across the boundary. Measured on this
box at 1080p: 430 fps in-process, 384 isolated, 89% of it, worst case
(every export of an untouched clip takes the descriptor path instead).

The proof does not need a wedged ring, which is the one thing a wedged
machine cannot supply: VE_HW_TEST_FAKE opens a stand-in seat in the child and
VE_HW_TEST_ABORT / VE_HW_TEST_HANG say where it dies or stops, so the
containment paths are exercised on any machine, GPU or no GPU.

Decode is still in the editor's process, where the same abort would still be
fatal; the seam to move it is now the one this built.
Cargo.lockmodified+1 -0
@@ -1639,6 +1639,7 @@ dependencies = [
16391639 "flacenc",
16401640 "hound",
16411641 "image",
1642+ "libc",
16421643 "libloading",
16431644 "miniz_oxide",
16441645 "mp4",
crates/engine-hw/src/lib.rsmodified+15 -3
@@ -6,9 +6,21 @@
66 //! negative code: the caller's contract is "any failure means use the software
77 //! codec".
88 //!
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 the *encode* half of this plugin is no longer
14+//! loaded by the editor at all: it is `dlopen`ed by the `hw-encode-child`
15+//! helper, one process per session, and a driver that aborts now costs an export
16+//! its seat rather than costing a person their session
17+//! ([`engine::hwproc`](../engine/hwproc/index.html)).
18+//!
19+//! corner-cut: *decode* is still in the editor's own address space, where the
20+//! same abort would still be fatal -- and the same ring hangs it (mmhub page
21+//! faults, this box, 2026-08-13). The upgrade path is the seam that already
22+//! exists: give `vh_open_at`/`vh_next_frame` the message tags `vh_enc_*` have in
23+//! `hwproc` and let the same helper hold both.
1224
1325 use std::collections::VecDeque;
1426 use std::ffi::{CStr, c_char, c_void};
crates/engine/Cargo.tomlmodified+6 -0
@@ -12,6 +12,12 @@ edition.workspace = true
1212 hound = "3.5.1"
1313 flacenc = { version = "0.5.1", default-features = false }
1414 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"
1521 # Still images, decoded once per placed clip (`decode::Still`). Pure Rust like
1622 # everything else here, and already in the app's tree (gpui pulls it), so this
1723 # 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+38 -3
@@ -494,7 +494,33 @@ pub fn start(
494494 format.name()
495495 )
496496 .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+ }
498524 _ => run_audio(&project, &meta, &part, &worker, &settings),
499525 };
500526 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 {
583609 /// ([`Enc::open`] runs ahead of the muxer), which is what makes the refusal
584610 /// free.
585611 fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Option<HwEncoder>> {
586- if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") {
612+ // `VE_HW_TEST_FAKE` is the containment tests' stand-in seat -- a child that
613+ // opens no driver at all -- and it is not what a software pin is pinning
614+ // away: the pin says "do not use this machine's GPU", and that seat is not
615+ // this machine's GPU. Without this the suite could only prove the fallback
616+ // on a run with no other export test in it.
617+ if settings.seat == EncoderSeat::Software
618+ || (forced("VE_SW_ENC") && !crate::hwproc::faked())
619+ {
587620 return Ok(None);
588621 }
589622 let opened = open_hw_seat(meta, settings);
@@ -3547,7 +3580,9 @@ impl Enc {
35473580 /// person picks it by name because the vendored encoder reset this project's GPU
35483581 /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to
35493582 /// widen.
3550- fn dma_want(&self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> {
3583+ /// `&mut` because an isolated seat has to *ask* the process it lives in
3584+ /// ([`crate::hwproc`]), which is a round trip on its socket.
3585+ fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> {
35513586 match self {
35523587 Self::Hw(hw) | Self::HevcHw(hw) => hw.dma_want(meta.width, meta.height),
35533588 _ => None,
crates/engine/src/hw.rsmodified+269 -15
@@ -123,6 +123,14 @@ impl Default for VhDma {
123123 pub struct DmaFrame(VhDma);
124124
125125 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+
126134 pub fn width(&self) -> u32 {
127135 self.0.width
128136 }
@@ -504,13 +512,39 @@ fn load_enc() -> Option<EncPlugin> {
504512 None
505513 }
506514
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 {
509525 plugin: &'static EncPlugin,
510526 handle: *mut c_void,
511527 }
512528
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+
514548 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded
515549 /// at a constant `bitrate` bits per second. `None` whenever hardware encode
516550 /// is unavailable -- plugin missing, plugin too old to export the encode
@@ -668,10 +702,10 @@ impl HwEncoder {
668702 })
669703 }
670704
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)> {
675709 let geometry = self.plugin.dma_geometry?;
676710 self.plugin.frame_dma?;
677711 let (mut coded_width, mut coded_height) = (0u32, 0u32);
@@ -679,12 +713,7 @@ impl HwEncoder {
679713 if unsafe { geometry(self.handle, &mut coded_width, &mut coded_height) } != 1 {
680714 return None;
681715 }
682- Some(DmaWant {
683- coded_width,
684- coded_height,
685- width,
686- height,
687- })
716+ Some((coded_width, coded_height))
688717 }
689718
690719 /// Feeds one picture the decoder left on the GPU. Same answer and same
@@ -733,7 +762,7 @@ impl HwEncoder {
733762 }
734763 }
735764
736-impl Drop for HwEncoder {
765+impl Drop for LocalEncoder {
737766 fn drop(&mut self) {
738767 // SAFETY: `handle` came from `vh_enc_open` and is closed exactly once.
739768 unsafe { (self.plugin.close)(self.handle) }
@@ -741,4 +770,229 @@ impl Drop for HwEncoder {
741770 }
742771
743772 // 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+657 -0
@@ -0,0 +1,657 @@
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+ pub fn dma_geometry(&mut self) -> Option<(u32, u32)> {
466+ self.request(&[T_GEOM], &[]).ok()?;
467+ let (tag, _) = recv_tag(&self.sock).ok()?;
468+ if tag != R_AU {
469+ return None;
470+ }
471+ let mut buf = [0u8; 8];
472+ self.sock.read_exact(&mut buf).ok()?;
473+ Some((
474+ u32::from_le_bytes(buf[..4].try_into().ok()?),
475+ u32::from_le_bytes(buf[4..].try_into().ok()?),
476+ ))
477+ }
478+
479+ /// Feeds one packed I420 picture through the shared mapping.
480+ pub fn encode(
481+ &mut self,
482+ y: &[u8],
483+ u: &[u8],
484+ v: &[u8],
485+ width: u32,
486+ height: u32,
487+ force_key: bool,
488+ ) -> crate::Result<Option<&[u8]>> {
489+ let total = y.len() + u.len() + v.len();
490+ if total > self.shm.len {
491+ return Err(format!(
492+ "a {width}x{height} picture does not fit the staging buffer opened for {}x{}",
493+ self.open.width, self.open.height
494+ )
495+ .into());
496+ }
497+ let bytes = self.shm.bytes();
498+ bytes[..y.len()].copy_from_slice(y);
499+ bytes[y.len()..y.len() + u.len()].copy_from_slice(u);
500+ bytes[y.len() + u.len()..total].copy_from_slice(v);
501+ let mut msg = vec![T_ENCODE];
502+ msg.extend_from_slice(&width.to_le_bytes());
503+ msg.extend_from_slice(&height.to_le_bytes());
504+ msg.push(u8::from(force_key));
505+ self.round_trip(&msg, &[])
506+ }
507+
508+ /// Feeds one picture the decoder left on the GPU. The descriptors go over
509+ /// with the message, so the buffer itself never moves.
510+ pub fn encode_dma(&mut self, dma: &VhDma, force_key: bool) -> crate::Result<Option<&[u8]>> {
511+ let fds: Vec<RawFd> = dma.fd.iter().copied().filter(|&fd| fd >= 0).collect();
512+ let mut msg = vec![T_DMA];
513+ msg.extend_from_slice(&dma.fourcc.to_le_bytes());
514+ msg.extend_from_slice(&dma.modifier.to_le_bytes());
515+ for value in [
516+ dma.coded_width,
517+ dma.coded_height,
518+ dma.width,
519+ dma.height,
520+ dma.offset[0],
521+ dma.offset[1],
522+ dma.stride[0],
523+ dma.stride[1],
524+ ] {
525+ msg.extend_from_slice(&value.to_le_bytes());
526+ }
527+ msg.push(fds.len() as u8);
528+ msg.push(u8::from(force_key));
529+ self.round_trip(&msg, &fds)
530+ }
531+
532+ /// Flushes the child's encoder; call until it answers `None`.
533+ pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
534+ self.round_trip(&[T_DRAIN], &[])
535+ }
536+
537+ /// One request and its reply, which is every call above: the child is fed,
538+ /// then read, and anything that is not an answer is the child being gone.
539+ fn round_trip(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<Option<&[u8]>> {
540+ self.request(msg, fds)?;
541+ let mut au = std::mem::take(&mut self.au);
542+ let read = read_reply(&mut self.sock, &mut au);
543+ self.au = au;
544+ // Every "no access unit" leaves through a `return`, so the borrow of the
545+ // buffer below is the only one alive when it is taken.
546+ match read {
547+ Ok(None) => return Ok(None),
548+ Ok(Some(Ok(()))) => {}
549+ // The child's *own* refusal: it is alive and said no, so this is an
550+ // ordinary encode error and the process stays as it is.
551+ Ok(Some(Err(message))) => return Err(message.into()),
552+ Err(e) => return Err(self.bury(&e.to_string())),
553+ }
554+ Ok(Some(&self.au))
555+ }
556+
557+ fn request(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<()> {
558+ if let Some(gone) = &self.lost {
559+ return Err(gone.clone().into());
560+ }
561+ match send_msg(&self.sock, msg, fds) {
562+ Ok(()) => Ok(()),
563+ Err(e) => Err(self.bury(&e.to_string())),
564+ }
565+ }
566+
567+ /// Reaps the child and remembers why, so no later call waits on it. Kills
568+ /// first: the child may be *stuck* rather than dead, which is the hang this
569+ /// timeout exists to contain, and a stuck child is never waited for.
570+ fn bury(&mut self, why: &str) -> crate::Error {
571+ let _ = self.child.kill();
572+ let status = self.child.wait().ok();
573+ // The two shapes a wedged ring takes, told apart by who did the
574+ // killing: a driver that called `abort()` leaves its own signal, while
575+ // a child that merely stopped answering is still holding `SIGKILL` from
576+ // the line above and the read's own timeout is the real reason.
577+ let how = match status.and_then(|s| std::os::unix::process::ExitStatusExt::signal(&s)) {
578+ Some(libc::SIGKILL) | None => format!("stopped answering ({why}) and was killed"),
579+ Some(signal) => format!("was killed by signal {signal}"),
580+ };
581+ let message =
582+ format!("{HW_LOST} {how}; the driver took it down and not the editor");
583+ self.lost = Some(message.clone());
584+ message.into()
585+ }
586+}
587+
588+impl Drop for Remote {
589+ fn drop(&mut self) {
590+ // Nothing is pending -- the export drains before it drops -- and a
591+ // signal is the one exit a wedged child is guaranteed to take.
592+ if self.lost.is_none() {
593+ let _ = self.child.kill();
594+ let _ = self.child.wait();
595+ }
596+ }
597+}
598+
599+// As the in-process session: one thread at a time (the export worker).
600+unsafe impl Send for Remote {}
601+
602+#[cfg(test)]
603+mod tests {
604+ use super::*;
605+
606+ /// Descriptors really cross the socket, and the mapping really is shared:
607+ /// the two halves of the frame hand-off, checked without a driver.
608+ #[test]
609+ fn a_mapping_and_its_descriptor_cross_a_socket() {
610+ let (a, b) = UnixStream::pair().expect("socketpair");
611+ let (mut mine, fd) = Shm::create(64).expect("memfd");
612+ mine.bytes()[..5].copy_from_slice(b"hello");
613+ send_msg(&a, &[7u8], &[fd.as_raw_fd()]).expect("send");
614+ let (tag, fds) = recv_tag(&b).expect("recv");
615+ assert_eq!(tag, 7);
616+ assert_eq!(fds.len(), 1, "the descriptor came over");
617+ let mut theirs = Shm::map(fds[0].as_raw_fd(), 64).expect("map the received descriptor");
618+ assert_eq!(&theirs.bytes()[..5], b"hello", "one store, two mappings");
619+ theirs.bytes()[0] = b'j';
620+ assert_eq!(&mine.bytes()[..5], b"jello", "and it is shared both ways");
621+ }
622+
623+ /// A dead peer must come back as an error, never as a `SIGPIPE` that kills
624+ /// the process doing the sending -- the whole point of `MSG_NOSIGNAL`.
625+ #[test]
626+ fn sending_to_a_closed_socket_errors_instead_of_signalling() {
627+ let (a, b) = UnixStream::pair().expect("socketpair");
628+ drop(b);
629+ assert!(send_msg(&a, &[1u8, 2, 3], &[]).is_err());
630+ }
631+
632+ /// The open crosses to the child as text and comes back the same struct.
633+ #[test]
634+ fn an_open_round_trips_through_argv() {
635+ let open = Open {
636+ seat: Seat::Hevc,
637+ width: 1920,
638+ height: 1080,
639+ fps_num: 30000,
640+ fps_den: 1001,
641+ bitrate: 12_345_678,
642+ colour: ColorDescription {
643+ matrix: Matrix::Bt2020Ncl,
644+ transfer: Transfer::Pq,
645+ full_range: true,
646+ },
647+ };
648+ let back = Open::from_argv(&open.argv()).expect("parse");
649+ assert!(back.seat == Seat::Hevc);
650+ assert_eq!(
651+ (back.width, back.height, back.fps_num, back.fps_den, back.bitrate),
652+ (1920, 1080, 30000, 1001, 12_345_678)
653+ );
654+ assert_eq!(back.colour, open.colour);
655+ assert_eq!(back.frame_bytes(), 1920 * 1080 * 3 / 2);
656+ }
657+}
crates/engine/src/lib.rsmodified+1 -0
@@ -13,6 +13,7 @@ pub mod edith;
1313 pub mod eq;
1414 pub mod export;
1515 pub mod hw;
16+pub mod hwproc;
1617 pub mod limiter;
1718 pub mod mux;
1819 pub mod playback;
crates/engine/tests/export.rsmodified+203 -0
@@ -1158,3 +1158,206 @@ fn a_proxy_of_real_4k_film_is_made_faster_than_it_plays() {
11581158 assert!(!part_path(&out).exists(), "a cancelled proxy left its .part");
11591159 assert_eq!(engine::proxy::cached(&film), None);
11601160 }
1161+
1162+// ---------------------------------------------------------------------------
1163+// The hardware encoder's process dying under the driver.
1164+//
1165+// Mesa's radeonsi calls libc `abort()` from its own C worker thread when the
1166+// video ring resets under it, which no `catch_unwind` in the process can see:
1167+// on 2026-08-13 that killed the editor mid-export and took the session with it.
1168+// The encoder now lives in a child (`engine::hwproc`), and these are the proof
1169+// that its death is an inconvenience rather than a crash.
1170+//
1171+// None of them needs a GPU, and that is deliberate: the machine where this
1172+// matters is the one whose ring is already wedged, and a test that had to hang a
1173+// real ring to run could never be the oracle for the fix. `VE_HW_TEST_FAKE`
1174+// opens a stand-in seat in the child that touches no driver;
1175+// `VE_HW_TEST_ABORT` / `VE_HW_TEST_HANG` say where it dies or stops.
1176+
1177+/// The stand-in-seat variables are process-wide, so the tests below take turns
1178+/// with them; nothing else in this binary reads them, and every one is removed
1179+/// again before the turn is given up.
1180+fn injected<T>(abort: Option<&str>, hang: Option<&str>, body: impl FnOnce() -> T) -> T {
1181+ use std::sync::Mutex;
1182+ static TURN: Mutex<()> = Mutex::new(());
1183+ let _turn = TURN.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1184+ unsafe {
1185+ std::env::set_var("VE_HW_TEST_FAKE", "1");
1186+ std::env::set_var("VE_HW_CHILD_BIN", env!("CARGO_BIN_EXE_hw-encode-child"));
1187+ // Short, because one of these is waiting out a child that has stopped
1188+ // answering and the wait is the thing under test.
1189+ std::env::set_var("VE_HW_TIMEOUT_MS", "1500");
1190+ match abort {
1191+ Some(at) => std::env::set_var("VE_HW_TEST_ABORT", at),
1192+ None => std::env::remove_var("VE_HW_TEST_ABORT"),
1193+ }
1194+ match hang {
1195+ Some(at) => std::env::set_var("VE_HW_TEST_HANG", at),
1196+ None => std::env::remove_var("VE_HW_TEST_HANG"),
1197+ }
1198+ }
1199+ let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(body));
1200+ unsafe {
1201+ for var in [
1202+ "VE_HW_TEST_FAKE",
1203+ "VE_HW_CHILD_BIN",
1204+ "VE_HW_TIMEOUT_MS",
1205+ "VE_HW_TEST_ABORT",
1206+ "VE_HW_TEST_HANG",
1207+ ] {
1208+ std::env::remove_var(var);
1209+ }
1210+ }
1211+ match out {
1212+ Ok(value) => value,
1213+ Err(panic) => std::panic::resume_unwind(panic),
1214+ }
1215+}
1216+
1217+/// The timeline these all export: short, and cut, so the export really runs a
1218+/// span loop rather than copying one clip.
1219+fn short_edit(source: &Path, frames: u32) -> (Project, engine::VideoMeta) {
1220+ let (meta, _) = engine::demux::Demuxer::open(source).expect("open source");
1221+ let mut project = Project::single(source, meta.frame_count);
1222+ assert!(project.split(frames));
1223+ assert!(project.delete(1));
1224+ assert_eq!(project.timeline_frames(), frames);
1225+ (project, meta)
1226+}
1227+
1228+/// A whole export whose hardware encoder is killed three frames in: the editor
1229+/// is still here, and so is the file -- written again, from the first frame, by
1230+/// the software encoder for the same codec, and clean enough that an outside
1231+/// decoder reads every packet of it without a word.
1232+///
1233+/// Invariant 1 at its entry surface: `export::start` is what the export card
1234+/// presses, and this is that same call with a driver dying under it.
1235+#[test]
1236+fn a_hardware_encoder_killed_mid_export_costs_the_file_nothing() {
1237+ pin_software();
1238+ let source = asset("test_baseline.mp4");
1239+ let (project, meta) = short_edit(&source, 20);
1240+ let out = out_path("hw_child_abort");
1241+
1242+ injected(Some("3"), None, || {
1243+ // `Auto` is what an untouched export card sends: the seat that *may*
1244+ // fall back, which is the whole question here.
1245+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
1246+ wait(&handle, Duration::from_secs(180)).expect("the export survived its encoder");
1247+ });
1248+
1249+ let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file");
1250+ assert_eq!(written.frame_count, 20, "every timeline frame was written");
1251+ assert_eq!(decode_all(&out).len(), 20, "and every one of them decodes");
1252+ if let Some(said) = ffmpeg_complaints(&out) {
1253+ assert!(
1254+ said.is_empty(),
1255+ "ffmpeg read the fallback's file badly: {said}"
1256+ );
1257+ }
1258+ assert!(!part_path(&out).exists(), "the .part outlived the export");
1259+ std::fs::remove_file(&out).unwrap();
1260+}
1261+
1262+/// The same death at the *open*: the child never gets far enough to say yes, so
1263+/// there is no hardware seat at all and the software one takes the export from
1264+/// the first frame. A refusal, not a crash, and the file is whole.
1265+#[test]
1266+fn a_hardware_encoder_killed_at_its_open_is_simply_no_seat() {
1267+ pin_software();
1268+ let source = asset("test_baseline.mp4");
1269+ let (project, meta) = short_edit(&source, 12);
1270+ let out = out_path("hw_child_abort_init");
1271+
1272+ injected(Some("init"), None, || {
1273+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
1274+ wait(&handle, Duration::from_secs(180)).expect("the export survived the open");
1275+ });
1276+
1277+ let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file");
1278+ assert_eq!(written.frame_count, 12);
1279+ std::fs::remove_file(&out).unwrap();
1280+}
1281+
1282+/// ...and at the finalize, which is the third place a ring resets: every
1283+/// picture is fed and the encoder is being flushed when it dies.
1284+#[test]
1285+fn a_hardware_encoder_killed_at_the_drain_costs_the_file_nothing() {
1286+ pin_software();
1287+ let source = asset("test_baseline.mp4");
1288+ let (project, meta) = short_edit(&source, 12);
1289+ let out = out_path("hw_child_abort_drain");
1290+
1291+ injected(Some("drain"), None, || {
1292+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
1293+ wait(&handle, Duration::from_secs(180)).expect("the export survived the drain");
1294+ });
1295+
1296+ let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file");
1297+ assert_eq!(written.frame_count, 12);
1298+ assert_eq!(decode_all(&out).len(), 12);
1299+ std::fs::remove_file(&out).unwrap();
1300+}
1301+
1302+/// Invariant 4: a ring can wedge *without* anything dying -- the child stays
1303+/// alive and simply stops answering. The parent gives it `VE_HW_TIMEOUT_MS` and
1304+/// then kills it, which lands on the same fallback a death does. "Contained"
1305+/// here means bounded, so the wait is what is really being measured: an export
1306+/// that sat on a stuck child forever would be the hang this refuses.
1307+#[test]
1308+fn a_hardware_encoder_that_stops_answering_is_killed_and_replaced() {
1309+ pin_software();
1310+ let source = asset("test_baseline.mp4");
1311+ let (project, meta) = short_edit(&source, 12);
1312+ let out = out_path("hw_child_hang");
1313+
1314+ let started = Instant::now();
1315+ injected(None, Some("2"), || {
1316+ let handle = engine::export::start(project, meta, &out, &ExportSettings::default());
1317+ wait(&handle, Duration::from_secs(180)).expect("the export outlived the wedge");
1318+ });
1319+ println!(
1320+ "hung child: contained in {:.2} s",
1321+ started.elapsed().as_secs_f64()
1322+ );
1323+
1324+ let (written, _) = engine::demux::Demuxer::open(&out).expect("the export is a file");
1325+ assert_eq!(written.frame_count, 12);
1326+ assert_eq!(decode_all(&out).len(), 12);
1327+ std::fs::remove_file(&out).unwrap();
1328+}
1329+
1330+/// The seat's own contract, under the same injection and with no export around
1331+/// it: a killed child comes back as an error carrying
1332+/// [`engine::hwproc::HW_LOST`], every later call gives the same answer instead
1333+/// of blocking on a socket nobody holds, and the process doing the asking is
1334+/// still running to be asked.
1335+#[test]
1336+fn a_dead_encoder_answers_every_later_call_the_same_way() {
1337+ let (width, height) = (320u32, 240u32);
1338+ injected(Some("1"), None, || {
1339+ let mut encoder =
1340+ HwEncoder::open(width, height, 30, 1, 1_000_000).expect("the stand-in seat opened");
1341+ let (y, u, v) = synthetic(0, width as usize, height as usize);
1342+ assert!(
1343+ encoder.encode(&y, &u, &v, width, height, false).is_ok(),
1344+ "the first picture is before the injection point"
1345+ );
1346+ let died = encoder
1347+ .encode(&y, &u, &v, width, height, false)
1348+ .expect_err("the second picture kills the child");
1349+ assert!(
1350+ engine::hwproc::is_lost(&died),
1351+ "an encoder death must say so: {died}"
1352+ );
1353+ // The second ask is the one that would hang if the child were not
1354+ // reaped, and it must not spend the timeout answering either.
1355+ let again = Instant::now();
1356+ let repeat = encoder.drain().expect_err("the seat stays dead");
1357+ assert!(engine::hwproc::is_lost(&repeat), "{repeat}");
1358+ assert!(
1359+ again.elapsed() < Duration::from_millis(500),
1360+ "a dead seat answered only after waiting"
1361+ );
1362+ });
1363+}
crates/engine/tests/hw_encode.rsmodified+50 -0
@@ -216,6 +216,56 @@ fn a_decoded_buffer_is_encoded_without_ever_being_read_back() {
216216 }
217217 }
218218
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+
219269 /// Decode and encode resolve through two independent symbol tables, so an
220270 /// encoder that cannot load must not cost us the decoder (and vice versa).
221271 ///