Merge the GPU validation of the hardware video path

Measured on a real RX 7900 GRE with FFmpeg 9: VA-API and AMF encode
1080p60 and 1440p60 at a quarter to half a core, simulcast included;
RGB DMA-BUFs are converted to NV12 on the GPU; Wayland screen capture
delivers frames again (it delivered none) and switches to shared memory
where reading GPU memory is slow; the H.264 level of the SPS matches
the offer; AV1 is cropped to what this GPU really encodes; FFmpeg 9's
structure offsets are checked against its headers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 06:55:32 +03:00
commit cf0a0211c1
11 files changed
+2213 -142

No files matched your search

+6 -2
View File
@@ -20,7 +20,7 @@ openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"]
# Video encoders through FFmpeg loaded at runtime (never linked or shipped):
# VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox, x264,
# SVT-AV1, ... whatever the installed FFmpeg has (see docs/media.md).
ffmpeg = ["dep:libloading"]
ffmpeg = ["dep:libloading", "dep:rustix"]
# AV1 decoding through the system libdav1d (pkg-config `dav1d` >= 1.3).
av1 = ["dep:dav1d"]
# X11 screen capture (Linux).
@@ -62,7 +62,7 @@ yuv = "0.8.19"
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "tokio"], optional = true }
memmap2 = { version = "0.9.11", optional = true }
pipewire = { version = "0.10.1", optional = true }
rustix = { version = "1.1.5", features = ["event", "fs"], optional = true }
rustix = { version = "1.1.5", features = ["event", "fs", "stdio"], optional = true }
wayland-client = { version = "0.31.15", optional = true }
wayland-protocols = { version = "0.32.13", features = ["client", "staging"], optional = true }
wayland-protocols-wlr = { version = "0.3.12", features = ["client"], optional = true }
@@ -80,6 +80,10 @@ windows-capture = "2.0.1"
[dev-dependencies]
criterion = "0.8"
serde_json = "1"
# The H.264 `profile-level-id` the signalling offers, to check it against the
# SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream
# does not depend on this crate.
voelin-stream = { path = "../voelin-stream" }
# Logs of integration tests (`RUST_LOG`).
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] }
+14
View File
@@ -21,6 +21,18 @@ const DMA_BUF_SYNC_END: u64 = 1 << 2;
/// `DMA_BUF_IOCTL_SYNC`: `_IOW('b', 0, struct dma_buf_sync)`.
const SYNC: rustix::ioctl::Opcode = rustix::ioctl::opcode::write::<DmaBufSync>(b'b', 0);
/// The size of DMA-BUF `fd` in bytes (`lseek(fd, 0, SEEK_END)`, which a
/// DMA-BUF answers with its buffer object's size without moving anything).
pub(crate) fn size_of(fd: RawFd) -> Option<usize> {
if fd < 0 {
return None;
}
// SAFETY: borrowed for the call from a caller that holds it open.
let fd = unsafe { BorrowedFd::borrow_raw(fd) };
let end = rustix::fs::seek(fd, rustix::fs::SeekFrom::End(0)).ok()?;
usize::try_from(end).ok().filter(|&size| size > 0)
}
/// A read-only mapping of a DMA-BUF.
pub(crate) struct DmaBufMap {
fd: RawFd,
@@ -97,5 +109,7 @@ mod tests {
assert_eq!(map.fd(), file.as_raw_fd());
assert_eq!(map.read(|b| b.iter().map(|&x| u64::from(x)).sum::<u64>()), 7 * 8192);
assert!(DmaBufMap::new(-1, 10).is_err());
assert_eq!(size_of(file.as_raw_fd()), Some(8192));
assert_eq!(size_of(-1), None);
}
}
+63 -8
View File
@@ -11,9 +11,13 @@
//! (`BGRx` / `BGRA` / `RGBx` / `RGBA`) second, so compositors without
//! DMA-BUF support use shared memory. When reading DMA-BUFs turns out slow
//! (buffers in memory the CPU reads uncached, e.g. a discrete GPU's VRAM),
//! the stream switches to shared memory. Tiled DMA-BUFs would need a GPU
//! import and are not offered. Frames go to the [`FrameSink`] while the
//! buffer is dequeued; nothing is copied before conversion. The frame rate
//! the stream switches to shared memory. A sink that
//! [accepts DMA-BUFs](FrameSink::accepts_dmabuf) (a VA-API encoder, which
//! converts and encodes them on the GPU) gets them before anything is
//! mapped, and then the CPU never reads them. Tiled DMA-BUFs are not
//! offered: the modifiers the encoder's driver imports are not known here.
//! Frames go to the [`FrameSink`] while the buffer is dequeued; nothing is
//! copied before conversion. The frame rate
//! follows the sink's cap: the compositor is asked for up to that rate and
//! sends frames when the screen changes.
@@ -31,7 +35,7 @@ use pw::spa::pod::{
use pw::spa::utils::{Choice, ChoiceEnum, ChoiceFlags, Fraction, Id, Rectangle, SpaTypes};
use tracing::{debug, warn};
use crate::capture::dmabuf::DmaBufMap;
use crate::capture::dmabuf::{self, DmaBufMap};
use crate::capture::pw::{PwThread, pod, serialize};
use crate::capture::{
BoxFuture, CaptureOptions, CaptureSource, DRM_MOD_LINEAR, DmaBufRef, FrameSink, QueueSink,
@@ -248,9 +252,23 @@ const MODIFIER_LINEAR: i64 = 0;
/// Reading DMA-BUFs slower than this (per pixel, conversion included) means
/// the buffers live in memory the CPU reads uncached (e.g. a discrete GPU's
/// VRAM); shared memory is faster then.
const SLOW_DMABUF_NS_PER_PIXEL: f64 = 6.0;
///
/// Measured on a Radeon RX 7900 GRE capturing a 2560x1440 desktop at 60 fps,
/// the same run through both paths: a LINEAR DMA-BUF took 11.95 ms per frame
/// (3.24 ns per pixel) and 19.5 CPU cores, shared memory 0.27 ms (0.07 ns
/// per pixel) and 0.41 cores — 44 times the time and 48 times the CPU. The
/// threshold was 6.0, which that does not reach, so the switch never
/// happened and a discrete GPU burned twenty cores on screen sharing. It
/// sits between the two figures, an order of magnitude above the fast path,
/// so a GPU whose buffers the CPU can read (anything with unified memory)
/// keeps them.
const SLOW_DMABUF_NS_PER_PIXEL: f64 = 1.0;
/// DMA-BUF frames timed before deciding.
const DMABUF_PROBE_FRAMES: u32 = 30;
/// DMA-BUFs that failed to map before shared memory is offered instead. A
/// few failures can be a buffer being replaced; more means this compositor's
/// buffers cannot be read this way at all.
const DMABUF_FAILURES_BEFORE_SHM: u32 = 5;
/// What was negotiated.
#[derive(Clone, Copy, Debug)]
@@ -275,6 +293,9 @@ struct VideoState {
/// Time spent handing DMA-BUF frames to the sink, and how many.
dmabuf_time: Duration,
dmabuf_frames: u32,
/// DMA-BUFs that could not be mapped (see
/// [`DMABUF_FAILURES_BEFORE_SHM`]).
dmabuf_failures: u32,
logged: Option<bool>,
mainloop: pw::main_loop::MainLoopWeak,
}
@@ -303,6 +324,7 @@ fn video_stream(
maps: Vec::new(),
dmabuf_time: Duration::ZERO,
dmabuf_frames: 0,
dmabuf_failures: 0,
logged: None,
mainloop: mainloop.downgrade(),
};
@@ -582,7 +604,12 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
fourcc,
modifier: format.modifier.map_or(DRM_MOD_LINEAR, |m| m as u64),
fd: data.fd(),
size: (raw.mapoffset + raw.maxsize) as usize,
// As for the mapping below: compositors leave `maxsize` 0 for
// a DMA-BUF, whose size is its buffer object's.
size: match (raw.mapoffset + raw.maxsize) as usize {
0 => dmabuf::size_of(data.fd()).unwrap_or(raw.mapoffset as usize + needed),
size => size,
},
planes: [(raw.mapoffset as usize + offset, stride), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
};
@@ -600,14 +627,42 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
let started = Instant::now();
let more = if is_dmabuf {
let raw = data.as_raw();
let len = (raw.mapoffset + raw.maxsize) as usize;
// A DMA-BUF's size lives in its buffer object, not in `maxsize`:
// `maxsize` describes a mapping, which only shared memory has, and
// compositors leave it 0 (measured on a 2560x1440 Wayland desktop:
// fd valid, stride 10240, `mapoffset` and `maxsize` both 0). Mapping
// `mapoffset + maxsize` bytes then asks for a zero-length mapping
// and every frame is dropped, so fall back to the rows the
// negotiated format describes, which is exactly what is read below.
let len = match (raw.mapoffset + raw.maxsize) as usize {
0 => raw.mapoffset as usize + needed,
size => size,
};
let fd = data.fd();
if !state.maps.iter().any(|m| m.fd() == fd && m.len() >= len) {
state.maps.retain(|m| m.fd() != fd);
match DmaBufMap::new(fd, len) {
Ok(map) => state.maps.push(map),
Err(e) => {
warn!("cannot map a screen capture DMA-BUF: {e}");
warn!(
fd,
len,
mapoffset = raw.mapoffset,
maxsize = raw.maxsize,
stride,
height = format.height,
"cannot map a screen capture DMA-BUF: {e}"
);
// Dropping every frame would leave the viewer a black
// screen; shared memory always works.
state.dmabuf_failures += 1;
if state.dmabuf_failures >= DMABUF_FAILURES_BEFORE_SHM && state.dmabuf {
tracing::info!(
"screen capture DMA-BUFs cannot be mapped; switching to shared memory"
);
state.dmabuf = false;
renegotiate(stream, state.fps, false);
}
return;
}
}
File diff suppressed because it is too large. Load diff
+103 -8
View File
@@ -13,11 +13,15 @@
//! | `AVFrame.pict_type`, `AVFrame.pts` | forcing a keyframe, timestamps | right after the leading fields: `key_frame` (removed in libavutil 60), `pict_type`, `sample_aspect_ratio`, `pts` | a fresh frame must read `pict_type` 0, `sample_aspect_ratio` {0, 1}, `pts` `AV_NOPTS_VALUE` in exactly one of the two layouts |
//! | `AVCodecContext.hw_frames_ctx` | VA-API input frames | next to fields that have AVOptions, whose offsets `av_opt_find` reports: before `hw_device_ctx`, `hwaccel_flags` (libavcodec 61 and later, after `err_recognition`), or two fields before `max_pixels` (up to 60) | the neighbours' option offsets must match the layout, and the field must be NULL in a new context |
//! | `AVHWFramesContext` `initial_pool_size`, `format`, `sw_format`, `width`, `height` | creating a frame pool | after seven pointers (eight up to libavutil 58: `internal`) | `device_ctx` must equal the device and both formats must be `AV_PIX_FMT_NONE` in a new context |
//! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-60, 64-bit only) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool |
//! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-61, 64-bit only; an unlisted major disables the import) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool |
//! | `AVHWDeviceContext.hwctx` | the `VADisplay`, for the GPU colour conversion of RGB DMA-BUFs | right after `type`, after one pointer (two up to libavutil 58: `internal`) | `type` must be the device's type in exactly that layout |
//!
//! A check that fails disables only what needs the field (VA-API, or the
//! DMA-BUF import), with the reason in the probe results; a new major whose
//! layout matches keeps working without a change here.
//! DMA-BUF import), with the reason in the probe results. The first three
//! rows are found by searching, so a new major whose layout matches keeps
//! working without a change here; the last one is a table, because there is
//! nothing to anchor those offsets to, and an unlisted major turns the
//! DMA-BUF import off rather than guess (see [`frame_refs_table`]).
#![allow(unsafe_code)]
use std::ffi::c_int;
@@ -316,6 +320,51 @@ pub unsafe fn hw_frames_fields(frames: Ptr, device: Ptr) -> Result<HwFramesField
}
}
/// `AVHWDeviceContext` up to libavutil 58.
#[repr(C)]
struct DeviceWithInternal {
av_class: Ptr,
internal: Ptr,
kind: c_int,
hwctx: Ptr,
}
/// `AVHWDeviceContext` from libavutil 59 (`internal` removed).
#[repr(C)]
struct DevicePublic {
av_class: Ptr,
kind: c_int,
hwctx: Ptr,
}
/// `AVHWDeviceContext.hwctx` of `device`, a device of type `kind`: the
/// API's own context (`AVVAAPIDeviceContext` for VA-API, whose first field
/// is the `VADisplay`).
///
/// Found by `type`, which comes right before it: in the old layout the
/// same offset holds the low half of the `internal` pointer, which is
/// aligned and so never a small device type.
///
/// # Safety
/// `device` must be a live buffer reference of an `AVHWDeviceContext`.
pub unsafe fn device_hwctx(device: Ptr, kind: c_int) -> Result<Ptr, String> {
// SAFETY: guaranteed by the caller; `data` is the leading field pair,
// and both layouts lie within the smaller one (the current struct).
unsafe {
let ctx = (*device.cast::<BufferRefHead>()).data.cast::<std::ffi::c_void>();
for (kind_at, hwctx_at) in [
(offset_of!(DevicePublic, kind), offset_of!(DevicePublic, hwctx)),
(offset_of!(DeviceWithInternal, kind), offset_of!(DeviceWithInternal, hwctx)),
] {
if read::<c_int>(ctx, kind_at) == kind {
let hwctx: Ptr = read(ctx, hwctx_at);
return if hwctx.is_null() { Err("no device context".into()) } else { Ok(hwctx) };
}
}
}
Err("unknown AVHWDeviceContext layout".into())
}
/// Offsets of `buf[0]` and `hw_frames_ctx` in `AVFrame`, for importing
/// DMA-BUFs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -324,8 +373,19 @@ pub struct FrameRefs {
pub hw_frames_ctx: usize,
}
/// The table of [`FrameRefs`] per libavutil major (64-bit targets). A newer
/// major is tried with the newest entry and must pass the checks.
/// The table of [`FrameRefs`] per libavutil major (64-bit targets).
///
/// Every entry is `offsetof` compiled from that release's own
/// `libavutil/frame.h`; libavutil 61's was measured against the headers
/// installed next to the library it describes (FFmpeg 9.0.1: `buf` 184,
/// `hw_frames_ctx` 328, `sizeof(AVFrame)` 424).
///
/// A major that is not listed returns `None`, which disables the DMA-BUF
/// import (and nothing else) with the reason in the probe results. It
/// deliberately does not fall back to the newest entry: `AVFrame` has both
/// grown and shrunk between majors (424 bytes in 61 against 536 in 56), so
/// an offset guessed for an unknown layout could read past the end of the
/// struct. Adding a major here needs its `offsetof` values, not a guess.
fn frame_refs_table(avutil_major: u32) -> Option<FrameRefs> {
if size_of::<Ptr>() != 8 {
return None;
@@ -334,7 +394,7 @@ fn frame_refs_table(avutil_major: u32) -> Option<FrameRefs> {
56 => (288, 480),
57 | 58 => (224, 392),
59 => (200, 352),
60.. => (184, 328),
60 | 61 => (184, 328),
_ => return None,
};
Some(FrameRefs { buf, hw_frames_ctx })
@@ -346,8 +406,12 @@ fn frame_refs_table(avutil_major: u32) -> Option<FrameRefs> {
pub fn frame_refs(api: &Api, yuv420p: c_int) -> Result<FrameRefs, String> {
// SAFETY: no arguments.
let major = unsafe { (api.avutil_version)() } >> 16;
let refs = frame_refs_table(major)
.ok_or_else(|| format!("AVFrame references not known for libavutil {major} here"))?;
let refs = frame_refs_table(major).ok_or_else(|| {
format!(
"AVFrame.buf / hw_frames_ctx offsets are not recorded for libavutil {major} (see \
frame_refs_table); the import stays off until they are measured"
)
})?;
// SAFETY: a frame of 16x16 yuv420p pixels; the head fields are set
// before av_frame_get_buffer as its documentation asks; the offsets are
// inside AVFrame for this major (the table), pointer-aligned.
@@ -410,4 +474,35 @@ mod tests {
assert_eq!(frame_refs_table(58), Some(FrameRefs { buf: 224, hw_frames_ctx: 392 }));
assert_eq!(frame_refs_table(55), None);
}
/// libavutil 61 (FFmpeg 9), compiled from the installed headers on
/// x86-64: `AVFrame` `pict_type` 120, `pts` 136, `buf` 184,
/// `hw_frames_ctx` 328, `sizeof` 424; `AVCodecContext`
/// `err_recognition` 528, `hw_frames_ctx` 552, `hw_device_ctx` 560,
/// `hwaccel_flags` 568, `extra_hw_frames` 572; `AVHWFramesContext`
/// `pool` 48, `initial_pool_size` 56, `format` 60, `sw_format` 64,
/// `width` 68, `height` 72; `AVHWDeviceContext` `type` 8, `hwctx` 16.
#[cfg(target_pointer_width = "64")]
#[test]
fn libavutil_61_matches_the_headers() {
assert_eq!(frame_refs_table(61), Some(FrameRefs { buf: 184, hw_frames_ctx: 328 }));
assert_eq!(offset_of!(FrameWithoutKeyFrame, pict_type), 120);
assert_eq!(offset_of!(FrameWithoutKeyFrame, pts), 136);
let base = 528;
assert_eq!(base + offset_of!(HwFieldsNew, hw_frames_ctx), 552);
assert_eq!(base + offset_of!(HwFieldsNew, hw_device_ctx), 560);
assert_eq!(base + offset_of!(HwFieldsNew, hwaccel_flags), 568);
assert_eq!(base + offset_of!(HwFieldsNew, extra_hw_frames), 572);
assert_eq!(offset_of!(HwFramesPublic, pool), 48);
assert_eq!(offset_of!(HwFramesPublic, initial_pool_size), 56);
assert_eq!(offset_of!(HwFramesPublic, sw_format), 64);
assert_eq!(offset_of!(HwFramesPublic, height), 72);
assert_eq!(offset_of!(DevicePublic, kind), 8);
assert_eq!(offset_of!(DevicePublic, hwctx), 16);
// A major nobody measured must disable the import, not reuse 61's
// offsets: AVFrame has shrunk between majors (424 bytes in 61
// against 536 in 56), so reading at a guessed offset could leave
// the struct.
assert_eq!(frame_refs_table(62), None);
}
}
+4
View File
@@ -21,6 +21,7 @@ use std::sync::{Mutex, OnceLock};
pub mod encoder;
mod layout;
pub mod sys;
mod vpp;
pub use encoder::{
BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe,
@@ -37,6 +38,8 @@ pub(crate) struct PixFmts {
pub nv12: c_int,
pub vaapi: Option<c_int>,
pub drm_prime: Option<c_int>,
/// `bgr0`: B, G, R, x in memory, the DRM `XR24` of captured screens.
pub bgr0: Option<c_int>,
}
/// What was loaded, for logs and the UI.
@@ -98,6 +101,7 @@ impl Ffmpeg {
nv12,
vaapi: api.pix_fmt("vaapi").or_else(|| api.pix_fmt("vaapi_vld")),
drm_prime: api.pix_fmt("drm_prime"),
bgr0: api.pix_fmt("bgr0"),
};
let codec_hw_frames = layout::codec_hw_frames(&api);
let frame_refs = layout::frame_refs(&api, yuv420p);
+344
View File
@@ -0,0 +1,344 @@
//! RGB to NV12 on the GPU (VA-API video processing), so that a captured
//! RGB DMA-BUF reaches a VA-API encoder without the CPU reading a pixel.
//!
//! libva is what FFmpeg's VA-API support is built on, not one of FFmpeg's
//! libraries: it is opened at runtime (`libva.so.2`, which libavutil has
//! already loaded once a VA-API device exists) and driven on FFmpeg's own
//! `VADisplay`, so FFmpeg's surfaces (`AVFrame.data[3]`) are used as they
//! are. FFmpeg does the same conversion only in libavfilter (`scale_vaapi`),
//! which would be one more library to find and a filter graph to drive for
//! what is one call here. libva 2 has kept its ABI since 2017: structs are
//! padded to a fixed size and new fields take reserved space.
#![allow(unsafe_code)]
use std::ffi::{CStr, c_char, c_int, c_uint, c_void};
use std::sync::OnceLock;
use libloading::Library;
/// `VADisplay`.
pub type Display = *mut c_void;
/// `VAProfileNone`, `VAEntrypointVideoProc`, `VA_PROGRESSIVE`,
/// `VAProcPipelineParameterBufferType`.
const PROFILE_NONE: c_int = -1;
const ENTRYPOINT_VIDEO_PROC: c_int = 10;
const PROGRESSIVE: c_int = 1;
const PROC_PIPELINE_PARAMETER_BUFFER: c_int = 41;
/// `VAProcColorStandardBT601`, `VAProcColorStandardExplicit`,
/// `VA_SOURCE_RANGE_REDUCED` / `_FULL`.
const COLOR_STANDARD_BT601: c_int = 1;
const COLOR_STANDARD_EXPLICIT: c_int = 13;
const RANGE_REDUCED: u8 = 1;
const RANGE_FULL: u8 = 2;
/// ISO/IEC 23091-2 code points: SMPTE 170M (BT.601) primaries and transfer,
/// and the identity matrix (RGB).
const SMPTE170M: u8 = 6;
const MATRIX_IDENTITY: u8 = 0;
/// `VARectangle`.
#[repr(C)]
struct Rectangle {
x: i16,
y: i16,
width: u16,
height: u16,
}
/// `VAProcColorProperties`.
#[repr(C)]
#[derive(Default)]
struct ColorProperties {
chroma_sample_location: u8,
color_range: u8,
colour_primaries: u8,
transfer_characteristics: u8,
matrix_coefficients: u8,
reserved: [u8; 3],
}
/// `VAProcPipelineParameterBuffer` of libva 2 (224 bytes on 64-bit
/// targets).
#[repr(C)]
struct PipelineParameters {
surface: c_uint,
surface_region: *const Rectangle,
surface_color_standard: c_int,
output_region: *const Rectangle,
output_background_color: u32,
output_color_standard: c_int,
pipeline_flags: u32,
filter_flags: u32,
filters: *mut c_uint,
num_filters: u32,
forward_references: *mut c_uint,
num_forward_references: u32,
backward_references: *mut c_uint,
num_backward_references: u32,
rotation_state: u32,
blend_state: *const c_void,
mirror_state: u32,
additional_outputs: *mut c_uint,
num_additional_outputs: u32,
input_surface_flag: u32,
output_surface_flag: u32,
input_color_properties: ColorProperties,
output_color_properties: ColorProperties,
processing_mode: c_int,
output_hdr_metadata: *mut c_void,
#[cfg(target_pointer_width = "64")]
reserved: [u32; 16],
#[cfg(not(target_pointer_width = "64"))]
reserved: [u32; 19],
}
/// The libva functions used, with their `va.h` signatures.
struct Va {
create_config:
unsafe extern "C" fn(Display, c_int, c_int, *mut c_void, c_int, *mut c_uint) -> c_int,
destroy_config: unsafe extern "C" fn(Display, c_uint) -> c_int,
create_context: unsafe extern "C" fn(
Display,
c_uint,
c_int,
c_int,
c_int,
*mut c_uint,
c_int,
*mut c_uint,
) -> c_int,
destroy_context: unsafe extern "C" fn(Display, c_uint) -> c_int,
create_buffer: unsafe extern "C" fn(
Display,
c_uint,
c_int,
c_uint,
c_uint,
*mut c_void,
*mut c_uint,
) -> c_int,
destroy_buffer: unsafe extern "C" fn(Display, c_uint) -> c_int,
begin_picture: unsafe extern "C" fn(Display, c_uint, c_uint) -> c_int,
render_picture: unsafe extern "C" fn(Display, c_uint, *mut c_uint, c_int) -> c_int,
end_picture: unsafe extern "C" fn(Display, c_uint) -> c_int,
sync_surface: unsafe extern "C" fn(Display, c_uint) -> c_int,
error_str: unsafe extern "C" fn(c_int) -> *const c_char,
_lib: Library,
}
impl Va {
fn get() -> Result<&'static Va, String> {
static VA: OnceLock<Result<Va, String>> = OnceLock::new();
VA.get_or_init(|| {
// SAFETY: libva has no initialisers with requirements; once a
// VA-API device exists this is the copy libavutil loaded.
let lib = unsafe { Library::new("libva.so.2") }.map_err(|e| format!("libva: {e}"))?;
macro_rules! symbol {
($name:literal) => {
// SAFETY: looked up with its C signature from va.h; the
// library stays loaded as long as the pointers (`_lib`).
*unsafe { lib.get($name) }.map_err(|e| format!("libva: {e}"))?
};
}
Ok(Va {
create_config: symbol!(b"vaCreateConfig\0"),
destroy_config: symbol!(b"vaDestroyConfig\0"),
create_context: symbol!(b"vaCreateContext\0"),
destroy_context: symbol!(b"vaDestroyContext\0"),
create_buffer: symbol!(b"vaCreateBuffer\0"),
destroy_buffer: symbol!(b"vaDestroyBuffer\0"),
begin_picture: symbol!(b"vaBeginPicture\0"),
render_picture: symbol!(b"vaRenderPicture\0"),
end_picture: symbol!(b"vaEndPicture\0"),
sync_surface: symbol!(b"vaSyncSurface\0"),
error_str: symbol!(b"vaErrorStr\0"),
_lib: lib,
})
})
.as_ref()
.map_err(Clone::clone)
}
/// `Err` with libva's text for a status other than `VA_STATUS_SUCCESS`.
fn check(&self, what: &str, status: c_int) -> Result<(), String> {
if status == 0 {
return Ok(());
}
// SAFETY: returns a static string for any status.
let text = unsafe { CStr::from_ptr((self.error_str)(status)) };
Err(format!("{what}: {}", text.to_string_lossy()))
}
}
/// A VA-API video processing context that converts RGB surfaces into NV12
/// ones of `width` x `height`.
pub struct Converter {
va: &'static Va,
display: Display,
config: c_uint,
context: c_uint,
width: u32,
height: u32,
}
// SAFETY: libva serialises calls per display; the context is used from one
// thread at a time (`&self` of a session behind `&mut`).
unsafe impl Send for Converter {}
impl Converter {
/// A context on `display` (FFmpeg's, see
/// [`layout::device_hwctx`](super::layout::device_hwctx)) for output
/// surfaces of `width` x `height`.
pub fn new(display: Display, width: u32, height: u32) -> Result<Self, String> {
let va = Va::get()?;
let mut config = 0;
// SAFETY: a live display; no attributes; out pointer.
let status = unsafe {
(va.create_config)(
display,
PROFILE_NONE,
ENTRYPOINT_VIDEO_PROC,
std::ptr::null_mut(),
0,
&mut config,
)
};
va.check("no VA-API video processing", status)?;
let mut context = 0;
// SAFETY: the config just made; no render targets (surfaces are
// named per picture); out pointer.
let status = unsafe {
(va.create_context)(
display,
config,
width as c_int,
height as c_int,
PROGRESSIVE,
std::ptr::null_mut(),
0,
&mut context,
)
};
if let Err(e) = va.check("VA-API video processing context", status) {
// SAFETY: made above.
unsafe { (va.destroy_config)(display, config) };
return Err(e);
}
Ok(Self { va, display, config, context, width, height })
}
/// Convert the top-left `width` x `height` of RGB surface `input` into
/// NV12 surface `output` (both of this display): BT.601, limited range,
/// what the encoders signal and the CPU path ([`crate::convert`])
/// produces.
///
/// Returns once the GPU has read `input`, so a captured buffer can go
/// back to the compositor; `output` is ready for an encoder of the same
/// display, which orders its reads after this.
pub fn convert(&self, input: c_uint, output: c_uint) -> Result<(), String> {
let va = self.va;
let region = Rectangle { x: 0, y: 0, width: self.width as u16, height: self.height as u16 };
let mut parameters = PipelineParameters {
surface: input,
surface_region: &region,
output_region: &region,
output_background_color: 0xff00_0000,
output_color_standard: COLOR_STANDARD_BT601,
pipeline_flags: 0,
filter_flags: 0,
filters: std::ptr::null_mut(),
num_filters: 0,
forward_references: std::ptr::null_mut(),
num_forward_references: 0,
backward_references: std::ptr::null_mut(),
num_backward_references: 0,
rotation_state: 0,
blend_state: std::ptr::null(),
mirror_state: 0,
additional_outputs: std::ptr::null_mut(),
num_additional_outputs: 0,
input_surface_flag: 0,
output_surface_flag: 0,
// The input is described with the output's primaries and transfer,
// so the driver applies the matrix and nothing else, as the CPU
// path does. Left to itself (no standard, or sRGB) Mesa also
// converts the transfer function: measured on an RX 7900 GRE,
// grey 30 came out as Y 47 instead of 42, every dark pixel about
// 5 levels too bright.
surface_color_standard: COLOR_STANDARD_EXPLICIT,
input_color_properties: ColorProperties {
color_range: RANGE_FULL,
colour_primaries: SMPTE170M,
transfer_characteristics: SMPTE170M,
matrix_coefficients: MATRIX_IDENTITY,
..Default::default()
},
output_color_properties: ColorProperties {
color_range: RANGE_REDUCED,
..Default::default()
},
processing_mode: 0,
output_hdr_metadata: std::ptr::null_mut(),
reserved: Default::default(),
};
let (display, context) = (self.display, self.context);
// SAFETY: surfaces and context of this display; the parameters are
// copied by vaCreateBuffer (and the regions they point to live until
// vaEndPicture returns); the buffer is ours to destroy afterwards.
unsafe {
va.check("vaBeginPicture", (va.begin_picture)(display, context, output))?;
let mut buffer = 0;
let status = (va.create_buffer)(
display,
context,
PROC_PIPELINE_PARAMETER_BUFFER,
size_of::<PipelineParameters>() as c_uint,
1,
(&raw mut parameters).cast(),
&mut buffer,
);
let rendered = va.check("vaCreateBuffer", status).and_then(|()| {
va.check("vaRenderPicture", (va.render_picture)(display, context, &mut buffer, 1))
});
// A picture that was begun has to end, rendered or not.
let ended = va.check("vaEndPicture", (va.end_picture)(display, context));
if status == 0 {
(va.destroy_buffer)(display, buffer);
}
rendered?;
ended?;
va.check("vaSyncSurface", (va.sync_surface)(display, output))
}
}
}
impl Drop for Converter {
fn drop(&mut self) {
// SAFETY: made in `new` on this display, no longer used.
unsafe {
(self.va.destroy_context)(self.display, self.context);
(self.va.destroy_config)(self.display, self.config);
}
}
}
#[cfg(test)]
mod tests {
use std::mem::offset_of;
use super::*;
/// The mirror against `va/va_vpp.h` of libva 2.24 (x86-64), compiled.
#[cfg(target_pointer_width = "64")]
#[test]
fn pipeline_parameters_match_the_header() {
assert_eq!(size_of::<PipelineParameters>(), 224);
assert_eq!(offset_of!(PipelineParameters, output_color_standard), 36);
assert_eq!(offset_of!(PipelineParameters, rotation_state), 92);
assert_eq!(offset_of!(PipelineParameters, input_surface_flag), 124);
assert_eq!(offset_of!(PipelineParameters, input_color_properties), 132);
assert_eq!(offset_of!(PipelineParameters, output_color_properties), 140);
assert_eq!(offset_of!(PipelineParameters, processing_mode), 148);
assert_eq!(offset_of!(ColorProperties, color_range), 1);
}
}
+179 -17
View File
@@ -41,19 +41,21 @@ fn decoder(codec: Codec) -> Option<Box<dyn VideoDecoder>> {
}
}
/// Twelve frames of the moving test pattern, a keyframe forced at 8, a
/// bitrate change at 5: keyframes where asked, timestamps kept, and (with a
/// decoder) every picture decodable at PSNR > 28 dB.
fn roundtrip(name: &'static str) {
let screen = SyntheticScreen::new(W, H);
/// Twelve frames of the moving test pattern at `w` x `h`, a keyframe forced
/// at 8, a bitrate change at 5: keyframes where asked, timestamps kept, and
/// (with a decoder) every picture decodable at its own size, PSNR > 28 dB.
fn roundtrip(name: &'static str, w: u32, h: u32) {
let screen = SyntheticScreen::new(w, h);
let config = EncoderConfig { fps: 30, bitrate_bps: 1_500_000, ..EncoderConfig::default() };
let mut encoder = FfmpegEncoder::new(name, config).unwrap();
assert_eq!(encoder.backend(), EncoderBackend::Ffmpeg(name));
let (aw, ah) = probe().iter().find(|s| s.spec.name == name).unwrap().alignment;
let codec = encoder.codec();
let mut decoder = decoder(codec);
let mut keyframes = Vec::new();
let mut sent = Vec::new();
let mut decoded = 0;
let mut worst = f64::INFINITY;
let mut sources = Vec::new();
// Frames in until the first packet came out (the encoder's delay).
let mut delay = None;
@@ -81,15 +83,25 @@ fn roundtrip(name: &'static str) {
if let Some(decoder) = &mut decoder
&& let Some(picture) = decoder.decode(&f.data).unwrap()
{
assert_eq!((picture.width, picture.height), (W, H));
let psnr = convert::psnr(&sources[index], &picture).unwrap();
assert!(psnr > 28.0, "{name} frame {index}: PSNR {psnr:.1} dB");
// The top-left part the encoder's alignment allows, never
// padding (which the viewer would see).
let (pw, ph) = (picture.width, picture.height);
assert!(
pw <= w && ph <= h && w - pw < aw && h - ph < ah,
"{name}: {w}x{h} decoded as {pw}x{ph} (alignment {aw}x{ah})"
);
let mut source = sources[index].view();
(source.width, source.height) = (pw, ph);
let psnr = convert::psnr(&source.to_frame(), &picture).unwrap();
assert!(psnr > 28.0, "{name} {w}x{h} frame {index}: PSNR {psnr:.1} dB");
worst = worst.min(psnr);
decoded += 1;
}
}
}
eprintln!(
"{name}: {} packets from {} frames (first after {delay:?}), keyframes at {keyframes:?}, decoded {decoded}",
"{name} {w}x{h} (alignment {aw}x{ah}): {} packets from {} frames (first after \
{delay:?}), keyframes at {keyframes:?}, decoded {decoded}, lowest PSNR {worst:.1} dB",
sent.len(),
sources.len()
);
@@ -139,7 +151,7 @@ fn software_encoders_roundtrip() {
let mut tested = Vec::new();
for name in ["libx264", "libopenh264", "libsvtav1", "librav1e", "libaom-av1"] {
if available(name) {
roundtrip(name);
roundtrip(name, W, H);
tested.push(name);
} else {
eprintln!("{name} skipped: not available");
@@ -148,6 +160,40 @@ fn software_encoders_roundtrip() {
eprintln!("tested: {tested:?}");
}
/// What the GPU encoders produce, through the same round-trip as the
/// software ones: our own decoders have to decode it (OpenH264 for H.264 with
/// `VOELIN_OPENH264_LIB`, dav1d for AV1 with `--features av1`), keyframes
/// where asked, timestamps kept, PSNR above 28 dB.
///
/// Also at 1920x1080, which is not a whole number of 16-pixel macroblocks:
/// the H.264 SPS has to crop the 1088 coded rows, and AV1 has no cropping at
/// all, so a GPU that only encodes aligned sizes shows as a wrong decoded
/// size.
///
/// Whatever hardware the machine has; skipped where none of it works. HEVC is
/// left out, having no decoder here.
#[test]
fn hardware_encoders_roundtrip() {
if ffmpeg().is_none() {
return;
}
let names: Vec<&'static str> = BACKENDS
.iter()
.filter(|b| b.is_hardware() && matches!(b.codec, Codec::H264 | Codec::Av1))
.map(|b| b.name)
.filter(|name| available(name))
.collect();
if names.is_empty() {
eprintln!("no usable hardware encoder, skipped");
return;
}
for name in &names {
roundtrip(name, W, H);
roundtrip(name, 1920, 1080);
}
eprintln!("tested: {names:?}");
}
#[test]
fn x264_is_constrained_high_and_changes_size() {
if ffmpeg().is_none() || !available("libx264") {
@@ -183,11 +229,24 @@ fn x264_is_constrained_high_and_changes_size() {
/// `profile_idc` of the first SPS in an Annex B stream.
fn h264_profile(data: &[u8]) -> Option<u8> {
sps(data).map(|(profile, _, _)| profile)
}
/// `profile_idc`, the constraint-flag byte (`constraint_set0..5` in the top
/// six bits) and `level_idc` of the first SPS in an Annex B stream: the very
/// three bytes of `profile-level-id` in the SDP `a=fmtp` line.
///
/// They are the first three bytes of the SPS payload, so no bit reading is
/// needed. Emulation prevention cannot touch them either: it only ever
/// inserts a byte after two zeros, and no valid SPS starts
/// `profile_idc == 0`.
fn sps(data: &[u8]) -> Option<(u8, u8, u8)> {
let mut i = 0;
while i + 4 < data.len() {
while i + 3 < data.len() {
if data[i..i + 3] == [0, 0, 1] {
if data[i + 3] & 0x1f == 7 {
return data.get(i + 4).copied();
let p = data.get(i + 4..i + 7)?;
return Some((p[0], p[1], p[2]));
}
i += 3;
} else {
@@ -197,6 +256,92 @@ fn h264_profile(data: &[u8]) -> Option<u8> {
None
}
/// What every usable H.264 backend puts in the SPS against the
/// `profile-level-id` the signalling offers for the same stream. A decoder
/// set up from our offer must be able to decode what we send, so the
/// emitted `level_idc` may never exceed the offered one, and `profile_idc`
/// has to be the profile we claim.
///
/// The constraint-flag byte is only reported, not asserted: VA-API has no
/// Constrained High profile at all (`h264_vaapi` offers `main`, `high`,
/// `high10`, `constrained_baseline`), so it emits plain High with the flags
/// clear, while AMF's `constrained_high` sets `constraint_set4` and
/// `constraint_set5` as the offer says. See `docs/media.md`.
#[test]
fn sps_carries_the_offered_profile_and_level() {
use voelin_media::H264Profile;
if ffmpeg().is_none() {
return;
}
// 720p30 (offered level 3.1) and 1080p60 (4.2).
const CASES: [(u32, u32, u32, u32); 2] =
[(1280, 720, 30, 4_000_000), (1920, 1080, 60, 6_000_000)];
let mut tested = 0;
for status in probe().iter().filter(|s| s.available.is_ok()) {
if status.spec.codec != Codec::H264 {
continue;
}
for profile in [H264Profile::ConstrainedHigh, H264Profile::ConstrainedBaseline] {
let (offered_profile, want_idc) = match profile {
H264Profile::ConstrainedHigh => (voelin_stream::H264Profile::ConstrainedHigh, 100),
H264Profile::ConstrainedBaseline => {
(voelin_stream::H264Profile::ConstrainedBaseline, 66)
}
};
for (w, h, fps, bitrate) in CASES {
let config = EncoderConfig {
fps,
bitrate_bps: bitrate,
h264_profile: profile,
..EncoderConfig::default()
};
let mut encoder = FfmpegEncoder::new(status.spec.name, config).unwrap();
let screen = SyntheticScreen::new(w, h);
// Hardware encoders hold a frame or two before the first packet.
let mut packets = Vec::new();
for n in 0..8 {
packets.extend(encoder.encode(&screen.frame(n, fps), n == 0).unwrap());
if !packets.is_empty() {
break;
}
}
let Some(first) = packets.first() else {
panic!("{} produced no packet at {w}x{h}", status.spec.name)
};
let Some((idc, flags, level)) = sps(&first.data) else {
panic!("{} sent no SPS at {w}x{h}", status.spec.name)
};
let offered = voelin_stream::h264::offer_profile_level_id(
offered_profile,
w,
h,
fps,
u64::from(bitrate),
);
let offered_level = (offered & 0xff) as u8;
eprintln!(
"{:<12} {profile:?} {w}x{h}@{fps}: SPS {idc:02x} {flags:02x} {level:02x}, \
offer {:06x}",
status.spec.name, offered
);
assert_eq!(
idc, want_idc,
"{} emits profile_idc {idc}, the offer claims {want_idc}",
status.spec.name
);
assert!(
level <= offered_level,
"{} emits level_idc {level} at {w}x{h}@{fps}, above the offered {offered_level}: \
a decoder set up from our SDP could refuse it",
status.spec.name
);
tested += 1;
}
}
}
assert!(tested > 0, "no usable H.264 backend to check");
}
#[test]
fn codecs_prefer_ffmpeg_h264_over_nothing() {
if ffmpeg().is_none() || !available("libx264") {
@@ -255,29 +400,46 @@ fn bitrate_changes_without_live_reconfiguration() {
assert!(!key(&mut encoder, 6, false));
}
/// DMA-BUF import is for VA-API encoders and NV12 buffers; anything else is
/// refused as unavailable, so the caller maps the buffer instead.
/// DMA-BUF import is for VA-API encoders and NV12 or RGB buffers; anything
/// else is refused as unavailable, so the caller maps the buffer instead. A
/// buffer the driver cannot import is an error, not a crash: the encoder
/// takes the next frame, and drops cleanly although nothing went in (FFmpeg
/// 9's VA-API encoders crash when drained before their first frame).
#[cfg(target_os = "linux")]
#[test]
fn dmabuf_import_is_refused_cleanly() {
use std::os::fd::AsRawFd;
use voelin_media::capture::{DRM_MOD_LINEAR, DmaBufRef, drm_fourcc};
if ffmpeg().is_none() {
return;
}
let not_a_dmabuf = std::fs::File::open("/dev/null").unwrap();
let frame = DmaBufRef {
width: W,
height: H,
timestamp: Duration::ZERO,
fourcc: drm_fourcc(b"XR24"),
modifier: DRM_MOD_LINEAR,
fd: -1,
fd: not_a_dmabuf.as_raw_fd(),
size: (W * H * 4) as usize,
planes: [(0, (W * 4) as usize), (0, 0), (0, 0), (0, 0)],
plane_count: 1,
};
for name in ["libx264", "h264_vaapi"] {
let unavailable = |name: &str, frame: &DmaBufRef| {
let mut encoder = FfmpegEncoder::new(name, EncoderConfig::default()).unwrap();
let err = encoder.encode_dmabuf(&frame, true, &mut |_| {}).unwrap_err();
let err = encoder.encode_dmabuf(frame, true, &mut |_| {}).unwrap_err();
assert!(matches!(err, voelin_media::Error::CodecUnavailable { .. }), "{name}: {err}");
};
unavailable("libx264", &frame);
unavailable("h264_vaapi", &DmaBufRef { fourcc: drm_fourcc(b"YUYV"), ..frame });
if !available("h264_vaapi") {
return;
}
let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
assert!(encoder.encode_dmabuf(&frame, true, &mut |_| {}).is_err(), "/dev/null imported");
drop(encoder);
let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
assert!(encoder.encode_dmabuf(&frame, true, &mut |_| {}).is_err());
let black = voelin_media::VideoFrame::black_i420(W, H);
assert!(!encoder.encode(&black, true).unwrap().is_empty(), "no packet after a failed import");
}