1 // Copyright 2022 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 use std::os::unix::io::AsRawFd;
9 use std::path::PathBuf;
13 use crate::config::Config;
14 use crate::context::Context;
15 use crate::formats::{RTFormat, VAFourcc};
17 use crate::surface::Surface;
18 use crate::UsageHints;
20 /// Iterates over existing DRM devices.
22 /// DRM devices can be passed to [`Display::open_drm_display`] in order to create a `Display` on
24 pub struct DrmDeviceIterator {
28 const DRM_NODE_DEFAULT_PREFIX: &str = "/dev/dri/renderD";
29 const DRM_NUM_NODES: usize = 64;
30 const DRM_RENDER_NODE_START: usize = 128;
32 impl Default for DrmDeviceIterator {
33 fn default() -> Self {
35 cur_idx: DRM_RENDER_NODE_START,
40 impl Iterator for DrmDeviceIterator {
43 fn next(&mut self) -> Option<Self::Item> {
45 idx if idx >= DRM_RENDER_NODE_START + DRM_NUM_NODES => None,
47 let path = PathBuf::from(format!("{}{}", DRM_NODE_DEFAULT_PREFIX, idx));
59 unsafe extern "C" fn null_msg_cb(_ctx: *mut std::ffi::c_void, _message: *const std::ffi::c_char) {
60 // let msg = CStr::from_ptr(message).to_string_lossy();
63 /// A VADisplay opened over DRM.
65 /// A Display is the starting point to using libva. This struct is essentially a safe wrapper over
66 /// `VADisplay`, from which [`Surface`]s and [`Context`]s can be allocated in order to perform
67 /// actual work using [`Display::create_surfaces`] and [`Display::create_context`], respectively.
69 /// Although libva offers several ways to create a display, this struct currently only supports
70 /// opening through DRM. It may be extended to support other display types (X11, Wayland) in the
73 /// Handle to interact with the underlying `VADisplay`.
74 handle: bindings::VADisplay,
75 /// DRM file that must be kept open while the display is in use.
81 /// Opens and initializes a specific DRM `Display`.
83 /// `path` is the path to a DRM device that supports VAAPI, e.g. `/dev/dri/renderD128`.
84 pub fn open_drm_display<P: AsRef<Path>>(path: P) -> VAResult<Rc<Self>> {
85 Self::open_drm_display_internal(path, false)
87 fn open_drm_display_internal<P: AsRef<Path>>(path: P, silent: bool) -> VAResult<Rc<Self>> {
88 let file = std::fs::File::options()
92 .map_err(|_| VAError::InvalidValue)?;
94 // Safe because fd represents a valid file descriptor and the pointer is checked for
96 let display = unsafe { bindings::vaGetDisplayDRM(file.as_raw_fd()) };
97 if display.is_null() {
98 // The File will close the DRM fd on drop.
99 return Err(VAError::InvalidDisplay);
103 // Safe because we ensure that the display is valid (i.e not NULL) before call.
105 bindings::vaSetInfoCallback(display, Some(null_msg_cb), std::ptr::null_mut());
109 let mut major = 0i32;
110 let mut minor = 0i32;
111 // Safe because we ensure that the display is valid (i.e not NULL) before calling
112 // vaInitialize. The File will close the DRM fd on drop.
113 (unsafe { bindings::vaInitialize(display, &mut major, &mut minor) }).check()?;
116 // Safe because we ensure that the display is valid (i.e not NULL) before call.
118 bindings::vaSetInfoCallback(display, None, std::ptr::null_mut());
128 /// Opens the first device that succeeds and returns its `Display`.
130 /// If an error occurs on a given device, it is ignored and the next one is tried until one
131 /// succeeds or we reach the end of the iterator.
132 pub fn open() -> Option<Rc<Self>> {
133 let devices = DrmDeviceIterator::default();
135 // Try all the DRM devices until one succeeds.
136 for device in devices {
137 if let Ok(display) = Self::open_drm_display(device) {
138 return Some(display);
145 /// Opens the first device that succeeds and returns its `Display`.
147 /// The only difference from ordinary `open` is that it does not print debug information
148 /// about libva version and opened driver.
150 /// If an error occurs on a given device, it is ignored and the next one is tried until one
151 /// succeeds or we reach the end of the iterator.
152 pub fn open_silently() -> Option<Rc<Self>> {
153 let devices = DrmDeviceIterator::default();
155 // Try all the DRM devices until one succeeds.
156 for device in devices {
157 if let Ok(display) = Self::open_drm_display_internal(device, true) {
158 return Some(display);
165 /// Returns the handle of this display.
166 pub(crate) fn handle(&self) -> bindings::VADisplay {
170 /// Queries supported profiles by this display.
171 pub fn query_config_profiles(&self) -> VAResult<Vec<bindings::VAProfile::Type>> {
172 // Safe because `self` represents a valid VADisplay.
173 let mut max_num_profiles = unsafe { bindings::vaMaxNumProfiles(self.handle) };
174 let mut profiles = Vec::with_capacity(max_num_profiles as usize);
176 // Safe because `self` represents a valid `VADisplay` and the vector has `max_num_profiles`
179 bindings::vaQueryConfigProfiles(
181 profiles.as_mut_ptr(),
182 &mut max_num_profiles,
187 // Safe because `profiles` is allocated with a `max_num_profiles` capacity and
188 // `vaQueryConfigProfiles` wrote the actual number of profiles to `max_num_entrypoints`.
190 profiles.set_len(max_num_profiles as usize);
196 /// Returns a string describing some aspects of the VA implemenation on the specific hardware
197 /// accelerator used by this display.
199 /// The format of the returned string is vendor specific and at the discretion of the
200 /// implementer. e.g. for the Intel GMA500 implementation, an example would be: `Intel GMA500 -
202 pub fn query_vendor_string(&self) -> std::result::Result<String, &'static str> {
203 // Safe because `self` represents a valid VADisplay.
204 let vendor_string = unsafe { bindings::vaQueryVendorString(self.handle) };
206 if vendor_string.is_null() {
207 return Err("vaQueryVendorString() returned NULL");
210 // Safe because we check the whether the vendor_String pointer is NULL
211 Ok(unsafe { CStr::from_ptr(vendor_string) }
216 /// Query supported entrypoints for a given profile.
217 pub fn query_config_entrypoints(
219 profile: bindings::VAProfile::Type,
220 ) -> VAResult<Vec<bindings::VAEntrypoint::Type>> {
221 // Safe because `self` represents a valid VADisplay.
222 let mut max_num_entrypoints = unsafe { bindings::vaMaxNumEntrypoints(self.handle) };
223 let mut entrypoints = Vec::with_capacity(max_num_entrypoints as usize);
225 // Safe because `self` represents a valid VADisplay and the vector has `max_num_entrypoints`
228 bindings::vaQueryConfigEntrypoints(
231 entrypoints.as_mut_ptr(),
232 &mut max_num_entrypoints,
237 // Safe because `entrypoints` is allocated with a `max_num_entrypoints` capacity, and
238 // `vaQueryConfigEntrypoints` wrote the actual number of entrypoints to
239 // `max_num_entrypoints`
241 entrypoints.set_len(max_num_entrypoints as usize);
247 /// Writes attributes for a given `profile`/`entrypoint` pair into `attributes`.
249 /// Entries of `attributes` must have their `type_` member initialized to the desired attribute
251 pub fn get_config_attributes(
253 profile: bindings::VAProfile::Type,
254 entrypoint: bindings::VAEntrypoint::Type,
255 attributes: &mut [bindings::VAConfigAttrib],
257 // Safe because `self` represents a valid VADisplay. The slice length is passed to the C
258 // function, so it is impossible to write past the end of the slice's storage by mistake.
260 bindings::vaGetConfigAttributes(
264 attributes.as_mut_ptr(),
265 attributes.len() as i32,
271 /// Creates `Surface`s by wrapping around a `vaCreateSurfaces` call.
275 /// * `rt_format` - The desired surface format.
276 /// * `va_fourcc` - The desired pixel format (optional). See `VA_FOURCC_*`
277 /// * `width` - Width for the create surfaces
278 /// * `height` - Height for the created surfaces
279 /// * `usage_hint` - Optional hint of intended usage to optimize allocation (e.g. tiling)
280 /// * `num_surfaces` - Number of surfaces to create
281 pub fn create_surfaces(
284 va_fourcc: Option<VAFourcc>,
287 usage_hints: Option<UsageHints>,
289 ) -> VAResult<Vec<Surface>> {
301 /// Creates a `Context` by wrapping around a `vaCreateContext` call.
305 /// * `config` - The configuration for the context
306 /// * `coded_width` - The coded picture width
307 /// * `coded_height` - The coded picture height
308 /// * `surfaces` - Optional hint for the amount of surfaces tied to the context
309 /// * `progressive` - Whether only progressive frame pictures are present in the sequence
310 pub fn create_context(
315 surfaces: Option<&Vec<Surface>>,
317 ) -> VAResult<Rc<Context>> {
328 /// Creates a `Config` by wrapping around the `vaCreateConfig` call.
330 /// `attrs` describe the attributes to set for this config. A list of the supported attributes
331 /// for a given profile/entrypoint pair can be retrieved using
332 /// [`Display::get_config_attributes`]. Other attributes will take their default values, and
333 /// `attrs` can be empty in order to obtain a default configuration.
334 pub fn create_config(
336 attrs: Vec<bindings::VAConfigAttrib>,
337 profile: bindings::VAProfile::Type,
338 entrypoint: bindings::VAEntrypoint::Type,
339 ) -> VAResult<Config> {
340 Config::new(Rc::clone(self), attrs, profile, entrypoint)
343 /// Returns available image formats for this display by wrapping around `vaQueryImageFormats`.
344 pub fn query_image_formats(&self) -> VAResult<Vec<bindings::VAImageFormat>> {
345 // Safe because `self` represents a valid VADisplay.
346 let mut num_image_formats = unsafe { bindings::vaMaxNumImageFormats(self.handle) };
347 let mut image_formats = Vec::with_capacity(num_image_formats as usize);
349 // Safe because `self` represents a valid VADisplay. The `image_formats` vector is properly
350 // initialized and a valid size is passed to the C function, so it is impossible to write
351 // past the end of their storage by mistake.
353 bindings::vaQueryImageFormats(
355 image_formats.as_mut_ptr(),
356 &mut num_image_formats,
361 // Safe because the C function will have written exactly `num_image_format` entries, which
362 // is known to be within the vector's capacity.
364 image_formats.set_len(num_image_formats as usize);
371 impl Drop for Display {
373 // Safe because `self` represents a valid VADisplay.
375 bindings::vaTerminate(self.handle);
376 // The File will close the DRM fd on drop.