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 anyhow::Context as AnyhowContext;
17 use crate::config::Config;
18 use crate::context::Context;
19 use crate::status::Status;
20 use crate::surface::Surface;
23 /// Iterates over existing DRM devices.
25 /// DRM devices can be passed to [`Display::open_drm_display`] in order to create a `Display` on
27 pub struct DrmDeviceIterator {
31 const DRM_NODE_DEFAULT_PREFIX: &str = "/dev/dri/renderD";
32 const DRM_NUM_NODES: usize = 64;
33 const DRM_RENDER_NODE_START: usize = 128;
35 impl Default for DrmDeviceIterator {
36 fn default() -> Self {
38 cur_idx: DRM_RENDER_NODE_START,
43 impl Iterator for DrmDeviceIterator {
46 fn next(&mut self) -> Option<Self::Item> {
48 idx if idx >= DRM_RENDER_NODE_START + DRM_NUM_NODES => None,
50 let path = PathBuf::from(format!("{}{}", DRM_NODE_DEFAULT_PREFIX, idx));
62 /// A VADisplay opened over DRM.
64 /// A Display is the starting point to using libva. This struct is essentially a safe wrapper over
65 /// `VADisplay`, from which [`Surface`]s and [`Context`]s can be allocated in order to perform
66 /// actual work using [`Display::create_surfaces`] and [`Display::create_context`], respectively.
68 /// Although libva offers several ways to create a display, this struct currently only supports
69 /// opening through DRM. It may be extended to support other display types (X11, Wayland) in the
72 /// Handle to interact with the underlying `VADisplay`.
73 handle: bindings::VADisplay,
74 /// DRM file that must be kept open while the display is in use.
80 /// Opens and initializes a specific DRM `Display`.
82 /// `path` is the path to a DRM device that supports VAAPI, e.g. `/dev/dri/renderD128`.
83 pub fn open_drm_display<P: AsRef<Path>>(path: P) -> Result<Rc<Self>> {
84 let file = std::fs::File::options()
88 .context(format!("failed to open {}", path.as_ref().display()))?;
90 // Safe because fd represents a valid file descriptor and the pointer is checked for
92 let display = unsafe { bindings::vaGetDisplayDRM(file.as_raw_fd()) };
93 if display.is_null() {
94 // The File will close the DRM fd on drop.
96 "failed to obtain VA display from DRM device {}",
97 path.as_ref().display()
101 let mut major = 0i32;
102 let mut minor = 0i32;
103 // Safe because we ensure that the display is valid (i.e not NULL) before calling
104 // vaInitialize. The File will close the DRM fd on drop.
105 Status(unsafe { bindings::vaInitialize(display, &mut major, &mut minor) }).check()?;
113 /// Opens the first device that succeeds and returns its `Display`.
115 /// If an error occurs on a given device, it is ignored and the next one is tried until one
116 /// succeeds or we reach the end of the iterator.
117 pub fn open() -> Option<Rc<Self>> {
118 let devices = DrmDeviceIterator::default();
120 // Try all the DRM devices until one succeeds.
121 for device in devices {
122 if let Ok(display) = Self::open_drm_display(device) {
123 return Some(display);
130 /// Returns the handle of this display.
131 pub(crate) fn handle(&self) -> bindings::VADisplay {
135 /// Queries supported profiles by this display.
136 pub fn query_config_profiles(&self) -> Result<Vec<bindings::VAProfile::Type>> {
137 // Safe because `self` represents a valid VADisplay.
138 let mut max_num_profiles = unsafe { bindings::vaMaxNumProfiles(self.handle) };
139 let mut profiles = Vec::with_capacity(max_num_profiles as usize);
141 // Safe because `self` represents a valid `VADisplay` and the vector has `max_num_profiles`
144 bindings::vaQueryConfigProfiles(
146 profiles.as_mut_ptr(),
147 &mut max_num_profiles,
152 // Safe because `profiles` is allocated with a `max_num_profiles` capacity and
153 // `vaQueryConfigProfiles` wrote the actual number of profiles to `max_num_entrypoints`.
155 profiles.set_len(max_num_profiles as usize);
161 /// Returns a string describing some aspects of the VA implemenation on the specific hardware
162 /// accelerator used by this display.
164 /// The format of the returned string is vendor specific and at the discretion of the
165 /// implementer. e.g. for the Intel GMA500 implementation, an example would be: `Intel GMA500 -
167 pub fn query_vendor_string(&self) -> std::result::Result<String, &'static str> {
168 // Safe because `self` represents a valid VADisplay.
169 let vendor_string = unsafe { bindings::vaQueryVendorString(self.handle) };
171 if vendor_string.is_null() {
172 return Err("vaQueryVendorString() returned NULL");
175 // Safe because we check the whether the vendor_String pointer is NULL
176 Ok(unsafe { CStr::from_ptr(vendor_string) }
181 /// Query supported entrypoints for a given profile.
182 pub fn query_config_entrypoints(
184 profile: bindings::VAProfile::Type,
185 ) -> Result<Vec<bindings::VAEntrypoint::Type>> {
186 // Safe because `self` represents a valid VADisplay.
187 let mut max_num_entrypoints = unsafe { bindings::vaMaxNumEntrypoints(self.handle) };
188 let mut entrypoints = Vec::with_capacity(max_num_entrypoints as usize);
190 // Safe because `self` represents a valid VADisplay and the vector has `max_num_entrypoints`
193 bindings::vaQueryConfigEntrypoints(
196 entrypoints.as_mut_ptr(),
197 &mut max_num_entrypoints,
202 // Safe because `entrypoints` is allocated with a `max_num_entrypoints` capacity, and
203 // `vaQueryConfigEntrypoints` wrote the actual number of entrypoints to
204 // `max_num_entrypoints`
206 entrypoints.set_len(max_num_entrypoints as usize);
212 /// Writes attributes for a given `profile`/`entrypoint` pair into `attributes`.
214 /// Entries of `attributes` must have their `type_` member initialized to the desired attribute
216 pub fn get_config_attributes(
218 profile: bindings::VAProfile::Type,
219 entrypoint: bindings::VAEntrypoint::Type,
220 attributes: &mut [bindings::VAConfigAttrib],
222 // Safe because `self` represents a valid VADisplay. The slice length is passed to the C
223 // function, so it is impossible to write past the end of the slice's storage by mistake.
225 bindings::vaGetConfigAttributes(
229 attributes.as_mut_ptr(),
230 attributes.len() as i32,
236 /// Creates `Surface`s by wrapping around a `vaCreateSurfaces` call.
240 /// * `rt_format` - The desired surface format. See `VA_RT_FORMAT_*`
241 /// * `va_fourcc` - The desired pixel format (optional). See `VA_FOURCC_*`
242 /// * `width` - Width for the create surfaces
243 /// * `height` - Height for the created surfaces
244 /// * `usage_hint` - Optional hint of intended usage to optimize allocation (e.g. tiling)
245 /// * `num_surfaces` - Number of surfaces to create
246 pub fn create_surfaces(
249 va_fourcc: Option<u32>,
252 usage_hint: Option<UsageHint>,
254 ) -> Result<Vec<Surface>> {
266 /// Creates a `Context` by wrapping around a `vaCreateContext` call.
270 /// * `config` - The configuration for the context
271 /// * `coded_width` - The coded picture width
272 /// * `coded_height` - The coded picture height
273 /// * `surfaces` - Optional hint for the amount of surfaces tied to the context
274 /// * `progressive` - Whether only progressive frame pictures are present in the sequence
275 pub fn create_context(
280 surfaces: Option<&Vec<Surface>>,
282 ) -> Result<Rc<Context>> {
293 /// Creates a `Config` by wrapping around the `vaCreateConfig` call.
295 /// `attrs` describe the attributes to set for this config. A list of the supported attributes
296 /// for a given profile/entrypoint pair can be retrieved using
297 /// [`Display::get_config_attributes`]. Other attributes will take their default values, and
298 /// `attrs` can be empty in order to obtain a default configuration.
299 pub fn create_config(
301 attrs: Vec<bindings::VAConfigAttrib>,
302 profile: bindings::VAProfile::Type,
303 entrypoint: bindings::VAEntrypoint::Type,
304 ) -> Result<Config> {
305 Config::new(Rc::clone(self), attrs, profile, entrypoint)
308 /// Returns available image formats for this display by wrapping around `vaQueryImageFormats`.
309 pub fn query_image_formats(&self) -> Result<Vec<bindings::VAImageFormat>> {
310 // Safe because `self` represents a valid VADisplay.
311 let mut num_image_formats = unsafe { bindings::vaMaxNumImageFormats(self.handle) };
312 let mut image_formats = Vec::with_capacity(num_image_formats as usize);
314 // Safe because `self` represents a valid VADisplay. The `image_formats` vector is properly
315 // initialized and a valid size is passed to the C function, so it is impossible to write
316 // past the end of their storage by mistake.
318 bindings::vaQueryImageFormats(
320 image_formats.as_mut_ptr(),
321 &mut num_image_formats,
326 // Safe because the C function will have written exactly `num_image_format` entries, which
327 // is known to be within the vector's capacity.
329 image_formats.set_len(num_image_formats as usize);
336 impl Drop for Display {
338 // Safe because `self` represents a valid VADisplay.
340 bindings::vaTerminate(self.handle);
341 // The File will close the DRM fd on drop.