Skip to main content

kodecs_vaapi/
lib.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
5//! VA-API H.264 and H.265 encode and decode, with libva loaded at runtime.
6//!
7//! [`encode::Encoder`] and [`decode::Decoder`] each open their own [`Display`], and
8//! [`vpp::Processor`] imports, scales, and converts [`dmabuf::DmaBuf`]s on the GPU.
9
10#![allow(
11	dead_code,
12	unused_imports,
13	unexpected_cfgs,
14	mismatched_lifetime_syntaxes,
15	clippy::all,
16	reason = "vendored from discord/cros-libva and discord/cros-codecs; kept close to upstream so fixes port cleanly"
17)]
18// VA-API and DMA-BUF are Linux-only, so elsewhere the crate is an empty stub and
19// moq-video only depends on it there.
20#![cfg_attr(
21	not(target_os = "linux"),
22	allow(
23		rustdoc::broken_intra_doc_links,
24		reason = "the items these docs link to are Linux-only"
25	)
26)]
27#![cfg(target_os = "linux")]
28
29mod bindings;
30mod buffer;
31mod config;
32mod context;
33mod display;
34mod generic_value;
35mod image;
36mod picture;
37mod pool;
38mod surface;
39mod usage_hint;
40
41// Vendored from discord/cros-codecs (BSD-3-Clause): the H.264 and H.265 DPBs, and
42// thin VA-API encode and decode drivers. kodecs-h264 parses and writes the H.264
43// syntax, and kodecs-h265 parses the H.265 syntax.
44mod codec;
45pub mod decode;
46pub mod encode;
47
48// Written for this crate: DMA-BUF import, the color space an encoder labels its
49// stream with, and the VA-API video post-processing entrypoint, which scales,
50// converts, and re-tiles surfaces on the GPU.
51mod color;
52pub mod dmabuf;
53pub mod vpp;
54
55// The vendored modules name each other's items through these crate-root globs,
56// as upstream does. Only the items below are public.
57use bindings::*;
58use buffer::*;
59use config::*;
60use context::*;
61use generic_value::*;
62use picture::*;
63use surface::*;
64
65pub use bindings::{
66	VAEntrypoint, VAImage, VAImageFormat, VAProfile, VA_FOURCC_BGRA, VA_FOURCC_BGRX, VA_FOURCC_I420, VA_FOURCC_NV12,
67	VA_FOURCC_RGBA, VA_FOURCC_RGBX, VA_RT_FORMAT_RGB32, VA_RT_FORMAT_YUV420,
68};
69pub use codec::Codec;
70pub use color::{Color, Matrix};
71pub use display::{Display, DrmDeviceIterator, OpenDrmDisplayError};
72pub use image::{Image, ImageMut};
73pub use surface::{
74	DrmPrimeSurfaceDescriptor, DrmPrimeSurfaceDescriptorLayer, DrmPrimeSurfaceDescriptorObject, Surface,
75};
76pub use usage_hint::UsageHint;
77
78/// A frame resolution in pixels. (Vendored from discord/cros-codecs, BSD-3-Clause.)
79#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
80pub(crate) struct Resolution {
81	pub width: u32,
82	pub height: u32,
83}
84
85impl Resolution {
86	/// Whether `self` can contain `other`.
87	pub fn can_contain(&self, other: Self) -> bool {
88		self.width >= other.width && self.height >= other.height
89	}
90
91	pub fn get_area(&self) -> usize {
92		(self.width as usize) * (self.height as usize)
93	}
94}
95
96impl From<(u32, u32)> for Resolution {
97	fn from(value: (u32, u32)) -> Self {
98		Self {
99			width: value.0,
100			height: value.1,
101		}
102	}
103}
104
105impl From<Resolution> for (u32, u32) {
106	fn from(value: Resolution) -> Self {
107		(value.width, value.height)
108	}
109}
110
111use std::num::NonZeroI32;
112
113/// A `VAStatus` that is guaranteed to not be `VA_STATUS_SUCCESS`.
114#[derive(Debug)]
115pub struct VaError(NonZeroI32);
116
117impl VaError {
118	/// Returns an error carrying `status`, for a call libva reported as successful
119	/// whose result we cannot use.
120	fn status(status: u32) -> Self {
121		Self(NonZeroI32::new(status as i32).expect("a failure status"))
122	}
123
124	/// Returns the `VAStatus` of this error.
125	pub fn va_status(&self) -> VAStatus {
126		self.0.get() as VAStatus
127	}
128}
129
130impl std::fmt::Display for VaError {
131	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132		use std::ffi::CStr;
133
134		// Safe because `vaErrorStr` will return a pointer to a statically allocated, null
135		// terminated C string. The pointer is guaranteed to never be null.
136		let err_str = unsafe { CStr::from_ptr(bindings::va().vaErrorStr(self.0.get())) }
137			.to_str()
138			.unwrap();
139		f.write_str(err_str)
140	}
141}
142
143impl std::error::Error for VaError {}
144
145/// Checks a VA return value and returns a `VaError` if it is not `VA_STATUS_SUCCESS`.
146///
147/// This can be used on the return value of any VA function returning `VAStatus` in order to
148/// convert it to a proper Rust `Result`.
149fn va_check(code: VAStatus) -> Result<(), VaError> {
150	match code as u32 {
151		bindings::VA_STATUS_SUCCESS => Ok(()),
152		_ => Err(VaError(unsafe { NonZeroI32::new_unchecked(code) })),
153	}
154}