forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

caps.rs340 lines, 11.0 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: a newer libva can name a profile this build has never
5//! heard of, and that must survive as data rather than become an invalid enum.
6
7use std::rc::Rc;
8
9use cros_libva::{VAConfigAttrib, VAConfigAttribType};
10
11use crate::config::{Config, SurfaceCaps, caps_of};
12use crate::display::Display;
13use crate::error::{Result, va_ok};
14
15/// Generates a safe enum mirroring a C enum, plus its raw conversions.
16///
17/// One table, three derived functions — so the transcription can be diffed
18/// against the header in one place.
19macro_rules! va_enum {
20 (
21 $(#[$meta:meta])*
22 $name:ident : $raw:ty {
23 $( $variant:ident = $value:expr , )*
24 }
25 ) => {
26 $(#[$meta])*
27 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
28 #[non_exhaustive]
29 pub enum $name {
30 $( #[allow(missing_docs)] $variant, )*
31 /// A value this build does not know. Carried, never guessed at.
32 Unknown($raw),
33 }
34
35 impl $name {
36 /// Interpret a raw C value. Never panics, never UB.
37 pub fn from_raw(raw: $raw) -> Self {
38 match raw {
39 $( $value => $name::$variant, )*
40 other => $name::Unknown(other),
41 }
42 }
43
44 /// The raw C value.
45 pub fn as_raw(self) -> $raw {
46 match self {
47 $( $name::$variant => $value, )*
48 $name::Unknown(other) => other,
49 }
50 }
51
52 /// The libva identifier, e.g. `"VAProfileH264High"`.
53 pub fn name(self) -> &'static str {
54 match self {
55 $( $name::$variant => concat!(stringify!($name), "::", stringify!($variant)), )*
56 $name::Unknown(_) => concat!(stringify!($name), "::Unknown"),
57 }
58 }
59 }
60 };
61}
62
63va_enum! {
64 /// `VAProfile`, transcribed from `va.h:502-547` (libva 1.23).
65 Profile: i32 {
66 None = -1,
67 MPEG2Simple = 0,
68 MPEG2Main = 1,
69 MPEG4Simple = 2,
70 MPEG4AdvancedSimple = 3,
71 MPEG4Main = 4,
72 H264Baseline = 5,
73 H264Main = 6,
74 H264High = 7,
75 VC1Simple = 8,
76 VC1Main = 9,
77 VC1Advanced = 10,
78 H263Baseline = 11,
79 JPEGBaseline = 12,
80 H264ConstrainedBaseline = 13,
81 VP8Version0_3 = 14,
82 H264MultiviewHigh = 15,
83 H264StereoHigh = 16,
84 HEVCMain = 17,
85 HEVCMain10 = 18,
86 VP9Profile0 = 19,
87 VP9Profile1 = 20,
88 VP9Profile2 = 21,
89 VP9Profile3 = 22,
90 HEVCMain12 = 23,
91 HEVCMain422_10 = 24,
92 HEVCMain422_12 = 25,
93 HEVCMain444 = 26,
94 HEVCMain444_10 = 27,
95 HEVCMain444_12 = 28,
96 HEVCSccMain = 29,
97 HEVCSccMain10 = 30,
98 HEVCSccMain444 = 31,
99 AV1Profile0 = 32,
100 AV1Profile1 = 33,
101 HEVCSccMain444_10 = 34,
102 Protected = 35,
103 H264High10 = 36,
104 VVCMain10 = 37,
105 VVCMultilayerMain10 = 38,
106 AV1Profile2 = 39,
107 H264High422 = 40,
108 }
109}
110
111va_enum! {
112 /// `VAEntrypoint`, transcribed from `va.h:552-616` (libva 1.23).
113 Entrypoint: u32 {
114 VLD = 1,
115 IZZ = 2,
116 IDCT = 3,
117 MoComp = 4,
118 Deblocking = 5,
119 EncSlice = 6,
120 EncPicture = 7,
121 EncSliceLP = 8,
122 VideoProc = 10,
123 FEI = 11,
124 Stats = 12,
125 ProtectedTEEComm = 13,
126 ProtectedContent = 14,
127 }
128}
129
130impl Profile {
131 /// True for the profiles the family decodes or encodes in hardware.
132 pub fn is_family_codec(self) -> bool {
133 matches!(
134 self,
135 Profile::H264ConstrainedBaseline
136 | Profile::H264Main
137 | Profile::H264High
138 | Profile::H264High10
139 | Profile::HEVCMain
140 | Profile::HEVCMain10
141 | Profile::VP9Profile0
142 | Profile::VP9Profile2
143 | Profile::AV1Profile0
144 | Profile::AV1Profile2
145 )
146 }
147}
148
149/// What one (profile, entrypoint) pair supports.
150/// One supported (profile, entrypoint) pair and what the driver says about it.
151#[derive(Debug, Clone)]
152pub struct CapEntry {
153 /// The profile.
154 pub profile: Profile,
155 /// The entrypoint.
156 pub entrypoint: Entrypoint,
157 /// `VAConfigAttribRTFormat`: the `VA_RT_FORMAT_*` mask.
158 pub rt_formats: u32,
159 /// `VAConfigAttribEncPackedHeaders`.
160 pub packed_headers: u32,
161 /// `VAConfigAttribRateControl`.
162 pub rate_control: u32,
163 /// Surface constraints, when the config could be created to ask.
164 pub surfaces: Option<SurfaceCaps>,
165}
166
167impl CapEntry {
168 /// True if `rt_format` (a `VA_RT_FORMAT_*` bit) is in the mask.
169 pub fn supports_rt_format(&self, rt_format: u32) -> bool {
170 self.rt_formats & rt_format != 0
171 }
172}
173
174/// Everything the driver told us about itself.
175#[derive(Debug, Clone)]
176pub struct CapReport {
177 /// `vaQueryVendorString`.
178 pub vendor: String,
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
185impl 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: &Rc<Display>) -> Result<CapReport> {
190 let entries = probe_entries(display)?;
191 Ok(CapReport {
192 vendor: crate::display::vendor(display)?,
193 entries,
194 image_formats: query_image_formats(display)?,
195 })
196 }
197
198 /// The entry for a pair, if the driver supports it.
199 pub fn entry(&self, profile: Profile, entrypoint: Entrypoint) -> Option<&CapEntry> {
200 self.entries
201 .iter()
202 .find(|e| e.profile == profile && e.entrypoint == entrypoint)
203 }
204
205 /// True if this GPU supports the pair at all.
206 pub fn supports(&self, profile: Profile, entrypoint: Entrypoint) -> bool {
207 self.entry(profile, entrypoint).is_some()
208 }
209
210 /// Profiles supporting `entrypoint`, deduplicated, in driver order.
211 pub fn profiles_for(&self, entrypoint: Entrypoint) -> Vec<Profile> {
212 let mut out = Vec::new();
213 for e in self.entries.iter().filter(|e| e.entrypoint == entrypoint) {
214 if !out.contains(&e.profile) {
215 out.push(e.profile);
216 }
217 }
218 out
219 }
220}
221
222fn probe_entries(display: &Rc<Display>) -> Result<Vec<CapEntry>> {
223 let mut entries = Vec::new();
224 for profile in query_profiles(display)? {
225 for entrypoint in query_entrypoints(display, profile)? {
226 let [rt_formats, packed_headers, rate_control] =
227 query_attribs(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), which 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(mut config) => caps_of(&mut config).ok(),
235 Err(_) => None,
236 };
237 entries.push(CapEntry {
238 profile,
239 entrypoint,
240 rt_formats,
241 packed_headers,
242 rate_control,
243 surfaces,
244 });
245 }
246 }
247 Ok(entries)
248}
249
250fn query_profiles(display: &Rc<Display>) -> Result<Vec<Profile>> {
251 let raw = va_ok("vaQueryConfigProfiles", display.query_config_profiles())?;
252 Ok(raw.into_iter().map(Profile::from_raw).collect())
253}
254
255fn query_entrypoints(display: &Rc<Display>, profile: Profile) -> Result<Vec<Entrypoint>> {
256 let raw = va_ok(
257 "vaQueryConfigEntrypoints",
258 display.query_config_entrypoints(profile.as_raw()),
259 )?;
260 Ok(raw.into_iter().map(Entrypoint::from_raw).collect())
261}
262
263fn query_attribs(
264 display: &Rc<Display>,
265 profile: Profile,
266 entrypoint: Entrypoint,
267) -> Result<[u32; 3]> {
268 let mut attrs = [
269 VAConfigAttrib {
270 type_: VAConfigAttribType::VAConfigAttribRTFormat,
271 value: 0,
272 },
273 VAConfigAttrib {
274 type_: VAConfigAttribType::VAConfigAttribEncPackedHeaders,
275 value: 0,
276 },
277 VAConfigAttrib {
278 type_: VAConfigAttribType::VAConfigAttribRateControl,
279 value: 0,
280 },
281 ];
282 va_ok(
283 "vaGetConfigAttributes",
284 display.get_config_attributes(profile.as_raw(), entrypoint.as_raw(), &mut attrs),
285 )?;
286 // VA_ATTRIB_NOT_SUPPORTED is 0xffffffff; a decode entrypoint answers that
287 // for the encode-only attributes, and "all bits set" is not a capability.
288 let value = |a: &VAConfigAttrib| if a.value == u32::MAX { 0 } else { a.value };
289 Ok([value(&attrs[0]), value(&attrs[1]), value(&attrs[2])])
290}
291
292fn query_image_formats(display: &Rc<Display>) -> Result<Vec<u32>> {
293 let formats = va_ok("vaQueryImageFormats", display.query_image_formats())?;
294 Ok(formats.into_iter().map(|f| f.fourcc).collect())
295}
296
297/// Render a FourCC as its four characters, `?` for non-printable bytes.
298pub fn fourcc_str(fourcc: u32) -> String {
299 fourcc
300 .to_le_bytes()
301 .iter()
302 .map(|&b| if b.is_ascii_graphic() { b as char } else { '?' })
303 .collect()
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309
310 #[test]
311 fn profile_roundtrip_and_unknown_arm() {
312 for raw in -1..=40 {
313 let p = Profile::from_raw(raw);
314 assert_eq!(p.as_raw(), raw, "roundtrip failed for {raw}");
315 assert_ne!(p, Profile::Unknown(raw), "{raw} should be a known profile");
316 }
317 // A profile from a future libva must survive, not become UB or a panic.
318 assert_eq!(Profile::from_raw(9_999), Profile::Unknown(9_999));
319 assert_eq!(Profile::from_raw(9_999).as_raw(), 9_999);
320 assert_eq!(Profile::Unknown(9_999).name(), "Profile::Unknown");
321 assert_eq!(Profile::H264High.name(), "Profile::H264High");
322 }
323
324 #[test]
325 fn entrypoint_roundtrip_and_unknown_arm() {
326 for raw in [1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14] {
327 assert_eq!(Entrypoint::from_raw(raw).as_raw(), raw);
328 }
329 // 9 is unassigned in libva 1.23 and 15 is beyond the table.
330 assert_eq!(Entrypoint::from_raw(9), Entrypoint::Unknown(9));
331 assert_eq!(Entrypoint::from_raw(15), Entrypoint::Unknown(15));
332 }
333
334 #[test]
335 fn fourcc_rendering() {
336 assert_eq!(fourcc_str(cros_libva::VA_FOURCC_NV12), "NV12");
337 assert_eq!(fourcc_str(cros_libva::VA_FOURCC_P010), "P010");
338 assert_eq!(fourcc_str(0), "????");
339 }
340}