forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

hwproc.rs942 lines, 35.9 KiBHistoryRawDownload
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::deadline`] -- the parent sees a closed socket or a timed-out read,
17//! reaps the child, and reports a [`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`, which both sides read and write through their own descriptor), so a
24//! frame costs one write and a read and a 10-byte message. Pictures still on the
25//! GPU never move at all: the DRM-PRIME descriptors travel as file descriptors
26//! over `SCM_RIGHTS`, so the zero-copy export path stays zero-copy across the
27//! process boundary.
28//!
29//! Nothing here is `unsafe`: the memfd and the descriptor passing go through
30//! `rustix` and `nix`, and the staging buffer is file I/O rather than a mapping.
31
32use std::ffi::OsString;
33use std::fs::File;
34use std::io::{IoSlice, IoSliceMut, Read, Write};
35use std::mem::MaybeUninit;
36use std::os::fd::{AsFd, AsRawFd, OwnedFd, RawFd};
37use std::os::unix::fs::FileExt;
38use std::os::unix::net::UnixStream;
39use std::path::PathBuf;
40use std::process::{Child, Command, Stdio};
41use std::time::Duration;
42
43use nix::sys::socket::{ControlMessage, MsgFlags, UnixAddr, sendmsg};
44use rustix::net::{RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags};
45use rustix::process::{Signal, set_parent_process_death_signal};
46
47use crate::colorspace::{ColorDescription, Matrix, Transfer};
48use crate::hw::{DmaFrame, VhDma};
49
50/// The words every "the child is gone" error carries, for the person reading
51/// the log; what *decides* anything is [`Lost`], never this text.
52pub const HW_LOST: &str = "the hardware encoder process";
53
54/// The error a dead child carries.
55///
56/// A type and not a phrase. [`is_lost`] is what commits a whole export to being
57/// written again from the first frame ([`crate::export::start`]), and matching
58/// on words handed that decision to any future error whose message happened to
59/// mention the child -- a silent re-encode of a feature film, caused by a
60/// wording. Nothing outside this module can make one.
61#[derive(Debug)]
62pub struct Lost(pub(crate) String);
63
64impl std::fmt::Display for Lost {
65 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66 f.write_str(&self.0)
67 }
68}
69
70impl std::error::Error for Lost {}
71
72/// Whether an error is one: a driver that took its process down, rather than a
73/// picture this engine got wrong.
74pub fn is_lost(error: &crate::Error) -> bool {
75 error.downcast_ref::<Lost>().is_some()
76}
77
78/// The child's file name. It is a binary of the `engine-hw` package, built into
79/// the same directory as the editor, and it is the only process that opens a
80/// video driver.
81const BIN: &str = "hw-child";
82
83/// Which encoder the child opens. Sent as argv, so the child needs no protocol
84/// before it has one.
85#[derive(Clone, Copy, PartialEq, Eq)]
86pub enum Seat {
87 H264,
88 Intra,
89 Av1,
90 Hevc,
91 HevcIntra,
92}
93
94impl Seat {
95 pub fn code(self) -> u8 {
96 match self {
97 Self::H264 => 0,
98 Self::Intra => 1,
99 Self::Av1 => 2,
100 Self::Hevc => 3,
101 Self::HevcIntra => 4,
102 }
103 }
104
105 pub fn from_code(code: u8) -> Option<Self> {
106 Some(match code {
107 0 => Self::H264,
108 1 => Self::Intra,
109 2 => Self::Av1,
110 3 => Self::Hevc,
111 4 => Self::HevcIntra,
112 _ => return None,
113 })
114 }
115}
116
117/// How the encode seat spends bits: a constant bitrate in bits per second, or a
118/// constant quantiser (H.264/HEVC 0..51, AV1 0..255 on the seat's own scale).
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120pub enum SeatRate {
121 Bitrate(u64),
122 ConstantQp(u32),
123}
124
125/// Everything an open needs, in one place because it travels as argv and comes
126/// back as a struct on the other side.
127#[derive(Clone, Copy)]
128pub struct Open {
129 pub seat: Seat,
130 pub width: u32,
131 pub height: u32,
132 pub fps_num: u32,
133 pub fps_den: u32,
134 pub rate: SeatRate,
135 /// What the sequence header will say the samples mean. Only the HEVC seat
136 /// takes one; the others ignore it.
137 pub colour: ColorDescription,
138 /// Pictures between key frames; `None` is the seat's own two seconds.
139 pub gop: Option<u32>,
140 /// Code at 10 bits (HEVC Main10): pictures arrive as 16-bit LE samples.
141 pub ten_bit: bool,
142}
143
144impl Open {
145 fn argv(&self) -> Vec<String> {
146 let (matrix, transfer) = (
147 match self.colour.matrix {
148 Matrix::Bt709 => 0,
149 Matrix::Bt601 => 1,
150 Matrix::Bt2020Ncl => 2,
151 },
152 match self.colour.transfer {
153 Transfer::Sdr => 0,
154 Transfer::Pq => 1,
155 Transfer::Hlg => 2,
156 },
157 );
158 [
159 u32::from(self.seat.code()),
160 self.width,
161 self.height,
162 self.fps_num,
163 self.fps_den,
164 matrix,
165 transfer,
166 u32::from(self.colour.full_range),
167 ]
168 .iter()
169 .map(u32::to_string)
170 .chain(match self.rate {
171 SeatRate::Bitrate(bps) => [0, bps],
172 SeatRate::ConstantQp(qp) => [1, u64::from(qp)],
173 }.map(|v| v.to_string()))
174 .chain(std::iter::once(self.gop.unwrap_or(0).to_string()))
175 .chain(std::iter::once(u8::from(self.ten_bit).to_string()))
176 .collect()
177 }
178
179 /// The other half of [`Open::argv`], in the child.
180 pub fn from_argv(args: &[String]) -> Option<Self> {
181 let n = |i: usize| args.get(i)?.parse::<u32>().ok();
182 Some(Self {
183 seat: Seat::from_code(u8::try_from(n(0)?).ok()?)?,
184 width: n(1)?,
185 height: n(2)?,
186 fps_num: n(3)?,
187 fps_den: n(4)?,
188 rate: {
189 let value = args.get(9)?.parse::<u64>().ok()?;
190 match n(8)? {
191 0 => SeatRate::Bitrate(value),
192 1 => SeatRate::ConstantQp(u32::try_from(value).ok()?),
193 _ => return None,
194 }
195 },
196 colour: ColorDescription {
197 matrix: match n(5)? {
198 0 => Matrix::Bt709,
199 1 => Matrix::Bt601,
200 _ => Matrix::Bt2020Ncl,
201 },
202 transfer: match n(6)? {
203 0 => Transfer::Sdr,
204 1 => Transfer::Pq,
205 _ => Transfer::Hlg,
206 },
207 full_range: n(7)? != 0,
208 },
209 gop: match n(10)? {
210 0 => None,
211 gop => Some(gop),
212 },
213 ten_bit: n(11)? != 0,
214 })
215 }
216
217 /// How many bytes one packed I420 picture of this size takes -- the size of
218 /// the shared mapping, decided once at the open because the export feeds one
219 /// canvas size for the whole file.
220 pub fn frame_bytes(&self) -> usize {
221 let (w, h) = (self.width as usize, self.height as usize);
222 let samples = w * h + 2 * (w.div_ceil(2) * h.div_ceil(2));
223 if self.ten_bit { samples * 2 } else { samples }
224 }
225}
226
227// Requests, parent to child (encode seat).
228pub const T_ENCODE: u8 = 1;
229pub const T_DMA: u8 = 2;
230pub const T_DRAIN: u8 = 3;
231pub const T_GEOM: u8 = 4;
232pub const T_ENCODE16: u8 = 8;
233// Requests, parent to child (decode seat). `T_NEXT` has no body, `T_NEXT_DMA`
234// carries `coded_width, coded_height, width, height` as u32 LE, `T_SEEK` the
235// 1-based target sample as u32 LE.
236pub const T_NEXT: u8 = 5;
237pub const T_NEXT_DMA: u8 = 6;
238pub const T_SEEK: u8 = 7;
239/// `T_NEXT`, but a picture deeper than 8 bits comes back as `K_PIXELS16`.
240pub const T_NEXT_WIDE: u8 = 9;
241pub const T_NEXT_DMA16: u8 = 10;
242// Replies, child to parent. `R_NONE` carries no body; `R_AU` and `R_ERR` carry
243// a u32 LE length and that many bytes. Descriptors ride on the tag byte.
244pub const R_NONE: u8 = 0;
245pub const R_AU: u8 = 1;
246pub const R_ERR: u8 = 2;
247// First byte of a decode frame's `R_AU` body: the picture is in the staging
248// buffer as packed I420 (`K_PIXELS`: then `w` and `h` as u32 LE follow), or it
249// is still on the GPU (`K_DMA`: the descriptor follows, see `DMA_BODY`, and the
250// descriptors ride on the tag byte, one per plane object).
251pub const K_PIXELS: u8 = 0;
252pub const K_DMA: u8 = 1;
253/// As `K_PIXELS`, with 16-bit LE samples at 10-bit scale.
254pub const K_PIXELS16: u8 = 2;
255/// The `K_DMA` descriptor after its kind byte: fourcc u32, modifier u64, coded
256/// width and height, picture width and height, two offsets and two strides as
257/// u32 each, then the number of descriptors (1 or 2) as one byte.
258pub const DMA_BODY: usize = 4 + 8 + 4 * 8 + 1;
259
260/// A `memfd` this process reads and writes through its own descriptor: the
261/// staging buffer one picture is written into and read out of, shared with the
262/// other process. The protocol -- one request, one reply, never overlapping -- is
263/// what keeps only one of the two touching it at a time.
264///
265/// File I/O rather than a mapping: an `mmap` is the one thing here that needs
266/// `unsafe` at every turn, and a picture is copied in and out once either way.
267pub struct Shm {
268 file: File,
269 len: usize,
270}
271
272impl Shm {
273 /// Creates one of `len` bytes, returning it plus the descriptor to hand the
274 /// other process.
275 pub fn create(len: usize) -> std::io::Result<(Self, OwnedFd)> {
276 let fd = rustix::fs::memfd_create("edith-hwenc", rustix::fs::MemfdFlags::CLOEXEC)
277 .map_err(std::io::Error::from)?;
278 let file = File::from(fd);
279 file.set_len(len as u64)?;
280 let shared = OwnedFd::from(file.try_clone()?);
281 Ok((Self { file, len }, shared))
282 }
283
284 /// Takes the other process's descriptor of a buffer it created, `len` bytes long.
285 pub fn from_fd(fd: OwnedFd, len: usize) -> Self {
286 Self {
287 file: File::from(fd),
288 len,
289 }
290 }
291
292 /// How many bytes the buffer holds.
293 pub fn capacity(&self) -> usize {
294 self.len
295 }
296
297 /// Writes `parts` back to back from the start of the buffer.
298 pub fn write_picture(&self, parts: &[&[u8]]) -> std::io::Result<()> {
299 let mut at = 0u64;
300 for part in parts {
301 self.file.write_all_at(part, at)?;
302 at += part.len() as u64;
303 }
304 Ok(())
305 }
306
307 /// Reads the first `len` bytes of the buffer into `into`, reusing its
308 /// allocation.
309 pub fn read_into(&self, into: &mut Vec<u8>, len: usize) -> std::io::Result<()> {
310 if len > self.len {
311 return Err(std::io::Error::new(
312 std::io::ErrorKind::InvalidInput,
313 "a read past the end of the staging buffer",
314 ));
315 }
316 into.resize(len, 0);
317 self.file.read_exact_at(into, 0)
318 }
319
320 pub fn read_u16(&self, offset: usize, count: usize) -> std::io::Result<Vec<u16>> {
321 if offset + 2 * count > self.len {
322 return Err(std::io::Error::new(
323 std::io::ErrorKind::InvalidInput,
324 "a read past the end of the staging buffer",
325 ));
326 }
327 let mut out = vec![0u16; count];
328 self.file.read_exact_at(bytemuck::cast_slice_mut(&mut out), offset as u64)?;
329 Ok(out)
330 }
331
332 /// Reads the first `len` bytes of the buffer into an owned one.
333 pub fn read_bytes(&self, len: usize) -> std::io::Result<Vec<u8>> {
334 if len > self.len {
335 return Err(std::io::Error::new(
336 std::io::ErrorKind::InvalidInput,
337 "a read past the end of the staging buffer",
338 ));
339 }
340 let mut bytes = vec![0u8; len];
341 self.file.read_exact_at(&mut bytes, 0)?;
342 Ok(bytes)
343 }
344}
345
346/// Sends one message with its file descriptors attached.
347///
348/// `MSG_NOSIGNAL` is the point of writing this by hand rather than
349/// [`Write::write_all`]: a child that has just died leaves a socket whose next
350/// write raises `SIGPIPE`, and a crash-containment path that kills the editor
351/// with a signal of its own would be no containment at all.
352pub fn send_msg(sock: &UnixStream, bytes: &[u8], fds: &[RawFd]) -> std::io::Result<()> {
353 debug_assert!(!bytes.is_empty(), "ancillary data rides on a real byte");
354 let rights = [ControlMessage::ScmRights(fds)];
355 let control: &[ControlMessage] = if fds.is_empty() { &[] } else { &rights };
356 let sent = loop {
357 match sendmsg::<UnixAddr>(
358 sock.as_raw_fd(),
359 &[IoSlice::new(bytes)],
360 control,
361 MsgFlags::MSG_NOSIGNAL,
362 None,
363 ) {
364 Err(nix::errno::Errno::EINTR) => continue,
365 other => break other.map_err(std::io::Error::from)?,
366 }
367 };
368 // Messages here are tens of bytes and a socket buffer is kilobytes, so a
369 // short send means the peer is gone rather than that we should loop.
370 if sent != bytes.len() {
371 return Err(std::io::Error::new(
372 std::io::ErrorKind::WriteZero,
373 "short send",
374 ));
375 }
376 Ok(())
377}
378
379/// Reads the one byte a message's descriptors ride on, and those descriptors.
380///
381/// Ancillary data attaches to a position in the byte stream, so the tag is read
382/// with `recvmsg` and everything after it with an ordinary read.
383pub fn recv_tag(sock: &UnixStream) -> std::io::Result<(u8, Vec<OwnedFd>)> {
384 let mut byte = [0u8; 1];
385 let mut iov = [IoSliceMut::new(&mut byte)];
386 // Room for four descriptors; the most anything here sends is two.
387 let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(4))];
388 let mut control = RecvAncillaryBuffer::new(&mut space);
389 let received = loop {
390 match rustix::net::recvmsg(sock, &mut iov, &mut control, RecvFlags::CMSG_CLOEXEC) {
391 Err(rustix::io::Errno::INTR) => continue,
392 other => break other.map_err(std::io::Error::from)?,
393 }
394 };
395 if received.bytes == 0 {
396 return Err(std::io::Error::new(
397 std::io::ErrorKind::UnexpectedEof,
398 "peer closed",
399 ));
400 }
401 let mut fds = Vec::new();
402 for message in control.drain() {
403 if let RecvAncillaryMessage::ScmRights(rights) = message {
404 fds.extend(rights);
405 }
406 }
407 Ok((byte[0], fds))
408}
409
410/// One access unit, or the child's own error, read off the socket.
411fn read_reply(sock: &mut UnixStream, au: &mut Vec<u8>) -> std::io::Result<Option<Result<(), String>>> {
412 let (tag, _) = recv_tag(sock)?;
413 if tag == R_NONE {
414 return Ok(None);
415 }
416 let mut len = [0u8; 4];
417 sock.read_exact(&mut len)?;
418 let len = u32::from_le_bytes(len) as usize;
419 au.clear();
420 au.resize(len, 0);
421 sock.read_exact(au)?;
422 Ok(Some(match tag {
423 R_AU => Ok(()),
424 _ => Err(String::from_utf8_lossy(au).into_owned()),
425 }))
426}
427
428/// Writes one reply: the tag with `fds` riding on it, then the body when the tag
429/// carries one (`R_AU` and `R_ERR` do; `R_NONE` is the tag alone).
430pub fn send_reply(sock: &mut UnixStream, tag: u8, body: &[u8], fds: &[RawFd]) -> std::io::Result<()> {
431 send_msg(sock, &[tag], fds)?;
432 if tag == R_AU || tag == R_ERR {
433 sock.write_all(&(body.len() as u32).to_le_bytes())?;
434 sock.write_all(body)?;
435 }
436 Ok(())
437}
438
439/// Reads one reply: its tag and the descriptors that rode on it, and its body
440/// into `body` when the tag carries one.
441pub fn recv_reply(sock: &mut UnixStream, body: &mut Vec<u8>) -> std::io::Result<(u8, Vec<OwnedFd>)> {
442 let (tag, fds) = recv_tag(sock)?;
443 body.clear();
444 if tag == R_AU || tag == R_ERR {
445 let mut len = [0u8; 4];
446 sock.read_exact(&mut len)?;
447 body.resize(u32::from_le_bytes(len) as usize, 0);
448 sock.read_exact(body)?;
449 }
450 Ok((tag, fds))
451}
452
453/// Where the helper lives: told outright, or beside the running executable --
454/// which is `target/<profile>/` for the editor and one directory up from
455/// `deps/` for a test binary -- or, when cargo started the process, in the
456/// workspace's target directory under this build's profile. That last place is
457/// what a test finds the child in when cargo's `build-dir` puts the test
458/// binaries outside `target/` (the workspace's `.cargo/config.toml` names it as
459/// `EDITH_TARGET_DIR`).
460fn locate_child() -> Option<PathBuf> {
461 if let Some(pinned) = crate::envcfg::var_os("VE_HW_CHILD_BIN") {
462 let pinned = PathBuf::from(pinned);
463 return pinned.is_file().then_some(pinned);
464 }
465 let exe = std::env::current_exe().ok()?;
466 let dir = exe.parent()?.to_path_buf();
467 let profile = if cfg!(debug_assertions) { "debug" } else { "release" };
468 let target = crate::envcfg::var_os("EDITH_TARGET_DIR").map(|t| PathBuf::from(t).join(profile).join(BIN));
469 [Some(dir.join(BIN)), dir.parent().map(|up| up.join(BIN)), target]
470 .into_iter()
471 .flatten()
472 .find(|candidate| candidate.is_file())
473}
474
475/// The command that builds the child, as the warning and the test panics say it.
476pub const BUILD_CHILD: &str = "cargo build -p engine-hw --bin hw-child";
477
478/// Whether this machine has a DRM render node, the thing the hardware seats
479/// need. `false` on a machine with no GPU, where a missing child is expected.
480pub fn render_node_present() -> bool {
481 std::fs::read_dir("/dev/dri").is_ok_and(|dir| {
482 dir.flatten()
483 .any(|entry| entry.file_name().to_string_lossy().starts_with("renderD"))
484 })
485}
486
487/// Where the child binary is, or `None` when it is not built next to the
488/// editor (and `VE_HW_CHILD_BIN` does not name a file). A missing child on a
489/// machine with a render node is warned about once, on stderr.
490pub fn child_path() -> Option<PathBuf> {
491 static WARNED: std::sync::Once = std::sync::Once::new();
492 let found = locate_child();
493 if found.is_none() {
494 WARNED.call_once(|| {
495 if render_node_present() {
496 eprintln!(
497 "edith: hardware decode/encode is off: this machine has a GPU but hw-child is not built. \
498 Run `{BUILD_CHILD}` (or set VE_HW_CHILD_BIN to a built hw-child)."
499 );
500 }
501 });
502 }
503 found
504}
505
506/// Whether an isolated child can be had at all -- a binary to run. `false`
507/// means every hardware seat answers "no" and the software codec takes over.
508pub fn available() -> bool {
509 child_path().is_some()
510}
511
512/// Starts the child with `args` (its mode first, then the mode's own arguments)
513/// and hands it one end of a socket pair as its standard input, which is the
514/// only channel the child has. Its stdout goes to our stderr: an MCP client
515/// reads our stdout as JSON-RPC only. `None` when there is no child binary or
516/// it will not start.
517pub fn spawn_child(args: &[OsString]) -> Option<(Child, UnixStream)> {
518 type Job = (Vec<OsString>, std::sync::mpsc::Sender<Option<(Child, UnixStream)>>);
519 static SPAWNER: std::sync::OnceLock<std::sync::mpsc::Sender<Job>> = std::sync::OnceLock::new();
520 let jobs = SPAWNER.get_or_init(|| {
521 let (tx, rx) = std::sync::mpsc::channel::<Job>();
522 let _ = std::thread::Builder::new().name("hw-spawn".into()).spawn(move || {
523 for (args, back) in rx {
524 let _ = back.send(spawn_here(&args));
525 }
526 });
527 tx
528 });
529 let (back, answer) = std::sync::mpsc::channel();
530 jobs.send((args.to_vec(), back)).ok()?;
531 answer.recv().ok()?
532}
533
534fn spawn_here(args: &[OsString]) -> Option<(Child, UnixStream)> {
535 let bin = child_path()?;
536 let (mine, theirs) = UnixStream::pair().ok()?;
537 mine.set_read_timeout(Some(timeout())).ok()?;
538 let mut command = Command::new(bin);
539 crate::envcfg::apply(&mut command);
540 let child = command
541 .args(args)
542 .stdin(Stdio::from(OwnedFd::from(theirs)))
543 .stdout(Stdio::from(std::io::stderr().as_fd().try_clone_to_owned().ok()?))
544 .spawn()
545 .ok()?;
546 Some((child, mine))
547}
548
549/// The child's side of the containment: it dies with the parent, so an editor
550/// that is killed or aborts does not leave a driver holder behind. Called
551/// first thing in the child.
552pub fn die_with_parent() {
553 let _ = set_parent_process_death_signal(Some(Signal::KILL));
554}
555
556/// How long one call to the child may take before the child is treated as hung
557/// (`VE_HW_TIMEOUT_MS`, 15 s by default).
558pub fn timeout() -> Duration {
559 let ms = crate::envcfg::var("VE_HW_TIMEOUT_MS")
560 .and_then(|v| v.parse().ok())
561 .unwrap_or(15_000);
562 Duration::from_millis(ms)
563}
564
565/// The test-only stand-in seat: a child that opens no driver at all, so the
566/// containment paths below can be exercised on a machine whose GPU is wedged --
567/// which is the only machine where they matter and the only one where the real
568/// trigger cannot be pulled.
569pub fn faked() -> bool {
570 crate::envcfg::var_os("VE_HW_TEST_FAKE").is_some()
571}
572
573/// Packs Y, U and V samples as 16-bit LE, back to back, into `out`.
574const _: () = assert!(cfg!(target_endian = "little"));
575
576pub fn pack16(y: &[u16], u: &[u16], v: &[u16], out: &mut Vec<u8>) {
577 out.clear();
578 out.reserve(2 * (y.len() + u.len() + v.len()));
579 for plane in [y, u, v] {
580 out.extend_from_slice(bytemuck::cast_slice(plane));
581 }
582}
583
584pub fn unpack16(bytes: &[u8]) -> Vec<u16> {
585 let n = bytes.len() / 2;
586 let mut out = vec![0u16; n];
587 bytemuck::cast_slice_mut(&mut out).copy_from_slice(&bytes[..2 * n]);
588 out
589}
590
591/// A hardware encode session living in another process.
592pub struct Remote {
593 child: Child,
594 sock: UnixStream,
595 /// The staging buffer, once the child has said it is open. `None` only while
596 /// [`Remote::spawn`] is still reading that answer.
597 shm: Option<Shm>,
598 open: Open,
599 /// The last access unit, owned here: the child's buffer is in the child.
600 au: Vec<u8>,
601 /// Set the moment the child is known gone, so every later call refuses in
602 /// the same words instead of blocking on a socket nobody holds.
603 lost: Option<String>,
604 /// The slowest call this child has answered, and how many it has answered
605 /// at all: what [`Remote::deadline`] measures its patience against.
606 slowest: Duration,
607 answered: u32,
608}
609
610/// How many answered calls it takes before the wait stops being the configured
611/// ceiling and becomes this encoder's own measure, how much slower than its
612/// slowest answer a call may be before it is a wedge, and the least it is ever
613/// given.
614///
615/// The ceiling has to be generous -- an encoder opening on a 4K frame is not a
616/// dead one -- and the export spends every second of it on a child that will
617/// never answer again: the file is owed the software encoder and the wait is
618/// pure delay before it starts. The window is what shrinks, not the ceiling.
619/// Once a child has answered [`CALIBRATE`] calls, the machine has said how long
620/// its own frames take, and eight times the slowest of them (never under
621/// [`FLOOR`]) contains a wedge in two or three seconds rather than fifteen,
622/// while a slow open still gets the whole ceiling and is never killed for
623/// being slow. The editor is live throughout either way -- the wait is on the
624/// export's own thread and the card goes on repainting -- so what this buys is
625/// the delay, not the window.
626const CALIBRATE: u32 = 8;
627const SLACK: u32 = 8;
628const FLOOR: Duration = Duration::from_secs(2);
629
630impl Remote {
631 /// How long the child may take over one call before it is treated as hung.
632 /// A wedged ring does not always `abort()` -- it can simply stop -- and a
633 /// timeout is the only thing that tells those apart from a slow frame.
634 fn timeout() -> Duration {
635 timeout()
636 }
637
638 /// How long the *next* call may take: the ceiling until this child has
639 /// shown what its frames cost, then its own slowest answer with room to
640 /// spare ([`CALIBRATE`]).
641 fn deadline(&self) -> Duration {
642 let ceiling = Self::timeout();
643 match self.answered >= CALIBRATE {
644 true => ceiling.min((self.slowest * SLACK).max(FLOOR)),
645 false => ceiling,
646 }
647 }
648
649 /// Starts a child on this seat. `None` is the plugin's own "no" carried
650 /// across the process boundary -- no driver, no entrypoint, a size refused
651 /// -- and the caller takes the software encoder exactly as it always did.
652 pub fn spawn(open: Open) -> Option<Self> {
653 let mut args = vec![OsString::from("encode")];
654 args.extend(open.argv().into_iter().map(OsString::from));
655 let (child, mine) = spawn_child(&args)?;
656 let mut remote = Self {
657 child,
658 sock: mine,
659 shm: None,
660 open,
661 au: Vec::new(),
662 lost: None,
663 slowest: Duration::ZERO,
664 answered: 0,
665 };
666 // The child answers once its encoder is open: a byte, and with it the
667 // descriptor of the staging buffer it made for this session's size.
668 match recv_tag(&remote.sock) {
669 Ok((1, mut fds)) if fds.len() == 1 => {
670 remote.shm = Some(Shm::from_fd(fds.remove(0), open.frame_bytes()));
671 Some(remote)
672 }
673 // Anything else is "no seat here", including a child that died
674 // opening the driver -- which is the crash this whole module exists
675 // for, and it costs an export nothing but the software encoder.
676 _ => None,
677 }
678 }
679
680 /// What the child's encoder codes in, or `None` where it has no zero-copy
681 /// door.
682 ///
683 /// The two `None`s are not the same thing and only one of them is an
684 /// answer. A child that *says* it has no door costs the caller a read-back
685 /// and nothing else; a child that does not answer at all is gone, and is
686 /// reaped right here -- otherwise the next picture would spend a whole
687 /// second timeout discovering what this call already knows.
688 pub fn dma_geometry(&mut self) -> Option<(u32, u32)> {
689 self.request(&[T_GEOM], &[]).ok()?;
690 let mut buf = [0u8; 8];
691 let answered = match recv_tag(&self.sock) {
692 Ok((R_AU, _)) => self.sock.read_exact(&mut buf).map(|()| true),
693 Ok(_) => Ok(false),
694 Err(e) => Err(e),
695 };
696 match answered {
697 Ok(true) => Some((
698 u32::from_le_bytes(buf[..4].try_into().ok()?),
699 u32::from_le_bytes(buf[4..].try_into().ok()?),
700 )),
701 Ok(false) => None,
702 Err(e) => {
703 self.bury(&e.to_string());
704 None
705 }
706 }
707 }
708
709 /// Feeds one packed I420 picture through the shared mapping.
710 pub fn encode(
711 &mut self,
712 y: &[u8],
713 u: &[u8],
714 v: &[u8],
715 width: u32,
716 height: u32,
717 force_key: bool,
718 ) -> crate::Result<Option<&[u8]>> {
719 let total = y.len() + u.len() + v.len();
720 let Some(shm) = self.shm.as_ref() else {
721 return Err("the staging buffer was never opened".to_owned().into());
722 };
723 if total > shm.capacity() {
724 return Err(format!(
725 "a {width}x{height} picture does not fit the staging buffer opened for {}x{}",
726 self.open.width, self.open.height
727 )
728 .into());
729 }
730 if let Err(e) = shm.write_picture(&[y, u, v]) {
731 return Err(format!("cannot stage the picture: {e}").into());
732 }
733 let mut msg = vec![T_ENCODE];
734 msg.extend_from_slice(&width.to_le_bytes());
735 msg.extend_from_slice(&height.to_le_bytes());
736 msg.push(u8::from(force_key));
737 self.round_trip(&msg, &[])
738 }
739
740 /// Feeds one 10-bit picture (samples in the low 10 bits) through the shared mapping.
741 pub fn encode16(
742 &mut self,
743 y: &[u16],
744 u: &[u16],
745 v: &[u16],
746 width: u32,
747 height: u32,
748 force_key: bool,
749 ) -> crate::Result<Option<&[u8]>> {
750 let mut bytes = Vec::new();
751 pack16(y, u, v, &mut bytes);
752 self.encode16_le(&bytes, width, height, force_key)
753 }
754
755 /// Feeds one picture already packed as 16-bit LE samples, Y then U then V.
756 pub fn encode16_le(
757 &mut self,
758 bytes: &[u8],
759 width: u32,
760 height: u32,
761 force_key: bool,
762 ) -> crate::Result<Option<&[u8]>> {
763 let Some(shm) = self.shm.as_ref() else {
764 return Err("the staging buffer was never opened".to_owned().into());
765 };
766 if bytes.len() > shm.capacity() {
767 return Err(format!(
768 "a {width}x{height} picture does not fit the staging buffer opened for {}x{}",
769 self.open.width, self.open.height
770 )
771 .into());
772 }
773 if let Err(e) = shm.write_picture(&[bytes]) {
774 return Err(format!("cannot stage the picture: {e}").into());
775 }
776 let mut msg = vec![T_ENCODE16];
777 msg.extend_from_slice(&width.to_le_bytes());
778 msg.extend_from_slice(&height.to_le_bytes());
779 msg.push(u8::from(force_key));
780 self.round_trip(&msg, &[])
781 }
782
783 /// Feeds one picture the decoder left on the GPU. The descriptors go over
784 /// with the message, so the buffer itself never moves.
785 pub fn encode_dma(&mut self, frame: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> {
786 let dma: &VhDma = &frame.desc;
787 let fds: Vec<RawFd> = frame.fds.iter().map(AsRawFd::as_raw_fd).collect();
788 let mut msg = vec![T_DMA];
789 msg.extend_from_slice(&dma.fourcc.to_le_bytes());
790 msg.extend_from_slice(&dma.modifier.to_le_bytes());
791 for value in [
792 dma.coded_width,
793 dma.coded_height,
794 dma.width,
795 dma.height,
796 dma.offset[0],
797 dma.offset[1],
798 dma.stride[0],
799 dma.stride[1],
800 ] {
801 msg.extend_from_slice(&value.to_le_bytes());
802 }
803 msg.push(fds.len() as u8);
804 msg.push(u8::from(force_key));
805 self.round_trip(&msg, &fds)
806 }
807
808 /// Flushes the child's encoder; call until it answers `None`.
809 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
810 self.round_trip(&[T_DRAIN], &[])
811 }
812
813 /// One request and its reply, which is every call above: the child is fed,
814 /// then read, and anything that is not an answer is the child being gone.
815 fn round_trip(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<Option<&[u8]>> {
816 // Set per call, because what it may be is measured from the calls
817 // before it ([`deadline`]).
818 let _ = self.sock.set_read_timeout(Some(self.deadline()));
819 let started = std::time::Instant::now();
820 self.request(msg, fds)?;
821 let mut au = std::mem::take(&mut self.au);
822 let read = read_reply(&mut self.sock, &mut au);
823 self.au = au;
824 if read.is_ok() {
825 self.slowest = self.slowest.max(started.elapsed());
826 self.answered += 1;
827 }
828 // Every "no access unit" leaves through a `return`, so the borrow of the
829 // buffer below is the only one alive when it is taken.
830 match read {
831 Ok(None) => return Ok(None),
832 Ok(Some(Ok(()))) => {}
833 // The child's *own* refusal: it is alive and said no, so this is an
834 // ordinary encode error and the process stays as it is.
835 Ok(Some(Err(message))) => return Err(message.into()),
836 Err(e) => return Err(self.bury(&e.to_string())),
837 }
838 Ok(Some(&self.au))
839 }
840
841 fn request(&mut self, msg: &[u8], fds: &[RawFd]) -> crate::Result<()> {
842 if let Some(gone) = &self.lost {
843 return Err(Lost(gone.clone()).into());
844 }
845 match send_msg(&self.sock, msg, fds) {
846 Ok(()) => Ok(()),
847 Err(e) => Err(self.bury(&e.to_string())),
848 }
849 }
850
851 /// Reaps the child and remembers why, so no later call waits on it. Kills
852 /// first: the child may be *stuck* rather than dead, which is the hang this
853 /// timeout exists to contain, and a stuck child is never waited for.
854 fn bury(&mut self, why: &str) -> crate::Error {
855 let _ = self.child.kill();
856 let status = self.child.wait().ok();
857 // The two shapes a wedged ring takes, told apart by who did the
858 // killing: a driver that called `abort()` leaves its own signal, while
859 // a child that merely stopped answering is still holding `SIGKILL` from
860 // the line above and the read's own timeout is the real reason.
861 let how = match status.and_then(|s| std::os::unix::process::ExitStatusExt::signal(&s)) {
862 Some(libc::SIGKILL) | None => format!("stopped answering ({why}) and was killed"),
863 Some(signal) => format!("was killed by signal {signal}"),
864 };
865 let message = format!("{HW_LOST} {how}; the driver took it down and not the editor");
866 self.lost = Some(message.clone());
867 Lost(message).into()
868 }
869}
870
871impl Drop for Remote {
872 fn drop(&mut self) {
873 // Nothing is pending -- the export drains before it drops -- and a
874 // signal is the one exit a wedged child is guaranteed to take.
875 if self.lost.is_none() {
876 let _ = self.child.kill();
877 let _ = self.child.wait();
878 }
879 }
880}
881
882#[cfg(test)]
883mod tests {
884 use super::*;
885
886 /// Descriptors really cross the socket, and the buffer really is shared: the
887 /// two halves of the frame hand-off, checked without a driver.
888 #[test]
889 fn a_buffer_and_its_descriptor_cross_a_socket() {
890 use std::os::fd::AsRawFd;
891 let (a, b) = UnixStream::pair().expect("socketpair");
892 let (mine, fd) = Shm::create(64).expect("memfd");
893 mine.write_picture(&[b"hello"]).expect("stage");
894 send_msg(&a, &[7u8], &[fd.as_raw_fd()]).expect("send");
895 let (tag, mut fds) = recv_tag(&b).expect("recv");
896 assert_eq!(tag, 7);
897 assert_eq!(fds.len(), 1, "the descriptor came over");
898 let theirs = Shm::from_fd(fds.remove(0), 64);
899 assert_eq!(theirs.read_bytes(5).expect("read"), b"hello", "one store, two handles");
900 theirs.write_picture(&[b"j"]).expect("write back");
901 assert_eq!(mine.read_bytes(5).expect("read"), b"jello", "and it is shared both ways");
902 }
903
904 /// A dead peer must come back as an error, never as a `SIGPIPE` that kills
905 /// the process doing the sending -- the whole point of `MSG_NOSIGNAL`.
906 #[test]
907 fn sending_to_a_closed_socket_errors_instead_of_signalling() {
908 let (a, b) = UnixStream::pair().expect("socketpair");
909 drop(b);
910 assert!(send_msg(&a, &[1u8, 2, 3], &[]).is_err());
911 }
912
913 /// The open crosses to the child as text and comes back the same struct.
914 #[test]
915 fn an_open_round_trips_through_argv() {
916 let open = Open {
917 seat: Seat::Hevc,
918 width: 1920,
919 height: 1080,
920 fps_num: 30000,
921 fps_den: 1001,
922 rate: SeatRate::Bitrate(12_345_678),
923 colour: ColorDescription {
924 matrix: Matrix::Bt2020Ncl,
925 transfer: Transfer::Pq,
926 full_range: true,
927 },
928 gop: Some(15),
929 ten_bit: false,
930 };
931 let back = Open::from_argv(&open.argv()).expect("parse");
932 assert!(back.seat == Seat::Hevc);
933 assert_eq!(back.gop, Some(15));
934 assert_eq!(
935 (back.width, back.height, back.fps_num, back.fps_den),
936 (1920, 1080, 30000, 1001)
937 );
938 assert!(back.rate == SeatRate::Bitrate(12_345_678));
939 assert_eq!(back.colour, open.colour);
940 assert_eq!(back.frame_bytes(), 1920 * 1080 * 3 / 2);
941 }
942}