🐎 Make a decode session's surfaces as its pictures need them
A VA-API decode session made its surface pool up front, its DPB, the picture and two spare, at the stream's coded size, and gave them to its context as render targets. A session whose pictures land in the device's caches decodes only its references into surfaces of its own, so it held surfaces no picture used. The pool now starts empty and the context is made with no render targets. The pool makes a surface when a picture is to be decoded into one of its own and none is free, up to 48, and lends the one freed last first. A kept context's shape no longer holds a surface count. Mesa's vlVaCreateContext reads no render target (read from code, Mesa 26.2.4), and surface::lazy's tests check the decision off the GPU and, on it, that streams of the driver's own encoder decode to the same pictures with surfaces made as needed as made up front. Measured with the process's DRM fdinfo, 8 surfaces at 1080p NV12, 4K NV12 and 4K P010: - radeonsi (Mesa 26.2.6; Radeon 780M, m3-max-64940; RX 7900 XTX, -64945) makes no buffer until a surface's first use: +0.0 MiB once made, then 31, 108 and 203 MiB on the 780M (41, 144, 279 on the XTX) once each held an image. Nothing changes there. - iHD 26.3.5 (Iris Xe, m3-max-64988) makes each surface's buffer object at its full size when the surface is made, +28, +96 and +192 MiB drm-total, and backs none of it until first use (drm-resident +0.0). A session no longer holds the objects of surfaces it never decodes into. - On Windows each surface made is a committed D3D12 resource (CreateCommittedResource in d3d12.rs's shared_texture, read from code), which allocates when it is made: a session whose pictures land in caches no longer holds its spare surfaces' memory there. Not measured. A make takes 0.001 ms or less on radeonsi and 0.004 ms on iHD. The first access unit, which holds the config, context and first surfaces, took the same time either way within the runs' spread on all three GPUs (H.264 1080p on the XTX 12.95 ms as needed, 13.18 up front), with two or three surfaces made as needed against five up front. Nothing changes for the guest: the device's answers, the pictures and their order are the same.
This commit is contained in:
1 parent
b8907d46d9
commit
ff96c37f07
9 files changed
+735
-82
No files matched your search
@@ -18,7 +18,7 @@ use crate::core::sync::MutexGuard;
|
||||
use super::display::{Display, Error, Teardown, check};
|
||||
use super::ffi;
|
||||
use super::ffi::encode as enc;
|
||||
use super::surface::{SurfaceFormat, SurfacePool};
|
||||
use super::surface::{SurfaceFormat, SurfacePool, made_with_context};
|
||||
|
||||
/// A `VAProfile`. Drivers may report profiles newer than this crate, so
|
||||
/// any value is kept, and [`Profile::name`] names the ones va.h 1.24 has.
|
||||
@@ -686,7 +686,7 @@ pub(crate) struct Context {
|
||||
|
||||
/// What a decoder's context is made of and for, which decides whether a context kept on
|
||||
/// Windows is taken back for it ([`Context::new_decoder`]): its config's profile and its
|
||||
/// attributes' types and values, in the order given, the format, size and number of its pool's
|
||||
/// attributes' types and values, in the order given, the format and size of its pool's
|
||||
/// surfaces, and the references its decoder is sized by.
|
||||
#[cfg(windows)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -696,7 +696,6 @@ pub(crate) struct ContextShape {
|
||||
format: SurfaceFormat,
|
||||
width: u32,
|
||||
height: u32,
|
||||
surfaces: usize,
|
||||
references: u32,
|
||||
}
|
||||
|
||||
@@ -773,15 +772,18 @@ impl Context {
|
||||
}
|
||||
|
||||
/// A decoder's context, on a config of `profile`, the entrypoint `VLD` and `attribs`, and
|
||||
/// the pool of `surfaces` surfaces of `format`, `width` by `height`, that it decodes into,
|
||||
/// its render targets. On Windows the context is kept on drop, with its config and its pool,
|
||||
/// while another context lives on the display, and taken back, with them, by a decoder of
|
||||
/// its shape (`ContextShape`): the same profile and attributes, the same format, size and
|
||||
/// number of surfaces, and the same `references`, the count the picture parameters carry
|
||||
/// the pool of surfaces of `format`, `width` by `height`, that its decoder decodes into. The
|
||||
/// pool makes no surface until a picture needs one (`SurfacePool::get`), so the context has
|
||||
/// no render targets, and a decoder whose every picture is decoded into a target over the
|
||||
/// caller's memory makes no surface at all. On Windows the context is kept on drop, with its
|
||||
/// config and its pool, while another context lives on the display, and taken back, with
|
||||
/// them, by a decoder of its shape (`ContextShape`): the same profile and attributes, the
|
||||
/// same format and size, and the same `references`, the count the picture parameters carry
|
||||
/// that the driver sizes its decoder by (H.264's `num_ref_frames`, HEVC's
|
||||
/// `sps_max_dec_pic_buffering_minus1`). So beside a live context a decoder of a shape kept
|
||||
/// makes no config, pool or context, and one let go destroys none
|
||||
/// ([`Display::release_teardown`]).
|
||||
/// ([`Display::release_teardown`]); a pool taken back holds the surfaces its last decoder
|
||||
/// made, and makes more as a picture needs one.
|
||||
///
|
||||
/// **Measured** on the UHD Graphics 630 (vaon12 of Mesa 26.2.7 over Intel's Direct3D 12
|
||||
/// video driver, 2026-11-20; `super::teardown`'s churn test, beside a 4K H.264 decoder that
|
||||
@@ -801,7 +803,6 @@ impl Context {
|
||||
attribs: &mut [ffi::VAConfigAttrib],
|
||||
format: SurfaceFormat,
|
||||
(width, height): (u32, u32),
|
||||
surfaces: usize,
|
||||
references: u32,
|
||||
) -> Result<(Self, SurfacePool), Error> {
|
||||
#[cfg(windows)]
|
||||
@@ -811,7 +812,6 @@ impl Context {
|
||||
format,
|
||||
width,
|
||||
height,
|
||||
surfaces,
|
||||
references,
|
||||
};
|
||||
#[cfg(windows)]
|
||||
@@ -829,7 +829,7 @@ impl Context {
|
||||
#[cfg(unix)]
|
||||
let _ = references;
|
||||
let config = Config::new(display, profile, Entrypoint::VLD, attribs)?;
|
||||
let pool = SurfacePool::new(display, format, width, height, surfaces)?;
|
||||
let pool = SurfacePool::new(display, format, width, height, made_with_context())?;
|
||||
let mut targets = pool.ids();
|
||||
#[cfg_attr(unix, allow(unused_mut))]
|
||||
let mut context = Self::new(display, config, width, height, &mut targets)?;
|
||||
|
||||
@@ -16,10 +16,6 @@ use crate::codec::h264::{
|
||||
SliceParams, slice::SliceType, sps::Sps,
|
||||
};
|
||||
|
||||
/// Surfaces a pool makes beyond the DPB and the current picture, so that
|
||||
/// a frame the caller still holds does not stall the next decode.
|
||||
const SPARE_SURFACES: usize = 2;
|
||||
|
||||
/// The most macroblocks of an H.264 picture the decoder takes: iHD and
|
||||
/// radeonsi answer 4096x4096 as their largest H.264 decode, yet decode
|
||||
/// nothing of a picture of 65,536 (256 by 256), every call answering
|
||||
@@ -37,10 +33,11 @@ pub struct H264Decoder {
|
||||
}
|
||||
|
||||
impl H264Decoder {
|
||||
/// The frames a caller may hold at once, beyond those the decoder holds
|
||||
/// itself, before a decode finds no free surface (`Error::OutOfSurfaces`):
|
||||
/// the pool's spare surfaces.
|
||||
pub const SPARE_FRAMES: usize = SPARE_SURFACES;
|
||||
/// The frames a caller is to hold at once, beyond those the decoder holds itself. The
|
||||
/// decoder's pool makes a surface for a picture as it needs one, whether the DPB, the
|
||||
/// caller or the picture being decoded holds it, up to a bound past which a decode finds no
|
||||
/// free surface (`Error::OutOfSurfaces`).
|
||||
pub const SPARE_FRAMES: usize = 2;
|
||||
|
||||
/// A decoder for samples described by an `avcC` record (ISO/IEC
|
||||
/// 14496-15, 5.3.3.1), whose parameter sets it takes. The record's
|
||||
@@ -120,6 +117,13 @@ impl H264Decoder {
|
||||
self.inner.accelerator().session.as_ref().map(|s| s.profile)
|
||||
}
|
||||
|
||||
/// How many surfaces of its own the decoder's session made, once it has started a picture.
|
||||
#[cfg(test)]
|
||||
pub(super) fn surfaces_made(&self) -> Option<usize> {
|
||||
let session = self.inner.accelerator().session.as_ref()?;
|
||||
Some(session.pool.made())
|
||||
}
|
||||
|
||||
/// The VA context the decoder's session decodes on, once it has started a picture.
|
||||
#[cfg(test)]
|
||||
pub(super) fn context_id(&self) -> Option<ffi::VAContextID> {
|
||||
@@ -269,7 +273,7 @@ impl Accelerator for VaH264 {
|
||||
type Picture = Surface;
|
||||
type Error = Error;
|
||||
|
||||
fn configure(&mut self, sps: &Sps, dpb_frames: usize) -> Result<(), Error> {
|
||||
fn configure(&mut self, sps: &Sps, _dpb_frames: usize) -> Result<(), Error> {
|
||||
self.session = None;
|
||||
let profile = select_profile(&self.display, sps)?;
|
||||
let (width, height) = (sps.coded_width(), sps.coded_height());
|
||||
@@ -285,7 +289,6 @@ impl Accelerator for VaH264 {
|
||||
&mut attribs,
|
||||
SurfaceFormat::Nv12,
|
||||
(width, height),
|
||||
dpb_frames + 1 + SPARE_SURFACES,
|
||||
references,
|
||||
)?;
|
||||
self.session = Some(Session {
|
||||
|
||||
@@ -20,10 +20,6 @@ use crate::codec::hevc::{
|
||||
sps::Sps,
|
||||
};
|
||||
|
||||
/// Surfaces a pool makes beyond the DPB and the current picture, so that
|
||||
/// a frame the caller still holds does not stall the next decode.
|
||||
const SPARE_SURFACES: usize = 2;
|
||||
|
||||
/// An entry of `RefPicList[][]` that names no picture (va_dec_hevc.h).
|
||||
const NO_REFERENCE: u8 = 0xff;
|
||||
|
||||
@@ -46,10 +42,11 @@ pub struct HevcDecoder {
|
||||
}
|
||||
|
||||
impl HevcDecoder {
|
||||
/// The frames a caller may hold at once, beyond those the decoder holds
|
||||
/// itself, before a decode finds no free surface (`Error::OutOfSurfaces`):
|
||||
/// the pool's spare surfaces.
|
||||
pub const SPARE_FRAMES: usize = SPARE_SURFACES;
|
||||
/// The frames a caller is to hold at once, beyond those the decoder holds itself. The
|
||||
/// decoder's pool makes a surface for a picture as it needs one, whether the DPB, the
|
||||
/// caller or the picture being decoded holds it, up to a bound past which a decode finds no
|
||||
/// free surface (`Error::OutOfSurfaces`).
|
||||
pub const SPARE_FRAMES: usize = 2;
|
||||
|
||||
/// A decoder for samples described by an `hvcC` record (ISO/IEC
|
||||
/// 14496-15, 8.3.3.1), whose parameter sets it takes. The record's
|
||||
@@ -132,6 +129,13 @@ impl HevcDecoder {
|
||||
pub fn profile(&self) -> Option<Profile> {
|
||||
self.inner.accelerator().session.as_ref().map(|s| s.profile)
|
||||
}
|
||||
|
||||
/// How many surfaces of its own the decoder's session made, once it has started a picture.
|
||||
#[cfg(test)]
|
||||
pub(super) fn surfaces_made(&self) -> Option<usize> {
|
||||
let session = self.inner.accelerator().session.as_ref()?;
|
||||
Some(session.pool.made())
|
||||
}
|
||||
}
|
||||
|
||||
// Decoders move between threads: libva is thread-safe (va.h,
|
||||
@@ -256,7 +260,7 @@ impl Accelerator for VaHevc {
|
||||
type Picture = Surface;
|
||||
type Error = Error;
|
||||
|
||||
fn configure(&mut self, sps: &Sps, dpb_size: usize) -> Result<(), Error> {
|
||||
fn configure(&mut self, sps: &Sps, _dpb_size: usize) -> Result<(), Error> {
|
||||
self.session = None;
|
||||
let profile = select_profile(&self.display, sps)?;
|
||||
let (_, format) = profile_for(sps);
|
||||
@@ -276,7 +280,6 @@ impl Accelerator for VaHevc {
|
||||
&mut attribs,
|
||||
format,
|
||||
(width, height),
|
||||
dpb_size + 1 + SPARE_SURFACES,
|
||||
references,
|
||||
)?;
|
||||
self.session = Some(Session {
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
//! one at a time, and their readback into caller-provided planes. 8-bit
|
||||
//! 4:2:0 is NV12, and 10-bit 4:2:0 is P010.
|
||||
//!
|
||||
//! A pool makes a surface only when one is asked of it and none is free
|
||||
//! ([`SurfacePool::get`]), so it holds no more surfaces than were lent at
|
||||
//! once: a decoder's pool starts with none (`Context::new_decoder`), and one
|
||||
//! whose every picture is decoded into a target over the caller's memory
|
||||
//! ([`SurfacePool::lend_target`]) makes none.
|
||||
//!
|
||||
//! A frame's wait for its decode, and the staged copy back's run after it,
|
||||
//! end at one deadline (`super::wait`). Past it the pool is stalled: that
|
||||
//! frame fails, each later frame of the pool, and each surface asked of it,
|
||||
@@ -34,6 +40,8 @@ use super::target::{Target, TargetFormat, TargetShape};
|
||||
use super::vpp_ffi as vpp;
|
||||
use super::wait::{self, Unfinished, Work};
|
||||
|
||||
#[cfg(test)]
|
||||
mod lazy;
|
||||
#[cfg(test)]
|
||||
#[cfg(windows)]
|
||||
mod shared;
|
||||
@@ -132,12 +140,34 @@ struct PoolInner {
|
||||
textures: Mutex<Vec<(ffi::VASurfaceID, Arc<SharedTexture>)>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct PoolState {
|
||||
/// Every surface the pool made, lent or not.
|
||||
all: Vec<ffi::VASurfaceID>,
|
||||
free: Vec<ffi::VASurfaceID>,
|
||||
}
|
||||
|
||||
impl PoolState {
|
||||
/// A surface to lend: the one freed last, where one is free; else one `make` makes, given
|
||||
/// how many the pool made before it, where that is fewer than [`MAX_SURFACES`]; else
|
||||
/// [`Error::OutOfSurfaces`]. A surface made is the pool's from then on; a make that fails
|
||||
/// leaves the pool as it was.
|
||||
fn take_or_make(
|
||||
&mut self,
|
||||
make: impl FnOnce(usize) -> Result<ffi::VASurfaceID, Error>,
|
||||
) -> Result<ffi::VASurfaceID, Error> {
|
||||
if let Some(id) = self.free.pop() {
|
||||
return Ok(id);
|
||||
}
|
||||
if self.all.len() >= MAX_SURFACES {
|
||||
return Err(Error::OutOfSurfaces);
|
||||
}
|
||||
let id = make(self.all.len())?;
|
||||
self.all.push(id);
|
||||
Ok(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// How frames are read back (`super::readback`): staged through host
|
||||
/// memory, through an image of the pool's format and size that
|
||||
/// `vaGetImage` fills, or by `vaDeriveImage` where the driver cannot; each
|
||||
@@ -174,7 +204,8 @@ impl Drop for PoolInner {
|
||||
}
|
||||
|
||||
impl SurfacePool {
|
||||
/// Makes `count` surfaces of `format`, `width` by `height`.
|
||||
/// A pool of surfaces of `format`, `width` by `height`, with `count` of them made now: none
|
||||
/// for a pool that makes each as it is asked for one ([`Self::get`]).
|
||||
pub(crate) fn new(
|
||||
display: &Display,
|
||||
format: SurfaceFormat,
|
||||
@@ -187,10 +218,7 @@ impl SurfacePool {
|
||||
format,
|
||||
width,
|
||||
height,
|
||||
state: Mutex::new(PoolState {
|
||||
all: Vec::new(),
|
||||
free: Vec::new(),
|
||||
}),
|
||||
state: Mutex::new(PoolState::default()),
|
||||
readback: Mutex::new(Readback::Unknown),
|
||||
times: Mutex::new(ReadbackTimes::default()),
|
||||
#[cfg(unix)]
|
||||
@@ -201,11 +229,11 @@ impl SurfacePool {
|
||||
#[cfg(windows)]
|
||||
textures: Mutex::new(Vec::new()),
|
||||
});
|
||||
#[cfg(unix)]
|
||||
let made = create_surfaces(display, format, width, height, count)?;
|
||||
#[cfg(windows)]
|
||||
let made = shared_surfaces(&inner, count)?;
|
||||
{
|
||||
if count > 0 {
|
||||
#[cfg(unix)]
|
||||
let made = create_surfaces(display, format, width, height, count)?;
|
||||
#[cfg(windows)]
|
||||
let made = shared_surfaces(&inner, count)?;
|
||||
let mut state = inner.state.lock();
|
||||
state.all.extend(&made);
|
||||
state.free.extend(made.iter().rev());
|
||||
@@ -218,32 +246,32 @@ impl SurfacePool {
|
||||
self.inner.state.lock().all.clone()
|
||||
}
|
||||
|
||||
/// A free surface, making one more when none is free; none from a
|
||||
/// stalled pool.
|
||||
/// How many surfaces the pool made, lent or not.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn made(&self) -> usize {
|
||||
self.inner.state.lock().all.len()
|
||||
}
|
||||
|
||||
/// A free surface, making one more when none is free (`PoolState::take_or_make`); none from
|
||||
/// a stalled pool.
|
||||
pub(crate) fn get(&self) -> Result<Surface, Error> {
|
||||
self.inner.stalled()?;
|
||||
let mut state = self.inner.state.lock();
|
||||
let id = match state.free.pop() {
|
||||
Some(id) => id,
|
||||
None => {
|
||||
if state.all.len() >= MAX_SURFACES {
|
||||
return Err(Error::OutOfSurfaces);
|
||||
}
|
||||
let inner = &self.inner;
|
||||
#[cfg(unix)]
|
||||
let made =
|
||||
create_surfaces(&inner.display, inner.format, inner.width, inner.height, 1)?;
|
||||
// On Windows, of the kind the pool was made of.
|
||||
#[cfg(windows)]
|
||||
let made = if inner.textures.lock().is_empty() {
|
||||
create_surfaces(&inner.display, inner.format, inner.width, inner.height, 1)?
|
||||
} else {
|
||||
shared_surfaces(inner, 1)?
|
||||
};
|
||||
state.all.extend(&made);
|
||||
made[0]
|
||||
}
|
||||
};
|
||||
let inner = &self.inner;
|
||||
let id = inner.state.lock().take_or_make(|made_before| {
|
||||
#[cfg(unix)]
|
||||
let _ = made_before;
|
||||
#[cfg(unix)]
|
||||
let made = create_surfaces(&inner.display, inner.format, inner.width, inner.height, 1)?;
|
||||
// On Windows, of the kind the pool's first surface is: shared where it could be made
|
||||
// so, else the driver's own (`shared_surfaces`).
|
||||
#[cfg(windows)]
|
||||
let made = if made_before == 0 || !inner.textures.lock().is_empty() {
|
||||
shared_surfaces(inner, 1)?
|
||||
} else {
|
||||
create_surfaces(&inner.display, inner.format, inner.width, inner.height, 1)?
|
||||
};
|
||||
Ok(made[0])
|
||||
})?;
|
||||
Ok(Surface {
|
||||
id,
|
||||
pool: self.inner.clone(),
|
||||
@@ -330,6 +358,25 @@ thread_local! {
|
||||
/// memory of the test's own (`super::target_probe`), in place of one the driver allocates.
|
||||
pub(crate) static MAKE_SURFACE: std::cell::RefCell<Option<MakeSurface>> =
|
||||
const { std::cell::RefCell::new(None) };
|
||||
|
||||
/// The surfaces a decoder's pool made on this thread makes with its context, which are the
|
||||
/// context's render targets, for tests that compare such a pool with one that makes each
|
||||
/// surface as a picture needs one: none where unset, as for every decoder's pool
|
||||
/// ([`made_with_context`]).
|
||||
pub(crate) static UP_FRONT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The surfaces a decoder's pool makes with its context (`Context::new_decoder`): none, each
|
||||
/// made as a picture needs one ([`SurfacePool::get`]); in tests, as many as `UP_FRONT` says.
|
||||
pub(crate) fn made_with_context() -> usize {
|
||||
#[cfg(test)]
|
||||
{
|
||||
UP_FRONT.with(std::cell::Cell::get)
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
fn create_surfaces(
|
||||
|
||||
@@ -0,0 +1,521 @@
|
||||
//! Pools that make each surface as it is asked for one (`super::SurfacePool::get`): the decision
|
||||
//! itself, off the GPU, and decoders' pools on it.
|
||||
//!
|
||||
//! Off the GPU, `PoolState::take_or_make`: a pool makes a surface only when one is asked of it
|
||||
//! and none is free, lends the one freed last first, and makes no more than `MAX_SURFACES`; a
|
||||
//! decoder's pool makes none with its context.
|
||||
//!
|
||||
//! On the GPU, run on a VA-API host holding its GPU: on Windows on the adapter libva-win32 opens
|
||||
//! first, elsewhere on the render node `RVG_VAAPI_NODE` names (`/dev/dri/renderD128` where it is
|
||||
//! unset).
|
||||
//! - A pool's surfaces are made one at a time, each lent again once freed, with how long one
|
||||
//! surface's make takes printed for 1080p NV12 and 4K NV12 and P010, beside a pool's count made
|
||||
//! at once, and on Linux what the process's GPU memory grew by once they are made and once each
|
||||
//! holds an image (`vaPutImage`).
|
||||
//! - Streams of the driver's own encoder (H.264, HEVC Main and Main 10, at 1080p and 4K, each
|
||||
//! where the driver encodes it) decode to the same pictures with the decoder's surfaces made
|
||||
//! as pictures need them, its context given no render target, as with them made up front as
|
||||
//! the context's render targets (`super::UP_FRONT`: the DPB, the picture and two spare, the
|
||||
//! count decoders made before), and make no more of them. Each way's first picture's time,
|
||||
//! which holds the decoder's config, context and first surfaces, and its later pictures', are
|
||||
//! printed.
|
||||
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::codec::encode::{EncoderSettings, InputFrame, Plane, Profile as Encoded};
|
||||
use crate::core::runtime::{Runtime as _, StdRuntime};
|
||||
use crate::vaapi::va::display::{Display, Error};
|
||||
use crate::vaapi::va::encoder::VideoEncoder;
|
||||
use crate::vaapi::va::frame::{Frame, PlaneRows};
|
||||
use crate::vaapi::va::teardown::display;
|
||||
use crate::vaapi::va::{H264Decoder, HevcDecoder};
|
||||
|
||||
use super::{MAX_SURFACES, PoolState, Surface, SurfaceFormat, SurfacePool, UP_FRONT};
|
||||
|
||||
#[test]
|
||||
fn a_decoders_pool_makes_no_surface_with_its_context() {
|
||||
assert_eq!(super::made_with_context(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pool_makes_a_surface_only_when_one_is_asked_for_and_none_is_free() {
|
||||
let mut state = PoolState::default();
|
||||
let mut made = 0;
|
||||
let first = state
|
||||
.take_or_make(|before| {
|
||||
assert_eq!(before, 0);
|
||||
made += 1;
|
||||
Ok(10)
|
||||
})
|
||||
.expect("a surface");
|
||||
assert_eq!((first, made), (10, 1));
|
||||
assert_eq!(state.all, [10]);
|
||||
state.free.push(first);
|
||||
let again = state
|
||||
.take_or_make(|_| panic!("a surface made while one is free"))
|
||||
.expect("a surface");
|
||||
assert_eq!(again, 10);
|
||||
assert_eq!(state.all, [10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_surface_freed_last_is_lent_first() {
|
||||
let mut state = PoolState::default();
|
||||
for id in 1..=3 {
|
||||
state.take_or_make(|_| Ok(id)).expect("a surface");
|
||||
}
|
||||
state.free.extend([1, 3, 2]);
|
||||
let lent: Vec<_> = (0..3)
|
||||
.map(|_| {
|
||||
(state.take_or_make(|_| panic!("a surface made while one is free"))).expect("a surface")
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(lent, [2, 3, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pool_makes_no_more_than_max_surfaces() {
|
||||
let mut state = PoolState::default();
|
||||
for n in 0..MAX_SURFACES {
|
||||
let id = u32::try_from(n).expect("an id") + 1;
|
||||
state
|
||||
.take_or_make(|before| {
|
||||
assert_eq!(before, n);
|
||||
Ok(id)
|
||||
})
|
||||
.expect("a surface");
|
||||
}
|
||||
let past = state.take_or_make(|_| panic!("a surface made past the bound"));
|
||||
assert!(matches!(past, Err(Error::OutOfSurfaces)), "{past:?}");
|
||||
state.free.push(7);
|
||||
let freed = state.take_or_make(|_| panic!("a surface made while one is free"));
|
||||
assert_eq!(freed.expect("the one freed"), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_make_leaves_the_pool_as_it_was() {
|
||||
let mut state = PoolState::default();
|
||||
let failed = state.take_or_make(|_| Err(Error::Unsupported("no memory".into())));
|
||||
assert!(matches!(failed, Err(Error::Unsupported(_))), "{failed:?}");
|
||||
assert!(state.all.is_empty() && state.free.is_empty());
|
||||
}
|
||||
|
||||
/// Surfaces lent and freed in any order, as a decode's pictures, its DPB's and the caller's
|
||||
/// frames take and let go of them: the pool holds as many as were lent at once, at most.
|
||||
#[test]
|
||||
fn a_pool_holds_no_more_surfaces_than_were_lent_at_once() {
|
||||
let mut state = PoolState::default();
|
||||
let mut lent = Vec::new();
|
||||
let mut most = 0;
|
||||
let mut next = 0;
|
||||
let mut seed = 0x2545_f491_4f6c_dd1d_u64;
|
||||
for _ in 0..10_000 {
|
||||
seed ^= seed << 13;
|
||||
seed ^= seed >> 7;
|
||||
seed ^= seed << 17;
|
||||
if lent.is_empty() || (seed % 2 == 0 && lent.len() < MAX_SURFACES) {
|
||||
let id = state
|
||||
.take_or_make(|_| {
|
||||
next += 1;
|
||||
Ok(next)
|
||||
})
|
||||
.expect("a surface");
|
||||
assert!(!lent.contains(&id), "surface {id} lent twice");
|
||||
lent.push(id);
|
||||
most = most.max(lent.len());
|
||||
} else {
|
||||
let at = usize::try_from(seed >> 8).expect("an index") % lent.len();
|
||||
state.free.push(lent.swap_remove(at));
|
||||
}
|
||||
assert_eq!(state.all.len(), most);
|
||||
}
|
||||
}
|
||||
|
||||
/// The surfaces each make is timed for.
|
||||
const COUNT: usize = 8;
|
||||
|
||||
/// A make's time in milliseconds.
|
||||
fn ms(time: Duration) -> f64 {
|
||||
time.as_secs_f64() * 1e3
|
||||
}
|
||||
|
||||
/// The GPU memory this process's DRM clients hold, in MiB, each client once: what their objects
|
||||
/// take (each client's `drm-total-*` sizes in `/proc/self/fdinfo`, or its `drm-memory-*` sizes
|
||||
/// where it gives none), and what of that is resident (`drm-resident-*`, or the same where it
|
||||
/// gives none); `None` off Linux, or where no client gives either.
|
||||
fn gpu_memory_mib() -> Option<[f64; 2]> {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let mut clients = std::collections::HashSet::new();
|
||||
let mut kib = [0; 2];
|
||||
let mut any = false;
|
||||
for entry in std::fs::read_dir("/proc/self/fdinfo").ok()?.flatten() {
|
||||
let Ok(text) = std::fs::read_to_string(entry.path()) else {
|
||||
continue;
|
||||
};
|
||||
let mut lines = text.lines();
|
||||
let client = lines.find_map(|line| line.strip_prefix("drm-client-id:"));
|
||||
if !client.is_some_and(|id| clients.insert(id.trim().to_owned())) {
|
||||
continue;
|
||||
}
|
||||
let mut total = sizes(&text, "drm-total-");
|
||||
if total.is_empty() {
|
||||
total = sizes(&text, "drm-memory-");
|
||||
}
|
||||
let mut resident = sizes(&text, "drm-resident-");
|
||||
if resident.is_empty() {
|
||||
resident.clone_from(&total);
|
||||
}
|
||||
any |= !total.is_empty();
|
||||
kib[0] += total.iter().sum::<u64>();
|
||||
kib[1] += resident.iter().sum::<u64>();
|
||||
}
|
||||
any.then_some(kib.map(|kib| kib as f64 / 1024.0))
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
None
|
||||
}
|
||||
|
||||
/// The sizes, in KiB, of the lines of an fdinfo `text` whose keys start with `prefix`.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn sizes(text: &str, prefix: &str) -> Vec<u64> {
|
||||
let mut sizes = Vec::new();
|
||||
for line in text.lines() {
|
||||
let Some((key, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let mut words = value.split_whitespace();
|
||||
let Some(Ok(n)) = words.next().map(str::parse::<u64>) else {
|
||||
continue;
|
||||
};
|
||||
if key.starts_with(prefix) {
|
||||
sizes.push(match words.next() {
|
||||
Some("KiB") => n,
|
||||
Some("MiB") => n << 10,
|
||||
Some("GiB") => n << 20,
|
||||
_ => n >> 10,
|
||||
});
|
||||
}
|
||||
}
|
||||
sizes
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs a VA-API GPU: run on the VA-API host"]
|
||||
fn surfaces_are_made_one_at_a_time_and_lent_again_once_freed() {
|
||||
let display = display();
|
||||
for (width, height, format) in [
|
||||
(1920, 1088, SurfaceFormat::Nv12),
|
||||
(3840, 2160, SurfaceFormat::Nv12),
|
||||
(3840, 2160, SurfaceFormat::P010),
|
||||
] {
|
||||
let name = format!("{} {width}x{height}", format.name());
|
||||
let pool = SurfacePool::new(&display, format, width, height, 0).expect("a pool");
|
||||
assert_eq!(pool.made(), 0, "{name}");
|
||||
let image = super::create_image(&display, format, width, height).expect("an image");
|
||||
let before = gpu_memory_mib();
|
||||
let mut held = Vec::new();
|
||||
let mut times = Vec::new();
|
||||
for n in 1..=COUNT {
|
||||
let start = StdRuntime.now();
|
||||
held.push(pool.get().expect("a surface"));
|
||||
times.push(StdRuntime.now().saturating_duration_since(start));
|
||||
assert_eq!(pool.made(), n, "{name}");
|
||||
}
|
||||
let made = gpu_memory_mib();
|
||||
for surface in &held {
|
||||
image
|
||||
.put_into(surface.id(), width, height)
|
||||
.expect("vaPutImage");
|
||||
}
|
||||
let used = gpu_memory_mib();
|
||||
if let (Some(before), Some(made), Some(used)) = (before, made, used) {
|
||||
eprintln!(
|
||||
"{name}: the process's GPU memory (DRM fdinfo, total/resident) {:+.1}/{:+.1} MiB \
|
||||
once {COUNT} are made, {:+.1}/{:+.1} MiB once an image is put into each",
|
||||
made[0] - before[0],
|
||||
made[1] - before[1],
|
||||
used[0] - before[0],
|
||||
used[1] - before[1],
|
||||
);
|
||||
}
|
||||
drop(image);
|
||||
let mut ids: Vec<_> = held.iter().map(Surface::id).collect();
|
||||
held.clear();
|
||||
let again: Vec<_> = (0..COUNT).map(|_| pool.get().expect("a surface")).collect();
|
||||
assert_eq!(pool.made(), COUNT, "{name}: made again once freed");
|
||||
let mut lent: Vec<_> = again.iter().map(Surface::id).collect();
|
||||
ids.sort_unstable();
|
||||
lent.sort_unstable();
|
||||
assert_eq!(ids, lent, "{name}");
|
||||
drop(again);
|
||||
drop(pool);
|
||||
let start = StdRuntime.now();
|
||||
let batch = SurfacePool::new(&display, format, width, height, COUNT).expect("a pool");
|
||||
let at_once = StdRuntime.now().saturating_duration_since(start);
|
||||
drop(batch);
|
||||
let first = times[0];
|
||||
times.sort_unstable();
|
||||
eprintln!(
|
||||
"{name}: one surface made in {:.3} ms (median), {:.3} to {:.3} ms, the first {:.3} \
|
||||
ms; {COUNT} made at once in {:.3} ms",
|
||||
ms(times[COUNT / 2]),
|
||||
ms(times[0]),
|
||||
ms(times[COUNT - 1]),
|
||||
ms(first),
|
||||
ms(at_once),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The pictures each stream holds.
|
||||
const PICTURES: u64 = 30;
|
||||
|
||||
/// The rounds each way decodes a stream in.
|
||||
const ROUNDS: usize = 3;
|
||||
|
||||
/// `PICTURES` pictures of a gradient moving a few samples a picture, `size`, by the driver's
|
||||
/// encoder of `profile`: its configuration record and samples; `None` where the driver encodes
|
||||
/// no such stream.
|
||||
fn encoded(
|
||||
display: &Display,
|
||||
profile: Encoded,
|
||||
size: (u32, u32),
|
||||
) -> Option<(Vec<u8>, Vec<Vec<u8>>)> {
|
||||
let mut encoder =
|
||||
VideoEncoder::new(display, EncoderSettings::new(profile, size.0, size.1)).ok()?;
|
||||
let (w, h) = (size.0 as usize, size.1 as usize);
|
||||
let sample = if profile == Encoded::HevcMain10 { 2 } else { 1 };
|
||||
let mut samples = Vec::new();
|
||||
for n in 0..PICTURES {
|
||||
let shift = usize::try_from(n).expect("a shift") * 3;
|
||||
let mut bytes = vec![0u8; w * h * 3 / 2 * sample];
|
||||
for (i, chunk) in bytes.chunks_exact_mut(sample).enumerate() {
|
||||
let (x, y) = (i % w, i / w);
|
||||
let value = ((x + shift) * 3 + y * 5 + (x * y) % 7) as u8;
|
||||
match chunk {
|
||||
[b] => *b = value,
|
||||
[low, high] => (*low, *high) = (0, value),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let (luma, chroma) = bytes.split_at(w * h * sample);
|
||||
let frame = InputFrame {
|
||||
planes: [
|
||||
Plane {
|
||||
data: luma,
|
||||
bytes_per_row: w * sample,
|
||||
},
|
||||
Plane {
|
||||
data: chroma,
|
||||
bytes_per_row: w * sample,
|
||||
},
|
||||
],
|
||||
pts: i64::try_from(n).expect("a time") * 3000,
|
||||
duration: 3000,
|
||||
force_key_frame: false,
|
||||
id: n,
|
||||
};
|
||||
let coded = encoder.encode(&frame).ok()?;
|
||||
samples.extend(coded.into_iter().map(|c| c.expect("a sample").data));
|
||||
}
|
||||
samples.extend(
|
||||
encoder
|
||||
.flush()
|
||||
.into_iter()
|
||||
.map(|c| c.expect("a sample").data),
|
||||
);
|
||||
Some((encoder.configuration().to_vec(), samples))
|
||||
}
|
||||
|
||||
/// A decoder of one of the encoded streams.
|
||||
enum Decoding {
|
||||
H264(H264Decoder),
|
||||
Hevc(HevcDecoder),
|
||||
}
|
||||
|
||||
impl Decoding {
|
||||
fn new(display: &Display, profile: Encoded, record: &[u8]) -> Self {
|
||||
match profile {
|
||||
Encoded::HevcMain | Encoded::HevcMain10 => {
|
||||
Self::Hevc(HevcDecoder::new(display, record).expect("a decoder"))
|
||||
}
|
||||
_ => Self::H264(H264Decoder::new(display, record).expect("a decoder")),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(&mut self, sample: &[u8], id: u64) -> Vec<Frame> {
|
||||
match self {
|
||||
Self::H264(decoder) => decoder.decode(sample, id),
|
||||
Self::Hevc(decoder) => decoder.decode(sample, id),
|
||||
}
|
||||
.expect("a decode")
|
||||
}
|
||||
|
||||
fn surfaces_made(&self) -> usize {
|
||||
match self {
|
||||
Self::H264(decoder) => decoder.surfaces_made(),
|
||||
Self::Hevc(decoder) => decoder.surfaces_made(),
|
||||
}
|
||||
.expect("a session")
|
||||
}
|
||||
}
|
||||
|
||||
/// The surfaces decoders made up front for `record`'s stream: its first SPS's DPB, the picture
|
||||
/// and two spare.
|
||||
fn up_front(profile: Encoded, record: &[u8]) -> usize {
|
||||
let dpb = match profile {
|
||||
Encoded::HevcMain | Encoded::HevcMain10 => {
|
||||
use crate::codec::hevc::{hvcc::DecoderConfiguration, nal, sps::Sps};
|
||||
let config = DecoderConfiguration::parse(record).expect("a record");
|
||||
let sps = (config.nal_units.iter())
|
||||
.find(|unit| {
|
||||
nal::NalUnit::new(unit).is_ok_and(|n| n.unit_type() == nal::nal_type::SPS)
|
||||
})
|
||||
.expect("an SPS");
|
||||
Sps::parse(sps).expect("an SPS").dpb_size()
|
||||
}
|
||||
_ => {
|
||||
use crate::codec::h264::{avcc::DecoderConfiguration, sps::Sps};
|
||||
let config = DecoderConfiguration::parse(record).expect("a record");
|
||||
let sps = config.sequence_parameter_sets.first().expect("an SPS");
|
||||
Sps::parse(sps).expect("an SPS").dpb_frames()
|
||||
}
|
||||
};
|
||||
dpb + 1 + 2
|
||||
}
|
||||
|
||||
/// One decode of a stream: each picture's hash, each access unit's time to decode and wait for
|
||||
/// its pictures, and the surfaces the decoder made.
|
||||
struct Run {
|
||||
pictures: Vec<u64>,
|
||||
times: Vec<Duration>,
|
||||
made: usize,
|
||||
}
|
||||
|
||||
/// `samples` decoded by a new decoder, each picture read back as the CPU's copy does once it was
|
||||
/// waited for, with the pool making `made_up_front` surfaces with the context.
|
||||
fn run(
|
||||
display: &Display,
|
||||
profile: Encoded,
|
||||
record: &[u8],
|
||||
samples: &[Vec<u8>],
|
||||
made_up_front: usize,
|
||||
) -> Run {
|
||||
UP_FRONT.with(|count| count.set(made_up_front));
|
||||
let mut decoder = Decoding::new(display, profile, record);
|
||||
let mut run = Run {
|
||||
pictures: Vec::new(),
|
||||
times: Vec::new(),
|
||||
made: 0,
|
||||
};
|
||||
for (id, sample) in (0u64..).zip(samples) {
|
||||
let start = StdRuntime.now();
|
||||
let frames = decoder.decode(sample, id);
|
||||
for frame in &frames {
|
||||
frame.sync().expect("a picture's wait");
|
||||
}
|
||||
run.times
|
||||
.push(StdRuntime.now().saturating_duration_since(start));
|
||||
UP_FRONT.with(|count| count.set(0));
|
||||
for frame in frames {
|
||||
run.pictures.push(hash(&frame));
|
||||
}
|
||||
}
|
||||
run.made = decoder.surfaces_made();
|
||||
UP_FRONT.with(|count| count.set(0));
|
||||
run
|
||||
}
|
||||
|
||||
/// A hash of `frame`'s picture, as the CPU's copy reads it back.
|
||||
fn hash(frame: &Frame) -> u64 {
|
||||
let sample = if frame.bit_depth() > 8 { 2 } else { 1 };
|
||||
let (w, h) = (frame.width() as usize, frame.height() as usize);
|
||||
let row = w * sample;
|
||||
let mut luma = vec![0u8; row * h];
|
||||
let mut chroma = vec![0u8; row * h.div_ceil(2)];
|
||||
let rows = |bytes, rows| PlaneRows {
|
||||
bytes,
|
||||
bytes_per_row: row,
|
||||
rows,
|
||||
row_bytes: row,
|
||||
};
|
||||
(frame.read_back().expect("a read back"))
|
||||
.copy_into(rows(&mut luma, h), rows(&mut chroma, h.div_ceil(2)))
|
||||
.expect("a copy");
|
||||
let mut hasher = DefaultHasher::new();
|
||||
luma.hash(&mut hasher);
|
||||
chroma.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// The median of `times`.
|
||||
fn median(mut times: Vec<Duration>) -> Duration {
|
||||
times.sort_unstable();
|
||||
times[times.len() / 2]
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs a VA-API GPU: run on the VA-API host"]
|
||||
fn pictures_decode_the_same_into_surfaces_made_as_they_are_needed() {
|
||||
let display = display();
|
||||
let mut compared = 0;
|
||||
for (profile, name) in [
|
||||
(Encoded::H264High, "H.264"),
|
||||
(Encoded::HevcMain, "HEVC Main"),
|
||||
(Encoded::HevcMain10, "HEVC Main 10"),
|
||||
] {
|
||||
for size in [(1920, 1080), (3840, 2160)] {
|
||||
let name = format!("{name} {}x{}", size.0, size.1);
|
||||
let Some((record, samples)) = encoded(&display, profile, size) else {
|
||||
eprintln!("{name}: not compared: the driver encodes no such stream");
|
||||
continue;
|
||||
};
|
||||
let count = up_front(profile, &record);
|
||||
let mut runs: [Vec<Run>; 2] = Default::default();
|
||||
for round in 0..ROUNDS {
|
||||
// Each way first in turn.
|
||||
for way in [round % 2, 1 - round % 2] {
|
||||
let made = if way == 0 { 0 } else { count };
|
||||
runs[way].push(run(&display, profile, &record, &samples, made));
|
||||
}
|
||||
}
|
||||
let reference = &runs[1][0].pictures;
|
||||
assert!(!reference.is_empty(), "{name}: no picture");
|
||||
for (way, runs) in ["as needed", "up front"].iter().zip(&runs) {
|
||||
for run in runs {
|
||||
assert!(
|
||||
run.pictures == *reference,
|
||||
"{name}: the pictures of surfaces made {way} differ"
|
||||
);
|
||||
}
|
||||
}
|
||||
let [needed, made_up_front] = runs.each_ref().map(|runs| runs[0].made);
|
||||
assert!(
|
||||
needed <= made_up_front,
|
||||
"{name}: {needed} surfaces made as needed, {made_up_front} up front"
|
||||
);
|
||||
let first = |runs: &[Run]| median(runs.iter().map(|run| run.times[0]).collect());
|
||||
let later = |runs: &[Run]| {
|
||||
median(
|
||||
runs.iter()
|
||||
.flat_map(|run| run.times[1..].iter().copied())
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
eprintln!(
|
||||
"{name}: {} pictures the same; surfaces made: {needed} as needed, \
|
||||
{made_up_front} up front; the first access unit in {:.3} ms as needed, {:.3} \
|
||||
ms up front; later ones in {:.3} ms, {:.3} ms (medians of {ROUNDS} runs)",
|
||||
reference.len(),
|
||||
ms(first(runs[0].as_slice())),
|
||||
ms(first(runs[1].as_slice())),
|
||||
ms(later(runs[0].as_slice())),
|
||||
ms(later(runs[1].as_slice())),
|
||||
);
|
||||
compared += 1;
|
||||
}
|
||||
}
|
||||
assert!(compared > 0, "no stream the driver encodes");
|
||||
}
|
||||
@@ -63,6 +63,13 @@ fn a_stand_in_copy_gives_the_surface_what_the_other_holds() {
|
||||
"{}: a later surface not shared",
|
||||
format.name()
|
||||
);
|
||||
// A pool made with none, as a decoder's is, makes its first surface shared too.
|
||||
let empty = SurfacePool::new(&display, format, SIZE.0, SIZE.1, 0).expect("a pool");
|
||||
assert!(
|
||||
empty.get().expect("a surface").texture().is_some(),
|
||||
"{}: an empty pool's first surface not shared",
|
||||
format.name()
|
||||
);
|
||||
put(&display, &from, format, 0x5a);
|
||||
put(&display, &to, format, 0xa5);
|
||||
let held = read(&from, format);
|
||||
|
||||
@@ -404,6 +404,15 @@ impl Decoder {
|
||||
frame.sync().map_err(|e| format!("picture {id}: {e}"))?;
|
||||
Ok(frame)
|
||||
}
|
||||
|
||||
/// How many surfaces of its own the decoder's session made, once it has started a picture.
|
||||
#[cfg(test)]
|
||||
fn surfaces_made(&self) -> Option<usize> {
|
||||
match self {
|
||||
Decoder::H264(decoder) => decoder.surfaces_made(),
|
||||
Decoder::Hevc(decoder) => decoder.surfaces_made(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The check of `codec` into `format` (module docs) on `display`: `Err` with why it failed, or
|
||||
@@ -594,13 +603,14 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Each picture's crop as decoded into targets over three memories in turn, each a new import,
|
||||
/// each scribbled over once read, while the decoder may still reference its picture.
|
||||
/// each scribbled over once read, while the decoder may still reference its picture; and how
|
||||
/// many surfaces of its own the decoder made.
|
||||
fn into_targets(
|
||||
display: &Display,
|
||||
codec: TargetCodec,
|
||||
record: &[u8],
|
||||
samples: &[Vec<u8>],
|
||||
) -> Vec<Vec<u8>> {
|
||||
) -> (Vec<Vec<u8>>, Option<usize>) {
|
||||
let mut decoder = decoder(display, codec, record);
|
||||
let shape = TargetShape {
|
||||
format: TargetFormat::Nv12,
|
||||
@@ -624,8 +634,9 @@ mod tests {
|
||||
drop(frame);
|
||||
laid.scribble();
|
||||
}
|
||||
let made = decoder.surfaces_made();
|
||||
drop(decoder);
|
||||
out
|
||||
(out, made)
|
||||
}
|
||||
|
||||
/// Where the check passes a codec, a stream of the driver's own encoder (with motion and
|
||||
@@ -650,7 +661,7 @@ mod tests {
|
||||
continue;
|
||||
};
|
||||
let reference = read_back(&display, codec, &record, &samples);
|
||||
let targets = into_targets(&display, codec, &record, &samples);
|
||||
let (targets, _) = into_targets(&display, codec, &record, &samples);
|
||||
assert_eq!(reference.len(), targets.len(), "{codec:?}: the pictures");
|
||||
for (n, (r, t)) in reference.iter().zip(&targets).enumerate() {
|
||||
assert!(
|
||||
@@ -665,6 +676,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A decoder whose every picture is decoded into a target over the caller's memory makes no
|
||||
/// surface of its own (`super::super::surface`), where the check passes the codec.
|
||||
#[test]
|
||||
#[ignore = "needs a VA-API GPU: run on the VA-API host"]
|
||||
fn a_decoder_whose_every_picture_goes_into_a_target_makes_no_surface() {
|
||||
let display = display();
|
||||
let checks = TargetChecks::check(&display);
|
||||
let mut compared = 0;
|
||||
for (codec, profile) in [
|
||||
(TargetCodec::H264, Encoded::H264High),
|
||||
(TargetCodec::Hevc, Encoded::HevcMain),
|
||||
] {
|
||||
if let Err(why) = checks.passed(codec, TargetFormat::Nv12) {
|
||||
eprintln!("{codec:?}: not run: the check answered {why}");
|
||||
continue;
|
||||
}
|
||||
let Some((record, samples)) = encoded(&display, profile) else {
|
||||
eprintln!("{codec:?}: not run: the driver encodes no {profile:?}");
|
||||
continue;
|
||||
};
|
||||
let (pictures, made) = into_targets(&display, codec, &record, &samples);
|
||||
assert!(!pictures.is_empty(), "{codec:?}: no picture");
|
||||
assert_eq!(made, Some(0), "{codec:?}: surfaces of the decoder's own");
|
||||
eprintln!(
|
||||
"{codec:?}: {} pictures into targets, no surface of the decoder's own",
|
||||
pictures.len()
|
||||
);
|
||||
compared += 1;
|
||||
}
|
||||
eprintln!("{compared} codecs run");
|
||||
}
|
||||
|
||||
/// The check's streams decode to their samples on the driver's own surfaces, read back by the
|
||||
/// CPU's copy: where they do not, a check's failure is the stream's, not the target's. Prints
|
||||
/// each picture's first wrong sample.
|
||||
|
||||
+2
-2
@@ -17,8 +17,8 @@ Everything known to be wrong, untested or put off in the reims-graphics device's
|
||||
|
||||
### B14. A guest's video sessions have no VRAM budget
|
||||
|
||||
- **What:** each decode session holds a pool of surfaces at its stream's coded size, as many as its DPB asks plus a few, and the host bounds neither how many sessions a guest opens nor the bytes their pools take: about 480 MB for one 4096x4096 H.264 session with 16 frames, so a few sessions of large streams can take a shared GPU's memory.
|
||||
- **Evidence:** **read**: the VA-API H.264 decoder's `configure` (`crates/reims-vgpu-video/src/vaapi/va/h264.rs`) makes `dpb_frames + 1 + SPARE_SURFACES` surfaces at the SPS's size. **Measured** on an RTX 5080 Laptop GPU (16,303 MiB, driver 615.71.09), 2026-10-24: one decoder of a 7680x4320 HEVC Main 10 stream held 1,020 MiB of VRAM, with the DPB its SPS asks for; one process with one held 1,216 MiB, with two 2,236 MiB. NVDEC's surfaces are the DPB plus 3 at the stream's size.
|
||||
- **What:** each decode session holds surfaces at its stream's coded size, as many as its pictures use at once (on VA-API its DPB's references, the picture it decodes and those not landed yet; on NVDEC its DPB plus a few), and the host bounds neither how many sessions a guest opens nor the bytes their surfaces take: about 480 MB for one 4096x4096 H.264 session with 16 reference frames, so a few sessions of large streams can take a shared GPU's memory.
|
||||
- **Evidence:** **read**: the VA-API decoders' pools (`crates/reims-vgpu-video/src/vaapi/va/surface.rs`) make a surface at the SPS's size for each picture decoded into one of their own while none is free, up to 48. **Measured** on an RTX 5080 Laptop GPU (16,303 MiB, driver 615.71.09), 2026-10-24: one decoder of a 7680x4320 HEVC Main 10 stream held 1,020 MiB of VRAM, with the DPB its SPS asks for; one process with one held 1,216 MiB, with two 2,236 MiB. NVDEC's surfaces are the DPB plus 3 at the stream's size.
|
||||
- **Why it waits:** the host puts no limit of its own on how much of its hardware one VM holds, as a native GPU's driver puts none on its apps.
|
||||
- **Fix, if that changes:** a budget of surface bytes per process's sessions, or a bound on its sessions.
|
||||
|
||||
|
||||
+39
-10
@@ -505,7 +505,11 @@ answers for its device, `rt_platform::HostGpu`). The arm
|
||||
"A decode").
|
||||
- **Surfaces.** A picture holds its decode surface until it lands, and
|
||||
the session holds no more pictures unlanded than the decoder's spare
|
||||
surfaces (`SPARE_FRAMES`, 2), so a decode always finds a free surface.
|
||||
frames (`SPARE_FRAMES`, 2). The decoder's pool makes a surface only for
|
||||
a picture decoded into one of its own ("Surfaces and readback"): a
|
||||
reference, or a picture given no cache target. So a session whose
|
||||
pictures land in caches holds surfaces only for its references and the
|
||||
pictures not landed yet.
|
||||
- **The display** opens once per runtime device and logs its driver, the
|
||||
open's time and thread, and the import check's answers.
|
||||
|
||||
@@ -708,11 +712,13 @@ once a process that one was held.
|
||||
(`Context::new_decoder`, `Display::context_let_go`): on Windows a
|
||||
decoder's context let go while another context lives is kept, with its
|
||||
config and the pool of surfaces its decoder decoded into, and the next
|
||||
decoder of the same profile, config attributes, surface format, size,
|
||||
number of surfaces and DPB (H.264's `num_ref_frames`, HEVC's
|
||||
decoder of the same profile, config attributes, surface format, size
|
||||
and DPB (H.264's `num_ref_frames`, HEVC's
|
||||
`sps_max_dec_pic_buffering_minus1`) takes the three back instead of
|
||||
making its own. So beside a live context a decoder of a shape kept makes
|
||||
no config, pool or context, and one let go destroys none, and what the
|
||||
making its own. The pool taken back holds the surfaces its last decoder
|
||||
made, and makes more as pictures need them. So beside a live context a
|
||||
decoder of a shape kept makes no config, pool or context, and one let
|
||||
go destroys none, and what the
|
||||
kept contexts hold is bounded by the most decoders of one shape that
|
||||
lived at once, rather than growing with every session that ends beside a
|
||||
long one. A pool kept lets go of its video-processing context first (the
|
||||
@@ -866,12 +872,35 @@ by radeonsi; a driver that reads them is their hardware test.
|
||||
|
||||
### Surfaces and readback
|
||||
|
||||
- Each session makes a pool of NV12 surfaces at the coded size, sized
|
||||
DPB + 1 + 2 spare. They are the context's render targets.
|
||||
- A `Frame` holds its surface until it is dropped; a caller that holds
|
||||
- Each session has a pool of surfaces at the coded size (NV12, or P010
|
||||
for HEVC Main 10). It starts with none, and the session's context is
|
||||
made with no render targets. The pool makes a surface when a picture is
|
||||
to be decoded into one of its own and none is free, and lends the one
|
||||
freed last first. So it holds as many surfaces as were in use at once:
|
||||
the DPB's references, the picture being decoded and the frames the
|
||||
caller holds. A session whose every picture is decoded into a target
|
||||
makes none.
|
||||
- A `Frame` holds its surface until it is dropped. A caller that holds
|
||||
frames makes the pool grow, up to 48 surfaces, then `OutOfSurfaces`.
|
||||
Surfaces made after the context are decoded into fine: main-720p
|
||||
matched with the caller holding 24 frames.
|
||||
- Surfaces made after the context are decoded into fine: main-720p
|
||||
matched with the caller holding 24 frames. **Read from code** (Mesa
|
||||
26.2.4, `frontends/va/context.c`): `vlVaCreateContext` reads no render
|
||||
target.
|
||||
- **Measured** (2026-11-21, `surface::lazy`'s tests on the GPU, at 1080p
|
||||
NV12 and 4K NV12 and P010): a surface's make takes 0.001 ms or less
|
||||
(median) on radeonsi (Mesa 26.2.6) on a Radeon 780M and an RX 7900 XTX,
|
||||
and 0.004 ms on iHD 26.3.5 on an Iris Xe. radeonsi makes no buffer for a
|
||||
surface until its first use: the process's GPU memory (DRM fdinfo,
|
||||
`drm-total-*`) grew by 0.0 MiB once 8 were made, and by 31, 108 and
|
||||
203 MiB on the 780M (41, 144 and 279 on the XTX) once each held an
|
||||
image. iHD makes each surface's buffer at its full size when it is made
|
||||
(`drm-total-*` +28, +96 and +192 MiB for 8) and backs none of it until
|
||||
first use (`drm-resident-*` +0.0, then +28, +96 and +192). Streams of
|
||||
each driver's own encoder decoded to the same pictures with surfaces
|
||||
made as needed as with five made up front, making two or three, and the
|
||||
first access unit took the same time either way within the runs' spread
|
||||
(H.264 1080p on the XTX 12.95 ms as needed, 13.18 up front; HEVC Main 10
|
||||
4K on the Iris 10.06, 10.01).
|
||||
- Readback waits for the decode ("Waiting for the GPU"), has the GPU copy
|
||||
the frame into host memory of the pool's, and copies the cropped
|
||||
rectangle row by row into the caller's planes at the caller's strides;
|
||||
|
||||
Reference in new issue
Block a user