From 36bd0e7aac892873e9d5789b089aba0a309726c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 12 Sep 2026 22:51:16 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor(engine-hw):=20the?= =?UTF-8?q?=20VP8=20decode=20seat=20is=20ec-vp8=20native=20--=20libvpx=20a?= =?UTF-8?q?nd=20its=20hand-written=20FFI=20are=20deleted,=20the=20plugin?= =?UTF-8?q?=20links=20the=20decoder=20as=20ordinary=20Rust=20(56=20ec=5Fvp?= =?UTF-8?q?8=20symbols,=20no=20DT=5FNEEDED,=20no=20dlopen);=20VpxSession?= =?UTF-8?q?=20keeps=20its=20five-verb=20boundary=20(init/decode/flush/get?= =?UTF-8?q?=5Fframe,=20destroy=20now=20the=20drop=20of=20an=20owned=20deco?= =?UTF-8?q?der)=20and=20everything=20above=20it=20is=20untouched;=20CAP=5F?= =?UTF-8?q?VP8=20lights=20unconditionally=20and=20still=20never=20reads=20?= =?UTF-8?q?as=20a=20GPU=20seat;=20A/B=20byte-exact=20against=20the=20libvp?= =?UTF-8?q?x=20seat=20on=20the=201280x720=20fixture=20(60/60=20frames),=20?= =?UTF-8?q?the=202560x1321=20odd-size=20webm=20(270/270)=20and=20a=20two-p?= =?UTF-8?q?ass=20auto-altref=20stream=20(90/90=20shown,=206=20hidden=20pro?= =?UTF-8?q?duce=20none,=20seek=20landings=20identical);=20vp8=20twins=204/?= =?UTF-8?q?4,=20capability=5Fmatrix+backends+caps=20green,=20--all-targets?= =?UTF-8?q?=200=20warnings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 9 +- crates/engine-hw/Cargo.toml | 8 +- crates/engine-hw/src/lib.rs | 171 ++++++++----------- crates/engine-hw/src/vpx.rs | 321 +++++++----------------------------- crates/engine/src/caps.rs | 19 ++- crates/engine/src/decode.rs | 4 +- crates/engine/src/demux.rs | 12 +- crates/engine/src/hw.rs | 11 +- crates/engine/tests/vp8.rs | 18 +- 9 files changed, 177 insertions(+), 396 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5652459..caa9a6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1648,6 +1648,13 @@ dependencies = [ "wide", ] +[[package]] +name = "ec-vp8" +version = "0.1.0" +dependencies = [ + "ec-core", +] + [[package]] name = "edith" version = "0.1.0" @@ -1738,9 +1745,9 @@ name = "engine-hw" version = "0.1.0" dependencies = [ "cros-codecs", + "ec-vp8", "engine", "gbm", - "libloading", ] [[package]] diff --git a/crates/engine-hw/Cargo.toml b/crates/engine-hw/Cargo.toml index 1d93546..39825ee 100644 --- a/crates/engine-hw/Cargo.toml +++ b/crates/engine-hw/Cargo.toml @@ -14,7 +14,7 @@ engine = { path = "../engine" } cros-codecs = { version = "0.0.6", features = ["vaapi"] } # Same version cros-codecs already pulls in; we allocate output frames ourselves. gbm = { version = "0.15", default-features = false, features = ["drm-support"] } -# Same version `engine` pins for its own dlopens (`hw.rs`, `ao.rs`); this is -# the plugin's half of the same philosophy, one level down: `libvpx` for the -# software VP8 seat (`src/vpx.rs`), resolved at runtime like libva itself. -libloading = "0.8" +# The software VP8 seat, this project's own (`ec-vp8`, RFC 6386): linked in +# as ordinary Rust, the one codec with no runtime dlopen behind it -- the +# `libloading` the old libvpx FFI needed is gone with the FFI. +ec-vp8 = { path = "../../../edith_codecs/crates/ec-vp8" } diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index b43478d..ea37f4f 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -1,10 +1,11 @@ //! VA-API decode (H.264, HEVC, VP9 and AV1) -- and VP8, which decodes on -//! `libvpx`, dlopen'd by this plugin in turn ([`vpx`], software, no VA-API -//! anything) -- and encode (H.264 and HEVC, and AV1 where the GPU has an -//! entrypoint for it), shipped as a +//! `ec-vp8` ([`vpx`], this project's own, software, no VA-API anything), +//! linked into the plugin itself -- and encode (H.264 and HEVC, and AV1 +//! where the GPU has an entrypoint for it), shipped as a //! `dlopen`-able plugin so the main binary never gets a DT_NEEDED on -//! libva/gbm/drm -- nor on libvpx, the same rule one level down. Every entry -//! point is +//! libva/gbm/drm. VP8's seat is the one codec with no runtime dlopen +//! behind it anywhere: the old libvpx FFI is gone with the library it +//! loaded. 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". @@ -71,10 +72,7 @@ use cros_codecs::{Fourcc, FrameLayout, PlaneLayout, Resolution}; use gbm::{BufferObjectFlags, Format as GbmFormat}; use engine::demux::{Codec, Demuxer, VideoMeta}; -use engine::hw::{ - CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP8, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta, -}; -use vpx::VpxCtx; +use engine::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP8, CAP_VP9, VhCaps, VhDma, VhFrame, VhMeta}; type PooledFrame = PooledVideoFrame; type Dec = StatelessDecoder>; @@ -872,19 +870,19 @@ impl OpenSession { } } -/// One libvpx decode session: the VP8 half of the plugin, the whole of the +/// One VP8 decode session: the VP8 half of the plugin, the whole of the /// same job [`Session`] does for the VA-API codecs. No display, no GBM, no -/// surface pool -- libvpx hands the planes back in memory, and the only +/// surface pool -- `ec-vp8` hands the planes back in memory, and the only /// shapes worth carrying over from the other half are the ones the caller /// sees: [`VhMeta`], one picture per `pump`, the same [`VhFrame`] layout, the /// same skip/position arithmetic a seek is. /// -/// VP8 reorders nothing: every access unit fed is one picture out, in feed -/// order, which is why `position` advances exactly as the VA-API half's does -/// without any of its drain machinery. +/// VP8 reorders nothing: every access unit fed is *at most* one picture out, +/// in feed order (a hidden altref frame produces none), which is why +/// `position` advances exactly as the VA-API half's does without any of its +/// drain machinery. struct VpxSession { - vpx: &'static vpx::Vpx, - ctx: VpxCtx, + dec: vpx::Decoder, demuxer: Demuxer, meta: VhMeta, flushed: bool, @@ -905,10 +903,11 @@ struct VpxSession { impl VpxSession { fn opened(meta: VideoMeta, demuxer: Demuxer) -> Option { - let vpx = vpx::vpx()?; - let mut session = Self { - vpx, - ctx: VpxCtx::default(), + // The decoder cannot refuse to exist any more: it is linked in. The + // `Option` is the shape [`OpenSession::open_at`] routes on, shared + // with [`Session::opened`], whose failures are real. + Some(Self { + dec: vpx::Decoder::new(), demuxer, meta: VhMeta { width: meta.width, @@ -922,50 +921,30 @@ impl VpxSession { out: Vec::new(), luma: 0, chroma: 0, - }; - if let Err(e) = session.init() { - eprintln!("engine_hw: {e}"); - return None; - } - Some(session) - } - - /// (Re-)initialises the decoder. libvpx has no mid-stream reset, so this - /// *is* the flush: a seek pays destroy + init, and what makes that safe - /// is the demuxer's sync-sample seek, which restarts the feed where the - /// reference chain restarts -- the same discipline [`Session`]'s VA-API - /// flush leans on. - fn init(&mut self) -> Result<(), String> { - self.vpx.dec_init(&mut self.ctx) + }) } /// Feeds one access unit. VP8 emits at most one picture per unit, so the /// pull belongs to the `pump` loop, not here. fn decode(&mut self, au: &[u8]) -> Result<(), String> { - if au.is_empty() { - return Ok(()); - } - self.vpx.decode(&mut self.ctx, au) + self.dec.decode(au) } fn pump(&mut self) -> Result { loop { // Whatever the last fed unit produced is the picture this call - // hands back. The iterator starts fresh per feed because VP8 - // queues nothing: one unit in, at most one picture out. - let mut iter: *const c_void = std::ptr::null(); - while let Some(img) = self.vpx.get_frame(&mut self.ctx, &mut iter) { + // hands back. The slot is taken, not peeked -- the next fed unit + // overwrites it, because VP8 queues nothing: one unit in, at + // most one picture out. + if let Some(pic) = self.dec.get_frame() { // One picture further along, shown or skipped past alike -- - // the same walk [`Session::pump`] makes. The fields the copy - // needs are taken by value, which ends the context's borrow - // before `emit` may take the session again. - let (planes, stride, (w, h)) = (img.planes, img.stride, img.display()); + // the same walk [`Session::pump`] makes. self.position += 1; if self.skip > 0 { self.skip -= 1; continue; } - self.emit(planes, stride, w, h); + self.emit(&pic); return Ok(true); } if self.flushed { @@ -974,11 +953,12 @@ impl VpxSession { match self.demuxer.next_access_unit() { Ok(Some(au)) => self.decode(&au)?, Ok(None) => { - // End of the track: the empty `vpx_codec_decode` that - // releases anything held back is this decoder's flush, - // and it costs no iteration of its own -- the pull at the - // top of the loop drains it. - self.vpx.flush(&mut self.ctx)?; + // End of the track. VP8 holds nothing back -- the flush + // is the formality [`vpx::Decoder::flush`] documents -- + // and it costs no iteration of its own: the pull at the + // top of the loop finds the slot empty and ends the + // stream. + self.dec.flush()?; self.flushed = true; } Err(e) => return Err(e.to_string()), @@ -990,27 +970,24 @@ impl VpxSession { /// for a decoder that hands the planes back in memory rather than behind /// a `vaGetImage`. VP8 output is always 8-bit 4:2:0, so there is no /// 10-bit branch to mirror. - fn emit(&mut self, planes: [*mut u8; 4], stride: [std::ffi::c_int; 4], w: u32, h: u32) { - let (w, h) = (w as usize, h as usize); + fn emit(&mut self, pic: &vpx::Picture) { + let (w, h) = (usize::from(pic.width), usize::from(pic.height)); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); if self.luma != w * h || self.chroma != cw * ch { self.luma = w * h; self.chroma = cw * ch; self.out = vec![0u8; self.luma + 2 * self.chroma]; } - self.meta.width = w as u32; - self.meta.height = h as u32; + self.meta.width = u32::from(pic.width); + self.meta.height = u32::from(pic.height); let (dst_y, rest) = self.out.split_at_mut(self.luma); let (dst_u, dst_v) = rest.split_at_mut(self.chroma); - // SAFETY: libvpx guarantees the planes stride-cover the *display* - // size (4:2:0, so the chroma planes cover cw x ch) for the life of - // the image, which ends at this session's next `get_frame` -- after - // the copies below. - unsafe { - copy_plane(planes[0], stride[0] as usize, dst_y, w, h); - copy_plane(planes[1], stride[1] as usize, dst_u, cw, ch); - copy_plane(planes[2], stride[2] as usize, dst_v, cw, ch); - } + // The planes stride-cover the visible frame by the `Picture` + // contract (4:2:0, so the chroma planes cover cw x ch), and they are + // owned by this session -- no lifetime to out-think, no unsafe. + copy_plane(&pic.y, pic.stride, dst_y, w, h); + copy_plane(&pic.u, pic.uv_stride, dst_u, cw, ch); + copy_plane(&pic.v, pic.uv_stride, dst_v, cw, ch); } fn fill(&self, out: &mut VhFrame) { @@ -1031,9 +1008,9 @@ impl VpxSession { /// Repositions the session, exactly [`Session::seek_to`]: the same /// forward walk within [`FORWARD_SECS`], the same demuxer seek to a sync - /// sample otherwise -- and for the decoder, destroy + re-init where the - /// VA-API half pays a flush, because VP8 is stateful to its last inter - /// frame and libvpx offers no softer reset. + /// sample otherwise -- and for the decoder, a fresh [`vpx::Decoder`] + /// where the VA-API half pays a flush, because VP8 is stateful to its + /// last inter frame. fn seek_to(&mut self, target_sample: u32) -> Result<(), String> { let target_frame = target_sample.saturating_sub(1); if let Reposition::Forward(ahead) = reposition( @@ -1045,11 +1022,11 @@ impl VpxSession { self.skip = forward_skip(self.skip, ahead); return Ok(()); } - // Dropping every reference the decoder holds. The destroy's answer is - // not checked against `Ok` because the init below re-zeroes the - // context either way; a destroy that failed has nothing to leak. - self.vpx.destroy(&mut self.ctx); - self.init()?; + // Dropping every reference the decoder holds: the whole of what the + // FFI seat paid as destroy + re-init is now the assignment of an + // owned value. What makes it safe is unchanged -- the demuxer's + // sync-sample seek restarts the feed where the reference chain does. + self.dec = vpx::Decoder::new(); self.flushed = false; let first = self.demuxer.seek_to_sync_at_or_before(target_frame); self.skip = (i64::from(target_frame) - first).max(0) as u32; @@ -1058,20 +1035,11 @@ impl VpxSession { } } -impl Drop for VpxSession { - fn drop(&mut self) { - self.vpx.destroy(&mut self.ctx); - } -} - /// One strided plane down to tightly packed rows: the whole of the read-back /// a VP8 picture costs, where the VA-API half pays `vaGetImage` for the same. -/// -/// # Safety -/// `src` must stride-cover `w` x `h`, and `dst` must be `w` x `h`. -unsafe fn copy_plane(src: *const u8, stride: usize, dst: &mut [u8], w: usize, h: usize) { +fn copy_plane(src: &[u8], src_stride: usize, dst: &mut [u8], w: usize, h: usize) { for row in 0..h { - let s = unsafe { std::slice::from_raw_parts(src.add(row * stride), w) }; + let s = &src[row * src_stride..row * src_stride + w]; dst[row * w..(row + 1) * w].copy_from_slice(s); } } @@ -1079,8 +1047,8 @@ unsafe fn copy_plane(src: *const u8, stride: usize, dst: &mut [u8], w: usize, h: /// Opens `path` for hardware decode, positioned so the first /// [`vh_next_frame`] returns sample `target_sample` (1-based; 0 and 1 both mean /// the start of the stream). Returns null on any failure at all: no libva -/// runtime, no render node, no libvpx for a VP8 file, unsupported profile, -/// unreadable file. +/// runtime, no render node, unsupported profile, unreadable file, a VP8 +/// stream the decoder rejects. /// /// # Safety /// `path` must be a valid NUL-terminated C string. @@ -1215,7 +1183,7 @@ pub unsafe extern "C" fn vh_next_frame_dma( let session = unsafe { &mut *(session as *mut OpenSession) }; // SAFETY: as above. unsafe { *dma = VhDma::default() }; - // A libvpx picture has no GPU buffer to hand over: this session reads + // A VP8 picture has no GPU buffer to hand over: this session reads // back, exactly as `vh_next_frame` does, and the caller's `dma` keeps // the fd-below-zero default that says so. match session { @@ -1333,12 +1301,13 @@ const CAP_TABLE: [(u32, &[VAProfile::Type], &[VAProfile::Type], Option Option { .query_config_entrypoints(profile) .is_ok_and(|e| e.contains(&entrypoint)) }; - let decodes = |list: &[VAProfile::Type]| { - list.iter() - .any(|&p| has(p, VAEntrypoint::VAEntrypointVLD)) - }; + let decodes = + |list: &[VAProfile::Type]| list.iter().any(|&p| has(p, VAEntrypoint::VAEntrypointVLD)); let mut caps = VhCaps::default(); for (bit, eight, ten, encode) in CAP_TABLE { if decodes(eight) { @@ -1374,10 +1341,10 @@ fn query_caps() -> Option { } } // The plugin's own software decoder, on its own account rather than the - // driver's -- the plugin's capability, never a GPU feat. - if vpx::vpx().is_some() { - caps.decode |= CAP_VP8; - } + // driver's -- the plugin's capability, never a GPU feat. Native now, so + // the bit has no "when it loads" condition left: it lights on every + // machine this plugin runs on. + caps.decode |= CAP_VP8; Some(caps) } diff --git a/crates/engine-hw/src/vpx.rs b/crates/engine-hw/src/vpx.rs index 86003cb..1e266b5 100644 --- a/crates/engine-hw/src/vpx.rs +++ b/crates/engine-hw/src/vpx.rs @@ -1,273 +1,78 @@ -//! `libvpx`, dlopen'd: the software VP8 decoder, and the reason a VP8 file -//! decodes on a machine whose GPU has no VP8 profile -- or whose GPU is -//! absent altogether. +//! The software VP8 decoder: `ec-vp8`, this project's own implementation of +//! RFC 6386 -- the reason a VP8 file decodes on a machine whose GPU has no +//! VP8 profile, or whose GPU is absent altogether. //! -//! The plugin's own libva linkage, one level down: this plugin keeps no -//! DT_NEEDED on `libvpx` any more than the main binary does. The symbols are -//! resolved lazily, once, and a machine without the library is a machine -//! without the codec -- answered as `None` at [`vpx`] before any file is -//! opened, which is what [`crate::query_caps`] reports as the absence of -//! `CAP_VP8`. +//! The seat was `libvpx`, resolved at runtime behind a hand-written FFI; the +//! native crate replaces it outright, and with it the whole dlopen layer +//! goes: the plugin links the decoder as ordinary Rust, so there is no +//! library to look for, no ABI to pin, and no machine where the codec is +//! absent from a build that carries this plugin. What survives from the FFI +//! days is the seat's shape -- the five verbs the session above lives on: //! -//! The extern declarations are hand-written against `vpx_decoder.h`, -//! `vpx_codec.h` and `vpx_image.h` as this soname has carried them since -//! libvpx 1.14: `VPX_DECODER_ABI_VERSION` 12. A libvpx from another ABI -//! answers `vpx_codec_dec_init_ver` with `VPX_CODEC_ABI_MISMATCH`, which -//! surfaces as a refused session -- loudly, in the eprintln, never as a -//! wrong picture. The struct layouts below are the ABI, not an assumption: -//! `vpx_codec_ctx_t`'s fields have not moved since the library's first -//! release, and `vpx_image_t`'s prefix is what every decoder in the field -//! reads. - -use std::ffi::{CStr, c_char, c_int, c_long, c_uint, c_void}; -use std::sync::LazyLock; - -use libloading::Library; - -/// `VPX_DECODER_ABI_VERSION`: `3 + VPX_CODEC_ABI_VERSION`, and -/// `VPX_CODEC_ABI_VERSION = 4 + VPX_IMAGE_ABI_VERSION` with -/// `VPX_IMAGE_ABI_VERSION = 5` -- the three headers this module mirrors. -const VPX_DECODER_ABI_VERSION: c_int = 12; - -/// `VPX_CODEC_OK`, the one return code that is not a refusal. -const VPX_CODEC_OK: c_int = 0; - -/// `VPX_DL_REALTIME`, the decode `deadline` argument -- which `vpx_decoder.h` -/// states this API ignores; passed because the type demands a value, and the -/// constant because it is the documented one. -const VPX_DL_REALTIME: c_long = 1; - -/// The decoder context, `vpx_codec_ctx_t` field for field. Nothing here is -/// read: the struct exists so the context is laid out exactly as libvpx -/// lays it out, and so the `&mut` handoffs to the C side are the whole of -/// the story. -#[repr(C)] -pub struct VpxCtx { - name: *const c_char, - iface: *const c_void, - err: c_int, - err_detail: *const c_char, - init_flags: c_uint, - config: *const c_void, - priv_: *mut c_void, -} - -impl Default for VpxCtx { - fn default() -> Self { - // SAFETY: all-pointer/zero initialisation is what libvpx's own init - // performs on the context before it fills it; `vpx_codec_dec_init_ver` - // re-zeroes it anyway. - unsafe { std::mem::zeroed() } - } +//! - `init` -- a fresh [`Decoder`], infallible now that there is no ABI to +//! negotiate; +//! - `decode` -- one access unit in, the picture (if any) held for the next +//! `get_frame`; +//! - `get_frame` -- the picture the last `decode` produced, taken once; +//! - `flush` -- a formality: VP8 reorders nothing and holds nothing back, so +//! end of stream has nothing to release (libvpx wanted the empty +//! `vpx_codec_decode`; the native decoder has no equivalent need, and the +//! verb stays because the session's pump is written around it); +//! - `destroy` -- now simply the drop of an owned value, which is why a +//! seek is `self.decoder = Decoder::new()` where the FFI seat paid a +//! destroy + re-init round trip. + +use ec_vp8::decode; + +/// The VP8 decoder: [`decode::Decoder`] plus the one-picture slot between +/// `decode` and `get_frame`. +pub(super) struct Decoder { + inner: decode::Decoder, + pending: Option, } -/// `vpx_codec_dec_cfg_t`: thread count and a best-known size the caller may -/// leave at zero. -#[repr(C)] -struct VpxDecCfg { - threads: c_uint, - w: c_uint, - h: c_uint, -} - -/// `vpx_image_t` complete: the planes of one decoded picture and the strides -/// they sit at. The decoder owns the bytes -- they stay valid only until the -/// next `get_frame` or `decode` on the same context, which is exactly the -/// [`crate::VhFrame`] contract the caller already lives with. -#[repr(C)] -pub struct VpxImage { - fmt: c_int, - cs: c_int, - range: c_int, - w: c_uint, - h: c_uint, - bit_depth: c_uint, - d_w: c_uint, - d_h: c_uint, - r_w: c_uint, - r_h: c_uint, - x_chroma_shift: c_uint, - y_chroma_shift: c_uint, - pub planes: [*mut u8; 4], - pub stride: [c_int; 4], - bps: c_int, - user_priv: *mut c_void, - img_data: *mut u8, - img_data_owner: c_int, - self_allocd: c_int, - fb_priv: *mut c_void, -} - -impl VpxImage { - /// Displayed dimensions: what [`crate::VhFrame`] describes, not the - /// macroblock-padded storage the planes actually cover. - pub fn display(&self) -> (u32, u32) { - (self.d_w, self.d_h) - } -} - -type Dx = unsafe extern "C" fn() -> *const c_void; -type DecInitVer = - unsafe extern "C" fn(*mut VpxCtx, *const c_void, *const VpxDecCfg, c_uint, c_int) -> c_int; -type Decode = unsafe extern "C" fn(*mut VpxCtx, *const u8, c_uint, *mut c_void, c_long) -> c_int; -type GetFrame = unsafe extern "C" fn(*mut VpxCtx, *mut *const c_void) -> *mut VpxImage; -type Destroy = unsafe extern "C" fn(*mut VpxCtx) -> c_int; -type ErrorFn = unsafe extern "C" fn(*const VpxCtx) -> *const c_char; - -/// The resolved symbols, held with the library that carries them -- exactly -/// the shape `engine::hw`'s `Plugin` has on the other side of the ABI. -pub struct Vpx { - vp8_dx: Dx, - dec_init_ver: DecInitVer, - decode: Decode, - get_frame: GetFrame, - destroy: Destroy, - error: ErrorFn, - // Never dropped (the struct lives in a static), so the pointers above - // stay valid for the life of the process. - _lib: Library, -} - -/// The library, loaded once per process. `None` -- no `libvpx.so` on this -/// machine, or one missing a symbol this module names -- is the one answer, -/// asked before any file is opened. -static VPX: LazyLock> = LazyLock::new(load); - -/// The loaded library, or `None` on a machine without one this module can -/// use. Asked before any file is opened. -pub fn vpx() -> Option<&'static Vpx> { - VPX.as_ref() -} - -fn load() -> Option { - // The versioned soname first -- the name every distribution actually - // ships -- then the unversioned development name for the odd link that - // has it. - for name in ["libvpx.so.9", "libvpx.so"] { - let lib = match unsafe { Library::new(name) } { - Ok(lib) => lib, - Err(_) => continue, - }; - // SAFETY: the symbols are type-checked against the declarations above; - // a missing one unloads the library with the dropped closure and the - // next candidate gets its turn. - let vpx = unsafe { - (|| { - Some(Vpx { - vp8_dx: *lib.get(b"vpx_codec_vp8_dx\0").ok()?, - dec_init_ver: *lib.get(b"vpx_codec_dec_init_ver\0").ok()?, - decode: *lib.get(b"vpx_codec_decode\0").ok()?, - get_frame: *lib.get(b"vpx_codec_get_frame\0").ok()?, - destroy: *lib.get(b"vpx_codec_destroy\0").ok()?, - error: *lib.get(b"vpx_codec_error\0").ok()?, - _lib: lib, - }) - })() - }; - if vpx.is_some() { - return vpx; +/// One decoded picture: the visible frame's planes, 8-bit 4:2:0, strided +/// (`stride` may exceed `width`) and owned by whoever holds it -- what +/// [`crate::VhFrame`] hands on is the packed copy the session makes. +pub(super) use decode::Picture; + +impl Decoder { + /// `init`: a decoder holding no references yet; the first key frame + /// sets the size. + pub(super) fn new() -> Self { + Self { + inner: decode::Decoder::new(), + pending: None, } } - None -} -impl Vpx { - /// `vpx_codec_error`'s line about the context's last answer: what an init - /// or decode refusal says instead of a bare `vpx_codec_err_t` number. - fn last_error(&self, ctx: &VpxCtx) -> String { - // SAFETY: `ctx` is a live libvpx context; the string it names is - // static and read before anything else touches the context. - let msg = unsafe { (self.error)(ctx) }; - if msg.is_null() { - return "no description".to_string(); + /// `decode`: one access unit in -- one complete VP8 frame payload, + /// exactly what a container demuxer hands over for `V_VP8`/`vp08`. A + /// hidden frame (an alternate reference, `show_frame == 0`) updates the + /// reference buffers and produces no picture: the same nothing libvpx + /// emitted for one, so the seat's picture accounting does not move. + pub(super) fn decode(&mut self, au: &[u8]) -> Result<(), String> { + if au.is_empty() { + return Ok(()); } - // SAFETY: non-null per the check above, NUL-terminated per libvpx. - unsafe { CStr::from_ptr(msg) }.to_string_lossy().into_owned() - } - - /// The VP8 decoder interface, `vpx_codec_vp8_dx`: the argument every - /// `dec_init_ver` on this context takes. - fn iface(&self) -> *const c_void { - // SAFETY: a pure lookup in libvpx's own tables. - unsafe { (self.vp8_dx)() } - } - - /// `vpx_codec_dec_init_ver` with the ABI version this module was written - /// against -- the check a mismatched libvpx fails rather than a call it - /// misreads. - pub(super) fn dec_init(&self, ctx: &mut VpxCtx) -> Result<(), String> { - let cfg = VpxDecCfg { - threads: threads(), - w: 0, - h: 0, - }; - // SAFETY: the context is ours and live for the session; `cfg` is read - // only during the call; the version pins the ABI. - let rc = unsafe { (self.dec_init_ver)(ctx, self.iface(), &cfg, 0, VPX_DECODER_ABI_VERSION) }; - match rc { - VPX_CODEC_OK => Ok(()), - _ => Err(format!("libvpx init failed: {}", self.last_error(ctx))), + match self.inner.decode(au) { + Ok(picture) => self.pending = picture, + Err(e) => return Err(format!("vp8 decode failed: {e}")), } + Ok(()) } - /// `vpx_codec_decode`: one access unit in. `VPX_DL_REALTIME` is the - /// documented-but-ignored deadline. - pub(super) fn decode(&self, ctx: &mut VpxCtx, au: &[u8]) -> Result<(), String> { - // SAFETY: `au` outlives the call; the context is live and used from - // the one thread the session lives on. - let rc = unsafe { - (self.decode)( - ctx, - au.as_ptr(), - au.len() as c_uint, - std::ptr::null_mut(), - VPX_DL_REALTIME, - ) - }; - match rc { - VPX_CODEC_OK => Ok(()), - _ => Err(format!("libvpx decode failed: {}", self.last_error(ctx))), - } - } - - /// `vpx_codec_decode` with a null, empty frame: the end-of-stream signal - /// that releases whatever the decoder held back. - pub(super) fn flush(&self, ctx: &mut VpxCtx) -> Result<(), String> { - // SAFETY: as `decode`, with the nulls libvpx reads as "no more data". - let rc = unsafe { - (self.decode)(ctx, std::ptr::null(), 0, std::ptr::null_mut(), VPX_DL_REALTIME) - }; - match rc { - VPX_CODEC_OK => Ok(()), - _ => Err(format!("libvpx flush failed: {}", self.last_error(ctx))), - } + /// `get_frame`: the picture the last `decode` produced, if that frame + /// was shown. Taken, not peeked -- the slot is empty again afterwards, + /// which is what lets the pump loop feed the next unit. + pub(super) fn get_frame(&mut self) -> Option { + self.pending.take() } - /// `vpx_codec_get_frame`: the next picture of the current iteration, or - /// `None` when the iteration is done. The bytes belong to the decoder - /// until the next `decode`/`flush`. - pub(super) fn get_frame<'a>( - &self, - ctx: &'a mut VpxCtx, - iter: &mut *const c_void, - ) -> Option<&'a VpxImage> { - // SAFETY: the context is live; the returned pointer is libvpx's own - // image, borrowed for exactly as long as the lifetime above says. - unsafe { (self.get_frame)(ctx, iter).as_ref() } + /// `flush`: end of the track. VP8 queues nothing -- one unit in, at + /// most one picture out, feed order -- so there is nothing held back to + /// drain; the answer is always ok, immediately. + pub(super) fn flush(&mut self) -> Result<(), String> { + Ok(()) } - - /// `vpx_codec_destroy`: the context's half of `VpxSession`'s `Drop`. - pub(super) fn destroy(&self, ctx: &mut VpxCtx) { - // SAFETY: called once per live context; libvpx frees what the context - // holds, and a context whose init never completed reads as an - // `INVALID_PARAM` refusal rather than a crash. - unsafe { (self.destroy)(ctx) }; - } -} - -/// VP8's row-based multithreaded decode stops paying past a handful of -/// threads -- the row sync costs what the parallelism buys -- so this is not -/// the machine's whole core count. -pub(super) fn threads() -> c_uint { - std::thread::available_parallelism().map_or(1, |n| n.get().min(4) as c_uint) } diff --git a/crates/engine/src/caps.rs b/crates/engine/src/caps.rs index ca1d17e..34e9c94 100644 --- a/crates/engine/src/caps.rs +++ b/crates/engine/src/caps.rs @@ -12,12 +12,13 @@ //! driver all read the same way -- "software only" -- because that is what they //! mean for the file a user is about to write. //! -//! VP8 is deliberately on neither line: the plugin decodes it on libvpx, -//! dlopen'd at runtime, and reports `CAP_VP8` for it -- the plugin's seat, -//! never the GPU's. [`HW_CODECS`] does not carry the bit, because this file's -//! one job is not presenting a seat as a GPU feat that no GPU has. +//! VP8 is deliberately on neither line: the plugin decodes it on its own +//! native `ec-vp8`, always present, and reports `CAP_VP8` for it -- the +//! plugin's seat, never the GPU's. [`HW_CODECS`] does not carry the bit, +//! because this file's one job is not presenting a seat as a GPU feat that +//! no GPU has. -use crate::hw::{VhCaps, CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9}; +use crate::hw::{CAP_AV1, CAP_H264, CAP_HEVC, CAP_VP9, VhCaps}; /// The codecs a hardware line can name, in the order it lists them. const HW_CODECS: [(u32, &str); 4] = [ @@ -136,10 +137,10 @@ mod tests { assert_eq!(hw_line(Some(h264_only)), "H.264 dec"); } - /// The plugin's VP8 bit is its own libvpx software decoder. However lit - /// the mask is, the hardware line never reads it as a GPU seat -- and a - /// mask holding nothing *but* it still reads as the nothing a driver - /// without seats would answer. + /// The plugin's VP8 bit is its own native decoder (`ec-vp8`), lit + /// unconditionally. However lit the mask is, the hardware line never + /// reads it as a GPU seat -- and a mask holding nothing *but* it still + /// reads as the nothing a driver without seats would answer. #[test] fn the_plugin_s_software_vp8_never_reads_as_a_gpu_seat() { let vpx_only = VhCaps { diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 5920836..53d455e 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -1016,8 +1016,8 @@ fn run_span( } // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or // VP8 bytes to either software seat would be garbage, not a fallback -- - // VP8's software decoder is libvpx, inside the plugin. H.264 and AV1 each - // have one of this project's own: `ec-h264`, `ec-av1`. + // VP8's decoder is `ec-vp8`, inside the plugin. H.264 and AV1 each + // have one of this project's own here: `ec-h264`, `ec-av1`. match opened.meta.codec { Codec::H264 => { eprintln!("decode backend: software (ec-h264)"); diff --git a/crates/engine/src/demux.rs b/crates/engine/src/demux.rs index 1ba9356..def89ae 100644 --- a/crates/engine/src/demux.rs +++ b/crates/engine/src/demux.rs @@ -110,8 +110,8 @@ pub fn cancelled_read_error() -> crate::Error { CANCELLED.into() } -/// What the video track is coded with. Not a decoder choice by itself: only -/// H.264 has a software decoder in this binary, and VP8's (libvpx) lives +/// What the video track is coded with. Not a decoder choice by itself: H.264 +/// and AV1 have software decoders in this binary, and VP8's (`ec-vp8`) lives /// inside the plugin -- which is what [`Codec::needs_plugin`] says for the /// rest, per codec, in the words that stay true. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -140,9 +140,9 @@ impl Codec { /// own (`ec-h264`, `ec-av1`) and are never refused for missing hardware on /// the *playback* path; HEVC and VP9 have no software decoder at all, so /// the refusal names the plugin as the only way. VP8's software decoder - /// *is* libvpx inside the plugin, so "there is no software decoder" would - /// be a lie the day the plugin grew that arm -- the refusal keeps naming - /// the plugin, because that is still the thing to make present. AV1's arm + /// *is* this project's own `ec-vp8`, inside the plugin, so "there is no + /// software decoder" would be a lie -- the refusal keeps naming the + /// plugin, because that is still the thing to make present. AV1's arm /// is the one refusal left that can reach it: the software *export* /// decoder is H.264-only (`export::SwDecoder`), so an AV1 source on a /// machine with no plugin exports through nothing. Shared so playback and @@ -150,7 +150,7 @@ impl Codec { pub fn needs_plugin(self) -> String { match self { Self::Vp8 => { - "VP8 needs the VA-API plugin (libengine_hw.so) — its decoder is libvpx, inside the plugin" + "VP8 needs the VA-API plugin (libengine_hw.so) — its decoder is ec-vp8, inside the plugin" .to_string() } Self::Av1 => { diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index d028937..5319ca3 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -178,10 +178,11 @@ pub const CAP_HEVC: u32 = 1 << 1; pub const CAP_VP9: u32 = 1 << 2; pub const CAP_AV1: u32 = 1 << 3; -/// VP8 decodes on libvpx inside the plugin -- software, dlopen'd at runtime, -/// no GPU and no VA-API profile anywhere in it -- so this bit is the -/// *plugin's* seat, never the driver's. It lights up [`VhCaps::decode`] when -/// the library is present; the hardware line in [`crate::caps`] deliberately +/// VP8 decodes on `ec-vp8` inside the plugin -- software, linked into the +/// plugin itself, no GPU and no VA-API profile anywhere in it -- so this bit +/// is the *plugin's* seat, never the driver's, and it lights up +/// [`VhCaps::decode`] unconditionally: there is no library whose presence the +/// bit depends on any more. The hardware line in [`crate::caps`] deliberately /// keeps it off, being a line about what the GPU takes. pub const CAP_VP8: u32 = 1 << 4; @@ -263,7 +264,7 @@ fn load() -> Option { /// "software only" for all of them, which is what they mean. /// /// VP8 sits outside that reading on a driverless machine: its decoder is -/// libvpx inside the plugin, so the plugin may open a VP8 file where this +/// `ec-vp8` inside the plugin, so the plugin may open a VP8 file where this /// table answers `None`. Nothing here promises otherwise -- the decode path /// asks the plugin, not this table -- and the one display-dependent half the /// front-end draws from this stays exactly as truthful as it was. diff --git a/crates/engine/tests/vp8.rs b/crates/engine/tests/vp8.rs index 8691645..34e85f6 100644 --- a/crates/engine/tests/vp8.rs +++ b/crates/engine/tests/vp8.rs @@ -1,7 +1,7 @@ //! VP8 import: the container half, and the decode half -- software, on the -//! libvpx the plugin dlopens (`engine-hw`'s `vpx.rs`), which is why these -//! twins need a built `libengine_hw.so` and a `libvpx.so` but **no VA-API -//! VP8 profile**: no such profile exists on this GPU, and none is asked for. +//! plugin's own native decoder (`ec-vp8`, `engine-hw`'s `vpx.rs`), which is +//! why these twins need a built `libengine_hw.so` but **no VA-API VP8 +//! profile**: no such profile exists on this GPU, and none is asked for. //! //! ```text //! cargo build -p engine -p engine-hw --release @@ -55,9 +55,9 @@ fn the_demuxer_reports_a_vp8_track() { /// There is no software VP8 decoder *in this binary*, so the software path /// must refuse by name rather than feed VP8 bytes to `ec-h264` -- and it /// must refuse where a caller can still show it, i.e. out of `open`, not from -/// inside the worker. The decoder the refusal names is the plugin's libvpx -/// arm, which is why the sentence names the plugin and not a nonexistent -/// absence. +/// inside the worker. The decoder the refusal names is the plugin's own +/// (`ec-vp8`), which is why the sentence names the plugin and not a +/// nonexistent absence. #[test] fn the_software_path_refuses_vp8_by_name() { // SAFETY: the suite is documented to run with --test-threads=1. @@ -73,10 +73,10 @@ fn the_software_path_refuses_vp8_by_name() { } /// The end-to-end user path: opening the file yields pictures, all of them, -/// through the plugin's libvpx arm. The `.webm` is the file this decodes, +/// through the plugin's VP8 arm. The `.webm` is the file this decodes, /// the container half being the Matroska demuxer's `V_VP8` row. #[test] -#[ignore = "needs a built libengine_hw.so and libvpx.so.9 -- no VA-API profile involved"] +#[ignore = "needs a built libengine_hw.so -- no VA-API profile involved"] fn the_plugin_decodes_every_vp8_frame() { let start = Instant::now(); let (meta, frames) = DecodeSession::open(asset("test_vp8.webm")).expect("open test_vp8.webm"); @@ -117,7 +117,7 @@ fn the_plugin_decodes_every_vp8_frame() { /// Export re-encodes to H.264 whatever the source was coded with: the packet /// copy path is audio-only, so no VP8 byte can reach an `avc1` track. #[test] -#[ignore = "needs a built libengine_hw.so and libvpx.so.9 -- no VA-API profile involved"] +#[ignore = "needs a built libengine_hw.so -- no VA-API profile involved"] fn a_vp8_source_exports_as_h264() { let session = PlaybackSession::open(asset("test_vp8.webm")).expect("open test_vp8.webm"); let meta = *session.meta();