forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

display.rs186 lines, 7.2 KiBHistoryRawDownload
1//! [`Display`] — an initialized `VADisplay` on a DRM render node.
2
3use std::ffi::CStr;
4use std::fs::File;
5use std::os::fd::AsRawFd;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use crate::error::{Error, Result, check};
10use crate::sys;
11
12/// An initialized VA display, owning both the DRM file descriptor and the
13/// `VADisplay` derived from it.
14///
15/// Everything else in this crate holds an `Arc<Display>`, so the display is
16/// terminated only after the last surface, config, context and buffer is gone —
17/// the ordering libva requires, enforced by the type system rather than by
18/// documentation.
19pub struct Display {
20 /// Raw `VADisplay`. Valid until [`Drop`] calls `vaTerminate`.
21 handle: sys::VADisplay,
22 /// The render node. Must outlive `handle`: libva does not dup the fd.
23 node: File,
24 path: PathBuf,
25 version: (i32, i32),
26}
27
28// SAFETY: libva's dispatch layer (`va.c`) and the Mesa VA driver both take an
29// internal lock per display around every entry point used here, so a
30// `VADisplay` may be used from any thread and from several threads at once.
31// The `File` and `PathBuf` fields are themselves `Send + Sync`. This mirrors
32// what every VA-API consumer (the oracle, GStreamer, cros-libva) relies on.
33//
34// Note the narrower claim this crate actually needs: `&Display` is only ever
35// used to *call* libva, never to hand out interior pointers.
36unsafe impl Send for Display {}
37// SAFETY: see above.
38unsafe impl Sync for Display {}
39
40impl Display {
41 /// Open the first usable DRM render node (`/dev/dri/renderD128` upwards).
42 ///
43 /// Render nodes are used rather than card nodes: they need no DRM master
44 /// and no display server, which is what a headless encode/decode pipeline
45 /// wants.
46 pub fn open() -> Result<Arc<Display>> {
47 let mut last: Option<Error> = None;
48 // 128..=143 is the kernel's render-node numbering (16 GPUs is plenty).
49 for n in 128..=143u32 {
50 let path = PathBuf::from(format!("/dev/dri/renderD{n}"));
51 if !path.exists() {
52 continue;
53 }
54 match Display::open_path(&path) {
55 Ok(display) => return Ok(display),
56 Err(e) => last = Some(e),
57 }
58 }
59 Err(last.unwrap_or(Error::NoDevice))
60 }
61
62 /// Open a specific DRM node, e.g. `/dev/dri/renderD128`.
63 ///
64 /// The node is opened **read-write**, and that is not a detail: with a
65 /// read-only fd radeonsi 26.1 fails `amdgpu_bo_cpu_map` and then segfaults
66 /// *inside* `vaInitialize`, before it can return a status this crate could
67 /// turn into an error. Verified on this machine (gfx1200, Mesa 26.1.6).
68 pub fn open_path(path: &Path) -> Result<Arc<Display>> {
69 let node = File::options()
70 .read(true)
71 .write(true)
72 .open(path)
73 .map_err(|source| Error::Drm {
74 path: path.display().to_string(),
75 source,
76 })?;
77
78 // SAFETY: `node` is an open DRM fd that lives as long as the returned
79 // Display (it is moved into it below, and closed only after
80 // vaTerminate in Drop). vaGetDisplayDRM does not take ownership of the
81 // fd and returns NULL on failure, which is checked.
82 let handle = unsafe { sys::vaGetDisplayDRM(node.as_raw_fd()) };
83 if handle.is_null() {
84 return Err(Error::va(
85 "vaGetDisplayDRM",
86 sys::VA_STATUS_ERROR_OPERATION_FAILED,
87 ));
88 }
89
90 let mut major: i32 = 0;
91 let mut minor: i32 = 0;
92 // SAFETY: `handle` is a non-NULL VADisplay from vaGetDisplayDRM; the
93 // two out-parameters are valid, aligned, initialized `int`s that
94 // outlive the call.
95 let status = unsafe { sys::vaInitialize(handle, &mut major, &mut minor) };
96 if let Err(e) = check("vaInitialize", status) {
97 // libva allocates display state inside vaGetDisplayDRM, so a failed
98 // initialize still has to be terminated or that state leaks. This
99 // is what the oracle's vaapi_device_create does on its failure path.
100 //
101 // SAFETY: `handle` is still a valid (if uninitialized) VADisplay;
102 // vaTerminate accepts exactly this state.
103 unsafe { sys::vaTerminate(handle) };
104 return Err(e);
105 }
106
107 // Runtime drift guard. The struct layouts in `sys` are transcribed from
108 // the 1.23 headers; talking to an older runtime would be guesswork.
109 if major != crate::MIN_VA_MAJOR || minor < crate::MIN_VA_MINOR {
110 // SAFETY: initialize succeeded, so terminating is required and valid.
111 unsafe { sys::vaTerminate(handle) };
112 return Err(Error::Version { major, minor });
113 }
114
115 Ok(Arc::new(Display {
116 handle,
117 node,
118 path: path.to_path_buf(),
119 version: (major, minor),
120 }))
121 }
122
123 /// The raw handle, for the rest of the crate's FFI calls.
124 pub(crate) fn handle(&self) -> sys::VADisplay {
125 self.handle
126 }
127
128 /// Runtime libva version as `(major, minor)`, from `vaInitialize`.
129 pub fn version(&self) -> (i32, i32) {
130 self.version
131 }
132
133 /// The DRM node this display was opened on.
134 pub fn device_path(&self) -> &Path {
135 &self.path
136 }
137
138 /// The raw DRM render-node fd. Borrowed, never closed by the caller.
139 pub fn drm_fd(&self) -> std::os::fd::BorrowedFd<'_> {
140 // `File` guarantees the fd is open for as long as `self` lives.
141 std::os::fd::AsFd::as_fd(&self.node)
142 }
143
144 /// Driver vendor string, e.g. `"Mesa Gallium driver 26.1.6 for AMD ..."`.
145 pub fn vendor(&self) -> Result<String> {
146 // SAFETY: `self.handle` is initialized and valid for the lifetime of
147 // `self`. The returned pointer is owned by the driver and stays valid
148 // until vaTerminate, i.e. strictly longer than this borrow; the string
149 // is copied before returning.
150 let ptr = unsafe { sys::vaQueryVendorString(self.handle) };
151 if ptr.is_null() {
152 return Err(Error::Protocol(
153 "vaQueryVendorString returned NULL".to_string(),
154 ));
155 }
156 // SAFETY: non-NULL, NUL-terminated, driver-owned static string.
157 Ok(unsafe { CStr::from_ptr(ptr) }
158 .to_string_lossy()
159 .into_owned())
160 }
161
162 /// `vaDisplayIsValid`, mostly useful in tests.
163 pub fn is_valid(&self) -> bool {
164 // SAFETY: `self.handle` is a valid VADisplay for the lifetime of `self`.
165 unsafe { sys::vaDisplayIsValid(self.handle) != 0 }
166 }
167}
168
169impl std::fmt::Debug for Display {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171 f.debug_struct("Display")
172 .field("path", &self.path)
173 .field("version", &self.version)
174 .finish_non_exhaustive()
175 }
176}
177
178impl Drop for Display {
179 fn drop(&mut self) {
180 // SAFETY: `self.handle` was initialized in `open_path` and no child
181 // object can still be alive: every one of them holds an `Arc<Display>`,
182 // so this runs only after the last of them was dropped. `self.node` is
183 // closed after this, as libva requires.
184 unsafe { sys::vaTerminate(self.handle) };
185 }
186}