1use std::ffi::CStr;
6use std::fs::File;
7use std::io;
8use std::os::raw::c_int;
9use std::os::unix::io::AsRawFd;
10use std::path::Path;
11use std::path::PathBuf;
12use std::rc::Rc;
13use std::sync::Arc;
14
15use thiserror::Error;
16
17use crate::bindings;
18use crate::config::Config;
19use crate::context::Context;
20use crate::surface::Surface;
21use crate::va_check;
22use crate::SurfaceMemoryDescriptor;
23use crate::UsageHint;
24use crate::VaError;
25
26pub struct DrmDeviceIterator {
31 cur_idx: usize,
32}
33
34const DRM_NODE_DEFAULT_PREFIX: &str = "/dev/dri/renderD";
35const DRM_NUM_NODES: usize = 64;
36const DRM_RENDER_NODE_START: usize = 128;
37
38impl Default for DrmDeviceIterator {
39 fn default() -> Self {
40 Self {
41 cur_idx: DRM_RENDER_NODE_START,
42 }
43 }
44}
45
46impl Iterator for DrmDeviceIterator {
47 type Item = PathBuf;
48
49 fn next(&mut self) -> Option<Self::Item> {
50 while self.cur_idx < DRM_RENDER_NODE_START + DRM_NUM_NODES {
53 let path = PathBuf::from(format!("{}{}", DRM_NODE_DEFAULT_PREFIX, self.cur_idx));
54 self.cur_idx += 1;
55 if path.exists() {
56 return Some(path);
57 }
58 }
59 None
60 }
61}
62
63pub(crate) fn open_first(
74 probe: impl Fn(&Arc<Display>) -> anyhow::Result<()>,
75) -> anyhow::Result<(PathBuf, Arc<Display>)> {
76 let mut refused = Vec::new();
77 for node in DrmDeviceIterator::default() {
78 let opened = Display::open_drm_display(&node)
79 .map_err(anyhow::Error::from)
80 .and_then(|display| probe(&display).map(|()| display));
81 match opened {
82 Ok(display) => return Ok((node, display)),
83 Err(err) => refused.push(format!("{}: {err:#}", node.display())),
84 }
85 }
86 match refused.is_empty() {
87 true => anyhow::bail!("no DRM render node under {DRM_NODE_DEFAULT_PREFIX}*"),
88 false => anyhow::bail!("no DRM render node qualifies ({})", refused.join("; ")),
89 }
90}
91
92pub struct Display {
101 handle: bindings::VADisplay,
103 drm_file: File,
105}
106
107#[derive(Debug, Error)]
109pub enum OpenDrmDisplayError {
110 #[error("libva could not be loaded: {0}")]
111 LibvaUnavailable(&'static str),
112 #[error("cannot open DRM device: {0}")]
113 DeviceOpen(io::Error),
114 #[error("vaGetDisplayDRM returned NULL")]
115 VaGetDisplayDrm,
116 #[error("call to vaInitialize failed: {0}")]
117 VaInitialize(VaError),
118}
119
120impl Display {
121 pub fn open_drm_display<P: AsRef<Path>>(path: P) -> Result<Arc<Self>, OpenDrmDisplayError> {
125 bindings::load().map_err(OpenDrmDisplayError::LibvaUnavailable)?;
128
129 let file = std::fs::File::options()
130 .read(true)
131 .write(true)
132 .open(path.as_ref())
133 .map_err(OpenDrmDisplayError::DeviceOpen)?;
134
135 let display = unsafe { bindings::va().vaGetDisplayDRM(file.as_raw_fd()) };
138 if display.is_null() {
139 return Err(OpenDrmDisplayError::VaGetDisplayDrm);
140 }
141
142 let mut major = 0i32;
143 let mut minor = 0i32;
144 va_check(unsafe { bindings::va().vaInitialize(display, &mut major, &mut minor) })
147 .map(|()| {
148 Arc::new(Self {
149 handle: display,
150 drm_file: file,
151 })
152 })
153 .map_err(OpenDrmDisplayError::VaInitialize)
154 }
155
156 pub fn open() -> Option<Arc<Self>> {
161 let devices = DrmDeviceIterator::default();
162
163 for device in devices {
165 if let Ok(display) = Self::open_drm_display(device) {
166 return Some(display);
167 }
168 }
169
170 None
171 }
172
173 pub(crate) fn handle(&self) -> bindings::VADisplay {
175 self.handle
176 }
177
178 pub fn query_config_profiles(&self) -> Result<Vec<bindings::VAProfile::Type>, VaError> {
180 let max = unsafe { bindings::va().vaMaxNumProfiles(self.handle) };
182 query(max, |profiles, num| unsafe {
184 bindings::va().vaQueryConfigProfiles(self.handle, profiles, num)
185 })
186 }
187
188 pub fn query_vendor_string(&self) -> std::result::Result<String, &'static str> {
195 let vendor_string = unsafe { bindings::va().vaQueryVendorString(self.handle) };
197
198 if vendor_string.is_null() {
199 return Err("vaQueryVendorString() returned NULL");
200 }
201
202 Ok(unsafe { CStr::from_ptr(vendor_string) }.to_string_lossy().to_string())
204 }
205
206 pub fn query_config_entrypoints(
208 &self,
209 profile: bindings::VAProfile::Type,
210 ) -> Result<Vec<bindings::VAEntrypoint::Type>, VaError> {
211 let max = unsafe { bindings::va().vaMaxNumEntrypoints(self.handle) };
213 query(max, |entrypoints, num| unsafe {
215 bindings::va().vaQueryConfigEntrypoints(self.handle, profile, entrypoints, num)
216 })
217 }
218
219 pub(crate) fn get_config_attributes(
225 &self,
226 profile: bindings::VAProfile::Type,
227 entrypoint: bindings::VAEntrypoint::Type,
228 attributes: &mut [bindings::VAConfigAttrib],
229 ) -> Result<(), VaError> {
230 va_check(unsafe {
233 bindings::va().vaGetConfigAttributes(
234 self.handle,
235 profile,
236 entrypoint,
237 attributes.as_mut_ptr(),
238 attributes.len() as i32,
239 )
240 })
241 }
242
243 pub fn create_surfaces<D: SurfaceMemoryDescriptor>(
265 self: &Arc<Self>,
266 rt_format: u32,
267 va_fourcc: Option<u32>,
268 width: u32,
269 height: u32,
270 usage_hint: Option<UsageHint>,
271 descriptors: Vec<D>,
272 ) -> Result<Vec<Surface<D>>, VaError> {
273 Surface::new(
274 Arc::clone(self),
275 rt_format,
276 va_fourcc,
277 width,
278 height,
279 usage_hint,
280 descriptors,
281 )
282 }
283
284 pub(crate) fn create_context<D: SurfaceMemoryDescriptor>(
294 self: &Arc<Self>,
295 config: &Config,
296 coded_width: u32,
297 coded_height: u32,
298 surfaces: Option<&Vec<Surface<D>>>,
299 progressive: bool,
300 ) -> Result<Rc<Context>, VaError> {
301 Context::new(
302 Arc::clone(self),
303 config,
304 coded_width,
305 coded_height,
306 surfaces,
307 progressive,
308 )
309 }
310
311 pub(crate) fn create_config(
318 self: &Arc<Self>,
319 attrs: Vec<bindings::VAConfigAttrib>,
320 profile: bindings::VAProfile::Type,
321 entrypoint: bindings::VAEntrypoint::Type,
322 ) -> Result<Config, VaError> {
323 Config::new(Arc::clone(self), attrs, profile, entrypoint)
324 }
325
326 pub fn query_image_formats(&self) -> Result<Vec<bindings::VAImageFormat>, VaError> {
328 let max = unsafe { bindings::va().vaMaxNumImageFormats(self.handle) };
330 query(max, |formats, num| unsafe {
332 bindings::va().vaQueryImageFormats(self.handle, formats, num)
333 })
334 }
335}
336
337fn query<T>(max: c_int, query: impl FnOnce(*mut T, *mut c_int) -> bindings::VAStatus) -> Result<Vec<T>, VaError> {
340 let invalid = || VaError::status(bindings::VA_STATUS_ERROR_OPERATION_FAILED);
341 let capacity = usize::try_from(max).map_err(|_| invalid())?;
342 let mut list = Vec::with_capacity(capacity);
343 let mut num = max;
344 va_check(query(list.as_mut_ptr(), &mut num))?;
345 let len = usize::try_from(num)
346 .ok()
347 .filter(|&len| len <= capacity)
348 .ok_or_else(invalid)?;
349 unsafe { list.set_len(len) };
351 Ok(list)
352}
353
354impl Drop for Display {
355 fn drop(&mut self) {
356 unsafe {
358 bindings::va().vaTerminate(self.handle);
359 }
361 }
362}
363
364unsafe impl Send for Display {}
367unsafe impl Sync for Display {}