forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

picture.rs553 lines, 18.4 KiBHistoryRawDownload
1//! [`Context`], [`Buffer`] and the [`Picture`] typestate machine.
2//!
3//! VA-API's submission protocol is a state machine: `vaBeginPicture` ->
4//! N x `vaRenderPicture` -> `vaEndPicture` -> `vaSyncSurface`. Calling those out
5//! of order is a driver-defined mess (at best an error, at worst a GPU hang),
6//! and it is not something a code review reliably catches.
7//!
8//! So the order is in the type system. Each transition consumes the picture and
9//! returns it in the next state; there is no method to skip a step and no way
10//! to name an intermediate state that was never reached:
11//!
12//! ```text
13//! Picture<New> --begin()--> Picture<Rendering> --render(buf)--> Picture<Rendering>
14//! --end()-------> Picture<Ended>
15//! --sync()------> Picture<Synced>
16//! ```
17//!
18//! The legal walk compiles:
19//!
20//! ```no_run
21//! # use ec_va::{Buffer, Context, Picture, Surface};
22//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>, buffer: Buffer)
23//! # -> ec_va::Result<()> {
24//! let surface = Picture::new(context, target)
25//! .begin()?
26//! .render(buffer)?
27//! .end()?
28//! .sync()?
29//! .into_surface();
30//! # Ok(())
31//! # }
32//! ```
33//!
34//! Ordering violations are compile errors (`E0599`: the method does not exist
35//! on that state):
36//!
37//! ```compile_fail,E0599
38//! # use ec_va::{Context, Picture, Surface};
39//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>) {
40//! let picture = Picture::new(context, target);
41//! // ERROR: no method `end` on `Picture<New>` — begin() was never called.
42//! let ended = picture.end().unwrap();
43//! # }
44//! ```
45//!
46//! ```compile_fail,E0599
47//! # use ec_va::{Context, Picture, Surface};
48//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>) {
49//! let picture = Picture::new(context, target).begin().unwrap();
50//! // ERROR: no method `sync` on `Picture<Rendering>` — end() must come first.
51//! let synced = picture.sync().unwrap();
52//! # }
53//! ```
54//!
55//! ```compile_fail,E0599
56//! # use ec_va::{Buffer, Context, Picture, Surface};
57//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>, buffer: Buffer) {
58//! let picture = Picture::new(context, target).begin().unwrap().end().unwrap();
59//! // ERROR: no method `render` on `Picture<Ended>` — the picture is closed.
60//! let rendered = picture.render(buffer).unwrap();
61//! # }
62//! ```
63//!
64//! ```compile_fail,E0599
65//! # use ec_va::{Context, Picture, Surface};
66//! # fn demo(context: &std::sync::Arc<Context>, target: std::sync::Arc<Surface>) {
67//! let picture = Picture::new(context, target).begin().unwrap();
68//! // ERROR: no method `begin` on `Picture<Rendering>` — no double submission.
69//! let again = picture.begin().unwrap();
70//! # }
71//! ```
72
73use std::marker::PhantomData;
74use std::sync::Arc;
75
76use crate::config::Config;
77use crate::display::Display;
78use crate::error::{Error, Result, check};
79use crate::surface::Surface;
80use crate::sys;
81
82/// A live `VAContextID`.
83///
84/// Holds its config and render targets, so neither can be destroyed while the
85/// context still references them — the ordering libva demands.
86pub struct Context {
87 display: Arc<Display>,
88 config: Arc<Config>,
89 id: sys::VAContextID,
90 _targets: Vec<Arc<Surface>>,
91 width: u32,
92 height: u32,
93}
94
95impl Context {
96 /// Create a context for `config` at `width` x `height`.
97 ///
98 /// `targets` are the surfaces the driver may render into. `flags` is
99 /// usually [`sys::VA_PROGRESSIVE`].
100 pub fn new(
101 config: &Arc<Config>,
102 width: u32,
103 height: u32,
104 flags: i32,
105 targets: &[Arc<Surface>],
106 ) -> Result<Arc<Context>> {
107 let display = Arc::clone(config.display());
108 let mut ids: Vec<sys::VASurfaceID> = targets.iter().map(|s| s.id()).collect();
109 let mut id: sys::VAContextID = sys::VA_INVALID_ID;
110 // SAFETY: `ids` is a valid array of `ids.len()` surface ids, all live
111 // (their `Arc`s are cloned into the context below, so they outlive it);
112 // `id` is a valid out-parameter. libva copies the target array.
113 let status = unsafe {
114 sys::vaCreateContext(
115 display.handle(),
116 config.id(),
117 width as i32,
118 height as i32,
119 flags,
120 ids.as_mut_ptr(),
121 ids.len() as i32,
122 &mut id,
123 )
124 };
125 check("vaCreateContext", status)?;
126 if id == sys::VA_INVALID_ID {
127 return Err(Error::Protocol(
128 "vaCreateContext succeeded but returned VA_INVALID_ID".to_string(),
129 ));
130 }
131 Ok(Arc::new(Context {
132 display,
133 config: Arc::clone(config),
134 id,
135 _targets: targets.to_vec(),
136 width,
137 height,
138 }))
139 }
140
141 /// The config this context was created from.
142 pub fn config(&self) -> &Arc<Config> {
143 &self.config
144 }
145
146 /// The display this context belongs to.
147 pub fn display(&self) -> &Arc<Display> {
148 &self.display
149 }
150
151 /// Coded size the context was created with.
152 pub fn size(&self) -> (u32, u32) {
153 (self.width, self.height)
154 }
155
156 /// The raw context id, for calls with no typestate-protected wrapper
157 /// (e.g. `vaQueryVideoProcFilters`).
158 pub(crate) fn raw_id(&self) -> sys::VAContextID {
159 self.id
160 }
161}
162
163impl std::fmt::Debug for Context {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 f.debug_struct("Context")
166 .field("id", &self.id)
167 .field("size", &(self.width, self.height))
168 .field("profile", &self.config.profile())
169 .finish()
170 }
171}
172
173impl Drop for Context {
174 fn drop(&mut self) {
175 // SAFETY: `self.id` is live on `self.display`. Buffers hold an
176 // `Arc<Context>` and pictures hold buffers, so none can be alive here;
177 // the render targets and config are released after this call.
178 unsafe { sys::vaDestroyContext(self.display.handle(), self.id) };
179 }
180}
181
182/// A live `VABufferID` belonging to a context.
183pub struct Buffer {
184 context: Arc<Context>,
185 id: sys::VABufferID,
186 type_: sys::VABufferType,
187}
188
189impl Buffer {
190 /// Create a buffer holding a copy of `data`.
191 ///
192 /// This is the parameter-buffer path: picture/slice parameters and slice
193 /// data are copied into driver memory, so `data` need not outlive the call.
194 pub fn from_bytes(
195 context: &Arc<Context>,
196 type_: sys::VABufferType,
197 data: &[u8],
198 ) -> Result<Buffer> {
199 if data.is_empty() {
200 return Err(Error::Protocol(format!(
201 "refusing to create an empty VA buffer of type {type_}"
202 )));
203 }
204 let mut id: sys::VABufferID = sys::VA_INVALID_ID;
205 // SAFETY: libva copies `size * num_elements` = `data.len()` bytes out
206 // of `data` during the call and never retains the pointer (va.h:3820).
207 // The cast to `*mut c_void` is sound because libva only reads it: the
208 // `data` parameter is documented as `in`.
209 let status = unsafe {
210 sys::vaCreateBuffer(
211 context.display.handle(),
212 context.id,
213 type_,
214 data.len() as u32,
215 1,
216 data.as_ptr() as *mut std::ffi::c_void,
217 &mut id,
218 )
219 };
220 check("vaCreateBuffer", status)?;
221 Buffer::wrap(context, id, type_)
222 }
223
224 /// Create a buffer holding a copy of one plain-old-data parameter struct.
225 ///
226 /// # Safety
227 ///
228 /// `T` must be the exact `#[repr(C)]` parameter struct libva expects for
229 /// `type_` (e.g. `VAPictureParameterBufferH264` for
230 /// `VAPictureParameterBufferType`) and must contain no padding-sensitive
231 /// invariants: the driver reads `size_of::<T>()` bytes of it verbatim.
232 pub unsafe fn from_param<T: Copy>(
233 context: &Arc<Context>,
234 type_: sys::VABufferType,
235 param: &T,
236 ) -> Result<Buffer> {
237 // SAFETY: `T: Copy` with the caller's guarantee that it is a repr(C)
238 // POD parameter struct, so its bytes are a valid representation to
239 // hand to the driver; the slice covers exactly one `T` and is only
240 // read during the call below.
241 let bytes =
242 unsafe { std::slice::from_raw_parts((param as *const T).cast::<u8>(), size_of::<T>()) };
243 Buffer::from_bytes(context, type_, bytes)
244 }
245
246 /// Allocate an empty buffer of `size` bytes to be filled via [`Buffer::map`].
247 ///
248 /// This is the coded-output path: `VAEncCodedBufferType` buffers are
249 /// written by the GPU and read back after sync.
250 pub fn allocate(context: &Arc<Context>, type_: sys::VABufferType, size: u32) -> Result<Buffer> {
251 let mut id: sys::VABufferID = sys::VA_INVALID_ID;
252 // SAFETY: a NULL `data` pointer is the documented "allocate only" form
253 // (va.h:3826); `id` is a valid out-parameter.
254 let status = unsafe {
255 sys::vaCreateBuffer(
256 context.display.handle(),
257 context.id,
258 type_,
259 size,
260 1,
261 std::ptr::null_mut(),
262 &mut id,
263 )
264 };
265 check("vaCreateBuffer", status)?;
266 Buffer::wrap(context, id, type_)
267 }
268
269 fn wrap(
270 context: &Arc<Context>,
271 id: sys::VABufferID,
272 type_: sys::VABufferType,
273 ) -> Result<Buffer> {
274 if id == sys::VA_INVALID_ID {
275 return Err(Error::Protocol(
276 "vaCreateBuffer succeeded but returned VA_INVALID_ID".to_string(),
277 ));
278 }
279 Ok(Buffer {
280 context: Arc::clone(context),
281 id,
282 type_,
283 })
284 }
285
286 /// Map the buffer for reading or writing. Unmaps on drop.
287 pub fn map(&mut self) -> Result<MappedBuffer<'_>> {
288 let mut ptr: *mut std::ffi::c_void = std::ptr::null_mut();
289 // SAFETY: `self.id` is a live buffer on this display; `ptr` is a valid
290 // out-parameter. libva keeps the mapping valid until vaUnmapBuffer,
291 // which `MappedBuffer::drop` calls exactly once.
292 let status =
293 unsafe { sys::vaMapBuffer(self.context.display.handle(), self.id, &raw mut ptr) };
294 check("vaMapBuffer", status)?;
295 if ptr.is_null() {
296 // SAFETY: the map reported success, so it must be undone even
297 // though the returned pointer is unusable.
298 unsafe { sys::vaUnmapBuffer(self.context.display.handle(), self.id) };
299 return Err(Error::Protocol(
300 "vaMapBuffer succeeded but returned NULL".to_string(),
301 ));
302 }
303 Ok(MappedBuffer {
304 buffer: self,
305 base: ptr.cast::<u8>(),
306 })
307 }
308
309 /// The buffer id.
310 pub fn id(&self) -> sys::VABufferID {
311 self.id
312 }
313
314 /// The `VABufferType` this buffer was created with.
315 pub fn buffer_type(&self) -> sys::VABufferType {
316 self.type_
317 }
318}
319
320impl std::fmt::Debug for Buffer {
321 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
322 f.debug_struct("Buffer")
323 .field("id", &self.id)
324 .field("type", &self.type_)
325 .finish()
326 }
327}
328
329impl Drop for Buffer {
330 fn drop(&mut self) {
331 // SAFETY: `self.id` is live and belongs to `self.context`'s display,
332 // which outlives it (the `Arc<Context>` is held here). Mappings borrow
333 // `&mut self`, so none can be outstanding.
334 unsafe { sys::vaDestroyBuffer(self.context.display.handle(), self.id) };
335 }
336}
337
338/// A mapped [`Buffer`]. Unmaps on drop.
339///
340/// The length of the mapping is not reported by libva for parameter buffers,
341/// so access goes through explicit sizes the caller already knows (for coded
342/// buffers, through the `VACodedBufferSegment` list, which `ec-hw` parses).
343pub struct MappedBuffer<'a> {
344 buffer: &'a mut Buffer,
345 base: *mut u8,
346}
347
348impl MappedBuffer<'_> {
349 /// The raw mapped pointer.
350 ///
351 /// # Safety
352 ///
353 /// The caller must not read or write beyond the size the buffer was created
354 /// with, and must not keep the pointer past this guard's lifetime.
355 pub unsafe fn as_ptr(&self) -> *mut u8 {
356 self.base
357 }
358
359 /// The first `len` bytes of the mapping.
360 ///
361 /// # Safety
362 ///
363 /// `len` must not exceed the size the buffer was created with.
364 pub unsafe fn as_slice(&self, len: usize) -> &[u8] {
365 // SAFETY: the caller guarantees `len` is within the allocation, and the
366 // mapping is live for as long as this guard exists.
367 unsafe { std::slice::from_raw_parts(self.base, len) }
368 }
369
370 /// The first `len` bytes of the mapping, mutably.
371 ///
372 /// # Safety
373 ///
374 /// `len` must not exceed the size the buffer was created with.
375 pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [u8] {
376 // SAFETY: as `as_slice`, plus `&mut self` makes this the only live
377 // reference into the mapping.
378 unsafe { std::slice::from_raw_parts_mut(self.base, len) }
379 }
380}
381
382impl Drop for MappedBuffer<'_> {
383 fn drop(&mut self) {
384 // SAFETY: mapped in `Buffer::map`, unmapped exactly once here; the
385 // buffer is still alive because this guard borrows it.
386 unsafe { sys::vaUnmapBuffer(self.buffer.context.display.handle(), self.buffer.id) };
387 }
388}
389
390mod sealed {
391 /// Prevents downstream crates from inventing picture states.
392 pub trait Sealed {}
393}
394
395/// Marker trait for the [`Picture`] states.
396pub trait PictureState: sealed::Sealed {}
397
398macro_rules! picture_states {
399 ($($(#[$meta:meta])* $name:ident),* $(,)?) => {
400 $(
401 $(#[$meta])*
402 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
403 pub struct $name;
404 impl sealed::Sealed for $name {}
405 impl PictureState for $name {}
406 )*
407 };
408}
409
410picture_states! {
411 /// Nothing submitted yet.
412 New,
413 /// `vaBeginPicture` done; buffers may be rendered.
414 Rendering,
415 /// `vaEndPicture` done; the GPU is working on it.
416 Ended,
417 /// `vaSyncSurface` done; the target surface is readable.
418 Synced,
419}
420
421/// One picture submission, parameterised by how far through the VA protocol it is.
422///
423/// See the [module docs](self) for the state diagram and the compile-fail
424/// examples.
425pub struct Picture<S: PictureState> {
426 context: Arc<Context>,
427 target: Arc<Surface>,
428 /// Kept alive until the picture is dropped: the driver may reference
429 /// parameter buffers until the submission completes.
430 buffers: Vec<Buffer>,
431 _state: PhantomData<S>,
432}
433
434impl<S: PictureState> Picture<S> {
435 /// The surface this picture renders into.
436 pub fn target(&self) -> &Arc<Surface> {
437 &self.target
438 }
439
440 /// The context this picture is submitted to.
441 pub fn context(&self) -> &Arc<Context> {
442 &self.context
443 }
444
445 fn transition<T: PictureState>(self) -> Picture<T> {
446 Picture {
447 context: self.context,
448 target: self.target,
449 buffers: self.buffers,
450 _state: PhantomData,
451 }
452 }
453}
454
455impl Picture<New> {
456 /// Start a picture targeting `target`. No driver call yet.
457 pub fn new(context: &Arc<Context>, target: Arc<Surface>) -> Picture<New> {
458 Picture {
459 context: Arc::clone(context),
460 target,
461 buffers: Vec::new(),
462 _state: PhantomData,
463 }
464 }
465
466 /// `vaBeginPicture`.
467 ///
468 /// On failure the picture is consumed and the context is left with no
469 /// picture in flight; the next `begin` starts cleanly.
470 pub fn begin(self) -> Result<Picture<Rendering>> {
471 // SAFETY: live context and surface ids, both kept alive by the `Arc`s
472 // this picture holds.
473 let status = unsafe {
474 sys::vaBeginPicture(
475 self.context.display.handle(),
476 self.context.id,
477 self.target.id(),
478 )
479 };
480 check("vaBeginPicture", status)?;
481 Ok(self.transition())
482 }
483}
484
485impl Picture<Rendering> {
486 /// `vaRenderPicture` with one buffer, which the picture then owns.
487 pub fn render(self, buffer: Buffer) -> Result<Picture<Rendering>> {
488 self.render_all(vec![buffer])
489 }
490
491 /// `vaRenderPicture` with several buffers in one call.
492 pub fn render_all(mut self, buffers: Vec<Buffer>) -> Result<Picture<Rendering>> {
493 if buffers.is_empty() {
494 return Ok(self);
495 }
496 let mut ids: Vec<sys::VABufferID> = buffers.iter().map(|b| b.id).collect();
497 // SAFETY: `ids` is a valid array of `ids.len()` live buffer ids; the
498 // buffers themselves are moved into `self.buffers` below, so they
499 // outlive the submission. libva does not retain the id array.
500 let status = unsafe {
501 sys::vaRenderPicture(
502 self.context.display.handle(),
503 self.context.id,
504 ids.as_mut_ptr(),
505 ids.len() as i32,
506 )
507 };
508 // Keep the buffers alive regardless of the outcome: on failure the
509 // driver may still hold references until the context is torn down.
510 self.buffers.extend(buffers);
511 check("vaRenderPicture", status)?;
512 Ok(self)
513 }
514
515 /// `vaEndPicture` — hand the picture to the GPU.
516 pub fn end(self) -> Result<Picture<Ended>> {
517 // SAFETY: live context id; a picture is in flight because this method
518 // exists only on `Picture<Rendering>`, i.e. after a successful begin.
519 let status = unsafe { sys::vaEndPicture(self.context.display.handle(), self.context.id) };
520 check("vaEndPicture", status)?;
521 Ok(self.transition())
522 }
523}
524
525impl Picture<Ended> {
526 /// `vaSyncSurface` — block until the target surface is complete.
527 pub fn sync(self) -> Result<Picture<Synced>> {
528 self.target.sync()?;
529 Ok(self.transition())
530 }
531}
532
533impl Picture<Synced> {
534 /// The completed surface, ready to export or map.
535 pub fn into_surface(self) -> Arc<Surface> {
536 self.target
537 }
538
539 /// The buffers submitted with this picture, e.g. to read a coded buffer.
540 pub fn buffers_mut(&mut self) -> &mut [Buffer] {
541 &mut self.buffers
542 }
543}
544
545impl<S: PictureState> std::fmt::Debug for Picture<S> {
546 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
547 f.debug_struct("Picture")
548 .field("state", &std::any::type_name::<S>())
549 .field("target", &self.target.id())
550 .field("buffers", &self.buffers.len())
551 .finish()
552 }
553}