forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

hw.rs335 lines, 12.1 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
65struct Plugin {
66 open_at: unsafe extern "C" fn(*const c_char, u32) -> *mut c_void,
67 meta: unsafe extern "C" fn(*mut c_void, *mut VhMeta) -> i32,
68 next_frame: unsafe extern "C" fn(*mut c_void, *mut VhFrame) -> i32,
69 close: unsafe extern "C" fn(*mut c_void),
70 // Never dropped (lives in a static), so the fn pointers above stay valid.
71 _lib: Library,
72}
73
74fn plugin() -> Option<&'static Plugin> {
75 static PLUGIN: OnceLock<Option<Plugin>> = OnceLock::new();
76 PLUGIN.get_or_init(load).as_ref()
77}
78
79/// Where the plugin may live: next to the executable first (cargo puts both in
80/// target/<profile>), then whatever the dynamic linker's search path turns up.
81fn candidates() -> impl Iterator<Item = PathBuf> {
82 std::env::current_exe()
83 .ok()
84 .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)))
85 .into_iter()
86 .chain(std::iter::once(PathBuf::from(LIB_NAME)))
87}
88
89fn load() -> Option<Plugin> {
90 for candidate in candidates() {
91 // SAFETY: loading a shared object runs its initialisers; we only ever
92 // name our own plugin, and every symbol below is type-checked against
93 // the definitions this crate shares with it.
94 let lib = match unsafe { Library::new(candidate) } {
95 Ok(lib) => lib,
96 Err(_) => continue,
97 };
98 let plugin = unsafe {
99 (|| {
100 Some(Plugin {
101 open_at: *lib.get(b"vh_open_at\0").ok()?,
102 meta: *lib.get(b"vh_meta\0").ok()?,
103 next_frame: *lib.get(b"vh_next_frame\0").ok()?,
104 close: *lib.get(b"vh_close\0").ok()?,
105 _lib: lib,
106 })
107 })()
108 };
109 if plugin.is_some() {
110 return plugin;
111 }
112 }
113 None
114}
115
116/// An open hardware decode session. Dropping it closes the plugin session.
117pub struct HwSession {
118 plugin: &'static Plugin,
119 handle: *mut c_void,
120}
121
122impl HwSession {
123 /// Probes the plugin against this very file: success means the driver,
124 /// the render node and the stream's profile are all usable.
125 pub fn open(path: &Path) -> Option<Self> {
126 Self::open_at(path, 0)
127 }
128
129 /// As [`HwSession::open`], but the first [`HwSession::next_frame`] returns
130 /// display index `start_frame`; earlier pictures are decoded and dropped
131 /// inside the plugin, without the read-back copy.
132 pub fn open_at(path: &Path, start_frame: u32) -> Option<Self> {
133 let plugin = plugin()?;
134 let c_path = CString::new(path.as_os_str().as_encoded_bytes()).ok()?;
135 // Sample ids are 1-based, frame indices 0-based.
136 let target_sample = start_frame.saturating_add(1);
137 // SAFETY: `c_path` is a valid NUL-terminated string alive for the call.
138 let handle = unsafe { (plugin.open_at)(c_path.as_ptr(), target_sample) };
139 if handle.is_null() {
140 return None;
141 }
142 Some(Self { plugin, handle })
143 }
144
145 pub fn meta(&self) -> Option<VhMeta> {
146 let mut meta = VhMeta::default();
147 // SAFETY: `handle` came from `vh_open_at` and is still open.
148 if unsafe { (self.plugin.meta)(self.handle, &mut meta) } < 0 {
149 return None;
150 }
151 Some(meta)
152 }
153
154 /// Next picture in display order as tightly packed I420 `(y, u, v)`.
155 /// `Ok(None)` is clean end of stream.
156 pub fn next_frame(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
157 let mut frame = VhFrame::default();
158 // SAFETY: `handle` is live; the plugin fills `frame` with pointers that
159 // stay valid until the next call, which `&mut self` prevents overlapping.
160 match unsafe { (self.plugin.next_frame)(self.handle, &mut frame) } {
161 0 => return Ok(None),
162 1 => {}
163 code => return Err(format!("hardware decode failed (code {code})").into()),
164 }
165 let (w, h) = (frame.width as usize, frame.height as usize);
166 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
167 if frame.y.is_null()
168 || frame.u.is_null()
169 || frame.v.is_null()
170 || frame.y_stride != w
171 || frame.u_stride != cw
172 || frame.v_stride != cw
173 {
174 return Err("hardware plugin returned a non-packed I420 frame".into());
175 }
176 // SAFETY: plane pointers are non-null and the strides just checked above
177 // pin each plane's length; the borrow ends before the next call.
178 unsafe {
179 Ok(Some((
180 std::slice::from_raw_parts(frame.y, w * h),
181 std::slice::from_raw_parts(frame.u, cw * ch),
182 std::slice::from_raw_parts(frame.v, cw * ch),
183 frame.width,
184 frame.height,
185 )))
186 }
187 }
188}
189
190impl Drop for HwSession {
191 fn drop(&mut self) {
192 // SAFETY: `handle` came from `vh_open_at` and is closed exactly once.
193 unsafe { (self.plugin.close)(self.handle) }
194 }
195}
196
197// The plugin session is used from one thread at a time (the decode worker) and
198// never shared; VA-API state inside it is not `Sync`.
199unsafe impl Send for HwSession {}
200
201struct EncPlugin {
202 open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void,
203 frame:
204 unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32,
205 drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32,
206 close: unsafe extern "C" fn(*mut c_void),
207 // Never dropped (lives in a static), so the fn pointers above stay valid.
208 _lib: Library,
209}
210
211fn enc_plugin() -> Option<&'static EncPlugin> {
212 static PLUGIN: OnceLock<Option<EncPlugin>> = OnceLock::new();
213 PLUGIN.get_or_init(load_enc).as_ref()
214}
215
216fn load_enc() -> Option<EncPlugin> {
217 for candidate in candidates() {
218 // SAFETY: as in `load` -- our own plugin, symbols type-checked against
219 // the definitions this crate shares with it.
220 let lib = match unsafe { Library::new(candidate) } {
221 Ok(lib) => lib,
222 Err(_) => continue,
223 };
224 let plugin = unsafe {
225 (|| {
226 Some(EncPlugin {
227 open: *lib.get(b"vh_enc_open\0").ok()?,
228 frame: *lib.get(b"vh_enc_frame\0").ok()?,
229 drain: *lib.get(b"vh_enc_drain\0").ok()?,
230 close: *lib.get(b"vh_enc_close\0").ok()?,
231 _lib: lib,
232 })
233 })()
234 };
235 if plugin.is_some() {
236 return plugin;
237 }
238 }
239 None
240}
241
242/// An open hardware encode session. Dropping it closes the plugin session.
243pub struct HwEncoder {
244 plugin: &'static EncPlugin,
245 handle: *mut c_void,
246}
247
248impl HwEncoder {
249 /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded
250 /// at a constant `bitrate` bits per second. `None` whenever hardware encode
251 /// is unavailable -- plugin missing, plugin too old to export the encode
252 /// entry points, no driver, dimensions the driver refuses -- and the caller
253 /// falls back to the software encoder.
254 pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
255 let plugin = enc_plugin()?;
256 let handle = (plugin.open)(width, height, fps_num, fps_den, bitrate);
257 if handle.is_null() {
258 return None;
259 }
260 Some(Self { plugin, handle })
261 }
262
263 /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has
264 /// not finished an access unit yet; the returned bytes are Annex-B and stay
265 /// valid until the next call on this session.
266 pub fn encode(
267 &mut self,
268 y: &[u8],
269 u: &[u8],
270 v: &[u8],
271 width: u32,
272 height: u32,
273 force_key: bool,
274 ) -> crate::Result<Option<&[u8]>> {
275 let (w, h) = (width as usize, height as usize);
276 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
277 if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch {
278 return Err("encode input is not a packed I420 frame".into());
279 }
280 let frame = VhFrame {
281 y: y.as_ptr(),
282 u: u.as_ptr(),
283 v: v.as_ptr(),
284 y_stride: w,
285 u_stride: cw,
286 v_stride: cw,
287 width,
288 height,
289 };
290 // SAFETY: `handle` is live, the planes outlive the call and their sizes
291 // were just checked against the strides we declare.
292 self.take(|plugin, handle, out, out_len| unsafe {
293 (plugin.frame)(handle, &frame, force_key as i32, out, out_len)
294 })
295 }
296
297 /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule
298 /// as [`HwEncoder::encode`].
299 pub fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
300 // SAFETY: `handle` is live.
301 self.take(|plugin, handle, out, out_len| unsafe { (plugin.drain)(handle, out, out_len) })
302 }
303
304 /// Shared tail of `encode`/`drain`: run the call, then turn the plugin's
305 /// (pointer, length) pair into a slice borrowed for as long as `&mut self`,
306 /// which is exactly the "valid until the next call" contract.
307 fn take(
308 &mut self,
309 call: impl FnOnce(&EncPlugin, *mut c_void, *mut *const u8, *mut usize) -> i32,
310 ) -> crate::Result<Option<&[u8]>> {
311 let mut ptr: *const u8 = std::ptr::null();
312 let mut len: usize = 0;
313 match call(self.plugin, self.handle, &mut ptr, &mut len) {
314 0 => return Ok(None),
315 1 => {}
316 code => return Err(format!("hardware encode failed (code {code})").into()),
317 }
318 if ptr.is_null() || len == 0 {
319 return Err("hardware encoder returned an empty access unit".into());
320 }
321 // SAFETY: the plugin promises `len` readable bytes at `ptr` until its
322 // next call on this session, which `&mut self` prevents overlapping.
323 Ok(Some(unsafe { std::slice::from_raw_parts(ptr, len) }))
324 }
325}
326
327impl Drop for HwEncoder {
328 fn drop(&mut self) {
329 // SAFETY: `handle` came from `vh_enc_open` and is closed exactly once.
330 unsafe { (self.plugin.close)(self.handle) }
331 }
332}
333
334// As `HwSession`: used from one thread at a time (the export worker).
335unsafe impl Send for HwEncoder {}