Skip to main content

kodecs_vaapi/
display.rs

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.
4
5use 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
26/// Iterates over existing DRM devices.
27///
28/// DRM devices can be passed to [`Display::open_drm_display`] in order to create a `Display` on
29/// that device.
30pub 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		// Skips a missing node rather than stopping at it: numbering follows the
51		// order devices probed in, and a device that has been unbound leaves a gap.
52		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
63/// Opens the first render node whose driver passes `probe`, returning the node with its display.
64///
65/// A machine with more than one GPU numbers its render nodes in probe order,
66/// so the one a caller needs is not reliably `renderD128`: on a laptop with an
67/// NVIDIA and an Intel GPU, either can come first, and only one may offer the
68/// entrypoint the caller wants.
69///
70/// # Errors
71///
72/// Fails when no node passes, naming each node tried and why it was passed over.
73pub(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
90/// A VADisplay opened over DRM.
91///
92/// A Display is the starting point to using libva. This struct is essentially a safe wrapper over
93/// `VADisplay`, from which [`Surface`]s can be allocated with [`Display::create_surfaces`].
94///
95/// Although libva offers several ways to create a display, this struct currently only supports
96/// opening through DRM. It may be extended to support other display types (X11, Wayland) in the
97/// future.
98pub struct Display {
99	/// Handle to interact with the underlying `VADisplay`.
100	handle: bindings::VADisplay,
101	/// DRM file that must be kept open while the display is in use.
102	drm_file: File,
103}
104
105/// Error type for `Display::open_drm_display`.
106#[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	/// Opens and initializes a specific DRM `Display`.
120	///
121	/// `path` is the path to a DRM device that supports VAAPI, e.g. `/dev/dri/renderD128`.
122	pub fn open_drm_display<P: AsRef<Path>>(path: P) -> Result<Arc<Self>, OpenDrmDisplayError> {
123		// dlopen libva up front so a libva-less host fails here (and the caller
124		// falls back) instead of panicking on the first va* call below.
125		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		// Safe because fd represents a valid file descriptor and the pointer is checked for
134		// NULL afterwards.
135		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		// Safe because we ensure that the display is valid (i.e not NULL) before calling
143		// vaInitialize. The File will close the DRM fd on drop.
144		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	/// Opens the first device that succeeds and returns its `Display`.
155	///
156	/// If an error occurs on a given device, it is ignored and the next one is tried until one
157	/// succeeds or we reach the end of the iterator.
158	pub fn open() -> Option<Arc<Self>> {
159		let devices = DrmDeviceIterator::default();
160
161		// Try all the DRM devices until one succeeds.
162		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	/// Returns the handle of this display.
172	pub(crate) fn handle(&self) -> bindings::VADisplay {
173		self.handle
174	}
175
176	/// Queries supported profiles by this display by wrapping `vaQueryConfigProfiles`.
177	pub fn query_config_profiles(&self) -> Result<Vec<bindings::VAProfile::Type>, VaError> {
178		// Safe because `self` represents a valid VADisplay.
179		let max = unsafe { bindings::va().vaMaxNumProfiles(self.handle) };
180		// Safe because `self` represents a valid `VADisplay` and `query` passes a buffer of `max`.
181		query(max, |profiles, num| unsafe {
182			bindings::va().vaQueryConfigProfiles(self.handle, profiles, num)
183		})
184	}
185
186	/// Returns a string describing some aspects of the VA implemenation on the specific hardware
187	/// accelerator used by this display. Wrapper over `vaQueryVendorString`.
188	///
189	/// The format of the returned string is vendor specific and at the discretion of the
190	/// implementer. e.g. for the Intel GMA500 implementation, an example would be: `Intel GMA500 -
191	/// 2.0.0.32L.0005`.
192	pub fn query_vendor_string(&self) -> std::result::Result<String, &'static str> {
193		// Safe because `self` represents a valid VADisplay.
194		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		// Safe because we check the whether the vendor_String pointer is NULL
201		Ok(unsafe { CStr::from_ptr(vendor_string) }.to_string_lossy().to_string())
202	}
203
204	/// Query supported entrypoints for a given profile by wrapping `vaQueryConfigEntrypoints`.
205	pub fn query_config_entrypoints(
206		&self,
207		profile: bindings::VAProfile::Type,
208	) -> Result<Vec<bindings::VAEntrypoint::Type>, VaError> {
209		// Safe because `self` represents a valid VADisplay.
210		let max = unsafe { bindings::va().vaMaxNumEntrypoints(self.handle) };
211		// Safe because `self` represents a valid VADisplay and `query` passes a buffer of `max`.
212		query(max, |entrypoints, num| unsafe {
213			bindings::va().vaQueryConfigEntrypoints(self.handle, profile, entrypoints, num)
214		})
215	}
216
217	/// Writes attributes for a given `profile`/`entrypoint` pair into `attributes`. Wrapper over
218	/// `vaGetConfigAttributes`.
219	///
220	/// Entries of `attributes` must have their `type_` member initialized to the desired attribute
221	/// to retrieve.
222	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		// Safe because `self` represents a valid VADisplay. The slice length is passed to the C
229		// function, so it is impossible to write past the end of the slice's storage by mistake.
230		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	/// Creates `Surface`s by wrapping around a `vaCreateSurfaces` call.
242	///
243	/// The number of surfaces created will be equal to the length of `descriptors`.
244	///
245	/// # Arguments
246	///
247	/// * `rt_format` - The desired surface format. See `VA_RT_FORMAT_*`
248	/// * `va_fourcc` - The desired pixel format (optional). See `VA_FOURCC_*`
249	/// * `width` - Width for the create surfaces
250	/// * `height` - Height for the created surfaces
251	/// * `usage_hint` - Optional hint of intended usage to optimize allocation (e.g. tiling)
252	/// * `num_surfaces` - Number of surfaces to create
253	/// * `descriptors` - Memory descriptors used as surface memory backing.
254	///
255	/// # Return value
256	///
257	/// Returns as many surfaces as the length of `descriptors`.
258	///
259	/// Note that the `descriptors`'s ownership is irrevocably given to the surfaces, and that in
260	/// case of error the `descriptors` will be destroyed. Make sure to duplicate the descriptors
261	/// if you need something outside of libva to access them.
262	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	/// Creates a `Context` by wrapping around a `vaCreateContext` call.
283	///
284	/// # Arguments
285	///
286	/// * `config` - The configuration for the context
287	/// * `coded_width` - The coded picture width
288	/// * `coded_height` - The coded picture height
289	/// * `surfaces` - Optional hint for the amount of surfaces tied to the context
290	/// * `progressive` - Whether only progressive frame pictures are present in the sequence
291	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	/// Creates a `Config` by wrapping around the `vaCreateConfig` call.
310	///
311	/// `attrs` describe the attributes to set for this config. A list of the supported attributes
312	/// for a given profile/entrypoint pair can be retrieved using
313	/// [`Display::get_config_attributes`]. Other attributes will take their default values, and
314	/// `attrs` can be empty in order to obtain a default configuration.
315	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	/// Returns available image formats for this display by wrapping around `vaQueryImageFormats`.
325	pub fn query_image_formats(&self) -> Result<Vec<bindings::VAImageFormat>, VaError> {
326		// Safe because `self` represents a valid VADisplay.
327		let max = unsafe { bindings::va().vaMaxNumImageFormats(self.handle) };
328		// Safe because `self` represents a valid VADisplay and `query` passes a buffer of `max`.
329		query(max, |formats, num| unsafe {
330			bindings::va().vaQueryImageFormats(self.handle, formats, num)
331		})
332	}
333}
334
335/// Runs a libva `query` that fills a buffer of `max` entries and writes how many it filled,
336/// failing when libva reports a negative maximum or more entries than fit.
337fn 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	// Safe because libva wrote `len` entries, which fit the `capacity` allocated above.
348	unsafe { list.set_len(len) };
349	Ok(list)
350}
351
352impl Drop for Display {
353	fn drop(&mut self) {
354		// Safe because `self` represents a valid VADisplay.
355		unsafe {
356			bindings::va().vaTerminate(self.handle);
357			// The File will close the DRM fd on drop.
358		}
359	}
360}
361
362// Safe because because it only contains a `File` (which is Send+Sync), and a VADisplay handle
363// which is also thread-safe. The Drop handler can also be safely called from any thread.
364unsafe impl Send for Display {}
365unsafe impl Sync for Display {}