🐛 Send VA's quality level alone, and the nearest the driver takes

iHD 26.3.5's HEVC encoder takes quality levels 1, 4 and 7 of the 7 its config
lists, and answers success for a render that carries another level with a packed
header after it, then codes at the refused level (read in its source:
media_ddi_encode_hevc.cpp's ParseMiscParams, RenderPicture and
EncodeInCodecHal). An arm64 guest's session at a Quality of 0.9, level 2, hung
the Iris Xe's render engine (boot m3-max-79085, bugs.md B102). The refused level
is the likely trigger, unconfirmed.

The VA crate now renders the quality level alone, first, where a picture sends
its misc buffers (IDR pictures and a rate control change), so the driver's
answer to it is its own. A refused level gives way to the nearest level the
driver takes, the better quality first at a tie, before the picture's other
buffers, and the session keeps the level taken. VA-API's text allows the form:
a picture's buffers go in as many renders as the caller makes, and va.h's own
misc parameter example renders one alone. The choice is the driver's answer
alone, with no driver name, version or card in it, and a driver that takes
every level sees the same buffers, the level in a render of its own.

For the guest: a session asks the same quality as before. Where the driver
refuses that level, the stream codes at the nearest level the driver takes
rather than at the refused one: on the Iris Xe's HEVC, 1 for 2, 4 for 3 and 5,
and 7 for 6. reims-vgpu counts such a session as
video-encode-quality-level-adjusted and logs it once a session. x86-64 guests'
encoder asks level 4, which iHD takes, so they see no change, nor does a session
on radeonsi, which takes every level. iHD's H.264 encoder copies the level into
the sequence as it parses the sequence buffer (read), so its first sequence now
takes the asked level too, where it took the context's earlier one. HEVC Main
4:2:2 10 stays held back (B102).

Ledger (bugs.md B102 and U37). Read from code: iHD's masked refusal, above, a
lead until the guest's 4:2:2 case encodes under the fix, which waits for the
owner's word. Run: a fake driver modelled on that read gives the refused level's
render a failure and the next choice is taken (red m3-max-79207 at the masked
path, green m3-max-79223 with rustfmt and clippy). No report on file names an
Intel host's HEVC encode at a level iHD refuses but boot m3-max-79085's: the
Intel rows on file (B98 to B101) are x86-64 guests', at level 4.

Run on hardware: on the Radeon 780M (radeonsi) the VA encode tests and the new
one, asked level 2 and taken 2, 52.0 to 54.9 dB luma (m3-max-79243,
m3-max-79256; m3-max-79318 with the commits after it). The RTX 3090's VA driver
lists no encoder, so no level reaches it (m3-max-79247), and NVENC takes no VA
buffer: its encode tests pass (m3-max-79251). On the Iris Xe (iHD 26.3.5), one
encode of the 4:2:0 HEVC Main test asked at level 2: taken 1, 52.5 to 53.2 dB
luma, and no GPU hang or reset in the kernel's log (m3-max-79388).
This commit is contained in:
Anees Iqbal committed 2026-12-02 11:00:01 -08:00
1 parent d6511054f5
commit 201d165e47
14 files changed
+602 -62

No files matched your search

