forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

hw.rs959 lines, 33.7 KiBHistoryRawDownload
1//! Hardware decode and encode, held by a child process.
2//!
3//! The VA-API drivers live in `hw-child`, a binary of the `engine-hw` package
4//! that is started next to the editor's own executable the same way the editor
5//! finds its other helpers ([`crate::hwproc`]). This module is the parent side:
6//! a session is a child plus a socket, and every call is one request and one
7//! reply. Nothing here links a driver and nothing here is `unsafe`.
8//!
9//! Anything that goes wrong -- child missing, no VA-API runtime, no render node,
10//! unsupported stream, a child that stops answering or dies -- leaves us with
11//! `None` or an `Err`, and the caller falls back to the software codec exactly
12//! as it always did. A dead child is reaped at once and the next open starts a
13//! fresh one.
14//!
15//! Pictures in memory cross in a shared memfd, read out with one `pread`.
16//! Pictures still on the GPU cross as DRM-PRIME descriptors over `SCM_RIGHTS`
17//! and are never copied through the socket.
18
19use std::collections::VecDeque;
20use std::ffi::OsString;
21use std::os::fd::OwnedFd;
22use std::path::Path;
23use std::process::Child;
24use std::sync::OnceLock;
25use std::sync::mpsc::{self, Receiver, Sender, SyncSender, TryRecvError};
26use std::thread::JoinHandle;
27
28use crate::colorspace::ColorDescription;
29use crate::hwproc::{
30 DMA_BODY, HW_LOST, K_DMA, K_PIXELS, K_PIXELS16, Lost, Open, R_AU, R_ERR, R_NONE, Remote, Seat, SeatRate, Shm,
31 T_NEXT, T_NEXT_DMA, T_NEXT_DMA16, T_NEXT_WIDE, T_SEEK, pack16, recv_reply, send_msg, spawn_child,
32};
33
34#[cfg(test)]
35thread_local! {
36 /// How many times this thread asked for a decoder. The seam the tests read
37 /// to show a file was never offered to the GPU, which stderr cannot show
38 /// in-process.
39 pub(crate) static OPEN_ATTEMPTS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
40}
41
42/// One picture as the caller reads it: the Y, U and V planes, then the width
43/// and height they are laid out at.
44type Planes<'a> = (&'a [u8], &'a [u8], &'a [u8], u32, u32);
45
46/// Stream metadata. The picture half of [`crate::VideoMeta`]: the four fields a
47/// session was opened with, plus the coded pair and the sample aspect a display
48/// size can differ from the coded one by.
49///
50/// `width`/`height` are the *displayed* shape, exactly as [`crate::VideoMeta`]
51/// promises. `coded_width`/`coded_height` name the stored pair explicitly, and
52/// `pixel_aspect_h`/`_v` carry the ratio one coded pixel is drawn at; zero and
53/// zero reads square.
54#[derive(Default, Clone, Copy, Debug, PartialEq)]
55pub struct VhMeta {
56 pub width: u32,
57 pub height: u32,
58 pub frame_rate: f64,
59 pub frame_count: u32,
60 pub coded_width: u32,
61 pub coded_height: u32,
62 pub pixel_aspect_h: u32,
63 pub pixel_aspect_v: u32,
64}
65
66/// Bytes of [`VhMeta`] on the wire: eight 4-byte fields, the frame rate as its
67/// bit pattern in 8 bytes.
68pub const META_WIRE: usize = 36;
69
70/// [`VhMeta`] as the child sends it at open.
71pub fn meta_to_wire(meta: &VhMeta) -> [u8; META_WIRE] {
72 let mut out = [0u8; META_WIRE];
73 out[0..4].copy_from_slice(&meta.width.to_le_bytes());
74 out[4..8].copy_from_slice(&meta.height.to_le_bytes());
75 out[8..16].copy_from_slice(&meta.frame_rate.to_bits().to_le_bytes());
76 out[16..20].copy_from_slice(&meta.frame_count.to_le_bytes());
77 out[20..24].copy_from_slice(&meta.coded_width.to_le_bytes());
78 out[24..28].copy_from_slice(&meta.coded_height.to_le_bytes());
79 out[28..32].copy_from_slice(&meta.pixel_aspect_h.to_le_bytes());
80 out[32..36].copy_from_slice(&meta.pixel_aspect_v.to_le_bytes());
81 out
82}
83
84/// The other half of [`meta_to_wire`]; `None` for anything of the wrong size.
85pub fn meta_from_wire(bytes: &[u8]) -> Option<VhMeta> {
86 if bytes.len() != META_WIRE {
87 return None;
88 }
89 let u32_at = |at: usize| Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?));
90 Some(VhMeta {
91 width: u32_at(0)?,
92 height: u32_at(4)?,
93 frame_rate: f64::from_bits(u64::from_le_bytes(bytes.get(8..16)?.try_into().ok()?)),
94 frame_count: u32_at(16)?,
95 coded_width: u32_at(20)?,
96 coded_height: u32_at(24)?,
97 pixel_aspect_h: u32_at(28)?,
98 pixel_aspect_v: u32_at(32)?,
99 })
100}
101
102/// What the driver says this machine decodes and encodes: one bit per codec
103/// ([`CAP_H264`] and its neighbours) in each mask.
104#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
105pub struct VhCaps {
106 pub decode: u32,
107 pub encode: u32,
108 /// Codecs whose 10-bit profiles decode.
109 pub decode_10bit: u32,
110}
111
112pub const CAP_H264: u32 = 1 << 0;
113pub const CAP_HEVC: u32 = 1 << 1;
114pub const CAP_VP9: u32 = 1 << 2;
115pub const CAP_AV1: u32 = 1 << 3;
116
117/// VP8 decodes on `ec-vp8` inside the child -- software, no GPU and no VA-API
118/// profile anywhere in it -- so this bit is the child's seat, never the
119/// driver's, and it lights up [`VhCaps::decode`] unconditionally. The hardware
120/// line in [`crate::caps`] deliberately keeps it off.
121pub const CAP_VP8: u32 = 1 << 4;
122
123/// A picture's DRM-PRIME description, without its file descriptors (those
124/// travel beside it in a [`DmaFrame`]): one object per plane, luma first, or one
125/// object for both.
126#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
127pub struct VhDma {
128 /// `NV12` and nothing else, today.
129 pub fourcc: u32,
130 /// DRM format modifier of the buffer, passed through to the import.
131 pub modifier: u64,
132 /// The surface's own size, rounded up to what the codec codes in.
133 pub coded_width: u32,
134 pub coded_height: u32,
135 /// The picture inside it.
136 pub width: u32,
137 pub height: u32,
138 /// Luma then chroma, each inside its own object.
139 pub offset: [u32; 2],
140 pub stride: [u32; 2],
141}
142
143/// One decoded picture left on the GPU, with the descriptors owned: dropping it
144/// closes them. The decode child keeps the buffer out of its pool for a few
145/// pictures only (see `DMA_HOLD` in engine-hw), so encode it before asking for
146/// several more.
147#[derive(Debug)]
148pub struct DmaFrame {
149 pub desc: VhDma,
150 /// One per plane object, luma first.
151 pub fds: Vec<OwnedFd>,
152}
153
154impl DmaFrame {
155 pub fn width(&self) -> u32 {
156 self.desc.width
157 }
158
159 pub fn height(&self) -> u32 {
160 self.desc.height
161 }
162}
163
164/// Bytes of one packed I420 picture of this size.
165fn i420_bytes(width: u32, height: u32) -> usize {
166 let (w, h) = (width as usize, height as usize);
167 w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))
168}
169
170/// Reads a `u32` little-endian at `at`, or `None` past the end.
171fn le_u32(bytes: &[u8], at: usize) -> Option<u32> {
172 Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?))
173}
174
175/// The one-time capability query, asked of a child that answers and exits.
176/// `None` on every way there is no answer -- no child, no driver, a child that
177/// refuses -- and a caller says "software only" for all of them.
178///
179/// VP8 sits outside that reading on a driverless machine: its decoder is inside
180/// the child, so a VP8 file may open where this answers `None`.
181///
182/// Costs one VA-API init (~90 ms) the first time: ask it off a render thread.
183pub fn caps() -> Option<VhCaps> {
184 static CAPS: OnceLock<Option<VhCaps>> = OnceLock::new();
185 *CAPS.get_or_init(query_caps)
186}
187
188fn query_caps() -> Option<VhCaps> {
189 let (mut child, mut sock) = spawn_child(&[OsString::from("caps")])?;
190 let mut body = Vec::new();
191 let answer = match recv_reply(&mut sock, &mut body) {
192 Ok((R_AU, _)) => Some(VhCaps {
193 decode: le_u32(&body, 0)?,
194 encode: le_u32(&body, 4)?,
195 decode_10bit: le_u32(&body, 8)?,
196 }),
197 _ => None,
198 };
199 reap(&mut child);
200 answer
201}
202
203/// Kills and reaps a child. Kills first: a child may be stuck in a driver
204/// rather than dead, and a stuck child is never waited for.
205fn reap(child: &mut Child) {
206 let _ = child.kill();
207 let _ = child.wait();
208}
209
210/// Picture count at which new sessions inject a hardware error; negative for
211/// none. Read once per [`HwSession::open_at`].
212static FAIL_AFTER: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(-1);
213
214/// Test hook: sessions opened from now on report a hardware error after
215/// `pictures` pictures (counted from the open, or the last seek), as a hung or
216/// reset GPU context would. `None` switches it off. `EC_HW_FAIL_AT=N` does the
217/// same for a whole process.
218#[doc(hidden)]
219pub fn inject_failure_after(pictures: Option<u64>) {
220 let value = pictures.map_or(-1, |n| i64::try_from(n).unwrap_or(i64::MAX));
221 FAIL_AFTER.store(value, std::sync::atomic::Ordering::SeqCst);
222}
223
224fn injected_failure() -> Option<u64> {
225 match FAIL_AFTER.load(std::sync::atomic::Ordering::SeqCst) {
226 n if n >= 0 => Some(n as u64),
227 _ => crate::envcfg::var("EC_HW_FAIL_AT")?.parse().ok(),
228 }
229}
230
231/// What one decode request handed back.
232enum Fetched {
233 /// The picture is in the session's pixel buffer.
234 Pixels,
235 /// The picture is still on the GPU.
236 Dma(DmaFrame),
237}
238
239/// An open hardware decode session, in a child process of its own. Dropping it
240/// kills the child.
241pub struct HwSession {
242 child: Child,
243 sock: std::os::unix::net::UnixStream,
244 /// The staging buffer pictures in memory are read out of. Its capacity is
245 /// the child's own, so a frame that does not fit comes with a new one.
246 shm: Shm,
247 meta: VhMeta,
248 /// The last reply's body.
249 body: Vec<u8>,
250 /// The last picture read out of `shm`, packed I420.
251 pixels: Vec<u8>,
252 /// Whether `pixels` holds 16-bit LE samples (`K_PIXELS16`).
253 pixels_wide: bool,
254 /// Set the moment the child is known gone, so every later call refuses in
255 /// the same words instead of waiting on a socket nobody holds.
256 lost: Option<String>,
257 /// Test hook: the number of pictures after which `next_frame*` reports a
258 /// hardware error. Set by [`inject_failure_after`] or `EC_HW_FAIL_AT`.
259 fail_after: Option<u64>,
260 delivered: u64,
261}
262
263impl HwSession {
264 /// Probes the child against this very file: success means the driver, the
265 /// render node and the stream's profile are all usable.
266 pub fn open(path: &Path) -> Option<Self> {
267 Self::open_at(path, 0)
268 }
269
270 /// As [`HwSession::open`], but the first [`HwSession::next_frame`] returns
271 /// display index `start_frame`; earlier pictures are decoded and dropped
272 /// inside the child, without the read-back copy.
273 pub fn open_at(path: &Path, start_frame: u32) -> Option<Self> {
274 #[cfg(test)]
275 OPEN_ATTEMPTS.with(|n| n.set(n.get() + 1));
276 // Sample ids are 1-based, frame indices 0-based.
277 let target_sample = start_frame.saturating_add(1);
278 let args = [
279 OsString::from("decode"),
280 path.as_os_str().to_owned(),
281 OsString::from(target_sample.to_string()),
282 ];
283 let (mut child, mut sock) = spawn_child(&args)?;
284 let mut body = Vec::new();
285 let opened = match recv_reply(&mut sock, &mut body) {
286 Ok((R_AU, mut fds)) if fds.len() == 1 => {
287 meta_from_wire(&body).map(|meta| (meta, fds.remove(0)))
288 }
289 // A child that said no, or died opening the driver, is no session.
290 _ => None,
291 };
292 let Some((meta, fd)) = opened else {
293 reap(&mut child);
294 return None;
295 };
296 Some(Self {
297 child,
298 sock,
299 shm: Shm::from_fd(fd, i420_bytes(meta.width, meta.height)),
300 meta,
301 body,
302 pixels: Vec::new(),
303 pixels_wide: false,
304 lost: None,
305 fail_after: injected_failure(),
306 delivered: 0,
307 })
308 }
309
310 /// Repositions this very session so the next [`HwSession::next_frame`]
311 /// returns display index `start_frame`, without a new child and its driver
312 /// initialisation. `false` when the child cannot do it, and the caller then
313 /// opens a new session as it always did. The session is left usable either
314 /// way.
315 pub fn seek(&mut self, start_frame: u32) -> bool {
316 // Sample ids are 1-based, frame indices 0-based -- as in `open_at`.
317 let target_sample = start_frame.saturating_add(1);
318 let moved = matches!(self.call(T_SEEK, &target_sample.to_le_bytes()), Ok((R_AU, _)));
319 if moved {
320 self.delivered = 0;
321 }
322 moved
323 }
324
325 /// The injected error, once `fail_after` pictures have been delivered.
326 fn inject(&mut self) -> crate::Result<()> {
327 if let Some(limit) = self.fail_after {
328 if self.delivered >= limit {
329 return Err(format!("injected hardware error after {limit} pictures").into());
330 }
331 self.delivered += 1;
332 }
333 Ok(())
334 }
335
336 pub fn meta(&self) -> Option<VhMeta> {
337 Some(self.meta)
338 }
339
340 /// Next picture in display order as tightly packed I420 `(y, u, v)`.
341 /// `Ok(None)` is clean end of stream.
342 pub fn next_frame(&mut self) -> crate::Result<Option<Planes<'_>>> {
343 self.inject()?;
344 match self.fetch(T_NEXT, &[])? {
345 None => Ok(None),
346 Some(Fetched::Pixels) => Ok(Some(self.planes())),
347 Some(Fetched::Dma(_)) => Err("the decoder handed over a GPU buffer nobody asked for".into()),
348 }
349 }
350
351 /// The next picture for a 10-bit consumer: a picture deeper than 8 bits comes
352 /// back whole ([`HwFrame::Wide`]), an 8-bit one as ordinary planes.
353 pub fn next_frame_wide(&mut self) -> crate::Result<Option<HwFrame<'_>>> {
354 self.inject()?;
355 match self.fetch(T_NEXT_WIDE, &[])? {
356 None => Ok(None),
357 Some(Fetched::Pixels) if self.pixels_wide => {
358 let (w, h) = (self.meta.width, self.meta.height);
359 Ok(Some(HwFrame::Wide(&self.pixels[..2 * i420_bytes(w, h)], w, h)))
360 }
361 Some(Fetched::Pixels) => Ok(Some(HwFrame::Narrow(self.planes()))),
362 Some(Fetched::Dma(_)) => Err("the decoder handed over a GPU buffer nobody asked for".into()),
363 }
364 }
365
366 /// The next picture *without reading it back* where the caller's encoder can
367 /// take the buffer the decoder wrote into -- which is what `want` describes.
368 /// Anything the child cannot hand over that way comes back as pixels
369 /// instead ([`HwPicture::Pixels`]), so a mismatch costs the read-back it
370 /// always cost and never a frame.
371 ///
372 /// The buffer behind a [`DmaFrame`] is the decoder's, held out of its pool
373 /// for a few pictures only: encode it before asking this for a few more.
374 pub fn next_frame_dma(&mut self, want: DmaWant) -> crate::Result<Option<HwPicture<'_>>> {
375 self.inject()?;
376 let mut body = Vec::with_capacity(16);
377 for value in [want.coded_width, want.coded_height, want.width, want.height] {
378 body.extend_from_slice(&value.to_le_bytes());
379 }
380 match self.fetch(if want.ten_bit { T_NEXT_DMA16 } else { T_NEXT_DMA }, &body)? {
381 None => Ok(None),
382 Some(Fetched::Dma(frame)) => Ok(Some(HwPicture::Dma(frame))),
383 Some(Fetched::Pixels) if self.pixels_wide => {
384 let (w, h) = (self.meta.width, self.meta.height);
385 Ok(Some(HwPicture::Wide(&self.pixels[..2 * i420_bytes(w, h)], w, h)))
386 }
387 Some(Fetched::Pixels) => {
388 let (y, u, v, width, height) = self.planes();
389 Ok(Some(HwPicture::Pixels(y, u, v, width, height)))
390 }
391 }
392 }
393
394 /// One decode request and its reply: `None` at end of stream, otherwise
395 /// where the picture is.
396 fn fetch(&mut self, request: u8, body: &[u8]) -> crate::Result<Option<Fetched>> {
397 let (tag, mut fds) = self.call(request, body)?;
398 if tag == R_NONE {
399 return Ok(None);
400 }
401 let reply = self.body.clone();
402 match reply.first().copied() {
403 Some(kind @ (K_PIXELS | K_PIXELS16)) if tag == R_AU => {
404 let bad = || -> crate::Error { "the decoder sent a short picture header".into() };
405 let width = le_u32(&reply, 1).ok_or_else(bad)?;
406 let height = le_u32(&reply, 5).ok_or_else(bad)?;
407 self.pixels_wide = kind == K_PIXELS16;
408 let needed = i420_bytes(width, height) * if self.pixels_wide { 2 } else { 1 };
409 if let Some(fd) = fds.pop() {
410 // The child made a bigger staging buffer for this frame.
411 self.shm = Shm::from_fd(fd, needed);
412 }
413 if needed > self.shm.capacity() {
414 return Err(format!("a {width}x{height} picture does not fit the staging buffer").into());
415 }
416 self.shm
417 .read_into(&mut self.pixels, needed)
418 .map_err(|e| format!("cannot read the staging buffer: {e}"))?;
419 self.meta.width = width;
420 self.meta.height = height;
421 Ok(Some(Fetched::Pixels))
422 }
423 Some(K_DMA) if tag == R_AU => {
424 let desc = dma_from_wire(&reply).ok_or("the decoder sent a short GPU buffer header")?;
425 let count = usize::from(*reply.get(DMA_BODY).ok_or("the decoder sent a short GPU buffer header")?);
426 if fds.len() != count || !(1..=2).contains(&count) {
427 return Err(format!("the decoder's GPU buffer came without its descriptors ({} of {count})", fds.len()).into());
428 }
429 self.meta.width = desc.width;
430 self.meta.height = desc.height;
431 Ok(Some(Fetched::Dma(DmaFrame { desc, fds })))
432 }
433 _ => Err(format!("unexpected reply {tag} from the decoder").into()),
434 }
435 }
436
437 /// The picture last read into `pixels`, as planes of the current size.
438 fn planes(&self) -> Planes<'_> {
439 let (w, h) = (self.meta.width as usize, self.meta.height as usize);
440 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
441 let (y, rest) = self.pixels.split_at(w * h);
442 let (u, rest) = rest.split_at(cw * ch);
443 (y, u, &rest[..cw * ch], self.meta.width, self.meta.height)
444 }
445
446 /// One request and its reply on this session's socket. A child that does
447 /// not answer, or is gone, is reaped here and every later call refuses.
448 fn call(&mut self, tag: u8, body: &[u8]) -> crate::Result<(u8, Vec<OwnedFd>)> {
449 if let Some(gone) = &self.lost {
450 return Err(Lost(gone.clone()).into());
451 }
452 let mut msg = Vec::with_capacity(1 + body.len());
453 msg.push(tag);
454 msg.extend_from_slice(body);
455 if let Err(e) = send_msg(&self.sock, &msg, &[]) {
456 return Err(self.bury(&e.to_string()));
457 }
458 match recv_reply(&mut self.sock, &mut self.body) {
459 Ok((R_ERR, _)) => Err(String::from_utf8_lossy(&self.body).into_owned().into()),
460 Ok(answer) => Ok(answer),
461 Err(e) => Err(self.bury(&e.to_string())),
462 }
463 }
464
465 fn bury(&mut self, why: &str) -> crate::Error {
466 reap(&mut self.child);
467 let message = format!("{HW_LOST} stopped answering ({why}) and was killed; the driver took it down and not the editor");
468 self.lost = Some(message.clone());
469 Lost(message).into()
470 }
471}
472
473/// The `K_DMA` header after its kind byte.
474fn dma_from_wire(body: &[u8]) -> Option<VhDma> {
475 let at = 1;
476 Some(VhDma {
477 fourcc: le_u32(body, at)?,
478 modifier: u64::from_le_bytes(body.get(at + 4..at + 12)?.try_into().ok()?),
479 coded_width: le_u32(body, at + 12)?,
480 coded_height: le_u32(body, at + 16)?,
481 width: le_u32(body, at + 20)?,
482 height: le_u32(body, at + 24)?,
483 offset: [le_u32(body, at + 28)?, le_u32(body, at + 32)?],
484 stride: [le_u32(body, at + 36)?, le_u32(body, at + 40)?],
485 })
486}
487
488impl Drop for HwSession {
489 fn drop(&mut self) {
490 reap(&mut self.child);
491 }
492}
493
494/// What an encoder needs a decoded buffer to look like before it can read it
495/// without a copy: the surface's coded size and the picture inside it.
496#[derive(Clone, Copy, PartialEq, Eq)]
497pub struct DmaWant {
498 pub coded_width: u32,
499 pub coded_height: u32,
500 pub width: u32,
501 pub height: u32,
502 pub ten_bit: bool,
503}
504
505/// One picture out of [`HwSession::next_frame_wide`]: 8-bit planes, or packed
506/// I420 of 16-bit LE samples with its width and height.
507pub enum HwFrame<'a> {
508 Narrow(Planes<'a>),
509 Wide(&'a [u8], u32, u32),
510}
511
512/// One picture out of [`HwSession::next_frame_dma`]: still on the GPU, or read
513/// back like every other frame.
514pub enum HwPicture<'a> {
515 Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32),
516 Wide(&'a [u8], u32, u32),
517 Dma(DmaFrame),
518}
519
520/// An open hardware encode session, in a child process of its own. See
521/// [`crate::hwproc`] for why the driver is never in the editor's address space.
522///
523/// The API is the one it always was, call for call, so nothing in the export
524/// loop knows which side of a process boundary the encoder is on.
525pub struct HwEncoder {
526 remote: Option<Remote>,
527 pipe: Option<Pipe>,
528 backlog: VecDeque<Vec<u8>>,
529 au: Vec<u8>,
530 spare: Vec<Vec<u8>>,
531 failed: Option<crate::Error>,
532}
533
534/// A finished job: its access unit, if any, copied out, and the job's buffer
535/// back for reuse.
536type Done = (crate::Result<Option<Vec<u8>>>, Vec<u8>);
537
538enum Job {
539 Eight {
540 bytes: Vec<u8>,
541 y: usize,
542 u: usize,
543 width: u32,
544 height: u32,
545 key: bool,
546 },
547 Ten {
548 bytes: Vec<u8>,
549 width: u32,
550 height: u32,
551 key: bool,
552 },
553}
554
555/// The worker thread that owns the [`Remote`] while jobs are in flight.
556struct Pipe {
557 jobs: SyncSender<Job>,
558 done: Receiver<Done>,
559 worker: JoinHandle<Remote>,
560 queued: usize,
561}
562
563impl Pipe {
564 fn start(remote: Remote) -> crate::Result<Self> {
565 let (jobs, inbox) = mpsc::sync_channel(2);
566 let (outbox, done) = mpsc::channel();
567 let worker = std::thread::Builder::new()
568 .name("hw-encode".to_owned())
569 .spawn(move || serve(remote, inbox, outbox))?;
570 Ok(Self {
571 jobs,
572 done,
573 worker,
574 queued: 0,
575 })
576 }
577}
578
579fn serve(mut remote: Remote, inbox: Receiver<Job>, outbox: Sender<Done>) -> Remote {
580 for job in inbox {
581 let (result, bytes) = match job {
582 Job::Eight {
583 bytes,
584 y,
585 u,
586 width,
587 height,
588 key,
589 } => {
590 let (ys, rest) = bytes.split_at(y);
591 let (us, vs) = rest.split_at(u);
592 let result = remote
593 .encode(ys, us, vs, width, height, key)
594 .map(|au| au.map(<[u8]>::to_vec));
595 (result, bytes)
596 }
597 Job::Ten {
598 bytes,
599 width,
600 height,
601 key,
602 } => {
603 let result = remote
604 .encode16_le(&bytes, width, height, key)
605 .map(|au| au.map(<[u8]>::to_vec));
606 (result, bytes)
607 }
608 };
609 if outbox.send((result, bytes)).is_err() {
610 break;
611 }
612 }
613 remote
614}
615
616impl HwEncoder {
617 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded
618 /// at a constant `rate` (a bitrate or a quantiser). `None` whenever hardware encode
619 /// is unavailable -- no child binary, no driver, dimensions the driver
620 /// refuses, *or a child that died opening any of it* -- and the caller falls
621 /// back to the software encoder.
622 pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate, gop: Option<u32>) -> Option<Self> {
623 Self::seated(
624 Seat::H264,
625 width,
626 height,
627 fps_num,
628 fps_den,
629 rate,
630 ColorDescription::default(),
631 gop,
632 false,
633 )
634 }
635
636 /// The same H.264 seat, **intra-only**: every picture comes back an IDR, so
637 /// every frame of the file is one a decoder may be started from. What
638 /// [`crate::proxy`] codes a stand-in with. `None` on a child that cannot
639 /// make that seat, and the caller must then take the software encoder rather
640 /// than the ordinary hardware seat.
641 pub fn open_intra(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate) -> Option<Self> {
642 Self::seated(
643 Seat::Intra,
644 width,
645 height,
646 fps_num,
647 fps_den,
648 rate,
649 ColorDescription::default(),
650 None,
651 false,
652 )
653 }
654
655 /// The same, coding AV1 instead. `None` on a child or a GPU with no AV1
656 /// encoder, and the caller's software AV1 encoder takes the export without
657 /// saying anything about it.
658 pub fn open_av1(width: u32, height: u32, fps_num: u32, fps_den: u32, rate: SeatRate, gop: Option<u32>) -> Option<Self> {
659 Self::seated(
660 Seat::Av1,
661 width,
662 height,
663 fps_num,
664 fps_den,
665 rate,
666 ColorDescription::default(),
667 gop,
668 false,
669 )
670 }
671
672 /// The same, coding HEVC. `colour` is what the SPS will say the samples
673 /// mean, and it is taken at the open because the parameter sets are written
674 /// when the sequence starts.
675 #[allow(clippy::too_many_arguments)]
676 pub fn open_hevc(
677 width: u32,
678 height: u32,
679 fps_num: u32,
680 fps_den: u32,
681 rate: SeatRate,
682 colour: ColorDescription,
683 gop: Option<u32>,
684 ten_bit: bool,
685 ) -> Option<Self> {
686 Self::seated(Seat::Hevc, width, height, fps_num, fps_den, rate, colour, gop, ten_bit)
687 }
688
689 /// The HEVC seat, **intra-only**: every picture an IDR, as [`Self::open_intra`]
690 /// is for H.264.
691 pub fn open_hevc_intra(
692 width: u32,
693 height: u32,
694 fps_num: u32,
695 fps_den: u32,
696 rate: SeatRate,
697 colour: ColorDescription,
698 ten_bit: bool,
699 ) -> Option<Self> {
700 Self::seated(Seat::HevcIntra, width, height, fps_num, fps_den, rate, colour, None, ten_bit)
701 }
702
703 #[allow(clippy::too_many_arguments)]
704 fn seated(
705 seat: Seat,
706 width: u32,
707 height: u32,
708 fps_num: u32,
709 fps_den: u32,
710 rate: SeatRate,
711 colour: ColorDescription,
712 gop: Option<u32>,
713 ten_bit: bool,
714 ) -> Option<Self> {
715 let open = Open {
716 seat,
717 width,
718 height,
719 fps_num,
720 fps_den,
721 rate,
722 colour,
723 gop,
724 ten_bit,
725 };
726 // No child binary beside the executable means no hardware seat at all:
727 // `Remote::spawn` answers `None` before a process is forked.
728 Remote::spawn(open).map(|remote| Self {
729 remote: Some(remote),
730 pipe: None,
731 backlog: VecDeque::new(),
732 au: Vec::new(),
733 spare: Vec::new(),
734 failed: None,
735 })
736 }
737
738 /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has
739 /// not finished an access unit yet; the returned bytes are Annex-B and stay
740 /// valid until the next call on this session.
741 pub fn encode(
742 &mut self,
743 y: &[u8],
744 u: &[u8],
745 v: &[u8],
746 width: u32,
747 height: u32,
748 force_key: bool,
749 ) -> crate::Result<Option<&[u8]>> {
750 // Checked on this side of the boundary: a caller's mistake is a caller's
751 // mistake, and the child must not turn one into a message about a dead
752 // child.
753 let (w, h) = (width as usize, height as usize);
754 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
755 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
756 return Err("encode input is not a packed I420 frame".into());
757 }
758 let mut bytes = self.spare.pop().unwrap_or_default();
759 bytes.clear();
760 bytes.extend_from_slice(y);
761 bytes.extend_from_slice(u);
762 bytes.extend_from_slice(v);
763 self.submit(Job::Eight {
764 bytes,
765 y: y.len(),
766 u: u.len(),
767 width,
768 height,
769 key: force_key,
770 })?;
771 self.collect_ready()?;
772 Ok(self.pop())
773 }
774
775 /// Feeds one tightly packed 10-bit I420 picture (samples in the low 10 bits).
776 pub fn encode16(
777 &mut self,
778 y: &[u16],
779 u: &[u16],
780 v: &[u16],
781 width: u32,
782 height: u32,
783 force_key: bool,
784 ) -> crate::Result<Option<&[u8]>> {
785 let (w, h) = (width as usize, height as usize);
786 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
787 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
788 return Err("encode input is not a packed I420 frame".into());
789 }
790 let mut bytes = self.spare.pop().unwrap_or_default();
791 pack16(&y[..w * h], &u[..cw * ch], &v[..cw * ch], &mut bytes);
792 self.submit(Job::Ten {
793 bytes,
794 width,
795 height,
796 key: force_key,
797 })?;
798 self.collect_ready()?;
799 Ok(self.pop())
800 }
801
802 /// What a decoded buffer must look like to reach this encoder without a
803 /// copy, or `None` where the child has no zero-copy door at all.
804 pub fn dma_want(&mut self, width: u32, height: u32) -> Option<DmaWant> {
805 let remote = match self.settled() {
806 Ok(remote) => remote,
807 Err(e) => {
808 self.failed = Some(e);
809 return None;
810 }
811 };
812 let (coded_width, coded_height) = remote.dma_geometry()?;
813 Some(DmaWant {
814 coded_width,
815 coded_height,
816 width,
817 height,
818 ten_bit: false,
819 })
820 }
821
822 /// Feeds one picture the decoder left on the GPU. The descriptors go over
823 /// with the message, so the buffer itself never moves.
824 pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> {
825 let au = self.settled()?.encode_dma(dma, force_key)?.map(<[u8]>::to_vec);
826 if let Some(au) = au {
827 self.backlog.push_back(au);
828 }
829 Ok(self.pop())
830 }
831
832 /// Flushes the encoder; call until it returns `Ok(None)`.
833 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
834 self.settle()?;
835 if !self.backlog.is_empty() {
836 return Ok(self.pop());
837 }
838 let remote = self.remote.as_mut().ok_or("the hardware encoder was lost")?;
839 let Some(au) = remote.drain()? else {
840 return Ok(None);
841 };
842 self.au.clear();
843 self.au.extend_from_slice(au);
844 Ok(Some(&self.au))
845 }
846
847 fn submit(&mut self, job: Job) -> crate::Result<()> {
848 if let Some(e) = self.failed.take() {
849 return Err(e);
850 }
851 if self.pipe.is_none() {
852 let remote = self.remote.take().ok_or("the hardware encoder was lost")?;
853 self.pipe = Some(Pipe::start(remote)?);
854 }
855 let pipe = self.pipe.as_mut().ok_or("the hw encode pipe is missing")?;
856 pipe.jobs.send(job).map_err(|_| "the hw encode worker panicked")?;
857 pipe.queued += 1;
858 Ok(())
859 }
860
861 fn collect_ready(&mut self) -> crate::Result<()> {
862 loop {
863 let Some(pipe) = self.pipe.as_mut() else {
864 return Ok(());
865 };
866 let finished = match pipe.done.try_recv() {
867 Ok(finished) => finished,
868 Err(TryRecvError::Empty) => return Ok(()),
869 Err(TryRecvError::Disconnected) => return Err("the hw encode worker panicked".into()),
870 };
871 pipe.queued -= 1;
872 self.finish(finished)?;
873 }
874 }
875
876 fn finish(&mut self, (result, bytes): Done) -> crate::Result<()> {
877 if self.spare.len() < 3 {
878 self.spare.push(bytes);
879 }
880 if let Some(au) = result? {
881 self.backlog.push_back(au);
882 }
883 Ok(())
884 }
885
886 /// Waits for every queued job, keeps their access units in order, and takes
887 /// the [`Remote`] back from the worker. The first error is returned.
888 fn settle(&mut self) -> crate::Result<()> {
889 if let Some(e) = self.failed.take() {
890 return Err(e);
891 }
892 let Some(pipe) = self.pipe.take() else {
893 return Ok(());
894 };
895 let Pipe {
896 jobs,
897 done,
898 worker,
899 mut queued,
900 } = pipe;
901 drop(jobs);
902 let mut first: Option<crate::Error> = None;
903 while queued > 0 {
904 let Ok(finished) = done.recv() else {
905 break;
906 };
907 queued -= 1;
908 if let Err(e) = self.finish(finished) {
909 first = first.or(Some(e));
910 }
911 }
912 match worker.join() {
913 Ok(remote) => self.remote = Some(remote),
914 Err(_) => first = first.or(Some("the hw encode worker panicked".into())),
915 }
916 match first {
917 Some(e) => Err(e),
918 None => Ok(()),
919 }
920 }
921
922 fn settled(&mut self) -> crate::Result<&mut Remote> {
923 self.settle()?;
924 self.remote.as_mut().ok_or_else(|| "the hardware encoder was lost".into())
925 }
926
927 fn pop(&mut self) -> Option<&[u8]> {
928 self.au = self.backlog.pop_front()?;
929 Some(&self.au)
930 }
931}
932
933#[cfg(test)]
934mod tests {
935 use super::*;
936
937 /// The meta block survives the wire, frame rate's bit pattern included.
938 #[test]
939 fn meta_round_trips_through_the_wire() {
940 let meta = VhMeta {
941 width: 1920,
942 height: 1080,
943 frame_rate: 30000.0 / 1001.0,
944 frame_count: 4321,
945 coded_width: 1920,
946 coded_height: 1088,
947 pixel_aspect_h: 4,
948 pixel_aspect_v: 3,
949 };
950 assert_eq!(meta_from_wire(&meta_to_wire(&meta)), Some(meta));
951 assert_eq!(meta_from_wire(&[0u8; 35]), None);
952 }
953
954 #[test]
955 fn i420_size_rounds_chroma_up() {
956 assert_eq!(i420_bytes(3, 3), 9 + 2 * 4);
957 assert_eq!(i420_bytes(1920, 1080), 1920 * 1080 * 3 / 2);
958 }
959}