forge
Explore
Log in

Don't you dare go Hollow

Vh_enc_* — VA-API H.264 encode with Mesa slice-header fixup

Browse files at this commit

b75c83e85d34de817c4fc9c3622d964fb3f32127Ahmet Kaan GümüşParent: 5ce68fe
  • feat
    • vh_enc_* — VA-API H.264 encode with Mesa slice-header fixup
Show full message
✨ feat(engine-hw): vh_enc_* — VA-API H.264 encode with Mesa slice-header fixup

The plugin grows an encode half beside the decode one:
vh_enc_open/vh_enc_frame/vh_enc_drain/vh_enc_close, and engine::hw
gains HwEncoder behind a SEPARATE symbol table. That separation is the
point -- a libengine_hw.so predating this commit must keep decoding, so
the four new symbols must not join the decode Plugin struct where a
missing one would take decode down with them. Absent symbols just mean
HwEncoder::open returns None and the caller falls back to the
rusty_h264 software encoder.

Measured on radeonsi (Mesa 26.1.5): 3.98 ms/frame at
1280x720 CBR 4 Mbps including the I420->NV12 upload, against 25.6
ms/frame for rusty_h264 Fast at the same size -- 6.4x. Profile Main,
level 4, LowDelay so there are no B-frames and coded order is display
order; radeonsi exposes no VAEntrypointEncSliceLP for H.264 so
low_power stays off. One reusable DMA-BUF frame carries every picture
because BlockingMode::Blocking plus a poll() in each entry point syncs
the coded and recon promises before returning. Non-16-aligned sizes
allocate aligned surfaces, carry the true size in the SPS crop, and
replicate the edge pixel into the padding rather than shipping gbm
garbage there.

