forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBa5441e8Tahinli3 months ago1014 commits

config.rs233 lines, 8.3 KiBHistoryRawDownload
1//! [`Config`] — a `VAConfigID` for one (profile, entrypoint) pair, plus the
2//! surface geometry the driver will accept for it.
3
4use std::sync::Arc;
5
6use crate::caps::{Entrypoint, Profile};
7use crate::display::Display;
8use crate::error::{Error, Result, check};
9use crate::sys;
10
11/// A configuration attribute, e.g. `RTFormat = VA_RT_FORMAT_YUV420`.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub 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
20impl 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)]
36pub 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
51impl 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.
70pub struct Config {
71 display: Arc<Display>,
72 id: sys::VAConfigID,
73 profile: Profile,
74 entrypoint: Entrypoint,
75}
76
77impl 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
216impl 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
226impl 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}