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(
74	probe: impl Fn(&Arc<Display>) -> anyhow::Result<()>,
75) -> anyhow::Result<(PathBuf, Arc<Display>)> {
76	let mut refused = Vec::new();
77	for node in DrmDeviceIterator::default() {
78		let opened = Display::open_drm_display(&node)
79			.map_err(anyhow::Error::from)
80			.and_then(|display| probe(&display).map(|()| display));
81		match opened {
82			Ok(display) => return Ok((node, display)),
83			Err(err) => refused.push(format!("{}: {err:#}", node.display())),
84		}
85	}
86	match refused.is_empty() {
87		true => anyhow::bail!("no DRM render node under {DRM_NODE_DEFAULT_PREFIX}*"),
88		false => anyhow::bail!("no DRM render node qualifies ({})", refused.join("; ")),
89	}
90}
91
92/// A VADisplay opened over DRM.
93///
94/// A Display is the starting point to using libva. This struct is essentially a safe wrapper over
95/// `VADisplay`, from which [`Surface`]s can be allocated with [`Display::create_surfaces`].
96///
97/// Although libva offers several ways to create a display, this struct currently only supports
98/// opening through DRM. It may be extended to support other display types (X11, Wayland) in the
99/// future.
100pub struct Display {
101	/// Handle to interact with the underlying `VADisplay`.
102	handle: bindings::VADisplay,
103	/// DRM file that must be kept open while the display is in use.
104	drm_file: File,
105}
106
107/// Error type for `Display::open_drm_display`.
108#[derive(Debug, Error)]
109pub enum OpenDrmDisplayError {
110	#[error("libva could not be loaded: {0}")]
111	LibvaUnavailable(&'static str),
112	#[error("cannot open DRM device: {0}")]
113	DeviceOpen(io::Error),
114	#[error("vaGetDisplayDRM returned NULL")]
115	VaGetDisplayDrm,
116	#[error("call to vaInitialize failed: {0}")]
117	VaInitialize(VaError),
118}
119
120impl Display {
121	/// Opens and initializes a specific DRM `Display`.
122	///
123	/// `path` is the path to a DRM device that supports VAAPI, e.g. `/dev/dri/renderD128`.
124	pub fn open_drm_display<P: AsRef<Path>>(path: P) -> Result<Arc<Self>, OpenDrmDisplayError> {
125		// dlopen libva up front so a libva-less host fails here (and the caller
126		// falls back) instead of panicking on the first va* call below.
127		bindings::load().map_err(OpenDrmDisplayError::LibvaUnavailable)?;
128
129		let file = std::fs::File::options()
130			.read(true)
131			.write(true)
132			.open(path.as_ref())
133			.map_err(OpenDrmDisplayError::DeviceOpen)?;
134
135		// Safe because fd represents a valid file descriptor and the pointer is checked for
136		// NULL afterwards.
137		let display = unsafe { bindings::va().vaGetDisplayDRM(file.as_raw_fd()) };
138		if display.is_null() {
139			return Err(OpenDrmDisplayError::VaGetDisplayDrm);
140		}
141
142		let mut major = 0i32;
143		let mut minor = 0i32;
144		// Safe because we ensure that the display is valid (i.e not NULL) before calling
145		// vaInitialize. The File will close the DRM fd on drop.
146		va_check(unsafe { bindings::va().vaInitialize(display, &mut major, &mut minor) })
147			.map(|()| {
148				Arc::new(Self {
149					handle: display,
150					drm_file: file,
151				})
152			})
153			.map_err(OpenDrmDisplayError::VaInitialize)
154	}
155
156	/// Opens the first device that succeeds and returns its `Display`.
157	///
158	/// If an error occurs on a given device, it is ignored and the next one is tried until one
159	/// succeeds or we reach the end of the iterator.
160	pub fn open() -> Option<Arc<Self>> {
161		let devices = DrmDeviceIterator::default();
162
163		// Try all the DRM devices until one succeeds.
164		for device in devices {
165			if let Ok(display) = Self::open_drm_display(device) {
166				return Some(display);
167			}
168		}
169
170		None
171	}
172
173	/// Returns the handle of this display.
174	pub(crate) fn handle(&self) -> bindings::VADisplay {
175		self.handle
176	}
177
178	/// Queries supported profiles by this display by wrapping `vaQueryConfigProfiles`.
179	pub fn query_config_profiles(&self) -> Result<Vec<bindings::VAProfile::Type>, VaError> {
180		// Safe because `self` represents a valid VADisplay.
181		let max = unsafe { bindings::va().vaMaxNumProfiles(self.handle) };
182		// Safe because `self` represents a valid `VADisplay` and `query` passes a buffer of `max`.
183		query(max, |profiles, num| unsafe {
184			bindings::va().vaQueryConfigProfiles(self.handle, profiles, num)
185		})
186	}
187
188	/// Returns a string describing some aspects of the VA implemenation on the specific hardware
189	/// accelerator used by this display. Wrapper over `vaQueryVendorString`.
190	///
191	/// The format of the returned string is vendor specific and at the discretion of the
192	/// implementer. e.g. for the Intel GMA500 implementation, an example would be: `Intel GMA500 -
193	/// 2.0.0.32L.0005`.
194	pub fn query_vendor_string(&self) -> std::result::Result<String, &'static str> {
195		// Safe because `self` represents a valid VADisplay.
196		let vendor_string = unsafe { bindings::va().vaQueryVendorString(self.handle) };
197
198		if vendor_string.is_null() {
199			return Err("vaQueryVendorString() returned NULL");
200		}
201
202		// Safe because we check the whether the vendor_String pointer is NULL
203		Ok(unsafe { CStr::from_ptr(vendor_string) }.to_string_lossy().to_string())
204	}
205
206	/// Query supported entrypoints for a given profile by wrapping `vaQueryConfigEntrypoints`.
207	pub fn query_config_entrypoints(
208		&self,
209		profile: bindings::VAProfile::Type,
210	) -> Result<Vec<bindings::VAEntrypoint::Type>, VaError> {
211		// Safe because `self` represents a valid VADisplay.
212		let max = unsafe { bindings::va().vaMaxNumEntrypoints(self.handle) };
213		// Safe because `self` represents a valid VADisplay and `query` passes a buffer of `max`.
214		query(max, |entrypoints, num| unsafe {
215			bindings::va().vaQueryConfigEntrypoints(self.handle, profile, entrypoints, num)
216		})
217	}
218
219	/// Writes attributes for a given `profile`/`entrypoint` pair into `attributes`. Wrapper over
220	/// `vaGetConfigAttributes`.
221	///
222	/// Entries of `attributes` must have their `type_` member initialized to the desired attribute
223	/// to retrieve.
224	pub(crate) fn get_config_attributes(
225		&self,
226		profile: bindings::VAProfile::Type,
227		entrypoint: bindings::VAEntrypoint::Type,
228		attributes: &mut [bindings::VAConfigAttrib],
229	) -> Result<(), VaError> {
230		// Safe because `self` represents a valid VADisplay. The slice length is passed to the C
231		// function, so it is impossible to write past the end of the slice's storage by mistake.
232		va_check(unsafe {
233			bindings::va().vaGetConfigAttributes(
234				self.handle,
235				profile,
236				entrypoint,
237				attributes.as_mut_ptr(),
238				attributes.len() as i32,
239			)
240		})
241	}
242
243	/// Creates `Surface`s by wrapping around a `vaCreateSurfaces` call.
244	///
245	/// The number of surfaces created will be equal to the length of `descriptors`.
246	///
247	/// # Arguments
248	///
249	/// * `rt_format` - The desired surface format. See `VA_RT_FORMAT_*`
250	/// * `va_fourcc` - The desired pixel format (optional). See `VA_FOURCC_*`
251	/// * `width` - Width for the create surfaces
252	/// * `height` - Height for the created surfaces
253	/// * `usage_hint` - Optional hint of intended usage to optimize allocation (e.g. tiling)
254	/// * `num_surfaces` - Number of surfaces to create
255	/// * `descriptors` - Memory descriptors used as surface memory backing.
256	///
257	/// # Return value
258	///
259	/// Returns as many surfaces as the length of `descriptors`.
260	///
261	/// Note that the `descriptors`'s ownership is irrevocably given to the surfaces, and that in
262	/// case of error the `descriptors` will be destroyed. Make sure to duplicate the descriptors
263	/// if you need something outside of libva to access them.
264	pub fn create_surfaces<D: SurfaceMemoryDescriptor>(
265		self: &Arc<Self>,
266		rt_format: u32,
267		va_fourcc: Option<u32>,
268		width: u32,
269		height: u32,
270		usage_hint: Option<UsageHint>,
271		descriptors: Vec<D>,
272	) -> Result<Vec<Surface<D>>, VaError> {
273		Surface::new(
274			Arc::clone(self),
275			rt_format,
276			va_fourcc,
277			width,
278			height,
279			usage_hint,
280			descriptors,
281		)
282	}
283
284	/// Creates a `Context` by wrapping around a `vaCreateContext` call.
285	///
286	/// # Arguments
287	///
288	/// * `config` - The configuration for the context
289	/// * `coded_width` - The coded picture width
290	/// * `coded_height` - The coded picture height
291	/// * `surfaces` - Optional hint for the amount of surfaces tied to the context
292	/// * `progressive` - Whether only progressive frame pictures are present in the sequence
293	pub(crate) fn create_context<D: SurfaceMemoryDescriptor>(
294		self: &Arc<Self>,
295		config: &Config,
296		coded_width: u32,
297		coded_height: u32,
298		surfaces: Option<&Vec<Surface<D>>>,
299		progressive: bool,
300	) -> Result<Rc<Context>, VaError> {
301		Context::new(
302			Arc::clone(self),
303			config,
304			coded_width,
305			coded_height,
306			surfaces,
307			progressive,
308		)
309	}
310
311	/// Creates a `Config` by wrapping around the `vaCreateConfig` call.
312	///
313	/// `attrs` describe the attributes to set for this config. A list of the supported attributes
314	/// for a given profile/entrypoint pair can be retrieved using
315	/// [`Display::get_config_attributes`]. Other attributes will take their default values, and
316	/// `attrs` can be empty in order to obtain a default configuration.
317	pub(crate) fn create_config(
318		self: &Arc<Self>,
319		attrs: Vec<bindings::VAConfigAttrib>,
320		profile: bindings::VAProfile::Type,
321		entrypoint: bindings::VAEntrypoint::Type,
322	) -> Result<Config, VaError> {
323		Config::new(Arc::clone(self), attrs, profile, entrypoint)
324	}
325
326	/// Returns available image formats for this display by wrapping around `vaQueryImageFormats`.
327	pub fn query_image_formats(&self) -> Result<Vec<bindings::VAImageFormat>, VaError> {
328		// Safe because `self` represents a valid VADisplay.
329		let max = unsafe { bindings::va().vaMaxNumImageFormats(self.handle) };
330		// Safe because `self` represents a valid VADisplay and `query` passes a buffer of `max`.
331		query(max, |formats, num| unsafe {
332			bindings::va().vaQueryImageFormats(self.handle, formats, num)
333		})
334	}
335}
336
337/// Runs a libva `query` that fills a buffer of `max` entries and writes how many it filled,
338/// failing when libva reports a negative maximum or more entries than fit.
339fn query<T>(max: c_int, query: impl FnOnce(*mut T, *mut c_int) -> bindings::VAStatus) -> Result<Vec<T>, VaError> {
340	let invalid = || VaError::status(bindings::VA_STATUS_ERROR_OPERATION_FAILED);
341	let capacity = usize::try_from(max).map_err(|_| invalid())?;
342	let mut list = Vec::with_capacity(capacity);
343	let mut num = max;
344	va_check(query(list.as_mut_ptr(), &mut num))?;
345	let len = usize::try_from(num)
346		.ok()
347		.filter(|&len| len <= capacity)
348		.ok_or_else(invalid)?;
349	// Safe because libva wrote `len` entries, which fit the `capacity` allocated above.
350	unsafe { list.set_len(len) };
351	Ok(list)
352}
353
354impl Drop for Display {
355	fn drop(&mut self) {
356		// Safe because `self` represents a valid VADisplay.
357		unsafe {
358			bindings::va().vaTerminate(self.handle);
359			// The File will close the DRM fd on drop.
360		}
361	}
362}
363
364// Safe because because it only contains a `File` (which is Send+Sync), and a VADisplay handle
365// which is also thread-safe. The Drop handler can also be safely called from any thread.
366unsafe impl Send for Display {}
367unsafe impl Sync for Display {}