The one ugly part is fix_slice_nal_headers. cros-codecs supplies no
VAEncPackedHeaderH264_Slice, and Mesa fills forbidden_zero_bit /
nal_ref_idc / nal_unit_type only from a packed slice header, so every
slice NAL leaves the encoder with a 0x00 header byte and both ffmpeg
and rusty_h264 refuse the stream. Patching that single byte per slice
makes both decode it fully. An all-zero header byte is never valid
H.264, so the rewrite is a no-op on drivers that write it properly
(Intel iHD, which cros-codecs was built against). Marked ponytail; the
real fix is a packed slice header in vendor/cros-codecs.
crates/engine-hw/src/lib.rsmodified+378 -24
@@ -1,7 +1,8 @@
1-//! VA-API H.264 decode, shipped as a `dlopen`-able plugin so the main binary1+//! VA-API H.264 decode and encode, shipped as a `dlopen`-able plugin so the main
2-//! never gets a DT_NEEDED on libva/gbm/drm. Every entry point is `extern "C"`,2+//! binary never gets a DT_NEEDED on libva/gbm/drm. Every entry point is
3-//! catches unwinds and reports failure as a null pointer or a negative code:3+//! `extern "C"`, catches unwinds and reports failure as a null pointer or a
4-//! the caller's contract is "any failure means use the software decoder".4+//! negative code: the caller's contract is "any failure means use the software
5+//! codec".
5 //!6 //!
6 //! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with7 //! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with
7 //! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path8 //! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path
@@ -14,11 +15,21 @@ use std::path::{Path, PathBuf};
14 use std::rc::Rc;15 use std::rc::Rc;
15 16
16 use cros_codecs::backend::vaapi::decoder::VaapiBackend;17 use cros_codecs::backend::vaapi::decoder::VaapiBackend;
18+use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend;
19+use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile};
17 use cros_codecs::decoder::stateless::h264::H264;20 use cros_codecs::decoder::stateless::h264::H264;
18 use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};21 use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder};
19 use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};22 use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo};
23+use cros_codecs::encoder::h264::EncoderConfig as H264Config;
24+use cros_codecs::encoder::stateless::h264::StatelessEncoder;
25+use cros_codecs::encoder::{
26+ FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder,
27+};
20 use cros_codecs::image_processing::nv12_to_i420;28 use cros_codecs::image_processing::nv12_to_i420;
21-use cros_codecs::libva::{Display, Image, VA_FOURCC_NV12, VAImageFormat};29+use cros_codecs::libva::{
30+ Display, Image, Surface, VA_FOURCC_NV12, VAEntrypoint, VAImageFormat, VAProfile,
31+};
32+use cros_codecs::video_frame::VideoFrame;
22 use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};33 use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame};
23 use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame;34 use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame;
24 use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};35 use cros_codecs::video_frame::{UV_PLANE, Y_PLANE};
@@ -31,6 +42,10 @@ use engine::hw::{VhFrame, VhMeta};
31 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;42 type PooledFrame = PooledVideoFrame<GenericDmaVideoFrame>;
32 type Decoder = StatelessDecoder<H264, VaapiBackend<PooledFrame>>;43 type Decoder = StatelessDecoder<H264, VaapiBackend<PooledFrame>>;
33 type Handle = <Decoder as StatelessVideoDecoder>::Handle;44 type Handle = <Decoder as StatelessVideoDecoder>::Handle;
45+type Encoder = StatelessEncoder<
46+ GenericDmaVideoFrame,
47+ VaapiEncBackend<GenericDmaVideoFrame, Surface<GenericDmaVideoFrame>>,
48+>;
34 49
35 /// Ceiling on decode/drain iterations that make no progress. VA-API in blocking50 /// Ceiling on decode/drain iterations that make no progress. VA-API in blocking
36 /// mode should always either hand back an event or accept input; this only51 /// mode should always either hand back an event or accept input; this only
@@ -74,25 +89,27 @@ fn alloc_nv12(
74 .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?;89 .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?;
75 let pitch = bo.stride().map_err(|e| e.to_string())? as usize;90 let pitch = bo.stride().map_err(|e| e.to_string())? as usize;
76 let fd = bo.fd().map_err(|e| e.to_string())?;91 let fd = bo.fd().map_err(|e| e.to_string())?;
77- GenericDmaVideoFrame::new(92+ GenericDmaVideoFrame::new(vec![std::fs::File::from(fd)], nv12_layout(coded, pitch))
78- vec![std::fs::File::from(fd)],93+}
79- FrameLayout {94+
80- format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */),95+/// Two NV12 planes packed one after the other in a single buffer object.
81- size: coded,96+fn nv12_layout(coded: Resolution, pitch: usize) -> FrameLayout {
82- planes: vec![97+ FrameLayout {
83- PlaneLayout {98+ format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */),
84- buffer_index: 0,99+ size: coded,
85- offset: 0,100+ planes: vec![
86- stride: pitch,101+ PlaneLayout {
87- },102+ buffer_index: 0,
88- PlaneLayout {103+ offset: 0,
89- buffer_index: 0,104+ stride: pitch,
90- offset: pitch * coded.height as usize,105+ },
91- stride: pitch,106+ PlaneLayout {
92- },107+ buffer_index: 0,
93- ],108+ offset: pitch * coded.height as usize,
94- },109+ stride: pitch,
95- )110+ },
111+ ],
112+ }
96 }113 }
97 114
98 /// First render node that gives us both a VA display and a GBM device. Which115 /// First render node that gives us both a VA display and a GBM device. Which
@@ -393,3 +410,340 @@ pub unsafe extern "C" fn vh_close(session: *mut c_void) {
393 }410 }
394 }));411 }));
395 }412 }
413+
414+fn 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.
434+fn 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.
463+struct 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+
482+impl 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)]
641+pub 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)]
665+pub 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)]
708+pub 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)]
742+pub 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+}
crates/engine/src/hw.rsmodified+152 -12
@@ -1,12 +1,16 @@
1-//! Runtime-optional hardware decode plugin (`libengine_hw.so`).1+//! Runtime-optional hardware decode/encode plugin (`libengine_hw.so`).
2 //!2 //!
3 //! The plugin links libva/gbm/drm; this crate and the app binary must not, so3 //! 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 --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 --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 decoder.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`].
7 11
8 use std::ffi::{CString, c_char, c_void};12 use std::ffi::{CString, c_char, c_void};
9-use std::path::Path;13+use std::path::{Path, PathBuf};
10 use std::sync::OnceLock;14 use std::sync::OnceLock;
11 15
12 use libloading::Library;16 use libloading::Library;
@@ -66,18 +70,18 @@ fn plugin() -> Option<&'static Plugin> {
66 PLUGIN.get_or_init(load).as_ref()70 PLUGIN.get_or_init(load).as_ref()
67 }71 }
68 72
69-fn load() -> Option<Plugin> {73+/// Where the plugin may live: next to the executable first (cargo puts both in
70- // Next to the executable first (cargo puts both in target/<profile>), then74+/// target/<profile>), then whatever the dynamic linker's search path turns up.
71- // whatever the dynamic linker's search path turns up.75+fn candidates() -> impl Iterator<Item = PathBuf> {
72- let beside_exe = std::env::current_exe()76+ std::env::current_exe()
73 .ok()77 .ok()
74- .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)));78+ .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)))
75- let candidates = beside_exe
76- .as_deref()
77 .into_iter()79 .into_iter()
78- .chain(std::iter::once(Path::new(LIB_NAME)));80+ .chain(std::iter::once(PathBuf::from(LIB_NAME)))
81+}
79 82
80- for candidate in candidates {83+fn load() -> Option<Plugin> {
84+ for candidate in candidates() {
81 // SAFETY: loading a shared object runs its initialisers; we only ever85 // SAFETY: loading a shared object runs its initialisers; we only ever
82 // name our own plugin, and every symbol below is type-checked against86 // name our own plugin, and every symbol below is type-checked against
83 // the definitions this crate shares with it.87 // the definitions this crate shares with it.
@@ -187,3 +191,139 @@ impl Drop for HwSession {
187 // The plugin session is used from one thread at a time (the decode worker) and191 // The plugin session is used from one thread at a time (the decode worker) and
188 // never shared; VA-API state inside it is not `Sync`.192 // never shared; VA-API state inside it is not `Sync`.
189 unsafe impl Send for HwSession {}193 unsafe impl Send for HwSession {}
194+
195+struct 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+
205+fn enc_plugin() -> Option<&'static EncPlugin> {
206+ static PLUGIN: OnceLock<Option<EncPlugin>> = OnceLock::new();
207+ PLUGIN.get_or_init(load_enc).as_ref()
208+}
209+
210+fn 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.
237+pub struct HwEncoder {
238+ plugin: &'static EncPlugin,
239+ handle: *mut c_void,
240+}
241+
242+impl 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+
321+impl 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).
329+unsafe impl Send for HwEncoder {}
crates/engine/tests/hw_encode.rsadded+162 -0
@@ -0,0 +1,162 @@
1+//! Hardware encode checks. These need a built `libengine_hw.so` plus a working
2+//! VA-API driver with an H.264 encode entrypoint, so they are `#[ignore]`d by
3+//! default. Run them with:
4+//!
5+//! ```text
6+//! cargo build --workspace --release
7+//! LD_LIBRARY_PATH=target/release \
8+//! cargo test -p engine --release --test hw_encode -- --ignored --nocapture --test-threads=1
9+//! ```
10+//!
11+//! The round trip goes out through the plugin and back in through the *software*
12+//! decoder (`rusty_h264` directly, not `DecodeSession`), so a bug on one side
13+//! cannot cancel out a bug on the other.
14+
15+use std::time::{Duration, Instant};
16+
17+use engine::hw::{HwEncoder, HwSession};
18+
19+const FPS: u32 = 30;
20+const BITRATE: u64 = 4_000_000;
21+
22+/// A moving diagonal gradient: something that actually costs bits, so the
23+/// encoder cannot make the whole test pass by emitting skip frames.
24+fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
25+ let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
26+ let mut y = vec![0u8; width * height];
27+ for row in 0..height {
28+ for col in 0..width {
29+ y[row * width + col] = (row + col + index as usize * 5) as u8;
30+ }
31+ }
32+ let u = vec![64u8.wrapping_add(index as u8); cw * ch];
33+ let v = vec![192u8.wrapping_sub(index as u8); cw * ch];
34+ (y, u, v)
35+}
36+
37+/// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus
38+/// the number of access units the plugin handed back.
39+fn encode(width: u32, height: u32, count: u32) -> Option<(Vec<u8>, u32)> {
40+ let mut encoder = HwEncoder::open(width, height, FPS, 1, BITRATE)?;
41+ let mut stream = Vec::new();
42+ let mut units = 0;
43+ // Timed around the plugin call only: building the synthetic picture is not
44+ // part of what an export would pay.
45+ let mut spent = Duration::ZERO;
46+ for index in 0..count {
47+ let (y, u, v) = synthetic(index, width as usize, height as usize);
48+ let started = Instant::now();
49+ let coded = encoder
50+ .encode(&y, &u, &v, width, height, false)
51+ .expect("encode");
52+ if let Some(au) = coded {
53+ stream.extend_from_slice(au);
54+ units += 1;
55+ }
56+ spent += started.elapsed();
57+ }
58+ while let Some(au) = encoder.drain().expect("drain") {
59+ stream.extend_from_slice(au);
60+ units += 1;
61+ }
62+ let per_frame = spent.as_secs_f64() * 1000.0 / count as f64;
63+ println!("{width}x{height}: {count} frames, {units} AUs, {per_frame:.2} ms/frame");
64+ Some((stream, units))
65+}
66+
67+fn decode(stream: &[u8]) -> Vec<rusty_h264::YuvFrame> {
68+ rusty_h264::Decoder::new()
69+ .decode_stream(stream)
70+ .expect("software decode of the hardware-encoded stream")
71+}
72+
73+fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 {
74+ assert_eq!(a.len(), b.len());
75+ a.iter()
76+ .zip(b)
77+ .map(|(x, y)| x.abs_diff(*y) as f64)
78+ .sum::<f64>()
79+ / a.len() as f64
80+}
81+
82+#[test]
83+#[ignore]
84+fn round_trips_sixty_frames() {
85+ let (width, height) = (1280u32, 720u32);
86+ let (stream, units) =
87+ encode(width, height, 60).expect("no hardware encode plugin/driver available");
88+ assert_eq!(units, 60, "one access unit per fed picture");
89+
90+ let frames = decode(&stream);
91+ assert_eq!(frames.len(), 60, "decoded picture count");
92+ for (index, frame) in frames.iter().enumerate() {
93+ assert_eq!(
94+ (frame.width, frame.height),
95+ (width as usize, height as usize),
96+ "frame {index} dimensions"
97+ );
98+ }
99+
100+ // The pictures have to survive the I420 -> NV12 upload, not merely exist:
101+ // a dropped plane or a swapped U/V would sail past a count-only check.
102+ // Tolerances are generous because this is lossy CBR, but nowhere near the
103+ // ~64 a U/V swap costs on these chroma values.
104+ for index in [0usize, 30, 59] {
105+ let (y, u, v) = synthetic(index as u32, width as usize, height as usize);
106+ let frame = &frames[index];
107+ for (plane, (got, want)) in [(&frame.y, &y), (&frame.u, &u), (&frame.v, &v)]
108+ .iter()
109+ .enumerate()
110+ {
111+ let diff = mean_abs_diff(got, want);
112+ println!("frame {index} plane {plane}: mean abs diff {diff:.2}");
113+ assert!(
114+ diff < 6.0,
115+ "frame {index} plane {plane} drifted by {diff:.2}"
116+ );
117+ }
118+ }
119+}
120+
121+/// 322x242 is even (NV12 needs that) but neither dimension is a multiple of 16,
122+/// so the surface is padded and the encoded stream has to crop it back. This is
123+/// the 1080p case in miniature: 1080 pads to 1088.
124+#[test]
125+#[ignore]
126+fn round_trips_unaligned_dimensions() {
127+ let (width, height) = (322u32, 242u32);
128+ let Some((stream, units)) = encode(width, height, 10) else {
129+ println!("driver refused {width}x{height}, software encode would take over -- skipping");
130+ return;
131+ };
132+ assert_eq!(units, 10);
133+
134+ let frames = decode(&stream);
135+ assert_eq!(frames.len(), 10);
136+ assert_eq!(
137+ (frames[0].width, frames[0].height),
138+ (width as usize, height as usize),
139+ "padding must be cropped away again"
140+ );
141+}
142+
143+/// Decode and encode resolve through two independent symbol tables, so an
144+/// encoder that cannot load must not cost us the decoder (and vice versa).
145+///
146+/// This is the positive half only: the negative half -- a plugin built without
147+/// `vh_enc_*` -- needs a second build of the `.so` and belongs to the slice's
148+/// verifier, not here.
149+#[test]
150+#[ignore]
151+fn decode_and_encode_load_independently() {
152+ let asset =
153+ std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4");
154+ assert!(
155+ HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some(),
156+ "encode table"
157+ );
158+ assert!(HwSession::open(&asset).is_some(), "decode table");
159+ // Order reversed: neither table's `OnceLock` may have primed the other.
160+ assert!(HwSession::open(&asset).is_some());
161+ assert!(HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some());
162+}