forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

hw.rs438 lines, 16.4 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::path::{Path, PathBuf};
20use std::sync::OnceLock;
21
22use libloading::Library;
23
24const LIB_NAME: &str = "libengine_hw.so";
25
26/// Stream metadata, C layout. Mirrors [`crate::VideoMeta`].
27#[repr(C)]
28#[derive(Default)]
29pub struct VhMeta {
30 pub width: u32,
31 pub height: u32,
32 pub frame_rate: f64,
33 pub frame_count: u32,
34}
35
36/// One decoded picture as planar I420. Pointers belong to the plugin and stay
37/// valid only until the next `vh_next_frame`/`vh_close` on the same session.
38#[repr(C)]
39pub struct VhFrame {
40 pub y: *const u8,
41 pub u: *const u8,
42 pub v: *const u8,
43 pub y_stride: usize,
44 pub u_stride: usize,
45 pub v_stride: usize,
46 pub width: u32,
47 pub height: u32,
48}
49
50impl Default for VhFrame {
51 fn default() -> Self {
52 Self {
53 y: std::ptr::null(),
54 u: std::ptr::null(),
55 v: std::ptr::null(),
56 y_stride: 0,
57 u_stride: 0,
58 v_stride: 0,
59 width: 0,
60 height: 0,
61 }
62 }
63}
64
65/// What *this machine* takes, as far as the plugin implements it: one bit per
66/// codec ([`CAP_H264`] and its three neighbours) in each mask, so a caller reads
67/// "H.264 decodes and encodes here, HEVC only decodes" off three `u32`s.
68///
69/// The intersection is the plugin's to compute, never the driver's alone: a GPU
70/// with an HEVC *encode* entrypoint is still not an HEVC encoder here -- the
71/// plugin has no such entry point -- and a capability nothing can reach would be
72/// a lie in whatever the front-end draws from this.
73#[repr(C)]
74#[derive(Default, Clone, Copy, Debug, PartialEq, Eq)]
75pub struct VhCaps {
76 pub decode: u32,
77 pub encode: u32,
78 /// Codecs whose 10-bit profiles decode: the driver has the profile *and* a
79 /// P010 image format for the read-back, which is the pair the plugin's
80 /// 10-bit path needs.
81 pub decode_10bit: u32,
82}
83
84pub const CAP_H264: u32 = 1 << 0;
85pub const CAP_HEVC: u32 = 1 << 1;
86pub const CAP_VP9: u32 = 1 << 2;
87pub const CAP_AV1: u32 = 1 << 3;
88
89struct Plugin {
90 open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,
91 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,
92 next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32,
93 close: unsafe extern "C" fn(*mut c_void),
94 /// The capability query, and the one symbol of this table that may be
95 /// missing: a plugin built before it exports the four above and not this,
96 /// which costs a front-end the listing and never a decode.
97 caps: Option<unsafe extern "C" fn(*mut VhCaps) -> i32>,
98 // Never dropped (lives in a static), so the fn pointers above stay valid.
99 _lib: Library,
100}
101
102fn plugin() -> Option<&'static Plugin> {
103 static PLUGIN: OnceLock<Option<Plugin>> = OnceLock::new();
104 PLUGIN.get_or_init(load).as_ref()
105}
106
107/// Where the plugin may live: next to the executable first (cargo puts both in
108/// target/<profile>), then whatever the dynamic linker's search path turns up.
109fn candidates() -> impl Iterator<Item = PathBuf> {
110 std::env::current_exe()
111 .ok()
112 .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)))
113 .into_iter()
114 .chain(std::iter::once(PathBuf::from(LIB_NAME)))
115}
116
117fn load() -> Option<Plugin> {
118 for candidate in candidates() {
119 // SAFETY: loading a shared object runs its initialisers; we only ever
120 // name our own plugin, and every symbol below is type-checked against
121 // the definitions this crate shares with it.
122 let lib = match unsafe { Library::new(candidate) } {
123 Ok(lib) => lib,
124 Err(_) => continue,
125 };
126 let plugin = unsafe {
127 (|| {
128 Some(Plugin {
129 open_at: *lib.get(b"vh_open_at\0").ok()?,
130 meta: *lib.get(b"vh_meta\0").ok()?,
131 next_frame: *lib.get(b"vh_next_frame\0").ok()?,
132 close: *lib.get(b"vh_close\0").ok()?,
133 caps: lib.get(b"vh_caps\0").ok().map(|s| *s),
134 _lib: lib,
135 })
136 })()
137 };
138 if plugin.is_some() {
139 return plugin;
140 }
141 }
142 None
143}
144
145/// What the plugin says this machine decodes and encodes, asked once per
146/// process and cached: the answer cannot change while we run.
147///
148/// `None` on every way there is no answer -- no plugin, a plugin older than the
149/// symbol (optional exactly as `vh_enc_av1_open` is: such a plugin still
150/// decodes), no driver, a driver that refuses the query -- and a caller says
151/// "software only" for all of them, which is what they mean.
152///
153/// Costs one VA-API init (~90 ms) the first time: ask it off a render thread.
154pub fn caps() -> Option<VhCaps> {
155 static CAPS: OnceLock<Option<VhCaps>> = OnceLock::new();
156 *CAPS.get_or_init(|| {
157 let query = plugin()?.caps?;
158 let mut caps = VhCaps::default();
159 // SAFETY: the plugin writes the struct it is handed and reports "no
160 // answer" as a negative code; nothing is borrowed across the call.
161 match unsafe { query(&mut caps) } {
162 0 => Some(caps),
163 _ => None,
164 }
165 })
166}
167
168/// An open hardware decode session. Dropping it closes the plugin session.
169pub struct HwSession {
170 plugin: &'static Plugin,
171 handle: *mut c_void,
172}
173
174impl HwSession {
175 /// Probes the plugin against this very file: success means the driver,
176 /// the render node and the stream's profile are all usable.
177 pub fn open(path: &Path) -> Option<Self> {
178 Self::open_at(path, 0)
179 }
180
181 /// As [`HwSession::open`], but the first [`HwSession::next_frame`] returns
182 /// display index `start_frame`; earlier pictures are decoded and dropped
183 /// inside the plugin, without the read-back copy.
184 pub fn open_at(path: &Path, start_frame: u32) -> Option<Self> {
185 let plugin = plugin()?;
186 let c_path = CString::new(path.as_os_str().as_encoded_bytes()).ok()?;
187 // Sample ids are 1-based, frame indices 0-based.
188 let target_sample = start_frame.saturating_add(1);
189 // SAFETY: `c_path` is a valid NUL-terminated string alive for the call.
190 let handle = unsafe { (plugin.open_at)(c_path.as_ptr(), target_sample) };
191 if handle.is_null() {
192 return None;
193 }
194 Some(Self { plugin, handle })
195 }
196
197 pub fn meta(&self) -> Option<VhMeta> {
198 let mut meta = VhMeta::default();
199 // SAFETY: `handle` came from `vh_open_at` and is still open.
200 if unsafe { (self.plugin.meta)(self.handle, &mut meta) } < 0 {
201 return None;
202 }
203 Some(meta)
204 }
205
206 /// Next picture in display order as tightly packed I420 `(y, u, v)`.
207 /// `Ok(None)` is clean end of stream.
208 pub fn next_frame(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
209 let mut frame = VhFrame::default();
210 // SAFETY: `handle` is live; the plugin fills `frame` with pointers that
211 // stay valid until the next call, which `&mut self` prevents overlapping.
212 match unsafe { (self.plugin.next_frame)(self.handle, &mut frame) } {
213 0 => return Ok(None),
214 1 => {}
215 code => return Err(format!("hardware decode failed (code {code})").into()),
216 }
217 let (w, h) = (frame.width as usize, frame.height as usize);
218 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
219 if frame.y.is_null()
220 || frame.u.is_null()
221 || frame.v.is_null()
222 || frame.y_stride != w
223 || frame.u_stride != cw
224 || frame.v_stride != cw
225 {
226 return Err("hardware plugin returned a non-packed I420 frame".into());
227 }
228 // SAFETY: plane pointers are non-null and the strides just checked above
229 // pin each plane's length; the borrow ends before the next call.
230 unsafe {
231 Ok(Some((
232 std::slice::from_raw_parts(frame.y, w * h),
233 std::slice::from_raw_parts(frame.u, cw * ch),
234 std::slice::from_raw_parts(frame.v, cw * ch),
235 frame.width,
236 frame.height,
237 )))
238 }
239 }
240}
241
242impl Drop for HwSession {
243 fn drop(&mut self) {
244 // SAFETY: `handle` came from `vh_open_at` and is closed exactly once.
245 unsafe { (self.plugin.close)(self.handle) }
246 }
247}
248
249// The plugin session is used from one thread at a time (the decode worker) and
250// never shared; VA-API state inside it is not `Sync`.
251unsafe impl Send for HwSession {}
252
253struct EncPlugin {
254 open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void,
255 /// The AV1 seat, and the one symbol that may be missing: a plugin built
256 /// before AV1 encode existed exports the four below and not this, which
257 /// costs an AV1 export its hardware path and nothing else. Every session it
258 /// opens is fed and closed through the very same three entry points -- the
259 /// plugin keeps one session type for both codecs, so the codec is decided
260 /// once, at the open, exactly as the H.264 seat's parameters are.
261 open_av1: Option<extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void>,
262 frame:
263 unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32,
264 drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32,
265 close: unsafe extern "C" fn(*mut c_void),
266 // Never dropped (lives in a static), so the fn pointers above stay valid.
267 _lib: Library,
268}
269
270fn enc_plugin() -> Option<&'static EncPlugin> {
271 static PLUGIN: OnceLock<Option<EncPlugin>> = OnceLock::new();
272 PLUGIN.get_or_init(load_enc).as_ref()
273}
274
275fn load_enc() -> Option<EncPlugin> {
276 for candidate in candidates() {
277 // SAFETY: as in `load` -- our own plugin, symbols type-checked against
278 // the definitions this crate shares with it.
279 let lib = match unsafe { Library::new(candidate) } {
280 Ok(lib) => lib,
281 Err(_) => continue,
282 };
283 let plugin = unsafe {
284 (|| {
285 Some(EncPlugin {
286 open: *lib.get(b"vh_enc_open\0").ok()?,
287 open_av1: lib.get(b"vh_enc_av1_open\0").ok().map(|s| *s),
288 frame: *lib.get(b"vh_enc_frame\0").ok()?,
289 drain: *lib.get(b"vh_enc_drain\0").ok()?,
290 close: *lib.get(b"vh_enc_close\0").ok()?,
291 _lib: lib,
292 })
293 })()
294 };
295 if plugin.is_some() {
296 return plugin;
297 }
298 }
299 None
300}
301
302/// An open hardware encode session. Dropping it closes the plugin session.
303pub struct HwEncoder {
304 plugin: &'static EncPlugin,
305 handle: *mut c_void,
306}
307
308impl HwEncoder {
309 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded
310 /// at a constant `bitrate` bits per second. `None` whenever hardware encode
311 /// is unavailable -- plugin missing, plugin too old to export the encode
312 /// entry points, no driver, dimensions the driver refuses -- and the caller
313 /// falls back to the software encoder.
314 pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
315 let plugin = enc_plugin()?;
316 Self::opened(
317 plugin,
318 plugin.open,
319 width,
320 height,
321 fps_num,
322 fps_den,
323 bitrate,
324 )
325 }
326
327 /// The same, coding AV1 instead. `None` on everything [`HwEncoder::open`]
328 /// answers `None` to *and* on a plugin or a GPU with no AV1 encoder -- an
329 /// AV1 encode entrypoint is recent hardware, so this is the fallback that
330 /// really fires, and the caller's software AV1 encoder takes the export
331 /// without saying anything about it.
332 ///
333 /// The caller only reaches this behind `VE_HW_AV1=1`: the vendored encoder
334 /// reset this project's own GPU, which [`crate::export::Enc::open_av1`]
335 /// states in full.
336 pub fn open_av1(
337 width: u32,
338 height: u32,
339 fps_num: u32,
340 fps_den: u32,
341 bitrate: u64,
342 ) -> Option<Self> {
343 let plugin = enc_plugin()?;
344 let open = plugin.open_av1?;
345 Self::opened(plugin, open, width, height, fps_num, fps_den, bitrate)
346 }
347
348 /// The null check both opens share, which is the plugin's whole way of
349 /// saying "no".
350 fn opened(
351 plugin: &'static EncPlugin,
352 open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void,
353 width: u32,
354 height: u32,
355 fps_num: u32,
356 fps_den: u32,
357 bitrate: u64,
358 ) -> Option<Self> {
359 let handle = open(width, height, fps_num, fps_den, bitrate);
360 if handle.is_null() {
361 return None;
362 }
363 Some(Self { plugin, handle })
364 }
365
366 /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has
367 /// not finished an access unit yet; the returned bytes are Annex-B and stay
368 /// valid until the next call on this session.
369 pub fn encode(
370 &mut self,
371 y: &[u8],
372 u: &[u8],
373 v: &[u8],
374 width: u32,
375 height: u32,
376 force_key: bool,
377 ) -> crate::Result<Option<&[u8]>> {
378 let (w, h) = (width as usize, height as usize);
379 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
380 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
381 return Err("encode input is not a packed I420 frame".into());
382 }
383 let frame = VhFrame {
384 y: y.as_ptr(),
385 u: u.as_ptr(),
386 v: v.as_ptr(),
387 y_stride: w,
388 u_stride: cw,
389 v_stride: cw,
390 width,
391 height,
392 };
393 // SAFETY: `handle` is live, the planes outlive the call and their sizes
394 // were just checked against the strides we declare.
395 self.take(|plugin, handle, out, out_len| unsafe {
396 (plugin.frame)(handle, &frame, force_key as i32, out, out_len)
397 })
398 }
399
400 /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule
401 /// as [`HwEncoder::encode`].
402 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
403 // SAFETY: `handle` is live.
404 self.take(|plugin, handle, out, out_len| unsafe { (plugin.drain)(handle, out, out_len) })
405 }
406
407 /// Shared tail of `encode`/`drain`: run the call, then turn the plugin's
408 /// (pointer, length) pair into a slice borrowed for as long as `&mut self`,
409 /// which is exactly the "valid until the next call" contract.
410 fn take(
411 &mut self,
412 call: impl FnOnce(&EncPlugin, *mut c_void, *mut *const u8, *mut usize) -> i32,
413 ) -> crate::Result<Option<&[u8]>> {
414 let mut ptr: *const u8 = std::ptr::null();
415 let mut len: usize = 0;
416 match call(self.plugin, self.handle, &mut ptr, &mut len) {
417 0 => return Ok(None),
418 1 => {}
419 code => return Err(format!("hardware encode failed (code {code})").into()),
420 }
421 if ptr.is_null() || len == 0 {
422 return Err("hardware encoder returned an empty access unit".into());
423 }
424 // SAFETY: the plugin promises `len` readable bytes at `ptr` until its
425 // next call on this session, which `&mut self` prevents overlapping.
426 Ok(Some(unsafe { std::slice::from_raw_parts(ptr, len) }))
427 }
428}
429
430impl Drop for HwEncoder {
431 fn drop(&mut self) {
432 // SAFETY: `handle` came from `vh_enc_open` and is closed exactly once.
433 unsafe { (self.plugin.close)(self.handle) }
434 }
435}
436
437// As `HwSession`: used from one thread at a time (the export worker).
438unsafe impl Send for HwEncoder {}