Skip to main content

moq_video/
device.rs

1//! Which hardware a codec or scaler opens.
2
3use std::path::{Path, PathBuf};
4
5use crate::Error;
6
7/// The hardware a decoder, encoder, or scaler opens.
8///
9/// Present on every platform and honoured by whichever backend opens. A Linux
10/// hardware backend that drives another kind of device is passed over, so a
11/// named node also steers automatic backend selection; software and a platform
12/// API that picks its own device (VideoToolbox, Media Foundation, MediaCodec)
13/// ignore it. A named device that fails to open is an error rather than a
14/// search for another one: only [`Auto`](Self::Auto) chooses. Whether software
15/// may take over when no hardware opens is the `Backend`'s call, not this.
16#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
17#[non_exhaustive]
18pub enum Device {
19	/// Let each backend pick its device.
20	#[default]
21	Auto,
22	/// A DRM render node, such as `/dev/dri/renderD129`: VA-API opens it, and
23	/// NVENC and NVDEC open the CUDA device behind it when an NVIDIA driver runs it.
24	Render(PathBuf),
25	/// A V4L2 memory-to-memory codec node, such as `/dev/video11`.
26	Video(PathBuf),
27}
28
29impl Device {
30	/// The named render node, if any.
31	#[cfg_attr(
32		not(all(target_os = "linux", any(feature = "vaapi", feature = "nvidia"))),
33		allow(dead_code, reason = "only the VA-API and NVIDIA backends open one")
34	)]
35	pub(crate) fn render(&self) -> Option<&Path> {
36		match self {
37			Self::Render(path) => Some(path),
38			_ => None,
39		}
40	}
41
42	/// The named V4L2 codec node, if any.
43	#[cfg_attr(
44		not(all(target_os = "linux", feature = "v4l2")),
45		allow(dead_code, reason = "only the V4L2 backends open one")
46	)]
47	pub(crate) fn video(&self) -> Option<&Path> {
48		match self {
49			Self::Video(path) => Some(path),
50			_ => None,
51		}
52	}
53
54	/// Whether a backend that drives `drives` opens this device, so selection
55	/// passes over one that would open another.
56	///
57	/// Fails when telling needs the named node's driver and that cannot be read.
58	pub(crate) fn takes(&self, drives: Drives) -> Result<bool, Error> {
59		match (self, drives) {
60			(Self::Auto, _) | (_, Drives::Own) => Ok(true),
61			(Self::Render(_), Drives::Render) | (Self::Video(_), Drives::Video) => Ok(true),
62			(Self::Render(path), Drives::Nvidia) => nvidia(path),
63			_ => Ok(false),
64		}
65	}
66}
67
68impl std::fmt::Display for Device {
69	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70		match self {
71			Self::Auto => f.write_str("any device"),
72			Self::Render(path) => write!(f, "render node {}", path.display()),
73			Self::Video(path) => write!(f, "codec node {}", path.display()),
74		}
75	}
76}
77
78/// The kind of [`Device`] a backend opens.
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80#[allow(dead_code, reason = "a build without a backend of some kind never names that kind")]
81pub(crate) enum Drives {
82	/// None a [`Device`] names: software, or a platform API that picks its own.
83	Own,
84	/// Any DRM render node (VA-API).
85	Render,
86	/// A DRM render node an NVIDIA driver runs (NVENC, NVDEC).
87	Nvidia,
88	/// A V4L2 codec node.
89	Video,
90}
91
92/// Whether the NVIDIA driver runs the render node at `path`.
93#[cfg(target_os = "linux")]
94fn nvidia(path: &Path) -> Result<bool, Error> {
95	Ok(field(&uevent(path)?, "DRIVER") == Some("nvidia"))
96}
97
98#[cfg(not(target_os = "linux"))]
99fn nvidia(_path: &Path) -> Result<bool, Error> {
100	Ok(false)
101}
102
103/// The sysfs `uevent` of the device behind the character node at `path`.
104#[cfg(target_os = "linux")]
105fn uevent(path: &Path) -> Result<String, Error> {
106	use std::os::unix::fs::{FileTypeExt, MetadataExt};
107
108	let failed = |err: &dyn std::fmt::Display| Error::codec(anyhow::anyhow!("{}: {err}", path.display()));
109	let meta = std::fs::metadata(path).map_err(|err| failed(&err))?;
110	if !meta.file_type().is_char_device() {
111		return Err(failed(&"not a device node"));
112	}
113	let rdev = meta.rdev();
114	let sysfs = format!(
115		"/sys/dev/char/{}:{}/device/uevent",
116		libc::major(rdev),
117		libc::minor(rdev)
118	);
119	std::fs::read_to_string(&sysfs).map_err(|err| failed(&format_args!("{sysfs}: {err}")))
120}
121
122/// The value of `key` in a sysfs `uevent`'s `KEY=value` lines.
123#[cfg(target_os = "linux")]
124fn field<'a>(uevent: &'a str, key: &str) -> Option<&'a str> {
125	uevent
126		.lines()
127		.find_map(|line| line.strip_prefix(key)?.strip_prefix('='))
128}
129
130/// A PCI device's address, without the function: what CUDA reports per device.
131#[cfg(all(target_os = "linux", feature = "nvidia"))]
132#[derive(Clone, Copy, Debug, PartialEq, Eq)]
133pub(crate) struct Pci {
134	pub domain: u32,
135	pub bus: u32,
136	pub device: u32,
137}
138
139#[cfg(all(target_os = "linux", feature = "nvidia"))]
140impl Pci {
141	/// The PCI address of the device behind the node at `path`.
142	pub(crate) fn of(path: &Path) -> Result<Self, Error> {
143		let uevent = uevent(path)?;
144		let slot = field(&uevent, "PCI_SLOT_NAME")
145			.ok_or_else(|| Error::codec(anyhow::anyhow!("{} is not a PCI device", path.display())))?;
146		Self::parse(slot)
147			.ok_or_else(|| Error::codec(anyhow::anyhow!("{}: malformed PCI address {slot}", path.display())))
148	}
149
150	/// Parses `domain:bus:device.function`, all hex, as sysfs spells it.
151	fn parse(slot: &str) -> Option<Self> {
152		let (domain, rest) = slot.split_once(':')?;
153		let (bus, rest) = rest.split_once(':')?;
154		let (device, _function) = rest.split_once('.')?;
155		let hex = |s: &str| u32::from_str_radix(s, 16).ok();
156		Some(Self {
157			domain: hex(domain)?,
158			bus: hex(bus)?,
159			device: hex(device)?,
160		})
161	}
162
163	/// The ordinal of the device at this address among `devices`, each an ordinal and its address.
164	pub(crate) fn find(self, devices: impl IntoIterator<Item = (usize, Self)>) -> Option<usize> {
165		devices
166			.into_iter()
167			.find_map(|(ordinal, pci)| (pci == self).then_some(ordinal))
168	}
169}
170
171#[cfg(test)]
172mod tests {
173	use super::*;
174
175	#[test]
176	fn a_named_node_steers_to_the_backends_that_drive_its_kind() {
177		let render = Device::Render("/dev/dri/renderD129".into());
178		let video = Device::Video("/dev/video11".into());
179		for drives in [Drives::Own, Drives::Render, Drives::Nvidia, Drives::Video] {
180			assert!(Device::Auto.takes(drives).unwrap(), "{drives:?} refused Auto");
181		}
182		assert!(render.takes(Drives::Own).unwrap());
183		assert!(render.takes(Drives::Render).unwrap());
184		assert!(!render.takes(Drives::Video).unwrap());
185		assert!(video.takes(Drives::Own).unwrap());
186		assert!(video.takes(Drives::Video).unwrap());
187		assert!(!video.takes(Drives::Render).unwrap());
188		assert!(!video.takes(Drives::Nvidia).unwrap());
189	}
190
191	/// The NVIDIA check reads the node, so a node that is not there is an error,
192	/// not a quiet pass to another device.
193	#[cfg(target_os = "linux")]
194	#[test]
195	fn a_missing_render_node_fails_the_nvidia_check() {
196		let missing = Device::Render("/dev/dri/renderD999-missing".into());
197		assert!(missing.takes(Drives::Nvidia).is_err());
198		let file = Device::Render("/proc/self/status".into());
199		assert!(file.takes(Drives::Nvidia).is_err());
200	}
201
202	#[cfg(target_os = "linux")]
203	#[test]
204	fn uevent_fields_are_read_by_exact_key() {
205		let uevent = "DRIVER=nvidia\nPCI_CLASS=30000\nPCI_SLOT_NAME=0000:01:00.0\n";
206		assert_eq!(field(uevent, "DRIVER"), Some("nvidia"));
207		assert_eq!(field(uevent, "PCI_SLOT_NAME"), Some("0000:01:00.0"));
208		assert_eq!(field(uevent, "PCI"), None);
209	}
210
211	#[cfg(all(target_os = "linux", feature = "nvidia"))]
212	#[test]
213	fn a_render_node_maps_to_the_cuda_device_at_its_pci_address() {
214		let first = Pci::parse("0000:01:00.0").unwrap();
215		let second = Pci::parse("0001:a1:1f.0").unwrap();
216		assert_eq!(
217			second,
218			Pci {
219				domain: 1,
220				bus: 0xa1,
221				device: 0x1f
222			}
223		);
224		let devices = [(0, first), (1, second)];
225		assert_eq!(first.find(devices), Some(0));
226		assert_eq!(second.find(devices), Some(1));
227		assert_eq!(Pci::parse("0000:02:00.0").unwrap().find(devices), None);
228		assert_eq!(Pci::parse("0000:01:00"), None);
229	}
230}