+1 -1
View File
@@ -52,5 +52,5 @@ pub(crate) use va::gated;
pub use va::{
EncoderCapabilities, EncoderSupport, Feature, HevcBlockSizes, HevcFeatures, InputLayout,
InputSurface, UploadMethod, VideoEncoder, encoder_support,
InputSurface, QualityLevel, UploadMethod, VideoEncoder, encoder_support,
};
+1 -1
View File
@@ -76,7 +76,7 @@ pub use display::DecoderCache;
pub use display::{Display, Error};
pub use encoder::{
EncoderCapabilities, EncoderSupport, Feature, HevcBlockSizes, HevcFeatures, InputLayout,
InputSurface, UploadMethod, VideoEncoder, encoder_support,
InputSurface, QualityLevel, UploadMethod, VideoEncoder, encoder_support,
};
pub use export::{ExportedPlane, SurfaceExport};
pub use frame::{Frame, FrameHold, GuestWrites, PlaneRows, ReadBack};
+124 -33
View File
@@ -28,6 +28,24 @@
//! call that may wait for the GPU, made on the display's call thread by the
//! frame's deadline ([`render_decode`], `super::calls`), and the decoder's
//! later ones on the caller's thread, as every other submission is.
//!
//! **An encoder's quality level is rendered alone, first**
//! ([`render_encode`]), so that the driver's answer to it is its own. iHD
//! 26.3.5's HEVC encoder on its Gen12 path keeps the level it is sent as
//! the context's target usage, then refuses any but 1, 4 and 7
//! (`VA_STATUS_ERROR_INVALID_PARAMETER`, answered as
//! `VA_STATUS_ERROR_INVALID_BUFFER`); its render loop then goes on with the
//! render's other buffers, and a packed header's after it answers over the
//! refusal, so the render that carries the level with the picture's other
//! buffers answers success, and the picture's end codes at the refused
//! level (**read** in its source, `media_ddi_encode_hevc.cpp`,
//! `ParseMiscParams` and `RenderPicture`; docs/video/bugs.md). Rendered
//! alone, a refused level is a failed render, and the next choice, the
//! nearest level the caller lists, is rendered in its place, before the
//! picture's other buffers. VA-API's text takes this form: the
//! Begin/Render/End sequence sends a picture's buffers in as many renders
//! as the caller makes, and va.h's own example of a misc parameter renders
//! it alone (`vaRenderPicture(dpy, context, &buf_id, 1)`, libva 2.24.1).
use super::caps::Context;
use super::display::{Display, Error, check};
@@ -125,7 +143,34 @@ pub(crate) fn render_picture(
target: ffi::VASurfaceID,
groups: &[&[&Buffer<'_>]],
) -> Result<(), Error> {
render(display, context, target, groups, None)
let mut calls = VaCalls {
display,
context,
target,
decoder: None,
};
render_with(&mut calls, &[], groups).map(|_| ())
}
/// [`render_picture`] for an encoder's picture whose quality level is
/// rendered alone, first (module docs): each of `choices`, a quality
/// level's misc buffer, alone in turn until the driver takes one, then
/// `groups`. The index of the choice the driver took; `None` where
/// `choices` is empty or it took none, the picture rendered on.
pub(crate) fn render_encode(
display: &Display,
context: ffi::VAContextID,
target: ffi::VASurfaceID,
choices: &[&Buffer<'_>],
groups: &[&[&Buffer<'_>]],
) -> Result<Option<usize>, Error> {
let mut calls = VaCalls {
display,
context,
target,
decoder: None,
};
render_with(&mut calls, choices, groups)
}
/// What a decoder's first `vaEndPicture` is, where it holds the display past
@@ -143,52 +188,98 @@ pub(crate) fn render_decode(
target: ffi::VASurfaceID,
groups: &[&[&Buffer<'_>]],
) -> Result<(), Error> {
render(display, context.id, target, groups, Some(context))
let mut calls = VaCalls {
display,
context: context.id,
target,
decoder: Some(context),
};
render_with(&mut calls, &[], groups).map(|_| ())
}
/// [`render_picture`], where `decoder` is a decoder's context, its first
/// `vaEndPicture` on the display's call thread.
fn render(
display: &Display,
/// The calls a picture's renders are made through: the display's
/// ([`VaCalls`]), or a test's model of a driver's.
pub(crate) trait PictureCalls<B: ?Sized> {
/// `vaBeginPicture`.
fn begin(&mut self) -> Result<(), Error>;
/// `vaRenderPicture` of `group`.
fn render(&mut self, group: &[&B]) -> Result<(), Error>;
/// `vaEndPicture`.
fn end(&mut self) -> Result<(), Error>;
}
/// A picture's renders through `calls`: begun, each of `choices` alone in
/// turn until one is taken, each of `groups` in turn until one fails, and
/// ended whatever they answered ([`render_picture`], [`render_encode`]).
fn render_with<B: ?Sized>(
calls: &mut impl PictureCalls<B>,
choices: &[&B],
groups: &[&[&B]],
) -> Result<Option<usize>, Error> {
calls.begin()?;
let taken = (choices.iter()).position(|&choice| calls.render(&[choice]).is_ok());
let rendered = groups.iter().try_for_each(|group| calls.render(group));
let ended = calls.end();
rendered.and(ended).map(|()| taken)
}
/// A picture's calls on the display: a decoder's first `vaEndPicture` on
/// the display's call thread ([`render_decode`]).
struct VaCalls<'a> {
display: &'a Display,
context: ffi::VAContextID,
target: ffi::VASurfaceID,
groups: &[&[&Buffer<'_>]],
decoder: Option<&Context>,
) -> Result<(), Error> {
check(
"vaBeginPicture",
// SAFETY: the context and the surface are this display's, alive for the
// call: their owners outlive it.
display.call(|raw| unsafe { ffi::vaBeginPicture(raw, context, target) })?,
)?;
let rendered = groups.iter().try_for_each(|group| {
/// The decoder's context, where the picture is a decoder's.
decoder: Option<&'a Context>,
}
impl PictureCalls<Buffer<'_>> for VaCalls<'_> {
fn begin(&mut self) -> Result<(), Error> {
let (display, context, target) = (self.display, self.context, self.target);
check(
"vaBeginPicture",
// SAFETY: the context and the surface are this display's, alive for the
// call: their owners outlive it.
display.call(|raw| unsafe { ffi::vaBeginPicture(raw, context, target) })?,
)
}
fn render(&mut self, group: &[&Buffer<'_>]) -> Result<(), Error> {
let context = self.context;
let mut ids: Vec<ffi::VABufferID> = group.iter().map(|b| b.id).collect();
let count = i32::try_from(ids.len())
.map_err(|_| Error::Unsupported("over 2 Gi buffers in a render".into()))?;
check(
"vaRenderPicture",
// SAFETY: `ids` holds `count` IDs of this display's live buffers,
// borrowed until this function returns, so past `vaEndPicture`.
// borrowed until the picture's renders return, so past `vaEndPicture`.
// Any pointer a buffer holds (a pipeline's rectangles) points at
// the caller's values, which outlive the call.
display.call(|raw| unsafe {
self.display.call(|raw| unsafe {
ffi::vaRenderPicture(raw, context, ids.as_mut_ptr(), count)
})?,
)
});
let ended = if decoder.is_some_and(Context::first_end) {
display.wait_call(
FIRST_PICTURE,
// SAFETY: a picture begun above on this context, ended once.
// The context and the buffers outlive the call wherever it
// returns: their destroys are made behind it.
move |raw| unsafe { ffi::vaEndPicture(raw, context) },
|_, _| {},
)
} else {
// SAFETY: a picture begun above on this context, ended once.
display.call(|raw| unsafe { ffi::vaEndPicture(raw, context) })
}
.and_then(|status| check("vaEndPicture", status));
rendered.and(ended)
fn end(&mut self) -> Result<(), Error> {
let context = self.context;
if self.decoder.is_some_and(Context::first_end) {
self.display.wait_call(
FIRST_PICTURE,
// SAFETY: a picture begun on this context, ended once.
// The context and the buffers outlive the call wherever it
// returns: their destroys are made behind it.
move |raw| unsafe { ffi::vaEndPicture(raw, context) },
|_, _| {},
)
} else {
// SAFETY: a picture begun on this context, ended once.
self.display
.call(|raw| unsafe { ffi::vaEndPicture(raw, context) })
}
.and_then(|status| check("vaEndPicture", status))
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,151 @@
use super::*;
/// A buffer of an encoder's picture, as a model of a driver sees it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Sequence,
/// A misc parameter buffer of this quality level.
Quality(u32),
/// Another misc parameter buffer: the rate control, the HRD or the frame rate.
Misc,
Picture,
PackedHeader,
Slice,
}
/// A model of a driver's picture calls for an encoder, as iHD 26.3.5's HEVC encoder on its Gen12
/// path makes them (**read** in its source, `media_ddi_encode_hevc.cpp`, `RenderPicture` and
/// `ParseMiscParams`): a quality level is kept as the context's level, then refused unless
/// `takes` holds it; a refusal is the render's answer unless a packed header after it in the
/// same render answers over it; and the picture's end codes at the level last kept.
struct Driver {
takes: Vec<u32>,
level: Option<u32>,
renders: Vec<Vec<Kind>>,
/// The level each picture's end coded at.
coded_at: Vec<Option<u32>>,
}
impl Driver {
fn taking(takes: &[u32]) -> Self {
Self {
takes: takes.to_vec(),
level: None,
renders: Vec::new(),
coded_at: Vec::new(),
}
}
}
impl PictureCalls<Kind> for Driver {
fn begin(&mut self) -> Result<(), Error> {
Ok(())
}
fn render(&mut self, group: &[&Kind]) -> Result<(), Error> {
self.renders.push(group.iter().map(|&&k| k).collect());
let mut answer = Ok(());
for kind in group {
match **kind {
Kind::Quality(level) => {
self.level = Some(level);
if !self.takes.contains(&level) {
answer = Err(Error::Va {
call: "vaRenderPicture",
// `VA_STATUS_ERROR_INVALID_BUFFER` (va.h).
status: 0x07,
message: "invalid VABufferID".to_owned(),
});
}
}
Kind::PackedHeader => answer = Ok(()),
_ => {}
}
}
answer
}
fn end(&mut self) -> Result<(), Error> {
self.coded_at.push(self.level);
Ok(())
}
}
/// An IDR picture's buffers other than its quality level, in the order the encoder renders them.
const PICTURE: [Kind; 6] = [
Kind::Sequence,
Kind::Misc,
Kind::Picture,
Kind::PackedHeader,
Kind::PackedHeader,
Kind::Slice,
];
/// A picture's quality level that the driver refuses, rendered alone, is answered as refused, and
/// the next of the choices is rendered in its place before the picture's other buffers: the
/// picture codes at the nearest level the driver takes, never at the refused one.
#[test]
fn a_refused_quality_level_gives_way_to_the_next_choice_before_the_picture() {
let mut driver = Driver::taking(&[1, 4, 7]);
let choices = [Kind::Quality(2), Kind::Quality(1), Kind::Quality(3)];
let choices: Vec<&Kind> = choices.iter().collect();
let picture: Vec<&Kind> = PICTURE.iter().collect();
let taken = render_with(&mut driver, &choices, &[&picture]).expect("rendered");
assert_eq!(taken, Some(1), "the second choice taken");
assert_eq!(driver.coded_at, [Some(1)], "coded at the level taken");
assert_eq!(
driver.renders,
[
vec![Kind::Quality(2)],
vec![Kind::Quality(1)],
PICTURE.to_vec()
]
);
}
/// A driver that takes the asked level sees it alone, first, and nothing else changes: the
/// picture codes at it.
#[test]
fn a_quality_level_the_driver_takes_is_the_only_choice_rendered() {
let mut driver = Driver::taking(&[1, 2, 3, 4, 5, 6, 7]);
let choices = [Kind::Quality(2), Kind::Quality(1)];
let choices: Vec<&Kind> = choices.iter().collect();
let picture: Vec<&Kind> = PICTURE.iter().collect();
let taken = render_with(&mut driver, &choices, &[&picture]).expect("rendered");
assert_eq!(taken, Some(0));
assert_eq!(driver.coded_at, [Some(2)]);
assert_eq!(driver.renders, [vec![Kind::Quality(2)], PICTURE.to_vec()]);
}
/// Where the driver takes none of the choices, the picture is rendered and ended as any, and the
/// answer says none was taken.
#[test]
fn a_picture_whose_quality_choices_are_all_refused_is_rendered_on() {
let mut driver = Driver::taking(&[]);
let choices = [Kind::Quality(2), Kind::Quality(1)];
let choices: Vec<&Kind> = choices.iter().collect();
let picture: Vec<&Kind> = PICTURE.iter().collect();
let taken = render_with(&mut driver, &choices, &[&picture]).expect("rendered");
assert_eq!(taken, None);
assert_eq!(driver.renders.len(), 3);
assert_eq!(driver.coded_at.len(), 1, "ended once");
}
/// The model's own answer when the quality level rides with the picture's other buffers in one
/// render, as the encoder rendered it before: the refusal is answered over by the packed header
/// after it, and the picture codes at the refused level. This is why the level goes alone.
#[test]
fn the_models_refusal_in_one_render_with_a_packed_header_is_answered_over() {
let mut driver = Driver::taking(&[1, 4, 7]);
let picture = [
Kind::Sequence,
Kind::Misc,
Kind::Quality(2),
Kind::Picture,
Kind::PackedHeader,
Kind::Slice,
];
let picture: Vec<&Kind> = picture.iter().collect();
assert!(render_with(&mut driver, &[], &[&picture]).is_ok());
assert_eq!(driver.coded_at, [Some(2)]);
}
+148 -1
View File
@@ -77,6 +77,7 @@ use crate::codec::encode::{
self, Codec, Coded, EncoderSettings, FrameRate, InputFormat, InputFrame, RateControl,
Unsupported, hevc,
};
pub use accelerator::QualityLevel;
use accelerator::{Input, VaAccelerator};
impl From<Unsupported> for Error {
@@ -271,7 +272,13 @@ impl VideoEncoder {
})?;
let limits = limits(display, &caps, settings.profile.codec())?;
let packed = caps.packed_headers.unwrap_or(0) & PACKED_HEADERS;
let accelerator = VaAccelerator::new(display, caps.profile, caps.entrypoint, packed);
let accelerator = VaAccelerator::new(
display,
caps.profile,
caps.entrypoint,
packed,
caps.quality_range,
);
Ok(Self {
inner: Encoder::new(accelerator, settings, &limits)?,
})
@@ -361,6 +368,13 @@ impl VideoEncoder {
self.inner.accelerator().packed_headers()
}
/// The quality level the stream asked of the driver and the one it took, once its settings
/// asked for one and a picture sent it: a level the driver refuses gives way to the nearest
/// it takes (`accelerator`'s docs, "The quality level").
pub fn quality_level(&self) -> Option<QualityLevel> {
self.inner.accelerator().quality_level()
}
/// How frames reach the driver, once the first has.
pub fn upload_method(&self) -> Option<UploadMethod> {
self.inner.accelerator().upload_method()
@@ -1037,6 +1051,139 @@ mod tests {
}
}
/// The quality levels tried for an ask: the asked one, then the config's others by their
/// distance from it, the better quality (the lower level) first at each distance; the asked
/// one alone where the driver lists no range or the range does not hold it.
#[test]
fn a_quality_levels_choices_are_the_nearest_first_the_better_first_at_a_tie() {
use super::accelerator::quality_choices;
assert_eq!(quality_choices(2, Some(7)), [2, 1, 3, 4, 5, 6, 7]);
assert_eq!(quality_choices(3, Some(7)), [3, 2, 4, 1, 5, 6, 7]);
assert_eq!(quality_choices(6, Some(7)), [6, 5, 7, 4, 3, 2, 1]);
assert_eq!(quality_choices(1, Some(1)), [1]);
assert_eq!(quality_choices(2, None), [2]);
assert_eq!(quality_choices(9, Some(7)), [9]);
}
/// On the driver, an HEVC Main stream asked at quality level 2, the level a guest's Quality
/// of 0.9 maps to among 7: the level is rendered alone, first, and gives way to the nearest
/// the driver takes where it refuses it (`accelerator`'s docs, "The quality level"). 6 frames
/// of a moving 330x202 picture, uploaded, at a constant QP with no B pictures, code at the
/// level taken into a stream the driver's own decoder gives back within 40 dB of luma. Passes
/// with a note where the driver encodes no HEVC Main.
#[test]
#[ignore = "needs a VA-API GPU: run on the VA-API host"]
fn an_hevc_stream_asked_at_a_refused_quality_level_codes_at_the_nearest_taken() {
use super::super::{HevcDecoder, PlaneRows};
let node = std::env::var("RVG_VAAPI_NODE").unwrap_or_else(|_| "/dev/dri/renderD128".into());
let display = Display::open(&node, Arc::new(GatedRuntime)).expect("a VA display");
let profile = encode::Profile::HevcMain;
if !(encoder_support(&display).iter()).any(|s| s.profile == profile) {
eprintln!("{node}: the driver encodes no HEVC Main");
return;
}
let (width, height) = (330usize, 202usize);
let mut settings = EncoderSettings::new(profile, width as u32, height as u32);
settings.rate_control = RateControl::ConstantQp {
intra: 18,
predicted: 20,
bidirectional: 22,
};
settings.allow_frame_reordering = false;
settings.quality_level = Some(2);
let mut encoder =
VideoEncoder::new(&display, settings).unwrap_or_else(|e| panic!("an encoder: {e}"));
let luma = |id: usize, x: usize, y: usize| ((x * 3 + y * 2 + id * 8) % 200 + 16) as u8;
let chroma = |id: usize, c: usize, x: usize, y: usize| {
((x * 5 + y + id * 4 + c * 60) % 160 + 48) as u8
};
let mut coded = Vec::new();
for id in 0..6usize {
let y: Vec<u8> = (0..width * height)
.map(|i| luma(id, i % width, i / width))
.collect();
let uv: Vec<u8> = (0..width * (height / 2))
.map(|i| chroma(id, i % 2, (i % width) / 2, i / width))
.collect();
let frame = InputFrame {
planes: [
Plane {
data: &y,
bytes_per_row: width,
},
Plane {
data: &uv,
bytes_per_row: width,
},
],
pts: 3000 * id as i64,
duration: 3000,
force_key_frame: false,
id: id as u64,
};
coded.extend((encoder.encode(&frame)).unwrap_or_else(|e| panic!("frame {id}: {e}")));
}
coded.extend(encoder.flush());
let samples: Vec<_> = (coded.into_iter())
.map(|c| c.unwrap_or_else(|f| panic!("frame {}: {:?}", f.id, f.error)))
.collect();
assert_eq!(samples.len(), 6, "samples");
let quality = encoder.quality_level().expect("the quality level sent");
eprintln!(
"{node}: quality level asked {}, taken {:?}",
quality.asked, quality.taken
);
assert_eq!(quality.asked, 2);
assert!(quality.taken.is_some(), "the driver took no level");
let record = encoder.configuration();
let mut decoder = HevcDecoder::new(&display, &record[..])
.unwrap_or_else(|e| panic!("the driver's decoder of the stream: {e}"));
let mut frames = Vec::new();
for sample in &samples {
frames.extend(
(decoder.decode(&sample.data, sample.id))
.unwrap_or_else(|e| panic!("the decode of frame {}: {e}", sample.id)),
);
}
frames.extend(
decoder
.flush()
.unwrap_or_else(|e| panic!("the decode's flush: {e}")),
);
assert_eq!(frames.len(), 6, "frames decoded");
for (id, frame) in frames.iter().enumerate() {
let (mut y, mut uv) = (vec![0u8; width * height], vec![0u8; width * height / 2]);
(frame.read_back())
.and_then(|read| {
read.copy_into(
PlaneRows {
bytes: &mut y,
bytes_per_row: width,
rows: height,
row_bytes: width,
},
PlaneRows {
bytes: &mut uv,
bytes_per_row: width,
rows: height / 2,
row_bytes: width,
},
)
})
.unwrap_or_else(|e| panic!("frame {id}'s read: {e}"));
let (mut sum, mut n) = (0f64, 0f64);
for (i, &sample) in y.iter().enumerate() {
let source = luma(id, i % width, i / width);
sum += (f64::from(sample) - f64::from(source)).powi(2);
n += 1.0;
}
let luma_db = 10.0 * (255f64.powi(2) / (sum / n).max(1e-9)).log10();
eprintln!("frame {id}: luma {luma_db:.1} dB");
assert!(luma_db > 40.0, "frame {id}: {luma_db}");
}
}
#[test]
fn a_linear_input_is_laid_out_at_rows_of_256_bytes_its_chroma_plane_after_the_coded_rows() {
let shape = |format, coded| TargetShape { format, coded };
@@ -24,13 +24,23 @@
//! which another device wrote: the picture is coded from it as from one of
//! the pool's, though the context was not made with it. A stalled picture's
//! imported input is kept with its session, as the GPU may read it still.
//!
//! **The quality level** the settings ask for is rendered alone, first in
//! its picture (`super::super::buffer`'s docs, "An encoder's quality level
//! is rendered alone, first"), where the misc buffers go: on IDR pictures
//! and when the rate control changes. A level the driver refuses gives way
//! to the next of its choices ([`quality_choices`]), the nearest the driver
//! takes, the better quality first at each distance, and the session keeps
//! the level the driver took ([`QualityLevel`]) and sends it alone from
//! then on. iHD 26.3.5's HEVC encoder refuses levels 2, 3, 5 and 6 of the
//! 7 its config lists, where its H.264 encoder and radeonsi take them.
use std::sync::Arc;
use crate::core::runtime::MonoTime;
use crate::core::sync::Mutex;
use super::super::buffer::{Buffer, render_picture};
use super::super::buffer::{Buffer, render_encode};
use super::super::caps::{Config, Context, Entrypoint, Profile};
use super::super::display::{Display, Error, check};
use super::super::export::{SurfaceExport, export_for_write};
@@ -95,6 +105,36 @@ struct Session {
/// Whether a picture was coded: the driver began the session on the
/// device.
coded: bool,
/// The quality level asked of the driver and the one it took, once one
/// was sent (module docs, "The quality level").
quality: Option<QualityLevel>,
}
/// The quality level a session asked of the driver (`VAEncMiscParameterBufferQualityLevel`), and
/// the one it took: the asked one, the nearest the driver takes in its place, or none where it
/// took no level of the config's range (module docs, "The quality level").
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct QualityLevel {
/// The level the settings ask for.
pub asked: u32,
/// The level the driver took.
pub taken: Option<u32>,
}
/// The quality levels to render for `asked`, in turn until the driver takes one: `asked` first,
/// then the others of the config's `range` (`1..=range`) by their distance from it, the better
/// quality, the lower level, first at each distance. `asked` alone where the driver lists no
/// range or the range does not hold it.
pub(crate) fn quality_choices(asked: u32, range: Option<u32>) -> Vec<u32> {
let Some(range) = range.filter(|range| (1..=*range).contains(&asked)) else {
return vec![asked];
};
let mut levels = vec![asked];
for distance in 1..range {
let around = [asked.checked_sub(distance), asked.checked_add(distance)];
levels.extend((around.into_iter().flatten()).filter(|level| (1..=range).contains(level)));
}
levels
}
impl Session {
@@ -135,6 +175,8 @@ pub(crate) struct VaAccelerator {
entrypoint: Entrypoint,
/// The `VA_ENC_PACKED_HEADER_*` bits the config asks for.
packed_headers: u32,
/// `VAConfigAttribEncQualityRange`: the quality levels the config lists, `1..=range`.
quality_range: Option<u32>,
session: Option<Session>,
forced_upload: Option<UploadMethod>,
/// The picture the GPU did not finish by its deadline, once it has not
@@ -148,12 +190,14 @@ impl VaAccelerator {
profile: Profile,
entrypoint: Entrypoint,
packed_headers: u32,
quality_range: Option<u32>,
) -> Self {
Self {
display: display.clone_ref(),
profile,
entrypoint,
packed_headers,
quality_range,
session: None,
forced_upload: None,
stalled: None,
@@ -201,6 +245,11 @@ impl VaAccelerator {
self.packed_headers
}
/// The quality level the session asked of the driver and the one it took, once one was sent.
pub(crate) fn quality_level(&self) -> Option<QualityLevel> {
self.session.as_ref().and_then(|s| s.quality)
}
pub(crate) fn upload_method(&self) -> Option<UploadMethod> {
self.session.as_ref().and_then(|s| s.uploader.method())
}
@@ -357,6 +406,7 @@ impl Accelerator for VaAccelerator {
picture_qp: stream.picture_qp,
attempt: None,
coded: false,
quality: None,
});
Ok(())
}
@@ -396,7 +446,7 @@ impl Accelerator for VaAccelerator {
let coded = code_picture(
&self.display,
session,
self.packed_headers,
(self.packed_headers, self.quality_range),
input,
p,
&reconstructed,
@@ -432,17 +482,42 @@ impl Accelerator for VaAccelerator {
}
/// Codes picture `p` of `input` into `reconstructed`, on `session`: its
/// parameter buffers, its submission, and its coded buffer's bytes, waited
/// for by the frame's deadline (`super::super::wait`).
/// parameter buffers, its quality level first and alone where it sends one
/// (module docs), its submission, and its coded buffer's bytes, waited for
/// by the frame's deadline (`super::super::wait`). `config` is the config's
/// packed header bits and quality range.
fn code_picture(
display: &Display,
session: &Session,
packed_headers: u32,
session: &mut Session,
config: (u32, Option<u32>),
input: &Input,
p: &PictureParams<'_>,
reconstructed: &Lent,
) -> Result<Vec<u8>, Error> {
let (packed_headers, quality_range) = config;
let context = session.context_id();
// The quality level's choices, where the picture sends its misc buffers (module docs): the
// level the driver took for the same ask alone, else the ask's choices in turn.
let misc = p.frame_type == FrameType::Idr || p.rate_control_changed;
let kept = (session.quality)
.filter(|quality| Some(quality.asked) == p.settings.quality_level)
.and_then(|quality| quality.taken);
let levels = match (misc, p.settings.quality_level, kept) {
(true, Some(_), Some(taken)) => vec![taken],
(true, Some(asked), None) => quality_choices(asked, quality_range),
_ => Vec::new(),
};
let choices = (levels.iter())
.map(|&level| {
let quality = params::quality_level(level);
Buffer::with_value(
display,
context,
enc::VAEncMiscParameterBufferType,
&quality,
)
})
.collect::<Result<Vec<_>, Error>>()?;
let surface_of = |number: u64| {
session
.references
@@ -567,7 +642,12 @@ fn code_picture(
}
}
let all: Vec<&Buffer<'_>> = buffers.iter().collect();
render_picture(display, context, input.id(), &[&all])?;
let choice_refs: Vec<&Buffer<'_>> = choices.iter().collect();
let taken = render_encode(display, context, input.id(), &choice_refs, &[&all])?;
if let (Some(asked), false) = (p.settings.quality_level, levels.is_empty()) {
let taken = taken.and_then(|index| levels.get(index).copied());
session.quality = Some(QualityLevel { asked, taken });
}
let deadline = wait::current(display);
let coded = read_coded(
display,
@@ -580,9 +660,9 @@ fn code_picture(
}
/// The misc parameters: rate control, HRD and frame rate on IDR pictures
/// and when they change, as libva's users send them, and the quality level
/// with them. Where the encoder picks each picture's QP, the driver's
/// constant QP takes no rate control or HRD.
/// and when they change, as libva's users send them; the quality level is
/// rendered apart, first (module docs). Where the encoder picks each
/// picture's QP, the driver's constant QP takes no rate control or HRD.
fn push_misc<'a>(
buffers: &mut Vec<Buffer<'a>>,
display: &'a Display,
@@ -610,9 +690,6 @@ fn push_misc<'a>(
ty,
&params::frame_rate(settings),
)?);
if let Some(quality) = params::quality_level(settings) {
buffers.push(Buffer::with_value(display, context, ty, &quality)?);
}
Ok(())
}
@@ -464,18 +464,17 @@ pub(crate) fn frame_rate(
}
}
/// The quality level, when the settings ask for one.
/// The misc buffer of quality level `quality_level`.
pub(crate) fn quality_level(
settings: &EncoderSettings,
) -> Option<VAEncMiscParameterBuffer<VAEncMiscParameterBufferQualityLevel>> {
let quality_level = settings.quality_level?;
Some(VAEncMiscParameterBuffer {
quality_level: u32,
) -> VAEncMiscParameterBuffer<VAEncMiscParameterBufferQualityLevel> {
VAEncMiscParameterBuffer {
type_: enc::VAEncMiscParameterTypeQualityLevel,
data: VAEncMiscParameterBufferQualityLevel {
quality_level,
..VAEncMiscParameterBufferQualityLevel::default()
},
})
}
}
#[cfg(test)]
+39 -2
View File
@@ -65,14 +65,16 @@ use reims_vgpu_video::codec::encode::{
use reims_vgpu_video::core::backend::BackendError as VideoError;
use reims_vgpu_video::core::surfaces::PlaneLayout;
use reims_vgpu_video::paravirt::{Encoder, EncoderConfig, SourceFrame};
use reims_vgpu_video::vaapi::{Capabilities, Display, EncoderSupport, Target, VideoEncoder};
use reims_vgpu_video::vaapi::{
Capabilities, Display, EncoderSupport, QualityLevel, Target, VideoEncoder,
};
use reims_vgpu_vulkan::core::platform::Platform;
use reims_vgpu_vulkan::core::sync::Mutex;
use super::super::decode::{GuestEncoder, GuestSource, rate_past_first_frame, same_rate_mode};
use super::super::video_host::{
BackendError, EncodeFrame, EncodeSource, Encoded, FrameSource, HostEncodedFrame, HostEncoder,
OutputPlane, SourcePlane,
OutputPlane, QUALITY_ADJUSTED_CODE, SourcePlane,
};
use super::super::vt_encode::{
buffer_planes, encoders_of, host_planes, quality_percent, source_planes,
@@ -329,6 +331,8 @@ struct State {
settings: Option<RgfxVideoEncodeSettings>,
/// Whether the next frame is made a keyframe: the last one did not fit.
key_next: bool,
/// Whether the session said the driver took another quality level ([`said_quality`]).
quality_said: bool,
}
impl State {
@@ -483,6 +487,7 @@ impl<P: Platform> VaEncoder<P> {
encoder: None,
settings: None,
key_next: false,
quality_said: false,
})),
fills: Arc::new(Mutex::new(Fills::new(filler))),
supports,
@@ -687,6 +692,9 @@ fn finish_coded(
mut coded: Vec<Coded<reims_vgpu_video::vaapi::Error>>,
out: &mut [u8],
) -> Result<Encoded, BackendError> {
if let Some(encoder) = &state.encoder {
said_quality(encoder, &mut state.quality_said);
}
let codec = state.codec;
let encoder = state.encoder.as_mut().ok_or("an encode with no settings")?;
let sample = match (coded.pop(), coded.len()) {
@@ -806,6 +814,8 @@ pub(super) struct VaGuestEncoder<P: Platform> {
encoded: bool,
/// What writes its source frames into the encoder's inputs on the GPU (module doc).
fills: Fills<P>,
/// Whether the session said the driver took another quality level ([`said_quality`]).
quality_said: bool,
}
impl<P: Platform> VaGuestEncoder<P> {
@@ -833,6 +843,7 @@ impl<P: Platform> VaGuestEncoder<P> {
settings,
encoded: false,
fills: Fills::new(filler),
quality_said: false,
})
}
@@ -855,10 +866,35 @@ impl<P: Platform> VaGuestEncoder<P> {
return Ok(None);
};
let coded = (self.encoder.encode_target(&target, times)).map_err(super::video_error)?;
said_quality(&self.encoder, &mut self.quality_said);
Ok(Some(coded))
}
}
/// Says once a session, where `said` is false, that `encoder`'s driver refused the quality level
/// its settings ask for and took another or none (the VA crate's encoder docs, "The quality
/// level"), and counts the session ([`QUALITY_ADJUSTED_CODE`]).
fn said_quality(encoder: &VideoEncoder, said: &mut bool) {
let Some(QualityLevel { asked, taken }) = encoder.quality_level() else {
return;
};
if *said || taken == Some(asked) {
return;
}
*said = true;
reims_vgpu_vulkan::answer::count_kind(QUALITY_ADJUSTED_CODE);
match taken {
Some(taken) => log::info!(
"hardware video: VA-API: an encode session's driver refused quality level {asked}; \
the session codes at {taken}, the nearest level it takes"
),
None => log::info!(
"hardware video: VA-API: an encode session's driver refused quality level {asked} and \
every other level of its range; the session codes at the driver's own"
),
}
}
/// A profile a guest encoder codes, as the driver answers it.
#[derive(Clone, Copy, Debug)]
struct GuestProfile {
@@ -941,6 +977,7 @@ impl<P: Platform> GuestEncoder<P> for VaGuestEncoder<P> {
..times
};
let coded = self.encoder.encode(&input).map_err(super::video_error)?;
said_quality(&self.encoder, &mut self.quality_said);
drop(view);
self.encoded = true;
Ok(guest_coded(coded))
@@ -174,6 +174,13 @@ pub(crate) const CARRIED_CODE: &str = "video-landing-failure-carried";
/// logged once per boot, then counted").
pub(crate) const CONVERTED_CODE: &str = "video-pictures-cpu-converted";
/// The code of a VA-API encode session whose driver refused the quality level its settings ask
/// for and coded at another, the nearest it takes, or at its own (the VA crate's encoder docs,
/// "The quality level"): one a session, its first said on a line of its own, as a session's
/// answer to its quality is (`vaapi::encode`'s `said_quality`). A quality is a hint of speed
/// against quality, so the guest's stream is coded as asked in every other way.
pub(crate) const QUALITY_ADJUSTED_CODE: &str = "video-encode-quality-level-adjusted";
/// The code of a decode's picture handed to the guest that landed in its output (the module
/// docs, "What each decode hands the guest"), counted per process.
pub(crate) const HANDED_LANDED_CODE: &str = "video-pictures-handed-landed";
+4 -1
View File
@@ -214,7 +214,10 @@ repeats the ones code cites.
`video-pictures-handed-landed`, one that landed in its output,
`video-pictures-handed-failed`, one that failed to land or whose
decode was refused at its take, and `video-pictures-handed-undecoded`,
one that no decode ran for), the rt
one that no decode ran for), its VA-API encodes'
(`video-encode-quality-level-adjusted`, a session whose driver refused
the quality level asked and coded at the nearest it takes, or at its
own: one a session), the rt
platform's on Windows (`rt-d3d11-surfaces`, the surfaces over Direct3D
11 textures it made, and `rt-refused-d3d11-surface`, those it refused),
and the contexts' Private
+1
View File
@@ -189,6 +189,7 @@ one. A new trap found the same way goes here.
- A reference decoder can be the one that is wrong. The guest lane's HEVC check compared each frame the guest decoded with ffmpeg 9.0.2's software decode, and two streams coded with 16x16 CTBs (1366x766 and a 1280x720 bisect of it) differed on most frames. A bisect of x265's options pinned it to CTU 16 with SAO and deblocking both on, and the difference was first taken for a bug of NVIDIA's decoder, with a host self-check planned to refuse such streams. It was ffmpeg: x265's reconstruction (`--recon`) of the same streams equals NVIDIA's decode (through the core, ffmpeg's Vulkan hwaccel and NVDEC), VideoToolbox's on an M3 Max and the guest's on every frame, and ffmpeg's software decode differs from all four (**measured**, 2026-11-03; upstream report 98). `hevc-check.sh` had already found the same difference on AMD's decoders and checks against the reconstruction where the two differ; a check written later against ffmpeg alone met it again. How to spot the next one: when hardware decoders disagree with a software reference, compare each with the encoder's own reconstruction, and with a second vendor's hardware, before calling the hardware wrong; a check that has one software reference has none for the streams that reference gets wrong.
- A test built from a model of a guest's struct checks the writer, never the model. The guest driver's HEVC writer read AppleGVA's short-term sets with the delta lists at `+0xe8` and the flags after them; at `+0xe8` a predicted set held bytes of 1, which was read as "AppleGVA keeps the prediction's syntax but not the pictures", and the writer gained a derivation of its own (7-61, 7-62). The unit tests built AppleGVA's form of the stream from the same layout, so they passed, and the guest refused the stream's SPS on every picture. A dump of AppleGVA's real struct, compared with the stream's own syntax at every field, showed the flags at `+0xe8` and `+0xf8` and the deltas at `+0x108` and `+0x148`, every set's pictures derived by AppleGVA itself (**measured**, 2026-11-03, `hevc-main-720p-sets-sps`, 25 sets). How to spot the next one: before reading meaning into a field of a guest-held record, dump the record for an input whose every value is known and match each field to it; where only one stream exercises a field, the tests that model it say nothing about the guest.
- Tests that make throwaway git repositories inherit git's environment. `git rebase -x` and git's hooks export `GIT_DIR` and its kin to what they run, and `git -C DIR` does not override them. reims-ctl's tests of its update and its installer, run under `git rebase -x` in a linked worktree, ran their `git init`, `config` and `commit` on the enclosing repository: its shared config became `core.bare=true` with the tests' `user.name` and `user.email`, which stopped the main checkout ("this operation must be run in a work tree") and gave another worktree's commit the tests' author (**measured**, 2026-11-07). reims-ctl now drops those variables for each git and script it runs on a checkout, its tests' included (`update::GIT_REPOSITORY_ENV`). Never run tests under `git rebase -x` in a worktree that shares the main checkout's `.git`: check each commit in a worktree of its own (`git worktree add --detach`). How to spot the next one: a config change or a commit in a repository no command named, made while a hook or a rebase's exec ran.
- A render's status can answer for its last buffer, not for each. The VA crate rendered an encoder's quality level with the picture's other buffers; iHD 26.3.5's HEVC encoder refuses levels other than 1, 4 and 7, but its render loop only sets the status for a refused buffer and goes on, and the packed header after it sets the status again, so the render answered success and the sequence coded at the refused level. An arm64 guest's session at level 2 hung the Iris Xe's render engine (bugs.md, B102, U37), the level the likely trigger. A parameter whose refusal changes what is coded is now rendered alone, first, so the driver's answer is its own. How to spot the next one: a misc parameter rendered beside packed headers or other buffers whose refusal nothing has seen, on a driver whose config lists more values than its source takes.
- A driver can read an imported buffer by the size it is declared at, so a test over memory of the exact size does not check the path that declares more. The VA crate's test of a Y210 encoder input wrote the frame into host memory of the layout's 360448 bytes and coded at 59.3 dB luma; the GPU path imported rt's dma-buf block, declared at its 393216-byte allocation, and iHD 26.3.5 read the same bytes at 8 bytes a pixel, coding at 9.4 dB (potluck jobs m3-max-78926 and m3-max-78945: the input read back byte for byte as the layout says, then declared at 360448, coded at 59.3 dB). An import now declares the layout's bytes. How to spot the next one: a picture whose rows are right and whose columns are another column's samples, from an import the CPU's test of the same layout codes right.
- A driver's answers can disagree, and a rule derived from one of them takes its value on every driver. The H.264 caps' cut to 65,535 macroblocks (bugs.md, U28) kept the driver's largest width and lowered the height, tested on radeonsi's answer of 4096x4096. iHD answers 8192x8192 in `VAConfigAttribMaxPictureWidth` and `Height` while its surfaces' bound, and the widest picture it decodes, is 4096x4096, so the cut answered 8192x2032 there and the guest refused 3840x2160 at its create. Spot it by feeding each rule every driver's real answers, and the sizes users play (3840x2160, 4096x2160), not only the case the rule was written for.
- A kernel address looked up at runtime and cast to a function-pointer type panics an arm64e kext at the call site, not the cast. Graft returns a symbol's raw address as a `uint64_t` (`graft_kernel_symbol`). On arm64e a C function pointer is signed (`ptrauth_key_function_pointer`, zero discriminator for a plain fn-ptr type our code builds without pointer-type discrimination), and `reinterpret_cast<T>(addr)` from an integer makes the compiler authenticate the value as though it were already signed, so `autiza` traps under FEAT_FPAC the moment it runs: `PAC failure from kernel with IA key while authing x16`, the last-started kext, its `__TEXT_EXEC` plus the faulting offset. **Measured** 2026-11-09 on Ambrosia's fixed firmware: RgfxGate panicked at `installHooks()` right after the second `graft_kernel_symbol`, reboot-looping with SIP on. Sign the raw address for the schema the call site uses instead, `reinterpret_cast<T>(ptrauth_sign_unauthenticated(reinterpret_cast<void *>(addr), ptrauth_key_function_pointer, 0))`, behind `__arm64e__`. How to spot the next one: any integer or data pointer cast to a function-pointer type, or called through, in arm64e kext code; the disassembly must sign (`pacia`/`paciza`) the address, never authenticate it.
+16 -3
View File
@@ -142,9 +142,10 @@ Everything known to be wrong, untested or put off in the reims-graphics device's
### B102. HEVC Main 4:2:2 10 encode is held back: an arm64 guest's session hung the Iris Xe's render engine
- **What:** an arm64 macOS 26 guest's VideoToolbox session of `HEVC_Main42210_AutoLevel` on its paravirtual encoder, 640x360 at a `Quality` of 0.9 (a constant QP of 10, VA quality level 2 of 7), hung the Iris Xe's render engine on its first frame. i915 reset the encoder's context, the host's 5 s wait failed the session, and none of its 10 frames came out: frames 0 to 4 failed −19092, the guest's reply wait timing out, and 5 to 9 −12912, the host's malfunction. The profile is held back from the guest's list (`graphics/vaapi.rs`, `repacked_profiles`), so a session's set of it is refused, as it was before its encode was built.
- **Evidence:** **measured**, boot m3-max-79085, 2026-12-02, iHD 26.3.5 on Linux 7.3.1: the kernel logged "GPU HANG ... context reset due to GPU hang" for the context made on the host's video thread, iHD's, active on `rcs0`; iHD encodes this profile on its `EncSlice` entrypoint alone, whose encode runs kernels on the render engine. The host's tests of the same profile, at 330x202, a constant QP of 18 to 22 and quality level 4, code it and decode it back above 40 dB (m3-max-78959). **Read** in iHD's source: its HEVC encoder refuses quality levels other than 1, 4 and 7, keeps the refused one, and a packed header in the same render answers over the refusal, so this session coded at level 2, the likely trigger.
- **Why it waits:** confirming the trigger takes an encode of the guest's case, which can hang the GPU again: that run waits for the owner's word.
- **Fix, once allowed:** the quality level sent so that the driver's refusal is seen and a level it takes is used, then one encode of the guest's case; if it passes, the hold is reverted.
- **Evidence:** **measured**, boot m3-max-79085, 2026-12-02, iHD 26.3.5 on Linux 7.3.1: the kernel logged "GPU HANG ... context reset due to GPU hang" for the context made on the host's video thread, iHD's, active on `rcs0`; iHD encodes this profile on its `EncSlice` entrypoint alone, whose encode runs kernels on the render engine. The host's tests of the same profile, at 330x202, a constant QP of 18 to 22 and quality level 4, code it and decode it back above 40 dB (m3-max-78959). **Read** in iHD's source: its HEVC encoder refuses quality levels other than 1, 4 and 7, keeps the refused one, and a packed header in the same render answers over the refusal (U37), so this session coded at level 2, the likely trigger, unconfirmed: the read is a lead until the guest's case encodes under the fix below. No report on file names an Intel host's HEVC encode at a level iHD refuses but this boot's: the Intel rows on file (B98 to B101) are x86-64 guests', whose encoder asks level 4 of every session.
- **The fix so far:** the quality level is rendered alone, first, and a level the driver refuses gives way to the nearest it takes ([vaapi.md](vaapi.md), "Shape"), so on the Iris Xe the guest's 0.9, level 2, codes at level 1. **Measured** under the fix, on the Iris Xe, one encode of the host's 4:2:0 HEVC Main test at the asked level 2: the driver refused 2 and took 1, the stream decoded back at 52.5 to 53.2 dB luma, and the kernel logged no GPU hang or reset (m3-max-79388).
- **Why it waits:** confirming the trigger takes one encode of the guest's 4:2:2 case under the fix, which can hang the GPU again if the level was not the trigger: that run waits for the owner's word.
- **Fix, once allowed:** that one encode; if it passes, the hold is reverted.
- **Who has it:** the video lane.
## Upstream bugs
@@ -214,6 +215,18 @@ Bugs in drivers, libraries and tools that our code or our checks work around.
fails, and no picture is delivered wrong; the card test holds each frame to its reference or
to a failure NVDEC reported (`nvidia::annex_b::av1_tests`). A report is written (the upstream
folder's 149) and not filed. Not checked on other NVIDIA generations or drivers.
- **U37. iHD 26.3.5's HEVC encoder answers success for a render whose quality level it refused.**
On its Gen12 path the encoder keeps the level a `VAEncMiscParameterBufferQualityLevel` sends
as the context's target usage, then refuses any but 1, 4 and 7 of the 7 its config lists
(`VA_STATUS_ERROR_INVALID_PARAMETER`, answered as `VA_STATUS_ERROR_INVALID_BUFFER`). The
refusal only sets the render's status and goes on to the render's next buffer, and a packed
header's parse later in the same render sets the status again, so the render answers success
and the next sequence codes at the refused level (**read** in its source,
`media_ddi_encode_hevc.cpp`: `ParseMiscParams`, `RenderPicture`, and `EncodeInCodecHal`, which
`EndPicture` calls). Its H.264 encoder takes every level, raising levels 1 to 3 to 4 on this
GPU (`media_ddi_encode_avc.cpp`). Ours: the VA crate renders the level alone,
first, so the refusal is the render's answer, and codes at the nearest level the driver takes
([vaapi.md](vaapi.md), "Shape"); reims-vgpu counts and logs each session that does (B102).
## Untested, or tested by unit tests only
+1 -1
View File
@@ -526,7 +526,7 @@ buffer of an encode session's process (reims-vgpu's `graphics/video_host/encode.
| arm | encoder | its access unit |
|---|---|---|
| NVENC | `NvencEncoder` ([nvidia.md](nvidia.md)); `quality` picks the preset at the high-quality tuning: P1 up to the middle, 50, then P2 to P7, and the keyframe interval is the GOP (`graphics/nvidia/encode.rs`) | Annex B as NVENC writes it, its parameter sets before each IDR picture |
| VA-API | `VideoEncoder` ([vaapi.md](vaapi.md)), on `EncSlice`, else `EncSliceLP`; `quality` maps onto the driver's quality levels (`graphics/vaapi/encode.rs`) | the encoder's length-prefixed sample, written as Annex B, a keyframe's parameter sets first from its configuration record |
| VA-API | `VideoEncoder` ([vaapi.md](vaapi.md)), on `EncSlice`, else `EncSliceLP`; `quality` maps onto the driver's quality levels (`graphics/vaapi/encode.rs`), the nearest the driver takes where it refuses the one asked ([vaapi.md](vaapi.md), "Shape") | the encoder's length-prefixed sample, written as Annex B, a keyframe's parameter sets first from its configuration record |
## How each arm lands a picture
+14
View File
@@ -1487,6 +1487,20 @@ picture: the first sample carries the record it belongs with, and
buffer of one second at the peak. The bitrate, the frame rate and the
key-frame interval change mid-stream from the next picture; the mode
does not.
- **The quality level**, 1 the best of the range `VAConfigAttribEncQualityRange`
lists, is rendered alone, first, where a picture sends its misc
buffers (IDR pictures and a rate control change). Where the driver
refuses it, the nearest level it takes is rendered in its place, the
better quality first at a tie, before the picture's other buffers, and
the session keeps the level taken (`src/vaapi/va/encoder/accelerator.rs`'s
docs, "The quality level"). iHD 26.3.5's HEVC encoder takes 1, 4 and 7
alone and, sent the level with the picture's other buffers, answers
success for a level it refused and codes at it (bugs.md, U37): so there
2 codes at 1, 3 and 5 at 4, and 6 at 7. radeonsi takes every level of
its range (a Radeon 780M took level 2, m3-max-79256). reims-vgpu counts a
session whose level the driver refused as
`video-encode-quality-level-adjusted`, and logs it once a session; the
guest's stream is coded as it asked in every other way.
- **Small and odd sizes.** Below the driver's minimum (128x128, HEVC
130x128) the picture is padded up to it. Every size is padded to the
coded size (16 for H.264, the minimum CB for HEVC) by repeating the last