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(probe: impl Fn(&Display) -> anyhow::Result<()>) -> anyhow::Result<(PathBuf, Arc<Display>)> {
74 let mut refused = Vec::new();
75 for node in DrmDeviceIterator::default() {
76 let opened = Display::open_drm_display(&node)
77 .map_err(anyhow::Error::from)
78 .and_then(|display| probe(&display).map(|()| display));
79 match opened {
80 Ok(display) => return Ok((node, display)),
81 Err(err) => refused.push(format!("{}: {err:#}", node.display())),
82 }
83 }
84 match refused.is_empty() {
85 true => anyhow::bail!("no DRM render node under {DRM_NODE_DEFAULT_PREFIX}*"),
86 false => anyhow::bail!("no DRM render node qualifies ({})", refused.join("; ")),
87 }
88}
89
90pub struct Display {
99 handle: bindings::VADisplay,
101 drm_file: File,
103}
104
105#[derive(Debug, Error)]
107pub enum OpenDrmDisplayError {
108 #[error("libva could not be loaded: {0}")]
109 LibvaUnavailable(&'static str),
110 #[error("cannot open DRM device: {0}")]
111 DeviceOpen(io::Error),
112 #[error("vaGetDisplayDRM returned NULL")]
113 VaGetDisplayDrm,
114 #[error("call to vaInitialize failed: {0}")]
115 VaInitialize(VaError),
116}
117
118impl Display {
119 pub fn open_drm_display<P: AsRef<Path>>(path: P) -> Result<Arc<Self>, OpenDrmDisplayError> {
123 bindings::load().map_err(OpenDrmDisplayError::LibvaUnavailable)?;
126
127 let file = std::fs::File::options()
128 .read(true)
129 .write(true)
130 .open(path.as_ref())
131 .map_err(OpenDrmDisplayError::DeviceOpen)?;
132
133 let display = unsafe { bindings::va().vaGetDisplayDRM(file.as_raw_fd()) };
136 if display.is_null() {
137 return Err(OpenDrmDisplayError::VaGetDisplayDrm);
138 }
139
140 let mut major = 0i32;
141 let mut minor = 0i32;
142 va_check(unsafe { bindings::va().vaInitialize(display, &mut major, &mut minor) })
145 .map(|()| {
146 Arc::new(Self {
147 handle: display,
148 drm_file: file,
149 })
150 })
151 .map_err(OpenDrmDisplayError::VaInitialize)
152 }
153
154 pub fn open() -> Option<Arc<Self>> {
159 let devices = DrmDeviceIterator::default();
160
161 for device in devices {
163 if let Ok(display) = Self::open_drm_display(device) {
164 return Some(display);
165 }
166 }
167
168 None
169 }
170
171 pub(crate) fn handle(&self) -> bindings::VADisplay {
173 self.handle
174 }
175
176 pub fn query_config_profiles(&self) -> Result<Vec<bindings::VAProfile::Type>, VaError> {
178 let max = unsafe { bindings::va().vaMaxNumProfiles(self.handle) };
180 query(max, |profiles, num| unsafe {
182 bindings::va().vaQueryConfigProfiles(self.handle, profiles, num)
183 })
184 }
185
186 pub fn query_vendor_string(&self) -> std::result::Result<String, &'static str> {
193 let vendor_string = unsafe { bindings::va().vaQueryVendorString(self.handle) };
195
196 if vendor_string.is_null() {
197 return Err("vaQueryVendorString() returned NULL");
198 }
199
200 Ok(unsafe { CStr::from_ptr(vendor_string) }.to_string_lossy().to_string())
202 }
203
204 pub fn query_config_entrypoints(
206 &self,
207 profile: bindings::VAProfile::Type,
208 ) -> Result<Vec<bindings::VAEntrypoint::Type>, VaError> {
209 let max = unsafe { bindings::va().vaMaxNumEntrypoints(self.handle) };
211 query(max, |entrypoints, num| unsafe {
213 bindings::va().vaQueryConfigEntrypoints(self.handle, profile, entrypoints, num)
214 })
215 }
216
217 pub(crate) fn get_config_attributes(
223 &self,
224 profile: bindings::VAProfile::Type,
225 entrypoint: bindings::VAEntrypoint::Type,
226 attributes: &mut [bindings::VAConfigAttrib],
227 ) -> Result<(), VaError> {
228 va_check(unsafe {
231 bindings::va().vaGetConfigAttributes(
232 self.handle,
233 profile,
234 entrypoint,
235 attributes.as_mut_ptr(),
236 attributes.len() as i32,
237 )
238 })
239 }
240
241 pub fn create_surfaces<D: SurfaceMemoryDescriptor>(
263 self: &Arc<Self>,
264 rt_format: u32,
265 va_fourcc: Option<u32>,
266 width: u32,
267 height: u32,
268 usage_hint: Option<UsageHint>,
269 descriptors: Vec<D>,
270 ) -> Result<Vec<Surface<D>>, VaError> {
271 Surface::new(
272 Arc::clone(self),
273 rt_format,
274 va_fourcc,
275 width,
276 height,
277 usage_hint,
278 descriptors,
279 )
280 }
281
282 pub(crate) fn create_context<D: SurfaceMemoryDescriptor>(
292 self: &Arc<Self>,
293 config: &Config,
294 coded_width: u32,
295 coded_height: u32,
296 surfaces: Option<&Vec<Surface<D>>>,
297 progressive: bool,
298 ) -> Result<Rc<Context>, VaError> {
299 Context::new(
300 Arc::clone(self),
301 config,
302 coded_width,
303 coded_height,
304 surfaces,
305 progressive,
306 )
307 }
308
309 pub(crate) fn create_config(
316 self: &Arc<Self>,
317 attrs: Vec<bindings::VAConfigAttrib>,
318 profile: bindings::VAProfile::Type,
319 entrypoint: bindings::VAEntrypoint::Type,
320 ) -> Result<Config, VaError> {
321 Config::new(Arc::clone(self), attrs, profile, entrypoint)
322 }
323
324 pub fn query_image_formats(&self) -> Result<Vec<bindings::VAImageFormat>, VaError> {
326 let max = unsafe { bindings::va().vaMaxNumImageFormats(self.handle) };
328 query(max, |formats, num| unsafe {
330 bindings::va().vaQueryImageFormats(self.handle, formats, num)
331 })
332 }
333}
334
335fn query<T>(max: c_int, query: impl FnOnce(*mut T, *mut c_int) -> bindings::VAStatus) -> Result<Vec<T>, VaError> {
338 let invalid = || VaError::status(bindings::VA_STATUS_ERROR_OPERATION_FAILED);
339 let capacity = usize::try_from(max).map_err(|_| invalid())?;
340 let mut list = Vec::with_capacity(capacity);
341 let mut num = max;
342 va_check(query(list.as_mut_ptr(), &mut num))?;
343 let len = usize::try_from(num)
344 .ok()
345 .filter(|&len| len <= capacity)
346 .ok_or_else(invalid)?;
347 unsafe { list.set_len(len) };
349 Ok(list)
350}
351
352impl Drop for Display {
353 fn drop(&mut self) {
354 unsafe {
356 bindings::va().vaTerminate(self.handle);
357 }
359 }
360}
361
362unsafe impl Send for Display {}
365unsafe impl Sync for Display {}