forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBeb83b6fTahinli3 months ago495 commits

caps.rs392 lines, 13.5 KiBHistoryRawDownload
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
10use std::sync::Arc;
11
12use crate::config::{Config, SurfaceCaps};
13use crate::display::Display;
14use crate::error::{Result, check};
15use 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.
21macro_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
65va_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
113va_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
132impl 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)]
153pub 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 /// `VAConfigAttribEncPackedHeaders` bitmask (`VA_ENC_PACKED_HEADER_*`);
161 /// zero for a decode entrypoint. An encoder has to ask for these in its
162 /// config before the driver will use the headers it writes.
163 pub packed_headers: u32,
164 /// `VAConfigAttribRateControl` bitmask (`VA_RC_*`); zero for decode.
165 pub rate_control: u32,
166 /// Surface geometry and pixel formats this config accepts, when the driver
167 /// reports them. `None` if `vaQuerySurfaceAttributes` refused the config.
168 pub surfaces: Option<SurfaceCaps>,
169}
170
171impl CapEntry {
172 /// True if `rt_format` (a `VA_RT_FORMAT_*` bit) is in the mask.
173 pub fn supports_rt_format(&self, rt_format: u32) -> bool {
174 self.rt_formats & rt_format != 0
175 }
176}
177
178/// Everything the driver told us about itself.
179#[derive(Debug, Clone)]
180pub struct CapReport {
181 /// `vaQueryVendorString`.
182 pub vendor: String,
183 /// Runtime libva version.
184 pub version: (i32, i32),
185 /// One entry per supported (profile, entrypoint) pair, in driver order.
186 pub entries: Vec<CapEntry>,
187 /// FourCCs from `vaQueryImageFormats` — the formats `vaGetImage` can produce.
188 pub image_formats: Vec<u32>,
189}
190
191impl CapReport {
192 /// Probe a display. One `vaCreateConfig`/`vaDestroyConfig` round trip per
193 /// supported pair; ~15 pairs on a typical GPU, so this is cheap enough to
194 /// do once at startup and cache.
195 pub fn probe(display: &Arc<Display>) -> Result<CapReport> {
196 let entries = probe_entries(display)?;
197 Ok(CapReport {
198 vendor: display.vendor()?,
199 version: display.version(),
200 entries,
201 image_formats: query_image_formats(display)?,
202 })
203 }
204
205 /// The entry for a pair, if the driver supports it.
206 pub fn entry(&self, profile: Profile, entrypoint: Entrypoint) -> Option<&CapEntry> {
207 self.entries
208 .iter()
209 .find(|e| e.profile == profile && e.entrypoint == entrypoint)
210 }
211
212 /// True if this GPU supports the pair at all.
213 pub fn supports(&self, profile: Profile, entrypoint: Entrypoint) -> bool {
214 self.entry(profile, entrypoint).is_some()
215 }
216
217 /// Profiles supporting `entrypoint`, deduplicated, in driver order.
218 pub fn profiles_for(&self, entrypoint: Entrypoint) -> Vec<Profile> {
219 let mut out = Vec::new();
220 for e in self.entries.iter().filter(|e| e.entrypoint == entrypoint) {
221 if !out.contains(&e.profile) {
222 out.push(e.profile);
223 }
224 }
225 out
226 }
227}
228
229fn probe_entries(display: &Arc<Display>) -> Result<Vec<CapEntry>> {
230 let mut entries = Vec::new();
231 for profile in query_profiles(display)? {
232 for entrypoint in query_entrypoints(display, profile)? {
233 let [rt_formats, packed_headers, rate_control] =
234 query_attribs(display, profile, entrypoint)?;
235 // Creating the config is also how the legal surface sizes are
236 // discovered: `vaQuerySurfaceAttributes` needs a config id. A
237 // driver may refuse a pair it just advertised (radeonsi does this
238 // for some encode entrypoints) — that is data, not an error, so it
239 // lands as `surfaces: None` instead of failing the whole probe.
240 let surfaces = match Config::new(display, profile, entrypoint, &[]) {
241 Ok(config) => config.surface_caps().ok(),
242 Err(_) => None,
243 };
244 entries.push(CapEntry {
245 profile,
246 entrypoint,
247 rt_formats,
248 packed_headers,
249 rate_control,
250 surfaces,
251 });
252 }
253 }
254 Ok(entries)
255}
256
257fn query_profiles(display: &Arc<Display>) -> Result<Vec<Profile>> {
258 // SAFETY: valid display; vaMaxNumProfiles only reads driver constants.
259 let max = unsafe { sys::vaMaxNumProfiles(display.handle()) };
260 let max = max.max(0) as usize;
261 let mut raw = vec![0 as sys::VAProfile; max];
262 let mut count: i32 = 0;
263 // SAFETY: `raw` has `max` elements, which is the capacity libva promises
264 // never to exceed (va.h:1524). `count` is a valid out-parameter. On return
265 // only the first `count` entries are initialized, and only those are read.
266 let status =
267 unsafe { sys::vaQueryConfigProfiles(display.handle(), raw.as_mut_ptr(), &mut count) };
268 check("vaQueryConfigProfiles", status)?;
269 raw.truncate(count.clamp(0, max as i32) as usize);
270 Ok(raw.into_iter().map(Profile::from_raw).collect())
271}
272
273fn query_entrypoints(display: &Arc<Display>, profile: Profile) -> Result<Vec<Entrypoint>> {
274 // SAFETY: valid display; reads driver constants only.
275 let max = unsafe { sys::vaMaxNumEntrypoints(display.handle()) };
276 let max = max.max(0) as usize;
277 let mut raw = vec![0 as sys::VAEntrypoint; max];
278 let mut count: i32 = 0;
279 // SAFETY: as in `query_profiles` — buffer sized by vaMaxNumEntrypoints,
280 // valid out-parameter, only the reported prefix is read.
281 let status = unsafe {
282 sys::vaQueryConfigEntrypoints(
283 display.handle(),
284 profile.as_raw(),
285 raw.as_mut_ptr(),
286 &mut count,
287 )
288 };
289 check("vaQueryConfigEntrypoints", status)?;
290 raw.truncate(count.clamp(0, max as i32) as usize);
291 Ok(raw.into_iter().map(Entrypoint::from_raw).collect())
292}
293
294/// The three config attributes this family reads, in one round trip:
295/// RT format, packed headers, rate control modes.
296fn query_attribs(
297 display: &Arc<Display>,
298 profile: Profile,
299 entrypoint: Entrypoint,
300) -> Result<[u32; 3]> {
301 let mut attrs = [
302 sys::VAConfigAttrib {
303 type_: sys::VAConfigAttribRTFormat,
304 value: 0,
305 },
306 sys::VAConfigAttrib {
307 type_: sys::VAConfigAttribEncPackedHeaders,
308 value: 0,
309 },
310 sys::VAConfigAttrib {
311 type_: sys::VAConfigAttribRateControl,
312 value: 0,
313 },
314 ];
315 // SAFETY: `attrs` is a valid, initialized array of 1 VAConfigAttrib and the
316 // length passed matches. vaGetConfigAttributes writes only `value`.
317 let status = unsafe {
318 sys::vaGetConfigAttributes(
319 display.handle(),
320 profile.as_raw(),
321 entrypoint.as_raw(),
322 attrs.as_mut_ptr(),
323 attrs.len() as i32,
324 )
325 };
326 check("vaGetConfigAttributes", status)?;
327 // VA_ATTRIB_NOT_SUPPORTED is 0xffffffff; a decode entrypoint answers that
328 // for the encode-only attributes, and "all bits set" is not a capability.
329 let value = |a: &sys::VAConfigAttrib| if a.value == u32::MAX { 0 } else { a.value };
330 Ok([value(&attrs[0]), value(&attrs[1]), value(&attrs[2])])
331}
332
333fn query_image_formats(display: &Arc<Display>) -> Result<Vec<u32>> {
334 // SAFETY: valid display; reads driver constants only.
335 let max = unsafe { sys::vaMaxNumImageFormats(display.handle()) };
336 let max = max.max(0) as usize;
337 let mut formats = vec![sys::VAImageFormat::default(); max];
338 let mut count: i32 = 0;
339 // SAFETY: buffer sized by vaMaxNumImageFormats as the header requires
340 // (va.h:4773); `count` is a valid out-parameter; only the reported prefix
341 // is read afterwards.
342 let status =
343 unsafe { sys::vaQueryImageFormats(display.handle(), formats.as_mut_ptr(), &mut count) };
344 check("vaQueryImageFormats", status)?;
345 formats.truncate(count.clamp(0, max as i32) as usize);
346 Ok(formats.into_iter().map(|f| f.fourcc).collect())
347}
348
349/// A FourCC as its four ASCII characters, for logs and reports.
350pub fn fourcc_str(fourcc: u32) -> String {
351 fourcc
352 .to_le_bytes()
353 .iter()
354 .map(|&b| if b.is_ascii_graphic() { b as char } else { '?' })
355 .collect()
356}
357
358#[cfg(test)]
359mod tests {
360 use super::*;
361
362 #[test]
363 fn profile_roundtrip_and_unknown_arm() {
364 for raw in -1..=40 {
365 let p = Profile::from_raw(raw);
366 assert_eq!(p.as_raw(), raw, "roundtrip failed for {raw}");
367 assert_ne!(p, Profile::Unknown(raw), "{raw} should be a known profile");
368 }
369 // A profile from a future libva must survive, not become UB or a panic.
370 assert_eq!(Profile::from_raw(9_999), Profile::Unknown(9_999));
371 assert_eq!(Profile::from_raw(9_999).as_raw(), 9_999);
372 assert_eq!(Profile::Unknown(9_999).name(), "Profile::Unknown");
373 assert_eq!(Profile::H264High.name(), "Profile::H264High");
374 }
375
376 #[test]
377 fn entrypoint_roundtrip_and_unknown_arm() {
378 for raw in [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14] {
379 assert_eq!(Entrypoint::from_raw(raw).as_raw(), raw);
380 }
381 // 9 is unassigned in libva 1.23 and 15 is beyond the table.
382 assert_eq!(Entrypoint::from_raw(9), Entrypoint::Unknown(9));
383 assert_eq!(Entrypoint::from_raw(15), Entrypoint::Unknown(15));
384 }
385
386 #[test]
387 fn fourcc_rendering() {
388 assert_eq!(fourcc_str(sys::VA_FOURCC_NV12), "NV12");
389 assert_eq!(fourcc_str(sys::VA_FOURCC_P010), "P010");
390 assert_eq!(fourcc_str(0), "????");
391 }
392}