forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

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