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;
16 use crate::surface::Surface;
19 /// Iterates over existing DRM devices.
21 /// DRM devices can be passed to [`Display::open_drm_display`] in order to create a `Display` on
23 pub struct DrmDeviceIterator {
27 const DRM_NODE_DEFAULT_PREFIX: &str = "/dev/dri/renderD";
28 const DRM_NUM_NODES: usize = 64;
29 const DRM_RENDER_NODE_START: usize = 128;
31 impl Default for DrmDeviceIterator {
32 fn default() -> Self {
34 cur_idx: DRM_RENDER_NODE_START,
39 impl Iterator for DrmDeviceIterator {
42 fn next(&mut self) -> Option<Self::Item> {
44 idx if idx >= DRM_RENDER_NODE_START + DRM_NUM_NODES => None,
46 let path = PathBuf::from(format!("{}{}", DRM_NODE_DEFAULT_PREFIX, idx));
58 /// A VADisplay opened over DRM.
60 /// A Display is the starting point to using libva. This struct is essentially a safe wrapper over
61 /// `VADisplay`, from which [`Surface`]s and [`Context`]s can be allocated in order to perform
62 /// actual work using [`Display::create_surfaces`] and [`Display::create_context`], respectively.
64 /// Although libva offers several ways to create a display, this struct currently only supports
65 /// opening through DRM. It may be extended to support other display types (X11, Wayland) in the
68 /// Handle to interact with the underlying `VADisplay`.
69 handle: bindings::VADisplay,
70 /// DRM file that must be kept open while the display is in use.
76 /// Opens and initializes a specific DRM `Display`.
78 /// `path` is the path to a DRM device that supports VAAPI, e.g. `/dev/dri/renderD128`.
79 pub fn open_drm_display<P: AsRef<Path>>(path: P) -> VAResult<Rc<Self>> {
80 let file = std::fs::File::options()
84 .map_err(|_| VAError::InvalidValue)?;
86 // Safe because fd represents a valid file descriptor and the pointer is checked for
88 let display = unsafe { bindings::vaGetDisplayDRM(file.as_raw_fd()) };
89 if display.is_null() {
90 // The File will close the DRM fd on drop.
91 return Err(VAError::InvalidDisplay);
96 // Safe because we ensure that the display is valid (i.e not NULL) before calling
97 // vaInitialize. The File will close the DRM fd on drop.
98 (unsafe { bindings::vaInitialize(display, &mut major, &mut minor) }).check()?;
106 /// Opens the first device that succeeds and returns its `Display`.
108 /// If an error occurs on a given device, it is ignored and the next one is tried until one
109 /// succeeds or we reach the end of the iterator.
110 pub fn open() -> Option<Rc<Self>> {
111 let devices = DrmDeviceIterator::default();
113 // Try all the DRM devices until one succeeds.
114 for device in devices {
115 if let Ok(display) = Self::open_drm_display(device) {
116 return Some(display);
123 /// Returns the handle of this display.
124 pub(crate) fn handle(&self) -> bindings::VADisplay {
128 /// Queries supported profiles by this display.
129 pub fn query_config_profiles(&self) -> VAResult<Vec<bindings::VAProfile::Type>> {
130 // Safe because `self` represents a valid VADisplay.
131 let mut max_num_profiles = unsafe { bindings::vaMaxNumProfiles(self.handle) };
132 let mut profiles = Vec::with_capacity(max_num_profiles as usize);
134 // Safe because `self` represents a valid `VADisplay` and the vector has `max_num_profiles`
137 bindings::vaQueryConfigProfiles(
139 profiles.as_mut_ptr(),
140 &mut max_num_profiles,
145 // Safe because `profiles` is allocated with a `max_num_profiles` capacity and
146 // `vaQueryConfigProfiles` wrote the actual number of profiles to `max_num_entrypoints`.
148 profiles.set_len(max_num_profiles as usize);
154 /// Returns a string describing some aspects of the VA implemenation on the specific hardware
155 /// accelerator used by this display.
157 /// The format of the returned string is vendor specific and at the discretion of the
158 /// implementer. e.g. for the Intel GMA500 implementation, an example would be: `Intel GMA500 -
160 pub fn query_vendor_string(&self) -> std::result::Result<String, &'static str> {
161 // Safe because `self` represents a valid VADisplay.
162 let vendor_string = unsafe { bindings::vaQueryVendorString(self.handle) };
164 if vendor_string.is_null() {
165 return Err("vaQueryVendorString() returned NULL");
168 // Safe because we check the whether the vendor_String pointer is NULL
169 Ok(unsafe { CStr::from_ptr(vendor_string) }
174 /// Query supported entrypoints for a given profile.
175 pub fn query_config_entrypoints(
177 profile: bindings::VAProfile::Type,
178 ) -> VAResult<Vec<bindings::VAEntrypoint::Type>> {
179 // Safe because `self` represents a valid VADisplay.
180 let mut max_num_entrypoints = unsafe { bindings::vaMaxNumEntrypoints(self.handle) };
181 let mut entrypoints = Vec::with_capacity(max_num_entrypoints as usize);
183 // Safe because `self` represents a valid VADisplay and the vector has `max_num_entrypoints`
186 bindings::vaQueryConfigEntrypoints(
189 entrypoints.as_mut_ptr(),
190 &mut max_num_entrypoints,
195 // Safe because `entrypoints` is allocated with a `max_num_entrypoints` capacity, and
196 // `vaQueryConfigEntrypoints` wrote the actual number of entrypoints to
197 // `max_num_entrypoints`
199 entrypoints.set_len(max_num_entrypoints as usize);
205 /// Writes attributes for a given `profile`/`entrypoint` pair into `attributes`.
207 /// Entries of `attributes` must have their `type_` member initialized to the desired attribute
209 pub fn get_config_attributes(
211 profile: bindings::VAProfile::Type,
212 entrypoint: bindings::VAEntrypoint::Type,
213 attributes: &mut [bindings::VAConfigAttrib],
215 // Safe because `self` represents a valid VADisplay. The slice length is passed to the C
216 // function, so it is impossible to write past the end of the slice's storage by mistake.
218 bindings::vaGetConfigAttributes(
222 attributes.as_mut_ptr(),
223 attributes.len() as i32,
229 /// Creates `Surface`s by wrapping around a `vaCreateSurfaces` call.
233 /// * `rt_format` - The desired surface format. See `VA_RT_FORMAT_*`
234 /// * `va_fourcc` - The desired pixel format (optional). See `VA_FOURCC_*`
235 /// * `width` - Width for the create surfaces
236 /// * `height` - Height for the created surfaces
237 /// * `usage_hint` - Optional hint of intended usage to optimize allocation (e.g. tiling)
238 /// * `num_surfaces` - Number of surfaces to create
239 pub fn create_surfaces(
242 va_fourcc: Option<u32>,
245 usage_hint: Option<UsageHint>,
247 ) -> VAResult<Vec<Surface>> {
259 /// Creates a `Context` by wrapping around a `vaCreateContext` call.
263 /// * `config` - The configuration for the context
264 /// * `coded_width` - The coded picture width
265 /// * `coded_height` - The coded picture height
266 /// * `surfaces` - Optional hint for the amount of surfaces tied to the context
267 /// * `progressive` - Whether only progressive frame pictures are present in the sequence
268 pub fn create_context(
273 surfaces: Option<&Vec<Surface>>,
275 ) -> VAResult<Rc<Context>> {
286 /// Creates a `Config` by wrapping around the `vaCreateConfig` call.
288 /// `attrs` describe the attributes to set for this config. A list of the supported attributes
289 /// for a given profile/entrypoint pair can be retrieved using
290 /// [`Display::get_config_attributes`]. Other attributes will take their default values, and
291 /// `attrs` can be empty in order to obtain a default configuration.
292 pub fn create_config(
294 attrs: Vec<bindings::VAConfigAttrib>,
295 profile: bindings::VAProfile::Type,
296 entrypoint: bindings::VAEntrypoint::Type,
297 ) -> VAResult<Config> {
298 Config::new(Rc::clone(self), attrs, profile, entrypoint)
301 /// Returns available image formats for this display by wrapping around `vaQueryImageFormats`.
302 pub fn query_image_formats(&self) -> VAResult<Vec<bindings::VAImageFormat>> {
303 // Safe because `self` represents a valid VADisplay.
304 let mut num_image_formats = unsafe { bindings::vaMaxNumImageFormats(self.handle) };
305 let mut image_formats = Vec::with_capacity(num_image_formats as usize);
307 // Safe because `self` represents a valid VADisplay. The `image_formats` vector is properly
308 // initialized and a valid size is passed to the C function, so it is impossible to write
309 // past the end of their storage by mistake.
311 bindings::vaQueryImageFormats(
313 image_formats.as_mut_ptr(),
314 &mut num_image_formats,
319 // Safe because the C function will have written exactly `num_image_format` entries, which
320 // is known to be within the vector's capacity.
322 image_formats.set_len(num_image_formats as usize);
329 impl Drop for Display {
331 // Safe because `self` represents a valid VADisplay.
333 bindings::vaTerminate(self.handle);
334 // The File will close the DRM fd on drop.