forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

hw.rs1033 lines, 41.5 KiBHistoryRawDownload
1//! Runtime-optional hardware decode/encode plugin (`libengine_hw.so`).
2//!
3//! The plugin links libva/gbm/drm; this crate and the app binary must not, so
4//! the only coupling is this C ABI plus a `dlopen`. Anything that goes wrong --
5//! plugin missing, no VA-API runtime, no render node, unsupported stream --
6//! leaves us with `None` and the caller falls back to the software codec.
7//!
8//! Decode and encode resolve their symbols into *separate* tables on purpose: a
9//! plugin built before the encode entry points existed must still decode, so a
10//! missing `vh_enc_*` may only cost us [`HwEncoder`], never [`HwSession`].
11//!
12//! The codec is *not* part of this ABI and adding VP9 and HEVC did not change
13//! it: the plugin demuxes the file it is given and picks its decoder from the
14//! container, so a plugin older than that support simply returns null for such a
15//! path -- the same "no" it gives for an unsupported profile, and the caller's
16//! honest [`crate::demux::Codec::needs_plugin`] refusal covers both.
17
18use std::ffi::{c_char, c_void, CString};
19use std::os::fd::FromRawFd;
20use std::path::{Path, PathBuf};
21use std::sync::OnceLock;
22
23use libloading::Library;
24
25use crate::colorspace::ColorDescription;
26
27const LIB_NAME: &str = "libengine_hw.so";
28
29/// Stream metadata, C layout. Mirrors [`crate::VideoMeta`]'s picture half --
30/// the four fields a session was opened with, plus the coded pair and the
31/// sample aspect a display size can now differ from the coded one by.
32///
33/// `width`/`height` are the *displayed* shape, exactly as [`crate::VideoMeta`]
34/// promises: a plugin opened on a rotated file has always been handed a
35/// swapped pair here, and the pictures it hands back are sized by its own
36/// decoder's output, which is the coded pair. `coded_width`/`coded_height`
37/// name that pair explicitly, and `pixel_aspect_h`/`_v` carry the ratio one
38/// coded pixel is drawn at, so a caller that needs the stored shape (a copy
39/// declaring a track, an encoder agreeing on a surface) asks the coded one and
40/// a caller that draws asks the display one -- both answered, neither derived.
41#[repr(C)]
42#[derive(Default)]
43pub struct VhMeta {
44 pub width: u32,
45 pub height: u32,
46 pub frame_rate: f64,
47 pub frame_count: u32,
48 /// What the samples are stored at, before any turn or stretch.
49 pub coded_width: u32,
50 pub coded_height: u32,
51 /// The sample aspect ratio, h over v, square as 1 and 1 -- or 0 and 0,
52 /// which is `Default` and reads square ([`crate::demux::PixelAspect`]).
53 pub pixel_aspect_h: u32,
54 pub pixel_aspect_v: u32,
55}
56
57/// One decoded picture as planar I420. Pointers belong to the plugin and stay
58/// valid only until the next `vh_next_frame`/`vh_close` on the same session.
59#[repr(C)]
60pub struct VhFrame {
61 pub y: *const u8,
62 pub u: *const u8,
63 pub v: *const u8,
64 pub y_stride: usize,
65 pub u_stride: usize,
66 pub v_stride: usize,
67 pub width: u32,
68 pub height: u32,
69}
70
71impl Default for VhFrame {
72 fn default() -> Self {
73 Self {
74 y: std::ptr::null(),
75 u: std::ptr::null(),
76 v: std::ptr::null(),
77 y_stride: 0,
78 u_stride: 0,
79 v_stride: 0,
80 width: 0,
81 height: 0,
82 }
83 }
84}
85
86/// One decoded picture *left on the GPU*: a DRM-PRIME buffer the encoder
87/// imports instead of the caller reading the pixels back and writing them out
88/// again. All integers, so it crosses a channel to the encoding thread the way
89/// a picture's bytes used to.
90///
91/// The `fd` belongs to whoever holds this: the plugin hands ownership over with
92/// the descriptor and [`DmaFrame`] closes it. What it does *not* own is the
93/// buffer's contents -- the decode session keeps the picture from being decoded
94/// over for a few frames only (see `vh_next_frame_dma`), which is why nothing
95/// but the export's two-deep decode channel may sit between the two calls.
96#[repr(C)]
97#[derive(Clone, Copy)]
98pub struct VhDma {
99 /// One DRM-PRIME handle per plane, luma then chroma -- which is how the
100 /// driver hands its own surfaces out (radeonsi exports an NV12 surface as
101 /// *two* objects into one allocation, measured 2026-08-13), and describing
102 /// it any other way is guessing at what the second one means. `fd[0]` below
103 /// zero says this picture is not on the GPU at all; `fd[1]` below zero says
104 /// both planes live in the first object.
105 pub fd: [i32; 2],
106 /// `NV12` and nothing else, today.
107 pub fourcc: u32,
108 /// DRM format modifier of the buffer, passed through to the import.
109 pub modifier: u64,
110 /// The surface's own size, which is the picture's rounded up to whatever
111 /// the codec codes in -- what an encoder has to agree with, sample for
112 /// sample, before it can read this buffer at all.
113 pub coded_width: u32,
114 pub coded_height: u32,
115 /// The picture inside it.
116 pub width: u32,
117 pub height: u32,
118 /// Luma then chroma, each inside its own object above.
119 pub offset: [u32; 2],
120 pub stride: [u32; 2],
121}
122
123impl Default for VhDma {
124 fn default() -> Self {
125 Self {
126 fd: [-1, -1],
127 fourcc: 0,
128 modifier: 0,
129 coded_width: 0,
130 coded_height: 0,
131 width: 0,
132 height: 0,
133 offset: [0; 2],
134 stride: [0; 2],
135 }
136 }
137}
138
139/// A [`VhDma`] with its file descriptor owned: dropping it closes the handle,
140/// which is the only thing this side of the ABI has to get right.
141pub struct DmaFrame(VhDma);
142
143impl DmaFrame {
144 /// Takes ownership of descriptors that arrived from somewhere other than a
145 /// decode session -- which is the `hw-encode-child` helper, receiving over
146 /// `SCM_RIGHTS` the very buffer the parent's decoder wrote into.
147 #[doc(hidden)]
148 pub fn from_desc(desc: VhDma) -> Self {
149 Self(desc)
150 }
151
152 pub fn width(&self) -> u32 {
153 self.0.width
154 }
155
156 pub fn height(&self) -> u32 {
157 self.0.height
158 }
159}
160
161impl Drop for DmaFrame {
162 fn drop(&mut self) {
163 for fd in self.0.fd {
164 if fd >= 0 {
165 // SAFETY: the plugin transferred these descriptors to us with
166 // the frame and nothing else owns them; `DmaFrame` is not
167 // `Clone`, and the two are distinct handles even where they
168 // name one allocation.
169 drop(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) });
170 }
171 }
172 }
173}
174
175/// What *this machine* takes, as far as the plugin implements it: one bit per
176/// codec ([`CAP_H264`] and its four neighbours) in each mask, so a caller reads
177/// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s.
178///
179/// The intersection is the plugin's to compute, never the driver's alone: a GPU
180/// with an HEVC *encode* entrypoint is still not an HEVC encoder here -- the
181/// plugin has no such entry point -- and a capability nothing can reach would be
182/// a lie in whatever the front-end draws from this.
183#[repr(C)]
184#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
185pub struct VhCaps {
186 pub decode: u32,
187 pub encode: u32,
188 /// Codecs whose 10-bit profiles decode: the driver has the profile *and* a
189 /// P010 image format for the read-back, which is the pair the plugin's
190 /// 10-bit path needs.
191 pub decode_10bit: u32,
192}
193
194pub const CAP_H264: u32 = 1 << 0;
195pub const CAP_HEVC: u32 = 1 << 1;
196pub const CAP_VP9: u32 = 1 << 2;
197pub const CAP_AV1: u32 = 1 << 3;
198
199/// VP8 decodes on `ec-vp8` inside the plugin -- software, linked into the
200/// plugin itself, no GPU and no VA-API profile anywhere in it -- so this bit
201/// is the *plugin's* seat, never the driver's, and it lights up
202/// [`VhCaps::decode`] unconditionally: there is no library whose presence the
203/// bit depends on any more. The hardware line in [`crate::caps`] deliberately
204/// keeps it off, being a line about what the GPU takes.
205pub const CAP_VP8: u32 = 1 << 4;
206
207struct Plugin {
208 open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,
209 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,
210 next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32,
211 /// The zero-copy door, and optional for the same reason [`Plugin::caps`] is:
212 /// a plugin built before it decodes exactly as it did, through the read-back
213 /// above.
214 next_frame_dma: Option<
215 unsafe extern "C" fn(*mut c_void, *mut VhFrame, *mut VhDma, u32, u32, u32, u32) -> i32,
216 >,
217 close: unsafe extern "C" fn(*mut c_void),
218 /// The capability query, and the one symbol of this table that may be
219 /// missing: a plugin built before it exports the four above and not this,
220 /// which costs a front-end the listing and never a decode.
221 caps: Option<unsafe extern "C" fn(*mut VhCaps) -> i32>,
222 /// Repositioning an open session, and optional for the reason `caps` is: a
223 /// plugin built before it decodes exactly as it did, and a caller that
224 /// cannot reposition closes the session and opens another -- which is what
225 /// every seek did before this symbol existed.
226 seek: Option<unsafe extern "C" fn(*mut c_void, u32) -> i32>,
227 // Never dropped (lives in a static), so the fn pointers above stay valid.
228 _lib: Library,
229}
230
231fn plugin() -> Option<&'static Plugin> {
232 static PLUGIN: OnceLock<Option<Plugin>> = OnceLock::new();
233 PLUGIN.get_or_init(load).as_ref()
234}
235
236/// Where the plugin may live: next to the executable first (cargo puts both in
237/// target/<profile>), then whatever the dynamic linker's search path turns up.
238fn candidates() -> impl Iterator<Item = PathBuf> {
239 std::env::current_exe()
240 .ok()
241 .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)))
242 .into_iter()
243 .chain(std::iter::once(PathBuf::from(LIB_NAME)))
244}
245
246fn load() -> Option<Plugin> {
247 for candidate in candidates() {
248 // SAFETY: loading a shared object runs its initialisers; we only ever
249 // name our own plugin, and every symbol below is type-checked against
250 // the definitions this crate shares with it.
251 let lib = match unsafe { Library::new(candidate) } {
252 Ok(lib) => lib,
253 Err(_) => continue,
254 };
255 let plugin = unsafe {
256 (|| {
257 Some(Plugin {
258 open_at: *lib.get(b"vh_open_at\0").ok()?,
259 meta: *lib.get(b"vh_meta\0").ok()?,
260 next_frame: *lib.get(b"vh_next_frame\0").ok()?,
261 next_frame_dma: lib.get(b"vh_next_frame_dma\0").ok().map(|s| *s),
262 close: *lib.get(b"vh_close\0").ok()?,
263 caps: lib.get(b"vh_caps\0").ok().map(|s| *s),
264 seek: lib.get(b"vh_seek\0").ok().map(|s| *s),
265 _lib: lib,
266 })
267 })()
268 };
269 if plugin.is_some() {
270 return plugin;
271 }
272 }
273 None
274}
275
276/// What the plugin says this machine decodes and encodes, asked once per
277/// process and cached: the answer cannot change while we run.
278///
279/// `None` on every way there is no answer -- no plugin, a plugin older than the
280/// symbol (optional exactly as `vh_enc_av1_open` is: such a plugin still
281/// decodes), no driver, a driver that refuses the query -- and a caller says
282/// "software only" for all of them, which is what they mean.
283///
284/// VP8 sits outside that reading on a driverless machine: its decoder is
285/// `ec-vp8` inside the plugin, so the plugin may open a VP8 file where this
286/// table answers `None`. Nothing here promises otherwise -- the decode path
287/// asks the plugin, not this table -- and the one display-dependent half the
288/// front-end draws from this stays exactly as truthful as it was.
289///
290/// Costs one VA-API init (~90 ms) the first time: ask it off a render thread.
291pub fn caps() -> Option<VhCaps> {
292 static CAPS: OnceLock<Option<VhCaps>> = OnceLock::new();
293 *CAPS.get_or_init(|| {
294 let query = plugin()?.caps?;
295 let mut caps = VhCaps::default();
296 // SAFETY: the plugin writes the struct it is handed and reports "no
297 // answer" as a negative code; nothing is borrowed across the call.
298 match unsafe { query(&mut caps) } {
299 0 => Some(caps),
300 _ => None,
301 }
302 })
303}
304
305/// An open hardware decode session. Dropping it closes the plugin session.
306pub struct HwSession {
307 plugin: &'static Plugin,
308 handle: *mut c_void,
309}
310
311impl HwSession {
312 /// Probes the plugin against this very file: success means the driver,
313 /// the render node and the stream's profile are all usable.
314 pub fn open(path: &Path) -> Option<Self> {
315 Self::open_at(path, 0)
316 }
317
318 /// As [`HwSession::open`], but the first [`HwSession::next_frame`] returns
319 /// display index `start_frame`; earlier pictures are decoded and dropped
320 /// inside the plugin, without the read-back copy.
321 pub fn open_at(path: &Path, start_frame: u32) -> Option<Self> {
322 let plugin = plugin()?;
323 let c_path = CString::new(path.as_os_str().as_encoded_bytes()).ok()?;
324 // Sample ids are 1-based, frame indices 0-based.
325 let target_sample = start_frame.saturating_add(1);
326 // SAFETY: `c_path` is a valid NUL-terminated string alive for the call.
327 let handle = unsafe { (plugin.open_at)(c_path.as_ptr(), target_sample) };
328 if handle.is_null() {
329 return None;
330 }
331 Some(Self { plugin, handle })
332 }
333
334 /// Repositions this very session so the next [`HwSession::next_frame`]
335 /// returns display index `start_frame` -- the same landing
336 /// [`HwSession::open_at`] gives, without the VA-API initialisation (~90 ms),
337 /// the render node probe and the container parse that opening one again
338 /// costs. What lets a decode worker outlive the seeks its caller makes.
339 ///
340 /// `false` when the plugin cannot do it -- too old to export the symbol, or
341 /// a decoder that would not flush -- and the caller then opens a new session
342 /// exactly as it always did. The session is left untouched either way, so a
343 /// `false` is never a half-moved decoder.
344 pub fn seek(&mut self, start_frame: u32) -> bool {
345 let Some(seek) = self.plugin.seek else {
346 return false;
347 };
348 // Sample ids are 1-based, frame indices 0-based -- as in `open_at`.
349 let target_sample = start_frame.saturating_add(1);
350 // SAFETY: `handle` came from `vh_open_at` and is still open; the plugin
351 // writes nothing through it and the call cannot unwind (it catches).
352 unsafe { seek(self.handle, target_sample) == 0 }
353 }
354
355 pub fn meta(&self) -> Option<VhMeta> {
356 let mut meta = VhMeta::default();
357 // SAFETY: `handle` came from `vh_open_at` and is still open.
358 if unsafe { (self.plugin.meta)(self.handle, &mut meta) } < 0 {
359 return None;
360 }
361 Some(meta)
362 }
363
364 /// Next picture in display order as tightly packed I420 `(y, u, v)`.
365 /// `Ok(None)` is clean end of stream.
366 pub fn next_frame(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
367 let mut frame = VhFrame::default();
368 // SAFETY: `handle` is live; the plugin fills `frame` with pointers that
369 // stay valid until the next call, which `&mut self` prevents overlapping.
370 match unsafe { (self.plugin.next_frame)(self.handle, &mut frame) } {
371 0 => return Ok(None),
372 1 => {}
373 code => return Err(format!("hardware decode failed (code {code})").into()),
374 }
375 self.pixels(&frame).map(Some)
376 }
377
378 /// The next picture *without reading it back* where the caller's encoder can
379 /// take the buffer the decoder wrote into -- which is what `want` describes,
380 /// down to the coded size, because an encoder reads a surface of its own
381 /// shape or none at all.
382 ///
383 /// Anything the plugin cannot hand over that way comes back as pixels
384 /// instead ([`HwPicture::Pixels`]), so a mismatch costs the read-back it
385 /// always cost and never a frame. A plugin too old to know the door exists
386 /// is the same answer.
387 ///
388 /// The buffer behind a [`DmaFrame`] is the decoder's, held out of its pool
389 /// for a few pictures only: encode it before asking this for a few more.
390 pub fn next_frame_dma(&mut self, want: DmaWant) -> crate::Result<Option<HwPicture<'_>>> {
391 let Some(next_dma) = self.plugin.next_frame_dma else {
392 return Ok(self
393 .next_frame()?
394 .map(|(y, u, v, w, h)| HwPicture::Pixels(y, u, v, w, h)));
395 };
396 let mut frame = VhFrame::default();
397 let mut dma = VhDma::default();
398 // SAFETY: as `next_frame`, plus a writable descriptor whose `fd` the
399 // plugin either hands us ownership of or leaves at -1.
400 let code = unsafe {
401 next_dma(
402 self.handle,
403 &mut frame,
404 &mut dma,
405 want.coded_width,
406 want.coded_height,
407 want.width,
408 want.height,
409 )
410 };
411 match code {
412 0 => return Ok(None),
413 1 => {}
414 code => return Err(format!("hardware decode failed (code {code})").into()),
415 }
416 if dma.fd[0] >= 0 {
417 return Ok(Some(HwPicture::Dma(DmaFrame(dma))));
418 }
419 let (y, u, v, w, h) = self.pixels(&frame)?;
420 Ok(Some(HwPicture::Pixels(y, u, v, w, h)))
421 }
422
423 /// The plugin's plane pointers as slices, checked against the strides it
424 /// declares -- the one shape this side takes.
425 fn pixels(&self, frame: &VhFrame) -> crate::Result<(&[u8], &[u8], &[u8], u32, u32)> {
426 let (w, h) = (frame.width as usize, frame.height as usize);
427 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
428 if frame.y.is_null()
429 || frame.u.is_null()
430 || frame.v.is_null()
431 || frame.y_stride != w
432 || frame.u_stride != cw
433 || frame.v_stride != cw
434 {
435 return Err("hardware plugin returned a non-packed I420 frame".into());
436 }
437 // SAFETY: plane pointers are non-null and the strides just checked above
438 // pin each plane's length; the borrow ends before the next call.
439 unsafe {
440 Ok((
441 std::slice::from_raw_parts(frame.y, w * h),
442 std::slice::from_raw_parts(frame.u, cw * ch),
443 std::slice::from_raw_parts(frame.v, cw * ch),
444 frame.width,
445 frame.height,
446 ))
447 }
448 }
449}
450
451/// What an encoder needs a decoded buffer to look like before it can read it
452/// without a copy: the surface's coded size and the picture inside it.
453#[derive(Clone, Copy)]
454pub struct DmaWant {
455 pub coded_width: u32,
456 pub coded_height: u32,
457 pub width: u32,
458 pub height: u32,
459}
460
461/// One picture out of [`HwSession::next_frame_dma`]: still on the GPU, or read
462/// back like every other frame.
463pub enum HwPicture<'a> {
464 Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32),
465 Dma(DmaFrame),
466}
467
468impl Drop for HwSession {
469 fn drop(&mut self) {
470 // SAFETY: `handle` came from `vh_open_at` and is closed exactly once.
471 unsafe { (self.plugin.close)(self.handle) }
472 }
473}
474
475// The plugin session is used from one thread at a time (the decode worker) and
476// never shared; VA-API state inside it is not `Sync`.
477unsafe impl Send for HwSession {}
478
479struct EncPlugin {
480 open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void,
481 /// The AV1 seat, and the one symbol that may be missing: a plugin built
482 /// before AV1 encode existed exports the four below and not this, which
483 /// costs an AV1 export its hardware path and nothing else. Every session it
484 /// opens is fed and closed through the very same three entry points -- the
485 /// plugin keeps one session type for both codecs, so the codec is decided
486 /// once, at the open, exactly as the H.264 seat's parameters are.
487 open_av1: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>,
488 /// The HEVC seat, missing from an older plugin for the same reason and at
489 /// the same cost: an HEVC export then runs on the software intra encoder.
490 /// Four arguments more than the others: what the SPS says the samples mean
491 /// ([`HwEncoder::open_hevc`]), which is why the symbol is named apart from
492 /// the colourless `vh_enc_hevc_open` it replaced rather than sharing its
493 /// name with another signature.
494 open_hevc: Option<extern "C" fn(u32, u32, u32, u32, u64, u32, u32, u32, i32) -> *mut c_void>,
495 /// The **intra-only** H.264 seat, missing from an older plugin for the same
496 /// reason and at the same cost: a proxy then runs on the software encoder,
497 /// which codes one frame a GOP and so writes the same kind of file.
498 open_intra: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>,
499 frame:
500 unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32,
501 /// The zero-copy pair, both optional together: an older plugin exports
502 /// neither and every picture reaches it as bytes, which is what it always
503 /// did.
504 dma_geometry: Option<unsafe extern "C" fn(*mut c_void, *mut u32, *mut u32) -> i32>,
505 frame_dma: Option<
506 unsafe extern "C" fn(*mut c_void, *const VhDma, i32, *mut *const u8, *mut usize) -> i32,
507 >,
508 drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32,
509 close: unsafe extern "C" fn(*mut c_void),
510 // Never dropped (lives in a static), so the fn pointers above stay valid.
511 _lib: Library,
512}
513
514fn enc_plugin() -> Option<&'static EncPlugin> {
515 static PLUGIN: OnceLock<Option<EncPlugin>> = OnceLock::new();
516 PLUGIN.get_or_init(load_enc).as_ref()
517}
518
519fn load_enc() -> Option<EncPlugin> {
520 for candidate in candidates() {
521 // SAFETY: as in `load` -- our own plugin, symbols type-checked against
522 // the definitions this crate shares with it.
523 let lib = match unsafe { Library::new(candidate) } {
524 Ok(lib) => lib,
525 Err(_) => continue,
526 };
527 let plugin = unsafe {
528 (|| {
529 Some(EncPlugin {
530 open: *lib.get(b"vh_enc_open\0").ok()?,
531 open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s),
532 open_hevc: lib.get(b"vh_enc_hevc_open_colour\0").ok().map(|s| *s),
533 open_intra: lib.get(b"vh_enc_open_intra\0").ok().map(|s| *s),
534 frame: *lib.get(b"vh_enc_frame\0").ok()?,
535 dma_geometry: lib.get(b"vh_enc_dma_geometry\0").ok().map(|s| *s),
536 frame_dma: lib.get(b"vh_enc_frame_dma\0").ok().map(|s| *s),
537 drain: *lib.get(b"vh_enc_drain\0").ok()?,
538 close: *lib.get(b"vh_enc_close\0").ok()?,
539 _lib: lib,
540 })
541 })()
542 };
543 if plugin.is_some() {
544 return plugin;
545 }
546 }
547 None
548}
549
550/// An open hardware encode session **in this process**, which is the one thing
551/// an editor must not have: the driver's own C threads `abort()` the process
552/// they are in when the video ring resets ([`crate::hwproc`]). Public only so
553/// that the `hw-encode-child` helper -- the process whose whole job is to be the
554/// one that dies -- can open it; every other caller goes through [`HwEncoder`],
555/// which is this seat held at arm's length.
556///
557/// Dropping it closes the plugin session.
558#[doc(hidden)]
559pub struct LocalEncoder {
560 plugin: &'static EncPlugin,
561 handle: *mut c_void,
562}
563
564impl LocalEncoder {
565 /// The four seats behind one argument, which is how the helper is told
566 /// which of them to open.
567 pub fn open_seat(open: crate::hwproc::Open) -> Option<Self> {
568 let (w, h, n, d, b) = (
569 open.width,
570 open.height,
571 open.fps_num,
572 open.fps_den,
573 open.bitrate,
574 );
575 match open.seat {
576 crate::hwproc::Seat::H264 => Self::open(w, h, n, d, b),
577 crate::hwproc::Seat::Intra => Self::open_intra(w, h, n, d, b),
578 crate::hwproc::Seat::Av1 => Self::open_av1(w, h, n, d, b),
579 crate::hwproc::Seat::Hevc => Self::open_hevc(w, h, n, d, b, open.colour),
580 }
581 }
582
583 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded
584 /// at a constant `bitrate` bits per second. `None` whenever hardware encode
585 /// is unavailable -- plugin missing, plugin too old to export the encode
586 /// entry points, no driver, dimensions the driver refuses -- and the caller
587 /// falls back to the software encoder.
588 pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
589 let plugin = enc_plugin()?;
590 Self::opened(
591 plugin,
592 plugin.open,
593 width,
594 height,
595 fps_num,
596 fps_den,
597 bitrate,
598 )
599 }
600
601 /// The same H.264 seat, **intra-only**: every picture comes back an IDR
602 /// with its own parameter sets, so every frame of the file is one a decoder
603 /// may be started from. What [`crate::proxy`] codes a stand-in with.
604 ///
605 /// `None` on everything [`HwEncoder::open`] answers `None` to *and* on a
606 /// plugin built before this seat existed -- and that `None` matters more
607 /// than the others: the caller must then take the software encoder, which
608 /// codes one frame a GOP, rather than the ordinary hardware seat, which
609 /// would write a long-GOP file under a name that promises otherwise.
610 pub fn open_intra(
611 width: u32,
612 height: u32,
613 fps_num: u32,
614 fps_den: u32,
615 bitrate: u64,
616 ) -> Option<Self> {
617 let plugin = enc_plugin()?;
618 let open = plugin.open_intra?;
619 Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate)
620 }
621
622 /// The same, coding AV1 instead. `None` on everything [`HwEncoder::open`]
623 /// answers `None` to *and* on a plugin or a GPU with no AV1 encoder -- an
624 /// AV1 encode entrypoint is recent hardware, so this is the fallback that
625 /// really fires, and the caller's software AV1 encoder takes the export
626 /// without saying anything about it.
627 ///
628 /// The caller only reaches this when a person picked
629 /// [`crate::export::EncoderSeat::Hardware`] for an AV1 export: the vendored
630 /// encoder reset this project's own GPU, which
631 /// [`crate::export::Enc::open_av1`] states in full.
632 pub fn open_av1(
633 width: u32,
634 height: u32,
635 fps_num: u32,
636 fps_den: u32,
637 bitrate: u64,
638 ) -> Option<Self> {
639 let plugin = enc_plugin()?;
640 let open = plugin.open_av1?;
641 Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate)
642 }
643
644 /// The same, coding HEVC. Unlike the AV1 seat this is **not** behind an
645 /// opt-in: it is the default for an HEVC export, and what makes that safe is
646 /// that the pictures it codes are intra-only, which is the same file the
647 /// software seat writes ([`crate::export::Enc::open_hevc`]) and not the
648 /// GPU-resetting inter path AV1's opt-in exists for.
649 ///
650 /// `None` on everything [`HwEncoder::open`] answers `None` to, on a plugin
651 /// too old to export the symbol, on a GPU with no HEVC encode entrypoint,
652 /// and below 384x384 -- the driver's own floor, stated in the plugin. The
653 /// caller then takes the software intra encoder without a word about it.
654 ///
655 /// `colour` is what the SPS will say the samples mean, and it is taken at
656 /// the open because the parameter sets are written when the sequence starts.
657 /// libavcodec's HEVC decoder overwrites a container's colour with the
658 /// bitstream's, so a seat that signalled nothing hands a player
659 /// "unspecified" -- BT.601 -- however the file is tagged.
660 pub fn open_hevc(
661 width: u32,
662 height: u32,
663 fps_num: u32,
664 fps_den: u32,
665 bitrate: u64,
666 colour: ColorDescription,
667 ) -> Option<Self> {
668 let plugin = enc_plugin()?;
669 let open = plugin.open_hevc?;
670 let (primaries, transfer, matrix) = colour.codes();
671 let handle = open(
672 width,
673 height,
674 fps_num,
675 fps_den,
676 bitrate,
677 u32::from(primaries),
678 u32::from(transfer),
679 u32::from(matrix),
680 i32::from(colour.full_range),
681 );
682 if handle.is_null() {
683 return None;
684 }
685 Some(Self { plugin, handle })
686 }
687
688 /// The null check both opens share, which is the plugin's whole way of
689 /// saying "no".
690 fn opened(
691 plugin: &'static EncPlugin,
692 open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void,
693 width: u32,
694 height: u32,
695 fps_num: u32,
696 fps_den: u32,
697 bitrate: u64,
698 ) -> Option<Self> {
699 let handle = open(width, height, fps_num, fps_den, bitrate);
700 if handle.is_null() {
701 return None;
702 }
703 Some(Self { plugin, handle })
704 }
705
706 /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has
707 /// not finished an access unit yet; the returned bytes are Annex-B and stay
708 /// valid until the next call on this session.
709 pub fn encode(
710 &mut self,
711 y: &[u8],
712 u: &[u8],
713 v: &[u8],
714 width: u32,
715 height: u32,
716 force_key: bool,
717 ) -> crate::Result<Option<&[u8]>> {
718 let (w, h) = (width as usize, height as usize);
719 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
720 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
721 return Err("encode input is not a packed I420 frame".into());
722 }
723 let frame = VhFrame {
724 y: y.as_ptr(),
725 u: u.as_ptr(),
726 v: v.as_ptr(),
727 y_stride: w,
728 u_stride: cw,
729 v_stride: cw,
730 width,
731 height,
732 };
733 // SAFETY: `handle` is live, the planes outlive the call and their sizes
734 // were just checked against the strides we declare.
735 self.take(|plugin, handle, out, out_len| unsafe {
736 (plugin.frame)(handle, &frame, force_key as i32, out, out_len)
737 })
738 }
739
740 /// The surface size this seat codes in, or `None` where the plugin has no
741 /// zero-copy door at all. What [`HwEncoder::dma_want`] turns into the whole
742 /// description a decoder is asked for.
743 pub fn dma_geometry(&self) -> Option<(u32, u32)> {
744 let geometry = self.plugin.dma_geometry?;
745 self.plugin.frame_dma?;
746 let (mut coded_width, mut coded_height) = (0u32, 0u32);
747 // SAFETY: `handle` is live and both destinations are writable.
748 if unsafe { geometry(self.handle, &mut coded_width, &mut coded_height) } != 1 {
749 return None;
750 }
751 Some((coded_width, coded_height))
752 }
753
754 /// Feeds one picture the decoder left on the GPU. Same answer and same
755 /// lifetime rule as [`HwEncoder::encode`]; an error here is a real one, the
756 /// caller having asked [`HwEncoder::dma_want`] what this seat takes before
757 /// the decoder handed the buffer over.
758 pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> {
759 let Some(frame_dma) = self.plugin.frame_dma else {
760 return Err("hardware encoder has no zero-copy path".into());
761 };
762 let desc = dma.0;
763 // SAFETY: `handle` is live and `desc` outlives the call; the buffer it
764 // names is the decode session's, held for the caller by contract.
765 self.take(|_, handle, out, out_len| unsafe {
766 frame_dma(handle, &desc, force_key as i32, out, out_len)
767 })
768 }
769
770 /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule
771 /// as [`HwEncoder::encode`].
772 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
773 // SAFETY: `handle` is live.
774 self.take(|plugin, handle, out, out_len| unsafe { (plugin.drain)(handle, out, out_len) })
775 }
776
777 /// Shared tail of `encode`/`drain`: run the call, then turn the plugin's
778 /// (pointer, length) pair into a slice borrowed for as long as `&mut self`,
779 /// which is exactly the "valid until the next call" contract.
780 fn take(
781 &mut self,
782 call: impl FnOnce(&EncPlugin, *mut c_void, *mut *const u8, *mut usize) -> i32,
783 ) -> crate::Result<Option<&[u8]>> {
784 let mut ptr: *const u8 = std::ptr::null();
785 let mut len: usize = 0;
786 match call(self.plugin, self.handle, &mut ptr, &mut len) {
787 0 => return Ok(None),
788 1 => {}
789 code => return Err(format!("hardware encode failed (code {code})").into()),
790 }
791 if ptr.is_null() || len == 0 {
792 return Err("hardware encoder returned an empty access unit".into());
793 }
794 // SAFETY: the plugin promises `len` readable bytes at `ptr` until its
795 // next call on this session, which `&mut self` prevents overlapping.
796 Ok(Some(unsafe { std::slice::from_raw_parts(ptr, len) }))
797 }
798}
799
800impl Drop for LocalEncoder {
801 fn drop(&mut self) {
802 // SAFETY: `handle` came from `vh_enc_open` and is closed exactly once.
803 unsafe { (self.plugin.close)(self.handle) }
804 }
805}
806
807// As `HwSession`: used from one thread at a time (the export worker).
808unsafe impl Send for LocalEncoder {}
809
810/// An open hardware encode session, **in a child process** wherever there is a
811/// helper to run it in -- which is what keeps a driver's `abort()` off the
812/// editor. See [`crate::hwproc`] for the whole of why.
813///
814/// The API is the in-process one it replaced, call for call, so nothing in the
815/// export loop knows which side of a process boundary the encoder is on.
816pub enum HwEncoder {
817 /// The isolated seat, and the one every ordinary build takes.
818 Remote(crate::hwproc::Remote),
819 /// The seat as it was: taken only where there is no helper binary to run
820 /// (a build that produced the plugin and not the editor's own directory) or
821 /// where `VE_HW_INPROCESS` pins it, which is how the isolated path's cost is
822 /// measured against the path it replaced.
823 Local(LocalEncoder),
824}
825
826impl HwEncoder {
827 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded
828 /// at a constant `bitrate` bits per second. `None` whenever hardware encode
829 /// is unavailable -- plugin missing, plugin too old to export the encode
830 /// entry points, no driver, dimensions the driver refuses, *or a helper that
831 /// died opening any of it* -- and the caller falls back to the software
832 /// encoder.
833 pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
834 Self::seated(
835 crate::hwproc::Seat::H264,
836 width,
837 height,
838 fps_num,
839 fps_den,
840 bitrate,
841 ColorDescription::default(),
842 )
843 }
844
845 /// The same H.264 seat, **intra-only**: every picture comes back an IDR
846 /// with its own parameter sets, so every frame of the file is one a decoder
847 /// may be started from. What [`crate::proxy`] codes a stand-in with.
848 ///
849 /// `None` on everything [`HwEncoder::open`] answers `None` to *and* on a
850 /// plugin built before this seat existed -- and that `None` matters more
851 /// than the others: the caller must then take the software encoder, which
852 /// codes one frame a GOP, rather than the ordinary hardware seat, which
853 /// would write a long-GOP file under a name that promises otherwise.
854 pub fn open_intra(
855 width: u32,
856 height: u32,
857 fps_num: u32,
858 fps_den: u32,
859 bitrate: u64,
860 ) -> Option<Self> {
861 Self::seated(
862 crate::hwproc::Seat::Intra,
863 width,
864 height,
865 fps_num,
866 fps_den,
867 bitrate,
868 ColorDescription::default(),
869 )
870 }
871
872 /// The same, coding AV1 instead. `None` on everything [`HwEncoder::open`]
873 /// answers `None` to *and* on a plugin or a GPU with no AV1 encoder -- an
874 /// AV1 encode entrypoint is recent hardware, so this is the fallback that
875 /// really fires, and the caller's software AV1 encoder takes the export
876 /// without saying anything about it.
877 ///
878 /// The caller only reaches this when a person picked
879 /// [`crate::export::EncoderSeat::Hardware`] for an AV1 export: this is the
880 /// seat whose ring hang killed the editor on 2026-08-13, and it is now the
881 /// seat that kills a child instead.
882 pub fn open_av1(
883 width: u32,
884 height: u32,
885 fps_num: u32,
886 fps_den: u32,
887 bitrate: u64,
888 ) -> Option<Self> {
889 Self::seated(
890 crate::hwproc::Seat::Av1,
891 width,
892 height,
893 fps_num,
894 fps_den,
895 bitrate,
896 ColorDescription::default(),
897 )
898 }
899
900 /// The same, coding HEVC. Unlike the AV1 seat this is **not** behind an
901 /// opt-in: it is the default for an HEVC export, and what makes that safe is
902 /// that the pictures it codes are intra-only, which is the same file the
903 /// software seat writes ([`crate::export::Enc::open_hevc`]) and not the
904 /// GPU-resetting inter path AV1's opt-in exists for.
905 ///
906 /// `colour` is what the SPS will say the samples mean, and it is taken at
907 /// the open because the parameter sets are written when the sequence starts.
908 /// libavcodec's HEVC decoder overwrites a container's colour with the
909 /// bitstream's, so a seat that signalled nothing hands a player
910 /// "unspecified" -- BT.601 -- however the file is tagged.
911 pub fn open_hevc(
912 width: u32,
913 height: u32,
914 fps_num: u32,
915 fps_den: u32,
916 bitrate: u64,
917 colour: ColorDescription,
918 ) -> Option<Self> {
919 Self::seated(
920 crate::hwproc::Seat::Hevc,
921 width,
922 height,
923 fps_num,
924 fps_den,
925 bitrate,
926 colour,
927 )
928 }
929
930 /// Where the choice between the two seats is made, and the only place it is.
931 ///
932 /// A child is not started where there is nothing for it to open: with no
933 /// plugin on this machine the answer is `None` before a process is forked,
934 /// which is exactly what a plugin-less machine has always answered and at
935 /// the same cost.
936 fn seated(
937 seat: crate::hwproc::Seat,
938 width: u32,
939 height: u32,
940 fps_num: u32,
941 fps_den: u32,
942 bitrate: u64,
943 colour: ColorDescription,
944 ) -> Option<Self> {
945 let open = crate::hwproc::Open {
946 seat,
947 width,
948 height,
949 fps_num,
950 fps_den,
951 bitrate,
952 colour,
953 };
954 if enc_plugin().is_none() && !crate::hwproc::faked() {
955 return None;
956 }
957 // corner-cut: a build with no helper beside the executable keeps the
958 // in-process seat rather than losing hardware encode outright, so a
959 // driver crash there is still fatal. The ceiling is packaging: ship
960 // `hw-encode-child` next to `edith` (cargo already does) and this arm is
961 // never taken.
962 if !crate::hwproc::available() || std::env::var_os("VE_HW_INPROCESS").is_some() {
963 return LocalEncoder::open_seat(open).map(Self::Local);
964 }
965 crate::hwproc::Remote::spawn(open).map(Self::Remote)
966 }
967
968 /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has
969 /// not finished an access unit yet; the returned bytes are Annex-B and stay
970 /// valid until the next call on this session.
971 pub fn encode(
972 &mut self,
973 y: &[u8],
974 u: &[u8],
975 v: &[u8],
976 width: u32,
977 height: u32,
978 force_key: bool,
979 ) -> crate::Result<Option<&[u8]>> {
980 // Checked on this side of the boundary whichever seat has the picture:
981 // a caller's mistake is a caller's mistake, and the isolated seat must
982 // not turn one into a message about a dead child.
983 let (w, h) = (width as usize, height as usize);
984 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
985 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
986 return Err("encode input is not a packed I420 frame".into());
987 }
988 match self {
989 Self::Remote(remote) => remote.encode(y, u, v, width, height, force_key),
990 Self::Local(local) => local.encode(y, u, v, width, height, force_key),
991 }
992 }
993
994 /// What a decoded buffer must look like to reach this encoder without a
995 /// copy -- the surface size it codes in, plus the picture it was opened for
996 /// -- or `None` where the plugin has no zero-copy door at all.
997 pub fn dma_want(&mut self, width: u32, height: u32) -> Option<DmaWant> {
998 let (coded_width, coded_height) = match self {
999 Self::Remote(remote) => remote.dma_geometry()?,
1000 Self::Local(local) => local.dma_geometry()?,
1001 };
1002 Some(DmaWant {
1003 coded_width,
1004 coded_height,
1005 width,
1006 height,
1007 })
1008 }
1009
1010 /// Feeds one picture the decoder left on the GPU. Same answer and same
1011 /// lifetime rule as [`HwEncoder::encode`]; an error here is a real one, the
1012 /// caller having asked [`HwEncoder::dma_want`] what this seat takes before
1013 /// the decoder handed the buffer over.
1014 ///
1015 /// The buffer does not move for the isolated seat either: its descriptors
1016 /// go to the child over `SCM_RIGHTS` and the pixels stay where the decoder
1017 /// wrote them.
1018 pub fn encode_dma(&mut self, dma: &DmaFrame, force_key: bool) -> crate::Result<Option<&[u8]>> {
1019 match self {
1020 Self::Remote(remote) => remote.encode_dma(&dma.0, force_key),
1021 Self::Local(local) => local.encode_dma(dma, force_key),
1022 }
1023 }
1024
1025 /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule
1026 /// as [`HwEncoder::encode`].
1027 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
1028 match self {
1029 Self::Remote(remote) => remote.drain(),
1030 Self::Local(local) => local.drain(),
1031 }
1032 }
1033}