forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

lib.rs753 lines, 28.0 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 // The ABI still speaks 1-based sample ids, the demuxer speaks 0-based
183 // display frames -- and answers with a signed one, since a sync sample
184 // inside what the edit list trims sits before frame 0.
185 let target_frame = target_sample.saturating_sub(1);
186 let first = session.demuxer.seek_to_sync_at_or_before(target_frame);
187 session.skip = (i64::from(target_frame) - first).max(0) as u32;
188 Some(session)
189 }
190
191 /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF.
192 fn pump(&mut self) -> Result<bool, String> {
193 let mut stalls = 0u32;
194 loop {
195 // Stop draining as soon as we have a picture: every handle we hold
196 // keeps a pool buffer out of circulation.
197 while self.ready.is_empty() {
198 match self.decoder.next_event() {
199 Some(DecoderEvent::FrameReady(handle)) => self.ready.push_back(handle),
200 Some(DecoderEvent::FormatChanged) => {
201 let info = self
202 .decoder
203 .stream_info()
204 .ok_or("format changed without stream info")?
205 .clone();
206 self.pool.resize(&info);
207 }
208 None => break,
209 }
210 }
211 if let Some(handle) = self.ready.pop_front() {
212 // Seek discards: dropping the handle skips the `vaGetImage`
213 // read-back (~1.2 ms/picture) and frees its pool buffer.
214 if self.skip > 0 {
215 self.skip -= 1;
216 continue;
217 }
218 self.emit(handle);
219 return Ok(true);
220 }
221 if self.flushed {
222 return Ok(false);
223 }
224
225 if self.pending.is_empty() {
226 match self.demuxer.next_access_unit() {
227 Ok(Some(au)) => self.pending = au,
228 Ok(None) => {
229 self.decoder.flush().map_err(|e| e.to_string())?;
230 self.flushed = true;
231 continue;
232 }
233 Err(e) => return Err(e.to_string()),
234 }
235 }
236
237 let Self {
238 decoder,
239 pool,
240 pending,
241 timestamp,
242 ..
243 } = self;
244 match decoder.decode(*timestamp, pending, &mut || pool.alloc()) {
245 Ok(0) => return Err("decoder consumed no input".into()),
246 Ok(n) => {
247 pending.drain(..n.min(pending.len()));
248 if pending.is_empty() {
249 *timestamp += 1;
250 }
251 stalls = 0;
252 }
253 // Both mean "handle pending events, then resubmit the same data".
254 Err(DecodeError::CheckEvents) | Err(DecodeError::NotEnoughOutputBuffers(_)) => {
255 stalls += 1;
256 if stalls > STALL_LIMIT {
257 return Err("decoder stalled waiting for output buffers".into());
258 }
259 }
260 Err(e) => return Err(e.to_string()),
261 }
262 }
263 }
264
265 /// Copies a decoded NV12 surface into `self.out` as packed I420.
266 fn emit(&mut self, handle: Handle) {
267 let res = handle.display_resolution();
268 let (w, h) = (res.width as usize, res.height as usize);
269 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
270 if self.luma != w * h || self.chroma != cw * ch {
271 self.luma = w * h;
272 self.chroma = cw * ch;
273 self.out = vec![0u8; self.luma + 2 * self.chroma];
274 }
275 self.meta.width = res.width;
276 self.meta.height = res.height;
277
278 // Read back with vaGetImage rather than mapping our own DMA-BUF: on a
279 // discrete GPU that buffer lives in VRAM and a CPU read of it runs at
280 // ~44 MB/s over the PCIe BAR (measured), which costs 350 ms/frame. The
281 // driver copies into host-visible memory for us instead.
282 // Cheap no-op in blocking mode, but pixels must never be read early.
283 let _ = DecodedHandle::sync(&handle);
284 let borrowed = handle.borrow();
285 let size = (w as u32, h as u32);
286 let image = Image::create_from(borrowed.surface(), self.nv12_format, size, size)
287 .expect("vaGetImage failed");
288 let va = *image.image();
289 let data: &[u8] = image.as_ref();
290
291 let (dst_y, rest) = self.out.split_at_mut(self.luma);
292 let (dst_u, dst_v) = rest.split_at_mut(self.chroma);
293 nv12_to_i420(
294 &data[va.offsets[Y_PLANE] as usize..],
295 va.pitches[Y_PLANE] as usize,
296 dst_y,
297 w,
298 &data[va.offsets[UV_PLANE] as usize..],
299 va.pitches[UV_PLANE] as usize,
300 dst_u,
301 cw,
302 dst_v,
303 cw,
304 w,
305 h,
306 );
307 }
308
309 fn fill(&self, out: &mut VhFrame) {
310 let w = self.meta.width as usize;
311 let cw = w.div_ceil(2);
312 out.y = self.out.as_ptr();
313 // SAFETY: `out` was sized to luma + 2 * chroma just above in `emit`.
314 unsafe {
315 out.u = self.out.as_ptr().add(self.luma);
316 out.v = self.out.as_ptr().add(self.luma + self.chroma);
317 }
318 out.y_stride = w;
319 out.u_stride = cw;
320 out.v_stride = cw;
321 out.width = self.meta.width;
322 out.height = self.meta.height;
323 }
324}
325
326/// Opens `path` for hardware decode, positioned so the first
327/// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean
328/// the start of the stream). Returns null on any failure at all: no libva
329/// runtime, no render node, unsupported profile, unreadable file.
330///
331/// # Safety
332/// `path` must be a valid NUL-terminated C string.
333#[unsafe(no_mangle)]
334pub unsafe extern "C" fn vh_open_at(path: *const c_char, target_sample: u32) -> *mut c_void {
335 catch_unwind(AssertUnwindSafe(|| {
336 if path.is_null() {
337 return std::ptr::null_mut();
338 }
339 // SAFETY: caller-guaranteed NUL-terminated string, read before return.
340 let path = unsafe { CStr::from_ptr(path) };
341 let Ok(path) = path.to_str() else {
342 return std::ptr::null_mut();
343 };
344 match Session::open_at(Path::new(path), target_sample) {
345 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
346 None => std::ptr::null_mut(),
347 }
348 }))
349 .unwrap_or(std::ptr::null_mut())
350}
351
352/// Fills `out` with stream metadata. 0 on success, negative on failure.
353///
354/// # Safety
355/// `session` must come from [`vh_open_at`] and `out` must be writable.
356#[unsafe(no_mangle)]
357pub unsafe extern "C" fn vh_meta(session: *mut c_void, out: *mut VhMeta) -> i32 {
358 catch_unwind(AssertUnwindSafe(|| {
359 if session.is_null() || out.is_null() {
360 return -1;
361 }
362 // SAFETY: caller-guaranteed live session and writable destination.
363 unsafe {
364 let session = &*(session as *const Session);
365 (*out).width = session.meta.width;
366 (*out).height = session.meta.height;
367 (*out).frame_rate = session.meta.frame_rate;
368 (*out).frame_count = session.meta.frame_count;
369 }
370 0
371 }))
372 .unwrap_or(-1)
373}
374
375/// 1 when `out` holds the next picture in display order, 0 at clean end of
376/// stream, negative on error. Plane pointers stay valid until the next call.
377///
378/// # Safety
379/// `session` must come from [`vh_open_at`] and `out` must be writable.
380#[unsafe(no_mangle)]
381pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) -> i32 {
382 catch_unwind(AssertUnwindSafe(|| {
383 if session.is_null() || out.is_null() {
384 return -1;
385 }
386 // SAFETY: caller-guaranteed live session and writable destination.
387 let session = unsafe { &mut *(session as *mut Session) };
388 match session.pump() {
389 Ok(true) => {
390 // SAFETY: `out` is non-null and writable per the contract.
391 session.fill(unsafe { &mut *out });
392 1
393 }
394 Ok(false) => 0,
395 Err(e) => {
396 eprintln!("engine_hw: {e}");
397 -2
398 }
399 }
400 }))
401 .unwrap_or(-1)
402}
403
404/// Releases a session. Safe to call with null.
405///
406/// # Safety
407/// `session` must come from [`vh_open_at`] and must not be used afterwards.
408#[unsafe(no_mangle)]
409pub unsafe extern "C" fn vh_close(session: *mut c_void) {
410 let _ = catch_unwind(AssertUnwindSafe(|| {
411 if !session.is_null() {
412 // SAFETY: pointer came from `Box::into_raw` in `vh_open_at`.
413 drop(unsafe { Box::from_raw(session as *mut Session) });
414 }
415 }));
416}
417
418fn align16(v: u32) -> u32 {
419 v.div_ceil(16) * 16
420}
421
422/// Fills in slice NAL header bytes the driver left at zero.
423///
424/// Mesa's radeonsi encoder writes `forbidden_zero_bit`, `nal_ref_idc` and
425/// `nal_unit_type` from state it only ever populates out of a *packed* slice
426/// header, and cros-codecs supplies none (`h264/vaapi.rs` says as much in its
427/// "use packed headers" TODO). Every other bit of the slice is correct, so the
428/// whole damage is one byte per slice: measured on radeonsi, patching it turns
429/// a stream neither ffmpeg nor `rusty_h264` will touch into one both decode.
430///
431/// An all-zero byte after a start code is never valid H.264, so drivers that do
432/// write the header (Intel's, which is what cros-codecs was built against) fall
433/// straight through this.
434///
435/// ponytail: the real fix is a `VAEncPackedHeaderH264_Slice` buffer in the
436/// vendored cros-codecs backend, which means synthesizing the entire slice
437/// header there rather than correcting two fields here.
438fn fix_slice_nal_headers(au: &mut [u8]) {
439 // cros-codecs prepends SPS+PPS to the access unit at every IDR and only
440 // there, so an SPS seen earlier in this unit is what makes the slice one.
441 let mut idr = false;
442 let mut i = 0;
443 while i + 3 < au.len() {
444 if au[i..i + 3] != [0, 0, 1] {
445 i += 1;
446 continue;
447 }
448 let nal = &mut au[i + 3];
449 if *nal == 0 {
450 // nal_ref_idc 3 + IDR, or 2 + non-IDR: every picture this encoder
451 // emits is a short-term reference (no B-frames, no disposables).
452 *nal = if idr { 0x65 } else { 0x41 };
453 } else if *nal & 0x1f == 7 {
454 idr = true;
455 }
456 i += 3;
457 }
458}
459
460/// One hardware H.264 encode session.
461///
462/// Input goes through a single reusable NV12 buffer object: the caller's I420
463/// planes are interleaved into it and the encoder imports it as a VA surface.
464/// Reuse is safe because the encoder runs in blocking mode and every entry
465/// point polls it before returning, so the GPU is finished with the buffer
466/// before the next picture is written into it.
467struct EncSession {
468 encoder: Encoder,
469 /// Owns the DRM node the buffer object below was allocated from.
470 _gbm: gbm::Device<std::fs::File>,
471 frame: GenericDmaVideoFrame,
472 layout: FrameLayout,
473 /// Macroblock-aligned surface size; `width`/`height` are what is encoded.
474 coded: Resolution,
475 width: usize,
476 height: usize,
477 timestamp: u64,
478 drained: bool,
479 /// Coded access units the encoder has finished but the caller has not
480 /// collected yet, in encode order (which is display order: no B-frames).
481 ready: VecDeque<Vec<u8>>,
482 /// The access unit currently handed out, kept alive until the next call.
483 out: Vec<u8>,
484}
485
486impl EncSession {
487 fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option<Self> {
488 // NV12 chroma is half resolution, so odd dimensions have no packing;
489 // and radeonsi refuses encode contexts below 64x64 (measured).
490 if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 {
491 return None;
492 }
493 if fps_num == 0 || fps_den == 0 || bitrate == 0 {
494 return None;
495 }
496 let (display, gbm) = open_devices()?;
497 let coded = Resolution {
498 width: align16(width),
499 height: align16(height),
500 };
501 let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32;
502 let low_power = display
503 .query_config_entrypoints(VAProfile::VAProfileH264Main)
504 .ok()?
505 .contains(&VAEntrypoint::VAEntrypointEncSliceLP);
506 let config = H264Config {
507 resolution: Resolution { width, height },
508 profile: H264Profile::Main,
509 level: Level::L4,
510 // No B-frames: coded order stays display order, which is what the
511 // muxer's duration-only timing assumes.
512 pred_structure: PredictionStructure::LowDelay {
513 limit: (framerate * 2) as u16,
514 },
515 initial_tunings: Tunings {
516 rate_control: RateControl::ConstantBitrate(bitrate),
517 framerate,
518 ..Default::default()
519 },
520 };
521 let encoder = Encoder::new_vaapi(
522 display,
523 config,
524 Fourcc::from(b"NV12"),
525 coded,
526 low_power,
527 BlockingMode::Blocking,
528 )
529 .ok()?;
530 // Allocated at the aligned size, so the buffer's pitch is never smaller
531 // than a padded row.
532 let frame = alloc_nv12(&gbm, coded).ok()?;
533 let layout = nv12_layout(coded, frame.get_plane_pitch()[0]);
534 Some(Self {
535 encoder,
536 _gbm: gbm,
537 frame,
538 layout,
539 coded,
540 width: width as usize,
541 height: height as usize,
542 timestamp: 0,
543 drained: false,
544 ready: VecDeque::new(),
545 out: Vec::new(),
546 })
547 }
548
549 /// Interleaves one packed I420 picture into the NV12 input buffer.
550 ///
551 /// # Safety
552 /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their
553 /// declared stride.
554 unsafe fn upload(&mut self, src: &VhFrame) -> Result<(), String> {
555 let (w, h) = (self.width, self.height);
556 let (cw, ch) = (w / 2, h / 2);
557 let (aw, ah) = (self.coded.width as usize, self.coded.height as usize);
558 let pitch = self.frame.get_plane_pitch();
559 let mapping = self.frame.map_mut()?;
560 let planes = mapping.get();
561 {
562 let mut dst = planes[0].borrow_mut();
563 for row in 0..ah {
564 // SAFETY: caller contract; rows past the picture repeat the last.
565 let s = unsafe {
566 std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w)
567 };
568 let dst = &mut dst[row * pitch[0]..row * pitch[0] + aw];
569 dst[..w].copy_from_slice(s);
570 // Macroblock padding: replicate the edge rather than leave the
571 // buffer's garbage there, which would cost bitrate for nothing.
572 dst[w..].fill(s[w - 1]);
573 }
574 }
575 let mut dst = planes[1].borrow_mut();
576 for row in 0..ah / 2 {
577 let src_row = row.min(ch - 1);
578 // SAFETY: as above, for the two chroma planes.
579 let (u, v) = unsafe {
580 (
581 std::slice::from_raw_parts(src.u.add(src_row * src.u_stride), cw),
582 std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw),
583 )
584 };
585 let dst = &mut dst[row * pitch[1]..row * pitch[1] + aw];
586 for x in 0..cw {
587 dst[2 * x] = u[x];
588 dst[2 * x + 1] = v[x];
589 }
590 for x in w..aw {
591 dst[x] = dst[x - 2];
592 }
593 }
594 Ok(())
595 }
596
597 /// # Safety
598 /// As [`EncSession::upload`].
599 unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> {
600 // SAFETY: caller contract, forwarded.
601 unsafe { self.upload(src)? };
602 let meta = FrameMetadata {
603 timestamp: self.timestamp,
604 layout: self.layout.clone(),
605 force_keyframe,
606 };
607 self.timestamp += 1;
608 self.encoder
609 .encode(meta, self.frame.clone())
610 .map_err(|e| e.to_string())?;
611 self.collect()
612 }
613
614 /// Moves every access unit the encoder has finished into `ready`.
615 fn collect(&mut self) -> Result<(), String> {
616 while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? {
617 let mut au = coded.bitstream;
618 fix_slice_nal_headers(&mut au);
619 self.ready.push_back(au);
620 }
621 Ok(())
622 }
623
624 /// Hands the oldest finished access unit to the caller, or reports that
625 /// there is none.
626 fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 {
627 let Some(au) = self.ready.pop_front() else {
628 return 0;
629 };
630 self.out = au;
631 // SAFETY: caller-guaranteed writable destinations.
632 unsafe {
633 *out = self.out.as_ptr();
634 *out_len = self.out.len();
635 }
636 1
637 }
638}
639
640/// Opens a hardware H.264 encoder for `width`x`height` at `fps_num / fps_den`,
641/// constant bitrate `bitrate` bits per second. Returns null on any failure at
642/// all -- no VA-API runtime, no render node, no encode entrypoint, dimensions
643/// the driver will not take -- and the caller falls back to software.
644#[unsafe(no_mangle)]
645pub extern "C" fn vh_enc_open(
646 width: u32,
647 height: u32,
648 fps_num: u32,
649 fps_den: u32,
650 bitrate: u64,
651) -> *mut c_void {
652 catch_unwind(AssertUnwindSafe(|| {
653 match EncSession::open(width, height, fps_num, fps_den, bitrate) {
654 Some(session) => Box::into_raw(Box::new(session)) as *mut c_void,
655 None => std::ptr::null_mut(),
656 }
657 }))
658 .unwrap_or(std::ptr::null_mut())
659}
660
661/// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one
662/// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on
663/// error. The bytes stay valid until the next call on this session.
664///
665/// # Safety
666/// `session` must come from [`vh_enc_open`], `frame`'s planes must cover the
667/// picture at their declared strides, and `out`/`out_len` must be writable.
668#[unsafe(no_mangle)]
669pub unsafe extern "C" fn vh_enc_frame(
670 session: *mut c_void,
671 frame: *const VhFrame,
672 force_key: i32,
673 out: *mut *const u8,
674 out_len: *mut usize,
675) -> i32 {
676 catch_unwind(AssertUnwindSafe(|| {
677 if session.is_null() || frame.is_null() || out.is_null() || out_len.is_null() {
678 return -1;
679 }
680 // SAFETY: caller-guaranteed live session and readable frame.
681 let (session, frame) = unsafe { (&mut *(session as *mut EncSession), &*frame) };
682 if frame.y.is_null() || frame.u.is_null() || frame.v.is_null() {
683 return -1;
684 }
685 if frame.width as usize != session.width
686 || frame.height as usize != session.height
687 || frame.y_stride < session.width
688 || frame.u_stride < session.width / 2
689 || frame.v_stride < session.width / 2
690 {
691 return -1;
692 }
693 // SAFETY: caller contract on the plane pointers, sizes checked above.
694 match unsafe { session.encode(frame, force_key != 0) } {
695 Ok(()) => session.take(out, out_len),
696 Err(e) => {
697 eprintln!("engine_hw: {e}");
698 -2
699 }
700 }
701 }))
702 .unwrap_or(-1)
703}
704
705/// Flushes the encoder: 1 while `out`/`out_len` describe another access unit,
706/// 0 once every picture fed has been handed back, negative on error. Same
707/// lifetime rule as [`vh_enc_frame`].
708///
709/// # Safety
710/// `session` must come from [`vh_enc_open`]; `out`/`out_len` must be writable.
711#[unsafe(no_mangle)]
712pub unsafe extern "C" fn vh_enc_drain(
713 session: *mut c_void,
714 out: *mut *const u8,
715 out_len: *mut usize,
716) -> i32 {
717 catch_unwind(AssertUnwindSafe(|| {
718 if session.is_null() || out.is_null() || out_len.is_null() {
719 return -1;
720 }
721 // SAFETY: caller-guaranteed live session.
722 let session = unsafe { &mut *(session as *mut EncSession) };
723 if !session.drained {
724 if let Err(e) = session.encoder.drain().map_err(|e| e.to_string()) {
725 eprintln!("engine_hw: {e}");
726 return -2;
727 }
728 session.drained = true;
729 }
730 match session.collect() {
731 Ok(()) => session.take(out, out_len),
732 Err(e) => {
733 eprintln!("engine_hw: {e}");
734 -2
735 }
736 }
737 }))
738 .unwrap_or(-1)
739}
740
741/// Releases an encode session. Safe to call with null.
742///
743/// # Safety
744/// `session` must come from [`vh_enc_open`] and must not be used afterwards.
745#[unsafe(no_mangle)]
746pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) {
747 let _ = catch_unwind(AssertUnwindSafe(|| {
748 if !session.is_null() {
749 // SAFETY: pointer came from `Box::into_raw` in `vh_enc_open`.
750 drop(unsafe { Box::from_raw(session as *mut EncSession) });
751 }
752 }));
753}