diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 163b73e..c14e04e 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -1,7 +1,8 @@ -//! VA-API H.264 decode, shipped as a `dlopen`-able plugin so the main binary -//! never gets a DT_NEEDED on libva/gbm/drm. Every entry point is `extern "C"`, -//! catches unwinds and reports failure as a null pointer or a negative code: -//! the caller's contract is "any failure means use the software decoder". +//! VA-API H.264 decode and encode, shipped as a `dlopen`-able plugin so the main +//! binary never gets a DT_NEEDED on libva/gbm/drm. Every entry point is +//! `extern "C"`, catches unwinds and reports failure as a null pointer or a +//! negative code: the caller's contract is "any failure means use the software +//! codec". //! //! ponytail: that guarantee rests on `panic = "unwind"`. Building this crate with //! `panic = "abort"` would turn a driver bug into a killed app; the upgrade path @@ -14,11 +15,21 @@ use std::path::{Path, PathBuf}; use std::rc::Rc; use cros_codecs::backend::vaapi::decoder::VaapiBackend; +use cros_codecs::backend::vaapi::encoder::VaapiBackend as VaapiEncBackend; +use cros_codecs::codec::h264::parser::{Level, Profile as H264Profile}; use cros_codecs::decoder::stateless::h264::H264; use cros_codecs::decoder::stateless::{DecodeError, StatelessDecoder, StatelessVideoDecoder}; use cros_codecs::decoder::{BlockingMode, DecodedHandle, DecoderEvent, StreamInfo}; +use cros_codecs::encoder::h264::EncoderConfig as H264Config; +use cros_codecs::encoder::stateless::h264::StatelessEncoder; +use cros_codecs::encoder::{ + FrameMetadata, PredictionStructure, RateControl, Tunings, VideoEncoder, +}; use cros_codecs::image_processing::nv12_to_i420; -use cros_codecs::libva::{Display, Image, VA_FOURCC_NV12, VAImageFormat}; +use cros_codecs::libva::{ + Display, Image, Surface, VA_FOURCC_NV12, VAEntrypoint, VAImageFormat, VAProfile, +}; +use cros_codecs::video_frame::VideoFrame; use cros_codecs::video_frame::frame_pool::{FramePool, PooledVideoFrame}; use cros_codecs::video_frame::generic_dma_video_frame::GenericDmaVideoFrame; use cros_codecs::video_frame::{UV_PLANE, Y_PLANE}; @@ -31,6 +42,10 @@ use engine::hw::{VhFrame, VhMeta}; type PooledFrame = PooledVideoFrame; type Decoder = StatelessDecoder>; type Handle = ::Handle; +type Encoder = StatelessEncoder< + GenericDmaVideoFrame, + VaapiEncBackend>, +>; /// Ceiling on decode/drain iterations that make no progress. VA-API in blocking /// mode should always either hand back an event or accept input; this only @@ -74,25 +89,27 @@ fn alloc_nv12( .map_err(|e| format!("gbm R8 {}x{rows} allocation failed: {e}", coded.width))?; let pitch = bo.stride().map_err(|e| e.to_string())? as usize; let fd = bo.fd().map_err(|e| e.to_string())?; - GenericDmaVideoFrame::new( - vec![std::fs::File::from(fd)], - FrameLayout { - format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */), - size: coded, - planes: vec![ - PlaneLayout { - buffer_index: 0, - offset: 0, - stride: pitch, - }, - PlaneLayout { - buffer_index: 0, - offset: pitch * coded.height as usize, - stride: pitch, - }, - ], - }, - ) + GenericDmaVideoFrame::new(vec![std::fs::File::from(fd)], nv12_layout(coded, pitch)) +} + +/// Two NV12 planes packed one after the other in a single buffer object. +fn nv12_layout(coded: Resolution, pitch: usize) -> FrameLayout { + FrameLayout { + format: (Fourcc::from(b"NV12"), 0 /* DRM_FORMAT_MOD_LINEAR */), + size: coded, + planes: vec![ + PlaneLayout { + buffer_index: 0, + offset: 0, + stride: pitch, + }, + PlaneLayout { + buffer_index: 0, + offset: pitch * coded.height as usize, + stride: pitch, + }, + ], + } } /// 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) { } })); } + +fn align16(v: u32) -> u32 { + v.div_ceil(16) * 16 +} + +/// Fills in slice NAL header bytes the driver left at zero. +/// +/// Mesa's radeonsi encoder writes `forbidden_zero_bit`, `nal_ref_idc` and +/// `nal_unit_type` from state it only ever populates out of a *packed* slice +/// header, and cros-codecs supplies none (`h264/vaapi.rs` says as much in its +/// "use packed headers" TODO). Every other bit of the slice is correct, so the +/// whole damage is one byte per slice: measured on radeonsi, patching it turns +/// a stream neither ffmpeg nor `rusty_h264` will touch into one both decode. +/// +/// An all-zero byte after a start code is never valid H.264, so drivers that do +/// write the header (Intel's, which is what cros-codecs was built against) fall +/// straight through this. +/// +/// ponytail: the real fix is a `VAEncPackedHeaderH264_Slice` buffer in the +/// vendored cros-codecs backend, which means synthesizing the entire slice +/// header there rather than correcting two fields here. +fn fix_slice_nal_headers(au: &mut [u8]) { + // cros-codecs prepends SPS+PPS to the access unit at every IDR and only + // there, so an SPS seen earlier in this unit is what makes the slice one. + let mut idr = false; + let mut i = 0; + while i + 3 < au.len() { + if au[i..i + 3] != [0, 0, 1] { + i += 1; + continue; + } + let nal = &mut au[i + 3]; + if *nal == 0 { + // nal_ref_idc 3 + IDR, or 2 + non-IDR: every picture this encoder + // emits is a short-term reference (no B-frames, no disposables). + *nal = if idr { 0x65 } else { 0x41 }; + } else if *nal & 0x1f == 7 { + idr = true; + } + i += 3; + } +} + +/// One hardware H.264 encode session. +/// +/// Input goes through a single reusable NV12 buffer object: the caller's I420 +/// planes are interleaved into it and the encoder imports it as a VA surface. +/// Reuse is safe because the encoder runs in blocking mode and every entry +/// point polls it before returning, so the GPU is finished with the buffer +/// before the next picture is written into it. +struct EncSession { + encoder: Encoder, + /// Owns the DRM node the buffer object below was allocated from. + _gbm: gbm::Device, + frame: GenericDmaVideoFrame, + layout: FrameLayout, + /// Macroblock-aligned surface size; `width`/`height` are what is encoded. + coded: Resolution, + width: usize, + height: usize, + timestamp: u64, + drained: bool, + /// Coded access units the encoder has finished but the caller has not + /// collected yet, in encode order (which is display order: no B-frames). + ready: VecDeque>, + /// The access unit currently handed out, kept alive until the next call. + out: Vec, +} + +impl EncSession { + fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option { + // NV12 chroma is half resolution, so odd dimensions have no packing; + // and radeonsi refuses encode contexts below 64x64 (measured). + if width < 64 || height < 64 || width % 2 != 0 || height % 2 != 0 { + return None; + } + if fps_num == 0 || fps_den == 0 || bitrate == 0 { + return None; + } + let (display, gbm) = open_devices()?; + let coded = Resolution { + width: align16(width), + height: align16(height), + }; + let framerate = ((fps_num as f64 / fps_den as f64).round() as i64).clamp(1, 240) as u32; + let low_power = display + .query_config_entrypoints(VAProfile::VAProfileH264Main) + .ok()? + .contains(&VAEntrypoint::VAEntrypointEncSliceLP); + let config = H264Config { + resolution: Resolution { width, height }, + profile: H264Profile::Main, + level: Level::L4, + // No B-frames: coded order stays display order, which is what the + // muxer's duration-only timing assumes. + pred_structure: PredictionStructure::LowDelay { + limit: (framerate * 2) as u16, + }, + initial_tunings: Tunings { + rate_control: RateControl::ConstantBitrate(bitrate), + framerate, + ..Default::default() + }, + }; + let encoder = Encoder::new_vaapi( + display, + config, + Fourcc::from(b"NV12"), + coded, + low_power, + BlockingMode::Blocking, + ) + .ok()?; + // Allocated at the aligned size, so the buffer's pitch is never smaller + // than a padded row. + let frame = alloc_nv12(&gbm, coded).ok()?; + let layout = nv12_layout(coded, frame.get_plane_pitch()[0]); + Some(Self { + encoder, + _gbm: gbm, + frame, + layout, + coded, + width: width as usize, + height: height as usize, + timestamp: 0, + drained: false, + ready: VecDeque::new(), + out: Vec::new(), + }) + } + + /// Interleaves one packed I420 picture into the NV12 input buffer. + /// + /// # Safety + /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their + /// declared stride. + unsafe fn upload(&mut self, src: &VhFrame) -> Result<(), String> { + let (w, h) = (self.width, self.height); + let (cw, ch) = (w / 2, h / 2); + let (aw, ah) = (self.coded.width as usize, self.coded.height as usize); + let pitch = self.frame.get_plane_pitch(); + let mapping = self.frame.map_mut()?; + let planes = mapping.get(); + { + let mut dst = planes[0].borrow_mut(); + for row in 0..ah { + // SAFETY: caller contract; rows past the picture repeat the last. + let s = unsafe { + std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w) + }; + let dst = &mut dst[row * pitch[0]..row * pitch[0] + aw]; + dst[..w].copy_from_slice(s); + // Macroblock padding: replicate the edge rather than leave the + // buffer's garbage there, which would cost bitrate for nothing. + dst[w..].fill(s[w - 1]); + } + } + let mut dst = planes[1].borrow_mut(); + for row in 0..ah / 2 { + let src_row = row.min(ch - 1); + // SAFETY: as above, for the two chroma planes. + let (u, v) = unsafe { + ( + std::slice::from_raw_parts(src.u.add(src_row * src.u_stride), cw), + std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw), + ) + }; + let dst = &mut dst[row * pitch[1]..row * pitch[1] + aw]; + for x in 0..cw { + dst[2 * x] = u[x]; + dst[2 * x + 1] = v[x]; + } + for x in w..aw { + dst[x] = dst[x - 2]; + } + } + Ok(()) + } + + /// # Safety + /// As [`EncSession::upload`]. + unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> { + // SAFETY: caller contract, forwarded. + unsafe { self.upload(src)? }; + let meta = FrameMetadata { + timestamp: self.timestamp, + layout: self.layout.clone(), + force_keyframe, + }; + self.timestamp += 1; + self.encoder + .encode(meta, self.frame.clone()) + .map_err(|e| e.to_string())?; + self.collect() + } + + /// Moves every access unit the encoder has finished into `ready`. + fn collect(&mut self) -> Result<(), String> { + while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? { + let mut au = coded.bitstream; + fix_slice_nal_headers(&mut au); + self.ready.push_back(au); + } + Ok(()) + } + + /// Hands the oldest finished access unit to the caller, or reports that + /// there is none. + fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 { + let Some(au) = self.ready.pop_front() else { + return 0; + }; + self.out = au; + // SAFETY: caller-guaranteed writable destinations. + unsafe { + *out = self.out.as_ptr(); + *out_len = self.out.len(); + } + 1 + } +} + +/// Opens a hardware H.264 encoder for `width`x`height` at `fps_num / fps_den`, +/// constant bitrate `bitrate` bits per second. Returns null on any failure at +/// all -- no VA-API runtime, no render node, no encode entrypoint, dimensions +/// the driver will not take -- and the caller falls back to software. +#[unsafe(no_mangle)] +pub extern "C" fn vh_enc_open( + width: u32, + height: u32, + fps_num: u32, + fps_den: u32, + bitrate: u64, +) -> *mut c_void { + catch_unwind(AssertUnwindSafe(|| { + match EncSession::open(width, height, fps_num, fps_den, bitrate) { + Some(session) => Box::into_raw(Box::new(session)) as *mut c_void, + None => std::ptr::null_mut(), + } + })) + .unwrap_or(std::ptr::null_mut()) +} + +/// Encodes one tightly-strided I420 picture. 1 when `out`/`out_len` describe one +/// Annex-B access unit, 0 when the encoder has nothing coded yet, negative on +/// error. The bytes stay valid until the next call on this session. +/// +/// # Safety +/// `session` must come from [`vh_enc_open`], `frame`'s planes must cover the +/// picture at their declared strides, and `out`/`out_len` must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_enc_frame( + session: *mut c_void, + frame: *const VhFrame, + force_key: i32, + out: *mut *const u8, + out_len: *mut usize, +) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() || frame.is_null() || out.is_null() || out_len.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session and readable frame. + let (session, frame) = unsafe { (&mut *(session as *mut EncSession), &*frame) }; + if frame.y.is_null() || frame.u.is_null() || frame.v.is_null() { + return -1; + } + if frame.width as usize != session.width + || frame.height as usize != session.height + || frame.y_stride < session.width + || frame.u_stride < session.width / 2 + || frame.v_stride < session.width / 2 + { + return -1; + } + // SAFETY: caller contract on the plane pointers, sizes checked above. + match unsafe { session.encode(frame, force_key != 0) } { + Ok(()) => session.take(out, out_len), + Err(e) => { + eprintln!("engine_hw: {e}"); + -2 + } + } + })) + .unwrap_or(-1) +} + +/// Flushes the encoder: 1 while `out`/`out_len` describe another access unit, +/// 0 once every picture fed has been handed back, negative on error. Same +/// lifetime rule as [`vh_enc_frame`]. +/// +/// # Safety +/// `session` must come from [`vh_enc_open`]; `out`/`out_len` must be writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_enc_drain( + session: *mut c_void, + out: *mut *const u8, + out_len: *mut usize, +) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() || out.is_null() || out_len.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &mut *(session as *mut EncSession) }; + if !session.drained { + if let Err(e) = session.encoder.drain().map_err(|e| e.to_string()) { + eprintln!("engine_hw: {e}"); + return -2; + } + session.drained = true; + } + match session.collect() { + Ok(()) => session.take(out, out_len), + Err(e) => { + eprintln!("engine_hw: {e}"); + -2 + } + } + })) + .unwrap_or(-1) +} + +/// Releases an encode session. Safe to call with null. +/// +/// # Safety +/// `session` must come from [`vh_enc_open`] and must not be used afterwards. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_enc_close(session: *mut c_void) { + let _ = catch_unwind(AssertUnwindSafe(|| { + if !session.is_null() { + // SAFETY: pointer came from `Box::into_raw` in `vh_enc_open`. + drop(unsafe { Box::from_raw(session as *mut EncSession) }); + } + })); +} diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index 1d100e8..dff2d34 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -1,12 +1,16 @@ -//! Runtime-optional hardware decode plugin (`libengine_hw.so`). +//! Runtime-optional hardware decode/encode plugin (`libengine_hw.so`). //! //! The plugin links libva/gbm/drm; this crate and the app binary must not, so //! the only coupling is this C ABI plus a `dlopen`. Anything that goes wrong -- //! plugin missing, no VA-API runtime, no render node, unsupported stream -- -//! leaves us with `None` and the caller falls back to the software decoder. +//! leaves us with `None` and the caller falls back to the software codec. +//! +//! Decode and encode resolve their symbols into *separate* tables on purpose: a +//! plugin built before the encode entry points existed must still decode, so a +//! missing `vh_enc_*` may only cost us [`HwEncoder`], never [`HwSession`]. use std::ffi::{CString, c_char, c_void}; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::OnceLock; use libloading::Library; @@ -66,18 +70,18 @@ fn plugin() -> Option<&'static Plugin> { PLUGIN.get_or_init(load).as_ref() } -fn load() -> Option { - // Next to the executable first (cargo puts both in target/), then - // whatever the dynamic linker's search path turns up. - let beside_exe = std::env::current_exe() +/// Where the plugin may live: next to the executable first (cargo puts both in +/// target/), then whatever the dynamic linker's search path turns up. +fn candidates() -> impl Iterator { + std::env::current_exe() .ok() - .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME))); - let candidates = beside_exe - .as_deref() + .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME))) .into_iter() - .chain(std::iter::once(Path::new(LIB_NAME))); + .chain(std::iter::once(PathBuf::from(LIB_NAME))) +} - for candidate in candidates { +fn load() -> Option { + for candidate in candidates() { // SAFETY: loading a shared object runs its initialisers; we only ever // name our own plugin, and every symbol below is type-checked against // the definitions this crate shares with it. @@ -187,3 +191,139 @@ impl Drop for HwSession { // The plugin session is used from one thread at a time (the decode worker) and // never shared; VA-API state inside it is not `Sync`. unsafe impl Send for HwSession {} + +struct EncPlugin { + open: extern "C" fn(u32, u32, u32, u32, u64) -> *mut c_void, + frame: + unsafe extern "C" fn(*mut c_void, *const VhFrame, i32, *mut *const u8, *mut usize) -> i32, + drain: unsafe extern "C" fn(*mut c_void, *mut *const u8, *mut usize) -> i32, + close: unsafe extern "C" fn(*mut c_void), + // Never dropped (lives in a static), so the fn pointers above stay valid. + _lib: Library, +} + +fn enc_plugin() -> Option<&'static EncPlugin> { + static PLUGIN: OnceLock> = OnceLock::new(); + PLUGIN.get_or_init(load_enc).as_ref() +} + +fn load_enc() -> Option { + for candidate in candidates() { + // SAFETY: as in `load` -- our own plugin, symbols type-checked against + // the definitions this crate shares with it. + let lib = match unsafe { Library::new(candidate) } { + Ok(lib) => lib, + Err(_) => continue, + }; + let plugin = unsafe { + (|| { + Some(EncPlugin { + open: *lib.get(b"vh_enc_open\0").ok()?, + frame: *lib.get(b"vh_enc_frame\0").ok()?, + drain: *lib.get(b"vh_enc_drain\0").ok()?, + close: *lib.get(b"vh_enc_close\0").ok()?, + _lib: lib, + }) + })() + }; + if plugin.is_some() { + return plugin; + } + } + None +} + +/// An open hardware encode session. Dropping it closes the plugin session. +pub struct HwEncoder { + plugin: &'static EncPlugin, + handle: *mut c_void, +} + +impl HwEncoder { + /// H.264 at `width`x`height`, `fps_num / fps_den` frames per second, coded + /// at a constant `bitrate` bits per second. `None` whenever hardware encode + /// is unavailable -- plugin missing, plugin too old to export the encode + /// entry points, no driver, dimensions the driver refuses -- and the caller + /// falls back to the software encoder. + pub fn open(width: u32, height: u32, fps_num: u32, fps_den: u32, bitrate: u64) -> Option { + let plugin = enc_plugin()?; + let handle = (plugin.open)(width, height, fps_num, fps_den, bitrate); + if handle.is_null() { + return None; + } + Some(Self { plugin, handle }) + } + + /// Feeds one tightly packed I420 picture. `Ok(None)` means the encoder has + /// not finished an access unit yet; the returned bytes are Annex-B and stay + /// valid until the next call on this session. + pub fn encode( + &mut self, + y: &[u8], + u: &[u8], + v: &[u8], + width: u32, + height: u32, + force_key: bool, + ) -> crate::Result> { + let (w, h) = (width as usize, height as usize); + let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); + if y.len() < w * h || u.len() < cw * ch || v.len() < cw * ch { + return Err("encode input is not a packed I420 frame".into()); + } + let frame = VhFrame { + y: y.as_ptr(), + u: u.as_ptr(), + v: v.as_ptr(), + y_stride: w, + u_stride: cw, + v_stride: cw, + width, + height, + }; + // SAFETY: `handle` is live, the planes outlive the call and their sizes + // were just checked against the strides we declare. + self.take(|plugin, handle, out, out_len| unsafe { + (plugin.frame)(handle, &frame, force_key as i32, out, out_len) + }) + } + + /// Flushes the encoder; call until it returns `Ok(None)`. Same lifetime rule + /// as [`HwEncoder::encode`]. + pub fn drain(&mut self) -> crate::Result> { + // SAFETY: `handle` is live. + self.take(|plugin, handle, out, out_len| unsafe { (plugin.drain)(handle, out, out_len) }) + } + + /// Shared tail of `encode`/`drain`: run the call, then turn the plugin's + /// (pointer, length) pair into a slice borrowed for as long as `&mut self`, + /// which is exactly the "valid until the next call" contract. + fn take( + &mut self, + call: impl FnOnce(&EncPlugin, *mut c_void, *mut *const u8, *mut usize) -> i32, + ) -> crate::Result> { + let mut ptr: *const u8 = std::ptr::null(); + let mut len: usize = 0; + match call(self.plugin, self.handle, &mut ptr, &mut len) { + 0 => return Ok(None), + 1 => {} + code => return Err(format!("hardware encode failed (code {code})").into()), + } + if ptr.is_null() || len == 0 { + return Err("hardware encoder returned an empty access unit".into()); + } + // SAFETY: the plugin promises `len` readable bytes at `ptr` until its + // next call on this session, which `&mut self` prevents overlapping. + Ok(Some(unsafe { std::slice::from_raw_parts(ptr, len) })) + } +} + +impl Drop for HwEncoder { + fn drop(&mut self) { + // SAFETY: `handle` came from `vh_enc_open` and is closed exactly once. + unsafe { (self.plugin.close)(self.handle) } + } +} + +// As `HwSession`: used from one thread at a time (the export worker). +unsafe impl Send for HwEncoder {} diff --git a/crates/engine/tests/hw_encode.rs b/crates/engine/tests/hw_encode.rs new file mode 100644 index 0000000..52dbd1b --- /dev/null +++ b/crates/engine/tests/hw_encode.rs @@ -0,0 +1,162 @@ +//! Hardware encode checks. These need a built `libengine_hw.so` plus a working +//! VA-API driver with an H.264 encode entrypoint, so they are `#[ignore]`d by +//! default. Run them with: +//! +//! ```text +//! cargo build --workspace --release +//! LD_LIBRARY_PATH=target/release \ +//! cargo test -p engine --release --test hw_encode -- --ignored --nocapture --test-threads=1 +//! ``` +//! +//! The round trip goes out through the plugin and back in through the *software* +//! decoder (`rusty_h264` directly, not `DecodeSession`), so a bug on one side +//! cannot cancel out a bug on the other. + +use std::time::{Duration, Instant}; + +use engine::hw::{HwEncoder, HwSession}; + +const FPS: u32 = 30; +const BITRATE: u64 = 4_000_000; + +/// A moving diagonal gradient: something that actually costs bits, so the +/// encoder cannot make the whole test pass by emitting skip frames. +fn synthetic(index: u32, width: usize, height: usize) -> (Vec, Vec, Vec) { + let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); + let mut y = vec![0u8; width * height]; + for row in 0..height { + for col in 0..width { + y[row * width + col] = (row + col + index as usize * 5) as u8; + } + } + let u = vec![64u8.wrapping_add(index as u8); cw * ch]; + let v = vec![192u8.wrapping_sub(index as u8); cw * ch]; + (y, u, v) +} + +/// Encodes `count` synthetic pictures and returns the whole Annex-B stream plus +/// the number of access units the plugin handed back. +fn encode(width: u32, height: u32, count: u32) -> Option<(Vec, u32)> { + let mut encoder = HwEncoder::open(width, height, FPS, 1, BITRATE)?; + let mut stream = Vec::new(); + let mut units = 0; + // Timed around the plugin call only: building the synthetic picture is not + // part of what an export would pay. + let mut spent = Duration::ZERO; + for index in 0..count { + let (y, u, v) = synthetic(index, width as usize, height as usize); + let started = Instant::now(); + let coded = encoder + .encode(&y, &u, &v, width, height, false) + .expect("encode"); + if let Some(au) = coded { + stream.extend_from_slice(au); + units += 1; + } + spent += started.elapsed(); + } + while let Some(au) = encoder.drain().expect("drain") { + stream.extend_from_slice(au); + units += 1; + } + let per_frame = spent.as_secs_f64() * 1000.0 / count as f64; + println!("{width}x{height}: {count} frames, {units} AUs, {per_frame:.2} ms/frame"); + Some((stream, units)) +} + +fn decode(stream: &[u8]) -> Vec { + rusty_h264::Decoder::new() + .decode_stream(stream) + .expect("software decode of the hardware-encoded stream") +} + +fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len()); + a.iter() + .zip(b) + .map(|(x, y)| x.abs_diff(*y) as f64) + .sum::() + / a.len() as f64 +} + +#[test] +#[ignore] +fn round_trips_sixty_frames() { + let (width, height) = (1280u32, 720u32); + let (stream, units) = + encode(width, height, 60).expect("no hardware encode plugin/driver available"); + assert_eq!(units, 60, "one access unit per fed picture"); + + let frames = decode(&stream); + assert_eq!(frames.len(), 60, "decoded picture count"); + for (index, frame) in frames.iter().enumerate() { + assert_eq!( + (frame.width, frame.height), + (width as usize, height as usize), + "frame {index} dimensions" + ); + } + + // The pictures have to survive the I420 -> NV12 upload, not merely exist: + // a dropped plane or a swapped U/V would sail past a count-only check. + // Tolerances are generous because this is lossy CBR, but nowhere near the + // ~64 a U/V swap costs on these chroma values. + for index in [0usize, 30, 59] { + let (y, u, v) = synthetic(index as u32, width as usize, height as usize); + let frame = &frames[index]; + for (plane, (got, want)) in [(&frame.y, &y), (&frame.u, &u), (&frame.v, &v)] + .iter() + .enumerate() + { + let diff = mean_abs_diff(got, want); + println!("frame {index} plane {plane}: mean abs diff {diff:.2}"); + assert!( + diff < 6.0, + "frame {index} plane {plane} drifted by {diff:.2}" + ); + } + } +} + +/// 322x242 is even (NV12 needs that) but neither dimension is a multiple of 16, +/// so the surface is padded and the encoded stream has to crop it back. This is +/// the 1080p case in miniature: 1080 pads to 1088. +#[test] +#[ignore] +fn round_trips_unaligned_dimensions() { + let (width, height) = (322u32, 242u32); + let Some((stream, units)) = encode(width, height, 10) else { + println!("driver refused {width}x{height}, software encode would take over -- skipping"); + return; + }; + assert_eq!(units, 10); + + let frames = decode(&stream); + assert_eq!(frames.len(), 10); + assert_eq!( + (frames[0].width, frames[0].height), + (width as usize, height as usize), + "padding must be cropped away again" + ); +} + +/// Decode and encode resolve through two independent symbol tables, so an +/// encoder that cannot load must not cost us the decoder (and vice versa). +/// +/// This is the positive half only: the negative half -- a plugin built without +/// `vh_enc_*` -- needs a second build of the `.so` and belongs to the slice's +/// verifier, not here. +#[test] +#[ignore] +fn decode_and_encode_load_independently() { + let asset = + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_baseline.mp4"); + assert!( + HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some(), + "encode table" + ); + assert!(HwSession::open(&asset).is_some(), "decode table"); + // Order reversed: neither table's `OnceLock` may have primed the other. + assert!(HwSession::open(&asset).is_some()); + assert!(HwEncoder::open(640, 480, FPS, 1, BITRATE).is_some()); +}