Hand-written libva FFI with RAII handles and picture typestate
Browse files at this commit0eac45755a8dd012f5e3b4f8b27ad5f04dcc25b9Parent: b73c680- feat
- hand-written libva FFI with RAII handles and picture typestate
11 changed files +3276 -0
- crates/ec-va/Cargo.toml +12 -0
- crates/ec-va/abi-probe.c +90 -0
- crates/ec-va/src/caps.rs +368 -0
- crates/ec-va/src/config.rs +233 -0
- crates/ec-va/src/display.rs +186 -0
- crates/ec-va/src/error.rs +148 -0
- crates/ec-va/src/lib.rs +65 -0
- crates/ec-va/src/picture.rs +547 -0
- crates/ec-va/src/surface.rs +567 -0
- crates/ec-va/src/sys.rs +558 -0
- crates/ec-va/tests/gpu.rs +502 -0
crates/ec-va/Cargo.tomladded+12 -0
| @@ -0,0 +1,12 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-va" | ||
| 3 | +description = "Minimal hand-written libva (VA-API) FFI and a safe RAII/typestate layer over it." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +# No dependencies, by design: the whole point of this crate is that the FFI | ||
| 10 | +# surface is small enough to be read end to end (see src/sys.rs). It links the | ||
| 11 | +# system libva/libva-drm shared objects; nothing is generated at build time. | ||
| 12 | +[dependencies] | ||
crates/ec-va/abi-probe.cadded+90 -0
| @@ -0,0 +1,90 @@ | |||
| 1 | +/* | ||
| 2 | + * ABI probe for the hand-written libva FFI in src/sys.rs. | ||
| 3 | + * | ||
| 4 | + * src/sys.rs transcribes libva struct layouts by hand (no bindgen, family rule). | ||
| 5 | + * This probe is the evidence for that transcription: it prints the sizes, | ||
| 6 | + * alignments and field offsets that the *system* headers produce, so the | ||
| 7 | + * `const _: () = assert!(...)` block in sys.rs can be checked against a real | ||
| 8 | + * compiler instead of against a reading of the header. | ||
| 9 | + * | ||
| 10 | + * Run: | ||
| 11 | + * cc -o /tmp/ec-va-abi-probe crates/ec-va/abi-probe.c $(pkg-config --cflags --libs libva) \ | ||
| 12 | + * && /tmp/ec-va-abi-probe | ||
| 13 | + * | ||
| 14 | + * Recorded output (libva 1.23.0, x86_64-unknown-linux-gnu, gcc 15) is pasted | ||
| 15 | + * into the assertion block in sys.rs. Any mismatch after a libva upgrade means | ||
| 16 | + * the transcription drifted — the exact failure mode that broke cros-libva at | ||
| 17 | + * libva >= 1.23. | ||
| 18 | + */ | ||
| 19 | +#include <stdio.h> | ||
| 20 | +#include <stddef.h> | ||
| 21 | +#include <va/va.h> | ||
| 22 | +#include <va/va_drmcommon.h> | ||
| 23 | + | ||
| 24 | +#define SA(T) printf("%-32s size=%-5zu align=%zu\n", #T, sizeof(T), _Alignof(T)) | ||
| 25 | +#define OF(T, F) printf(" %-30s offset=%zu\n", #T "." #F, offsetof(T, F)) | ||
| 26 | + | ||
| 27 | +int main(void) | ||
| 28 | +{ | ||
| 29 | + printf("libva headers: %s\n", VA_VERSION_S); | ||
| 30 | + | ||
| 31 | + SA(VAStatus); | ||
| 32 | + SA(VAGenericID); | ||
| 33 | + SA(VAProfile); | ||
| 34 | + SA(VAEntrypoint); | ||
| 35 | + SA(VAConfigAttribType); | ||
| 36 | + SA(VAConfigAttrib); | ||
| 37 | + OF(VAConfigAttrib, type); | ||
| 38 | + OF(VAConfigAttrib, value); | ||
| 39 | + | ||
| 40 | + SA(VAGenericValue); | ||
| 41 | + OF(VAGenericValue, type); | ||
| 42 | + OF(VAGenericValue, value); | ||
| 43 | + | ||
| 44 | + SA(VASurfaceAttrib); | ||
| 45 | + OF(VASurfaceAttrib, type); | ||
| 46 | + OF(VASurfaceAttrib, flags); | ||
| 47 | + OF(VASurfaceAttrib, value); | ||
| 48 | + | ||
| 49 | + SA(VAImageFormat); | ||
| 50 | + OF(VAImageFormat, fourcc); | ||
| 51 | + OF(VAImageFormat, byte_order); | ||
| 52 | + OF(VAImageFormat, bits_per_pixel); | ||
| 53 | + OF(VAImageFormat, depth); | ||
| 54 | + OF(VAImageFormat, red_mask); | ||
| 55 | + OF(VAImageFormat, alpha_mask); | ||
| 56 | + OF(VAImageFormat, va_reserved); | ||
| 57 | + | ||
| 58 | + SA(VAImage); | ||
| 59 | + OF(VAImage, image_id); | ||
| 60 | + OF(VAImage, format); | ||
| 61 | + OF(VAImage, buf); | ||
| 62 | + OF(VAImage, width); | ||
| 63 | + OF(VAImage, height); | ||
| 64 | + OF(VAImage, data_size); | ||
| 65 | + OF(VAImage, num_planes); | ||
| 66 | + OF(VAImage, pitches); | ||
| 67 | + OF(VAImage, offsets); | ||
| 68 | + OF(VAImage, num_palette_entries); | ||
| 69 | + OF(VAImage, entry_bytes); | ||
| 70 | + OF(VAImage, component_order); | ||
| 71 | + OF(VAImage, va_reserved); | ||
| 72 | + | ||
| 73 | + SA(VADRMPRIMESurfaceDescriptor); | ||
| 74 | + OF(VADRMPRIMESurfaceDescriptor, fourcc); | ||
| 75 | + OF(VADRMPRIMESurfaceDescriptor, width); | ||
| 76 | + OF(VADRMPRIMESurfaceDescriptor, height); | ||
| 77 | + OF(VADRMPRIMESurfaceDescriptor, num_objects); | ||
| 78 | + OF(VADRMPRIMESurfaceDescriptor, objects); | ||
| 79 | + OF(VADRMPRIMESurfaceDescriptor, num_layers); | ||
| 80 | + OF(VADRMPRIMESurfaceDescriptor, layers); | ||
| 81 | + printf(" object elem size=%zu align=%zu\n", | ||
| 82 | + sizeof(((VADRMPRIMESurfaceDescriptor *)0)->objects[0]), | ||
| 83 | + _Alignof(((VADRMPRIMESurfaceDescriptor *)0)->objects[0])); | ||
| 84 | + printf(" layer elem size=%zu align=%zu\n", | ||
| 85 | + sizeof(((VADRMPRIMESurfaceDescriptor *)0)->layers[0]), | ||
| 86 | + _Alignof(((VADRMPRIMESurfaceDescriptor *)0)->layers[0])); | ||
| 87 | + | ||
| 88 | + SA(VARectangle); | ||
| 89 | + return 0; | ||
| 90 | +} | ||
crates/ec-va/src/caps.rsadded+368 -0
| @@ -0,0 +1,368 @@ | |||
| 1 | +//! Capability probing: what this GPU can actually decode and encode. | ||
| 2 | +//! | ||
| 3 | +//! [`Profile`] and [`Entrypoint`] are safe mirrors of the C enums, each with an | ||
| 4 | +//! `Unknown(i32)` arm. That arm is not defensive decoration: `vaQueryConfigProfiles` | ||
| 5 | +//! writes driver-chosen `int`s into our array, and a newer libva can name a | ||
| 6 | +//! profile this build has never heard of. Decoding that into a `#[repr(i32)]` | ||
| 7 | +//! Rust enum would be undefined behaviour — which is exactly how header drift | ||
| 8 | +//! turns into a soundness bug. | ||
| 9 | + | ||
| 10 | +use std::sync::Arc; | ||
| 11 | + | ||
| 12 | +use crate::config::{Config, SurfaceCaps}; | ||
| 13 | +use crate::display::Display; | ||
| 14 | +use crate::error::{Result, check}; | ||
| 15 | +use crate::sys; | ||
| 16 | + | ||
| 17 | +/// Generates a safe enum mirroring a C enum, plus its raw conversions. | ||
| 18 | +/// | ||
| 19 | +/// One table, three derived functions — so the transcription can be diffed | ||
| 20 | +/// against the header in one place. | ||
| 21 | +macro_rules! va_enum { | ||
| 22 | + ( | ||
| 23 | + $(#[$meta:meta])* | ||
| 24 | + $name:ident : $raw:ty { | ||
| 25 | + $( $variant:ident = $value:expr , )* | ||
| 26 | + } | ||
| 27 | + ) => { | ||
| 28 | + $(#[$meta])* | ||
| 29 | + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] | ||
| 30 | + #[non_exhaustive] | ||
| 31 | + pub enum $name { | ||
| 32 | + $( #[allow(missing_docs)] $variant, )* | ||
| 33 | + /// A value this build does not know. Carried, never guessed at. | ||
| 34 | + Unknown(i32), | ||
| 35 | + } | ||
| 36 | + | ||
| 37 | + impl $name { | ||
| 38 | + /// Interpret a raw C value. Never panics, never UB. | ||
| 39 | + pub fn from_raw(raw: $raw) -> Self { | ||
| 40 | + match raw { | ||
| 41 | + $( $value => $name::$variant, )* | ||
| 42 | + other => $name::Unknown(other), | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + | ||
| 46 | + /// The raw C value. | ||
| 47 | + pub fn as_raw(self) -> $raw { | ||
| 48 | + match self { | ||
| 49 | + $( $name::$variant => $value, )* | ||
| 50 | + $name::Unknown(other) => other, | ||
| 51 | + } | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + /// The libva identifier, e.g. `"VAProfileH264High"`. | ||
| 55 | + pub fn name(self) -> &'static str { | ||
| 56 | + match self { | ||
| 57 | + $( $name::$variant => concat!(stringify!($name), "::", stringify!($variant)), )* | ||
| 58 | + $name::Unknown(_) => concat!(stringify!($name), "::Unknown"), | ||
| 59 | + } | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + }; | ||
| 63 | +} | ||
| 64 | + | ||
| 65 | +va_enum! { | ||
| 66 | + /// `VAProfile`, transcribed from `va.h:502-547` (libva 1.23). | ||
| 67 | + Profile: sys::VAProfile { | ||
| 68 | + None = -1, | ||
| 69 | + MPEG2Simple = 0, | ||
| 70 | + MPEG2Main = 1, | ||
| 71 | + MPEG4Simple = 2, | ||
| 72 | + MPEG4AdvancedSimple = 3, | ||
| 73 | + MPEG4Main = 4, | ||
| 74 | + H264Baseline = 5, | ||
| 75 | + H264Main = 6, | ||
| 76 | + H264High = 7, | ||
| 77 | + VC1Simple = 8, | ||
| 78 | + VC1Main = 9, | ||
| 79 | + VC1Advanced = 10, | ||
| 80 | + H263Baseline = 11, | ||
| 81 | + JPEGBaseline = 12, | ||
| 82 | + H264ConstrainedBaseline = 13, | ||
| 83 | + VP8Version0_3 = 14, | ||
| 84 | + H264MultiviewHigh = 15, | ||
| 85 | + H264StereoHigh = 16, | ||
| 86 | + HEVCMain = 17, | ||
| 87 | + HEVCMain10 = 18, | ||
| 88 | + VP9Profile0 = 19, | ||
| 89 | + VP9Profile1 = 20, | ||
| 90 | + VP9Profile2 = 21, | ||
| 91 | + VP9Profile3 = 22, | ||
| 92 | + HEVCMain12 = 23, | ||
| 93 | + HEVCMain422_10 = 24, | ||
| 94 | + HEVCMain422_12 = 25, | ||
| 95 | + HEVCMain444 = 26, | ||
| 96 | + HEVCMain444_10 = 27, | ||
| 97 | + HEVCMain444_12 = 28, | ||
| 98 | + HEVCSccMain = 29, | ||
| 99 | + HEVCSccMain10 = 30, | ||
| 100 | + HEVCSccMain444 = 31, | ||
| 101 | + AV1Profile0 = 32, | ||
| 102 | + AV1Profile1 = 33, | ||
| 103 | + HEVCSccMain444_10 = 34, | ||
| 104 | + Protected = 35, | ||
| 105 | + H264High10 = 36, | ||
| 106 | + VVCMain10 = 37, | ||
| 107 | + VVCMultilayerMain10 = 38, | ||
| 108 | + AV1Profile2 = 39, | ||
| 109 | + H264High422 = 40, | ||
| 110 | + } | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +va_enum! { | ||
| 114 | + /// `VAEntrypoint`, transcribed from `va.h:552-616` (libva 1.23). | ||
| 115 | + Entrypoint: sys::VAEntrypoint { | ||
| 116 | + VLD = 1, | ||
| 117 | + IZZ = 2, | ||
| 118 | + IDCT = 3, | ||
| 119 | + MoComp = 4, | ||
| 120 | + Deblocking = 5, | ||
| 121 | + EncSlice = 6, | ||
| 122 | + EncPicture = 7, | ||
| 123 | + EncSliceLP = 8, | ||
| 124 | + VideoProc = 10, | ||
| 125 | + FEI = 11, | ||
| 126 | + Stats = 12, | ||
| 127 | + ProtectedTEEComm = 13, | ||
| 128 | + ProtectedContent = 14, | ||
| 129 | + } | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +impl Profile { | ||
| 133 | + /// True for the profiles the family decodes or encodes in hardware. | ||
| 134 | + pub fn is_family_codec(self) -> bool { | ||
| 135 | + matches!( | ||
| 136 | + self, | ||
| 137 | + Profile::H264ConstrainedBaseline | ||
| 138 | + | Profile::H264Main | ||
| 139 | + | Profile::H264High | ||
| 140 | + | Profile::H264High10 | ||
| 141 | + | Profile::HEVCMain | ||
| 142 | + | Profile::HEVCMain10 | ||
| 143 | + | Profile::VP9Profile0 | ||
| 144 | + | Profile::VP9Profile2 | ||
| 145 | + | Profile::AV1Profile0 | ||
| 146 | + | Profile::AV1Profile2 | ||
| 147 | + ) | ||
| 148 | + } | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +/// What one (profile, entrypoint) pair supports. | ||
| 152 | +#[derive(Debug, Clone)] | ||
| 153 | +pub struct CapEntry { | ||
| 154 | + /// The profile. | ||
| 155 | + pub profile: Profile, | ||
| 156 | + /// The entrypoint. | ||
| 157 | + pub entrypoint: Entrypoint, | ||
| 158 | + /// `VAConfigAttribRTFormat` bitmask (`VA_RT_FORMAT_*`). | ||
| 159 | + pub rt_formats: u32, | ||
| 160 | + /// Surface geometry and pixel formats this config accepts, when the driver | ||
| 161 | + /// reports them. `None` if `vaQuerySurfaceAttributes` refused the config. | ||
| 162 | + pub surfaces: Option<SurfaceCaps>, | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +impl CapEntry { | ||
| 166 | + /// True if `rt_format` (a `VA_RT_FORMAT_*` bit) is in the mask. | ||
| 167 | + pub fn supports_rt_format(&self, rt_format: u32) -> bool { | ||
| 168 | + self.rt_formats & rt_format != 0 | ||
| 169 | + } | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +/// Everything the driver told us about itself. | ||
| 173 | +#[derive(Debug, Clone)] | ||
| 174 | +pub struct CapReport { | ||
| 175 | + /// `vaQueryVendorString`. | ||
| 176 | + pub vendor: String, | ||
| 177 | + /// Runtime libva version. | ||
| 178 | + pub version: (i32, i32), | ||
| 179 | + /// One entry per supported (profile, entrypoint) pair, in driver order. | ||
| 180 | + pub entries: Vec<CapEntry>, | ||
| 181 | + /// FourCCs from `vaQueryImageFormats` — the formats `vaGetImage` can produce. | ||
| 182 | + pub image_formats: Vec<u32>, | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +impl CapReport { | ||
| 186 | + /// Probe a display. One `vaCreateConfig`/`vaDestroyConfig` round trip per | ||
| 187 | + /// supported pair; ~15 pairs on a typical GPU, so this is cheap enough to | ||
| 188 | + /// do once at startup and cache. | ||
| 189 | + pub fn probe(display: &Arc<Display>) -> Result<CapReport> { | ||
| 190 | + let entries = probe_entries(display)?; | ||
| 191 | + Ok(CapReport { | ||
| 192 | + vendor: display.vendor()?, | ||
| 193 | + version: display.version(), | ||
| 194 | + entries, | ||
| 195 | + image_formats: query_image_formats(display)?, | ||
| 196 | + }) | ||
| 197 | + } | ||
| 198 | + | ||
| 199 | + /// The entry for a pair, if the driver supports it. | ||
| 200 | + pub fn entry(&self, profile: Profile, entrypoint: Entrypoint) -> Option<&CapEntry> { | ||
| 201 | + self.entries | ||
| 202 | + .iter() | ||
| 203 | + .find(|e| e.profile == profile && e.entrypoint == entrypoint) | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + /// True if this GPU supports the pair at all. | ||
| 207 | + pub fn supports(&self, profile: Profile, entrypoint: Entrypoint) -> bool { | ||
| 208 | + self.entry(profile, entrypoint).is_some() | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + /// Profiles supporting `entrypoint`, deduplicated, in driver order. | ||
| 212 | + pub fn profiles_for(&self, entrypoint: Entrypoint) -> Vec<Profile> { | ||
| 213 | + let mut out = Vec::new(); | ||
| 214 | + for e in self.entries.iter().filter(|e| e.entrypoint == entrypoint) { | ||
| 215 | + if !out.contains(&e.profile) { | ||
| 216 | + out.push(e.profile); | ||
| 217 | + } | ||
| 218 | + } | ||
| 219 | + out | ||
| 220 | + } | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +fn probe_entries(display: &Arc<Display>) -> Result<Vec<CapEntry>> { | ||
| 224 | + let mut entries = Vec::new(); | ||
| 225 | + for profile in query_profiles(display)? { | ||
| 226 | + for entrypoint in query_entrypoints(display, profile)? { | ||
| 227 | + let rt_formats = query_rt_formats(display, profile, entrypoint)?; | ||
| 228 | + // Creating the config is also how the legal surface sizes are | ||
| 229 | + // discovered: `vaQuerySurfaceAttributes` needs a config id. A | ||
| 230 | + // driver may refuse a pair it just advertised (radeonsi does this | ||
| 231 | + // for some encode entrypoints) — that is data, not an error, so it | ||
| 232 | + // lands as `surfaces: None` instead of failing the whole probe. | ||
| 233 | + let surfaces = match Config::new(display, profile, entrypoint, &[]) { | ||
| 234 | + Ok(config) => config.surface_caps().ok(), | ||
| 235 | + Err(_) => None, | ||
| 236 | + }; | ||
| 237 | + entries.push(CapEntry { | ||
| 238 | + profile, | ||
| 239 | + entrypoint, | ||
| 240 | + rt_formats, | ||
| 241 | + surfaces, | ||
| 242 | + }); | ||
| 243 | + } | ||
| 244 | + } | ||
| 245 | + Ok(entries) | ||
| 246 | +} | ||
| 247 | + | ||
| 248 | +fn query_profiles(display: &Arc<Display>) -> Result<Vec<Profile>> { | ||
| 249 | + // SAFETY: valid display; vaMaxNumProfiles only reads driver constants. | ||
| 250 | + let max = unsafe { sys::vaMaxNumProfiles(display.handle()) }; | ||
| 251 | + let max = max.max(0) as usize; | ||
| 252 | + let mut raw = vec![0 as sys::VAProfile; max]; | ||
| 253 | + let mut count: i32 = 0; | ||
| 254 | + // SAFETY: `raw` has `max` elements, which is the capacity libva promises | ||
| 255 | + // never to exceed (va.h:1524). `count` is a valid out-parameter. On return | ||
| 256 | + // only the first `count` entries are initialized, and only those are read. | ||
| 257 | + let status = | ||
| 258 | + unsafe { sys::vaQueryConfigProfiles(display.handle(), raw.as_mut_ptr(), &mut count) }; | ||
| 259 | + check("vaQueryConfigProfiles", status)?; | ||
| 260 | + raw.truncate(count.clamp(0, max as i32) as usize); | ||
| 261 | + Ok(raw.into_iter().map(Profile::from_raw).collect()) | ||
| 262 | +} | ||
| 263 | + | ||
| 264 | +fn query_entrypoints(display: &Arc<Display>, profile: Profile) -> Result<Vec<Entrypoint>> { | ||
| 265 | + // SAFETY: valid display; reads driver constants only. | ||
| 266 | + let max = unsafe { sys::vaMaxNumEntrypoints(display.handle()) }; | ||
| 267 | + let max = max.max(0) as usize; | ||
| 268 | + let mut raw = vec![0 as sys::VAEntrypoint; max]; | ||
| 269 | + let mut count: i32 = 0; | ||
| 270 | + // SAFETY: as in `query_profiles` — buffer sized by vaMaxNumEntrypoints, | ||
| 271 | + // valid out-parameter, only the reported prefix is read. | ||
| 272 | + let status = unsafe { | ||
| 273 | + sys::vaQueryConfigEntrypoints( | ||
| 274 | + display.handle(), | ||
| 275 | + profile.as_raw(), | ||
| 276 | + raw.as_mut_ptr(), | ||
| 277 | + &mut count, | ||
| 278 | + ) | ||
| 279 | + }; | ||
| 280 | + check("vaQueryConfigEntrypoints", status)?; | ||
| 281 | + raw.truncate(count.clamp(0, max as i32) as usize); | ||
| 282 | + Ok(raw.into_iter().map(Entrypoint::from_raw).collect()) | ||
| 283 | +} | ||
| 284 | + | ||
| 285 | +fn query_rt_formats( | ||
| 286 | + display: &Arc<Display>, | ||
| 287 | + profile: Profile, | ||
| 288 | + entrypoint: Entrypoint, | ||
| 289 | +) -> Result<u32> { | ||
| 290 | + let mut attrs = [sys::VAConfigAttrib { | ||
| 291 | + type_: sys::VAConfigAttribRTFormat, | ||
| 292 | + value: 0, | ||
| 293 | + }]; | ||
| 294 | + // SAFETY: `attrs` is a valid, initialized array of 1 VAConfigAttrib and the | ||
| 295 | + // length passed matches. vaGetConfigAttributes writes only `value`. | ||
| 296 | + let status = unsafe { | ||
| 297 | + sys::vaGetConfigAttributes( | ||
| 298 | + display.handle(), | ||
| 299 | + profile.as_raw(), | ||
| 300 | + entrypoint.as_raw(), | ||
| 301 | + attrs.as_mut_ptr(), | ||
| 302 | + attrs.len() as i32, | ||
| 303 | + ) | ||
| 304 | + }; | ||
| 305 | + check("vaGetConfigAttributes", status)?; | ||
| 306 | + Ok(attrs[0].value) | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +fn query_image_formats(display: &Arc<Display>) -> Result<Vec<u32>> { | ||
| 310 | + // SAFETY: valid display; reads driver constants only. | ||
| 311 | + let max = unsafe { sys::vaMaxNumImageFormats(display.handle()) }; | ||
| 312 | + let max = max.max(0) as usize; | ||
| 313 | + let mut formats = vec![sys::VAImageFormat::default(); max]; | ||
| 314 | + let mut count: i32 = 0; | ||
| 315 | + // SAFETY: buffer sized by vaMaxNumImageFormats as the header requires | ||
| 316 | + // (va.h:4773); `count` is a valid out-parameter; only the reported prefix | ||
| 317 | + // is read afterwards. | ||
| 318 | + let status = | ||
| 319 | + unsafe { sys::vaQueryImageFormats(display.handle(), formats.as_mut_ptr(), &mut count) }; | ||
| 320 | + check("vaQueryImageFormats", status)?; | ||
| 321 | + formats.truncate(count.clamp(0, max as i32) as usize); | ||
| 322 | + Ok(formats.into_iter().map(|f| f.fourcc).collect()) | ||
| 323 | +} | ||
| 324 | + | ||
| 325 | +/// A FourCC as its four ASCII characters, for logs and reports. | ||
| 326 | +pub fn fourcc_str(fourcc: u32) -> String { | ||
| 327 | + fourcc | ||
| 328 | + .to_le_bytes() | ||
| 329 | + .iter() | ||
| 330 | + .map(|&b| if b.is_ascii_graphic() { b as char } else { '?' }) | ||
| 331 | + .collect() | ||
| 332 | +} | ||
| 333 | + | ||
| 334 | +#[cfg(test)] | ||
| 335 | +mod tests { | ||
| 336 | + use super::*; | ||
| 337 | + | ||
| 338 | + #[test] | ||
| 339 | + fn profile_roundtrip_and_unknown_arm() { | ||
| 340 | + for raw in -1..=40 { | ||
| 341 | + let p = Profile::from_raw(raw); | ||
| 342 | + assert_eq!(p.as_raw(), raw, "roundtrip failed for {raw}"); | ||
| 343 | + assert_ne!(p, Profile::Unknown(raw), "{raw} should be a known profile"); | ||
| 344 | + } | ||
| 345 | + // A profile from a future libva must survive, not become UB or a panic. | ||
| 346 | + assert_eq!(Profile::from_raw(9_999), Profile::Unknown(9_999)); | ||
| 347 | + assert_eq!(Profile::from_raw(9_999).as_raw(), 9_999); | ||
| 348 | + assert_eq!(Profile::Unknown(9_999).name(), "Profile::Unknown"); | ||
| 349 | + assert_eq!(Profile::H264High.name(), "Profile::H264High"); | ||
| 350 | + } | ||
| 351 | + | ||
| 352 | + #[test] | ||
| 353 | + fn entrypoint_roundtrip_and_unknown_arm() { | ||
| 354 | + for raw in [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14] { | ||
| 355 | + assert_eq!(Entrypoint::from_raw(raw).as_raw(), raw); | ||
| 356 | + } | ||
| 357 | + // 9 is unassigned in libva 1.23 and 15 is beyond the table. | ||
| 358 | + assert_eq!(Entrypoint::from_raw(9), Entrypoint::Unknown(9)); | ||
| 359 | + assert_eq!(Entrypoint::from_raw(15), Entrypoint::Unknown(15)); | ||
| 360 | + } | ||
| 361 | + | ||
| 362 | + #[test] | ||
| 363 | + fn fourcc_rendering() { | ||
| 364 | + assert_eq!(fourcc_str(sys::VA_FOURCC_NV12), "NV12"); | ||
| 365 | + assert_eq!(fourcc_str(sys::VA_FOURCC_P010), "P010"); | ||
| 366 | + assert_eq!(fourcc_str(0), "????"); | ||
| 367 | + } | ||
| 368 | +} | ||
crates/ec-va/src/config.rsadded+233 -0
| @@ -0,0 +1,233 @@ | |||
| 1 | +//! [`Config`] — a `VAConfigID` for one (profile, entrypoint) pair, plus the | ||
| 2 | +//! surface geometry the driver will accept for it. | ||
| 3 | + | ||
| 4 | +use std::sync::Arc; | ||
| 5 | + | ||
| 6 | +use crate::caps::{Entrypoint, Profile}; | ||
| 7 | +use crate::display::Display; | ||
| 8 | +use crate::error::{Error, Result, check}; | ||
| 9 | +use crate::sys; | ||
| 10 | + | ||
| 11 | +/// A configuration attribute, e.g. `RTFormat = VA_RT_FORMAT_YUV420`. | ||
| 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 13 | +pub struct ConfigAttrib { | ||
| 14 | + /// `VAConfigAttrib*` type constant from [`crate::sys`]. | ||
| 15 | + pub type_: sys::VAConfigAttribType, | ||
| 16 | + /// Attribute value; meaning depends on `type_`. | ||
| 17 | + pub value: u32, | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +impl ConfigAttrib { | ||
| 21 | + /// `VAConfigAttribRTFormat` with the given `VA_RT_FORMAT_*` mask. | ||
| 22 | + pub fn rt_format(mask: u32) -> Self { | ||
| 23 | + ConfigAttrib { | ||
| 24 | + type_: sys::VAConfigAttribRTFormat, | ||
| 25 | + value: mask, | ||
| 26 | + } | ||
| 27 | + } | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/// Surface constraints reported for a config. | ||
| 31 | +/// | ||
| 32 | +/// The minimum sizes are the reason this type exists: radeonsi rejects | ||
| 33 | +/// surfaces below 64x64, and probing with a hardcoded 16x16 is how the | ||
| 34 | +/// incumbent stack used to panic on this GPU. | ||
| 35 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] | ||
| 36 | +pub struct SurfaceCaps { | ||
| 37 | + /// Smallest legal surface width, if reported. | ||
| 38 | + pub min_width: Option<u32>, | ||
| 39 | + /// Largest legal surface width, if reported. | ||
| 40 | + pub max_width: Option<u32>, | ||
| 41 | + /// Smallest legal surface height, if reported. | ||
| 42 | + pub min_height: Option<u32>, | ||
| 43 | + /// Largest legal surface height, if reported. | ||
| 44 | + pub max_height: Option<u32>, | ||
| 45 | + /// Pixel formats (FourCCs) the driver will allocate for this config. | ||
| 46 | + pub pixel_formats: Vec<u32>, | ||
| 47 | + /// `VASurfaceAttribMemoryType` bitmask, e.g. DRM PRIME 2 support. | ||
| 48 | + pub memory_types: u32, | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +impl SurfaceCaps { | ||
| 52 | + /// True if `width` x `height` is within the reported bounds. Unreported | ||
| 53 | + /// bounds are treated as "no constraint". | ||
| 54 | + pub fn allows(&self, width: u32, height: u32) -> bool { | ||
| 55 | + self.min_width.is_none_or(|v| width >= v) | ||
| 56 | + && self.max_width.is_none_or(|v| width <= v) | ||
| 57 | + && self.min_height.is_none_or(|v| height >= v) | ||
| 58 | + && self.max_height.is_none_or(|v| height <= v) | ||
| 59 | + } | ||
| 60 | + | ||
| 61 | + /// True if the driver will allocate this FourCC for the config. | ||
| 62 | + pub fn supports_fourcc(&self, fourcc: u32) -> bool { | ||
| 63 | + self.pixel_formats.contains(&fourcc) | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +/// A live `VAConfigID`. | ||
| 68 | +/// | ||
| 69 | +/// Held by `Arc` because a [`crate::Context`] must not outlive its config. | ||
| 70 | +pub struct Config { | ||
| 71 | + display: Arc<Display>, | ||
| 72 | + id: sys::VAConfigID, | ||
| 73 | + profile: Profile, | ||
| 74 | + entrypoint: Entrypoint, | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +impl Config { | ||
| 78 | + /// Create a config for `(profile, entrypoint)` with the given attributes. | ||
| 79 | + /// | ||
| 80 | + /// Pass `&[]` for the driver defaults — enough for capability probing; | ||
| 81 | + /// decode contexts want at least an explicit `RTFormat` so that a 10-bit | ||
| 82 | + /// stream gets a 10-bit config instead of silently getting an 8-bit one. | ||
| 83 | + pub fn new( | ||
| 84 | + display: &Arc<Display>, | ||
| 85 | + profile: Profile, | ||
| 86 | + entrypoint: Entrypoint, | ||
| 87 | + attribs: &[ConfigAttrib], | ||
| 88 | + ) -> Result<Arc<Config>> { | ||
| 89 | + let mut raw: Vec<sys::VAConfigAttrib> = attribs | ||
| 90 | + .iter() | ||
| 91 | + .map(|a| sys::VAConfigAttrib { | ||
| 92 | + type_: a.type_, | ||
| 93 | + value: a.value, | ||
| 94 | + }) | ||
| 95 | + .collect(); | ||
| 96 | + let mut id: sys::VAConfigID = sys::VA_INVALID_ID; | ||
| 97 | + // SAFETY: `raw` is a valid array of `raw.len()` VAConfigAttrib (a null | ||
| 98 | + // pointer with len 0 is also accepted by libva, and `as_mut_ptr` on an | ||
| 99 | + // empty Vec is a dangling-but-aligned pointer, which libva never | ||
| 100 | + // dereferences because the count is 0). `id` is a valid out-parameter. | ||
| 101 | + let status = unsafe { | ||
| 102 | + sys::vaCreateConfig( | ||
| 103 | + display.handle(), | ||
| 104 | + profile.as_raw(), | ||
| 105 | + entrypoint.as_raw(), | ||
| 106 | + raw.as_mut_ptr(), | ||
| 107 | + raw.len() as i32, | ||
| 108 | + &mut id, | ||
| 109 | + ) | ||
| 110 | + }; | ||
| 111 | + check("vaCreateConfig", status)?; | ||
| 112 | + if id == sys::VA_INVALID_ID { | ||
| 113 | + return Err(Error::Protocol( | ||
| 114 | + "vaCreateConfig succeeded but returned VA_INVALID_ID".to_string(), | ||
| 115 | + )); | ||
| 116 | + } | ||
| 117 | + Ok(Arc::new(Config { | ||
| 118 | + display: Arc::clone(display), | ||
| 119 | + id, | ||
| 120 | + profile, | ||
| 121 | + entrypoint, | ||
| 122 | + })) | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + /// Surface constraints for this config (`vaQuerySurfaceAttributes`). | ||
| 126 | + pub fn surface_caps(&self) -> Result<SurfaceCaps> { | ||
| 127 | + // Two-pass query: NULL first to learn the count, as documented at | ||
| 128 | + // va.h:1855 ("it is perfectly valid to pass NULL to attrib_list"). | ||
| 129 | + let mut count: u32 = 0; | ||
| 130 | + // SAFETY: valid display and config id; NULL attrib_list with a valid | ||
| 131 | + // count out-parameter is the documented "how many?" form. | ||
| 132 | + let status = unsafe { | ||
| 133 | + sys::vaQuerySurfaceAttributes( | ||
| 134 | + self.display.handle(), | ||
| 135 | + self.id, | ||
| 136 | + std::ptr::null_mut(), | ||
| 137 | + &mut count, | ||
| 138 | + ) | ||
| 139 | + }; | ||
| 140 | + check("vaQuerySurfaceAttributes", status)?; | ||
| 141 | + | ||
| 142 | + let mut attrs = vec![ | ||
| 143 | + sys::VASurfaceAttrib { | ||
| 144 | + type_: sys::VASurfaceAttribNone, | ||
| 145 | + flags: 0, | ||
| 146 | + value: sys::VAGenericValue { | ||
| 147 | + type_: sys::VAGenericValueTypeInteger, | ||
| 148 | + value: sys::VAGenericValueUnion { i: 0 }, | ||
| 149 | + }, | ||
| 150 | + }; | ||
| 151 | + count as usize | ||
| 152 | + ]; | ||
| 153 | + // SAFETY: `attrs` holds exactly `count` initialized elements, and | ||
| 154 | + // `count` is what the driver just asked for. It is passed by pointer | ||
| 155 | + // together with its length; libva rewrites `count` to the number | ||
| 156 | + // actually written, which cannot exceed the input. | ||
| 157 | + let status = unsafe { | ||
| 158 | + sys::vaQuerySurfaceAttributes( | ||
| 159 | + self.display.handle(), | ||
| 160 | + self.id, | ||
| 161 | + attrs.as_mut_ptr(), | ||
| 162 | + &mut count, | ||
| 163 | + ) | ||
| 164 | + }; | ||
| 165 | + check("vaQuerySurfaceAttributes", status)?; | ||
| 166 | + attrs.truncate(count as usize); | ||
| 167 | + | ||
| 168 | + let mut caps = SurfaceCaps::default(); | ||
| 169 | + for attr in &attrs { | ||
| 170 | + if attr.flags & sys::VA_SURFACE_ATTRIB_GETTABLE == 0 { | ||
| 171 | + continue; | ||
| 172 | + } | ||
| 173 | + // Every attribute read below is documented as an integer | ||
| 174 | + // (va.h:1691-1730). A driver contradicting that is a protocol | ||
| 175 | + // error, not something to reinterpret: reading the wrong union arm | ||
| 176 | + // is precisely the class of bug this crate exists to avoid. | ||
| 177 | + if attr.value.type_ != sys::VAGenericValueTypeInteger { | ||
| 178 | + continue; | ||
| 179 | + } | ||
| 180 | + // SAFETY: the discriminant was just checked to be Integer, so the | ||
| 181 | + // `i` arm of the union is the initialized one. | ||
| 182 | + let value = unsafe { attr.value.value.i }; | ||
| 183 | + match attr.type_ { | ||
| 184 | + sys::VASurfaceAttribPixelFormat => caps.pixel_formats.push(value as u32), | ||
| 185 | + sys::VASurfaceAttribMinWidth => caps.min_width = Some(value.max(0) as u32), | ||
| 186 | + sys::VASurfaceAttribMaxWidth => caps.max_width = Some(value.max(0) as u32), | ||
| 187 | + sys::VASurfaceAttribMinHeight => caps.min_height = Some(value.max(0) as u32), | ||
| 188 | + sys::VASurfaceAttribMaxHeight => caps.max_height = Some(value.max(0) as u32), | ||
| 189 | + sys::VASurfaceAttribMemoryType => caps.memory_types = value as u32, | ||
| 190 | + _ => {} | ||
| 191 | + } | ||
| 192 | + } | ||
| 193 | + Ok(caps) | ||
| 194 | + } | ||
| 195 | + | ||
| 196 | + /// The profile this config was created for. | ||
| 197 | + pub fn profile(&self) -> Profile { | ||
| 198 | + self.profile | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + /// The entrypoint this config was created for. | ||
| 202 | + pub fn entrypoint(&self) -> Entrypoint { | ||
| 203 | + self.entrypoint | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + /// The display this config belongs to. | ||
| 207 | + pub fn display(&self) -> &Arc<Display> { | ||
| 208 | + &self.display | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + pub(crate) fn id(&self) -> sys::VAConfigID { | ||
| 212 | + self.id | ||
| 213 | + } | ||
| 214 | +} | ||
| 215 | + | ||
| 216 | +impl std::fmt::Debug for Config { | ||
| 217 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 218 | + f.debug_struct("Config") | ||
| 219 | + .field("id", &self.id) | ||
| 220 | + .field("profile", &self.profile) | ||
| 221 | + .field("entrypoint", &self.entrypoint) | ||
| 222 | + .finish() | ||
| 223 | + } | ||
| 224 | +} | ||
| 225 | + | ||
| 226 | +impl Drop for Config { | ||
| 227 | + fn drop(&mut self) { | ||
| 228 | + // SAFETY: `self.id` was returned by vaCreateConfig on `self.display` | ||
| 229 | + // and has not been destroyed. Contexts hold an `Arc<Config>`, so no | ||
| 230 | + // context can still reference it here. | ||
| 231 | + unsafe { sys::vaDestroyConfig(self.display.handle(), self.id) }; | ||
| 232 | + } | ||
| 233 | +} | ||
crates/ec-va/src/display.rsadded+186 -0
| @@ -0,0 +1,186 @@ | |||
| 1 | +//! [`Display`] — an initialized `VADisplay` on a DRM render node. | ||
| 2 | + | ||
| 3 | +use std::ffi::CStr; | ||
| 4 | +use std::fs::File; | ||
| 5 | +use std::os::fd::AsRawFd; | ||
| 6 | +use std::path::{Path, PathBuf}; | ||
| 7 | +use std::sync::Arc; | ||
| 8 | + | ||
| 9 | +use crate::error::{Error, Result, check}; | ||
| 10 | +use crate::sys; | ||
| 11 | + | ||
| 12 | +/// An initialized VA display, owning both the DRM file descriptor and the | ||
| 13 | +/// `VADisplay` derived from it. | ||
| 14 | +/// | ||
| 15 | +/// Everything else in this crate holds an `Arc<Display>`, so the display is | ||
| 16 | +/// terminated only after the last surface, config, context and buffer is gone — | ||
| 17 | +/// the ordering libva requires, enforced by the type system rather than by | ||
| 18 | +/// documentation. | ||
| 19 | +pub struct Display { | ||
| 20 | + /// Raw `VADisplay`. Valid until [`Drop`] calls `vaTerminate`. | ||
| 21 | + handle: sys::VADisplay, | ||
| 22 | + /// The render node. Must outlive `handle`: libva does not dup the fd. | ||
| 23 | + node: File, | ||
| 24 | + path: PathBuf, | ||
| 25 | + version: (i32, i32), | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +// SAFETY: libva's dispatch layer (`va.c`) and the Mesa VA driver both take an | ||
| 29 | +// internal lock per display around every entry point used here, so a | ||
| 30 | +// `VADisplay` may be used from any thread and from several threads at once. | ||
| 31 | +// The `File` and `PathBuf` fields are themselves `Send + Sync`. This mirrors | ||
| 32 | +// what every VA-API consumer (ffmpeg, GStreamer, cros-libva) relies on. | ||
| 33 | +// | ||
| 34 | +// Note the narrower claim this crate actually needs: `&Display` is only ever | ||
| 35 | +// used to *call* libva, never to hand out interior pointers. | ||
| 36 | +unsafe impl Send for Display {} | ||
| 37 | +// SAFETY: see above. | ||
| 38 | +unsafe impl Sync for Display {} | ||
| 39 | + | ||
| 40 | +impl Display { | ||
| 41 | + /// Open the first usable DRM render node (`/dev/dri/renderD128` upwards). | ||
| 42 | + /// | ||
| 43 | + /// Render nodes are used rather than card nodes: they need no DRM master | ||
| 44 | + /// and no display server, which is what a headless encode/decode pipeline | ||
| 45 | + /// wants. | ||
| 46 | + pub fn open() -> Result<Arc<Display>> { | ||
| 47 | + let mut last: Option<Error> = None; | ||
| 48 | + // 128..=143 is the kernel's render-node numbering (16 GPUs is plenty). | ||
| 49 | + for n in 128..=143u32 { | ||
| 50 | + let path = PathBuf::from(format!("/dev/dri/renderD{n}")); | ||
| 51 | + if !path.exists() { | ||
| 52 | + continue; | ||
| 53 | + } | ||
| 54 | + match Display::open_path(&path) { | ||
| 55 | + Ok(display) => return Ok(display), | ||
| 56 | + Err(e) => last = Some(e), | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | + Err(last.unwrap_or(Error::NoDevice)) | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + /// Open a specific DRM node, e.g. `/dev/dri/renderD128`. | ||
| 63 | + /// | ||
| 64 | + /// The node is opened **read-write**, and that is not a detail: with a | ||
| 65 | + /// read-only fd radeonsi 26.1 fails `amdgpu_bo_cpu_map` and then segfaults | ||
| 66 | + /// *inside* `vaInitialize`, before it can return a status this crate could | ||
| 67 | + /// turn into an error. Verified on this machine (gfx1200, Mesa 26.1.6). | ||
| 68 | + pub fn open_path(path: &Path) -> Result<Arc<Display>> { | ||
| 69 | + let node = File::options() | ||
| 70 | + .read(true) | ||
| 71 | + .write(true) | ||
| 72 | + .open(path) | ||
| 73 | + .map_err(|source| Error::Drm { | ||
| 74 | + path: path.display().to_string(), | ||
| 75 | + source, | ||
| 76 | + })?; | ||
| 77 | + | ||
| 78 | + // SAFETY: `node` is an open DRM fd that lives as long as the returned | ||
| 79 | + // Display (it is moved into it below, and closed only after | ||
| 80 | + // vaTerminate in Drop). vaGetDisplayDRM does not take ownership of the | ||
| 81 | + // fd and returns NULL on failure, which is checked. | ||
| 82 | + let handle = unsafe { sys::vaGetDisplayDRM(node.as_raw_fd()) }; | ||
| 83 | + if handle.is_null() { | ||
| 84 | + return Err(Error::va( | ||
| 85 | + "vaGetDisplayDRM", | ||
| 86 | + sys::VA_STATUS_ERROR_OPERATION_FAILED, | ||
| 87 | + )); | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + let mut major: i32 = 0; | ||
| 91 | + let mut minor: i32 = 0; | ||
| 92 | + // SAFETY: `handle` is a non-NULL VADisplay from vaGetDisplayDRM; the | ||
| 93 | + // two out-parameters are valid, aligned, initialized `int`s that | ||
| 94 | + // outlive the call. | ||
| 95 | + let status = unsafe { sys::vaInitialize(handle, &mut major, &mut minor) }; | ||
| 96 | + if let Err(e) = check("vaInitialize", status) { | ||
| 97 | + // libva allocates display state inside vaGetDisplayDRM, so a failed | ||
| 98 | + // initialize still has to be terminated or that state leaks. This | ||
| 99 | + // is what ffmpeg's vaapi_device_create does on its failure path. | ||
| 100 | + // | ||
| 101 | + // SAFETY: `handle` is still a valid (if uninitialized) VADisplay; | ||
| 102 | + // vaTerminate accepts exactly this state. | ||
| 103 | + unsafe { sys::vaTerminate(handle) }; | ||
| 104 | + return Err(e); | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + // Runtime drift guard. The struct layouts in `sys` are transcribed from | ||
| 108 | + // the 1.23 headers; talking to an older runtime would be guesswork. | ||
| 109 | + if major != crate::MIN_VA_MAJOR || minor < crate::MIN_VA_MINOR { | ||
| 110 | + // SAFETY: initialize succeeded, so terminating is required and valid. | ||
| 111 | + unsafe { sys::vaTerminate(handle) }; | ||
| 112 | + return Err(Error::Version { major, minor }); | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + Ok(Arc::new(Display { | ||
| 116 | + handle, | ||
| 117 | + node, | ||
| 118 | + path: path.to_path_buf(), | ||
| 119 | + version: (major, minor), | ||
| 120 | + })) | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + /// The raw handle, for the rest of the crate's FFI calls. | ||
| 124 | + pub(crate) fn handle(&self) -> sys::VADisplay { | ||
| 125 | + self.handle | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + /// Runtime libva version as `(major, minor)`, from `vaInitialize`. | ||
| 129 | + pub fn version(&self) -> (i32, i32) { | ||
| 130 | + self.version | ||
| 131 | + } | ||
| 132 | + | ||
| 133 | + /// The DRM node this display was opened on. | ||
| 134 | + pub fn device_path(&self) -> &Path { | ||
| 135 | + &self.path | ||
| 136 | + } | ||
| 137 | + | ||
| 138 | + /// The raw DRM render-node fd. Borrowed, never closed by the caller. | ||
| 139 | + pub fn drm_fd(&self) -> std::os::fd::BorrowedFd<'_> { | ||
| 140 | + // `File` guarantees the fd is open for as long as `self` lives. | ||
| 141 | + std::os::fd::AsFd::as_fd(&self.node) | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + /// Driver vendor string, e.g. `"Mesa Gallium driver 26.1.6 for AMD ..."`. | ||
| 145 | + pub fn vendor(&self) -> Result<String> { | ||
| 146 | + // SAFETY: `self.handle` is initialized and valid for the lifetime of | ||
| 147 | + // `self`. The returned pointer is owned by the driver and stays valid | ||
| 148 | + // until vaTerminate, i.e. strictly longer than this borrow; the string | ||
| 149 | + // is copied before returning. | ||
| 150 | + let ptr = unsafe { sys::vaQueryVendorString(self.handle) }; | ||
| 151 | + if ptr.is_null() { | ||
| 152 | + return Err(Error::Protocol( | ||
| 153 | + "vaQueryVendorString returned NULL".to_string(), | ||
| 154 | + )); | ||
| 155 | + } | ||
| 156 | + // SAFETY: non-NULL, NUL-terminated, driver-owned static string. | ||
| 157 | + Ok(unsafe { CStr::from_ptr(ptr) } | ||
| 158 | + .to_string_lossy() | ||
| 159 | + .into_owned()) | ||
| 160 | + } | ||
| 161 | + | ||
| 162 | + /// `vaDisplayIsValid`, mostly useful in tests. | ||
| 163 | + pub fn is_valid(&self) -> bool { | ||
| 164 | + // SAFETY: `self.handle` is a valid VADisplay for the lifetime of `self`. | ||
| 165 | + unsafe { sys::vaDisplayIsValid(self.handle) != 0 } | ||
| 166 | + } | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +impl std::fmt::Debug for Display { | ||
| 170 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 171 | + f.debug_struct("Display") | ||
| 172 | + .field("path", &self.path) | ||
| 173 | + .field("version", &self.version) | ||
| 174 | + .finish_non_exhaustive() | ||
| 175 | + } | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +impl Drop for Display { | ||
| 179 | + fn drop(&mut self) { | ||
| 180 | + // SAFETY: `self.handle` was initialized in `open_path` and no child | ||
| 181 | + // object can still be alive: every one of them holds an `Arc<Display>`, | ||
| 182 | + // so this runs only after the last of them was dropped. `self.node` is | ||
| 183 | + // closed after this, as libva requires. | ||
| 184 | + unsafe { sys::vaTerminate(self.handle) }; | ||
| 185 | + } | ||
| 186 | +} | ||
crates/ec-va/src/error.rsadded+148 -0
| @@ -0,0 +1,148 @@ | |||
| 1 | +//! Typed errors. Every `VAStatus` that is not `VA_STATUS_SUCCESS` becomes an | ||
| 2 | +//! [`Error::Va`] carrying the failing entry point, the raw status and libva's | ||
| 3 | +//! own description of it — a bare status number in a log is a bug report | ||
| 4 | +//! waiting to happen. | ||
| 5 | + | ||
| 6 | +use std::ffi::CStr; | ||
| 7 | +use std::fmt; | ||
| 8 | + | ||
| 9 | +use crate::sys; | ||
| 10 | + | ||
| 11 | +/// Result alias for this crate. | ||
| 12 | +pub type Result<T> = std::result::Result<T, Error>; | ||
| 13 | + | ||
| 14 | +/// Everything that can go wrong between here and the driver. | ||
| 15 | +#[derive(Debug)] | ||
| 16 | +#[non_exhaustive] | ||
| 17 | +pub enum Error { | ||
| 18 | + /// A libva entry point returned a failing `VAStatus`. | ||
| 19 | + Va { | ||
| 20 | + /// The libva function that failed, e.g. `"vaCreateConfig"`. | ||
| 21 | + op: &'static str, | ||
| 22 | + /// The raw `VAStatus`. | ||
| 23 | + status: sys::VAStatus, | ||
| 24 | + /// `vaErrorStr(status)`. | ||
| 25 | + message: String, | ||
| 26 | + }, | ||
| 27 | + /// Opening a DRM render node failed. | ||
| 28 | + Drm { | ||
| 29 | + /// The device path that was tried. | ||
| 30 | + path: String, | ||
| 31 | + /// The underlying `open(2)` failure. | ||
| 32 | + source: std::io::Error, | ||
| 33 | + }, | ||
| 34 | + /// No `/dev/dri/renderD*` node could be opened as a VA display. | ||
| 35 | + NoDevice, | ||
| 36 | + /// The runtime libva is older than the ABI this crate transcribes. | ||
| 37 | + /// | ||
| 38 | + /// This is the drift guard: the struct layouts in [`crate::sys`] are | ||
| 39 | + /// compile-time transcriptions of the 1.23 headers, so refusing to talk to | ||
| 40 | + /// an older runtime is the only sound answer. | ||
| 41 | + Version { | ||
| 42 | + /// Runtime major version reported by `vaInitialize`. | ||
| 43 | + major: i32, | ||
| 44 | + /// Runtime minor version reported by `vaInitialize`. | ||
| 45 | + minor: i32, | ||
| 46 | + }, | ||
| 47 | + /// The driver returned something this FFI cannot interpret. | ||
| 48 | + /// | ||
| 49 | + /// Not a bitstream error and not a status code — a shape violation, e.g. a | ||
| 50 | + /// surface attribute whose value type contradicts its documented type. | ||
| 51 | + Protocol(String), | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +impl Error { | ||
| 55 | + /// Build an [`Error::Va`] for `op`, looking the status string up in libva. | ||
| 56 | + pub(crate) fn va(op: &'static str, status: sys::VAStatus) -> Self { | ||
| 57 | + Error::Va { | ||
| 58 | + op, | ||
| 59 | + status, | ||
| 60 | + message: status_str(status), | ||
| 61 | + } | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + /// The raw `VAStatus`, when this error came from a libva call. | ||
| 65 | + pub fn status(&self) -> Option<sys::VAStatus> { | ||
| 66 | + match self { | ||
| 67 | + Error::Va { status, .. } => Some(*status), | ||
| 68 | + _ => None, | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// `vaErrorStr` as an owned Rust string. | ||
| 74 | +pub(crate) fn status_str(status: sys::VAStatus) -> String { | ||
| 75 | + // SAFETY: `vaErrorStr` is documented (va.h:401) to return a pointer to a | ||
| 76 | + // static, NUL-terminated english description for any input value — | ||
| 77 | + // unknown codes map to a fallback string rather than NULL. It reads no | ||
| 78 | + // global state we mutate, so it is safe to call at any time, including | ||
| 79 | + // before vaInitialize. The pointer is static, so building a CStr from it | ||
| 80 | + // and copying is sound; the copy outlives the borrow. | ||
| 81 | + let ptr = unsafe { sys::vaErrorStr(status) }; | ||
| 82 | + if ptr.is_null() { | ||
| 83 | + return format!("VAStatus 0x{status:08x}"); | ||
| 84 | + } | ||
| 85 | + // SAFETY: non-NULL and NUL-terminated per the contract above. | ||
| 86 | + unsafe { CStr::from_ptr(ptr) } | ||
| 87 | + .to_string_lossy() | ||
| 88 | + .into_owned() | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// Turn a `VAStatus` into a `Result`, tagging it with the entry point name. | ||
| 92 | +pub(crate) fn check(op: &'static str, status: sys::VAStatus) -> Result<()> { | ||
| 93 | + if status == sys::VA_STATUS_SUCCESS { | ||
| 94 | + Ok(()) | ||
| 95 | + } else { | ||
| 96 | + Err(Error::va(op, status)) | ||
| 97 | + } | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +impl fmt::Display for Error { | ||
| 101 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| 102 | + match self { | ||
| 103 | + Error::Va { | ||
| 104 | + op, | ||
| 105 | + status, | ||
| 106 | + message, | ||
| 107 | + } => write!(f, "{op} failed: {message} (VAStatus 0x{status:08x})"), | ||
| 108 | + Error::Drm { path, source } => write!(f, "opening DRM node {path}: {source}"), | ||
| 109 | + Error::NoDevice => write!(f, "no usable /dev/dri/renderD* VA display"), | ||
| 110 | + Error::Version { major, minor } => write!( | ||
| 111 | + f, | ||
| 112 | + "libva {major}.{minor} is older than the {}.{} ABI this build transcribes", | ||
| 113 | + crate::MIN_VA_MAJOR, | ||
| 114 | + crate::MIN_VA_MINOR | ||
| 115 | + ), | ||
| 116 | + Error::Protocol(what) => write!(f, "libva returned an uninterpretable value: {what}"), | ||
| 117 | + } | ||
| 118 | + } | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +impl std::error::Error for Error { | ||
| 122 | + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | ||
| 123 | + match self { | ||
| 124 | + Error::Drm { source, .. } => Some(source), | ||
| 125 | + _ => None, | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +#[cfg(test)] | ||
| 131 | +mod tests { | ||
| 132 | + use super::*; | ||
| 133 | + | ||
| 134 | + #[test] | ||
| 135 | + fn status_strings_come_from_libva() { | ||
| 136 | + assert_eq!(status_str(sys::VA_STATUS_SUCCESS), "success (no error)"); | ||
| 137 | + // Any unknown code must still produce a string, never a panic or NULL deref. | ||
| 138 | + assert!(!status_str(0x7fff_0000).is_empty()); | ||
| 139 | + } | ||
| 140 | + | ||
| 141 | + #[test] | ||
| 142 | + fn check_maps_success_and_failure() { | ||
| 143 | + assert!(check("vaFake", sys::VA_STATUS_SUCCESS).is_ok()); | ||
| 144 | + let err = check("vaFake", sys::VA_STATUS_ERROR_UNIMPLEMENTED).unwrap_err(); | ||
| 145 | + assert_eq!(err.status(), Some(sys::VA_STATUS_ERROR_UNIMPLEMENTED)); | ||
| 146 | + assert!(err.to_string().contains("vaFake")); | ||
| 147 | + } | ||
| 148 | +} | ||
crates/ec-va/src/lib.rsadded+65 -0
| @@ -0,0 +1,65 @@ | |||
| 1 | +//! Minimal libva (VA-API) bindings and a safe layer over them. | ||
| 2 | +//! | ||
| 3 | +//! This is the hardware-video foundation of the `edith_codecs` family: `ec-hw` | ||
| 4 | +//! builds stateless VA-API decoders and encoders on top of it, and nothing else | ||
| 5 | +//! in the family talks to libva directly. | ||
| 6 | +//! | ||
| 7 | +//! # Shape | ||
| 8 | +//! | ||
| 9 | +//! * [`sys`] — the entire FFI surface, hand-written, one screenful per concern. | ||
| 10 | +//! Every ABI assumption is stated there and checked by a `const` assertion | ||
| 11 | +//! against numbers printed by `crates/ec-va/abi-probe.c`. | ||
| 12 | +//! * Everything else is safe: [`Display`], [`Config`], [`Surface`], [`Context`] | ||
| 13 | +//! and [`Buffer`] are RAII handles that destroy exactly what they created, in | ||
| 14 | +//! the order libva requires (each child holds an `Arc` of its parent, so the | ||
| 15 | +//! ordering is a borrow-checker fact rather than a review comment). | ||
| 16 | +//! * [`Picture`] encodes the `begin -> render -> end -> sync` protocol as a | ||
| 17 | +//! typestate machine, so submitting out of order does not compile. | ||
| 18 | +//! | ||
| 19 | +//! # Version policy | ||
| 20 | +//! | ||
| 21 | +//! Built against libva **1.23** headers and refuses older runtimes with | ||
| 22 | +//! [`Error::Version`]. The alternative — assuming a struct layout and finding | ||
| 23 | +//! out at runtime — is what broke the previous generation of VA-API bindings | ||
| 24 | +//! when 1.23 shifted their generated definitions. | ||
| 25 | +//! | ||
| 26 | +//! # Example | ||
| 27 | +//! | ||
| 28 | +//! ```no_run | ||
| 29 | +//! use ec_va::{CapReport, Display, Surface, SurfaceSpec}; | ||
| 30 | +//! use ec_va::caps::{Entrypoint, Profile}; | ||
| 31 | +//! | ||
| 32 | +//! let display = Display::open()?; | ||
| 33 | +//! let caps = CapReport::probe(&display)?; | ||
| 34 | +//! assert!(caps.supports(Profile::H264Main, Entrypoint::VLD)); | ||
| 35 | +//! | ||
| 36 | +//! let surfaces = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 8)?; | ||
| 37 | +//! # Ok::<(), ec_va::Error>(()) | ||
| 38 | +//! ``` | ||
| 39 | + | ||
| 40 | +#![deny(missing_docs)] | ||
| 41 | +#![deny(unsafe_op_in_unsafe_fn)] | ||
| 42 | + | ||
| 43 | +pub mod caps; | ||
| 44 | +pub mod config; | ||
| 45 | +pub mod display; | ||
| 46 | +pub mod error; | ||
| 47 | +pub mod picture; | ||
| 48 | +pub mod surface; | ||
| 49 | +pub mod sys; | ||
| 50 | + | ||
| 51 | +pub use caps::{CapEntry, CapReport, Entrypoint, Profile, fourcc_str}; | ||
| 52 | +pub use config::{Config, ConfigAttrib, SurfaceCaps}; | ||
| 53 | +pub use display::Display; | ||
| 54 | +pub use error::{Error, Result}; | ||
| 55 | +pub use picture::{ | ||
| 56 | + Buffer, Context, Ended, MappedBuffer, New, Picture, PictureState, Rendering, Synced, | ||
| 57 | +}; | ||
| 58 | +pub use surface::{ | ||
| 59 | + Image, MappedImage, PrimeLayer, PrimeObject, PrimeSurface, Surface, SurfaceSpec, | ||
| 60 | +}; | ||
| 61 | + | ||
| 62 | +/// Major libva version this crate's ABI transcription targets. | ||
| 63 | +pub const MIN_VA_MAJOR: i32 = 1; | ||
| 64 | +/// Minimum libva minor version accepted at runtime. | ||
| 65 | +pub const MIN_VA_MINOR: i32 = 23; | ||
crates/ec-va/src/picture.rsadded+547 -0
| @@ -0,0 +1,547 @@ | |||
| 1 | +//! [`Context`], [`Buffer`] and the [`Picture`] typestate machine. | ||
| 2 | +//! | ||
| 3 | +//! VA-API's submission protocol is a state machine: `vaBeginPicture` -> | ||
| 4 | +//! N x `vaRenderPicture` -> `vaEndPicture` -> `vaSyncSurface`. Calling those out | ||
| 5 | +//! of order is a driver-defined mess (at best an error, at worst a GPU hang), | ||
| 6 | +//! and it is not something a code review reliably catches. | ||
| 7 | +//! | ||
| 8 | +//! So the order is in the type system. Each transition consumes the picture and | ||
| 9 | +//! returns it in the next state; there is no method to skip a step and no way | ||
| 10 | +//! to name an intermediate state that was never reached: | ||
| 11 | +//! | ||
| 12 | +//! ```text | ||
| 13 | +//! Picture<New> --begin()--> Picture<Rendering> --render(buf)--> Picture<Rendering> | ||
| 14 | +//! --end()-------> Picture<Ended> | ||
| 15 | +//! --sync()------> Picture<Synced> | ||
| 16 | +//! ``` | ||
| 17 | +//! | ||
| 18 | +//! The legal walk compiles: | ||
| 19 | +//! | ||
| 20 | +//! ```no_run | ||
| 21 | +//! # use ec_va::{Buffer, Context, Picture, Surface}; | ||
| 22 | +//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>, buffer: Buffer) | ||
| 23 | +//! # -> ec_va::Result<()> { | ||
| 24 | +//! let surface = Picture::new(context, target) | ||
| 25 | +//! .begin()? | ||
| 26 | +//! .render(buffer)? | ||
| 27 | +//! .end()? | ||
| 28 | +//! .sync()? | ||
| 29 | +//! .into_surface(); | ||
| 30 | +//! # Ok(()) | ||
| 31 | +//! # } | ||
| 32 | +//! ``` | ||
| 33 | +//! | ||
| 34 | +//! Ordering violations are compile errors (`E0599`: the method does not exist | ||
| 35 | +//! on that state): | ||
| 36 | +//! | ||
| 37 | +//! ```compile_fail,E0599 | ||
| 38 | +//! # use ec_va::{Context, Picture, Surface}; | ||
| 39 | +//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>) { | ||
| 40 | +//! let picture = Picture::new(context, target); | ||
| 41 | +//! // ERROR: no method `end` on `Picture<New>` — begin() was never called. | ||
| 42 | +//! let ended = picture.end().unwrap(); | ||
| 43 | +//! # } | ||
| 44 | +//! ``` | ||
| 45 | +//! | ||
| 46 | +//! ```compile_fail,E0599 | ||
| 47 | +//! # use ec_va::{Context, Picture, Surface}; | ||
| 48 | +//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>) { | ||
| 49 | +//! let picture = Picture::new(context, target).begin().unwrap(); | ||
| 50 | +//! // ERROR: no method `sync` on `Picture<Rendering>` — end() must come first. | ||
| 51 | +//! let synced = picture.sync().unwrap(); | ||
| 52 | +//! # } | ||
| 53 | +//! ``` | ||
| 54 | +//! | ||
| 55 | +//! ```compile_fail,E0599 | ||
| 56 | +//! # use ec_va::{Buffer, Context, Picture, Surface}; | ||
| 57 | +//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>, buffer: Buffer) { | ||
| 58 | +//! let picture = Picture::new(context, target).begin().unwrap().end().unwrap(); | ||
| 59 | +//! // ERROR: no method `render` on `Picture<Ended>` — the picture is closed. | ||
| 60 | +//! let rendered = picture.render(buffer).unwrap(); | ||
| 61 | +//! # } | ||
| 62 | +//! ``` | ||
| 63 | +//! | ||
| 64 | +//! ```compile_fail,E0599 | ||
| 65 | +//! # use ec_va::{Context, Picture, Surface}; | ||
| 66 | +//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>) { | ||
| 67 | +//! let picture = Picture::new(context, target).begin().unwrap(); | ||
| 68 | +//! // ERROR: no method `begin` on `Picture<Rendering>` — no double submission. | ||
| 69 | +//! let again = picture.begin().unwrap(); | ||
| 70 | +//! # } | ||
| 71 | +//! ``` | ||
| 72 | + | ||
| 73 | +use std::marker::PhantomData; | ||
| 74 | +use std::sync::Arc; | ||
| 75 | + | ||
| 76 | +use crate::config::Config; | ||
| 77 | +use crate::display::Display; | ||
| 78 | +use crate::error::{Error, Result, check}; | ||
| 79 | +use crate::surface::Surface; | ||
| 80 | +use crate::sys; | ||
| 81 | + | ||
| 82 | +/// A live `VAContextID`. | ||
| 83 | +/// | ||
| 84 | +/// Holds its config and render targets, so neither can be destroyed while the | ||
| 85 | +/// context still references them — the ordering libva demands. | ||
| 86 | +pub struct Context { | ||
| 87 | + display: Arc<Display>, | ||
| 88 | + config: Arc<Config>, | ||
| 89 | + id: sys::VAContextID, | ||
| 90 | + _targets: Vec<Arc<Surface>>, | ||
| 91 | + width: u32, | ||
| 92 | + height: u32, | ||
| 93 | +} | ||
| 94 | + | ||
| 95 | +impl Context { | ||
| 96 | + /// Create a context for `config` at `width` x `height`. | ||
| 97 | + /// | ||
| 98 | + /// `targets` are the surfaces the driver may render into. `flags` is | ||
| 99 | + /// usually [`sys::VA_PROGRESSIVE`]. | ||
| 100 | + pub fn new( | ||
| 101 | + config: &Arc<Config>, | ||
| 102 | + width: u32, | ||
| 103 | + height: u32, | ||
| 104 | + flags: i32, | ||
| 105 | + targets: &[Arc<Surface>], | ||
| 106 | + ) -> Result<Arc<Context>> { | ||
| 107 | + let display = Arc::clone(config.display()); | ||
| 108 | + let mut ids: Vec<sys::VASurfaceID> = targets.iter().map(|s| s.id()).collect(); | ||
| 109 | + let mut id: sys::VAContextID = sys::VA_INVALID_ID; | ||
| 110 | + // SAFETY: `ids` is a valid array of `ids.len()` surface ids, all live | ||
| 111 | + // (their `Arc`s are cloned into the context below, so they outlive it); | ||
| 112 | + // `id` is a valid out-parameter. libva copies the target array. | ||
| 113 | + let status = unsafe { | ||
| 114 | + sys::vaCreateContext( | ||
| 115 | + display.handle(), | ||
| 116 | + config.id(), | ||
| 117 | + width as i32, | ||
| 118 | + height as i32, | ||
| 119 | + flags, | ||
| 120 | + ids.as_mut_ptr(), | ||
| 121 | + ids.len() as i32, | ||
| 122 | + &mut id, | ||
| 123 | + ) | ||
| 124 | + }; | ||
| 125 | + check("vaCreateContext", status)?; | ||
| 126 | + if id == sys::VA_INVALID_ID { | ||
| 127 | + return Err(Error::Protocol( | ||
| 128 | + "vaCreateContext succeeded but returned VA_INVALID_ID".to_string(), | ||
| 129 | + )); | ||
| 130 | + } | ||
| 131 | + Ok(Arc::new(Context { | ||
| 132 | + display, | ||
| 133 | + config: Arc::clone(config), | ||
| 134 | + id, | ||
| 135 | + _targets: targets.to_vec(), | ||
| 136 | + width, | ||
| 137 | + height, | ||
| 138 | + })) | ||
| 139 | + } | ||
| 140 | + | ||
| 141 | + /// The config this context was created from. | ||
| 142 | + pub fn config(&self) -> &Arc<Config> { | ||
| 143 | + &self.config | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + /// The display this context belongs to. | ||
| 147 | + pub fn display(&self) -> &Arc<Display> { | ||
| 148 | + &self.display | ||
| 149 | + } | ||
| 150 | + | ||
| 151 | + /// Coded size the context was created with. | ||
| 152 | + pub fn size(&self) -> (u32, u32) { | ||
| 153 | + (self.width, self.height) | ||
| 154 | + } | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +impl std::fmt::Debug for Context { | ||
| 158 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 159 | + f.debug_struct("Context") | ||
| 160 | + .field("id", &self.id) | ||
| 161 | + .field("size", &(self.width, self.height)) | ||
| 162 | + .field("profile", &self.config.profile()) | ||
| 163 | + .finish() | ||
| 164 | + } | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +impl Drop for Context { | ||
| 168 | + fn drop(&mut self) { | ||
| 169 | + // SAFETY: `self.id` is live on `self.display`. Buffers hold an | ||
| 170 | + // `Arc<Context>` and pictures hold buffers, so none can be alive here; | ||
| 171 | + // the render targets and config are released after this call. | ||
| 172 | + unsafe { sys::vaDestroyContext(self.display.handle(), self.id) }; | ||
| 173 | + } | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +/// A live `VABufferID` belonging to a context. | ||
| 177 | +pub struct Buffer { | ||
| 178 | + context: Arc<Context>, | ||
| 179 | + id: sys::VABufferID, | ||
| 180 | + type_: sys::VABufferType, | ||
| 181 | +} | ||
| 182 | + | ||
| 183 | +impl Buffer { | ||
| 184 | + /// Create a buffer holding a copy of `data`. | ||
| 185 | + /// | ||
| 186 | + /// This is the parameter-buffer path: picture/slice parameters and slice | ||
| 187 | + /// data are copied into driver memory, so `data` need not outlive the call. | ||
| 188 | + pub fn from_bytes( | ||
| 189 | + context: &Arc<Context>, | ||
| 190 | + type_: sys::VABufferType, | ||
| 191 | + data: &[u8], | ||
| 192 | + ) -> Result<Buffer> { | ||
| 193 | + if data.is_empty() { | ||
| 194 | + return Err(Error::Protocol(format!( | ||
| 195 | + "refusing to create an empty VA buffer of type {type_}" | ||
| 196 | + ))); | ||
| 197 | + } | ||
| 198 | + let mut id: sys::VABufferID = sys::VA_INVALID_ID; | ||
| 199 | + // SAFETY: libva copies `size * num_elements` = `data.len()` bytes out | ||
| 200 | + // of `data` during the call and never retains the pointer (va.h:3820). | ||
| 201 | + // The cast to `*mut c_void` is sound because libva only reads it: the | ||
| 202 | + // `data` parameter is documented as `in`. | ||
| 203 | + let status = unsafe { | ||
| 204 | + sys::vaCreateBuffer( | ||
| 205 | + context.display.handle(), | ||
| 206 | + context.id, | ||
| 207 | + type_, | ||
| 208 | + data.len() as u32, | ||
| 209 | + 1, | ||
| 210 | + data.as_ptr() as *mut std::ffi::c_void, | ||
| 211 | + &mut id, | ||
| 212 | + ) | ||
| 213 | + }; | ||
| 214 | + check("vaCreateBuffer", status)?; | ||
| 215 | + Buffer::wrap(context, id, type_) | ||
| 216 | + } | ||
| 217 | + | ||
| 218 | + /// Create a buffer holding a copy of one plain-old-data parameter struct. | ||
| 219 | + /// | ||
| 220 | + /// # Safety | ||
| 221 | + /// | ||
| 222 | + /// `T` must be the exact `#[repr(C)]` parameter struct libva expects for | ||
| 223 | + /// `type_` (e.g. `VAPictureParameterBufferH264` for | ||
| 224 | + /// `VAPictureParameterBufferType`) and must contain no padding-sensitive | ||
| 225 | + /// invariants: the driver reads `size_of::<T>()` bytes of it verbatim. | ||
| 226 | + pub unsafe fn from_param<T: Copy>( | ||
| 227 | + context: &Arc<Context>, | ||
| 228 | + type_: sys::VABufferType, | ||
| 229 | + param: &T, | ||
| 230 | + ) -> Result<Buffer> { | ||
| 231 | + // SAFETY: `T: Copy` with the caller's guarantee that it is a repr(C) | ||
| 232 | + // POD parameter struct, so its bytes are a valid representation to | ||
| 233 | + // hand to the driver; the slice covers exactly one `T` and is only | ||
| 234 | + // read during the call below. | ||
| 235 | + let bytes = | ||
| 236 | + unsafe { std::slice::from_raw_parts((param as *const T).cast::<u8>(), size_of::<T>()) }; | ||
| 237 | + Buffer::from_bytes(context, type_, bytes) | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + /// Allocate an empty buffer of `size` bytes to be filled via [`Buffer::map`]. | ||
| 241 | + /// | ||
| 242 | + /// This is the coded-output path: `VAEncCodedBufferType` buffers are | ||
| 243 | + /// written by the GPU and read back after sync. | ||
| 244 | + pub fn allocate(context: &Arc<Context>, type_: sys::VABufferType, size: u32) -> Result<Buffer> { | ||
| 245 | + let mut id: sys::VABufferID = sys::VA_INVALID_ID; | ||
| 246 | + // SAFETY: a NULL `data` pointer is the documented "allocate only" form | ||
| 247 | + // (va.h:3826); `id` is a valid out-parameter. | ||
| 248 | + let status = unsafe { | ||
| 249 | + sys::vaCreateBuffer( | ||
| 250 | + context.display.handle(), | ||
| 251 | + context.id, | ||
| 252 | + type_, | ||
| 253 | + size, | ||
| 254 | + 1, | ||
| 255 | + std::ptr::null_mut(), | ||
| 256 | + &mut id, | ||
| 257 | + ) | ||
| 258 | + }; | ||
| 259 | + check("vaCreateBuffer", status)?; | ||
| 260 | + Buffer::wrap(context, id, type_) | ||
| 261 | + } | ||
| 262 | + | ||
| 263 | + fn wrap( | ||
| 264 | + context: &Arc<Context>, | ||
| 265 | + id: sys::VABufferID, | ||
| 266 | + type_: sys::VABufferType, | ||
| 267 | + ) -> Result<Buffer> { | ||
| 268 | + if id == sys::VA_INVALID_ID { | ||
| 269 | + return Err(Error::Protocol( | ||
| 270 | + "vaCreateBuffer succeeded but returned VA_INVALID_ID".to_string(), | ||
| 271 | + )); | ||
| 272 | + } | ||
| 273 | + Ok(Buffer { | ||
| 274 | + context: Arc::clone(context), | ||
| 275 | + id, | ||
| 276 | + type_, | ||
| 277 | + }) | ||
| 278 | + } | ||
| 279 | + | ||
| 280 | + /// Map the buffer for reading or writing. Unmaps on drop. | ||
| 281 | + pub fn map(&mut self) -> Result<MappedBuffer<'_>> { | ||
| 282 | + let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut(); | ||
| 283 | + // SAFETY: `self.id` is a live buffer on this display; `ptr` is a valid | ||
| 284 | + // out-parameter. libva keeps the mapping valid until vaUnmapBuffer, | ||
| 285 | + // which `MappedBuffer::drop` calls exactly once. | ||
| 286 | + let status = | ||
| 287 | + unsafe { sys::vaMapBuffer(self.context.display.handle(), self.id, &raw mut ptr) }; | ||
| 288 | + check("vaMapBuffer", status)?; | ||
| 289 | + if ptr.is_null() { | ||
| 290 | + // SAFETY: the map reported success, so it must be undone even | ||
| 291 | + // though the returned pointer is unusable. | ||
| 292 | + unsafe { sys::vaUnmapBuffer(self.context.display.handle(), self.id) }; | ||
| 293 | + return Err(Error::Protocol( | ||
| 294 | + "vaMapBuffer succeeded but returned NULL".to_string(), | ||
| 295 | + )); | ||
| 296 | + } | ||
| 297 | + Ok(MappedBuffer { | ||
| 298 | + buffer: self, | ||
| 299 | + base: ptr.cast::<u8>(), | ||
| 300 | + }) | ||
| 301 | + } | ||
| 302 | + | ||
| 303 | + /// The buffer id. | ||
| 304 | + pub fn id(&self) -> sys::VABufferID { | ||
| 305 | + self.id | ||
| 306 | + } | ||
| 307 | + | ||
| 308 | + /// The `VABufferType` this buffer was created with. | ||
| 309 | + pub fn buffer_type(&self) -> sys::VABufferType { | ||
| 310 | + self.type_ | ||
| 311 | + } | ||
| 312 | +} | ||
| 313 | + | ||
| 314 | +impl std::fmt::Debug for Buffer { | ||
| 315 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 316 | + f.debug_struct("Buffer") | ||
| 317 | + .field("id", &self.id) | ||
| 318 | + .field("type", &self.type_) | ||
| 319 | + .finish() | ||
| 320 | + } | ||
| 321 | +} | ||
| 322 | + | ||
| 323 | +impl Drop for Buffer { | ||
| 324 | + fn drop(&mut self) { | ||
| 325 | + // SAFETY: `self.id` is live and belongs to `self.context`'s display, | ||
| 326 | + // which outlives it (the `Arc<Context>` is held here). Mappings borrow | ||
| 327 | + // `&mut self`, so none can be outstanding. | ||
| 328 | + unsafe { sys::vaDestroyBuffer(self.context.display.handle(), self.id) }; | ||
| 329 | + } | ||
| 330 | +} | ||
| 331 | + | ||
| 332 | +/// A mapped [`Buffer`]. Unmaps on drop. | ||
| 333 | +/// | ||
| 334 | +/// The length of the mapping is not reported by libva for parameter buffers, | ||
| 335 | +/// so access goes through explicit sizes the caller already knows (for coded | ||
| 336 | +/// buffers, through the `VACodedBufferSegment` list, which `ec-hw` parses). | ||
| 337 | +pub struct MappedBuffer<'a> { | ||
| 338 | + buffer: &'a mut Buffer, | ||
| 339 | + base: *mut u8, | ||
| 340 | +} | ||
| 341 | + | ||
| 342 | +impl MappedBuffer<'_> { | ||
| 343 | + /// The raw mapped pointer. | ||
| 344 | + /// | ||
| 345 | + /// # Safety | ||
| 346 | + /// | ||
| 347 | + /// The caller must not read or write beyond the size the buffer was created | ||
| 348 | + /// with, and must not keep the pointer past this guard's lifetime. | ||
| 349 | + pub unsafe fn as_ptr(&self) -> *mut u8 { | ||
| 350 | + self.base | ||
| 351 | + } | ||
| 352 | + | ||
| 353 | + /// The first `len` bytes of the mapping. | ||
| 354 | + /// | ||
| 355 | + /// # Safety | ||
| 356 | + /// | ||
| 357 | + /// `len` must not exceed the size the buffer was created with. | ||
| 358 | + pub unsafe fn as_slice(&self, len: usize) -> &[u8] { | ||
| 359 | + // SAFETY: the caller guarantees `len` is within the allocation, and the | ||
| 360 | + // mapping is live for as long as this guard exists. | ||
| 361 | + unsafe { std::slice::from_raw_parts(self.base, len) } | ||
| 362 | + } | ||
| 363 | + | ||
| 364 | + /// The first `len` bytes of the mapping, mutably. | ||
| 365 | + /// | ||
| 366 | + /// # Safety | ||
| 367 | + /// | ||
| 368 | + /// `len` must not exceed the size the buffer was created with. | ||
| 369 | + pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [u8] { | ||
| 370 | + // SAFETY: as `as_slice`, plus `&mut self` makes this the only live | ||
| 371 | + // reference into the mapping. | ||
| 372 | + unsafe { std::slice::from_raw_parts_mut(self.base, len) } | ||
| 373 | + } | ||
| 374 | +} | ||
| 375 | + | ||
| 376 | +impl Drop for MappedBuffer<'_> { | ||
| 377 | + fn drop(&mut self) { | ||
| 378 | + // SAFETY: mapped in `Buffer::map`, unmapped exactly once here; the | ||
| 379 | + // buffer is still alive because this guard borrows it. | ||
| 380 | + unsafe { sys::vaUnmapBuffer(self.buffer.context.display.handle(), self.buffer.id) }; | ||
| 381 | + } | ||
| 382 | +} | ||
| 383 | + | ||
| 384 | +mod sealed { | ||
| 385 | + /// Prevents downstream crates from inventing picture states. | ||
| 386 | + pub trait Sealed {} | ||
| 387 | +} | ||
| 388 | + | ||
| 389 | +/// Marker trait for the [`Picture`] states. | ||
| 390 | +pub trait PictureState: sealed::Sealed {} | ||
| 391 | + | ||
| 392 | +macro_rules! picture_states { | ||
| 393 | + ($($(#[$meta:meta])* $name:ident),* $(,)?) => { | ||
| 394 | + $( | ||
| 395 | + $(#[$meta])* | ||
| 396 | + #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 397 | + pub struct $name; | ||
| 398 | + impl sealed::Sealed for $name {} | ||
| 399 | + impl PictureState for $name {} | ||
| 400 | + )* | ||
| 401 | + }; | ||
| 402 | +} | ||
| 403 | + | ||
| 404 | +picture_states! { | ||
| 405 | + /// Nothing submitted yet. | ||
| 406 | + New, | ||
| 407 | + /// `vaBeginPicture` done; buffers may be rendered. | ||
| 408 | + Rendering, | ||
| 409 | + /// `vaEndPicture` done; the GPU is working on it. | ||
| 410 | + Ended, | ||
| 411 | + /// `vaSyncSurface` done; the target surface is readable. | ||
| 412 | + Synced, | ||
| 413 | +} | ||
| 414 | + | ||
| 415 | +/// One picture submission, parameterised by how far through the VA protocol it is. | ||
| 416 | +/// | ||
| 417 | +/// See the [module docs](self) for the state diagram and the compile-fail | ||
| 418 | +/// examples. | ||
| 419 | +pub struct Picture<S: PictureState> { | ||
| 420 | + context: Arc<Context>, | ||
| 421 | + target: Arc<Surface>, | ||
| 422 | + /// Kept alive until the picture is dropped: the driver may reference | ||
| 423 | + /// parameter buffers until the submission completes. | ||
| 424 | + buffers: Vec<Buffer>, | ||
| 425 | + _state: PhantomData<S>, | ||
| 426 | +} | ||
| 427 | + | ||
| 428 | +impl<S: PictureState> Picture<S> { | ||
| 429 | + /// The surface this picture renders into. | ||
| 430 | + pub fn target(&self) -> &Arc<Surface> { | ||
| 431 | + &self.target | ||
| 432 | + } | ||
| 433 | + | ||
| 434 | + /// The context this picture is submitted to. | ||
| 435 | + pub fn context(&self) -> &Arc<Context> { | ||
| 436 | + &self.context | ||
| 437 | + } | ||
| 438 | + | ||
| 439 | + fn transition<T: PictureState>(self) -> Picture<T> { | ||
| 440 | + Picture { | ||
| 441 | + context: self.context, | ||
| 442 | + target: self.target, | ||
| 443 | + buffers: self.buffers, | ||
| 444 | + _state: PhantomData, | ||
| 445 | + } | ||
| 446 | + } | ||
| 447 | +} | ||
| 448 | + | ||
| 449 | +impl Picture<New> { | ||
| 450 | + /// Start a picture targeting `target`. No driver call yet. | ||
| 451 | + pub fn new(context: &Arc<Context>, target: Arc<Surface>) -> Picture<New> { | ||
| 452 | + Picture { | ||
| 453 | + context: Arc::clone(context), | ||
| 454 | + target, | ||
| 455 | + buffers: Vec::new(), | ||
| 456 | + _state: PhantomData, | ||
| 457 | + } | ||
| 458 | + } | ||
| 459 | + | ||
| 460 | + /// `vaBeginPicture`. | ||
| 461 | + /// | ||
| 462 | + /// On failure the picture is consumed and the context is left with no | ||
| 463 | + /// picture in flight; the next `begin` starts cleanly. | ||
| 464 | + pub fn begin(self) -> Result<Picture<Rendering>> { | ||
| 465 | + // SAFETY: live context and surface ids, both kept alive by the `Arc`s | ||
| 466 | + // this picture holds. | ||
| 467 | + let status = unsafe { | ||
| 468 | + sys::vaBeginPicture( | ||
| 469 | + self.context.display.handle(), | ||
| 470 | + self.context.id, | ||
| 471 | + self.target.id(), | ||
| 472 | + ) | ||
| 473 | + }; | ||
| 474 | + check("vaBeginPicture", status)?; | ||
| 475 | + Ok(self.transition()) | ||
| 476 | + } | ||
| 477 | +} | ||
| 478 | + | ||
| 479 | +impl Picture<Rendering> { | ||
| 480 | + /// `vaRenderPicture` with one buffer, which the picture then owns. | ||
| 481 | + pub fn render(self, buffer: Buffer) -> Result<Picture<Rendering>> { | ||
| 482 | + self.render_all(vec![buffer]) | ||
| 483 | + } | ||
| 484 | + | ||
| 485 | + /// `vaRenderPicture` with several buffers in one call. | ||
| 486 | + pub fn render_all(mut self, buffers: Vec<Buffer>) -> Result<Picture<Rendering>> { | ||
| 487 | + if buffers.is_empty() { | ||
| 488 | + return Ok(self); | ||
| 489 | + } | ||
| 490 | + let mut ids: Vec<sys::VABufferID> = buffers.iter().map(|b| b.id).collect(); | ||
| 491 | + // SAFETY: `ids` is a valid array of `ids.len()` live buffer ids; the | ||
| 492 | + // buffers themselves are moved into `self.buffers` below, so they | ||
| 493 | + // outlive the submission. libva does not retain the id array. | ||
| 494 | + let status = unsafe { | ||
| 495 | + sys::vaRenderPicture( | ||
| 496 | + self.context.display.handle(), | ||
| 497 | + self.context.id, | ||
| 498 | + ids.as_mut_ptr(), | ||
| 499 | + ids.len() as i32, | ||
| 500 | + ) | ||
| 501 | + }; | ||
| 502 | + // Keep the buffers alive regardless of the outcome: on failure the | ||
| 503 | + // driver may still hold references until the context is torn down. | ||
| 504 | + self.buffers.extend(buffers); | ||
| 505 | + check("vaRenderPicture", status)?; | ||
| 506 | + Ok(self) | ||
| 507 | + } | ||
| 508 | + | ||
| 509 | + /// `vaEndPicture` — hand the picture to the GPU. | ||
| 510 | + pub fn end(self) -> Result<Picture<Ended>> { | ||
| 511 | + // SAFETY: live context id; a picture is in flight because this method | ||
| 512 | + // exists only on `Picture<Rendering>`, i.e. after a successful begin. | ||
| 513 | + let status = unsafe { sys::vaEndPicture(self.context.display.handle(), self.context.id) }; | ||
| 514 | + check("vaEndPicture", status)?; | ||
| 515 | + Ok(self.transition()) | ||
| 516 | + } | ||
| 517 | +} | ||
| 518 | + | ||
| 519 | +impl Picture<Ended> { | ||
| 520 | + /// `vaSyncSurface` — block until the target surface is complete. | ||
| 521 | + pub fn sync(self) -> Result<Picture<Synced>> { | ||
| 522 | + self.target.sync()?; | ||
| 523 | + Ok(self.transition()) | ||
| 524 | + } | ||
| 525 | +} | ||
| 526 | + | ||
| 527 | +impl Picture<Synced> { | ||
| 528 | + /// The completed surface, ready to export or map. | ||
| 529 | + pub fn into_surface(self) -> Arc<Surface> { | ||
| 530 | + self.target | ||
| 531 | + } | ||
| 532 | + | ||
| 533 | + /// The buffers submitted with this picture, e.g. to read a coded buffer. | ||
| 534 | + pub fn buffers_mut(&mut self) -> &mut [Buffer] { | ||
| 535 | + &mut self.buffers | ||
| 536 | + } | ||
| 537 | +} | ||
| 538 | + | ||
| 539 | +impl<S: PictureState> std::fmt::Debug for Picture<S> { | ||
| 540 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 541 | + f.debug_struct("Picture") | ||
| 542 | + .field("state", &std::any::type_name::<S>()) | ||
| 543 | + .field("target", &self.target.id()) | ||
| 544 | + .field("buffers", &self.buffers.len()) | ||
| 545 | + .finish() | ||
| 546 | + } | ||
| 547 | +} | ||
crates/ec-va/src/surface.rsadded+567 -0
| @@ -0,0 +1,567 @@ | |||
| 1 | +//! [`Surface`] — GPU-side picture storage, plus the two ways of getting at its | ||
| 2 | +//! contents: DRM PRIME export (zero-copy handoff) and image mapping (readback). | ||
| 3 | + | ||
| 4 | +use std::os::fd::{FromRawFd, OwnedFd}; | ||
| 5 | +use std::sync::Arc; | ||
| 6 | + | ||
| 7 | +use crate::display::Display; | ||
| 8 | +use crate::error::{Error, Result, check}; | ||
| 9 | +use crate::sys; | ||
| 10 | + | ||
| 11 | +/// What kind of surface to allocate. | ||
| 12 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 13 | +pub struct SurfaceSpec { | ||
| 14 | + /// `VA_RT_FORMAT_*` for the config this surface will be used with. | ||
| 15 | + pub rt_format: u32, | ||
| 16 | + /// Exact pixel layout (FourCC). `None` lets the driver choose. | ||
| 17 | + pub fourcc: Option<u32>, | ||
| 18 | + /// Width in pixels. Must satisfy [`crate::SurfaceCaps::allows`]. | ||
| 19 | + pub width: u32, | ||
| 20 | + /// Height in pixels. | ||
| 21 | + pub height: u32, | ||
| 22 | + /// `VA_SURFACE_ATTRIB_USAGE_HINT_*` bitmask; drivers use it to pick tiling. | ||
| 23 | + pub usage_hint: u32, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +impl SurfaceSpec { | ||
| 27 | + /// 8-bit 4:2:0 NV12, the decode output format of every codec in the family. | ||
| 28 | + pub fn nv12(width: u32, height: u32) -> Self { | ||
| 29 | + SurfaceSpec { | ||
| 30 | + rt_format: sys::VA_RT_FORMAT_YUV420, | ||
| 31 | + fourcc: Some(sys::VA_FOURCC_NV12), | ||
| 32 | + width, | ||
| 33 | + height, | ||
| 34 | + usage_hint: sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC, | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + /// 10-bit 4:2:0 P010, for HEVC Main10 / VP9 Profile 2 / AV1 10-bit. | ||
| 39 | + /// | ||
| 40 | + /// The RT format is derived from the stream's bit depth, never hardcoded to | ||
| 41 | + /// 8-bit: an 8-bit context on a 10-bit stream is the incumbent defect this | ||
| 42 | + /// constructor exists to make impossible to write by accident. | ||
| 43 | + pub fn p010(width: u32, height: u32) -> Self { | ||
| 44 | + SurfaceSpec { | ||
| 45 | + rt_format: sys::VA_RT_FORMAT_YUV420_10, | ||
| 46 | + fourcc: Some(sys::VA_FOURCC_P010), | ||
| 47 | + width, | ||
| 48 | + height, | ||
| 49 | + usage_hint: sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC, | ||
| 50 | + } | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + /// Set the usage hint (`VA_SURFACE_ATTRIB_USAGE_HINT_*`). | ||
| 54 | + pub fn with_usage_hint(mut self, hint: u32) -> Self { | ||
| 55 | + self.usage_hint = hint; | ||
| 56 | + self | ||
| 57 | + } | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +/// A live `VASurfaceID`. | ||
| 61 | +/// | ||
| 62 | +/// Surfaces may only be destroyed after every context using them is gone; | ||
| 63 | +/// [`crate::Context`] therefore holds `Arc<Surface>` for its render targets and | ||
| 64 | +/// this `Drop` cannot run too early. | ||
| 65 | +pub struct Surface { | ||
| 66 | + display: Arc<Display>, | ||
| 67 | + id: sys::VASurfaceID, | ||
| 68 | + spec: SurfaceSpec, | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +impl Surface { | ||
| 72 | + /// Allocate a single surface. | ||
| 73 | + pub fn create(display: &Arc<Display>, spec: &SurfaceSpec) -> Result<Arc<Surface>> { | ||
| 74 | + let mut pool = Surface::create_pool(display, spec, 1)?; | ||
| 75 | + Ok(pool.pop().expect("create_pool(1) returns one surface")) | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + /// Allocate `count` surfaces in one driver call. | ||
| 79 | + /// | ||
| 80 | + /// Each returned surface owns its own id and destroys exactly that id, so a | ||
| 81 | + /// pool can be torn down incrementally as frames are released. | ||
| 82 | + pub fn create_pool( | ||
| 83 | + display: &Arc<Display>, | ||
| 84 | + spec: &SurfaceSpec, | ||
| 85 | + count: usize, | ||
| 86 | + ) -> Result<Vec<Arc<Surface>>> { | ||
| 87 | + if count == 0 { | ||
| 88 | + return Ok(Vec::new()); | ||
| 89 | + } | ||
| 90 | + let mut attribs: Vec<sys::VASurfaceAttrib> = Vec::with_capacity(2); | ||
| 91 | + if let Some(fourcc) = spec.fourcc { | ||
| 92 | + attribs.push(int_attrib(sys::VASurfaceAttribPixelFormat, fourcc as i32)); | ||
| 93 | + } | ||
| 94 | + if spec.usage_hint != sys::VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC { | ||
| 95 | + attribs.push(int_attrib( | ||
| 96 | + sys::VASurfaceAttribUsageHint, | ||
| 97 | + spec.usage_hint as i32, | ||
| 98 | + )); | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + let mut ids = vec![sys::VA_INVALID_SURFACE; count]; | ||
| 102 | + // SAFETY: `ids` has room for exactly `count` surface ids and `attribs` | ||
| 103 | + // for exactly `attribs.len()` attributes; both counts are passed | ||
| 104 | + // alongside. libva writes only within those bounds and does not retain | ||
| 105 | + // either pointer past the call. | ||
| 106 | + let status = unsafe { | ||
| 107 | + sys::vaCreateSurfaces( | ||
| 108 | + display.handle(), | ||
| 109 | + spec.rt_format, | ||
| 110 | + spec.width, | ||
| 111 | + spec.height, | ||
| 112 | + ids.as_mut_ptr(), | ||
| 113 | + count as u32, | ||
| 114 | + attribs.as_mut_ptr(), | ||
| 115 | + attribs.len() as u32, | ||
| 116 | + ) | ||
| 117 | + }; | ||
| 118 | + check("vaCreateSurfaces", status)?; | ||
| 119 | + | ||
| 120 | + if ids.contains(&sys::VA_INVALID_SURFACE) { | ||
| 121 | + // Destroy whatever did get created rather than leaking it. | ||
| 122 | + let mut good: Vec<sys::VASurfaceID> = ids | ||
| 123 | + .iter() | ||
| 124 | + .copied() | ||
| 125 | + .filter(|&id| id != sys::VA_INVALID_SURFACE) | ||
| 126 | + .collect(); | ||
| 127 | + if !good.is_empty() { | ||
| 128 | + // SAFETY: every id in `good` was returned by the successful | ||
| 129 | + // vaCreateSurfaces above and has not been destroyed yet. | ||
| 130 | + unsafe { | ||
| 131 | + sys::vaDestroySurfaces(display.handle(), good.as_mut_ptr(), good.len() as i32) | ||
| 132 | + }; | ||
| 133 | + } | ||
| 134 | + return Err(Error::Protocol( | ||
| 135 | + "vaCreateSurfaces succeeded but left VA_INVALID_SURFACE in the array".to_string(), | ||
| 136 | + )); | ||
| 137 | + } | ||
| 138 | + | ||
| 139 | + Ok(ids | ||
| 140 | + .into_iter() | ||
| 141 | + .map(|id| { | ||
| 142 | + Arc::new(Surface { | ||
| 143 | + display: Arc::clone(display), | ||
| 144 | + id, | ||
| 145 | + spec: *spec, | ||
| 146 | + }) | ||
| 147 | + }) | ||
| 148 | + .collect()) | ||
| 149 | + } | ||
| 150 | + | ||
| 151 | + /// Block until every operation targeting this surface has completed. | ||
| 152 | + pub fn sync(&self) -> Result<()> { | ||
| 153 | + // SAFETY: `self.id` is live for the lifetime of `self` on | ||
| 154 | + // `self.display`. vaSyncSurface only blocks; it mutates no Rust state. | ||
| 155 | + let status = unsafe { sys::vaSyncSurface(self.display.handle(), self.id) }; | ||
| 156 | + check("vaSyncSurface", status) | ||
| 157 | + } | ||
| 158 | + | ||
| 159 | + /// Export as DRM PRIME (`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`). | ||
| 160 | + /// | ||
| 161 | + /// `flags` is a combination of `VA_EXPORT_SURFACE_*`. This performs no | ||
| 162 | + /// synchronisation: call [`Surface::sync`] first if the contents will be | ||
| 163 | + /// read. | ||
| 164 | + pub fn export_prime(&self, flags: u32) -> Result<PrimeSurface> { | ||
| 165 | + let mut desc = sys::VADRMPRIMESurfaceDescriptor::default(); | ||
| 166 | + // SAFETY: `desc` is a valid, fully initialized (zeroed) descriptor of | ||
| 167 | + // exactly the type `VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2` selects | ||
| 168 | + // (va_drmcommon.h:96-99); passing any other mem_type with this pointer | ||
| 169 | + // would be the unsound case, which is why mem_type is not a parameter. | ||
| 170 | + let status = unsafe { | ||
| 171 | + sys::vaExportSurfaceHandle( | ||
| 172 | + self.display.handle(), | ||
| 173 | + self.id, | ||
| 174 | + sys::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, | ||
| 175 | + flags, | ||
| 176 | + (&raw mut desc).cast(), | ||
| 177 | + ) | ||
| 178 | + }; | ||
| 179 | + check("vaExportSurfaceHandle", status)?; | ||
| 180 | + PrimeSurface::from_raw(desc) | ||
| 181 | + } | ||
| 182 | + | ||
| 183 | + /// A directly mapped view of the surface's own memory (`vaDeriveImage`). | ||
| 184 | + /// | ||
| 185 | + /// Falls back is the caller's business: drivers may refuse to derive (tiled | ||
| 186 | + /// or compressed layouts), reporting `VA_STATUS_ERROR_OPERATION_FAILED`. | ||
| 187 | + pub fn derive_image(self: &Arc<Self>) -> Result<Image> { | ||
| 188 | + let mut image = sys::VAImage::default(); | ||
| 189 | + // SAFETY: valid display and surface id; `image` is a valid | ||
| 190 | + // out-parameter that libva fully overwrites on success. | ||
| 191 | + let status = unsafe { sys::vaDeriveImage(self.display.handle(), self.id, &raw mut image) }; | ||
| 192 | + check("vaDeriveImage", status)?; | ||
| 193 | + Ok(Image { | ||
| 194 | + display: Arc::clone(&self.display), | ||
| 195 | + _surface: Some(Arc::clone(self)), | ||
| 196 | + raw: image, | ||
| 197 | + }) | ||
| 198 | + } | ||
| 199 | + | ||
| 200 | + /// Copy the surface into an [`Image`] created with [`Image::create`]. | ||
| 201 | + /// | ||
| 202 | + /// The readback path for drivers that refuse [`Surface::derive_image`]. | ||
| 203 | + /// The image must be at least as large as the requested region. | ||
| 204 | + pub fn read_into( | ||
| 205 | + &self, | ||
| 206 | + image: &mut Image, | ||
| 207 | + x: i32, | ||
| 208 | + y: i32, | ||
| 209 | + width: u32, | ||
| 210 | + height: u32, | ||
| 211 | + ) -> Result<()> { | ||
| 212 | + let (img_w, img_h) = image.size(); | ||
| 213 | + if width > img_w || height > img_h { | ||
| 214 | + return Err(Error::Protocol(format!( | ||
| 215 | + "vaGetImage region {width}x{height} exceeds image {img_w}x{img_h}" | ||
| 216 | + ))); | ||
| 217 | + } | ||
| 218 | + // SAFETY: valid display and surface id; `image.raw.image_id` is a live | ||
| 219 | + // image on the same display. The region is bounded above by the image | ||
| 220 | + // size, which is what vaGetImage requires (va.h:4827). | ||
| 221 | + let status = unsafe { | ||
| 222 | + sys::vaGetImage( | ||
| 223 | + self.display.handle(), | ||
| 224 | + self.id, | ||
| 225 | + x, | ||
| 226 | + y, | ||
| 227 | + width, | ||
| 228 | + height, | ||
| 229 | + image.raw.image_id, | ||
| 230 | + ) | ||
| 231 | + }; | ||
| 232 | + check("vaGetImage", status) | ||
| 233 | + } | ||
| 234 | + | ||
| 235 | + /// The surface id, for FFI-level callers (`ec-hw` picture parameters). | ||
| 236 | + pub fn id(&self) -> sys::VASurfaceID { | ||
| 237 | + self.id | ||
| 238 | + } | ||
| 239 | + | ||
| 240 | + /// The spec this surface was allocated with. | ||
| 241 | + pub fn spec(&self) -> &SurfaceSpec { | ||
| 242 | + &self.spec | ||
| 243 | + } | ||
| 244 | + | ||
| 245 | + /// Allocated size in pixels. | ||
| 246 | + pub fn size(&self) -> (u32, u32) { | ||
| 247 | + (self.spec.width, self.spec.height) | ||
| 248 | + } | ||
| 249 | + | ||
| 250 | + /// The display this surface belongs to. | ||
| 251 | + pub fn display(&self) -> &Arc<Display> { | ||
| 252 | + &self.display | ||
| 253 | + } | ||
| 254 | +} | ||
| 255 | + | ||
| 256 | +fn int_attrib(type_: sys::VASurfaceAttribType, value: i32) -> sys::VASurfaceAttrib { | ||
| 257 | + sys::VASurfaceAttrib { | ||
| 258 | + type_, | ||
| 259 | + flags: sys::VA_SURFACE_ATTRIB_SETTABLE, | ||
| 260 | + value: sys::VAGenericValue { | ||
| 261 | + type_: sys::VAGenericValueTypeInteger, | ||
| 262 | + value: sys::VAGenericValueUnion { i: value }, | ||
| 263 | + }, | ||
| 264 | + } | ||
| 265 | +} | ||
| 266 | + | ||
| 267 | +impl std::fmt::Debug for Surface { | ||
| 268 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 269 | + f.debug_struct("Surface") | ||
| 270 | + .field("id", &self.id) | ||
| 271 | + .field("size", &(self.spec.width, self.spec.height)) | ||
| 272 | + .finish() | ||
| 273 | + } | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +impl Drop for Surface { | ||
| 277 | + fn drop(&mut self) { | ||
| 278 | + let mut id = self.id; | ||
| 279 | + // SAFETY: `id` is live and belongs to `self.display`. Any context that | ||
| 280 | + // used it held an `Arc<Surface>`, so it was destroyed first; any | ||
| 281 | + // derived Image also held one. | ||
| 282 | + unsafe { sys::vaDestroySurfaces(self.display.handle(), &raw mut id, 1) }; | ||
| 283 | + } | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +/// One DRM object (buffer object) of an exported surface. | ||
| 287 | +#[derive(Debug)] | ||
| 288 | +pub struct PrimeObject { | ||
| 289 | + /// The PRIME file descriptor, owned and closed on drop. | ||
| 290 | + pub fd: OwnedFd, | ||
| 291 | + /// Total size of the object in bytes. | ||
| 292 | + pub size: u32, | ||
| 293 | + /// DRM format modifier (tiling/compression layout). | ||
| 294 | + pub modifier: u64, | ||
| 295 | +} | ||
| 296 | + | ||
| 297 | +/// One layer (plane group) of an exported surface. | ||
| 298 | +#[derive(Debug, Clone)] | ||
| 299 | +pub struct PrimeLayer { | ||
| 300 | + /// `DRM_FORMAT_*` FourCC of this layer. | ||
| 301 | + pub drm_format: u32, | ||
| 302 | + /// Per-plane `(object_index, offset, pitch)`. | ||
| 303 | + pub planes: Vec<(u32, u32, u32)>, | ||
| 304 | +} | ||
| 305 | + | ||
| 306 | +/// A surface exported as DRM PRIME file descriptors. | ||
| 307 | +/// | ||
| 308 | +/// Owns the descriptors: dropping this closes them. libva hands over ownership | ||
| 309 | +/// on export (`va.h:4155`), so anything less would leak one fd per frame. | ||
| 310 | +#[derive(Debug)] | ||
| 311 | +pub struct PrimeSurface { | ||
| 312 | + /// Surface FourCC (`VA_FOURCC_*`). | ||
| 313 | + pub fourcc: u32, | ||
| 314 | + /// Width in pixels. | ||
| 315 | + pub width: u32, | ||
| 316 | + /// Height in pixels. | ||
| 317 | + pub height: u32, | ||
| 318 | + /// Backing DRM objects. | ||
| 319 | + pub objects: Vec<PrimeObject>, | ||
| 320 | + /// Layers referencing those objects. | ||
| 321 | + pub layers: Vec<PrimeLayer>, | ||
| 322 | +} | ||
| 323 | + | ||
| 324 | +impl PrimeSurface { | ||
| 325 | + /// Take ownership of the fds in a filled descriptor. | ||
| 326 | + fn from_raw(desc: sys::VADRMPRIMESurfaceDescriptor) -> Result<PrimeSurface> { | ||
| 327 | + // The array is 4 elements wide; a driver reporting more would mean our | ||
| 328 | + // transcription and the runtime disagree about the struct, so refuse | ||
| 329 | + // rather than read past the end. | ||
| 330 | + if desc.num_objects as usize > desc.objects.len() | ||
| 331 | + || desc.num_layers as usize > desc.layers.len() | ||
| 332 | + { | ||
| 333 | + return Err(Error::Protocol(format!( | ||
| 334 | + "vaExportSurfaceHandle reported {} objects / {} layers, max 4 each", | ||
| 335 | + desc.num_objects, desc.num_layers | ||
| 336 | + ))); | ||
| 337 | + } | ||
| 338 | + | ||
| 339 | + let mut objects = Vec::with_capacity(desc.num_objects as usize); | ||
| 340 | + for obj in &desc.objects[..desc.num_objects as usize] { | ||
| 341 | + if obj.fd < 0 { | ||
| 342 | + return Err(Error::Protocol(format!( | ||
| 343 | + "vaExportSurfaceHandle returned fd {} for an exported object", | ||
| 344 | + obj.fd | ||
| 345 | + ))); | ||
| 346 | + } | ||
| 347 | + objects.push(PrimeObject { | ||
| 348 | + // SAFETY: libva transfers ownership of every exported fd to the | ||
| 349 | + // caller (va.h:4155). Each fd appears exactly once in the | ||
| 350 | + // descriptor, so it is wrapped exactly once here and closed | ||
| 351 | + // exactly once when this `PrimeSurface` drops. | ||
| 352 | + fd: unsafe { OwnedFd::from_raw_fd(obj.fd) }, | ||
| 353 | + size: obj.size, | ||
| 354 | + modifier: obj.drm_format_modifier, | ||
| 355 | + }); | ||
| 356 | + } | ||
| 357 | + | ||
| 358 | + let mut layers = Vec::with_capacity(desc.num_layers as usize); | ||
| 359 | + for layer in &desc.layers[..desc.num_layers as usize] { | ||
| 360 | + if layer.num_planes as usize > layer.object_index.len() { | ||
| 361 | + return Err(Error::Protocol(format!( | ||
| 362 | + "vaExportSurfaceHandle reported {} planes in a layer, max 4", | ||
| 363 | + layer.num_planes | ||
| 364 | + ))); | ||
| 365 | + } | ||
| 366 | + layers.push(PrimeLayer { | ||
| 367 | + drm_format: layer.drm_format, | ||
| 368 | + planes: (0..layer.num_planes as usize) | ||
| 369 | + .map(|i| (layer.object_index[i], layer.offset[i], layer.pitch[i])) | ||
| 370 | + .collect(), | ||
| 371 | + }); | ||
| 372 | + } | ||
| 373 | + | ||
| 374 | + Ok(PrimeSurface { | ||
| 375 | + fourcc: desc.fourcc, | ||
| 376 | + width: desc.width, | ||
| 377 | + height: desc.height, | ||
| 378 | + objects, | ||
| 379 | + layers, | ||
| 380 | + }) | ||
| 381 | + } | ||
| 382 | +} | ||
| 383 | + | ||
| 384 | +/// A `VAImage` bound to a surface (derived) or standalone (created). | ||
| 385 | +pub struct Image { | ||
| 386 | + display: Arc<Display>, | ||
| 387 | + /// Kept alive because a derived image aliases the surface's memory. | ||
| 388 | + _surface: Option<Arc<Surface>>, | ||
| 389 | + raw: sys::VAImage, | ||
| 390 | +} | ||
| 391 | + | ||
| 392 | +impl Image { | ||
| 393 | + /// Allocate a standalone image to read a surface back into | ||
| 394 | + /// ([`Surface::read_into`]). | ||
| 395 | + /// | ||
| 396 | + /// `fourcc` must be one of [`crate::CapReport::image_formats`]; the other | ||
| 397 | + /// [`sys::VAImageFormat`] fields are only meaningful for RGB layouts and | ||
| 398 | + /// are left zero, as libva's own examples do for planar YUV. | ||
| 399 | + pub fn create(display: &Arc<Display>, fourcc: u32, width: u32, height: u32) -> Result<Image> { | ||
| 400 | + let mut format = sys::VAImageFormat { | ||
| 401 | + fourcc, | ||
| 402 | + byte_order: 1, // VA_LSB_FIRST | ||
| 403 | + bits_per_pixel: match fourcc { | ||
| 404 | + sys::VA_FOURCC_NV12 | sys::VA_FOURCC_I420 | sys::VA_FOURCC_YV12 => 12, | ||
| 405 | + sys::VA_FOURCC_P010 => 24, | ||
| 406 | + _ => 0, | ||
| 407 | + }, | ||
| 408 | + ..sys::VAImageFormat::default() | ||
| 409 | + }; | ||
| 410 | + let mut image = sys::VAImage::default(); | ||
| 411 | + // SAFETY: `format` and `image` are valid, initialized in/out parameters | ||
| 412 | + // that outlive the call; libva copies the format and fully overwrites | ||
| 413 | + // `image` on success. | ||
| 414 | + let status = unsafe { | ||
| 415 | + sys::vaCreateImage( | ||
| 416 | + display.handle(), | ||
| 417 | + &raw mut format, | ||
| 418 | + width as i32, | ||
| 419 | + height as i32, | ||
| 420 | + &raw mut image, | ||
| 421 | + ) | ||
| 422 | + }; | ||
| 423 | + check("vaCreateImage", status)?; | ||
| 424 | + Ok(Image { | ||
| 425 | + display: Arc::clone(display), | ||
| 426 | + _surface: None, | ||
| 427 | + raw: image, | ||
| 428 | + }) | ||
| 429 | + } | ||
| 430 | + | ||
| 431 | + /// Pixel format FourCC. | ||
| 432 | + pub fn fourcc(&self) -> u32 { | ||
| 433 | + self.raw.format.fourcc | ||
| 434 | + } | ||
| 435 | + | ||
| 436 | + /// `(width, height)` of the image, which may exceed the requested size. | ||
| 437 | + pub fn size(&self) -> (u32, u32) { | ||
| 438 | + (self.raw.width as u32, self.raw.height as u32) | ||
| 439 | + } | ||
| 440 | + | ||
| 441 | + /// Number of planes (at most 3). | ||
| 442 | + pub fn num_planes(&self) -> u32 { | ||
| 443 | + self.raw.num_planes.min(3) | ||
| 444 | + } | ||
| 445 | + | ||
| 446 | + /// Row pitch of plane `i` in bytes. | ||
| 447 | + pub fn pitch(&self, plane: usize) -> Option<u32> { | ||
| 448 | + self.raw.pitches.get(plane).copied() | ||
| 449 | + } | ||
| 450 | + | ||
| 451 | + /// Map the image's buffer into this process. | ||
| 452 | + /// | ||
| 453 | + /// The returned guard unmaps on drop. That is not politeness: an unmatched | ||
| 454 | + /// `vaMapBuffer` leaks the mapping for the lifetime of the display, which | ||
| 455 | + /// is how the incumbent stack lost ~3MB per frame. | ||
| 456 | + pub fn map(&mut self) -> Result<MappedImage<'_>> { | ||
| 457 | + let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut(); | ||
| 458 | + // SAFETY: `self.raw.buf` is the image buffer libva created and still | ||
| 459 | + // owns; `ptr` is a valid out-parameter. On success libva guarantees the | ||
| 460 | + // mapping stays valid until vaUnmapBuffer, which `MappedImage::drop` | ||
| 461 | + // calls exactly once. | ||
| 462 | + let status = unsafe { sys::vaMapBuffer(self.display.handle(), self.raw.buf, &raw mut ptr) }; | ||
| 463 | + check("vaMapBuffer", status)?; | ||
| 464 | + if ptr.is_null() { | ||
| 465 | + // SAFETY: the map call reported success, so the buffer is mapped | ||
| 466 | + // and must be unmapped even though the pointer is unusable. | ||
| 467 | + unsafe { sys::vaUnmapBuffer(self.display.handle(), self.raw.buf) }; | ||
| 468 | + return Err(Error::Protocol( | ||
| 469 | + "vaMapBuffer succeeded but returned NULL".to_string(), | ||
| 470 | + )); | ||
| 471 | + } | ||
| 472 | + Ok(MappedImage { | ||
| 473 | + image: self, | ||
| 474 | + base: ptr.cast::<u8>(), | ||
| 475 | + }) | ||
| 476 | + } | ||
| 477 | +} | ||
| 478 | + | ||
| 479 | +impl std::fmt::Debug for Image { | ||
| 480 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| 481 | + f.debug_struct("Image") | ||
| 482 | + .field("fourcc", &crate::caps::fourcc_str(self.raw.format.fourcc)) | ||
| 483 | + .field("size", &(self.raw.width, self.raw.height)) | ||
| 484 | + .field("num_planes", &self.raw.num_planes) | ||
| 485 | + .field("data_size", &self.raw.data_size) | ||
| 486 | + .finish() | ||
| 487 | + } | ||
| 488 | +} | ||
| 489 | + | ||
| 490 | +impl Drop for Image { | ||
| 491 | + fn drop(&mut self) { | ||
| 492 | + // SAFETY: `image_id` came from vaDeriveImage/vaCreateImage on | ||
| 493 | + // `self.display` and is destroyed once. Any mapping was released | ||
| 494 | + // first: `map` borrows `self` mutably, so no `MappedImage` can outlive | ||
| 495 | + // this. The surface (if any) is released after, as libva requires. | ||
| 496 | + unsafe { sys::vaDestroyImage(self.display.handle(), self.raw.image_id) }; | ||
| 497 | + } | ||
| 498 | +} | ||
| 499 | + | ||
| 500 | +/// A mapped [`Image`]. Unmaps on drop. | ||
| 501 | +pub struct MappedImage<'a> { | ||
| 502 | + image: &'a mut Image, | ||
| 503 | + base: *mut u8, | ||
| 504 | +} | ||
| 505 | + | ||
| 506 | +impl MappedImage<'_> { | ||
| 507 | + /// Byte range of plane `i` within the mapped buffer, as `(offset, len)`. | ||
| 508 | + /// | ||
| 509 | + /// The length runs to the next plane's offset, or to `data_size` for the | ||
| 510 | + /// last plane — libva does not report per-plane sizes. | ||
| 511 | + fn plane_range(&self, plane: usize) -> Option<(usize, usize)> { | ||
| 512 | + let n = self.image.num_planes() as usize; | ||
| 513 | + if plane >= n { | ||
| 514 | + return None; | ||
| 515 | + } | ||
| 516 | + let raw = &self.image.raw; | ||
| 517 | + let offset = raw.offsets[plane] as usize; | ||
| 518 | + let end = raw | ||
| 519 | + .offsets | ||
| 520 | + .get(plane + 1) | ||
| 521 | + .copied() | ||
| 522 | + .filter(|_| plane + 1 < n) | ||
| 523 | + .unwrap_or(raw.data_size) as usize; | ||
| 524 | + // A driver reporting decreasing or out-of-range offsets would otherwise | ||
| 525 | + // produce a slice past the mapping. | ||
| 526 | + if end < offset || end > raw.data_size as usize { | ||
| 527 | + return None; | ||
| 528 | + } | ||
| 529 | + Some((offset, end - offset)) | ||
| 530 | + } | ||
| 531 | + | ||
| 532 | + /// Read-only view of plane `plane`. | ||
| 533 | + pub fn plane(&self, plane: usize) -> Option<&[u8]> { | ||
| 534 | + let (offset, len) = self.plane_range(plane)?; | ||
| 535 | + // SAFETY: `base` points at a mapping of `data_size` bytes that libva | ||
| 536 | + // keeps valid until vaUnmapBuffer (called only in `drop`). `plane_range` | ||
| 537 | + // guarantees `offset + len <= data_size`, so the slice stays inside the | ||
| 538 | + // mapping. The borrow is tied to `&self`, so it cannot outlive it. | ||
| 539 | + Some(unsafe { std::slice::from_raw_parts(self.base.add(offset), len) }) | ||
| 540 | + } | ||
| 541 | + | ||
| 542 | + /// Mutable view of plane `plane`, for upload paths. | ||
| 543 | + pub fn plane_mut(&mut self, plane: usize) -> Option<&mut [u8]> { | ||
| 544 | + let (offset, len) = self.plane_range(plane)?; | ||
| 545 | + // SAFETY: as `plane`, plus: `&mut self` guarantees no other slice into | ||
| 546 | + // the mapping is alive, so this is the only reference to those bytes. | ||
| 547 | + Some(unsafe { std::slice::from_raw_parts_mut(self.base.add(offset), len) }) | ||
| 548 | + } | ||
| 549 | + | ||
| 550 | + /// Row pitch of plane `plane` in bytes. | ||
| 551 | + pub fn pitch(&self, plane: usize) -> Option<u32> { | ||
| 552 | + self.image.pitch(plane) | ||
| 553 | + } | ||
| 554 | + | ||
| 555 | + /// The image being mapped. | ||
| 556 | + pub fn image(&self) -> &Image { | ||
| 557 | + self.image | ||
| 558 | + } | ||
| 559 | +} | ||
| 560 | + | ||
| 561 | +impl Drop for MappedImage<'_> { | ||
| 562 | + fn drop(&mut self) { | ||
| 563 | + // SAFETY: the buffer was mapped in `Image::map` and is unmapped exactly | ||
| 564 | + // once, here; `self.image` is still alive because this guard borrows it. | ||
| 565 | + unsafe { sys::vaUnmapBuffer(self.image.display.handle(), self.image.raw.buf) }; | ||
| 566 | + } | ||
| 567 | +} | ||
crates/ec-va/src/sys.rsadded+558 -0
| @@ -0,0 +1,558 @@ | |||
| 1 | +//! Hand-written FFI for the subset of libva this family uses. | ||
| 2 | +//! | ||
| 3 | +//! # Why hand-written | ||
| 4 | +//! | ||
| 5 | +//! No `bindgen`: the family rule is no build-time tooling, and a generated | ||
| 6 | +//! 40k-line binding hides exactly the thing that has to be audited — the ABI | ||
| 7 | +//! assumptions. Everything here is transcribed from the system headers and is | ||
| 8 | +//! short enough to read in one sitting. | ||
| 9 | +//! | ||
| 10 | +//! # ABI assumptions (all four are load-bearing) | ||
| 11 | +//! | ||
| 12 | +//! 1. **libva 1.23.0 headers**, `/usr/include/va/{va.h,va_drm.h,va_drmcommon.h}`, | ||
| 13 | +//! target `x86_64-unknown-linux-gnu`, System V C ABI. | ||
| 14 | +//! 2. **C `enum` is `int` (4 bytes)** on this ABI. Every VA enum is transcribed | ||
| 15 | +//! as a plain `i32` type alias plus constants, *never* as a `#[repr(i32)]` | ||
| 16 | +//! Rust enum: the driver writes profile/entrypoint values into buffers we | ||
| 17 | +//! own, and a value we have no variant for would be instant UB on a real | ||
| 18 | +//! Rust enum. Interpretation happens in the safe layer | ||
| 19 | +//! ([`crate::caps::Profile::from_raw`]), which has an `Unknown(i32)` arm. | ||
| 20 | +//! This is the header-drift trap that broke cros-libva at libva >= 1.23. | ||
| 21 | +//! 3. **Struct layouts** below are checked by the `const _: () = assert!(...)` | ||
| 22 | +//! block at the end of this file against numbers printed by | ||
| 23 | +//! `crates/ec-va/abi-probe.c` compiled against the *system* headers. Rerun | ||
| 24 | +//! that probe after a libva upgrade; a mismatch means this file drifted. | ||
| 25 | +//! 4. **`VADisplay` is an opaque pointer**; we never dereference it. | ||
| 26 | +//! | ||
| 27 | +//! Points 1-3 are compile-time. They cannot see a libva that changes layout | ||
| 28 | +//! *after* this crate is built, so [`crate::Display::open`] additionally | ||
| 29 | +//! performs a **runtime** `vaInitialize` version check and refuses anything | ||
| 30 | +//! older than 1.23 with a typed error. | ||
| 31 | + | ||
| 32 | +// Every item keeps its exact C spelling so that this file can be diffed | ||
| 33 | +// against the headers by eye — the whole audit story of a hand-written FFI. | ||
| 34 | +#![allow(non_camel_case_types)] | ||
| 35 | +#![allow(non_snake_case)] | ||
| 36 | +#![allow(non_upper_case_globals)] | ||
| 37 | +// Fields keep their C names and are documented by the header line cited on | ||
| 38 | +// each item; restating "the fourcc field is the fourcc" 60 times would bury | ||
| 39 | +// the ABI notes that actually matter here. | ||
| 40 | +#![allow(missing_docs)] | ||
| 41 | + | ||
| 42 | +use std::ffi::{c_char, c_int, c_uint, c_void}; | ||
| 43 | + | ||
| 44 | +// --------------------------------------------------------------------------- | ||
| 45 | +// Scalar types (va.h:260-262, 1580-1647, 2042, 4727) | ||
| 46 | +// --------------------------------------------------------------------------- | ||
| 47 | + | ||
| 48 | +/// Opaque display handle. Never dereferenced by this crate. | ||
| 49 | +pub type VADisplay = *mut c_void; | ||
| 50 | +/// Return status of every VA entry point. `va.h:262`. | ||
| 51 | +pub type VAStatus = i32; | ||
| 52 | +/// `va.h:1580`. | ||
| 53 | +pub type VAGenericID = c_uint; | ||
| 54 | +pub type VAConfigID = VAGenericID; | ||
| 55 | +pub type VAContextID = VAGenericID; | ||
| 56 | +pub type VASurfaceID = VAGenericID; | ||
| 57 | +pub type VABufferID = VAGenericID; | ||
| 58 | +pub type VAImageID = VAGenericID; | ||
| 59 | + | ||
| 60 | +/// C enum `VAProfile` (`va.h:502`), kept as `i32`. See ABI assumption 2. | ||
| 61 | +pub type VAProfile = i32; | ||
| 62 | +/// C enum `VAEntrypoint` (`va.h:552`), kept as `i32`. | ||
| 63 | +pub type VAEntrypoint = i32; | ||
| 64 | +/// C enum `VAConfigAttribType` (`va.h:619`), kept as `i32`. | ||
| 65 | +pub type VAConfigAttribType = i32; | ||
| 66 | +/// C enum `VASurfaceAttribType` (`va.h:1689`), kept as `i32`. | ||
| 67 | +pub type VASurfaceAttribType = i32; | ||
| 68 | +/// C enum `VAGenericValueType` (`va.h:1651`), kept as `i32`. | ||
| 69 | +pub type VAGenericValueType = i32; | ||
| 70 | +/// C enum `VABufferType` (`va.h:2044`), kept as `i32`. | ||
| 71 | +pub type VABufferType = i32; | ||
| 72 | + | ||
| 73 | +pub const VA_INVALID_ID: VAGenericID = 0xffff_ffff; | ||
| 74 | +pub const VA_INVALID_SURFACE: VASurfaceID = VA_INVALID_ID; | ||
| 75 | + | ||
| 76 | +// Status codes actually branched on; the rest are reported via `vaErrorStr`. | ||
| 77 | +// `va.h:264-309`. | ||
| 78 | +pub const VA_STATUS_SUCCESS: VAStatus = 0x0000_0000; | ||
| 79 | +pub const VA_STATUS_ERROR_INVALID_CONTEXT: VAStatus = 0x0000_0005; | ||
| 80 | +pub const VA_STATUS_ERROR_UNSUPPORTED_PROFILE: VAStatus = 0x0000_000c; | ||
| 81 | +pub const VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT: VAStatus = 0x0000_000d; | ||
| 82 | +pub const VA_STATUS_ERROR_UNSUPPORTED_RT_FORMAT: VAStatus = 0x0000_000e; | ||
| 83 | +pub const VA_STATUS_ERROR_MAX_NUM_EXCEEDED: VAStatus = 0x0000_000b; | ||
| 84 | +pub const VA_STATUS_ERROR_UNIMPLEMENTED: VAStatus = 0x0000_0014; | ||
| 85 | +pub const VA_STATUS_ERROR_RESOLUTION_NOT_SUPPORTED: VAStatus = 0x0000_0013; | ||
| 86 | +pub const VA_STATUS_ERROR_OPERATION_FAILED: VAStatus = 0x0000_0001; | ||
| 87 | +pub const VA_STATUS_ERROR_INVALID_PARAMETER: VAStatus = 0x0000_0012; | ||
| 88 | + | ||
| 89 | +// Entrypoints (`va.h:552`). | ||
| 90 | +pub const VAEntrypointVLD: VAEntrypoint = 1; | ||
| 91 | +pub const VAEntrypointEncSlice: VAEntrypoint = 6; | ||
| 92 | +pub const VAEntrypointEncPicture: VAEntrypoint = 7; | ||
| 93 | +pub const VAEntrypointEncSliceLP: VAEntrypoint = 8; | ||
| 94 | +pub const VAEntrypointVideoProc: VAEntrypoint = 10; | ||
| 95 | + | ||
| 96 | +// Config attribute types (`va.h:619`). | ||
| 97 | +pub const VAConfigAttribRTFormat: VAConfigAttribType = 0; | ||
| 98 | +pub const VAConfigAttribRateControl: VAConfigAttribType = 5; | ||
| 99 | +pub const VAConfigAttribDecSliceMode: VAConfigAttribType = 6; | ||
| 100 | +pub const VAConfigAttribEncPackedHeaders: VAConfigAttribType = 10; | ||
| 101 | + | ||
| 102 | +// RT formats (`va.h:1073-1090`). | ||
| 103 | +pub const VA_RT_FORMAT_YUV420: u32 = 0x0000_0001; | ||
| 104 | +pub const VA_RT_FORMAT_YUV422: u32 = 0x0000_0002; | ||
| 105 | +pub const VA_RT_FORMAT_YUV444: u32 = 0x0000_0004; | ||
| 106 | +pub const VA_RT_FORMAT_YUV400: u32 = 0x0000_0010; | ||
| 107 | +pub const VA_RT_FORMAT_YUV420_10: u32 = 0x0000_0100; | ||
| 108 | +pub const VA_RT_FORMAT_YUV422_10: u32 = 0x0000_0200; | ||
| 109 | +pub const VA_RT_FORMAT_YUV444_10: u32 = 0x0000_0400; | ||
| 110 | +pub const VA_RT_FORMAT_YUV420_12: u32 = 0x0000_1000; | ||
| 111 | +pub const VA_RT_FORMAT_RGB32: u32 = 0x0002_0000; | ||
| 112 | + | ||
| 113 | +// Surface attribute types (`va.h:1689`) and flags (`va.h:1681-1684`). | ||
| 114 | +pub const VASurfaceAttribNone: VASurfaceAttribType = 0; | ||
| 115 | +pub const VASurfaceAttribPixelFormat: VASurfaceAttribType = 1; | ||
| 116 | +pub const VASurfaceAttribMinWidth: VASurfaceAttribType = 2; | ||
| 117 | +pub const VASurfaceAttribMaxWidth: VASurfaceAttribType = 3; | ||
| 118 | +pub const VASurfaceAttribMinHeight: VASurfaceAttribType = 4; | ||
| 119 | +pub const VASurfaceAttribMaxHeight: VASurfaceAttribType = 5; | ||
| 120 | +pub const VASurfaceAttribMemoryType: VASurfaceAttribType = 6; | ||
| 121 | +pub const VASurfaceAttribUsageHint: VASurfaceAttribType = 8; | ||
| 122 | + | ||
| 123 | +pub const VA_SURFACE_ATTRIB_GETTABLE: u32 = 0x0000_0001; | ||
| 124 | +pub const VA_SURFACE_ATTRIB_SETTABLE: u32 = 0x0000_0002; | ||
| 125 | + | ||
| 126 | +pub const VA_SURFACE_ATTRIB_USAGE_HINT_GENERIC: u32 = 0x0000_0000; | ||
| 127 | +pub const VA_SURFACE_ATTRIB_USAGE_HINT_DECODER: u32 = 0x0000_0001; | ||
| 128 | +pub const VA_SURFACE_ATTRIB_USAGE_HINT_ENCODER: u32 = 0x0000_0002; | ||
| 129 | +pub const VA_SURFACE_ATTRIB_USAGE_HINT_EXPORT: u32 = 0x0000_0020; | ||
| 130 | + | ||
| 131 | +// Generic value discriminants (`va.h:1651`). | ||
| 132 | +pub const VAGenericValueTypeInteger: VAGenericValueType = 1; | ||
| 133 | +pub const VAGenericValueTypeFloat: VAGenericValueType = 2; | ||
| 134 | +pub const VAGenericValueTypePointer: VAGenericValueType = 3; | ||
| 135 | +pub const VAGenericValueTypeFunc: VAGenericValueType = 4; | ||
| 136 | + | ||
| 137 | +// Buffer types actually used by decode/encode paths (`va.h:2044`). | ||
| 138 | +pub const VAPictureParameterBufferType: VABufferType = 0; | ||
| 139 | +pub const VAIQMatrixBufferType: VABufferType = 1; | ||
| 140 | +pub const VASliceParameterBufferType: VABufferType = 4; | ||
| 141 | +pub const VASliceDataBufferType: VABufferType = 5; | ||
| 142 | +pub const VAImageBufferType: VABufferType = 9; | ||
| 143 | +pub const VAProbabilityBufferType: VABufferType = 13; | ||
| 144 | +pub const VAEncCodedBufferType: VABufferType = 21; | ||
| 145 | +pub const VAEncSequenceParameterBufferType: VABufferType = 22; | ||
| 146 | +pub const VAEncPictureParameterBufferType: VABufferType = 23; | ||
| 147 | +pub const VAEncSliceParameterBufferType: VABufferType = 24; | ||
| 148 | +pub const VAEncPackedHeaderParameterBufferType: VABufferType = 25; | ||
| 149 | +pub const VAEncPackedHeaderDataBufferType: VABufferType = 26; | ||
| 150 | +pub const VAEncMiscParameterBufferType: VABufferType = 27; | ||
| 151 | + | ||
| 152 | +/// `vaCreateContext` flag: sequence contains only progressive frames (`va.h:1919`). | ||
| 153 | +pub const VA_PROGRESSIVE: c_int = 0x1; | ||
| 154 | + | ||
| 155 | +// DRM PRIME memory types and export flags (`va_drmcommon.h:78-94`, `va.h:4130-4150`). | ||
| 156 | +pub const VA_SURFACE_ATTRIB_MEM_TYPE_VA: u32 = 0x0000_0001; | ||
| 157 | +pub const VA_SURFACE_ATTRIB_MEM_TYPE_KERNEL_DRM: u32 = 0x1000_0000; | ||
| 158 | +pub const VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME: u32 = 0x2000_0000; | ||
| 159 | +pub const VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2: u32 = 0x4000_0000; | ||
| 160 | + | ||
| 161 | +pub const VA_EXPORT_SURFACE_READ_ONLY: u32 = 0x0001; | ||
| 162 | +pub const VA_EXPORT_SURFACE_WRITE_ONLY: u32 = 0x0002; | ||
| 163 | +pub const VA_EXPORT_SURFACE_READ_WRITE: u32 = 0x0003; | ||
| 164 | +pub const VA_EXPORT_SURFACE_SEPARATE_LAYERS: u32 = 0x0004; | ||
| 165 | +pub const VA_EXPORT_SURFACE_COMPOSED_LAYERS: u32 = 0x0008; | ||
| 166 | + | ||
| 167 | +// FourCCs used by the family (`va.h:4400-4700`). | ||
| 168 | +pub const VA_FOURCC_NV12: u32 = 0x3231_564e; | ||
| 169 | +pub const VA_FOURCC_P010: u32 = 0x3031_3050; | ||
| 170 | +pub const VA_FOURCC_I420: u32 = 0x3032_3449; | ||
| 171 | +pub const VA_FOURCC_YV12: u32 = 0x3231_5659; | ||
| 172 | + | ||
| 173 | +// --------------------------------------------------------------------------- | ||
| 174 | +// Structs | ||
| 175 | +// --------------------------------------------------------------------------- | ||
| 176 | + | ||
| 177 | +/// `VAConfigAttrib`, `va.h:1155`. | ||
| 178 | +#[repr(C)] | ||
| 179 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 180 | +pub struct VAConfigAttrib { | ||
| 181 | + pub type_: VAConfigAttribType, | ||
| 182 | + pub value: u32, | ||
| 183 | +} | ||
| 184 | + | ||
| 185 | +/// The `value` union of `VAGenericValue`, `va.h:1663-1673`. | ||
| 186 | +/// | ||
| 187 | +/// Only ever read after checking the sibling `type_` discriminant. | ||
| 188 | +#[repr(C)] | ||
| 189 | +#[derive(Clone, Copy)] | ||
| 190 | +pub union VAGenericValueUnion { | ||
| 191 | + pub i: i32, | ||
| 192 | + pub f: f32, | ||
| 193 | + pub p: *mut c_void, | ||
| 194 | + pub func: Option<extern "C" fn()>, | ||
| 195 | +} | ||
| 196 | + | ||
| 197 | +/// `VAGenericValue`, `va.h:1661`. | ||
| 198 | +#[repr(C)] | ||
| 199 | +#[derive(Clone, Copy)] | ||
| 200 | +pub struct VAGenericValue { | ||
| 201 | + pub type_: VAGenericValueType, | ||
| 202 | + pub value: VAGenericValueUnion, | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +/// `VASurfaceAttrib`, `va.h:1741`. | ||
| 206 | +#[repr(C)] | ||
| 207 | +#[derive(Clone, Copy)] | ||
| 208 | +pub struct VASurfaceAttrib { | ||
| 209 | + pub type_: VASurfaceAttribType, | ||
| 210 | + pub flags: u32, | ||
| 211 | + pub value: VAGenericValue, | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +/// `VAImageFormat`, `va.h:4712`. `va_reserved` is `VA_PADDING_LOW` = 4 u32s. | ||
| 215 | +#[repr(C)] | ||
| 216 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] | ||
| 217 | +pub struct VAImageFormat { | ||
| 218 | + pub fourcc: u32, | ||
| 219 | + pub byte_order: u32, | ||
| 220 | + pub bits_per_pixel: u32, | ||
| 221 | + pub depth: u32, | ||
| 222 | + pub red_mask: u32, | ||
| 223 | + pub green_mask: u32, | ||
| 224 | + pub blue_mask: u32, | ||
| 225 | + pub alpha_mask: u32, | ||
| 226 | + pub va_reserved: [u32; 4], | ||
| 227 | +} | ||
| 228 | + | ||
| 229 | +/// `VAImage`, `va.h:4729`. | ||
| 230 | +#[repr(C)] | ||
| 231 | +#[derive(Debug, Clone, Copy)] | ||
| 232 | +pub struct VAImage { | ||
| 233 | + pub image_id: VAImageID, | ||
| 234 | + pub format: VAImageFormat, | ||
| 235 | + pub buf: VABufferID, | ||
| 236 | + pub width: u16, | ||
| 237 | + pub height: u16, | ||
| 238 | + pub data_size: u32, | ||
| 239 | + pub num_planes: u32, | ||
| 240 | + pub pitches: [u32; 3], | ||
| 241 | + pub offsets: [u32; 3], | ||
| 242 | + pub num_palette_entries: i32, | ||
| 243 | + pub entry_bytes: i32, | ||
| 244 | + pub component_order: [i8; 4], | ||
| 245 | + pub va_reserved: [u32; 4], | ||
| 246 | +} | ||
| 247 | + | ||
| 248 | +impl Default for VAImage { | ||
| 249 | + fn default() -> Self { | ||
| 250 | + // All-zero is a valid "not yet filled" VAImage; `image_id` is | ||
| 251 | + // overwritten by vaDeriveImage/vaCreateImage before any use. | ||
| 252 | + // SAFETY: every field is a plain integer or array of integers, so the | ||
| 253 | + // all-zero bit pattern is a valid value of this type. | ||
| 254 | + unsafe { std::mem::zeroed() } | ||
| 255 | + } | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +/// One DRM object of a `VADRMPRIMESurfaceDescriptor`, `va_drmcommon.h:139-147`. | ||
| 259 | +#[repr(C)] | ||
| 260 | +#[derive(Debug, Clone, Copy)] | ||
| 261 | +pub struct VADRMPRIMEObject { | ||
| 262 | + pub fd: c_int, | ||
| 263 | + pub size: u32, | ||
| 264 | + pub drm_format_modifier: u64, | ||
| 265 | +} | ||
| 266 | + | ||
| 267 | +/// One layer of a `VADRMPRIMESurfaceDescriptor`, `va_drmcommon.h:151-164`. | ||
| 268 | +#[repr(C)] | ||
| 269 | +#[derive(Debug, Clone, Copy)] | ||
| 270 | +pub struct VADRMPRIMELayer { | ||
| 271 | + pub drm_format: u32, | ||
| 272 | + pub num_planes: u32, | ||
| 273 | + pub object_index: [u32; 4], | ||
| 274 | + pub offset: [u32; 4], | ||
| 275 | + pub pitch: [u32; 4], | ||
| 276 | +} | ||
| 277 | + | ||
| 278 | +/// `VADRMPRIMESurfaceDescriptor`, `va_drmcommon.h:130`. Used with | ||
| 279 | +/// [`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`]. | ||
| 280 | +#[repr(C)] | ||
| 281 | +#[derive(Debug, Clone, Copy)] | ||
| 282 | +pub struct VADRMPRIMESurfaceDescriptor { | ||
| 283 | + pub fourcc: u32, | ||
| 284 | + pub width: u32, | ||
| 285 | + pub height: u32, | ||
| 286 | + pub num_objects: u32, | ||
| 287 | + pub objects: [VADRMPRIMEObject; 4], | ||
| 288 | + pub num_layers: u32, | ||
| 289 | + pub layers: [VADRMPRIMELayer; 4], | ||
| 290 | +} | ||
| 291 | + | ||
| 292 | +impl Default for VADRMPRIMESurfaceDescriptor { | ||
| 293 | + fn default() -> Self { | ||
| 294 | + // SAFETY: all fields are integers or arrays of integer structs; the | ||
| 295 | + // all-zero bit pattern is valid. `fd` = 0 is never treated as an owned | ||
| 296 | + // descriptor because `num_objects` = 0 in that state. | ||
| 297 | + unsafe { std::mem::zeroed() } | ||
| 298 | + } | ||
| 299 | +} | ||
| 300 | + | ||
| 301 | +/// `VARectangle`, `va.h:406`. | ||
| 302 | +#[repr(C)] | ||
| 303 | +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] | ||
| 304 | +pub struct VARectangle { | ||
| 305 | + pub x: i16, | ||
| 306 | + pub y: i16, | ||
| 307 | + pub width: u16, | ||
| 308 | + pub height: u16, | ||
| 309 | +} | ||
| 310 | + | ||
| 311 | +// --------------------------------------------------------------------------- | ||
| 312 | +// Entry points | ||
| 313 | +// --------------------------------------------------------------------------- | ||
| 314 | + | ||
| 315 | +#[link(name = "va")] | ||
| 316 | +unsafe extern "C" { | ||
| 317 | + /// `va.h:403`. Returns a pointer to a static string; never NULL. | ||
| 318 | + pub fn vaErrorStr(error_status: VAStatus) -> *const c_char; | ||
| 319 | + /// `va.h:453`. | ||
| 320 | + pub fn vaDisplayIsValid(dpy: VADisplay) -> c_int; | ||
| 321 | + /// `va.h:465`. | ||
| 322 | + pub fn vaInitialize( | ||
| 323 | + dpy: VADisplay, | ||
| 324 | + major_version: *mut c_int, | ||
| 325 | + minor_version: *mut c_int, | ||
| 326 | + ) -> VAStatus; | ||
| 327 | + /// `va.h:474`. | ||
| 328 | + pub fn vaTerminate(dpy: VADisplay) -> VAStatus; | ||
| 329 | + /// `va.h:486`. Static string owned by the driver, valid until `vaTerminate`. | ||
| 330 | + pub fn vaQueryVendorString(dpy: VADisplay) -> *const c_char; | ||
| 331 | + | ||
| 332 | + /// `va.h:1524`. | ||
| 333 | + pub fn vaMaxNumProfiles(dpy: VADisplay) -> c_int; | ||
| 334 | + /// `va.h:1529`. | ||
| 335 | + pub fn vaMaxNumEntrypoints(dpy: VADisplay) -> c_int; | ||
| 336 | + /// `va.h:1534`. | ||
| 337 | + pub fn vaMaxNumConfigAttributes(dpy: VADisplay) -> c_int; | ||
| 338 | + /// `va.h:1544`. | ||
| 339 | + pub fn vaQueryConfigProfiles( | ||
| 340 | + dpy: VADisplay, | ||
| 341 | + profile_list: *mut VAProfile, | ||
| 342 | + num_profiles: *mut c_int, | ||
| 343 | + ) -> VAStatus; | ||
| 344 | + /// `va.h:1556`. | ||
| 345 | + pub fn vaQueryConfigEntrypoints( | ||
| 346 | + dpy: VADisplay, | ||
| 347 | + profile: VAProfile, | ||
| 348 | + entrypoint_list: *mut VAEntrypoint, | ||
| 349 | + num_entrypoints: *mut c_int, | ||
| 350 | + ) -> VAStatus; | ||
| 351 | + /// `va.h:1571`. `attrib_list` is in/out: caller sets `type_`, driver fills `value`. | ||
| 352 | + pub fn vaGetConfigAttributes( | ||
| 353 | + dpy: VADisplay, | ||
| 354 | + profile: VAProfile, | ||
| 355 | + entrypoint: VAEntrypoint, | ||
| 356 | + attrib_list: *mut VAConfigAttrib, | ||
| 357 | + num_attribs: c_int, | ||
| 358 | + ) -> VAStatus; | ||
| 359 | + /// `va.h:1589`. | ||
| 360 | + pub fn vaCreateConfig( | ||
| 361 | + dpy: VADisplay, | ||
| 362 | + profile: VAProfile, | ||
| 363 | + entrypoint: VAEntrypoint, | ||
| 364 | + attrib_list: *mut VAConfigAttrib, | ||
| 365 | + num_attribs: c_int, | ||
| 366 | + config_id: *mut VAConfigID, | ||
| 367 | + ) -> VAStatus; | ||
| 368 | + /// `va.h:1601`. | ||
| 369 | + pub fn vaDestroyConfig(dpy: VADisplay, config_id: VAConfigID) -> VAStatus; | ||
| 370 | + | ||
| 371 | + /// `va.h:1868`. Pass NULL `attrib_list` to only query the count. | ||
| 372 | + pub fn vaQuerySurfaceAttributes( | ||
| 373 | + dpy: VADisplay, | ||
| 374 | + config: VAConfigID, | ||
| 375 | + attrib_list: *mut VASurfaceAttrib, | ||
| 376 | + num_attribs: *mut c_uint, | ||
| 377 | + ) -> VAStatus; | ||
| 378 | + /// `va.h:1894`. | ||
| 379 | + pub fn vaCreateSurfaces( | ||
| 380 | + dpy: VADisplay, | ||
| 381 | + format: c_uint, | ||
| 382 | + width: c_uint, | ||
| 383 | + height: c_uint, | ||
| 384 | + surfaces: *mut VASurfaceID, | ||
| 385 | + num_surfaces: c_uint, | ||
| 386 | + attrib_list: *mut VASurfaceAttrib, | ||
| 387 | + num_attribs: c_uint, | ||
| 388 | + ) -> VAStatus; | ||
| 389 | + /// `va.h:1914`. | ||
| 390 | + pub fn vaDestroySurfaces( | ||
| 391 | + dpy: VADisplay, | ||
| 392 | + surfaces: *mut VASurfaceID, | ||
| 393 | + num_surfaces: c_int, | ||
| 394 | + ) -> VAStatus; | ||
| 395 | + /// `va.h:4185`. `descriptor` type is chosen by `mem_type`. | ||
| 396 | + pub fn vaExportSurfaceHandle( | ||
| 397 | + dpy: VADisplay, | ||
| 398 | + surface_id: VASurfaceID, | ||
| 399 | + mem_type: u32, | ||
| 400 | + flags: u32, | ||
| 401 | + descriptor: *mut c_void, | ||
| 402 | + ) -> VAStatus; | ||
| 403 | + | ||
| 404 | + /// `va.h:1933`. | ||
| 405 | + pub fn vaCreateContext( | ||
| 406 | + dpy: VADisplay, | ||
| 407 | + config_id: VAConfigID, | ||
| 408 | + picture_width: c_int, | ||
| 409 | + picture_height: c_int, | ||
| 410 | + flag: c_int, | ||
| 411 | + render_targets: *mut VASurfaceID, | ||
| 412 | + num_render_targets: c_int, | ||
| 413 | + context: *mut VAContextID, | ||
| 414 | + ) -> VAStatus; | ||
| 415 | + /// `va.h:1949`. | ||
| 416 | + pub fn vaDestroyContext(dpy: VADisplay, context: VAContextID) -> VAStatus; | ||
| 417 | + | ||
| 418 | + /// `va.h:3833`. `data` NULL means "allocate, fill later via vaMapBuffer". | ||
| 419 | + pub fn vaCreateBuffer( | ||
| 420 | + dpy: VADisplay, | ||
| 421 | + context: VAContextID, | ||
| 422 | + type_: VABufferType, | ||
| 423 | + size: c_uint, | ||
| 424 | + num_elements: c_uint, | ||
| 425 | + data: *mut c_void, | ||
| 426 | + buf_id: *mut VABufferID, | ||
| 427 | + ) -> VAStatus; | ||
| 428 | + /// `va.h:3971`. | ||
| 429 | + pub fn vaMapBuffer(dpy: VADisplay, buf_id: VABufferID, pbuf: *mut *mut c_void) -> VAStatus; | ||
| 430 | + /// `va.h:4004`. | ||
| 431 | + pub fn vaUnmapBuffer(dpy: VADisplay, buf_id: VABufferID) -> VAStatus; | ||
| 432 | + /// `va.h:4018`. | ||
| 433 | + pub fn vaDestroyBuffer(dpy: VADisplay, buffer_id: VABufferID) -> VAStatus; | ||
| 434 | + | ||
| 435 | + /// `va.h:4205`. | ||
| 436 | + pub fn vaBeginPicture( | ||
| 437 | + dpy: VADisplay, | ||
| 438 | + context: VAContextID, | ||
| 439 | + render_target: VASurfaceID, | ||
| 440 | + ) -> VAStatus; | ||
| 441 | + /// `va.h:4214`. | ||
| 442 | + pub fn vaRenderPicture( | ||
| 443 | + dpy: VADisplay, | ||
| 444 | + context: VAContextID, | ||
| 445 | + buffers: *mut VABufferID, | ||
| 446 | + num_buffers: c_int, | ||
| 447 | + ) -> VAStatus; | ||
| 448 | + /// `va.h:4229`. | ||
| 449 | + pub fn vaEndPicture(dpy: VADisplay, context: VAContextID) -> VAStatus; | ||
| 450 | + /// `va.h:4271`. Blocks until the render target is idle. | ||
| 451 | + pub fn vaSyncSurface(dpy: VADisplay, render_target: VASurfaceID) -> VAStatus; | ||
| 452 | + | ||
| 453 | + /// `va.h:4773`. | ||
| 454 | + pub fn vaMaxNumImageFormats(dpy: VADisplay) -> c_int; | ||
| 455 | + /// `va.h:4783`. | ||
| 456 | + pub fn vaQueryImageFormats( | ||
| 457 | + dpy: VADisplay, | ||
| 458 | + format_list: *mut VAImageFormat, | ||
| 459 | + num_formats: *mut c_int, | ||
| 460 | + ) -> VAStatus; | ||
| 461 | + /// `va.h:4796`. | ||
| 462 | + pub fn vaCreateImage( | ||
| 463 | + dpy: VADisplay, | ||
| 464 | + format: *mut VAImageFormat, | ||
| 465 | + width: c_int, | ||
| 466 | + height: c_int, | ||
| 467 | + image: *mut VAImage, | ||
| 468 | + ) -> VAStatus; | ||
| 469 | + /// `va.h:4807`. | ||
| 470 | + pub fn vaDestroyImage(dpy: VADisplay, image: VAImageID) -> VAStatus; | ||
| 471 | + /// `va.h:4827`. | ||
| 472 | + pub fn vaGetImage( | ||
| 473 | + dpy: VADisplay, | ||
| 474 | + surface: VASurfaceID, | ||
| 475 | + x: c_int, | ||
| 476 | + y: c_int, | ||
| 477 | + width: c_uint, | ||
| 478 | + height: c_uint, | ||
| 479 | + image: VAImageID, | ||
| 480 | + ) -> VAStatus; | ||
| 481 | + /// `va.h:4888`. Zero-copy view of a surface, when the driver allows it. | ||
| 482 | + pub fn vaDeriveImage(dpy: VADisplay, surface: VASurfaceID, image: *mut VAImage) -> VAStatus; | ||
| 483 | +} | ||
| 484 | + | ||
| 485 | +#[link(name = "va-drm")] | ||
| 486 | +unsafe extern "C" { | ||
| 487 | + /// `va_drm.h:45`. Returns NULL on failure. Does **not** take ownership of `fd`. | ||
| 488 | + pub fn vaGetDisplayDRM(fd: c_int) -> VADisplay; | ||
| 489 | +} | ||
| 490 | + | ||
| 491 | +// --------------------------------------------------------------------------- | ||
| 492 | +// ABI transcription check | ||
| 493 | +// --------------------------------------------------------------------------- | ||
| 494 | +// | ||
| 495 | +// Reference output of `crates/ec-va/abi-probe.c` compiled against | ||
| 496 | +// /usr/include/va (libva 1.23.0) with gcc on x86_64: | ||
| 497 | +// | ||
| 498 | +// VAConfigAttrib size=8 align=4 type=0 value=4 | ||
| 499 | +// VAGenericValue size=16 align=8 type=0 value=8 | ||
| 500 | +// VASurfaceAttrib size=24 align=8 type=0 flags=4 value=8 | ||
| 501 | +// VAImageFormat size=48 align=4 fourcc=0 .. va_reserved=32 | ||
| 502 | +// VAImage size=120 align=4 image_id=0 format=4 buf=52 | ||
| 503 | +// width=56 height=58 data_size=60 | ||
| 504 | +// num_planes=64 pitches=68 offsets=80 | ||
| 505 | +// num_palette_entries=92 entry_bytes=96 | ||
| 506 | +// component_order=100 va_reserved=104 | ||
| 507 | +// VADRMPRIMESurfaceDescriptor size=312 align=8 fourcc=0 width=4 height=8 | ||
| 508 | +// num_objects=12 objects=16 | ||
| 509 | +// num_layers=80 layers=84 | ||
| 510 | +// object elem size=16, layer elem size=56 | ||
| 511 | +// VARectangle size=8 align=2 | ||
| 512 | +const _: () = { | ||
| 513 | + use std::mem::{align_of, offset_of, size_of}; | ||
| 514 | + | ||
| 515 | + assert!(size_of::<VAConfigAttrib>() == 8 && align_of::<VAConfigAttrib>() == 4); | ||
| 516 | + assert!(offset_of!(VAConfigAttrib, value) == 4); | ||
| 517 | + | ||
| 518 | + assert!(size_of::<VAGenericValue>() == 16 && align_of::<VAGenericValue>() == 8); | ||
| 519 | + assert!(offset_of!(VAGenericValue, value) == 8); | ||
| 520 | + | ||
| 521 | + assert!(size_of::<VASurfaceAttrib>() == 24 && align_of::<VASurfaceAttrib>() == 8); | ||
| 522 | + assert!(offset_of!(VASurfaceAttrib, flags) == 4); | ||
| 523 | + assert!(offset_of!(VASurfaceAttrib, value) == 8); | ||
| 524 | + | ||
| 525 | + assert!(size_of::<VAImageFormat>() == 48 && align_of::<VAImageFormat>() == 4); | ||
| 526 | + assert!(offset_of!(VAImageFormat, va_reserved) == 32); | ||
| 527 | + | ||
| 528 | + assert!(size_of::<VAImage>() == 120 && align_of::<VAImage>() == 4); | ||
| 529 | + assert!(offset_of!(VAImage, format) == 4); | ||
| 530 | + assert!(offset_of!(VAImage, buf) == 52); | ||
| 531 | + assert!(offset_of!(VAImage, width) == 56); | ||
| 532 | + assert!(offset_of!(VAImage, height) == 58); | ||
| 533 | + assert!(offset_of!(VAImage, data_size) == 60); | ||
| 534 | + assert!(offset_of!(VAImage, num_planes) == 64); | ||
| 535 | + assert!(offset_of!(VAImage, pitches) == 68); | ||
| 536 | + assert!(offset_of!(VAImage, offsets) == 80); | ||
| 537 | + assert!(offset_of!(VAImage, num_palette_entries) == 92); | ||
| 538 | + assert!(offset_of!(VAImage, entry_bytes) == 96); | ||
| 539 | + assert!(offset_of!(VAImage, component_order) == 100); | ||
| 540 | + assert!(offset_of!(VAImage, va_reserved) == 104); | ||
| 541 | + | ||
| 542 | + assert!(size_of::<VADRMPRIMEObject>() == 16); | ||
| 543 | + assert!(size_of::<VADRMPRIMELayer>() == 56); | ||
| 544 | + assert!( | ||
| 545 | + size_of::<VADRMPRIMESurfaceDescriptor>() == 312 | ||
| 546 | + && align_of::<VADRMPRIMESurfaceDescriptor>() == 8 | ||
| 547 | + ); | ||
| 548 | + assert!(offset_of!(VADRMPRIMESurfaceDescriptor, objects) == 16); | ||
| 549 | + assert!(offset_of!(VADRMPRIMESurfaceDescriptor, num_layers) == 80); | ||
| 550 | + assert!(offset_of!(VADRMPRIMESurfaceDescriptor, layers) == 84); | ||
| 551 | + | ||
| 552 | + assert!(size_of::<VARectangle>() == 8 && align_of::<VARectangle>() == 2); | ||
| 553 | + | ||
| 554 | + // Assumption 2: C `enum` and `unsigned int` are both 4 bytes here. | ||
| 555 | + assert!(size_of::<VAStatus>() == 4); | ||
| 556 | + assert!(size_of::<VAGenericID>() == 4); | ||
| 557 | + assert!(size_of::<c_int>() == 4); | ||
| 558 | +}; | ||
crates/ec-va/tests/gpu.rsadded+502 -0
| @@ -0,0 +1,502 @@ | |||
| 1 | +//! Live GPU tests. Not `#[ignore]`d: this machine has the hardware, and a test | ||
| 2 | +//! that never runs is not a test. On a machine with no VA-API device every one | ||
| 3 | +//! of these fails at `Display::open`, which is the honest outcome — the crate | ||
| 4 | +//! has no meaning without a driver. | ||
| 5 | +//! | ||
| 6 | +//! Everything lives in one test binary on purpose (a file per feature is a | ||
| 7 | +//! serial link-and-run tax). Every test opens its own display and takes | ||
| 8 | +//! [`serial`], so the two process-wide measurements below stay meaningful. | ||
| 9 | +//! | ||
| 10 | +//! Reference: `vainfo` on this box (Mesa 26.1.6, radeonsi gfx1200, RX 9060 XT). | ||
| 11 | + | ||
| 12 | +use std::os::fd::AsRawFd; | ||
| 13 | +use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; | ||
| 14 | + | ||
| 15 | +use ec_va::caps::{Entrypoint, Profile}; | ||
| 16 | +use ec_va::{ | ||
| 17 | + CapReport, Config, Context, Display, Error, Image, Picture, Surface, SurfaceSpec, sys, | ||
| 18 | +}; | ||
| 19 | + | ||
| 20 | +/// Runs the tests in this binary one at a time. | ||
| 21 | +/// | ||
| 22 | +/// Two of them measure process-wide state — `VmRSS` for the surface-pool leak | ||
| 23 | +/// check and `/proc/self/fd` for the PRIME export ownership check — and a | ||
| 24 | +/// sibling test allocating a 1080p pool on another thread would make both | ||
| 25 | +/// meaningless. Serialising is cheaper and more honest than loosening the | ||
| 26 | +/// thresholds until concurrency stops mattering. | ||
| 27 | +fn serial() -> MutexGuard<'static, ()> { | ||
| 28 | + static LOCK: OnceLock<Mutex<()>> = OnceLock::new(); | ||
| 29 | + LOCK.get_or_init(|| Mutex::new(())) | ||
| 30 | + .lock() | ||
| 31 | + // A panicking test poisons the mutex; the rest are still worth running. | ||
| 32 | + .unwrap_or_else(|poisoned| poisoned.into_inner()) | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +fn display() -> Arc<Display> { | ||
| 36 | + Display::open().expect("no VA-API display; this test needs the GPU") | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +// -------------------------------------------------------------------------- | ||
| 40 | +// Display | ||
| 41 | +// -------------------------------------------------------------------------- | ||
| 42 | + | ||
| 43 | +#[test] | ||
| 44 | +fn display_opens_on_a_render_node() { | ||
| 45 | + let _serial = serial(); | ||
| 46 | + let display = display(); | ||
| 47 | + assert!(display.is_valid()); | ||
| 48 | + let (major, minor) = display.version(); | ||
| 49 | + assert_eq!(major, ec_va::MIN_VA_MAJOR); | ||
| 50 | + assert!( | ||
| 51 | + minor >= ec_va::MIN_VA_MINOR, | ||
| 52 | + "runtime libva {major}.{minor} is older than the transcribed ABI" | ||
| 53 | + ); | ||
| 54 | + assert!( | ||
| 55 | + display | ||
| 56 | + .device_path() | ||
| 57 | + .to_string_lossy() | ||
| 58 | + .starts_with("/dev/dri/renderD"), | ||
| 59 | + "expected a render node, got {:?}", | ||
| 60 | + display.device_path() | ||
| 61 | + ); | ||
| 62 | + let vendor = display.vendor().expect("vendor string"); | ||
| 63 | + assert!(!vendor.is_empty(), "driver reported an empty vendor string"); | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +// -------------------------------------------------------------------------- | ||
| 67 | +// Capabilities — the table must match `vainfo` on this GPU | ||
| 68 | +// -------------------------------------------------------------------------- | ||
| 69 | + | ||
| 70 | +#[test] | ||
| 71 | +fn caps_match_vainfo_on_this_gpu() { | ||
| 72 | + let _serial = serial(); | ||
| 73 | + let display = display(); | ||
| 74 | + let caps = CapReport::probe(&display).expect("probe"); | ||
| 75 | + | ||
| 76 | + // Decode: every codec the family hands to hardware. | ||
| 77 | + for profile in [ | ||
| 78 | + Profile::H264ConstrainedBaseline, | ||
| 79 | + Profile::H264Main, | ||
| 80 | + Profile::H264High, | ||
| 81 | + Profile::HEVCMain, | ||
| 82 | + Profile::HEVCMain10, | ||
| 83 | + Profile::VP9Profile0, | ||
| 84 | + Profile::VP9Profile2, | ||
| 85 | + Profile::AV1Profile0, | ||
| 86 | + Profile::AV1Profile2, | ||
| 87 | + ] { | ||
| 88 | + assert!( | ||
| 89 | + caps.supports(profile, Entrypoint::VLD), | ||
| 90 | + "{} VLD missing from the probe but present in vainfo", | ||
| 91 | + profile.name() | ||
| 92 | + ); | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + // Encode: H.264 and HEVC are the two the family ships (AV1 encode exists on | ||
| 96 | + // this GPU too, but stays opt-in — see the family plan). | ||
| 97 | + for profile in [ | ||
| 98 | + Profile::H264ConstrainedBaseline, | ||
| 99 | + Profile::H264Main, | ||
| 100 | + Profile::H264High, | ||
| 101 | + Profile::HEVCMain, | ||
| 102 | + Profile::HEVCMain10, | ||
| 103 | + ] { | ||
| 104 | + assert!( | ||
| 105 | + caps.supports(profile, Entrypoint::EncSlice), | ||
| 106 | + "{} EncSlice missing from the probe but present in vainfo", | ||
| 107 | + profile.name() | ||
| 108 | + ); | ||
| 109 | + } | ||
| 110 | + | ||
| 111 | + // Post-processing, used later for colour conversion. | ||
| 112 | + assert!(caps.supports(Profile::None, Entrypoint::VideoProc)); | ||
| 113 | + | ||
| 114 | + // A pair this GPU genuinely lacks must be absent, not silently invented: | ||
| 115 | + // vainfo lists VP9 profiles 0 and 2 only. | ||
| 116 | + assert!(!caps.supports(Profile::VP9Profile1, Entrypoint::VLD)); | ||
| 117 | + assert!(!caps.supports(Profile::VP9Profile3, Entrypoint::VLD)); | ||
| 118 | + assert!(!caps.supports(Profile::VP9Profile0, Entrypoint::EncSlice)); | ||
| 119 | + | ||
| 120 | + // 10-bit decode must advertise a 10-bit RT format, or `ec-hw` would derive | ||
| 121 | + // an 8-bit context for Main10 — the incumbent's D2 defect. | ||
| 122 | + let main10 = caps | ||
| 123 | + .entry(Profile::HEVCMain10, Entrypoint::VLD) | ||
| 124 | + .expect("HEVC Main10 VLD"); | ||
| 125 | + assert!( | ||
| 126 | + main10.supports_rt_format(sys::VA_RT_FORMAT_YUV420_10), | ||
| 127 | + "HEVC Main10 VLD advertised rt_formats 0x{:08x} without a 10-bit format", | ||
| 128 | + main10.rt_formats | ||
| 129 | + ); | ||
| 130 | + let p010_supported = main10 | ||
| 131 | + .surfaces | ||
| 132 | + .as_ref() | ||
| 133 | + .expect("surface caps") | ||
| 134 | + .supports_fourcc(sys::VA_FOURCC_P010); | ||
| 135 | + assert!(p010_supported, "Main10 cannot allocate P010 surfaces"); | ||
| 136 | + | ||
| 137 | + // 8-bit decode: NV12 everywhere. | ||
| 138 | + let h264 = caps | ||
| 139 | + .entry(Profile::H264Main, Entrypoint::VLD) | ||
| 140 | + .expect("H264 Main VLD"); | ||
| 141 | + assert!(h264.supports_rt_format(sys::VA_RT_FORMAT_YUV420)); | ||
| 142 | + assert!( | ||
| 143 | + h264.surfaces | ||
| 144 | + .as_ref() | ||
| 145 | + .expect("surface caps") | ||
| 146 | + .supports_fourcc(sys::VA_FOURCC_NV12) | ||
| 147 | + ); | ||
| 148 | + | ||
| 149 | + // Readback formats: `vaGetImage` must be able to produce NV12 and P010. | ||
| 150 | + assert!(caps.image_formats.contains(&sys::VA_FOURCC_NV12)); | ||
| 151 | + assert!(caps.image_formats.contains(&sys::VA_FOURCC_P010)); | ||
| 152 | + | ||
| 153 | + assert!( | ||
| 154 | + caps.profiles_for(Entrypoint::VLD).len() >= 9, | ||
| 155 | + "expected at least 9 decode profiles, got {:?}", | ||
| 156 | + caps.profiles_for(Entrypoint::VLD) | ||
| 157 | + ); | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +#[test] | ||
| 161 | +fn caps_report_driver_legal_surface_sizes() { | ||
| 162 | + let _serial = serial(); | ||
| 163 | + let display = display(); | ||
| 164 | + let caps = CapReport::probe(&display).expect("probe"); | ||
| 165 | + let entry = caps | ||
| 166 | + .entry(Profile::H264Main, Entrypoint::VLD) | ||
| 167 | + .expect("H264 Main VLD"); | ||
| 168 | + let surfaces = entry.surfaces.as_ref().expect("surface caps"); | ||
| 169 | + | ||
| 170 | + // radeonsi rejects decode surfaces below 64x64. Probing with a hardcoded | ||
| 171 | + // 16x16 config is what used to panic here, so the minimum is reported | ||
| 172 | + // rather than assumed. | ||
| 173 | + assert_eq!(surfaces.min_width, Some(64)); | ||
| 174 | + assert_eq!(surfaces.min_height, Some(64)); | ||
| 175 | + assert!(surfaces.max_width.unwrap() >= 4096); | ||
| 176 | + assert!( | ||
| 177 | + !surfaces.allows(16, 16), | ||
| 178 | + "16x16 must be refused by the caps" | ||
| 179 | + ); | ||
| 180 | + assert!(surfaces.allows(1920, 1088)); | ||
| 181 | + | ||
| 182 | + // DRM PRIME 2 export must be advertised: that is how frames leave the GPU. | ||
| 183 | + assert!( | ||
| 184 | + surfaces.memory_types & sys::VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2 != 0, | ||
| 185 | + "memory types 0x{:08x} lack DRM_PRIME_2", | ||
| 186 | + surfaces.memory_types | ||
| 187 | + ); | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +#[test] | ||
| 191 | +fn unsupported_pair_is_refused_by_the_driver() { | ||
| 192 | + let _serial = serial(); | ||
| 193 | + // A refusal is a claim: prove the capability is genuinely absent rather | ||
| 194 | + // than assumed absent. | ||
| 195 | + let display = display(); | ||
| 196 | + let caps = CapReport::probe(&display).expect("probe"); | ||
| 197 | + assert!(!caps.supports(Profile::VP9Profile1, Entrypoint::VLD)); | ||
| 198 | + | ||
| 199 | + let err = Config::new(&display, Profile::VP9Profile1, Entrypoint::VLD, &[]) | ||
| 200 | + .expect_err("VP9 Profile1 decode does not exist on this GPU"); | ||
| 201 | + let status = err.status().expect("a VAStatus-carrying error"); | ||
| 202 | + assert!( | ||
| 203 | + status == sys::VA_STATUS_ERROR_UNSUPPORTED_PROFILE | ||
| 204 | + || status == sys::VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT, | ||
| 205 | + "unexpected refusal: {err}" | ||
| 206 | + ); | ||
| 207 | + assert!(err.to_string().contains("vaCreateConfig"), "{err}"); | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +// -------------------------------------------------------------------------- | ||
| 211 | +// Surfaces | ||
| 212 | +// -------------------------------------------------------------------------- | ||
| 213 | + | ||
| 214 | +#[test] | ||
| 215 | +fn surface_pool_create_and_destroy_is_leak_free() { | ||
| 216 | + let _serial = serial(); | ||
| 217 | + let display = display(); | ||
| 218 | + let spec = SurfaceSpec::nv12(64, 64); | ||
| 219 | + | ||
| 220 | + // Warm up so first-touch allocations are not counted as a leak. | ||
| 221 | + for _ in 0..4 { | ||
| 222 | + let pool = Surface::create_pool(&display, &spec, 16).expect("pool"); | ||
| 223 | + assert_eq!(pool.len(), 16); | ||
| 224 | + drop(pool); | ||
| 225 | + } | ||
| 226 | + | ||
| 227 | + let before = vm_rss_kb(); | ||
| 228 | + for _ in 0..100 { | ||
| 229 | + let pool = Surface::create_pool(&display, &spec, 16).expect("pool"); | ||
| 230 | + // Every id must be distinct and valid, or the pool is aliasing memory. | ||
| 231 | + let mut ids: Vec<_> = pool.iter().map(|s| s.id()).collect(); | ||
| 232 | + ids.sort_unstable(); | ||
| 233 | + ids.dedup(); | ||
| 234 | + assert_eq!(ids.len(), 16, "vaCreateSurfaces returned duplicate ids"); | ||
| 235 | + assert!(ids.iter().all(|&id| id != sys::VA_INVALID_SURFACE)); | ||
| 236 | + drop(pool); | ||
| 237 | + } | ||
| 238 | + let after = vm_rss_kb(); | ||
| 239 | + | ||
| 240 | + // 1600 surfaces created and destroyed. A per-surface leak would be obvious | ||
| 241 | + // at this scale; the incumbent's unmatched map leaked ~3MB per frame. | ||
| 242 | + let delta_kb = after.saturating_sub(before); | ||
| 243 | + assert!( | ||
| 244 | + delta_kb < 50 * 1024, | ||
| 245 | + "VmRSS grew {delta_kb} kB over 100 create/destroy cycles" | ||
| 246 | + ); | ||
| 247 | +} | ||
| 248 | + | ||
| 249 | +#[test] | ||
| 250 | +fn derive_image_maps_and_reads_back() { | ||
| 251 | + let _serial = serial(); | ||
| 252 | + let display = display(); | ||
| 253 | + let surface = Surface::create(&display, &SurfaceSpec::nv12(64, 64)).expect("surface"); | ||
| 254 | + let mut image = surface.derive_image().expect("vaDeriveImage"); | ||
| 255 | + | ||
| 256 | + assert_eq!(image.fourcc(), sys::VA_FOURCC_NV12); | ||
| 257 | + assert_eq!(image.size(), (64, 64)); | ||
| 258 | + assert_eq!(image.num_planes(), 2, "NV12 is luma + interleaved chroma"); | ||
| 259 | + let pitch = image.pitch(0).expect("luma pitch"); | ||
| 260 | + assert!(pitch >= 64, "luma pitch {pitch} is narrower than the image"); | ||
| 261 | + | ||
| 262 | + { | ||
| 263 | + let mut mapped = image.map().expect("vaMapBuffer"); | ||
| 264 | + let luma = mapped.plane_mut(0).expect("luma plane"); | ||
| 265 | + assert_eq!( | ||
| 266 | + luma.len(), | ||
| 267 | + pitch as usize * 64, | ||
| 268 | + "luma plane length must be pitch * height" | ||
| 269 | + ); | ||
| 270 | + for (i, byte) in luma.iter_mut().enumerate() { | ||
| 271 | + *byte = (i % 251) as u8; | ||
| 272 | + } | ||
| 273 | + let chroma = mapped.plane(1).expect("chroma plane"); | ||
| 274 | + assert!(!chroma.is_empty()); | ||
| 275 | + assert!(mapped.plane(2).is_none(), "NV12 has no third plane"); | ||
| 276 | + | ||
| 277 | + let luma = mapped.plane(0).expect("luma plane"); | ||
| 278 | + assert_eq!(luma[0], 0); | ||
| 279 | + assert_eq!(luma[250], 250); | ||
| 280 | + assert_eq!(luma[251], 0, "write did not survive within the mapping"); | ||
| 281 | + } | ||
| 282 | + | ||
| 283 | + // Re-mapping after the guard dropped proves the unmap actually happened: | ||
| 284 | + // libva returns the same buffer only once per map, and a never-unmapped | ||
| 285 | + // mapping is the incumbent's per-frame leak. | ||
| 286 | + // | ||
| 287 | + // What is deliberately *not* asserted: that the bytes written above are | ||
| 288 | + // readable through this second mapping. On radeonsi 26.1 a derived-image | ||
| 289 | + // mapping is write-oriented staging — the write reaches the surface (see | ||
| 290 | + // `created_image_reads_a_surface_back`), but a fresh map reads back zeros. | ||
| 291 | + // Readback therefore goes through `vaGetImage`, never through a re-derive. | ||
| 292 | + let mapped = image.map().expect("second vaMapBuffer after unmap"); | ||
| 293 | + assert_eq!( | ||
| 294 | + mapped.plane(0).expect("luma").len(), | ||
| 295 | + pitch as usize * 64, | ||
| 296 | + "second mapping has a different geometry" | ||
| 297 | + ); | ||
| 298 | +} | ||
| 299 | + | ||
| 300 | +#[test] | ||
| 301 | +fn created_image_reads_a_surface_back() { | ||
| 302 | + let _serial = serial(); | ||
| 303 | + let display = display(); | ||
| 304 | + let surface = Surface::create(&display, &SurfaceSpec::nv12(64, 64)).expect("surface"); | ||
| 305 | + // Paint through the derived image so there is something known to read back. | ||
| 306 | + { | ||
| 307 | + let mut derived = surface.derive_image().expect("derive"); | ||
| 308 | + let mut mapped = derived.map().expect("map"); | ||
| 309 | + for byte in mapped.plane_mut(0).expect("luma") { | ||
| 310 | + *byte = 0x5a; | ||
| 311 | + } | ||
| 312 | + } | ||
| 313 | + surface.sync().expect("sync"); | ||
| 314 | + | ||
| 315 | + let mut image = Image::create(&display, sys::VA_FOURCC_NV12, 64, 64).expect("vaCreateImage"); | ||
| 316 | + surface | ||
| 317 | + .read_into(&mut image, 0, 0, 64, 64) | ||
| 318 | + .expect("vaGetImage"); | ||
| 319 | + let mapped = image.map().expect("map"); | ||
| 320 | + let luma = mapped.plane(0).expect("luma"); | ||
| 321 | + assert!( | ||
| 322 | + luma.iter().take(64).all(|&b| b == 0x5a), | ||
| 323 | + "vaGetImage did not return the painted luma" | ||
| 324 | + ); | ||
| 325 | + | ||
| 326 | + // Out-of-range regions are refused before reaching the driver. | ||
| 327 | + drop(mapped); | ||
| 328 | + let err = surface | ||
| 329 | + .read_into(&mut image, 0, 0, 128, 128) | ||
| 330 | + .expect_err("region larger than the image must be refused"); | ||
| 331 | + assert!(matches!(err, Error::Protocol(_)), "{err}"); | ||
| 332 | +} | ||
| 333 | + | ||
| 334 | +#[test] | ||
| 335 | +fn prime_export_owns_and_releases_its_descriptors() { | ||
| 336 | + let _serial = serial(); | ||
| 337 | + let display = display(); | ||
| 338 | + let surface = Surface::create(&display, &SurfaceSpec::nv12(64, 64)).expect("surface"); | ||
| 339 | + surface.sync().expect("sync before export"); | ||
| 340 | + | ||
| 341 | + let baseline = open_fd_count(); | ||
| 342 | + let exported = surface | ||
| 343 | + .export_prime(sys::VA_EXPORT_SURFACE_READ_ONLY) | ||
| 344 | + .expect("vaExportSurfaceHandle"); | ||
| 345 | + | ||
| 346 | + assert_eq!(exported.fourcc, sys::VA_FOURCC_NV12); | ||
| 347 | + assert_eq!((exported.width, exported.height), (64, 64)); | ||
| 348 | + assert!(!exported.objects.is_empty(), "no DRM objects exported"); | ||
| 349 | + assert!(!exported.layers.is_empty(), "no layers exported"); | ||
| 350 | + for object in &exported.objects { | ||
| 351 | + assert!(object.fd.as_raw_fd() >= 0); | ||
| 352 | + assert!(object.size > 0); | ||
| 353 | + } | ||
| 354 | + for layer in &exported.layers { | ||
| 355 | + assert!(!layer.planes.is_empty()); | ||
| 356 | + for &(object_index, _offset, pitch) in &layer.planes { | ||
| 357 | + assert!((object_index as usize) < exported.objects.len()); | ||
| 358 | + assert!(pitch > 0); | ||
| 359 | + } | ||
| 360 | + } | ||
| 361 | + | ||
| 362 | + let with_export = open_fd_count(); | ||
| 363 | + assert_eq!( | ||
| 364 | + with_export - baseline, | ||
| 365 | + exported.objects.len(), | ||
| 366 | + "exported fd count does not match the descriptor" | ||
| 367 | + ); | ||
| 368 | + drop(exported); | ||
| 369 | + assert_eq!( | ||
| 370 | + open_fd_count(), | ||
| 371 | + baseline, | ||
| 372 | + "dropping the export leaked file descriptors" | ||
| 373 | + ); | ||
| 374 | +} | ||
| 375 | + | ||
| 376 | +// -------------------------------------------------------------------------- | ||
| 377 | +// Context / picture protocol | ||
| 378 | +// -------------------------------------------------------------------------- | ||
| 379 | + | ||
| 380 | +#[test] | ||
| 381 | +fn picture_typestate_walks_the_va_protocol() { | ||
| 382 | + let _serial = serial(); | ||
| 383 | + let display = display(); | ||
| 384 | + let config = Config::new(&display, Profile::H264Main, Entrypoint::VLD, &[]).expect("config"); | ||
| 385 | + let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 2).expect("pool"); | ||
| 386 | + let context = | ||
| 387 | + Context::new(&config, 1920, 1088, sys::VA_PROGRESSIVE, &targets).expect("context"); | ||
| 388 | + | ||
| 389 | + // New -> Rendering. Each transition consumes the picture, so nothing can | ||
| 390 | + // call `begin` twice or reach `sync` without `end` (see the compile_fail | ||
| 391 | + // examples in the `picture` module docs). | ||
| 392 | + let picture = Picture::new(&context, Arc::clone(&targets[0])); | ||
| 393 | + let picture = picture.begin().expect("vaBeginPicture"); | ||
| 394 | + assert_eq!(picture.target().id(), targets[0].id()); | ||
| 395 | + | ||
| 396 | + // Rendering -> Ended. Submitting a picture with no parameter buffers is a | ||
| 397 | + // driver-level error here (mesa creates the decoder lazily from the picture | ||
| 398 | + // parameters, so it has nothing to end); what matters is that it surfaces | ||
| 399 | + // as a typed error instead of a panic, an abort or a GPU hang. Real | ||
| 400 | + // submissions carry parameter/slice buffers and are `ec-hw`'s job. | ||
| 401 | + let err = picture | ||
| 402 | + .end() | ||
| 403 | + .expect_err("empty submission is rejected by radeonsi"); | ||
| 404 | + assert_eq!( | ||
| 405 | + err.status(), | ||
| 406 | + Some(sys::VA_STATUS_ERROR_INVALID_CONTEXT), | ||
| 407 | + "{err}" | ||
| 408 | + ); | ||
| 409 | + assert!(err.to_string().contains("vaEndPicture"), "{err}"); | ||
| 410 | + | ||
| 411 | + // The display is still usable afterwards: an abandoned picture must not | ||
| 412 | + // wedge the context. | ||
| 413 | + let picture = Picture::new(&context, Arc::clone(&targets[1])) | ||
| 414 | + .begin() | ||
| 415 | + .expect("second vaBeginPicture after a failed end"); | ||
| 416 | + drop(picture); | ||
| 417 | + assert!(display.is_valid()); | ||
| 418 | +} | ||
| 419 | + | ||
| 420 | +#[test] | ||
| 421 | +fn buffers_map_unmap_and_destroy() { | ||
| 422 | + let _serial = serial(); | ||
| 423 | + let display = display(); | ||
| 424 | + let config = | ||
| 425 | + Config::new(&display, Profile::H264Main, Entrypoint::EncSlice, &[]).expect("config"); | ||
| 426 | + let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 1).expect("pool"); | ||
| 427 | + let context = | ||
| 428 | + Context::new(&config, 1920, 1088, sys::VA_PROGRESSIVE, &targets).expect("context"); | ||
| 429 | + | ||
| 430 | + // Coded-output buffer: allocated empty, mapped, written, unmapped, dropped. | ||
| 431 | + const CODED_SIZE: u32 = 1 << 20; | ||
| 432 | + let mut coded = ec_va::Buffer::allocate(&context, sys::VAEncCodedBufferType, CODED_SIZE) | ||
| 433 | + .expect("vaCreateBuffer"); | ||
| 434 | + assert_eq!(coded.buffer_type(), sys::VAEncCodedBufferType); | ||
| 435 | + assert_ne!(coded.id(), sys::VA_INVALID_ID); | ||
| 436 | + { | ||
| 437 | + let mut mapped = coded.map().expect("vaMapBuffer"); | ||
| 438 | + // SAFETY: 64 bytes of a 1 MiB allocation. | ||
| 439 | + let slice = unsafe { mapped.as_mut_slice(64) }; | ||
| 440 | + slice[0] = 0x42; | ||
| 441 | + // SAFETY: same 64-byte window, now read-only. | ||
| 442 | + assert_eq!(unsafe { mapped.as_slice(64) }[0], 0x42); | ||
| 443 | + } | ||
| 444 | + // Mapping again proves the guard released the mapping. | ||
| 445 | + drop(coded.map().expect("second vaMapBuffer after unmap")); | ||
| 446 | + | ||
| 447 | + // Parameter buffer: data is copied into driver memory during the call. | ||
| 448 | + let params = [0u8; 32]; | ||
| 449 | + let buffer = ec_va::Buffer::from_bytes(&context, sys::VAEncMiscParameterBufferType, ¶ms) | ||
| 450 | + .expect("vaCreateBuffer from bytes"); | ||
| 451 | + assert_ne!(buffer.id(), sys::VA_INVALID_ID); | ||
| 452 | + | ||
| 453 | + // An empty buffer is refused before it reaches the driver. | ||
| 454 | + let err = ec_va::Buffer::from_bytes(&context, sys::VAEncMiscParameterBufferType, &[]) | ||
| 455 | + .expect_err("empty buffer must be refused"); | ||
| 456 | + assert!(matches!(err, Error::Protocol(_)), "{err}"); | ||
| 457 | +} | ||
| 458 | + | ||
| 459 | +#[test] | ||
| 460 | +fn context_keeps_its_dependencies_alive() { | ||
| 461 | + let _serial = serial(); | ||
| 462 | + // Dropping the config and the surfaces while the context lives must be | ||
| 463 | + // safe: the context holds `Arc`s, so libva's destruction order (buffers -> | ||
| 464 | + // context -> surfaces -> config -> display) cannot be violated. | ||
| 465 | + let display = display(); | ||
| 466 | + let config = Config::new(&display, Profile::H264Main, Entrypoint::VLD, &[]).expect("config"); | ||
| 467 | + let targets = Surface::create_pool(&display, &SurfaceSpec::nv12(1920, 1088), 2).expect("pool"); | ||
| 468 | + let context = | ||
| 469 | + Context::new(&config, 1920, 1088, sys::VA_PROGRESSIVE, &targets).expect("context"); | ||
| 470 | + let target = Arc::clone(&targets[0]); | ||
| 471 | + drop(config); | ||
| 472 | + drop(targets); | ||
| 473 | + | ||
| 474 | + let picture = Picture::new(&context, target).begin().expect("begin"); | ||
| 475 | + drop(picture); | ||
| 476 | + drop(context); | ||
| 477 | + assert!(display.is_valid()); | ||
| 478 | +} | ||
| 479 | + | ||
| 480 | +// -------------------------------------------------------------------------- | ||
| 481 | +// helpers | ||
| 482 | +// -------------------------------------------------------------------------- | ||
| 483 | + | ||
| 484 | +fn vm_rss_kb() -> u64 { | ||
| 485 | + let status = std::fs::read_to_string("/proc/self/status").expect("/proc/self/status"); | ||
| 486 | + for line in status.lines() { | ||
| 487 | + if let Some(rest) = line.strip_prefix("VmRSS:") { | ||
| 488 | + return rest | ||
| 489 | + .split_whitespace() | ||
| 490 | + .next() | ||
| 491 | + .and_then(|v| v.parse().ok()) | ||
| 492 | + .expect("VmRSS value"); | ||
| 493 | + } | ||
| 494 | + } | ||
| 495 | + panic!("VmRSS not found in /proc/self/status"); | ||
| 496 | +} | ||
| 497 | + | ||
| 498 | +fn open_fd_count() -> usize { | ||
| 499 | + std::fs::read_dir("/proc/self/fd") | ||
| 500 | + .expect("/proc/self/fd") | ||
| 501 | + .count() | ||
| 502 | +} | ||