forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBdff7d84Tahinli3 months ago58 commits

lib.rs749 lines, 27.7 KiBHistoryRawDownload
1//! VA-API H.264 decode and encode, shipped as a `dlopen`-able plugin so the main
2//! binary never gets a DT_NEEDED on libva/gbm/drm. Every entry point is
3//! `extern "C"`, catches unwinds and reports failure as a null pointer or a
4//! negative code: the caller's contract is "any failure means use the software
5//! codec".
6//!
7//! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with
8//! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path
9//! is running the decoder in a child process instead of in-process.
10
11use std::collections::VecDeque;
12use std::ffi::{CStr, c_char, c_void};
13use std::panic::{AssertUnwindSafe, catch_unwind};
14use std::path::{Path, PathBuf};
15use std::rc::Rc;
16
17use cros_codecs::backend::vaapi::decoder::VaapiBackend;
18use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
19use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};
20use cros_codecs::decoder::stateless::h264::H264;
21use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
22use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
23use cros_codecs::encoder::h264::EncoderConfig as H264Config;
24use cros_codecs::encoder::stateless::h264::StatelessEncoder;
25use cros_codecs::encoder::{
26 FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder,
27};
28use cros_codecs::image_processing::nv12_to_i420;
29use cros_codecs::libva::{
30 Display, Image, Surface, VA_FOURCC_NV12, VAEntrypoint, VAImageFormat, VAProfile,
31};
32use cros_codecs::video_frame::VideoFrame;
33use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};
34use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame;
35use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};
36use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution};
37use gbm::{BufferObjectFlags, Format as GbmFormat};
38
39use engine::demux::Demuxer;
40use engine::hw::{VhFrame, VhMeta};
41
42type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
43type Decoder = StatelessDecoder<H264, VaapiBackend<PooledFrame>>;
44type Handle = <Decoder as StatelessVideoDecoder>::Handle;
45type Encoder = StatelessEncoder<
46 GenericDmaVideoFrame,
47 VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
48>;
49
50/// Ceiling on decode/drain iterations that make no progress. VA-API in blocking
51/// mode should always either hand back an event or accept input; this only
52/// exists so a misbehaving driver returns an error instead of hanging the app.
53const STALL_LIMIT: u32 = 10_000;
54
55struct Session {
56 decoder: Decoder,
57 /// NV12 descriptor for `vaGetImage`, queried once at open.
58 nv12_format: VAImageFormat,
59 pool: FramePool<GenericDmaVideoFrame>,
60 demuxer: Demuxer,
61 meta: VhMeta,
62 ready: VecDeque<Handle>,
63 /// Remaining bytes of the access unit currently being fed, if any.
64 pending: Vec<u8>,
65 timestamp: u64,
66 flushed: bool,
67 /// Pictures still to be decoded and thrown away to land on a seek target.
68 skip: u32,
69 /// Tightly packed I420 handed out through [`VhFrame`]; reused every frame,
70 /// which is exactly why the pointers are only valid until the next call.
71 out: Vec<u8>,
72 luma: usize,
73 chroma: usize,
74}
75
76/// Mesa's GBM cannot allocate an NV12 buffer object at all (measured on
77/// radeonsi: every flag/modifier combination returns NULL), so we allocate one
78/// linear single-plane R8 buffer big enough for luma + chroma and describe the
79/// NV12 layout inside it ourselves. VA-API imports it as one DRM-PRIME object
80/// with two planes at known offsets, which is exactly what the descriptor in
81/// `GenericDmaVideoFrame` emits.
82fn alloc_nv12(
83 gbm: &gbm::Device<std::fs::File>,
84 coded: Resolution,
85) -> Result<GenericDmaVideoFrame, String> {
86 let rows = coded.height + coded.height.div_ceil(2);
87 let bo = gbm
88 .create_buffer_object::<()>(coded.width, rows, GbmFormat::R8, BufferObjectFlags::LINEAR)
89 .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?;
90 let pitch = bo.stride().map_err(|e| e.to_string())? as usize;
91 let fd = bo.fd().map_err(|e| e.to_string())?;
92 GenericDmaVideoFrame::new(vec![std::fs::File::from(fd)], nv12_layout(coded, pitch))
93}
94
95/// Two NV12 planes packed one after the other in a single buffer object.
96fn nv12_layout(coded: Resolution, pitch: usize) -> FrameLayout {
97 FrameLayout {
98 format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */),
99 size: coded,
100 planes: vec![
101 PlaneLayout {
102 buffer_index: 0,
103 offset: 0,
104 stride: pitch,
105 },
106 PlaneLayout {
107 buffer_index: 0,
108 offset: pitch * coded.height as usize,
109 stride: pitch,
110 },
111 ],
112 }
113}
114
115/// First render node that gives us both a VA display and a GBM device. Which
116/// node is the right one is a per-machine question, so we probe rather than
117/// hardcode renderD128.
118fn open_devices() -> Option<(Rc<Display>, gbm::Device<std::fs::File>)> {
119 let mut nodes: Vec<PathBuf> = std::fs::read_dir("/dev/dri")
120 .ok()?
121 .flatten()
122 .map(|e| e.path())
123 .filter(|p| {
124 p.file_name()
125 .and_then(|n| n.to_str())
126 .is_some_and(|n| n.starts_with("renderD"))
127 })
128 .collect();
129 nodes.sort();
130 nodes.into_iter().find_map(|node| {
131 let display = Display::open_drm_display(&node).ok()?;
132 let file = std::fs::OpenOptions::new()
133 .read(true)
134 .write(true)
135 .open(&node)
136 .ok()?;
137 let gbm = gbm::Device::new(file).ok()?;
138 Some((display, gbm))
139 })
140}
141
142impl Session {
143 fn open(path: &Path) -> Option<Self> {
144 let (meta, demuxer) = Demuxer::open(path).ok()?;
145 let (display, gbm) = open_devices()?;
146 let nv12_format = display
147 .query_image_formats()
148 .ok()?
149 .into_iter()
150 .find(|f| f.fourcc == VA_FOURCC_NV12)?;
151 let decoder = Decoder::new_vaapi(display, BlockingMode::Blocking).ok()?;
152 let pool = FramePool::new(move |info: &StreamInfo| {
153 alloc_nv12(&gbm, info.coded_resolution).expect("output frame allocation failed")
154 });
155 Some(Self {
156 decoder,
157 nv12_format,
158 pool,
159 demuxer,
160 meta: VhMeta {
161 width: meta.width,
162 height: meta.height,
163 frame_rate: meta.frame_rate,
164 frame_count: meta.frame_count,
165 },
166 ready: VecDeque::new(),
167 pending: Vec::new(),
168 timestamp: 0,
169 flushed: false,
170 skip: 0,
171 out: Vec::new(),
172 luma: 0,
173 chroma: 0,
174 })
175 }
176
177 /// As [`Session::open`], but positioned so the first picture handed out is
178 /// sample `target_sample` (1-based): decode restarts at the sync sample at
179 /// or before it and the pictures in between are dropped unread.
180 fn open_at(path: &Path, target_sample: u32) -> Option<Self> {
181 let mut session = Self::open(path)?;
182 let sync = session.demuxer.seek_to_sync_at_or_before(target_sample);
183 session.skip = target_sample.saturating_sub(sync);
184 Some(session)
185 }
186
187 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
188 fn pump(&mut self) -> Result<bool, String> {
189 let mut stalls = 0u32;
190 loop {
191 // Stop draining as soon as we have a picture: every handle we hold
192 // keeps a pool buffer out of circulation.
193 while self.ready.is_empty() {
194 match self.decoder.next_event() {
195 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),
196 Some(DecoderEvent::FormatChanged) => {
197 let info = self
198 .decoder
199 .stream_info()
200 .ok_or("format changed without stream info")?
201 .clone();
202 self.pool.resize(&info);
203 }
204 None => break,
205 }
206 }
207 if let Some(handle) = self.ready.pop_front() {
208 // Seek discards: dropping the handle skips the `vaGetImage`
209 // read-back (~1.2 ms/picture) and frees its pool buffer.
210 if self.skip > 0 {
211 self.skip -= 1;
212 continue;
213 }
214 self.emit(handle);
215 return Ok(true);
216 }
217 if self.flushed {
218 return Ok(false);
219 }
220
221 if self.pending.is_empty() {
222 match self.demuxer.next_access_unit() {
223 Ok(Some(au)) => self.pending = au,
224 Ok(None) => {
225 self.decoder.flush().map_err(|e| e.to_string())?;
226 self.flushed = true;
227 continue;
228 }
229 Err(e) => return Err(e.to_string()),
230 }
231 }
232
233 let Self {
234 decoder,
235 pool,
236 pending,
237 timestamp,
238 ..
239 } = self;
240 match decoder.decode(*timestamp, pending, &mut || pool.alloc()) {
241 Ok(0) => return Err("decoder consumed no input".into()),
242 Ok(n) => {
243 pending.drain(..n.min(pending.len()));
244 if pending.is_empty() {
245 *timestamp += 1;
246 }
247 stalls = 0;
248 }
249 // Both mean "handle pending events, then resubmit the same data".
250 Err(DecodeError::CheckEvents) | Err(DecodeError::NotEnoughOutputBuffers(_)) => {
251 stalls += 1;
252 if stalls > STALL_LIMIT {
253 return Err("decoder stalled waiting for output buffers".into());
254 }
255 }
256 Err(e) => return Err(e.to_string()),
257 }
258 }
259 }
260
261 /// Copies a decoded NV12 surface into `self.out` as packed I420.
262 fn emit(&mut self, handle: Handle) {
263 let res = handle.display_resolution();
264 let (w, h) = (res.width as usize, res.height as usize);
265 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
266 if self.luma != w * h || self.chroma != cw * ch {
267 self.luma = w * h;
268 self.chroma = cw * ch;
269 self.out = vec![0u8; self.luma + 2 * self.chroma];
270 }
271 self.meta.width = res.width;
272 self.meta.height = res.height;
273
274 // Read back with vaGetImage rather than mapping our own DMA-BUF: on a
275 // discrete GPU that buffer lives in VRAM and a CPU read of it runs at
276 // ~44 MB/s over the PCIe BAR (measured), which costs 350 ms/frame. The
277 // driver copies into host-visible memory for us instead.
278 // Cheap no-op in blocking mode, but pixels must never be read early.
279 let _ = DecodedHandle::sync(&handle);
280 let borrowed = handle.borrow();
281 let size = (w as u32, h as u32);
282 let image = Image::create_from(borrowed.surface(), self.nv12_format, size, size)
283 .expect("vaGetImage failed");
284 let va = *image.image();
285 let data: &[u8] = image.as_ref();
286
287 let (dst_y, rest) = self.out.split_at_mut(self.luma);
288 let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
289 nv12_to_i420(
290 &data[va.offsets[Y_PLANE] as usize..],
291 va.pitches[Y_PLANE] as usize,
292 dst_y,
293 w,
294 &data[va.offsets[UV_PLANE] as usize..],
295 va.pitches[UV_PLANE] as usize,
296 dst_u,
297 cw,
298 dst_v,
299 cw,
300 w,
301 h,
302 );
303 }
304
305 fn fill(&self, out: &mut VhFrame) {
306 let w = self.meta.width as usize;
307 let cw = w.div_ceil(2);
308 out.y = self.out.as_ptr();
309 // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`.
310 unsafe {
311 out.u = self.out.as_ptr().add(self.luma);
312 out.v = self.out.as_ptr().add(self.luma + self.chroma);
313 }
314 out.y_stride = w;
315 out.u_stride = cw;
316 out.v_stride = cw;
317 out.width = self.meta.width;
318 out.height = self.meta.height;
319 }
320}
321
322/// Opens `path` for hardware decode, positioned so the first
323/// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean
324/// the start of the stream). Returns null on any failure at all: no libva
325/// runtime, no render node, unsupported profile, unreadable file.
326///
327/// # Safety
328/// `path` must be a valid NUL-terminated C string.
329#[unsafe(no_mangle)]
330pub unsafe extern "C" fn vh_open_at(path: *const c_char, target_sample: u32) -> *mut c_void {
331 catch_unwind(AssertUnwindSafe(|| {
332 if path.is_null() {
333 return std::ptr::null_mut();
334 }
335 // SAFETY: caller-guaranteed NUL-terminated string, read before return.
336 let path = unsafe { CStr::from_ptr(path) };
337 let Ok(path) = path.to_str() else {
338 return std::ptr::null_mut();
339 };
340 match Session::open_at(Path::new(path), target_sample) {
341 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
342 None => std::ptr::null_mut(),
343 }
344 }))
345 .unwrap_or(std::ptr::null_mut())
346}
347
348/// Fills `out` with stream metadata. 0 on success, negative on failure.
349///
350/// # Safety
351/// `session` must come from [`vh_open_at`] and `out` must be writable.
352#[unsafe(no_mangle)]
353pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 {
354 catch_unwind(AssertUnwindSafe(|| {
355 if session.is_null() || out.is_null() {
356 return -1;
357 }
358 // SAFETY: caller-guaranteed live session and writable destination.
359 unsafe {
360 let session = &*(session as *const Session);
361 (*out).width = session.meta.width;
362 (*out).height = session.meta.height;
363 (*out).frame_rate = session.meta.frame_rate;
364 (*out).frame_count = session.meta.frame_count;
365 }
366 0
367 }))
368 .unwrap_or(-1)
369}
370
371/// 1 when `out` holds the next picture in display order, 0 at clean end of
372/// stream, negative on error. Plane pointers stay valid until the next call.
373///
374/// # Safety
375/// `session` must come from [`vh_open_at`] and `out` must be writable.
376#[unsafe(no_mangle)]
377pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 {
378 catch_unwind(AssertUnwindSafe(|| {
379 if session.is_null() || out.is_null() {
380 return -1;
381 }
382 // SAFETY: caller-guaranteed live session and writable destination.
383 let session = unsafe { &mut *(session as *mut Session) };
384 match session.pump() {
385 Ok(true) => {
386 // SAFETY: `out` is non-null and writable per the contract.
387 session.fill(unsafe { &mut *out });
388 1
389 }
390 Ok(false) => 0,
391 Err(e) => {
392 eprintln!("engine_hw: {e}");
393 -2
394 }
395 }
396 }))
397 .unwrap_or(-1)
398}
399
400/// Releases a session. Safe to call with null.
401///
402/// # Safety
403/// `session` must come from [`vh_open_at`] and must not be used afterwards.
404#[unsafe(no_mangle)]
405pub unsafe extern "C" fn vh_close(session: *mut c_void) {
406 let _ = catch_unwind(AssertUnwindSafe(|| {
407 if !session.is_null() {
408 // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`.
409 drop(unsafe { Box::from_raw(session as *mut Session) });
410 }
411 }));
412}
413
414fn align16(v: u32) -> u32 {
415 v.div_ceil(16) * 16
416}
417
418/// Fills in slice NAL header bytes the driver left at zero.
419///
420/// Mesa's radeonsi encoder writes `forbidden_zero_bit`, `nal_ref_idc` and
421/// `nal_unit_type` from state it only ever populates out of a *packed* slice
422/// header, and cros-codecs supplies none (`h264/vaapi.rs` says as much in its
423/// "use packed headers" TODO). Every other bit of the slice is correct, so the
424/// whole damage is one byte per slice: measured on radeonsi, patching it turns
425/// a stream neither ffmpeg nor `rusty_h264` will touch into one both decode.
426///
427/// An all-zero byte after a start code is never valid H.264, so drivers that do
428/// write the header (Intel's, which is what cros-codecs was built against) fall
429/// straight through this.
430///
431/// ponytail: the real fix is a `VAEncPackedHeaderH264_Slice` buffer in the
432/// vendored cros-codecs backend, which means synthesizing the entire slice
433/// header there rather than correcting two fields here.
434fn fix_slice_nal_headers(au: &mut [u8]) {
435 // cros-codecs prepends SPS+PPS to the access unit at every IDR and only
436 // there, so an SPS seen earlier in this unit is what makes the slice one.
437 let mut idr = false;
438 let mut i = 0;
439 while i + 3 < au.len() {
440 if au[i..i + 3] != [0, 0, 1] {
441 i += 1;
442 continue;
443 }
444 let nal = &mut au[i + 3];
445 if *nal == 0 {
446 // nal_ref_idc 3 + IDR, or 2 + non-IDR: every picture this encoder
447 // emits is a short-term reference (no B-frames, no disposables).
448 *nal = if idr { 0x65 } else { 0x41 };
449 } else if *nal & 0x1f == 7 {
450 idr = true;
451 }
452 i += 3;
453 }
454}
455
456/// One hardware H.264 encode session.
457///
458/// Input goes through a single reusable NV12 buffer object: the caller's I420
459/// planes are interleaved into it and the encoder imports it as a VA surface.
460/// Reuse is safe because the encoder runs in blocking mode and every entry
461/// point polls it before returning, so the GPU is finished with the buffer
462/// before the next picture is written into it.
463struct EncSession {
464 encoder: Encoder,
465 /// Owns the DRM node the buffer object below was allocated from.
466 _gbm: gbm::Device<std::fs::File>,
467 frame: GenericDmaVideoFrame,
468 layout: FrameLayout,
469 /// Macroblock-aligned surface size; `width`/`height` are what is encoded.
470 coded: Resolution,
471 width: usize,
472 height: usize,
473 timestamp: u64,
474 drained: bool,
475 /// Coded access units the encoder has finished but the caller has not
476 /// collected yet, in encode order (which is display order: no B-frames).
477 ready: VecDeque<Vec<u8>>,
478 /// The access unit currently handed out, kept alive until the next call.
479 out: Vec<u8>,
480}
481
482impl EncSession {
483 fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
484 // NV12 chroma is half resolution, so odd dimensions have no packing;
485 // and radeonsi refuses encode contexts below 64x64 (measured).
486 if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 {
487 return None;
488 }
489 if fps_num == 0 || fps_den == 0 || bitrate == 0 {
490 return None;
491 }
492 let (display, gbm) = open_devices()?;
493 let coded = Resolution {
494 width: align16(width),
495 height: align16(height),
496 };
497 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;
498 let low_power = display
499 .query_config_entrypoints(VAProfile::VAProfileH264Main)
500 .ok()?
501 .contains(&VAEntrypoint::VAEntrypointEncSliceLP);
502 let config = H264Config {
503 resolution: Resolution { width, height },
504 profile: H264Profile::Main,
505 level: Level::L4,
506 // No B-frames: coded order stays display order, which is what the
507 // muxer's duration-only timing assumes.
508 pred_structure: PredictionStructure::LowDelay {
509 limit: (framerate * 2) as u16,
510 },
511 initial_tunings: Tunings {
512 rate_control: RateControl::ConstantBitrate(bitrate),
513 framerate,
514 ..Default::default()
515 },
516 };
517 let encoder = Encoder::new_vaapi(
518 display,
519 config,
520 Fourcc::from(b"NV12"),
521 coded,
522 low_power,
523 BlockingMode::Blocking,
524 )
525 .ok()?;
526 // Allocated at the aligned size, so the buffer's pitch is never smaller
527 // than a padded row.
528 let frame = alloc_nv12(&gbm, coded).ok()?;
529 let layout = nv12_layout(coded, frame.get_plane_pitch()[0]);
530 Some(Self {
531 encoder,
532 _gbm: gbm,
533 frame,
534 layout,
535 coded,
536 width: width as usize,
537 height: height as usize,
538 timestamp: 0,
539 drained: false,
540 ready: VecDeque::new(),
541 out: Vec::new(),
542 })
543 }
544
545 /// Interleaves one packed I420 picture into the NV12 input buffer.
546 ///
547 /// # Safety
548 /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their
549 /// declared stride.
550 unsafe fn upload(&mut self, src: &VhFrame) -> Result<(), String> {
551 let (w, h) = (self.width, self.height);
552 let (cw, ch) = (w / 2, h / 2);
553 let (aw, ah) = (self.coded.width as usize, self.coded.height as usize);
554 let pitch = self.frame.get_plane_pitch();
555 let mapping = self.frame.map_mut()?;
556 let planes = mapping.get();
557 {
558 let mut dst = planes[0].borrow_mut();
559 for row in 0..ah {
560 // SAFETY: caller contract; rows past the picture repeat the last.
561 let s = unsafe {
562 std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w)
563 };
564 let dst = &mut dst[row * pitch[0]..row * pitch[0] + aw];
565 dst[..w].copy_from_slice(s);
566 // Macroblock padding: replicate the edge rather than leave the
567 // buffer's garbage there, which would cost bitrate for nothing.
568 dst[w..].fill(s[w - 1]);
569 }
570 }
571 let mut dst = planes[1].borrow_mut();
572 for row in 0..ah / 2 {
573 let src_row = row.min(ch - 1);
574 // SAFETY: as above, for the two chroma planes.
575 let (u, v) = unsafe {
576 (
577 std::slice::from_raw_parts(src.u.add(src_row * src.u_stride), cw),
578 std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw),
579 )
580 };
581 let dst = &mut dst[row * pitch[1]..row * pitch[1] + aw];
582 for x in 0..cw {
583 dst[2 * x] = u[x];
584 dst[2 * x + 1] = v[x];
585 }
586 for x in w..aw {
587 dst[x] = dst[x - 2];
588 }
589 }
590 Ok(())
591 }
592
593 /// # Safety
594 /// As [`EncSession::upload`].
595 unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> {
596 // SAFETY: caller contract, forwarded.
597 unsafe { self.upload(src)? };
598 let meta = FrameMetadata {
599 timestamp: self.timestamp,
600 layout: self.layout.clone(),
601 force_keyframe,
602 };
603 self.timestamp += 1;
604 self.encoder
605 .encode(meta, self.frame.clone())
606 .map_err(|e| e.to_string())?;
607 self.collect()
608 }
609
610 /// Moves every access unit the encoder has finished into `ready`.
611 fn collect(&mut self) -> Result<(), String> {
612 while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? {
613 let mut au = coded.bitstream;
614 fix_slice_nal_headers(&mut au);
615 self.ready.push_back(au);
616 }
617 Ok(())
618 }
619
620 /// Hands the oldest finished access unit to the caller, or reports that
621 /// there is none.
622 fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 {
623 let Some(au) = self.ready.pop_front() else {
624 return 0;
625 };
626 self.out = au;
627 // SAFETY: caller-guaranteed writable destinations.
628 unsafe {
629 *out = self.out.as_ptr();
630 *out_len = self.out.len();
631 }
632 1
633 }
634}
635
636/// Opens a hardware H.264 encoder for `width`x`height` at `fps_num / fps_den`,
637/// constant bitrate `bitrate` bits per second. Returns null on any failure at
638/// all -- no VA-API runtime, no render node, no encode entrypoint, dimensions
639/// the driver will not take -- and the caller falls back to software.
640#[unsafe(no_mangle)]
641pub extern "C" fn vh_enc_open(
642 width: u32,
643 height: u32,
644 fps_num: u32,
645 fps_den: u32,
646 bitrate: u64,
647) -> *mut c_void {
648 catch_unwind(AssertUnwindSafe(|| {
649 match EncSession::open(width, height, fps_num, fps_den, bitrate) {
650 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
651 None => std::ptr::null_mut(),
652 }
653 }))
654 .unwrap_or(std::ptr::null_mut())
655}
656
657/// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one
658/// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on
659/// error. The bytes stay valid until the next call on this session.
660///
661/// # Safety
662/// `session` must come from [`vh_enc_open`], `frame`'s planes must cover the
663/// picture at their declared strides, and `out`/`out_len` must be writable.
664#[unsafe(no_mangle)]
665pub unsafe extern "C" fn vh_enc_frame(
666 session: *mut c_void,
667 frame: *const VhFrame,
668 force_key: i32,
669 out: *mut *const u8,
670 out_len: *mut usize,
671) -> i32 {
672 catch_unwind(AssertUnwindSafe(|| {
673 if session.is_null() || frame.is_null() || out.is_null() || out_len.is_null() {
674 return -1;
675 }
676 // SAFETY: caller-guaranteed live session and readable frame.
677 let (session, frame) = unsafe { (&mut *(session as *mut EncSession), &*frame) };
678 if frame.y.is_null() || frame.u.is_null() || frame.v.is_null() {
679 return -1;
680 }
681 if frame.width as usize != session.width
682 || frame.height as usize != session.height
683 || frame.y_stride < session.width
684 || frame.u_stride < session.width / 2
685 || frame.v_stride < session.width / 2
686 {
687 return -1;
688 }
689 // SAFETY: caller contract on the plane pointers, sizes checked above.
690 match unsafe { session.encode(frame, force_key != 0) } {
691 Ok(()) => session.take(out, out_len),
692 Err(e) => {
693 eprintln!("engine_hw: {e}");
694 -2
695 }
696 }
697 }))
698 .unwrap_or(-1)
699}
700
701/// Flushes the encoder: 1 while `out`/`out_len` describe another access unit,
702/// 0 once every picture fed has been handed back, negative on error. Same
703/// lifetime rule as [`vh_enc_frame`].
704///
705/// # Safety
706/// `session` must come from [`vh_enc_open`]; `out`/`out_len` must be writable.
707#[unsafe(no_mangle)]
708pub unsafe extern "C" fn vh_enc_drain(
709 session: *mut c_void,
710 out: *mut *const u8,
711 out_len: *mut usize,
712) -> i32 {
713 catch_unwind(AssertUnwindSafe(|| {
714 if session.is_null() || out.is_null() || out_len.is_null() {
715 return -1;
716 }
717 // SAFETY: caller-guaranteed live session.
718 let session = unsafe { &mut *(session as *mut EncSession) };
719 if !session.drained {
720 if let Err(e) = session.encoder.drain().map_err(|e| e.to_string()) {
721 eprintln!("engine_hw: {e}");
722 return -2;
723 }
724 session.drained = true;
725 }
726 match session.collect() {
727 Ok(()) => session.take(out, out_len),
728 Err(e) => {
729 eprintln!("engine_hw: {e}");
730 -2
731 }
732 }
733 }))
734 .unwrap_or(-1)
735}
736
737/// Releases an encode session. Safe to call with null.
738///
739/// # Safety
740/// `session` must come from [`vh_enc_open`] and must not be used afterwards.
741#[unsafe(no_mangle)]
742pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) {
743 let _ = catch_unwind(AssertUnwindSafe(|| {
744 if !session.is_null() {
745 // SAFETY: pointer came from `Box::into_raw` in `vh_enc_open`.
746 drop(unsafe { Box::from_raw(session as *mut EncSession) });
747 }
748 }));
749}