forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

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