diff --git a/crates/ec-va/Cargo.toml b/crates/ec-va/Cargo.toml new file mode 100644 index 00000000..e3e2a0e6 --- /dev/null +++ b/crates/ec-va/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "ec-va" +description = "Minimal hand-written libva (VA-API) FFI and a safe RAII/typestate layer over it." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +# No dependencies, by design: the whole point of this crate is that the FFI +# surface is small enough to be read end to end (see src/sys.rs). It links the +# system libva/libva-drm shared objects; nothing is generated at build time. +[dependencies] diff --git a/crates/ec-va/abi-probe.c b/crates/ec-va/abi-probe.c new file mode 100644 index 00000000..951fea88 --- /dev/null +++ b/crates/ec-va/abi-probe.c @@ -0,0 +1,90 @@ +/* + * ABI probe for the hand-written libva FFI in src/sys.rs. + * + * src/sys.rs transcribes libva struct layouts by hand (no bindgen, family rule). + * This probe is the evidence for that transcription: it prints the sizes, + * alignments and field offsets that the *system* headers produce, so the + * `const _: () = assert!(...)` block in sys.rs can be checked against a real + * compiler instead of against a reading of the header. + * + * Run: + * cc -o /tmp/ec-va-abi-probe crates/ec-va/abi-probe.c $(pkg-config --cflags --libs libva) \ + * && /tmp/ec-va-abi-probe + * + * Recorded output (libva 1.23.0, x86_64-unknown-linux-gnu, gcc 15) is pasted + * into the assertion block in sys.rs. Any mismatch after a libva upgrade means + * the transcription drifted — the exact failure mode that broke cros-libva at + * libva >= 1.23. + */ +#include +#include +#include +#include + +#define SA(T) printf("%-32s size=%-5zu align=%zu\n", #T, sizeof(T), _Alignof(T)) +#define OF(T, F) printf(" %-30s offset=%zu\n", #T "." #F, offsetof(T, F)) + +int main(void) +{ + printf("libva headers: %s\n", VA_VERSION_S); + + SA(VAStatus); + SA(VAGenericID); + SA(VAProfile); + SA(VAEntrypoint); + SA(VAConfigAttribType); + SA(VAConfigAttrib); + OF(VAConfigAttrib, type); + OF(VAConfigAttrib, value); + + SA(VAGenericValue); + OF(VAGenericValue, type); + OF(VAGenericValue, value); + + SA(VASurfaceAttrib); + OF(VASurfaceAttrib, type); + OF(VASurfaceAttrib, flags); + OF(VASurfaceAttrib, value); + + SA(VAImageFormat); + OF(VAImageFormat, fourcc); + OF(VAImageFormat, byte_order); + OF(VAImageFormat, bits_per_pixel); + OF(VAImageFormat, depth); + OF(VAImageFormat, red_mask); + OF(VAImageFormat, alpha_mask); + OF(VAImageFormat, va_reserved); + + SA(VAImage); + OF(VAImage, image_id); + OF(VAImage, format); + OF(VAImage, buf); + OF(VAImage, width); + OF(VAImage, height); + OF(VAImage, data_size); + OF(VAImage, num_planes); + OF(VAImage, pitches); + OF(VAImage, offsets); + OF(VAImage, num_palette_entries); + OF(VAImage, entry_bytes); + OF(VAImage, component_order); + OF(VAImage, va_reserved); + + SA(VADRMPRIMESurfaceDescriptor); + OF(VADRMPRIMESurfaceDescriptor, fourcc); + OF(VADRMPRIMESurfaceDescriptor, width); + OF(VADRMPRIMESurfaceDescriptor, height); + OF(VADRMPRIMESurfaceDescriptor, num_objects); + OF(VADRMPRIMESurfaceDescriptor, objects); + OF(VADRMPRIMESurfaceDescriptor, num_layers); + OF(VADRMPRIMESurfaceDescriptor, layers); + printf(" object elem size=%zu align=%zu\n", + sizeof(((VADRMPRIMESurfaceDescriptor *)0)->objects[0]), + _Alignof(((VADRMPRIMESurfaceDescriptor *)0)->objects[0])); + printf(" layer elem size=%zu align=%zu\n", + sizeof(((VADRMPRIMESurfaceDescriptor *)0)->layers[0]), + _Alignof(((VADRMPRIMESurfaceDescriptor *)0)->layers[0])); + + SA(VARectangle); + return 0; +} diff --git a/crates/ec-va/src/caps.rs b/crates/ec-va/src/caps.rs new file mode 100644 index 00000000..9a7136db --- /dev/null +++ b/crates/ec-va/src/caps.rs @@ -0,0 +1,368 @@ +//! Capability probing: what this GPU can actually decode and encode. +//! +//! [`Profile`] and [`Entrypoint`] are safe mirrors of the C enums, each with an +//! `Unknown(i32)` arm. That arm is not defensive decoration: `vaQueryConfigProfiles` +//! writes driver-chosen `int`s into our array, and a newer libva can name a +//! profile this build has never heard of. Decoding that into a `#[repr(i32)]` +//! Rust enum would be undefined behaviour — which is exactly how header drift +//! turns into a soundness bug. + +use std::sync::Arc; + +use crate::config::{Config, SurfaceCaps}; +use crate::display::Display; +use crate::error::{Result, check}; +use crate::sys; + +/// Generates a safe enum mirroring a C enum, plus its raw conversions. +/// +/// One table, three derived functions — so the transcription can be diffed +/// against the header in one place. +macro_rules! va_enum { + ( + $(#[$meta:meta])* + $name:ident : $raw:ty { + $( $variant:ident = $value:expr , )* + } + ) => { + $(#[$meta])* + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] + #[non_exhaustive] + pub enum $name { + $( #[allow(missing_docs)] $variant, )* + /// A value this build does not know. Carried, never guessed at. + Unknown(i32), + } + + impl $name { + /// Interpret a raw C value. Never panics, never UB. + pub fn from_raw(raw: $raw) -> Self { + match raw { + $( $value => $name::$variant, )* + other => $name::Unknown(other), + } + } + + /// The raw C value. + pub fn as_raw(self) -> $raw { + match self { + $( $name::$variant => $value, )* + $name::Unknown(other) => other, + } + } + + /// The libva identifier, e.g. `"VAProfileH264High"`. + pub fn name(self) -> &'static str { + match self { + $( $name::$variant => concat!(stringify!($name), "::", stringify!($variant)), )* + $name::Unknown(_) => concat!(stringify!($name), "::Unknown"), + } + } + } + }; +} + +va_enum! { + /// `VAProfile`, transcribed from `va.h:502-547` (libva 1.23). + Profile: sys::VAProfile { + None = -1, + MPEG2Simple = 0, + MPEG2Main = 1, + MPEG4Simple = 2, + MPEG4AdvancedSimple = 3, + MPEG4Main = 4, + H264Baseline = 5, + H264Main = 6, + H264High = 7, + VC1Simple = 8, + VC1Main = 9, + VC1Advanced = 10, + H263Baseline = 11, + JPEGBaseline = 12, + H264ConstrainedBaseline = 13, + VP8Version0_3 = 14, + H264MultiviewHigh = 15, + H264StereoHigh = 16, + HEVCMain = 17, + HEVCMain10 = 18, + VP9Profile0 = 19, + VP9Profile1 = 20, + VP9Profile2 = 21, + VP9Profile3 = 22, + HEVCMain12 = 23, + HEVCMain422_10 = 24, + HEVCMain422_12 = 25, + HEVCMain444 = 26, + HEVCMain444_10 = 27, + HEVCMain444_12 = 28, + HEVCSccMain = 29, + HEVCSccMain10 = 30, + HEVCSccMain444 = 31, + AV1Profile0 = 32, + AV1Profile1 = 33, + HEVCSccMain444_10 = 34, + Protected = 35, + H264High10 = 36, + VVCMain10 = 37, + VVCMultilayerMain10 = 38, + AV1Profile2 = 39, + H264High422 = 40, + } +} + +va_enum! { + /// `VAEntrypoint`, transcribed from `va.h:552-616` (libva 1.23). + Entrypoint: sys::VAEntrypoint { + VLD = 1, + IZZ = 2, + IDCT = 3, + MoComp = 4, + Deblocking = 5, + EncSlice = 6, + EncPicture = 7, + EncSliceLP = 8, + VideoProc = 10, + FEI = 11, + Stats = 12, + ProtectedTEEComm = 13, + ProtectedContent = 14, + } +} + +impl Profile { + /// True for the profiles the family decodes or encodes in hardware. + pub fn is_family_codec(self) -> bool { + matches!( + self, + Profile::H264ConstrainedBaseline + | Profile::H264Main + | Profile::H264High + | Profile::H264High10 + | Profile::HEVCMain + | Profile::HEVCMain10 + | Profile::VP9Profile0 + | Profile::VP9Profile2 + | Profile::AV1Profile0 + | Profile::AV1Profile2 + ) + } +} + +/// What one (profile, entrypoint) pair supports. +#[derive(Debug, Clone)] +pub struct CapEntry { + /// The profile. + pub profile: Profile, + /// The entrypoint. + pub entrypoint: Entrypoint, + /// `VAConfigAttribRTFormat` bitmask (`VA_RT_FORMAT_*`). + pub rt_formats: u32, + /// Surface geometry and pixel formats this config accepts, when the driver + /// reports them. `None` if `vaQuerySurfaceAttributes` refused the config. + pub surfaces: Option, +} + +impl CapEntry { + /// True if `rt_format` (a `VA_RT_FORMAT_*` bit) is in the mask. + pub fn supports_rt_format(&self, rt_format: u32) -> bool { + self.rt_formats & rt_format != 0 + } +} + +/// Everything the driver told us about itself. +#[derive(Debug, Clone)] +pub struct CapReport { + /// `vaQueryVendorString`. + pub vendor: String, + /// Runtime libva version. + pub version: (i32, i32), + /// One entry per supported (profile, entrypoint) pair, in driver order. + pub entries: Vec, + /// FourCCs from `vaQueryImageFormats` — the formats `vaGetImage` can produce. + pub image_formats: Vec, +} + +impl CapReport { + /// Probe a display. One `vaCreateConfig`/`vaDestroyConfig` round trip per + /// supported pair; ~15 pairs on a typical GPU, so this is cheap enough to + /// do once at startup and cache. + pub fn probe(display: &Arc) -> Result { + let entries = probe_entries(display)?; + Ok(CapReport { + vendor: display.vendor()?, + version: display.version(), + entries, + image_formats: query_image_formats(display)?, + }) + } + + /// The entry for a pair, if the driver supports it. + pub fn entry(&self, profile: Profile, entrypoint: Entrypoint) -> Option<&CapEntry> { + self.entries + .iter() + .find(|e| e.profile == profile && e.entrypoint == entrypoint) + } + + /// True if this GPU supports the pair at all. + pub fn supports(&self, profile: Profile, entrypoint: Entrypoint) -> bool { + self.entry(profile, entrypoint).is_some() + } + + /// Profiles supporting `entrypoint`, deduplicated, in driver order. + pub fn profiles_for(&self, entrypoint: Entrypoint) -> Vec { + let mut out = Vec::new(); + for e in self.entries.iter().filter(|e| e.entrypoint == entrypoint) { + if !out.contains(&e.profile) { + out.push(e.profile); + } + } + out + } +} + +fn probe_entries(display: &Arc) -> Result> { + let mut entries = Vec::new(); + for profile in query_profiles(display)? { + for entrypoint in query_entrypoints(display, profile)? { + let rt_formats = query_rt_formats(display, profile, entrypoint)?; + // Creating the config is also how the legal surface sizes are + // discovered: `vaQuerySurfaceAttributes` needs a config id. A + // driver may refuse a pair it just advertised (radeonsi does this + // for some encode entrypoints) — that is data, not an error, so it + // lands as `surfaces: None` instead of failing the whole probe. + let surfaces = match Config::new(display, profile, entrypoint, &[]) { + Ok(config) => config.surface_caps().ok(), + Err(_) => None, + }; + entries.push(CapEntry { + profile, + entrypoint, + rt_formats, + surfaces, + }); + } + } + Ok(entries) +} + +fn query_profiles(display: &Arc) -> Result> { + // SAFETY: valid display; vaMaxNumProfiles only reads driver constants. + let max = unsafe { sys::vaMaxNumProfiles(display.handle()) }; + let max = max.max(0) as usize; + let mut raw = vec![0 as sys::VAProfile; max]; + let mut count: i32 = 0; + // SAFETY: `raw` has `max` elements, which is the capacity libva promises + // never to exceed (va.h:1524). `count` is a valid out-parameter. On return + // only the first `count` entries are initialized, and only those are read. + let status = + unsafe { sys::vaQueryConfigProfiles(display.handle(), raw.as_mut_ptr(), &mut count) }; + check("vaQueryConfigProfiles", status)?; + raw.truncate(count.clamp(0, max as i32) as usize); + Ok(raw.into_iter().map(Profile::from_raw).collect()) +} + +fn query_entrypoints(display: &Arc, profile: Profile) -> Result> { + // SAFETY: valid display; reads driver constants only. + let max = unsafe { sys::vaMaxNumEntrypoints(display.handle()) }; + let max = max.max(0) as usize; + let mut raw = vec![0 as sys::VAEntrypoint; max]; + let mut count: i32 = 0; + // SAFETY: as in `query_profiles` — buffer sized by vaMaxNumEntrypoints, + // valid out-parameter, only the reported prefix is read. + let status = unsafe { + sys::vaQueryConfigEntrypoints( + display.handle(), + profile.as_raw(), + raw.as_mut_ptr(), + &mut count, + ) + }; + check("vaQueryConfigEntrypoints", status)?; + raw.truncate(count.clamp(0, max as i32) as usize); + Ok(raw.into_iter().map(Entrypoint::from_raw).collect()) +} + +fn query_rt_formats( + display: &Arc, + profile: Profile, + entrypoint: Entrypoint, +) -> Result { + let mut attrs = [sys::VAConfigAttrib { + type_: sys::VAConfigAttribRTFormat, + value: 0, + }]; + // SAFETY: `attrs` is a valid, initialized array of 1 VAConfigAttrib and the + // length passed matches. vaGetConfigAttributes writes only `value`. + let status = unsafe { + sys::vaGetConfigAttributes( + display.handle(), + profile.as_raw(), + entrypoint.as_raw(), + attrs.as_mut_ptr(), + attrs.len() as i32, + ) + }; + check("vaGetConfigAttributes", status)?; + Ok(attrs[0].value) +} + +fn query_image_formats(display: &Arc) -> Result> { + // SAFETY: valid display; reads driver constants only. + let max = unsafe { sys::vaMaxNumImageFormats(display.handle()) }; + let max = max.max(0) as usize; + let mut formats = vec![sys::VAImageFormat::default(); max]; + let mut count: i32 = 0; + // SAFETY: buffer sized by vaMaxNumImageFormats as the header requires + // (va.h:4773); `count` is a valid out-parameter; only the reported prefix + // is read afterwards. + let status = + unsafe { sys::vaQueryImageFormats(display.handle(), formats.as_mut_ptr(), &mut count) }; + check("vaQueryImageFormats", status)?; + formats.truncate(count.clamp(0, max as i32) as usize); + Ok(formats.into_iter().map(|f| f.fourcc).collect()) +} + +/// A FourCC as its four ASCII characters, for logs and reports. +pub fn fourcc_str(fourcc: u32) -> String { + fourcc + .to_le_bytes() + .iter() + .map(|&b| if b.is_ascii_graphic() { b as char } else { '?' }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn profile_roundtrip_and_unknown_arm() { + for raw in -1..=40 { + let p = Profile::from_raw(raw); + assert_eq!(p.as_raw(), raw, "roundtrip failed for {raw}"); + assert_ne!(p, Profile::Unknown(raw), "{raw} should be a known profile"); + } + // A profile from a future libva must survive, not become UB or a panic. + assert_eq!(Profile::from_raw(9_999), Profile::Unknown(9_999)); + assert_eq!(Profile::from_raw(9_999).as_raw(), 9_999); + assert_eq!(Profile::Unknown(9_999).name(), "Profile::Unknown"); + assert_eq!(Profile::H264High.name(), "Profile::H264High"); + } + + #[test] + fn entrypoint_roundtrip_and_unknown_arm() { + for raw in [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14] { + assert_eq!(Entrypoint::from_raw(raw).as_raw(), raw); + } + // 9 is unassigned in libva 1.23 and 15 is beyond the table. + assert_eq!(Entrypoint::from_raw(9), Entrypoint::Unknown(9)); + assert_eq!(Entrypoint::from_raw(15), Entrypoint::Unknown(15)); + } + + #[test] + fn fourcc_rendering() { + assert_eq!(fourcc_str(sys::VA_FOURCC_NV12), "NV12"); + assert_eq!(fourcc_str(sys::VA_FOURCC_P010), "P010"); + assert_eq!(fourcc_str(0), "????"); + } +} diff --git a/crates/ec-va/src/config.rs b/crates/ec-va/src/config.rs new file mode 100644 index 00000000..bc55ba75 --- /dev/null +++ b/crates/ec-va/src/config.rs @@ -0,0 +1,233 @@ +//! [`Config`] — a `VAConfigID` for one (profile, entrypoint) pair, plus the +//! surface geometry the driver will accept for it. + +use std::sync::Arc; + +use crate::caps::{Entrypoint, Profile}; +use crate::display::Display; +use crate::error::{Error, Result, check}; +use crate::sys; + +/// A configuration attribute, e.g. `RTFormat = VA_RT_FORMAT_YUV420`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ConfigAttrib { + /// `VAConfigAttrib*` type constant from [`crate::sys`]. + pub type_: sys::VAConfigAttribType, + /// Attribute value; meaning depends on `type_`. + pub value: u32, +} + +impl ConfigAttrib { + /// `VAConfigAttribRTFormat` with the given `VA_RT_FORMAT_*` mask. + pub fn rt_format(mask: u32) -> Self { + ConfigAttrib { + type_: sys::VAConfigAttribRTFormat, + value: mask, + } + } +} + +/// Surface constraints reported for a config. +/// +/// The minimum sizes are the reason this type exists: radeonsi rejects +/// surfaces below 64x64, and probing with a hardcoded 16x16 is how the +/// incumbent stack used to panic on this GPU. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SurfaceCaps { + /// Smallest legal surface width, if reported. + pub min_width: Option, + /// Largest legal surface width, if reported. + pub max_width: Option, + /// Smallest legal surface height, if reported. + pub min_height: Option, + /// Largest legal surface height, if reported. + pub max_height: Option, + /// Pixel formats (FourCCs) the driver will allocate for this config. + pub pixel_formats: Vec, + /// `VASurfaceAttribMemoryType` bitmask, e.g. DRM PRIME 2 support. + pub memory_types: u32, +} + +impl SurfaceCaps { + /// True if `width` x `height` is within the reported bounds. Unreported + /// bounds are treated as "no constraint". + pub fn allows(&self, width: u32, height: u32) -> bool { + self.min_width.is_none_or(|v| width >= v) + && self.max_width.is_none_or(|v| width <= v) + && self.min_height.is_none_or(|v| height >= v) + && self.max_height.is_none_or(|v| height <= v) + } + + /// True if the driver will allocate this FourCC for the config. + pub fn supports_fourcc(&self, fourcc: u32) -> bool { + self.pixel_formats.contains(&fourcc) + } +} + +/// A live `VAConfigID`. +/// +/// Held by `Arc` because a [`crate::Context`] must not outlive its config. +pub struct Config { + display: Arc, + id: sys::VAConfigID, + profile: Profile, + entrypoint: Entrypoint, +} + +impl Config { + /// Create a config for `(profile, entrypoint)` with the given attributes. + /// + /// Pass `&[]` for the driver defaults — enough for capability probing; + /// decode contexts want at least an explicit `RTFormat` so that a 10-bit + /// stream gets a 10-bit config instead of silently getting an 8-bit one. + pub fn new( + display: &Arc, + profile: Profile, + entrypoint: Entrypoint, + attribs: &[ConfigAttrib], + ) -> Result> { + let mut raw: Vec = attribs + .iter() + .map(|a| sys::VAConfigAttrib { + type_: a.type_, + value: a.value, + }) + .collect(); + let mut id: sys::VAConfigID = sys::VA_INVALID_ID; + // SAFETY: `raw` is a valid array of `raw.len()` VAConfigAttrib (a null + // pointer with len 0 is also accepted by libva, and `as_mut_ptr` on an + // empty Vec is a dangling-but-aligned pointer, which libva never + // dereferences because the count is 0). `id` is a valid out-parameter. + let status = unsafe { + sys::vaCreateConfig( + display.handle(), + profile.as_raw(), + entrypoint.as_raw(), + raw.as_mut_ptr(), + raw.len() as i32, + &mut id, + ) + }; + check("vaCreateConfig", status)?; + if id == sys::VA_INVALID_ID { + return Err(Error::Protocol( + "vaCreateConfig succeeded but returned VA_INVALID_ID".to_string(), + )); + } + Ok(Arc::new(Config { + display: Arc::clone(display), + id, + profile, + entrypoint, + })) + } + + /// Surface constraints for this config (`vaQuerySurfaceAttributes`). + pub fn surface_caps(&self) -> Result { + // Two-pass query: NULL first to learn the count, as documented at + // va.h:1855 ("it is perfectly valid to pass NULL to attrib_list"). + let mut count: u32 = 0; + // SAFETY: valid display and config id; NULL attrib_list with a valid + // count out-parameter is the documented "how many?" form. + let status = unsafe { + sys::vaQuerySurfaceAttributes( + self.display.handle(), + self.id, + std::ptr::null_mut(), + &mut count, + ) + }; + check("vaQuerySurfaceAttributes", status)?; + + let mut attrs = vec![ + sys::VASurfaceAttrib { + type_: sys::VASurfaceAttribNone, + flags: 0, + value: sys::VAGenericValue { + type_: sys::VAGenericValueTypeInteger, + value: sys::VAGenericValueUnion { i: 0 }, + }, + }; + count as usize + ]; + // SAFETY: `attrs` holds exactly `count` initialized elements, and + // `count` is what the driver just asked for. It is passed by pointer + // together with its length; libva rewrites `count` to the number + // actually written, which cannot exceed the input. + let status = unsafe { + sys::vaQuerySurfaceAttributes( + self.display.handle(), + self.id, + attrs.as_mut_ptr(), + &mut count, + ) + }; + check("vaQuerySurfaceAttributes", status)?; + attrs.truncate(count as usize); + + let mut caps = SurfaceCaps::default(); + for attr in &attrs { + if attr.flags & sys::VA_SURFACE_ATTRIB_GETTABLE == 0 { + continue; + } + // Every attribute read below is documented as an integer + // (va.h:1691-1730). A driver contradicting that is a protocol + // error, not something to reinterpret: reading the wrong union arm + // is precisely the class of bug this crate exists to avoid. + if attr.value.type_ != sys::VAGenericValueTypeInteger { + continue; + } + // SAFETY: the discriminant was just checked to be Integer, so the + // `i` arm of the union is the initialized one. + let value = unsafe { attr.value.value.i }; + match attr.type_ { + sys::VASurfaceAttribPixelFormat => caps.pixel_formats.push(value as u32), + sys::VASurfaceAttribMinWidth => caps.min_width = Some(value.max(0) as u32), + sys::VASurfaceAttribMaxWidth => caps.max_width = Some(value.max(0) as u32), + sys::VASurfaceAttribMinHeight => caps.min_height = Some(value.max(0) as u32), + sys::VASurfaceAttribMaxHeight => caps.max_height = Some(value.max(0) as u32), + sys::VASurfaceAttribMemoryType => caps.memory_types = value as u32, + _ => {} + } + } + Ok(caps) + } + + /// The profile this config was created for. + pub fn profile(&self) -> Profile { + self.profile + } + + /// The entrypoint this config was created for. + pub fn entrypoint(&self) -> Entrypoint { + self.entrypoint + } + + /// The display this config belongs to. + pub fn display(&self) -> &Arc { + &self.display + } + + pub(crate) fn id(&self) -> sys::VAConfigID { + self.id + } +} + +impl std::fmt::Debug for Config { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Config") + .field("id", &self.id) + .field("profile", &self.profile) + .field("entrypoint", &self.entrypoint) + .finish() + } +} + +impl Drop for Config { + fn drop(&mut self) { + // SAFETY: `self.id` was returned by vaCreateConfig on `self.display` + // and has not been destroyed. Contexts hold an `Arc`, so no + // context can still reference it here. + unsafe { sys::vaDestroyConfig(self.display.handle(), self.id) }; + } +} diff --git a/crates/ec-va/src/display.rs b/crates/ec-va/src/display.rs new file mode 100644 index 00000000..e02e35d9 --- /dev/null +++ b/crates/ec-va/src/display.rs @@ -0,0 +1,186 @@ +//! [`Display`] — an initialized `VADisplay` on a DRM render node. + +use std::ffi::CStr; +use std::fs::File; +use std::os::fd::AsRawFd; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use crate::error::{Error, Result, check}; +use crate::sys; + +/// An initialized VA display, owning both the DRM file descriptor and the +/// `VADisplay` derived from it. +/// +/// Everything else in this crate holds an `Arc`, so the display is +/// terminated only after the last surface, config, context and buffer is gone — +/// the ordering libva requires, enforced by the type system rather than by +/// documentation. +pub struct Display { + /// Raw `VADisplay`. Valid until [`Drop`] calls `vaTerminate`. + handle: sys::VADisplay, + /// The render node. Must outlive `handle`: libva does not dup the fd. + node: File, + path: PathBuf, + version: (i32, i32), +} + +// SAFETY: libva's dispatch layer (`va.c`) and the Mesa VA driver both take an +// internal lock per display around every entry point used here, so a +// `VADisplay` may be used from any thread and from several threads at once. +// The `File` and `PathBuf` fields are themselves `Send + Sync`. This mirrors +// what every VA-API consumer (ffmpeg, GStreamer, cros-libva) relies on. +// +// Note the narrower claim this crate actually needs: `&Display` is only ever +// used to *call* libva, never to hand out interior pointers. +unsafe impl Send for Display {} +// SAFETY: see above. +unsafe impl Sync for Display {} + +impl Display { + /// Open the first usable DRM render node (`/dev/dri/renderD128` upwards). + /// + /// Render nodes are used rather than card nodes: they need no DRM master + /// and no display server, which is what a headless encode/decode pipeline + /// wants. + pub fn open() -> Result> { + let mut last: Option = None; + // 128..=143 is the kernel's render-node numbering (16 GPUs is plenty). + for n in 128..=143u32 { + let path = PathBuf::from(format!("/dev/dri/renderD{n}")); + if !path.exists() { + continue; + } + match Display::open_path(&path) { + Ok(display) => return Ok(display), + Err(e) => last = Some(e), + } + } + Err(last.unwrap_or(Error::NoDevice)) + } + + /// Open a specific DRM node, e.g. `/dev/dri/renderD128`. + /// + /// The node is opened **read-write**, and that is not a detail: with a + /// read-only fd radeonsi 26.1 fails `amdgpu_bo_cpu_map` and then segfaults + /// *inside* `vaInitialize`, before it can return a status this crate could + /// turn into an error. Verified on this machine (gfx1200, Mesa 26.1.6). + pub fn open_path(path: &Path) -> Result> { + let node = File::options() + .read(true) + .write(true) + .open(path) + .map_err(|source| Error::Drm { + path: path.display().to_string(), + source, + })?; + + // SAFETY: `node` is an open DRM fd that lives as long as the returned + // Display (it is moved into it below, and closed only after + // vaTerminate in Drop). vaGetDisplayDRM does not take ownership of the + // fd and returns NULL on failure, which is checked. + let handle = unsafe { sys::vaGetDisplayDRM(node.as_raw_fd()) }; + if handle.is_null() { + return Err(Error::va( + "vaGetDisplayDRM", + sys::VA_STATUS_ERROR_OPERATION_FAILED, + )); + } + + let mut major: i32 = 0; + let mut minor: i32 = 0; + // SAFETY: `handle` is a non-NULL VADisplay from vaGetDisplayDRM; the + // two out-parameters are valid, aligned, initialized `int`s that + // outlive the call. + let status = unsafe { sys::vaInitialize(handle, &mut major, &mut minor) }; + if let Err(e) = check("vaInitialize", status) { + // libva allocates display state inside vaGetDisplayDRM, so a failed + // initialize still has to be terminated or that state leaks. This + // is what ffmpeg's vaapi_device_create does on its failure path. + // + // SAFETY: `handle` is still a valid (if uninitialized) VADisplay; + // vaTerminate accepts exactly this state. + unsafe { sys::vaTerminate(handle) }; + return Err(e); + } + + // Runtime drift guard. The struct layouts in `sys` are transcribed from + // the 1.23 headers; talking to an older runtime would be guesswork. + if major != crate::MIN_VA_MAJOR || minor < crate::MIN_VA_MINOR { + // SAFETY: initialize succeeded, so terminating is required and valid. + unsafe { sys::vaTerminate(handle) }; + return Err(Error::Version { major, minor }); + } + + Ok(Arc::new(Display { + handle, + node, + path: path.to_path_buf(), + version: (major, minor), + })) + } + + /// The raw handle, for the rest of the crate's FFI calls. + pub(crate) fn handle(&self) -> sys::VADisplay { + self.handle + } + + /// Runtime libva version as `(major, minor)`, from `vaInitialize`. + pub fn version(&self) -> (i32, i32) { + self.version + } + + /// The DRM node this display was opened on. + pub fn device_path(&self) -> &Path { + &self.path + } + + /// The raw DRM render-node fd. Borrowed, never closed by the caller. + pub fn drm_fd(&self) -> std::os::fd::BorrowedFd<'_> { + // `File` guarantees the fd is open for as long as `self` lives. + std::os::fd::AsFd::as_fd(&self.node) + } + + /// Driver vendor string, e.g. `"Mesa Gallium driver 26.1.6 for AMD ..."`. + pub fn vendor(&self) -> Result { + // SAFETY: `self.handle` is initialized and valid for the lifetime of + // `self`. The returned pointer is owned by the driver and stays valid + // until vaTerminate, i.e. strictly longer than this borrow; the string + // is copied before returning. + let ptr = unsafe { sys::vaQueryVendorString(self.handle) }; + if ptr.is_null() { + return Err(Error::Protocol( + "vaQueryVendorString returned NULL".to_string(), + )); + } + // SAFETY: non-NULL, NUL-terminated, driver-owned static string. + Ok(unsafe { CStr::from_ptr(ptr) } + .to_string_lossy() + .into_owned()) + } + + /// `vaDisplayIsValid`, mostly useful in tests. + pub fn is_valid(&self) -> bool { + // SAFETY: `self.handle` is a valid VADisplay for the lifetime of `self`. + unsafe { sys::vaDisplayIsValid(self.handle) != 0 } + } +} + +impl std::fmt::Debug for Display { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Display") + .field("path", &self.path) + .field("version", &self.version) + .finish_non_exhaustive() + } +} + +impl Drop for Display { + fn drop(&mut self) { + // SAFETY: `self.handle` was initialized in `open_path` and no child + // object can still be alive: every one of them holds an `Arc`, + // so this runs only after the last of them was dropped. `self.node` is + // closed after this, as libva requires. + unsafe { sys::vaTerminate(self.handle) }; + } +} diff --git a/crates/ec-va/src/error.rs b/crates/ec-va/src/error.rs new file mode 100644 index 00000000..89ab27aa --- /dev/null +++ b/crates/ec-va/src/error.rs @@ -0,0 +1,148 @@ +//! Typed errors. Every `VAStatus` that is not `VA_STATUS_SUCCESS` becomes an +//! [`Error::Va`] carrying the failing entry point, the raw status and libva's +//! own description of it — a bare status number in a log is a bug report +//! waiting to happen. + +use std::ffi::CStr; +use std::fmt; + +use crate::sys; + +/// Result alias for this crate. +pub type Result = std::result::Result; + +/// Everything that can go wrong between here and the driver. +#[derive(Debug)] +#[non_exhaustive] +pub enum Error { + /// A libva entry point returned a failing `VAStatus`. + Va { + /// The libva function that failed, e.g. `"vaCreateConfig"`. + op: &'static str, + /// The raw `VAStatus`. + status: sys::VAStatus, + /// `vaErrorStr(status)`. + message: String, + }, + /// Opening a DRM render node failed. + Drm { + /// The device path that was tried. + path: String, + /// The underlying `open(2)` failure. + source: std::io::Error, + }, + /// No `/dev/dri/renderD*` node could be opened as a VA display. + NoDevice, + /// The runtime libva is older than the ABI this crate transcribes. + /// + /// This is the drift guard: the struct layouts in [`crate::sys`] are + /// compile-time transcriptions of the 1.23 headers, so refusing to talk to + /// an older runtime is the only sound answer. + Version { + /// Runtime major version reported by `vaInitialize`. + major: i32, + /// Runtime minor version reported by `vaInitialize`. + minor: i32, + }, + /// The driver returned something this FFI cannot interpret. + /// + /// Not a bitstream error and not a status code — a shape violation, e.g. a + /// surface attribute whose value type contradicts its documented type. + Protocol(String), +} + +impl Error { + /// Build an [`Error::Va`] for `op`, looking the status string up in libva. + pub(crate) fn va(op: &'static str, status: sys::VAStatus) -> Self { + Error::Va { + op, + status, + message: status_str(status), + } + } + + /// The raw `VAStatus`, when this error came from a libva call. + pub fn status(&self) -> Option { + match self { + Error::Va { status, .. } => Some(*status), + _ => None, + } + } +} + +/// `vaErrorStr` as an owned Rust string. +pub(crate) fn status_str(status: sys::VAStatus) -> String { + // SAFETY: `vaErrorStr` is documented (va.h:401) to return a pointer to a + // static, NUL-terminated english description for any input value — + // unknown codes map to a fallback string rather than NULL. It reads no + // global state we mutate, so it is safe to call at any time, including + // before vaInitialize. The pointer is static, so building a CStr from it + // and copying is sound; the copy outlives the borrow. + let ptr = unsafe { sys::vaErrorStr(status) }; + if ptr.is_null() { + return format!("VAStatus 0x{status:08x}"); + } + // SAFETY: non-NULL and NUL-terminated per the contract above. + unsafe { CStr::from_ptr(ptr) } + .to_string_lossy() + .into_owned() +} + +/// Turn a `VAStatus` into a `Result`, tagging it with the entry point name. +pub(crate) fn check(op: &'static str, status: sys::VAStatus) -> Result<()> { + if status == sys::VA_STATUS_SUCCESS { + Ok(()) + } else { + Err(Error::va(op, status)) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Va { + op, + status, + message, + } => write!(f, "{op} failed: {message} (VAStatus 0x{status:08x})"), + Error::Drm { path, source } => write!(f, "opening DRM node {path}: {source}"), + Error::NoDevice => write!(f, "no usable /dev/dri/renderD* VA display"), + Error::Version { major, minor } => write!( + f, + "libva {major}.{minor} is older than the {}.{} ABI this build transcribes", + crate::MIN_VA_MAJOR, + crate::MIN_VA_MINOR + ), + Error::Protocol(what) => write!(f, "libva returned an uninterpretable value: {what}"), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Drm { source, .. } => Some(source), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn status_strings_come_from_libva() { + assert_eq!(status_str(sys::VA_STATUS_SUCCESS), "success (no error)"); + // Any unknown code must still produce a string, never a panic or NULL deref. + assert!(!status_str(0x7fff_0000).is_empty()); + } + + #[test] + fn check_maps_success_and_failure() { + assert!(check("vaFake", sys::VA_STATUS_SUCCESS).is_ok()); + let err = check("vaFake", sys::VA_STATUS_ERROR_UNIMPLEMENTED).unwrap_err(); + assert_eq!(err.status(), Some(sys::VA_STATUS_ERROR_UNIMPLEMENTED)); + assert!(err.to_string().contains("vaFake")); + } +} diff --git a/crates/ec-va/src/lib.rs b/crates/ec-va/src/lib.rs new file mode 100644 index 00000000..2b86750a --- /dev/null +++ b/crates/ec-va/src/lib.rs @@ -0,0 +1,65 @@ +//! Minimal libva (VA-API) bindings and a safe layer over them. +//! +//! This is the hardware-video foundation of the `edith_codecs` family: `ec-hw` +//! builds stateless VA-API decoders and encoders on top of it, and nothing else +//! in the family talks to libva directly. +//! +//! # Shape +//! +//! * [`sys`] — the entire FFI surface, hand-written, one screenful per concern. +//! Every ABI assumption is stated there and checked by a `const` assertion +//! against numbers printed by `crates/ec-va/abi-probe.c`. +//! * Everything else is safe: [`Display`], [`Config`], [`Surface`], [`Context`] +//! and [`Buffer`] are RAII handles that destroy exactly what they created, in +//! the order libva requires (each child holds an `Arc` of its parent, so the +//! ordering is a borrow-checker fact rather than a review comment). +//! * [`Picture`] encodes the `begin -> render -> end -> sync` protocol as a +//! typestate machine, so submitting out of order does not compile. +//! +//! # Version policy +//! +//! Built against libva **1.23** headers and refuses older runtimes with +//! [`Error::Version`]. The alternative — assuming a struct layout and finding +//! out at runtime — is what broke the previous generation of VA-API bindings +//! when 1.23 shifted their generated definitions. +//! +//! # Example +//! +//! ```no_run +//! use ec_va::{CapReport, Display, Surface, SurfaceSpec}; +//! use ec_va::caps::{Entrypoint, Profile}; +//! +//! let display = Display::open()?; +//! let caps = CapReport::probe(&display)?; +//! assert!(caps.supports(Profile::H264Main, Entrypoint::VLD)); +//! +//! let surfaces = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 8)?; +//! # Ok::<(), ec_va::Error>(()) +//! ``` + +#![deny(missing_docs)] +#![deny(unsafe_op_in_unsafe_fn)] + +pub mod caps; +pub mod config; +pub mod display; +pub mod error; +pub mod picture; +pub mod surface; +pub mod sys; + +pub use caps::{CapEntry, CapReport, Entrypoint, Profile, fourcc_str}; +pub use config::{Config, ConfigAttrib, SurfaceCaps}; +pub use display::Display; +pub use error::{Error, Result}; +pub use picture::{ + Buffer, Context, Ended, MappedBuffer, New, Picture, PictureState, Rendering, Synced, +}; +pub use surface::{ + Image, MappedImage, PrimeLayer, PrimeObject, PrimeSurface, Surface, SurfaceSpec, +}; + +/// Major libva version this crate's ABI transcription targets. +pub const MIN_VA_MAJOR: i32 = 1; +/// Minimum libva minor version accepted at runtime. +pub const MIN_VA_MINOR: i32 = 23; diff --git a/crates/ec-va/src/picture.rs b/crates/ec-va/src/picture.rs new file mode 100644 index 00000000..bdbf2b30 --- /dev/null +++ b/crates/ec-va/src/picture.rs @@ -0,0 +1,547 @@ +//! [`Context`], [`Buffer`] and the [`Picture`] typestate machine. +//! +//! VA-API's submission protocol is a state machine: `vaBeginPicture` -> +//! N x `vaRenderPicture` -> `vaEndPicture` -> `vaSyncSurface`. Calling those out +//! of order is a driver-defined mess (at best an error, at worst a GPU hang), +//! and it is not something a code review reliably catches. +//! +//! So the order is in the type system. Each transition consumes the picture and +//! returns it in the next state; there is no method to skip a step and no way +//! to name an intermediate state that was never reached: +//! +//! ```text +//! Picture --begin()--> Picture --render(buf)--> Picture +//! --end()-------> Picture +//! --sync()------> Picture +//! ``` +//! +//! The legal walk compiles: +//! +//! ```no_run +//! # use ec_va::{Buffer, Context, Picture, Surface}; +//! # fn demo(context: &std::sync::Arc, target: std::sync::Arc, buffer: Buffer) +//! # -> ec_va::Result<()> { +//! let surface = Picture::new(context, target) +//! .begin()? +//! .render(buffer)? +//! .end()? +//! .sync()? +//! .into_surface(); +//! # Ok(()) +//! # } +//! ``` +//! +//! Ordering violations are compile errors (`E0599`: the method does not exist +//! on that state): +//! +//! ```compile_fail,E0599 +//! # use ec_va::{Context, Picture, Surface}; +//! # fn demo(context: &std::sync::Arc, target: std::sync::Arc) { +//! let picture = Picture::new(context, target); +//! // ERROR: no method `end` on `Picture` — begin() was never called. +//! let ended = picture.end().unwrap(); +//! # } +//! ``` +//! +//! ```compile_fail,E0599 +//! # use ec_va::{Context, Picture, Surface}; +//! # fn demo(context: &std::sync::Arc, target: std::sync::Arc) { +//! let picture = Picture::new(context, target).begin().unwrap(); +//! // ERROR: no method `sync` on `Picture` — end() must come first. +//! let synced = picture.sync().unwrap(); +//! # } +//! ``` +//! +//! ```compile_fail,E0599 +//! # use ec_va::{Buffer, Context, Picture, Surface}; +//! # fn demo(context: &std::sync::Arc, target: std::sync::Arc, buffer: Buffer) { +//! let picture = Picture::new(context, target).begin().unwrap().end().unwrap(); +//! // ERROR: no method `render` on `Picture` — the picture is closed. +//! let rendered = picture.render(buffer).unwrap(); +//! # } +//! ``` +//! +//! ```compile_fail,E0599 +//! # use ec_va::{Context, Picture, Surface}; +//! # fn demo(context: &std::sync::Arc, target: std::sync::Arc) { +//! let picture = Picture::new(context, target).begin().unwrap(); +//! // ERROR: no method `begin` on `Picture` — no double submission. +//! let again = picture.begin().unwrap(); +//! # } +//! ``` + +use std::marker::PhantomData; +use std::sync::Arc; + +use crate::config::Config; +use crate::display::Display; +use crate::error::{Error, Result, check}; +use crate::surface::Surface; +use crate::sys; + +/// A live `VAContextID`. +/// +/// Holds its config and render targets, so neither can be destroyed while the +/// context still references them — the ordering libva demands. +pub struct Context { + display: Arc, + config: Arc, + id: sys::VAContextID, + _targets: Vec>, + width: u32, + height: u32, +} + +impl Context { + /// Create a context for `config` at `width` x `height`. + /// + /// `targets` are the surfaces the driver may render into. `flags` is + /// usually [`sys::VA_PROGRESSIVE`]. + pub fn new( + config: &Arc, + width: u32, + height: u32, + flags: i32, + targets: &[Arc], + ) -> Result> { + let display = Arc::clone(config.display()); + let mut ids: Vec = targets.iter().map(|s| s.id()).collect(); + let mut id: sys::VAContextID = sys::VA_INVALID_ID; + // SAFETY: `ids` is a valid array of `ids.len()` surface ids, all live + // (their `Arc`s are cloned into the context below, so they outlive it); + // `id` is a valid out-parameter. libva copies the target array. + let status = unsafe { + sys::vaCreateContext( + display.handle(), + config.id(), + width as i32, + height as i32, + flags, + ids.as_mut_ptr(), + ids.len() as i32, + &mut id, + ) + }; + check("vaCreateContext", status)?; + if id == sys::VA_INVALID_ID { + return Err(Error::Protocol( + "vaCreateContext succeeded but returned VA_INVALID_ID".to_string(), + )); + } + Ok(Arc::new(Context { + display, + config: Arc::clone(config), + id, + _targets: targets.to_vec(), + width, + height, + })) + } + + /// The config this context was created from. + pub fn config(&self) -> &Arc { + &self.config + } + + /// The display this context belongs to. + pub fn display(&self) -> &Arc { + &self.display + } + + /// Coded size the context was created with. + pub fn size(&self) -> (u32, u32) { + (self.width, self.height) + } +} + +impl std::fmt::Debug for Context { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Context") + .field("id", &self.id) + .field("size", &(self.width, self.height)) + .field("profile", &self.config.profile()) + .finish() + } +} + +impl Drop for Context { + fn drop(&mut self) { + // SAFETY: `self.id` is live on `self.display`. Buffers hold an + // `Arc` and pictures hold buffers, so none can be alive here; + // the render targets and config are released after this call. + unsafe { sys::vaDestroyContext(self.display.handle(), self.id) }; + } +} + +/// A live `VABufferID` belonging to a context. +pub struct Buffer { + context: Arc, + id: sys::VABufferID, + type_: sys::VABufferType, +} + +impl Buffer { + /// Create a buffer holding a copy of `data`. + /// + /// This is the parameter-buffer path: picture/slice parameters and slice + /// data are copied into driver memory, so `data` need not outlive the call. + pub fn from_bytes( + context: &Arc, + type_: sys::VABufferType, + data: &[u8], + ) -> Result { + if data.is_empty() { + return Err(Error::Protocol(format!( + "refusing to create an empty VA buffer of type {type_}" + ))); + } + let mut id: sys::VABufferID = sys::VA_INVALID_ID; + // SAFETY: libva copies `size * num_elements` = `data.len()` bytes out + // of `data` during the call and never retains the pointer (va.h:3820). + // The cast to `*mut c_void` is sound because libva only reads it: the + // `data` parameter is documented as `in`. + let status = unsafe { + sys::vaCreateBuffer( + context.display.handle(), + context.id, + type_, + data.len() as u32, + 1, + data.as_ptr() as *mut std::ffi::c_void, + &mut id, + ) + }; + check("vaCreateBuffer", status)?; + Buffer::wrap(context, id, type_) + } + + /// Create a buffer holding a copy of one plain-old-data parameter struct. + /// + /// # Safety + /// + /// `T` must be the exact `#[repr(C)]` parameter struct libva expects for + /// `type_` (e.g. `VAPictureParameterBufferH264` for + /// `VAPictureParameterBufferType`) and must contain no padding-sensitive + /// invariants: the driver reads `size_of::()` bytes of it verbatim. + pub unsafe fn from_param( + context: &Arc, + type_: sys::VABufferType, + param: &T, + ) -> Result { + // SAFETY: `T: Copy` with the caller's guarantee that it is a repr(C) + // POD parameter struct, so its bytes are a valid representation to + // hand to the driver; the slice covers exactly one `T` and is only + // read during the call below. + let bytes = + unsafe { std::slice::from_raw_parts((param as *const T).cast::(), size_of::()) }; + Buffer::from_bytes(context, type_, bytes) + } + + /// Allocate an empty buffer of `size` bytes to be filled via [`Buffer::map`]. + /// + /// This is the coded-output path: `VAEncCodedBufferType` buffers are + /// written by the GPU and read back after sync. + pub fn allocate(context: &Arc, type_: sys::VABufferType, size: u32) -> Result { + let mut id: sys::VABufferID = sys::VA_INVALID_ID; + // SAFETY: a NULL `data` pointer is the documented "allocate only" form + // (va.h:3826); `id` is a valid out-parameter. + let status = unsafe { + sys::vaCreateBuffer( + context.display.handle(), + context.id, + type_, + size, + 1, + std::ptr::null_mut(), + &mut id, + ) + }; + check("vaCreateBuffer", status)?; + Buffer::wrap(context, id, type_) + } + + fn wrap( + context: &Arc, + id: sys::VABufferID, + type_: sys::VABufferType, + ) -> Result { + if id == sys::VA_INVALID_ID { + return Err(Error::Protocol( + "vaCreateBuffer succeeded but returned VA_INVALID_ID".to_string(), + )); + } + Ok(Buffer { + context: Arc::clone(context), + id, + type_, + }) + } + + /// Map the buffer for reading or writing. Unmaps on drop. + pub fn map(&mut self) -> Result> { + let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut(); + // SAFETY: `self.id` is a live buffer on this display; `ptr` is a valid + // out-parameter. libva keeps the mapping valid until vaUnmapBuffer, + // which `MappedBuffer::drop` calls exactly once. + let status = + unsafe { sys::vaMapBuffer(self.context.display.handle(), self.id, &raw mut ptr) }; + check("vaMapBuffer", status)?; + if ptr.is_null() { + // SAFETY: the map reported success, so it must be undone even + // though the returned pointer is unusable. + unsafe { sys::vaUnmapBuffer(self.context.display.handle(), self.id) }; + return Err(Error::Protocol( + "vaMapBuffer succeeded but returned NULL".to_string(), + )); + } + Ok(MappedBuffer { + buffer: self, + base: ptr.cast::(), + }) + } + + /// The buffer id. + pub fn id(&self) -> sys::VABufferID { + self.id + } + + /// The `VABufferType` this buffer was created with. + pub fn buffer_type(&self) -> sys::VABufferType { + self.type_ + } +} + +impl std::fmt::Debug for Buffer { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Buffer") + .field("id", &self.id) + .field("type", &self.type_) + .finish() + } +} + +impl Drop for Buffer { + fn drop(&mut self) { + // SAFETY: `self.id` is live and belongs to `self.context`'s display, + // which outlives it (the `Arc` is held here). Mappings borrow + // `&mut self`, so none can be outstanding. + unsafe { sys::vaDestroyBuffer(self.context.display.handle(), self.id) }; + } +} + +/// A mapped [`Buffer`]. Unmaps on drop. +/// +/// The length of the mapping is not reported by libva for parameter buffers, +/// so access goes through explicit sizes the caller already knows (for coded +/// buffers, through the `VACodedBufferSegment` list, which `ec-hw` parses). +pub struct MappedBuffer<'a> { + buffer: &'a mut Buffer, + base: *mut u8, +} + +impl MappedBuffer<'_> { + /// The raw mapped pointer. + /// + /// # Safety + /// + /// The caller must not read or write beyond the size the buffer was created + /// with, and must not keep the pointer past this guard's lifetime. + pub unsafe fn as_ptr(&self) -> *mut u8 { + self.base + } + + /// The first `len` bytes of the mapping. + /// + /// # Safety + /// + /// `len` must not exceed the size the buffer was created with. + pub unsafe fn as_slice(&self, len: usize) -> &[u8] { + // SAFETY: the caller guarantees `len` is within the allocation, and the + // mapping is live for as long as this guard exists. + unsafe { std::slice::from_raw_parts(self.base, len) } + } + + /// The first `len` bytes of the mapping, mutably. + /// + /// # Safety + /// + /// `len` must not exceed the size the buffer was created with. + pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [u8] { + // SAFETY: as `as_slice`, plus `&mut self` makes this the only live + // reference into the mapping. + unsafe { std::slice::from_raw_parts_mut(self.base, len) } + } +} + +impl Drop for MappedBuffer<'_> { + fn drop(&mut self) { + // SAFETY: mapped in `Buffer::map`, unmapped exactly once here; the + // buffer is still alive because this guard borrows it. + unsafe { sys::vaUnmapBuffer(self.buffer.context.display.handle(), self.buffer.id) }; + } +} + +mod sealed { + /// Prevents downstream crates from inventing picture states. + pub trait Sealed {} +} + +/// Marker trait for the [`Picture`] states. +pub trait PictureState: sealed::Sealed {} + +macro_rules! picture_states { + ($($(#[$meta:meta])* $name:ident),* $(,)?) => { + $( + $(#[$meta])* + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub struct $name; + impl sealed::Sealed for $name {} + impl PictureState for $name {} + )* + }; +} + +picture_states! { + /// Nothing submitted yet. + New, + /// `vaBeginPicture` done; buffers may be rendered. + Rendering, + /// `vaEndPicture` done; the GPU is working on it. + Ended, + /// `vaSyncSurface` done; the target surface is readable. + Synced, +} + +/// One picture submission, parameterised by how far through the VA protocol it is. +/// +/// See the [module docs](self) for the state diagram and the compile-fail +/// examples. +pub struct Picture { + context: Arc, + target: Arc, + /// Kept alive until the picture is dropped: the driver may reference + /// parameter buffers until the submission completes. + buffers: Vec, + _state: PhantomData, +} + +impl Picture { + /// The surface this picture renders into. + pub fn target(&self) -> &Arc { + &self.target + } + + /// The context this picture is submitted to. + pub fn context(&self) -> &Arc { + &self.context + } + + fn transition(self) -> Picture { + Picture { + context: self.context, + target: self.target, + buffers: self.buffers, + _state: PhantomData, + } + } +} + +impl Picture { + /// Start a picture targeting `target`. No driver call yet. + pub fn new(context: &Arc, target: Arc) -> Picture { + Picture { + context: Arc::clone(context), + target, + buffers: Vec::new(), + _state: PhantomData, + } + } + + /// `vaBeginPicture`. + /// + /// On failure the picture is consumed and the context is left with no + /// picture in flight; the next `begin` starts cleanly. + pub fn begin(self) -> Result> { + // SAFETY: live context and surface ids, both kept alive by the `Arc`s + // this picture holds. + let status = unsafe { + sys::vaBeginPicture( + self.context.display.handle(), + self.context.id, + self.target.id(), + ) + }; + check("vaBeginPicture", status)?; + Ok(self.transition()) + } +} + +impl Picture { + /// `vaRenderPicture` with one buffer, which the picture then owns. + pub fn render(self, buffer: Buffer) -> Result> { + self.render_all(vec![buffer]) + } + + /// `vaRenderPicture` with several buffers in one call. + pub fn render_all(mut self, buffers: Vec) -> Result> { + if buffers.is_empty() { + return Ok(self); + } + let mut ids: Vec = buffers.iter().map(|b| b.id).collect(); + // SAFETY: `ids` is a valid array of `ids.len()` live buffer ids; the + // buffers themselves are moved into `self.buffers` below, so they + // outlive the submission. libva does not retain the id array. + let status = unsafe { + sys::vaRenderPicture( + self.context.display.handle(), + self.context.id, + ids.as_mut_ptr(), + ids.len() as i32, + ) + }; + // Keep the buffers alive regardless of the outcome: on failure the + // driver may still hold references until the context is torn down. + self.buffers.extend(buffers); + check("vaRenderPicture", status)?; + Ok(self) + } + + /// `vaEndPicture` — hand the picture to the GPU. + pub fn end(self) -> Result> { + // SAFETY: live context id; a picture is in flight because this method + // exists only on `Picture`, i.e. after a successful begin. + let status = unsafe { sys::vaEndPicture(self.context.display.handle(), self.context.id) }; + check("vaEndPicture", status)?; + Ok(self.transition()) + } +} + +impl Picture { + /// `vaSyncSurface` — block until the target surface is complete. + pub fn sync(self) -> Result> { + self.target.sync()?; + Ok(self.transition()) + } +} + +impl Picture { + /// The completed surface, ready to export or map. + pub fn into_surface(self) -> Arc { + self.target + } + + /// The buffers submitted with this picture, e.g. to read a coded buffer. + pub fn buffers_mut(&mut self) -> &mut [Buffer] { + &mut self.buffers + } +} + +impl std::fmt::Debug for Picture { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Picture") + .field("state", &std::any::type_name::()) + .field("target", &self.target.id()) + .field("buffers", &self.buffers.len()) + .finish() + } +} diff --git a/crates/ec-va/src/surface.rs b/crates/ec-va/src/surface.rs new file mode 100644 index 00000000..8fc2f04f --- /dev/null +++ b/crates/ec-va/src/surface.rs @@ -0,0 +1,567 @@ +//! [`Surface`] — GPU-side picture storage, plus the two ways of getting at its +//! contents: DRM PRIME export (zero-copy handoff) and image mapping (readback). + +use std::os::fd::{FromRawFd, OwnedFd}; +use std::sync::Arc; + +use crate::display::Display; +use crate::error::{Error, Result, check}; +use crate::sys; + +/// What kind of surface to allocate. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SurfaceSpec { + /// `VA_RT_FORMAT_*` for the config this surface will be used with. + pub rt_format: u32, + /// Exact pixel layout (FourCC). `None` lets the driver choose. + pub fourcc: Option, + /// Width in pixels. Must satisfy [`crate::SurfaceCaps::allows`]. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// `VA_SURFACE_ATTRIB_USAGE_HINT_*` bitmask; drivers use it to pick tiling. + pub usage_hint: u32, +} + +impl SurfaceSpec { + /// 8-bit 4:2:0 NV12, the decode output format of every codec in the family. + pub fn nv12(width: u32, height: u32) -> Self { + SurfaceSpec { + rt_format: sys::VA_RT_FORMAT_YUV420, + fourcc: Some(sys::VA_FOURCC_NV12), + width, + height, + usage_hint: sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC, + } + } + + /// 10-bit 4:2:0 P010, for HEVC Main10 / VP9 Profile 2 / AV1 10-bit. + /// + /// The RT format is derived from the stream's bit depth, never hardcoded to + /// 8-bit: an 8-bit context on a 10-bit stream is the incumbent defect this + /// constructor exists to make impossible to write by accident. + pub fn p010(width: u32, height: u32) -> Self { + SurfaceSpec { + rt_format: sys::VA_RT_FORMAT_YUV420_10, + fourcc: Some(sys::VA_FOURCC_P010), + width, + height, + usage_hint: sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC, + } + } + + /// Set the usage hint (`VA_SURFACE_ATTRIB_USAGE_HINT_*`). + pub fn with_usage_hint(mut self, hint: u32) -> Self { + self.usage_hint = hint; + self + } +} + +/// A live `VASurfaceID`. +/// +/// Surfaces may only be destroyed after every context using them is gone; +/// [`crate::Context`] therefore holds `Arc` for its render targets and +/// this `Drop` cannot run too early. +pub struct Surface { + display: Arc, + id: sys::VASurfaceID, + spec: SurfaceSpec, +} + +impl Surface { + /// Allocate a single surface. + pub fn create(display: &Arc, spec: &SurfaceSpec) -> Result> { + let mut pool = Surface::create_pool(display, spec, 1)?; + Ok(pool.pop().expect("create_pool(1) returns one surface")) + } + + /// Allocate `count` surfaces in one driver call. + /// + /// Each returned surface owns its own id and destroys exactly that id, so a + /// pool can be torn down incrementally as frames are released. + pub fn create_pool( + display: &Arc, + spec: &SurfaceSpec, + count: usize, + ) -> Result>> { + if count == 0 { + return Ok(Vec::new()); + } + let mut attribs: Vec = Vec::with_capacity(2); + if let Some(fourcc) = spec.fourcc { + attribs.push(int_attrib(sys::VASurfaceAttribPixelFormat, fourcc as i32)); + } + if spec.usage_hint != sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC { + attribs.push(int_attrib( + sys::VASurfaceAttribUsageHint, + spec.usage_hint as i32, + )); + } + + let mut ids = vec![sys::VA_INVALID_SURFACE; count]; + // SAFETY: `ids` has room for exactly `count` surface ids and `attribs` + // for exactly `attribs.len()` attributes; both counts are passed + // alongside. libva writes only within those bounds and does not retain + // either pointer past the call. + let status = unsafe { + sys::vaCreateSurfaces( + display.handle(), + spec.rt_format, + spec.width, + spec.height, + ids.as_mut_ptr(), + count as u32, + attribs.as_mut_ptr(), + attribs.len() as u32, + ) + }; + check("vaCreateSurfaces", status)?; + + if ids.contains(&sys::VA_INVALID_SURFACE) { + // Destroy whatever did get created rather than leaking it. + let mut good: Vec = ids + .iter() + .copied() + .filter(|&id| id != sys::VA_INVALID_SURFACE) + .collect(); + if !good.is_empty() { + // SAFETY: every id in `good` was returned by the successful + // vaCreateSurfaces above and has not been destroyed yet. + unsafe { + sys::vaDestroySurfaces(display.handle(), good.as_mut_ptr(), good.len() as i32) + }; + } + return Err(Error::Protocol( + "vaCreateSurfaces succeeded but left VA_INVALID_SURFACE in the array".to_string(), + )); + } + + Ok(ids + .into_iter() + .map(|id| { + Arc::new(Surface { + display: Arc::clone(display), + id, + spec: *spec, + }) + }) + .collect()) + } + + /// Block until every operation targeting this surface has completed. + pub fn sync(&self) -> Result<()> { + // SAFETY: `self.id` is live for the lifetime of `self` on + // `self.display`. vaSyncSurface only blocks; it mutates no Rust state. + let status = unsafe { sys::vaSyncSurface(self.display.handle(), self.id) }; + check("vaSyncSurface", status) + } + + /// Export as DRM PRIME (`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`). + /// + /// `flags` is a combination of `VA_EXPORT_SURFACE_*`. This performs no + /// synchronisation: call [`Surface::sync`] first if the contents will be + /// read. + pub fn export_prime(&self, flags: u32) -> Result { + let mut desc = sys::VADRMPRIMESurfaceDescriptor::default(); + // SAFETY: `desc` is a valid, fully initialized (zeroed) descriptor of + // exactly the type `VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2` selects + // (va_drmcommon.h:96-99); passing any other mem_type with this pointer + // would be the unsound case, which is why mem_type is not a parameter. + let status = unsafe { + sys::vaExportSurfaceHandle( + self.display.handle(), + self.id, + sys::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, + flags, + (&raw mut desc).cast(), + ) + }; + check("vaExportSurfaceHandle", status)?; + PrimeSurface::from_raw(desc) + } + + /// A directly mapped view of the surface's own memory (`vaDeriveImage`). + /// + /// Falls back is the caller's business: drivers may refuse to derive (tiled + /// or compressed layouts), reporting `VA_STATUS_ERROR_OPERATION_FAILED`. + pub fn derive_image(self: &Arc) -> Result { + let mut image = sys::VAImage::default(); + // SAFETY: valid display and surface id; `image` is a valid + // out-parameter that libva fully overwrites on success. + let status = unsafe { sys::vaDeriveImage(self.display.handle(), self.id, &raw mut image) }; + check("vaDeriveImage", status)?; + Ok(Image { + display: Arc::clone(&self.display), + _surface: Some(Arc::clone(self)), + raw: image, + }) + } + + /// Copy the surface into an [`Image`] created with [`Image::create`]. + /// + /// The readback path for drivers that refuse [`Surface::derive_image`]. + /// The image must be at least as large as the requested region. + pub fn read_into( + &self, + image: &mut Image, + x: i32, + y: i32, + width: u32, + height: u32, + ) -> Result<()> { + let (img_w, img_h) = image.size(); + if width > img_w || height > img_h { + return Err(Error::Protocol(format!( + "vaGetImage region {width}x{height} exceeds image {img_w}x{img_h}" + ))); + } + // SAFETY: valid display and surface id; `image.raw.image_id` is a live + // image on the same display. The region is bounded above by the image + // size, which is what vaGetImage requires (va.h:4827). + let status = unsafe { + sys::vaGetImage( + self.display.handle(), + self.id, + x, + y, + width, + height, + image.raw.image_id, + ) + }; + check("vaGetImage", status) + } + + /// The surface id, for FFI-level callers (`ec-hw` picture parameters). + pub fn id(&self) -> sys::VASurfaceID { + self.id + } + + /// The spec this surface was allocated with. + pub fn spec(&self) -> &SurfaceSpec { + &self.spec + } + + /// Allocated size in pixels. + pub fn size(&self) -> (u32, u32) { + (self.spec.width, self.spec.height) + } + + /// The display this surface belongs to. + pub fn display(&self) -> &Arc { + &self.display + } +} + +fn int_attrib(type_: sys::VASurfaceAttribType, value: i32) -> sys::VASurfaceAttrib { + sys::VASurfaceAttrib { + type_, + flags: sys::VA_SURFACE_ATTRIB_SETTABLE, + value: sys::VAGenericValue { + type_: sys::VAGenericValueTypeInteger, + value: sys::VAGenericValueUnion { i: value }, + }, + } +} + +impl std::fmt::Debug for Surface { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Surface") + .field("id", &self.id) + .field("size", &(self.spec.width, self.spec.height)) + .finish() + } +} + +impl Drop for Surface { + fn drop(&mut self) { + let mut id = self.id; + // SAFETY: `id` is live and belongs to `self.display`. Any context that + // used it held an `Arc`, so it was destroyed first; any + // derived Image also held one. + unsafe { sys::vaDestroySurfaces(self.display.handle(), &raw mut id, 1) }; + } +} + +/// One DRM object (buffer object) of an exported surface. +#[derive(Debug)] +pub struct PrimeObject { + /// The PRIME file descriptor, owned and closed on drop. + pub fd: OwnedFd, + /// Total size of the object in bytes. + pub size: u32, + /// DRM format modifier (tiling/compression layout). + pub modifier: u64, +} + +/// One layer (plane group) of an exported surface. +#[derive(Debug, Clone)] +pub struct PrimeLayer { + /// `DRM_FORMAT_*` FourCC of this layer. + pub drm_format: u32, + /// Per-plane `(object_index, offset, pitch)`. + pub planes: Vec<(u32, u32, u32)>, +} + +/// A surface exported as DRM PRIME file descriptors. +/// +/// Owns the descriptors: dropping this closes them. libva hands over ownership +/// on export (`va.h:4155`), so anything less would leak one fd per frame. +#[derive(Debug)] +pub struct PrimeSurface { + /// Surface FourCC (`VA_FOURCC_*`). + pub fourcc: u32, + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// Backing DRM objects. + pub objects: Vec, + /// Layers referencing those objects. + pub layers: Vec, +} + +impl PrimeSurface { + /// Take ownership of the fds in a filled descriptor. + fn from_raw(desc: sys::VADRMPRIMESurfaceDescriptor) -> Result { + // The array is 4 elements wide; a driver reporting more would mean our + // transcription and the runtime disagree about the struct, so refuse + // rather than read past the end. + if desc.num_objects as usize > desc.objects.len() + || desc.num_layers as usize > desc.layers.len() + { + return Err(Error::Protocol(format!( + "vaExportSurfaceHandle reported {} objects / {} layers, max 4 each", + desc.num_objects, desc.num_layers + ))); + } + + let mut objects = Vec::with_capacity(desc.num_objects as usize); + for obj in &desc.objects[..desc.num_objects as usize] { + if obj.fd < 0 { + return Err(Error::Protocol(format!( + "vaExportSurfaceHandle returned fd {} for an exported object", + obj.fd + ))); + } + objects.push(PrimeObject { + // SAFETY: libva transfers ownership of every exported fd to the + // caller (va.h:4155). Each fd appears exactly once in the + // descriptor, so it is wrapped exactly once here and closed + // exactly once when this `PrimeSurface` drops. + fd: unsafe { OwnedFd::from_raw_fd(obj.fd) }, + size: obj.size, + modifier: obj.drm_format_modifier, + }); + } + + let mut layers = Vec::with_capacity(desc.num_layers as usize); + for layer in &desc.layers[..desc.num_layers as usize] { + if layer.num_planes as usize > layer.object_index.len() { + return Err(Error::Protocol(format!( + "vaExportSurfaceHandle reported {} planes in a layer, max 4", + layer.num_planes + ))); + } + layers.push(PrimeLayer { + drm_format: layer.drm_format, + planes: (0..layer.num_planes as usize) + .map(|i| (layer.object_index[i], layer.offset[i], layer.pitch[i])) + .collect(), + }); + } + + Ok(PrimeSurface { + fourcc: desc.fourcc, + width: desc.width, + height: desc.height, + objects, + layers, + }) + } +} + +/// A `VAImage` bound to a surface (derived) or standalone (created). +pub struct Image { + display: Arc, + /// Kept alive because a derived image aliases the surface's memory. + _surface: Option>, + raw: sys::VAImage, +} + +impl Image { + /// Allocate a standalone image to read a surface back into + /// ([`Surface::read_into`]). + /// + /// `fourcc` must be one of [`crate::CapReport::image_formats`]; the other + /// [`sys::VAImageFormat`] fields are only meaningful for RGB layouts and + /// are left zero, as libva's own examples do for planar YUV. + pub fn create(display: &Arc, fourcc: u32, width: u32, height: u32) -> Result { + let mut format = sys::VAImageFormat { + fourcc, + byte_order: 1, // VA_LSB_FIRST + bits_per_pixel: match fourcc { + sys::VA_FOURCC_NV12 | sys::VA_FOURCC_I420 | sys::VA_FOURCC_YV12 => 12, + sys::VA_FOURCC_P010 => 24, + _ => 0, + }, + ..sys::VAImageFormat::default() + }; + let mut image = sys::VAImage::default(); + // SAFETY: `format` and `image` are valid, initialized in/out parameters + // that outlive the call; libva copies the format and fully overwrites + // `image` on success. + let status = unsafe { + sys::vaCreateImage( + display.handle(), + &raw mut format, + width as i32, + height as i32, + &raw mut image, + ) + }; + check("vaCreateImage", status)?; + Ok(Image { + display: Arc::clone(display), + _surface: None, + raw: image, + }) + } + + /// Pixel format FourCC. + pub fn fourcc(&self) -> u32 { + self.raw.format.fourcc + } + + /// `(width, height)` of the image, which may exceed the requested size. + pub fn size(&self) -> (u32, u32) { + (self.raw.width as u32, self.raw.height as u32) + } + + /// Number of planes (at most 3). + pub fn num_planes(&self) -> u32 { + self.raw.num_planes.min(3) + } + + /// Row pitch of plane `i` in bytes. + pub fn pitch(&self, plane: usize) -> Option { + self.raw.pitches.get(plane).copied() + } + + /// Map the image's buffer into this process. + /// + /// The returned guard unmaps on drop. That is not politeness: an unmatched + /// `vaMapBuffer` leaks the mapping for the lifetime of the display, which + /// is how the incumbent stack lost ~3MB per frame. + pub fn map(&mut self) -> Result> { + let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut(); + // SAFETY: `self.raw.buf` is the image buffer libva created and still + // owns; `ptr` is a valid out-parameter. On success libva guarantees the + // mapping stays valid until vaUnmapBuffer, which `MappedImage::drop` + // calls exactly once. + let status = unsafe { sys::vaMapBuffer(self.display.handle(), self.raw.buf, &raw mut ptr) }; + check("vaMapBuffer", status)?; + if ptr.is_null() { + // SAFETY: the map call reported success, so the buffer is mapped + // and must be unmapped even though the pointer is unusable. + unsafe { sys::vaUnmapBuffer(self.display.handle(), self.raw.buf) }; + return Err(Error::Protocol( + "vaMapBuffer succeeded but returned NULL".to_string(), + )); + } + Ok(MappedImage { + image: self, + base: ptr.cast::(), + }) + } +} + +impl std::fmt::Debug for Image { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Image") + .field("fourcc", &crate::caps::fourcc_str(self.raw.format.fourcc)) + .field("size", &(self.raw.width, self.raw.height)) + .field("num_planes", &self.raw.num_planes) + .field("data_size", &self.raw.data_size) + .finish() + } +} + +impl Drop for Image { + fn drop(&mut self) { + // SAFETY: `image_id` came from vaDeriveImage/vaCreateImage on + // `self.display` and is destroyed once. Any mapping was released + // first: `map` borrows `self` mutably, so no `MappedImage` can outlive + // this. The surface (if any) is released after, as libva requires. + unsafe { sys::vaDestroyImage(self.display.handle(), self.raw.image_id) }; + } +} + +/// A mapped [`Image`]. Unmaps on drop. +pub struct MappedImage<'a> { + image: &'a mut Image, + base: *mut u8, +} + +impl MappedImage<'_> { + /// Byte range of plane `i` within the mapped buffer, as `(offset, len)`. + /// + /// The length runs to the next plane's offset, or to `data_size` for the + /// last plane — libva does not report per-plane sizes. + fn plane_range(&self, plane: usize) -> Option<(usize, usize)> { + let n = self.image.num_planes() as usize; + if plane >= n { + return None; + } + let raw = &self.image.raw; + let offset = raw.offsets[plane] as usize; + let end = raw + .offsets + .get(plane + 1) + .copied() + .filter(|_| plane + 1 < n) + .unwrap_or(raw.data_size) as usize; + // A driver reporting decreasing or out-of-range offsets would otherwise + // produce a slice past the mapping. + if end < offset || end > raw.data_size as usize { + return None; + } + Some((offset, end - offset)) + } + + /// Read-only view of plane `plane`. + pub fn plane(&self, plane: usize) -> Option<&[u8]> { + let (offset, len) = self.plane_range(plane)?; + // SAFETY: `base` points at a mapping of `data_size` bytes that libva + // keeps valid until vaUnmapBuffer (called only in `drop`). `plane_range` + // guarantees `offset + len <= data_size`, so the slice stays inside the + // mapping. The borrow is tied to `&self`, so it cannot outlive it. + Some(unsafe { std::slice::from_raw_parts(self.base.add(offset), len) }) + } + + /// Mutable view of plane `plane`, for upload paths. + pub fn plane_mut(&mut self, plane: usize) -> Option<&mut [u8]> { + let (offset, len) = self.plane_range(plane)?; + // SAFETY: as `plane`, plus: `&mut self` guarantees no other slice into + // the mapping is alive, so this is the only reference to those bytes. + Some(unsafe { std::slice::from_raw_parts_mut(self.base.add(offset), len) }) + } + + /// Row pitch of plane `plane` in bytes. + pub fn pitch(&self, plane: usize) -> Option { + self.image.pitch(plane) + } + + /// The image being mapped. + pub fn image(&self) -> &Image { + self.image + } +} + +impl Drop for MappedImage<'_> { + fn drop(&mut self) { + // SAFETY: the buffer was mapped in `Image::map` and is unmapped exactly + // once, here; `self.image` is still alive because this guard borrows it. + unsafe { sys::vaUnmapBuffer(self.image.display.handle(), self.image.raw.buf) }; + } +} diff --git a/crates/ec-va/src/sys.rs b/crates/ec-va/src/sys.rs new file mode 100644 index 00000000..ea7acd38 --- /dev/null +++ b/crates/ec-va/src/sys.rs @@ -0,0 +1,558 @@ +//! Hand-written FFI for the subset of libva this family uses. +//! +//! # Why hand-written +//! +//! No `bindgen`: the family rule is no build-time tooling, and a generated +//! 40k-line binding hides exactly the thing that has to be audited — the ABI +//! assumptions. Everything here is transcribed from the system headers and is +//! short enough to read in one sitting. +//! +//! # ABI assumptions (all four are load-bearing) +//! +//! 1. **libva 1.23.0 headers**, `/usr/include/va/{va.h,va_drm.h,va_drmcommon.h}`, +//! target `x86_64-unknown-linux-gnu`, System V C ABI. +//! 2. **C `enum` is `int` (4 bytes)** on this ABI. Every VA enum is transcribed +//! as a plain `i32` type alias plus constants, *never* as a `#[repr(i32)]` +//! Rust enum: the driver writes profile/entrypoint values into buffers we +//! own, and a value we have no variant for would be instant UB on a real +//! Rust enum. Interpretation happens in the safe layer +//! ([`crate::caps::Profile::from_raw`]), which has an `Unknown(i32)` arm. +//! This is the header-drift trap that broke cros-libva at libva >= 1.23. +//! 3. **Struct layouts** below are checked by the `const _: () = assert!(...)` +//! block at the end of this file against numbers printed by +//! `crates/ec-va/abi-probe.c` compiled against the *system* headers. Rerun +//! that probe after a libva upgrade; a mismatch means this file drifted. +//! 4. **`VADisplay` is an opaque pointer**; we never dereference it. +//! +//! Points 1-3 are compile-time. They cannot see a libva that changes layout +//! *after* this crate is built, so [`crate::Display::open`] additionally +//! performs a **runtime** `vaInitialize` version check and refuses anything +//! older than 1.23 with a typed error. + +// Every item keeps its exact C spelling so that this file can be diffed +// against the headers by eye — the whole audit story of a hand-written FFI. +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] +// Fields keep their C names and are documented by the header line cited on +// each item; restating "the fourcc field is the fourcc" 60 times would bury +// the ABI notes that actually matter here. +#![allow(missing_docs)] + +use std::ffi::{c_char, c_int, c_uint, c_void}; + +// --------------------------------------------------------------------------- +// Scalar types (va.h:260-262, 1580-1647, 2042, 4727) +// --------------------------------------------------------------------------- + +/// Opaque display handle. Never dereferenced by this crate. +pub type VADisplay = *mut c_void; +/// Return status of every VA entry point. `va.h:262`. +pub type VAStatus = i32; +/// `va.h:1580`. +pub type VAGenericID = c_uint; +pub type VAConfigID = VAGenericID; +pub type VAContextID = VAGenericID; +pub type VASurfaceID = VAGenericID; +pub type VABufferID = VAGenericID; +pub type VAImageID = VAGenericID; + +/// C enum `VAProfile` (`va.h:502`), kept as `i32`. See ABI assumption 2. +pub type VAProfile = i32; +/// C enum `VAEntrypoint` (`va.h:552`), kept as `i32`. +pub type VAEntrypoint = i32; +/// C enum `VAConfigAttribType` (`va.h:619`), kept as `i32`. +pub type VAConfigAttribType = i32; +/// C enum `VASurfaceAttribType` (`va.h:1689`), kept as `i32`. +pub type VASurfaceAttribType = i32; +/// C enum `VAGenericValueType` (`va.h:1651`), kept as `i32`. +pub type VAGenericValueType = i32; +/// C enum `VABufferType` (`va.h:2044`), kept as `i32`. +pub type VABufferType = i32; + +pub const VA_INVALID_ID: VAGenericID = 0xffff_ffff; +pub const VA_INVALID_SURFACE: VASurfaceID = VA_INVALID_ID; + +// Status codes actually branched on; the rest are reported via `vaErrorStr`. +// `va.h:264-309`. +pub const VA_STATUS_SUCCESS: VAStatus = 0x0000_0000; +pub const VA_STATUS_ERROR_INVALID_CONTEXT: VAStatus = 0x0000_0005; +pub const VA_STATUS_ERROR_UNSUPPORTED_PROFILE: VAStatus = 0x0000_000c; +pub const VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT: VAStatus = 0x0000_000d; +pub const VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT: VAStatus = 0x0000_000e; +pub const VA_STATUS_ERROR_MAX_NUM_EXCEEDED: VAStatus = 0x0000_000b; +pub const VA_STATUS_ERROR_UNIMPLEMENTED: VAStatus = 0x0000_0014; +pub const VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED: VAStatus = 0x0000_0013; +pub const VA_STATUS_ERROR_OPERATION_FAILED: VAStatus = 0x0000_0001; +pub const VA_STATUS_ERROR_INVALID_PARAMETER: VAStatus = 0x0000_0012; + +// Entrypoints (`va.h:552`). +pub const VAEntrypointVLD: VAEntrypoint = 1; +pub const VAEntrypointEncSlice: VAEntrypoint = 6; +pub const VAEntrypointEncPicture: VAEntrypoint = 7; +pub const VAEntrypointEncSliceLP: VAEntrypoint = 8; +pub const VAEntrypointVideoProc: VAEntrypoint = 10; + +// Config attribute types (`va.h:619`). +pub const VAConfigAttribRTFormat: VAConfigAttribType = 0; +pub const VAConfigAttribRateControl: VAConfigAttribType = 5; +pub const VAConfigAttribDecSliceMode: VAConfigAttribType = 6; +pub const VAConfigAttribEncPackedHeaders: VAConfigAttribType = 10; + +// RT formats (`va.h:1073-1090`). +pub const VA_RT_FORMAT_YUV420: u32 = 0x0000_0001; +pub const VA_RT_FORMAT_YUV422: u32 = 0x0000_0002; +pub const VA_RT_FORMAT_YUV444: u32 = 0x0000_0004; +pub const VA_RT_FORMAT_YUV400: u32 = 0x0000_0010; +pub const VA_RT_FORMAT_YUV420_10: u32 = 0x0000_0100; +pub const VA_RT_FORMAT_YUV422_10: u32 = 0x0000_0200; +pub const VA_RT_FORMAT_YUV444_10: u32 = 0x0000_0400; +pub const VA_RT_FORMAT_YUV420_12: u32 = 0x0000_1000; +pub const VA_RT_FORMAT_RGB32: u32 = 0x0002_0000; + +// Surface attribute types (`va.h:1689`) and flags (`va.h:1681-1684`). +pub const VASurfaceAttribNone: VASurfaceAttribType = 0; +pub const VASurfaceAttribPixelFormat: VASurfaceAttribType = 1; +pub const VASurfaceAttribMinWidth: VASurfaceAttribType = 2; +pub const VASurfaceAttribMaxWidth: VASurfaceAttribType = 3; +pub const VASurfaceAttribMinHeight: VASurfaceAttribType = 4; +pub const VASurfaceAttribMaxHeight: VASurfaceAttribType = 5; +pub const VASurfaceAttribMemoryType: VASurfaceAttribType = 6; +pub const VASurfaceAttribUsageHint: VASurfaceAttribType = 8; + +pub const VA_SURFACE_ATTRIB_GETTABLE: u32 = 0x0000_0001; +pub const VA_SURFACE_ATTRIB_SETTABLE: u32 = 0x0000_0002; + +pub const VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC: u32 = 0x0000_0000; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_DECODER: u32 = 0x0000_0001; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER: u32 = 0x0000_0002; +pub const VA_SURFACE_ATTRIB_USAGE_HINT_EXPORT: u32 = 0x0000_0020; + +// Generic value discriminants (`va.h:1651`). +pub const VAGenericValueTypeInteger: VAGenericValueType = 1; +pub const VAGenericValueTypeFloat: VAGenericValueType = 2; +pub const VAGenericValueTypePointer: VAGenericValueType = 3; +pub const VAGenericValueTypeFunc: VAGenericValueType = 4; + +// Buffer types actually used by decode/encode paths (`va.h:2044`). +pub const VAPictureParameterBufferType: VABufferType = 0; +pub const VAIQMatrixBufferType: VABufferType = 1; +pub const VASliceParameterBufferType: VABufferType = 4; +pub const VASliceDataBufferType: VABufferType = 5; +pub const VAImageBufferType: VABufferType = 9; +pub const VAProbabilityBufferType: VABufferType = 13; +pub const VAEncCodedBufferType: VABufferType = 21; +pub const VAEncSequenceParameterBufferType: VABufferType = 22; +pub const VAEncPictureParameterBufferType: VABufferType = 23; +pub const VAEncSliceParameterBufferType: VABufferType = 24; +pub const VAEncPackedHeaderParameterBufferType: VABufferType = 25; +pub const VAEncPackedHeaderDataBufferType: VABufferType = 26; +pub const VAEncMiscParameterBufferType: VABufferType = 27; + +/// `vaCreateContext` flag: sequence contains only progressive frames (`va.h:1919`). +pub const VA_PROGRESSIVE: c_int = 0x1; + +// DRM PRIME memory types and export flags (`va_drmcommon.h:78-94`, `va.h:4130-4150`). +pub const VA_SURFACE_ATTRIB_MEM_TYPE_VA: u32 = 0x0000_0001; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM: u32 = 0x1000_0000; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME: u32 = 0x2000_0000; +pub const VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2: u32 = 0x4000_0000; + +pub const VA_EXPORT_SURFACE_READ_ONLY: u32 = 0x0001; +pub const VA_EXPORT_SURFACE_WRITE_ONLY: u32 = 0x0002; +pub const VA_EXPORT_SURFACE_READ_WRITE: u32 = 0x0003; +pub const VA_EXPORT_SURFACE_SEPARATE_LAYERS: u32 = 0x0004; +pub const VA_EXPORT_SURFACE_COMPOSED_LAYERS: u32 = 0x0008; + +// FourCCs used by the family (`va.h:4400-4700`). +pub const VA_FOURCC_NV12: u32 = 0x3231_564e; +pub const VA_FOURCC_P010: u32 = 0x3031_3050; +pub const VA_FOURCC_I420: u32 = 0x3032_3449; +pub const VA_FOURCC_YV12: u32 = 0x3231_5659; + +// --------------------------------------------------------------------------- +// Structs +// --------------------------------------------------------------------------- + +/// `VAConfigAttrib`, `va.h:1155`. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VAConfigAttrib { + pub type_: VAConfigAttribType, + pub value: u32, +} + +/// The `value` union of `VAGenericValue`, `va.h:1663-1673`. +/// +/// Only ever read after checking the sibling `type_` discriminant. +#[repr(C)] +#[derive(Clone, Copy)] +pub union VAGenericValueUnion { + pub i: i32, + pub f: f32, + pub p: *mut c_void, + pub func: Option, +} + +/// `VAGenericValue`, `va.h:1661`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct VAGenericValue { + pub type_: VAGenericValueType, + pub value: VAGenericValueUnion, +} + +/// `VASurfaceAttrib`, `va.h:1741`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct VASurfaceAttrib { + pub type_: VASurfaceAttribType, + pub flags: u32, + pub value: VAGenericValue, +} + +/// `VAImageFormat`, `va.h:4712`. `va_reserved` is `VA_PADDING_LOW` = 4 u32s. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct VAImageFormat { + pub fourcc: u32, + pub byte_order: u32, + pub bits_per_pixel: u32, + pub depth: u32, + pub red_mask: u32, + pub green_mask: u32, + pub blue_mask: u32, + pub alpha_mask: u32, + pub va_reserved: [u32; 4], +} + +/// `VAImage`, `va.h:4729`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct VAImage { + pub image_id: VAImageID, + pub format: VAImageFormat, + pub buf: VABufferID, + pub width: u16, + pub height: u16, + pub data_size: u32, + pub num_planes: u32, + pub pitches: [u32; 3], + pub offsets: [u32; 3], + pub num_palette_entries: i32, + pub entry_bytes: i32, + pub component_order: [i8; 4], + pub va_reserved: [u32; 4], +} + +impl Default for VAImage { + fn default() -> Self { + // All-zero is a valid "not yet filled" VAImage; `image_id` is + // overwritten by vaDeriveImage/vaCreateImage before any use. + // SAFETY: every field is a plain integer or array of integers, so the + // all-zero bit pattern is a valid value of this type. + unsafe { std::mem::zeroed() } + } +} + +/// One DRM object of a `VADRMPRIMESurfaceDescriptor`, `va_drmcommon.h:139-147`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct VADRMPRIMEObject { + pub fd: c_int, + pub size: u32, + pub drm_format_modifier: u64, +} + +/// One layer of a `VADRMPRIMESurfaceDescriptor`, `va_drmcommon.h:151-164`. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct VADRMPRIMELayer { + pub drm_format: u32, + pub num_planes: u32, + pub object_index: [u32; 4], + pub offset: [u32; 4], + pub pitch: [u32; 4], +} + +/// `VADRMPRIMESurfaceDescriptor`, `va_drmcommon.h:130`. Used with +/// [`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`]. +#[repr(C)] +#[derive(Debug, Clone, Copy)] +pub struct VADRMPRIMESurfaceDescriptor { + pub fourcc: u32, + pub width: u32, + pub height: u32, + pub num_objects: u32, + pub objects: [VADRMPRIMEObject; 4], + pub num_layers: u32, + pub layers: [VADRMPRIMELayer; 4], +} + +impl Default for VADRMPRIMESurfaceDescriptor { + fn default() -> Self { + // SAFETY: all fields are integers or arrays of integer structs; the + // all-zero bit pattern is valid. `fd` = 0 is never treated as an owned + // descriptor because `num_objects` = 0 in that state. + unsafe { std::mem::zeroed() } + } +} + +/// `VARectangle`, `va.h:406`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct VARectangle { + pub x: i16, + pub y: i16, + pub width: u16, + pub height: u16, +} + +// --------------------------------------------------------------------------- +// Entry points +// --------------------------------------------------------------------------- + +#[link(name = "va")] +unsafe extern "C" { + /// `va.h:403`. Returns a pointer to a static string; never NULL. + pub fn vaErrorStr(error_status: VAStatus) -> *const c_char; + /// `va.h:453`. + pub fn vaDisplayIsValid(dpy: VADisplay) -> c_int; + /// `va.h:465`. + pub fn vaInitialize( + dpy: VADisplay, + major_version: *mut c_int, + minor_version: *mut c_int, + ) -> VAStatus; + /// `va.h:474`. + pub fn vaTerminate(dpy: VADisplay) -> VAStatus; + /// `va.h:486`. Static string owned by the driver, valid until `vaTerminate`. + pub fn vaQueryVendorString(dpy: VADisplay) -> *const c_char; + + /// `va.h:1524`. + pub fn vaMaxNumProfiles(dpy: VADisplay) -> c_int; + /// `va.h:1529`. + pub fn vaMaxNumEntrypoints(dpy: VADisplay) -> c_int; + /// `va.h:1534`. + pub fn vaMaxNumConfigAttributes(dpy: VADisplay) -> c_int; + /// `va.h:1544`. + pub fn vaQueryConfigProfiles( + dpy: VADisplay, + profile_list: *mut VAProfile, + num_profiles: *mut c_int, + ) -> VAStatus; + /// `va.h:1556`. + pub fn vaQueryConfigEntrypoints( + dpy: VADisplay, + profile: VAProfile, + entrypoint_list: *mut VAEntrypoint, + num_entrypoints: *mut c_int, + ) -> VAStatus; + /// `va.h:1571`. `attrib_list` is in/out: caller sets `type_`, driver fills `value`. + pub fn vaGetConfigAttributes( + dpy: VADisplay, + profile: VAProfile, + entrypoint: VAEntrypoint, + attrib_list: *mut VAConfigAttrib, + num_attribs: c_int, + ) -> VAStatus; + /// `va.h:1589`. + pub fn vaCreateConfig( + dpy: VADisplay, + profile: VAProfile, + entrypoint: VAEntrypoint, + attrib_list: *mut VAConfigAttrib, + num_attribs: c_int, + config_id: *mut VAConfigID, + ) -> VAStatus; + /// `va.h:1601`. + pub fn vaDestroyConfig(dpy: VADisplay, config_id: VAConfigID) -> VAStatus; + + /// `va.h:1868`. Pass NULL `attrib_list` to only query the count. + pub fn vaQuerySurfaceAttributes( + dpy: VADisplay, + config: VAConfigID, + attrib_list: *mut VASurfaceAttrib, + num_attribs: *mut c_uint, + ) -> VAStatus; + /// `va.h:1894`. + pub fn vaCreateSurfaces( + dpy: VADisplay, + format: c_uint, + width: c_uint, + height: c_uint, + surfaces: *mut VASurfaceID, + num_surfaces: c_uint, + attrib_list: *mut VASurfaceAttrib, + num_attribs: c_uint, + ) -> VAStatus; + /// `va.h:1914`. + pub fn vaDestroySurfaces( + dpy: VADisplay, + surfaces: *mut VASurfaceID, + num_surfaces: c_int, + ) -> VAStatus; + /// `va.h:4185`. `descriptor` type is chosen by `mem_type`. + pub fn vaExportSurfaceHandle( + dpy: VADisplay, + surface_id: VASurfaceID, + mem_type: u32, + flags: u32, + descriptor: *mut c_void, + ) -> VAStatus; + + /// `va.h:1933`. + pub fn vaCreateContext( + dpy: VADisplay, + config_id: VAConfigID, + picture_width: c_int, + picture_height: c_int, + flag: c_int, + render_targets: *mut VASurfaceID, + num_render_targets: c_int, + context: *mut VAContextID, + ) -> VAStatus; + /// `va.h:1949`. + pub fn vaDestroyContext(dpy: VADisplay, context: VAContextID) -> VAStatus; + + /// `va.h:3833`. `data` NULL means "allocate, fill later via vaMapBuffer". + pub fn vaCreateBuffer( + dpy: VADisplay, + context: VAContextID, + type_: VABufferType, + size: c_uint, + num_elements: c_uint, + data: *mut c_void, + buf_id: *mut VABufferID, + ) -> VAStatus; + /// `va.h:3971`. + pub fn vaMapBuffer(dpy: VADisplay, buf_id: VABufferID, pbuf: *mut *mut c_void) -> VAStatus; + /// `va.h:4004`. + pub fn vaUnmapBuffer(dpy: VADisplay, buf_id: VABufferID) -> VAStatus; + /// `va.h:4018`. + pub fn vaDestroyBuffer(dpy: VADisplay, buffer_id: VABufferID) -> VAStatus; + + /// `va.h:4205`. + pub fn vaBeginPicture( + dpy: VADisplay, + context: VAContextID, + render_target: VASurfaceID, + ) -> VAStatus; + /// `va.h:4214`. + pub fn vaRenderPicture( + dpy: VADisplay, + context: VAContextID, + buffers: *mut VABufferID, + num_buffers: c_int, + ) -> VAStatus; + /// `va.h:4229`. + pub fn vaEndPicture(dpy: VADisplay, context: VAContextID) -> VAStatus; + /// `va.h:4271`. Blocks until the render target is idle. + pub fn vaSyncSurface(dpy: VADisplay, render_target: VASurfaceID) -> VAStatus; + + /// `va.h:4773`. + pub fn vaMaxNumImageFormats(dpy: VADisplay) -> c_int; + /// `va.h:4783`. + pub fn vaQueryImageFormats( + dpy: VADisplay, + format_list: *mut VAImageFormat, + num_formats: *mut c_int, + ) -> VAStatus; + /// `va.h:4796`. + pub fn vaCreateImage( + dpy: VADisplay, + format: *mut VAImageFormat, + width: c_int, + height: c_int, + image: *mut VAImage, + ) -> VAStatus; + /// `va.h:4807`. + pub fn vaDestroyImage(dpy: VADisplay, image: VAImageID) -> VAStatus; + /// `va.h:4827`. + pub fn vaGetImage( + dpy: VADisplay, + surface: VASurfaceID, + x: c_int, + y: c_int, + width: c_uint, + height: c_uint, + image: VAImageID, + ) -> VAStatus; + /// `va.h:4888`. Zero-copy view of a surface, when the driver allows it. + pub fn vaDeriveImage(dpy: VADisplay, surface: VASurfaceID, image: *mut VAImage) -> VAStatus; +} + +#[link(name = "va-drm")] +unsafe extern "C" { + /// `va_drm.h:45`. Returns NULL on failure. Does **not** take ownership of `fd`. + pub fn vaGetDisplayDRM(fd: c_int) -> VADisplay; +} + +// --------------------------------------------------------------------------- +// ABI transcription check +// --------------------------------------------------------------------------- +// +// Reference output of `crates/ec-va/abi-probe.c` compiled against +// /usr/include/va (libva 1.23.0) with gcc on x86_64: +// +// VAConfigAttrib size=8 align=4 type=0 value=4 +// VAGenericValue size=16 align=8 type=0 value=8 +// VASurfaceAttrib size=24 align=8 type=0 flags=4 value=8 +// VAImageFormat size=48 align=4 fourcc=0 .. va_reserved=32 +// VAImage size=120 align=4 image_id=0 format=4 buf=52 +// width=56 height=58 data_size=60 +// num_planes=64 pitches=68 offsets=80 +// num_palette_entries=92 entry_bytes=96 +// component_order=100 va_reserved=104 +// VADRMPRIMESurfaceDescriptor size=312 align=8 fourcc=0 width=4 height=8 +// num_objects=12 objects=16 +// num_layers=80 layers=84 +// object elem size=16, layer elem size=56 +// VARectangle size=8 align=2 +const _: () = { + use std::mem::{align_of, offset_of, size_of}; + + assert!(size_of::() == 8 && align_of::() == 4); + assert!(offset_of!(VAConfigAttrib, value) == 4); + + assert!(size_of::() == 16 && align_of::() == 8); + assert!(offset_of!(VAGenericValue, value) == 8); + + assert!(size_of::() == 24 && align_of::() == 8); + assert!(offset_of!(VASurfaceAttrib, flags) == 4); + assert!(offset_of!(VASurfaceAttrib, value) == 8); + + assert!(size_of::() == 48 && align_of::() == 4); + assert!(offset_of!(VAImageFormat, va_reserved) == 32); + + assert!(size_of::() == 120 && align_of::() == 4); + assert!(offset_of!(VAImage, format) == 4); + assert!(offset_of!(VAImage, buf) == 52); + assert!(offset_of!(VAImage, width) == 56); + assert!(offset_of!(VAImage, height) == 58); + assert!(offset_of!(VAImage, data_size) == 60); + assert!(offset_of!(VAImage, num_planes) == 64); + assert!(offset_of!(VAImage, pitches) == 68); + assert!(offset_of!(VAImage, offsets) == 80); + assert!(offset_of!(VAImage, num_palette_entries) == 92); + assert!(offset_of!(VAImage, entry_bytes) == 96); + assert!(offset_of!(VAImage, component_order) == 100); + assert!(offset_of!(VAImage, va_reserved) == 104); + + assert!(size_of::() == 16); + assert!(size_of::() == 56); + assert!( + size_of::() == 312 + && align_of::() == 8 + ); + assert!(offset_of!(VADRMPRIMESurfaceDescriptor, objects) == 16); + assert!(offset_of!(VADRMPRIMESurfaceDescriptor, num_layers) == 80); + assert!(offset_of!(VADRMPRIMESurfaceDescriptor, layers) == 84); + + assert!(size_of::() == 8 && align_of::() == 2); + + // Assumption 2: C `enum` and `unsigned int` are both 4 bytes here. + assert!(size_of::() == 4); + assert!(size_of::() == 4); + assert!(size_of::() == 4); +}; diff --git a/crates/ec-va/tests/gpu.rs b/crates/ec-va/tests/gpu.rs new file mode 100644 index 00000000..b91d727b --- /dev/null +++ b/crates/ec-va/tests/gpu.rs @@ -0,0 +1,502 @@ +//! Live GPU tests. Not `#[ignore]`d: this machine has the hardware, and a test +//! that never runs is not a test. On a machine with no VA-API device every one +//! of these fails at `Display::open`, which is the honest outcome — the crate +//! has no meaning without a driver. +//! +//! Everything lives in one test binary on purpose (a file per feature is a +//! serial link-and-run tax). Every test opens its own display and takes +//! [`serial`], so the two process-wide measurements below stay meaningful. +//! +//! Reference: `vainfo` on this box (Mesa 26.1.6, radeonsi gfx1200, RX 9060 XT). + +use std::os::fd::AsRawFd; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; + +use ec_va::caps::{Entrypoint, Profile}; +use ec_va::{ + CapReport, Config, Context, Display, Error, Image, Picture, Surface, SurfaceSpec, sys, +}; + +/// Runs the tests in this binary one at a time. +/// +/// Two of them measure process-wide state — `VmRSS` for the surface-pool leak +/// check and `/proc/self/fd` for the PRIME export ownership check — and a +/// sibling test allocating a 1080p pool on another thread would make both +/// meaningless. Serialising is cheaper and more honest than loosening the +/// thresholds until concurrency stops mattering. +fn serial() -> MutexGuard<'static, ()> { + static LOCK: OnceLock> = OnceLock::new(); + LOCK.get_or_init(|| Mutex::new(())) + .lock() + // A panicking test poisons the mutex; the rest are still worth running. + .unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +fn display() -> Arc { + Display::open().expect("no VA-API display; this test needs the GPU") +} + +// -------------------------------------------------------------------------- +// Display +// -------------------------------------------------------------------------- + +#[test] +fn display_opens_on_a_render_node() { + let _serial = serial(); + let display = display(); + assert!(display.is_valid()); + let (major, minor) = display.version(); + assert_eq!(major, ec_va::MIN_VA_MAJOR); + assert!( + minor >= ec_va::MIN_VA_MINOR, + "runtime libva {major}.{minor} is older than the transcribed ABI" + ); + assert!( + display + .device_path() + .to_string_lossy() + .starts_with("/dev/dri/renderD"), + "expected a render node, got {:?}", + display.device_path() + ); + let vendor = display.vendor().expect("vendor string"); + assert!(!vendor.is_empty(), "driver reported an empty vendor string"); +} + +// -------------------------------------------------------------------------- +// Capabilities — the table must match `vainfo` on this GPU +// -------------------------------------------------------------------------- + +#[test] +fn caps_match_vainfo_on_this_gpu() { + let _serial = serial(); + let display = display(); + let caps = CapReport::probe(&display).expect("probe"); + + // Decode: every codec the family hands to hardware. + for profile in [ + Profile::H264ConstrainedBaseline, + Profile::H264Main, + Profile::H264High, + Profile::HEVCMain, + Profile::HEVCMain10, + Profile::VP9Profile0, + Profile::VP9Profile2, + Profile::AV1Profile0, + Profile::AV1Profile2, + ] { + assert!( + caps.supports(profile, Entrypoint::VLD), + "{} VLD missing from the probe but present in vainfo", + profile.name() + ); + } + + // Encode: H.264 and HEVC are the two the family ships (AV1 encode exists on + // this GPU too, but stays opt-in — see the family plan). + for profile in [ + Profile::H264ConstrainedBaseline, + Profile::H264Main, + Profile::H264High, + Profile::HEVCMain, + Profile::HEVCMain10, + ] { + assert!( + caps.supports(profile, Entrypoint::EncSlice), + "{} EncSlice missing from the probe but present in vainfo", + profile.name() + ); + } + + // Post-processing, used later for colour conversion. + assert!(caps.supports(Profile::None, Entrypoint::VideoProc)); + + // A pair this GPU genuinely lacks must be absent, not silently invented: + // vainfo lists VP9 profiles 0 and 2 only. + assert!(!caps.supports(Profile::VP9Profile1, Entrypoint::VLD)); + assert!(!caps.supports(Profile::VP9Profile3, Entrypoint::VLD)); + assert!(!caps.supports(Profile::VP9Profile0, Entrypoint::EncSlice)); + + // 10-bit decode must advertise a 10-bit RT format, or `ec-hw` would derive + // an 8-bit context for Main10 — the incumbent's D2 defect. + let main10 = caps + .entry(Profile::HEVCMain10, Entrypoint::VLD) + .expect("HEVC Main10 VLD"); + assert!( + main10.supports_rt_format(sys::VA_RT_FORMAT_YUV420_10), + "HEVC Main10 VLD advertised rt_formats 0x{:08x} without a 10-bit format", + main10.rt_formats + ); + let p010_supported = main10 + .surfaces + .as_ref() + .expect("surface caps") + .supports_fourcc(sys::VA_FOURCC_P010); + assert!(p010_supported, "Main10 cannot allocate P010 surfaces"); + + // 8-bit decode: NV12 everywhere. + let h264 = caps + .entry(Profile::H264Main, Entrypoint::VLD) + .expect("H264 Main VLD"); + assert!(h264.supports_rt_format(sys::VA_RT_FORMAT_YUV420)); + assert!( + h264.surfaces + .as_ref() + .expect("surface caps") + .supports_fourcc(sys::VA_FOURCC_NV12) + ); + + // Readback formats: `vaGetImage` must be able to produce NV12 and P010. + assert!(caps.image_formats.contains(&sys::VA_FOURCC_NV12)); + assert!(caps.image_formats.contains(&sys::VA_FOURCC_P010)); + + assert!( + caps.profiles_for(Entrypoint::VLD).len() >= 9, + "expected at least 9 decode profiles, got {:?}", + caps.profiles_for(Entrypoint::VLD) + ); +} + +#[test] +fn caps_report_driver_legal_surface_sizes() { + let _serial = serial(); + let display = display(); + let caps = CapReport::probe(&display).expect("probe"); + let entry = caps + .entry(Profile::H264Main, Entrypoint::VLD) + .expect("H264 Main VLD"); + let surfaces = entry.surfaces.as_ref().expect("surface caps"); + + // radeonsi rejects decode surfaces below 64x64. Probing with a hardcoded + // 16x16 config is what used to panic here, so the minimum is reported + // rather than assumed. + assert_eq!(surfaces.min_width, Some(64)); + assert_eq!(surfaces.min_height, Some(64)); + assert!(surfaces.max_width.unwrap() >= 4096); + assert!( + !surfaces.allows(16, 16), + "16x16 must be refused by the caps" + ); + assert!(surfaces.allows(1920, 1088)); + + // DRM PRIME 2 export must be advertised: that is how frames leave the GPU. + assert!( + surfaces.memory_types & sys::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 != 0, + "memory types 0x{:08x} lack DRM_PRIME_2", + surfaces.memory_types + ); +} + +#[test] +fn unsupported_pair_is_refused_by_the_driver() { + let _serial = serial(); + // A refusal is a claim: prove the capability is genuinely absent rather + // than assumed absent. + let display = display(); + let caps = CapReport::probe(&display).expect("probe"); + assert!(!caps.supports(Profile::VP9Profile1, Entrypoint::VLD)); + + let err = Config::new(&display, Profile::VP9Profile1, Entrypoint::VLD, &[]) + .expect_err("VP9 Profile1 decode does not exist on this GPU"); + let status = err.status().expect("a VAStatus-carrying error"); + assert!( + status == sys::VA_STATUS_ERROR_UNSUPPORTED_PROFILE + || status == sys::VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT, + "unexpected refusal: {err}" + ); + assert!(err.to_string().contains("vaCreateConfig"), "{err}"); +} + +// -------------------------------------------------------------------------- +// Surfaces +// -------------------------------------------------------------------------- + +#[test] +fn surface_pool_create_and_destroy_is_leak_free() { + let _serial = serial(); + let display = display(); + let spec = SurfaceSpec::nv12(64, 64); + + // Warm up so first-touch allocations are not counted as a leak. + for _ in 0..4 { + let pool = Surface::create_pool(&display, &spec, 16).expect("pool"); + assert_eq!(pool.len(), 16); + drop(pool); + } + + let before = vm_rss_kb(); + for _ in 0..100 { + let pool = Surface::create_pool(&display, &spec, 16).expect("pool"); + // Every id must be distinct and valid, or the pool is aliasing memory. + let mut ids: Vec<_> = pool.iter().map(|s| s.id()).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 16, "vaCreateSurfaces returned duplicate ids"); + assert!(ids.iter().all(|&id| id != sys::VA_INVALID_SURFACE)); + drop(pool); + } + let after = vm_rss_kb(); + + // 1600 surfaces created and destroyed. A per-surface leak would be obvious + // at this scale; the incumbent's unmatched map leaked ~3MB per frame. + let delta_kb = after.saturating_sub(before); + assert!( + delta_kb < 50 * 1024, + "VmRSS grew {delta_kb} kB over 100 create/destroy cycles" + ); +} + +#[test] +fn derive_image_maps_and_reads_back() { + let _serial = serial(); + let display = display(); + let surface = Surface::create(&display, &SurfaceSpec::nv12(64, 64)).expect("surface"); + let mut image = surface.derive_image().expect("vaDeriveImage"); + + assert_eq!(image.fourcc(), sys::VA_FOURCC_NV12); + assert_eq!(image.size(), (64, 64)); + assert_eq!(image.num_planes(), 2, "NV12 is luma + interleaved chroma"); + let pitch = image.pitch(0).expect("luma pitch"); + assert!(pitch >= 64, "luma pitch {pitch} is narrower than the image"); + + { + let mut mapped = image.map().expect("vaMapBuffer"); + let luma = mapped.plane_mut(0).expect("luma plane"); + assert_eq!( + luma.len(), + pitch as usize * 64, + "luma plane length must be pitch * height" + ); + for (i, byte) in luma.iter_mut().enumerate() { + *byte = (i % 251) as u8; + } + let chroma = mapped.plane(1).expect("chroma plane"); + assert!(!chroma.is_empty()); + assert!(mapped.plane(2).is_none(), "NV12 has no third plane"); + + let luma = mapped.plane(0).expect("luma plane"); + assert_eq!(luma[0], 0); + assert_eq!(luma[250], 250); + assert_eq!(luma[251], 0, "write did not survive within the mapping"); + } + + // Re-mapping after the guard dropped proves the unmap actually happened: + // libva returns the same buffer only once per map, and a never-unmapped + // mapping is the incumbent's per-frame leak. + // + // What is deliberately *not* asserted: that the bytes written above are + // readable through this second mapping. On radeonsi 26.1 a derived-image + // mapping is write-oriented staging — the write reaches the surface (see + // `created_image_reads_a_surface_back`), but a fresh map reads back zeros. + // Readback therefore goes through `vaGetImage`, never through a re-derive. + let mapped = image.map().expect("second vaMapBuffer after unmap"); + assert_eq!( + mapped.plane(0).expect("luma").len(), + pitch as usize * 64, + "second mapping has a different geometry" + ); +} + +#[test] +fn created_image_reads_a_surface_back() { + let _serial = serial(); + let display = display(); + let surface = Surface::create(&display, &SurfaceSpec::nv12(64, 64)).expect("surface"); + // Paint through the derived image so there is something known to read back. + { + let mut derived = surface.derive_image().expect("derive"); + let mut mapped = derived.map().expect("map"); + for byte in mapped.plane_mut(0).expect("luma") { + *byte = 0x5a; + } + } + surface.sync().expect("sync"); + + let mut image = Image::create(&display, sys::VA_FOURCC_NV12, 64, 64).expect("vaCreateImage"); + surface + .read_into(&mut image, 0, 0, 64, 64) + .expect("vaGetImage"); + let mapped = image.map().expect("map"); + let luma = mapped.plane(0).expect("luma"); + assert!( + luma.iter().take(64).all(|&b| b == 0x5a), + "vaGetImage did not return the painted luma" + ); + + // Out-of-range regions are refused before reaching the driver. + drop(mapped); + let err = surface + .read_into(&mut image, 0, 0, 128, 128) + .expect_err("region larger than the image must be refused"); + assert!(matches!(err, Error::Protocol(_)), "{err}"); +} + +#[test] +fn prime_export_owns_and_releases_its_descriptors() { + let _serial = serial(); + let display = display(); + let surface = Surface::create(&display, &SurfaceSpec::nv12(64, 64)).expect("surface"); + surface.sync().expect("sync before export"); + + let baseline = open_fd_count(); + let exported = surface + .export_prime(sys::VA_EXPORT_SURFACE_READ_ONLY) + .expect("vaExportSurfaceHandle"); + + assert_eq!(exported.fourcc, sys::VA_FOURCC_NV12); + assert_eq!((exported.width, exported.height), (64, 64)); + assert!(!exported.objects.is_empty(), "no DRM objects exported"); + assert!(!exported.layers.is_empty(), "no layers exported"); + for object in &exported.objects { + assert!(object.fd.as_raw_fd() >= 0); + assert!(object.size > 0); + } + for layer in &exported.layers { + assert!(!layer.planes.is_empty()); + for &(object_index, _offset, pitch) in &layer.planes { + assert!((object_index as usize) < exported.objects.len()); + assert!(pitch > 0); + } + } + + let with_export = open_fd_count(); + assert_eq!( + with_export - baseline, + exported.objects.len(), + "exported fd count does not match the descriptor" + ); + drop(exported); + assert_eq!( + open_fd_count(), + baseline, + "dropping the export leaked file descriptors" + ); +} + +// -------------------------------------------------------------------------- +// Context / picture protocol +// -------------------------------------------------------------------------- + +#[test] +fn picture_typestate_walks_the_va_protocol() { + let _serial = serial(); + let display = display(); + let config = Config::new(&display, Profile::H264Main, Entrypoint::VLD, &[]).expect("config"); + let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 2).expect("pool"); + let context = + Context::new(&config, 1920, 1088, sys::VA_PROGRESSIVE, &targets).expect("context"); + + // New -> Rendering. Each transition consumes the picture, so nothing can + // call `begin` twice or reach `sync` without `end` (see the compile_fail + // examples in the `picture` module docs). + let picture = Picture::new(&context, Arc::clone(&targets[0])); + let picture = picture.begin().expect("vaBeginPicture"); + assert_eq!(picture.target().id(), targets[0].id()); + + // Rendering -> Ended. Submitting a picture with no parameter buffers is a + // driver-level error here (mesa creates the decoder lazily from the picture + // parameters, so it has nothing to end); what matters is that it surfaces + // as a typed error instead of a panic, an abort or a GPU hang. Real + // submissions carry parameter/slice buffers and are `ec-hw`'s job. + let err = picture + .end() + .expect_err("empty submission is rejected by radeonsi"); + assert_eq!( + err.status(), + Some(sys::VA_STATUS_ERROR_INVALID_CONTEXT), + "{err}" + ); + assert!(err.to_string().contains("vaEndPicture"), "{err}"); + + // The display is still usable afterwards: an abandoned picture must not + // wedge the context. + let picture = Picture::new(&context, Arc::clone(&targets[1])) + .begin() + .expect("second vaBeginPicture after a failed end"); + drop(picture); + assert!(display.is_valid()); +} + +#[test] +fn buffers_map_unmap_and_destroy() { + let _serial = serial(); + let display = display(); + let config = + Config::new(&display, Profile::H264Main, Entrypoint::EncSlice, &[]).expect("config"); + let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 1).expect("pool"); + let context = + Context::new(&config, 1920, 1088, sys::VA_PROGRESSIVE, &targets).expect("context"); + + // Coded-output buffer: allocated empty, mapped, written, unmapped, dropped. + const CODED_SIZE: u32 = 1 << 20; + let mut coded = ec_va::Buffer::allocate(&context, sys::VAEncCodedBufferType, CODED_SIZE) + .expect("vaCreateBuffer"); + assert_eq!(coded.buffer_type(), sys::VAEncCodedBufferType); + assert_ne!(coded.id(), sys::VA_INVALID_ID); + { + let mut mapped = coded.map().expect("vaMapBuffer"); + // SAFETY: 64 bytes of a 1 MiB allocation. + let slice = unsafe { mapped.as_mut_slice(64) }; + slice[0] = 0x42; + // SAFETY: same 64-byte window, now read-only. + assert_eq!(unsafe { mapped.as_slice(64) }[0], 0x42); + } + // Mapping again proves the guard released the mapping. + drop(coded.map().expect("second vaMapBuffer after unmap")); + + // Parameter buffer: data is copied into driver memory during the call. + let params = [0u8; 32]; + let buffer = ec_va::Buffer::from_bytes(&context, sys::VAEncMiscParameterBufferType, ¶ms) + .expect("vaCreateBuffer from bytes"); + assert_ne!(buffer.id(), sys::VA_INVALID_ID); + + // An empty buffer is refused before it reaches the driver. + let err = ec_va::Buffer::from_bytes(&context, sys::VAEncMiscParameterBufferType, &[]) + .expect_err("empty buffer must be refused"); + assert!(matches!(err, Error::Protocol(_)), "{err}"); +} + +#[test] +fn context_keeps_its_dependencies_alive() { + let _serial = serial(); + // Dropping the config and the surfaces while the context lives must be + // safe: the context holds `Arc`s, so libva's destruction order (buffers -> + // context -> surfaces -> config -> display) cannot be violated. + let display = display(); + let config = Config::new(&display, Profile::H264Main, Entrypoint::VLD, &[]).expect("config"); + let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 2).expect("pool"); + let context = + Context::new(&config, 1920, 1088, sys::VA_PROGRESSIVE, &targets).expect("context"); + let target = Arc::clone(&targets[0]); + drop(config); + drop(targets); + + let picture = Picture::new(&context, target).begin().expect("begin"); + drop(picture); + drop(context); + assert!(display.is_valid()); +} + +// -------------------------------------------------------------------------- +// helpers +// -------------------------------------------------------------------------- + +fn vm_rss_kb() -> u64 { + let status = std::fs::read_to_string("/proc/self/status").expect("/proc/self/status"); + for line in status.lines() { + if let Some(rest) = line.strip_prefix("VmRSS:") { + return rest + .split_whitespace() + .next() + .and_then(|v| v.parse().ok()) + .expect("VmRSS value"); + } + } + panic!("VmRSS not found in /proc/self/status"); +} + +fn open_fd_count() -> usize { + std::fs::read_dir("/proc/self/fd") + .expect("/proc/self/fd") + .count() +}