🆕 Decode VP9 on VA-API and NVDEC
The hosts' drivers list VP9 decode (radeonsi, iHD and NVDEC at profiles 0 and 2), and the owner's order is to offer the guest what the host lists. This is the host's half: the decoders. Nothing offers them to a guest yet, so no guest sees a change. The codec module (codec/vp9) does on the host what VP9's hardware APIs leave to the caller: it splits a superframe into its frames, reads each frame's uncompressed header and keeps what persists between frames (the colour configuration, the loop filter's deltas, the segmentation's features and the eight reference slots), derives the quantizer scales and filter levels, and hands each frame whole to an accelerator that decodes the compressed header and the tiles. It refuses profiles 1 and 3 and 12 bits before anything reaches a driver, and a frame that predicts from an empty slot is a picture's error, after which a key frame decodes. Every field is checked against the bytes before it is used: the CPU tests feed it truncated and hostile streams and superframe indexes (the fuzz targets vp9-streams and vp9-samples). VA-API's arm (vaapi::va::vp9) fills VADecPictureParameterBufferVP9 and the slice parameters per frame, with a context per run of one format and size. NVDEC's (nvidia::nvdec::vp9) fills CUVIDVP9PICPARAMS, whose bit-fields are held in words of our own naming and checked against NVIDIA's header with the rest of the layout. NVDEC makes a decoder at a frame's exact size, and a frame that predicts from one of another decoder, a resized stream's, is refused as a picture's error (bugs.md B96). Two streams libvpx made from a synthetic source (640x360, profile 0 and profile 2 at 10 bits, three superframes each) and vpxdec's per-frame MD5s are committed; the ignored card tests decode them bit-exact on the RX 7900 XTX's radeonsi, the Iris Xe's iHD and the RTX 3090's NVDEC.
This commit is contained in:
1 parent
5c30529e18
commit
4b8d51d09e
37 files changed
+4426
-12
No files matched your search
@@ -16,6 +16,10 @@
|
||||
//! - [`hevc`] is HEVC's: NAL units, `hvcC`, parameter sets with their
|
||||
//! reference picture sets, slice segment headers, order counts and the
|
||||
//! DPB, over an `Accelerator` likewise. It shares H.264's bit reader.
|
||||
//! - [`vp9`] is VP9's: superframes, `vpcC`, the uncompressed header and
|
||||
//! what it keeps between frames, the derived quantizer scales and filter
|
||||
//! levels, and the eight reference slots, over an `Accelerator` that
|
||||
//! decodes the compressed header and the tiles.
|
||||
|
||||
// The crate's lint set, core's but its division lint: the decoding
|
||||
// processes divide by what the standards divide by. Tests are exempt as in
|
||||
@@ -61,6 +65,7 @@ pub mod encode;
|
||||
pub mod h264;
|
||||
pub mod hevc;
|
||||
mod num;
|
||||
pub mod vp9;
|
||||
|
||||
/// Whether a later picture of its stream may predict from a picture, as its first slice says:
|
||||
/// what each codec's decoder tells its accelerator as it asks for the picture's storage
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! VP9's syntax above the compressed header, for a stateless accelerator:
|
||||
//! superframes, the uncompressed header and what it keeps from frame to
|
||||
//! frame (the loop filter's deltas and the segmentation's features), the
|
||||
//! eight reference slots, and which frames are shown (the VP9 Bitstream and
|
||||
//! Decoding Process Specification, version 0.6, by section).
|
||||
//!
|
||||
//! This module is plain Rust and runs on any host, so that its tests run on
|
||||
//! a Mac too. What decodes the compressed header and the tiles is an
|
||||
//! [`Accelerator`], which the VA-API and NVIDIA crates implement over their
|
||||
//! hardware: both take a frame's bytes whole, uncompressed header first,
|
||||
//! with the header's fields beside them.
|
||||
//!
|
||||
//! A sample is a frame or a superframe (Annex B), as a container's sample
|
||||
//! and VideoToolbox's sample buffer hold it: the host splits a superframe
|
||||
//! itself, from bytes the guest wrote ([`superframe`]). Profiles 0 and 2,
|
||||
//! 4:2:0 at 8 and 10 bits, are decoded; profiles 1 and 3, 12-bit samples
|
||||
//! and RGB are refused with [`Error::Unsupported`] ([`check_supported`]).
|
||||
|
||||
mod bits;
|
||||
pub mod config;
|
||||
mod decoder;
|
||||
pub mod header;
|
||||
pub mod quant;
|
||||
pub mod superframe;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
|
||||
pub use decoder::{
|
||||
Accelerator, Decoder, Format, FrameParams, MAX_SIDE, Output, Reference, check_supported,
|
||||
};
|
||||
|
||||
/// VP9's highest level, 6.2, as `vpcC` and VideoToolbox number it: ten times the level. Apple's
|
||||
/// own decoders' capabilities number AV1's levels the same way (63 for 6.3; the M3 Max's
|
||||
/// AppleAVD, macOS 27.0.1, which lists no VP9 capabilities of its own).
|
||||
pub const TOP_LEVEL: u32 = 62;
|
||||
|
||||
/// Why a sample could not be read or decoded.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// The data ended inside a syntax element.
|
||||
Truncated,
|
||||
/// A syntax element, or a variable the specification derives from
|
||||
/// them, named, is outside what the specification allows.
|
||||
OutOfRange(&'static str),
|
||||
/// A superframe index (Annex B) whose frames' sizes do not add up to
|
||||
/// the bytes before it, or that holds a frame of no bytes.
|
||||
BadSuperframe,
|
||||
/// A sample of no bytes, or more frames than a superframe holds.
|
||||
EmptySample,
|
||||
/// A frame whose compressed header, `header_size_in_bytes` long, runs
|
||||
/// past the frame, or is empty (7.2).
|
||||
BadHeaderSize,
|
||||
/// An inter frame names a reference slot that holds no frame, or a
|
||||
/// frame shows a slot that holds none: as after starting at a frame
|
||||
/// that is not a key frame.
|
||||
MissingReference,
|
||||
/// An inter frame whose reference has another bit depth or chroma
|
||||
/// subsampling, or a size it does not scale from (2 to 1/16 of its
|
||||
/// own; 8.5.2.3).
|
||||
BadReference,
|
||||
/// A frame larger than [`MAX_SIDE`] on a side.
|
||||
TooLarge,
|
||||
/// A feature this decoder does not implement, named.
|
||||
Unsupported(&'static str),
|
||||
/// A `vpcC` record shorter than its fixed fields, or of another version.
|
||||
BadVpcc,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Truncated => write!(f, "the frame ends inside a syntax element"),
|
||||
Self::OutOfRange(name) => write!(f, "{name} is out of range"),
|
||||
Self::BadSuperframe => write!(f, "a superframe index that does not fit its sample"),
|
||||
Self::EmptySample => write!(f, "a sample of no frame, or of more than a superframe"),
|
||||
Self::BadHeaderSize => write!(f, "a compressed header past its frame"),
|
||||
Self::MissingReference => write!(f, "a reference frame is missing"),
|
||||
Self::BadReference => write!(f, "a reference frame of another format or scale"),
|
||||
Self::TooLarge => write!(f, "a frame past {MAX_SIDE} on a side"),
|
||||
Self::Unsupported(what) => write!(f, "unsupported: {what}"),
|
||||
Self::BadVpcc => write!(f, "bad vpcC record"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Whether the error is one sample's of the stream, after which the
|
||||
/// decoder goes on with the next: what this decoder does not take
|
||||
/// ([`Self::Unsupported`]) and a `vpcC` record's errors are not.
|
||||
pub fn is_picture_error(&self) -> bool {
|
||||
!matches!(self, Self::Unsupported(_) | Self::BadVpcc)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
@@ -0,0 +1,64 @@
|
||||
//! Reading the uncompressed header's syntax elements (4.9, 9.1): `f(n)`,
|
||||
//! most significant bit first, and `su(n)`. VP9 has no emulation
|
||||
//! prevention, so positions are the frame's own.
|
||||
|
||||
use super::Error;
|
||||
|
||||
/// A reader over a frame's bytes that refuses with [`Error::Truncated`]
|
||||
/// past its end.
|
||||
pub(crate) struct BitReader<'a> {
|
||||
data: &'a [u8],
|
||||
/// The next bit's position, from the frame's first bit.
|
||||
position: usize,
|
||||
}
|
||||
|
||||
impl<'a> BitReader<'a> {
|
||||
pub(crate) fn new(data: &'a [u8]) -> Self {
|
||||
Self { data, position: 0 }
|
||||
}
|
||||
|
||||
/// `f(1)`.
|
||||
pub(crate) fn bit(&mut self) -> Result<bool, Error> {
|
||||
let byte = self
|
||||
.data
|
||||
.get(self.position / 8)
|
||||
.copied()
|
||||
.ok_or(Error::Truncated)?;
|
||||
// `position % 8` is below 8, so the shift does not overflow.
|
||||
let shift = 7u32.saturating_sub(u32::try_from(self.position % 8).unwrap_or(7));
|
||||
self.position = self.position.checked_add(1).ok_or(Error::Truncated)?;
|
||||
Ok((byte >> shift) & 1 == 1)
|
||||
}
|
||||
|
||||
/// `f(n)`, for `n` up to 16.
|
||||
pub(crate) fn bits(&mut self, n: u32) -> Result<u16, Error> {
|
||||
debug_assert!(n <= 16);
|
||||
let mut value = 0u32;
|
||||
for _ in 0..n {
|
||||
value = (value << 1) | u32::from(self.bit()?);
|
||||
}
|
||||
u16::try_from(value).map_err(|_| Error::OutOfRange("f(n)"))
|
||||
}
|
||||
|
||||
/// `f(n)`, for `n` up to 8.
|
||||
pub(crate) fn u8(&mut self, n: u32) -> Result<u8, Error> {
|
||||
debug_assert!(n <= 8);
|
||||
u8::try_from(self.bits(n)?).map_err(|_| Error::OutOfRange("f(n)"))
|
||||
}
|
||||
|
||||
/// `su(n)` (4.9): `n` bits of magnitude, then a sign bit, for `n` up to 8.
|
||||
pub(crate) fn su(&mut self, n: u32) -> Result<i16, Error> {
|
||||
let value = i16::from(self.u8(n)?);
|
||||
Ok(if self.bit()? {
|
||||
value.wrapping_neg()
|
||||
} else {
|
||||
value
|
||||
})
|
||||
}
|
||||
|
||||
/// The bytes read so far, a partial byte counting whole: where
|
||||
/// `trailing_bits()` ends the uncompressed header (6.2).
|
||||
pub(crate) fn bytes_read(&self) -> usize {
|
||||
self.position.div_ceil(8)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! The VP codec configuration record, `vpcC` (VP Codec ISO Media File Format
|
||||
//! Binding, 2.2): the box VideoToolbox's format description of a VP9 stream
|
||||
//! carries as a sample description extension atom, as an app made it from
|
||||
//! its container. It is a full box: version 1 and three flag bytes, then
|
||||
//! the stream's profile, level, bit depth, chroma subsampling, range and
|
||||
//! colour, and codec initialization data, which VP9 has none of.
|
||||
|
||||
use super::Error;
|
||||
|
||||
/// What a `vpcC` record says of its stream.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct VpCodecConfiguration {
|
||||
/// `profile`: 0 to 3.
|
||||
pub profile: u8,
|
||||
/// `level`: the level times ten (10 is level 1), or 0 where the record
|
||||
/// names none.
|
||||
pub level: u8,
|
||||
/// `bitDepth`: 8, 10 or 12.
|
||||
pub bit_depth: u8,
|
||||
/// `chromaSubsampling`: 0 is 4:2:0 with chroma beside its luma
|
||||
/// vertically, 1 4:2:0 colocated with luma, 2 4:2:2, 3 4:4:4.
|
||||
pub chroma_subsampling: u8,
|
||||
/// `videoFullRangeFlag`.
|
||||
pub full_range: bool,
|
||||
/// `colourPrimaries` (ISO/IEC 23091-2).
|
||||
pub colour_primaries: u8,
|
||||
/// `transferCharacteristics`.
|
||||
pub transfer_characteristics: u8,
|
||||
/// `matrixCoefficients`.
|
||||
pub matrix_coefficients: u8,
|
||||
}
|
||||
|
||||
impl VpCodecConfiguration {
|
||||
/// The fixed part of a version 1 record: the full box's version and
|
||||
/// flags, then eight bytes, the initialization data's length last.
|
||||
const FIXED_BYTES: usize = 12;
|
||||
|
||||
/// Reads a `vpcC` record's payload, the box's version and flags first.
|
||||
/// A record shorter than its fixed fields, or of another version, is
|
||||
/// [`Error::BadVpcc`]; its initialization data, VP9's empty, is not
|
||||
/// read.
|
||||
pub fn parse(record: &[u8]) -> Result<Self, Error> {
|
||||
let fixed: &[u8; Self::FIXED_BYTES] = record
|
||||
.get(..Self::FIXED_BYTES)
|
||||
.and_then(|bytes| bytes.try_into().ok())
|
||||
.ok_or(Error::BadVpcc)?;
|
||||
let [
|
||||
version,
|
||||
_,
|
||||
_,
|
||||
_,
|
||||
profile,
|
||||
level,
|
||||
packed,
|
||||
primaries,
|
||||
transfer,
|
||||
matrix,
|
||||
_,
|
||||
_,
|
||||
] = *fixed;
|
||||
if version != 1 {
|
||||
return Err(Error::BadVpcc);
|
||||
}
|
||||
Ok(Self {
|
||||
profile,
|
||||
level,
|
||||
bit_depth: packed >> 4,
|
||||
chroma_subsampling: (packed >> 1) & 7,
|
||||
full_range: packed & 1 == 1,
|
||||
colour_primaries: primaries,
|
||||
transfer_characteristics: transfer,
|
||||
matrix_coefficients: matrix,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the record names 4:2:0 samples (either siting).
|
||||
pub fn is_4_2_0(&self) -> bool {
|
||||
self.chroma_subsampling <= 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
//! The decoding process above the compressed header: each sample's frames,
|
||||
//! their headers against the state the frames before them left, the eight
|
||||
//! reference slots, and which frames come out. What decodes a frame's
|
||||
//! compressed header and tiles is an [`Accelerator`].
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::header::{self, FrameHeader, State};
|
||||
use super::quant::{self, SegmentParams};
|
||||
use super::superframe;
|
||||
use super::{Error, config::VpCodecConfiguration};
|
||||
|
||||
/// The largest side this decoder takes, past what any lab driver decodes
|
||||
/// (8192 on the AMD cards and the 3090, 16384 on the Iris Xe) and far
|
||||
/// below VP9's 65536: a frame past it is [`Error::TooLarge`] before an
|
||||
/// accelerator sees it. Each accelerator holds frames to its driver's own
|
||||
/// limits when it is configured.
|
||||
pub const MAX_SIDE: u32 = 16384;
|
||||
|
||||
/// What an accelerator decodes a run of frames as: their profile, sample
|
||||
/// format and size. A frame of another is decoded after a new
|
||||
/// [`Accelerator::configure`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Format {
|
||||
/// `Profile`: 0 or 2 here ([`check_supported`]).
|
||||
pub profile: u8,
|
||||
/// `BitDepth`: 8 or 10 here.
|
||||
pub bit_depth: u8,
|
||||
/// `FrameWidth`.
|
||||
pub width: u32,
|
||||
/// `FrameHeight`.
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
/// A frame in a reference slot, as an accelerator sees it.
|
||||
pub struct Reference<'a, P> {
|
||||
/// Its picture.
|
||||
pub picture: &'a P,
|
||||
/// Its `FrameWidth`.
|
||||
pub width: u32,
|
||||
/// Its `FrameHeight`.
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
/// What one frame's decode is given.
|
||||
pub struct FrameParams<'a, P> {
|
||||
/// The frame's uncompressed header.
|
||||
pub header: &'a FrameHeader,
|
||||
/// Each segment's derived quantizer scales and filter levels.
|
||||
pub segments: &'a [SegmentParams; header::MAX_SEGMENTS],
|
||||
/// The eight reference slots, `None` where a slot holds no frame.
|
||||
pub references: [Option<Reference<'a, P>>; 8],
|
||||
/// The frame's bytes, the uncompressed header first.
|
||||
pub frame: &'a [u8],
|
||||
}
|
||||
|
||||
/// What decodes a frame's compressed header and tiles: the hardware's
|
||||
/// half of a stateless decoder.
|
||||
pub trait Accelerator {
|
||||
/// A decoded frame's storage, such as a VA surface.
|
||||
type Picture;
|
||||
/// The accelerator's error, which carries this module's errors too.
|
||||
type Error: From<Error>;
|
||||
|
||||
/// Prepares for frames of `format`: called before the first frame, and
|
||||
/// again before a frame of another format or size. Frames decoded
|
||||
/// before stay referenced by the slots that hold them.
|
||||
fn configure(&mut self, format: &Format) -> Result<(), Self::Error>;
|
||||
|
||||
/// Storage for the frame about to decode, of the configured format.
|
||||
fn new_picture(&mut self) -> Result<Self::Picture, Self::Error>;
|
||||
|
||||
/// Decodes one frame into `picture`.
|
||||
fn decode_frame(
|
||||
&mut self,
|
||||
picture: &Self::Picture,
|
||||
params: &FrameParams<'_, Self::Picture>,
|
||||
) -> Result<(), Self::Error>;
|
||||
}
|
||||
|
||||
/// A frame as the decoder emits it: each frame shown, in decode order,
|
||||
/// which is VP9's display order.
|
||||
pub struct Output<P> {
|
||||
/// The accelerator's picture holding the samples.
|
||||
pub picture: Arc<P>,
|
||||
/// The id the sample that carried the frame was decoded with.
|
||||
pub id: u64,
|
||||
/// Whether the frame is a key frame.
|
||||
pub key_frame: bool,
|
||||
/// Whether a slot holds it, for later frames to predict from: a frame
|
||||
/// that refreshes a slot, or one a slot shows.
|
||||
pub reference: bool,
|
||||
/// `FrameWidth` and `FrameHeight`.
|
||||
pub size: (u32, u32),
|
||||
/// `BitDepth`.
|
||||
pub bit_depth: u8,
|
||||
/// `color_range`.
|
||||
pub full_range: bool,
|
||||
}
|
||||
|
||||
/// A frame a slot holds.
|
||||
struct Slot<P> {
|
||||
picture: Arc<P>,
|
||||
key_frame: bool,
|
||||
width: u32,
|
||||
height: u32,
|
||||
color: header::ColorConfig,
|
||||
}
|
||||
|
||||
/// A VP9 decoder over an [`Accelerator`], one sample (a frame or a
|
||||
/// superframe) per call.
|
||||
///
|
||||
/// A sample that does not decode leaves the slots and the header's state
|
||||
/// as the frames before it left them, and the decoder takes the next
|
||||
/// sample as it would any: one that predicts from a slot no frame filled
|
||||
/// is [`Error::MissingReference`], until a key frame fills them.
|
||||
pub struct Decoder<A: Accelerator> {
|
||||
accelerator: A,
|
||||
slots: [Option<Slot<A::Picture>>; 8],
|
||||
state: State,
|
||||
/// The format the accelerator is configured for.
|
||||
active: Option<Format>,
|
||||
}
|
||||
|
||||
impl<A: Accelerator> Decoder<A> {
|
||||
/// A decoder with no frame yet.
|
||||
pub fn new(accelerator: A) -> Self {
|
||||
Self {
|
||||
accelerator,
|
||||
slots: Default::default(),
|
||||
state: State::default(),
|
||||
active: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The accelerator.
|
||||
pub fn accelerator(&self) -> &A {
|
||||
&self.accelerator
|
||||
}
|
||||
|
||||
/// The accelerator, to change its settings.
|
||||
pub fn accelerator_mut(&mut self) -> &mut A {
|
||||
&mut self.accelerator
|
||||
}
|
||||
|
||||
/// Forgets every slot and the header's state, as for a seek: the next
|
||||
/// frame decodes only if it is a key frame.
|
||||
pub fn reset(&mut self) {
|
||||
self.slots = Default::default();
|
||||
self.state = State::default();
|
||||
}
|
||||
|
||||
/// Decodes `sample`, a frame or a superframe, tagged `id`, and answers
|
||||
/// the frames it shows: one for a sample a container holds, none for a
|
||||
/// sample of hidden frames alone.
|
||||
pub fn decode(&mut self, sample: &[u8], id: u64) -> Result<Vec<Output<A::Picture>>, A::Error> {
|
||||
let frames = superframe::frames(sample)?;
|
||||
let mut outputs = Vec::new();
|
||||
for frame in frames {
|
||||
if let Some(output) = self.decode_frame(frame, id)? {
|
||||
outputs.push(output);
|
||||
}
|
||||
}
|
||||
Ok(outputs)
|
||||
}
|
||||
|
||||
/// Decodes one frame, and answers it where it is shown.
|
||||
fn decode_frame(
|
||||
&mut self,
|
||||
frame: &[u8],
|
||||
id: u64,
|
||||
) -> Result<Option<Output<A::Picture>>, A::Error> {
|
||||
let ref_sizes = self
|
||||
.slots
|
||||
.each_ref()
|
||||
.map(|slot| slot.as_ref().map(|s| (s.width, s.height)));
|
||||
let (header, state) = header::parse(frame, &self.state, &ref_sizes)?;
|
||||
if let Some(index) = header.show_existing_frame {
|
||||
let slot = self
|
||||
.slots
|
||||
.get(usize::from(index))
|
||||
.and_then(Option::as_ref)
|
||||
.ok_or(Error::MissingReference)?;
|
||||
return Ok(Some(Output {
|
||||
picture: Arc::clone(&slot.picture),
|
||||
id,
|
||||
key_frame: slot.key_frame,
|
||||
reference: true,
|
||||
size: (slot.width, slot.height),
|
||||
bit_depth: slot.color.bit_depth,
|
||||
full_range: slot.color.full_range,
|
||||
}));
|
||||
}
|
||||
let format = check_frame(&header)?;
|
||||
if !header.is_intra() {
|
||||
self.check_references(&header)?;
|
||||
}
|
||||
if self.active != Some(format) {
|
||||
self.active = None;
|
||||
self.accelerator.configure(&format)?;
|
||||
self.active = Some(format);
|
||||
}
|
||||
let picture = self.accelerator.new_picture()?;
|
||||
let segments = quant::segment_params(&header);
|
||||
let references = self.slots.each_ref().map(|slot| {
|
||||
slot.as_ref().map(|slot| Reference {
|
||||
picture: &*slot.picture,
|
||||
width: slot.width,
|
||||
height: slot.height,
|
||||
})
|
||||
});
|
||||
let params = FrameParams {
|
||||
header: &header,
|
||||
segments: &segments,
|
||||
references,
|
||||
frame,
|
||||
};
|
||||
self.accelerator.decode_frame(&picture, ¶ms)?;
|
||||
self.state = state;
|
||||
let picture = Arc::new(picture);
|
||||
for (bit, slot) in self.slots.iter_mut().enumerate() {
|
||||
if (header.refresh_frame_flags >> bit) & 1 == 1 {
|
||||
*slot = Some(Slot {
|
||||
picture: Arc::clone(&picture),
|
||||
key_frame: header.key_frame,
|
||||
width: header.width,
|
||||
height: header.height,
|
||||
color: header.color,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(header.show_frame.then(|| Output {
|
||||
picture,
|
||||
id,
|
||||
key_frame: header.key_frame,
|
||||
reference: header.refresh_frame_flags != 0,
|
||||
size: (header.width, header.height),
|
||||
bit_depth: header.color.bit_depth,
|
||||
full_range: header.color.full_range,
|
||||
}))
|
||||
}
|
||||
|
||||
/// An inter frame's three references: each slot holds a frame of the
|
||||
/// frame's bit depth and subsampling, of a size it scales from
|
||||
/// (8.5.2.3: twice the frame's at most, a sixteenth at least).
|
||||
fn check_references(&self, header: &FrameHeader) -> Result<(), Error> {
|
||||
for &index in &header.ref_frame_idx {
|
||||
let slot = self
|
||||
.slots
|
||||
.get(usize::from(index))
|
||||
.and_then(Option::as_ref)
|
||||
.ok_or(Error::MissingReference)?;
|
||||
let same_format = slot.color.bit_depth == header.color.bit_depth
|
||||
&& slot.color.subsampling_x == header.color.subsampling_x
|
||||
&& slot.color.subsampling_y == header.color.subsampling_y;
|
||||
let scales = |frame: u32, reference: u32| {
|
||||
u64::from(frame).saturating_mul(2) >= u64::from(reference)
|
||||
&& u64::from(frame) <= u64::from(reference).saturating_mul(16)
|
||||
};
|
||||
if !same_format
|
||||
|| !scales(header.width, slot.width)
|
||||
|| !scales(header.height, slot.height)
|
||||
{
|
||||
return Err(Error::BadReference);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame's format, where this decoder takes it: profile 0 or 2, 4:2:0 at
|
||||
/// 8 or 10 bits, no side past [`MAX_SIDE`].
|
||||
fn check_frame(header: &FrameHeader) -> Result<Format, Error> {
|
||||
let color = &header.color;
|
||||
if !(color.subsampling_x && color.subsampling_y) {
|
||||
return Err(Error::Unsupported("VP9 other than 4:2:0"));
|
||||
}
|
||||
match (header.profile, color.bit_depth) {
|
||||
(0, 8) | (2, 10) => {}
|
||||
(2, _) => return Err(Error::Unsupported("VP9 at 12 bits")),
|
||||
_ => return Err(Error::Unsupported("VP9 profiles 1 and 3")),
|
||||
}
|
||||
if header.width > MAX_SIDE || header.height > MAX_SIDE {
|
||||
return Err(Error::TooLarge);
|
||||
}
|
||||
Ok(Format {
|
||||
profile: header.profile,
|
||||
bit_depth: color.bit_depth,
|
||||
width: header.width,
|
||||
height: header.height,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether this decoder takes a stream of `config`'s record: profile 0 at
|
||||
/// 8 bits or profile 2 at 10, 4:2:0. What a frame's own header says is
|
||||
/// checked again at each frame.
|
||||
pub fn check_supported(config: &VpCodecConfiguration) -> Result<(), Error> {
|
||||
if !config.is_4_2_0() {
|
||||
return Err(Error::Unsupported("VP9 other than 4:2:0"));
|
||||
}
|
||||
match (config.profile, config.bit_depth) {
|
||||
(0, 8) | (2, 10) => Ok(()),
|
||||
(2, _) => Err(Error::Unsupported("VP9 at 12 bits")),
|
||||
_ => Err(Error::Unsupported("VP9 profiles 1 and 3")),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
//! The uncompressed header (6.2, 7.2), and what it keeps from one frame to
|
||||
//! the next ([`State`]): the loop filter's deltas, the segmentation's
|
||||
//! probabilities and features, and the colour configuration the last intra
|
||||
//! frame gave. Each element is read as the specification reads it; the
|
||||
//! values the accelerators take are kept in the specification's terms,
|
||||
//! and each accelerator maps them to its own.
|
||||
|
||||
use super::Error;
|
||||
use super::bits::BitReader;
|
||||
|
||||
/// `frame_sync_code()` (6.2.1).
|
||||
const SYNC_CODE: [u8; 3] = [0x49, 0x83, 0x42];
|
||||
/// `color_space`'s `CS_BT_601` (7.2.2).
|
||||
pub const CS_BT_601: u8 = 1;
|
||||
/// `color_space`'s `CS_RGB` (7.2.2).
|
||||
pub const CS_RGB: u8 = 7;
|
||||
/// The interpolation filter that each block chooses (`SWITCHABLE`), in the
|
||||
/// numbering VA-API's `mcomp_filter_type` and NVDEC's take: libvpx's, where
|
||||
/// `EIGHTTAP` is 0 and `EIGHTTAP_SMOOTH` 1.
|
||||
pub const SWITCHABLE: u8 = 4;
|
||||
/// The segments a frame has (`MAX_SEGMENTS`).
|
||||
pub const MAX_SEGMENTS: usize = 8;
|
||||
/// The features a segment has (`SEG_LVL_MAX`): the quantizer, the loop
|
||||
/// filter level, the reference frame and skip, in that order.
|
||||
pub const SEG_LVL_MAX: usize = 4;
|
||||
/// `segmentation_feature_bits` (7.2.10).
|
||||
const FEATURE_BITS: [u32; SEG_LVL_MAX] = [8, 6, 2, 0];
|
||||
/// `segmentation_feature_signed` (7.2.10).
|
||||
const FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, false, false];
|
||||
/// `loop_filter_ref_deltas` as `setup_past_independence()` leaves them:
|
||||
/// intra 1, last 0, golden −1, altref −1.
|
||||
const DEFAULT_REF_DELTAS: [i8; 4] = [1, 0, -1, -1];
|
||||
|
||||
/// A frame's colour configuration (7.2.2): what a key frame and a
|
||||
/// profile's intra-only frame code, and what inter frames take from them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ColorConfig {
|
||||
/// `BitDepth`: 8, 10 or 12.
|
||||
pub bit_depth: u8,
|
||||
/// `color_space`.
|
||||
pub color_space: u8,
|
||||
/// `color_range`.
|
||||
pub full_range: bool,
|
||||
/// `subsampling_x`.
|
||||
pub subsampling_x: bool,
|
||||
/// `subsampling_y`.
|
||||
pub subsampling_y: bool,
|
||||
}
|
||||
|
||||
/// `loop_filter_params()` (7.2.8), with the deltas in force.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct LoopFilter {
|
||||
/// `loop_filter_level`: 0 to 63.
|
||||
pub level: u8,
|
||||
/// `loop_filter_sharpness`: 0 to 7.
|
||||
pub sharpness: u8,
|
||||
/// `loop_filter_delta_enabled`.
|
||||
pub delta_enabled: bool,
|
||||
/// `loop_filter_ref_deltas`, intra, last, golden and altref: those this
|
||||
/// frame coded, else those kept.
|
||||
pub ref_deltas: [i8; 4],
|
||||
/// `loop_filter_mode_deltas`, likewise.
|
||||
pub mode_deltas: [i8; 2],
|
||||
}
|
||||
|
||||
/// `quantization_params()` (7.2.9).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Quantization {
|
||||
/// `base_q_idx`.
|
||||
pub base_q_idx: u8,
|
||||
/// `delta_q_y_dc`: −15 to 15.
|
||||
pub delta_q_y_dc: i8,
|
||||
/// `delta_q_uv_dc`.
|
||||
pub delta_q_uv_dc: i8,
|
||||
/// `delta_q_uv_ac`.
|
||||
pub delta_q_uv_ac: i8,
|
||||
}
|
||||
|
||||
impl Quantization {
|
||||
/// `Lossless` (7.2.9).
|
||||
pub fn lossless(&self) -> bool {
|
||||
self.base_q_idx == 0
|
||||
&& self.delta_q_y_dc == 0
|
||||
&& self.delta_q_uv_dc == 0
|
||||
&& self.delta_q_uv_ac == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// `segmentation_params()` (7.2.10), with the probabilities and features in
|
||||
/// force.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Segmentation {
|
||||
/// `segmentation_enabled`.
|
||||
pub enabled: bool,
|
||||
/// `segmentation_update_map`: false where segmentation is off.
|
||||
pub update_map: bool,
|
||||
/// `segmentation_temporal_update`: false where the map is not updated.
|
||||
pub temporal_update: bool,
|
||||
/// `segmentation_abs_or_delta_update`, as last coded since the last
|
||||
/// intra or error-resilient frame.
|
||||
pub abs_or_delta_update: bool,
|
||||
/// `segmentation_tree_probs`, as last coded.
|
||||
pub tree_probs: [u8; 7],
|
||||
/// `segmentation_pred_prob`, as last coded.
|
||||
pub pred_probs: [u8; 3],
|
||||
/// `FeatureEnabled`, each segment's four.
|
||||
pub feature_enabled: [[bool; SEG_LVL_MAX]; MAX_SEGMENTS],
|
||||
/// `FeatureData`, likewise.
|
||||
pub feature_data: [[i16; SEG_LVL_MAX]; MAX_SEGMENTS],
|
||||
}
|
||||
|
||||
impl Default for Segmentation {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
update_map: false,
|
||||
temporal_update: false,
|
||||
abs_or_delta_update: false,
|
||||
tree_probs: [255; 7],
|
||||
pred_probs: [255; 3],
|
||||
feature_enabled: [[false; SEG_LVL_MAX]; MAX_SEGMENTS],
|
||||
feature_data: [[0; SEG_LVL_MAX]; MAX_SEGMENTS],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the uncompressed header keeps between frames: each frame's header
|
||||
/// is read against it and leaves it as the frame changed it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct State {
|
||||
/// The colour configuration in force: the last key frame's or intra-only
|
||||
/// frame's; `None` before the first.
|
||||
pub color: Option<ColorConfig>,
|
||||
/// The loop filter's deltas.
|
||||
pub ref_deltas: [i8; 4],
|
||||
/// See `ref_deltas`.
|
||||
pub mode_deltas: [i8; 2],
|
||||
/// The segmentation's probabilities and features.
|
||||
pub segmentation: Segmentation,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// `setup_past_independence()` (7.2), what this module keeps of it:
|
||||
/// the segmentation's features cleared and the loop filter's deltas as
|
||||
/// a key frame starts them. The probability tables it resets are the
|
||||
/// accelerator's, which `reset_frame_context` and the frame's type tell.
|
||||
fn setup_past_independence(&mut self) {
|
||||
let segmentation = &mut self.segmentation;
|
||||
segmentation.feature_enabled = [[false; SEG_LVL_MAX]; MAX_SEGMENTS];
|
||||
segmentation.feature_data = [[0; SEG_LVL_MAX]; MAX_SEGMENTS];
|
||||
segmentation.abs_or_delta_update = false;
|
||||
self.ref_deltas = DEFAULT_REF_DELTAS;
|
||||
self.mode_deltas = [0; 2];
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame's uncompressed header.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct FrameHeader {
|
||||
/// `Profile`: 0 to 3.
|
||||
pub profile: u8,
|
||||
/// `frame_to_show_map_idx` of a frame with `show_existing_frame`, which
|
||||
/// shows that slot's frame and has no other field.
|
||||
pub show_existing_frame: Option<u8>,
|
||||
/// `frame_type` is `KEY_FRAME`.
|
||||
pub key_frame: bool,
|
||||
/// `show_frame`.
|
||||
pub show_frame: bool,
|
||||
/// `error_resilient_mode`.
|
||||
pub error_resilient_mode: bool,
|
||||
/// `intra_only`.
|
||||
pub intra_only: bool,
|
||||
/// `reset_frame_context`: 0 where not coded.
|
||||
pub reset_frame_context: u8,
|
||||
/// The colour configuration the frame decodes with.
|
||||
pub color: ColorConfig,
|
||||
/// `refresh_frame_flags`: bit `i` stores the frame in slot `i`.
|
||||
pub refresh_frame_flags: u8,
|
||||
/// `ref_frame_idx`: the slots of the last, golden and altref frames;
|
||||
/// zeros in an intra frame.
|
||||
pub ref_frame_idx: [u8; 3],
|
||||
/// `ref_frame_sign_bias` of the last, golden and altref frames.
|
||||
pub ref_frame_sign_bias: [bool; 3],
|
||||
/// `FrameWidth`: 1 to 65536.
|
||||
pub width: u32,
|
||||
/// `FrameHeight`.
|
||||
pub height: u32,
|
||||
/// `RenderWidth`.
|
||||
pub render_width: u32,
|
||||
/// `RenderHeight`.
|
||||
pub render_height: u32,
|
||||
/// `allow_high_precision_mv`: false in an intra frame.
|
||||
pub allow_high_precision_mv: bool,
|
||||
/// `interp_filter`, in libvpx's numbering ([`SWITCHABLE`]); 0 in an
|
||||
/// intra frame.
|
||||
pub interp_filter: u8,
|
||||
/// `refresh_frame_context`.
|
||||
pub refresh_frame_context: bool,
|
||||
/// `frame_parallel_decoding_mode`.
|
||||
pub frame_parallel_decoding_mode: bool,
|
||||
/// `frame_context_idx` as coded, but 0 in a key frame and an intra-only
|
||||
/// frame, which libvpx and ffmpeg hand their hardware so.
|
||||
pub frame_context_idx: u8,
|
||||
/// The loop filter.
|
||||
pub loop_filter: LoopFilter,
|
||||
/// The quantizer.
|
||||
pub quantization: Quantization,
|
||||
/// The segmentation.
|
||||
pub segmentation: Segmentation,
|
||||
/// `tile_cols_log2`.
|
||||
pub tile_cols_log2: u8,
|
||||
/// `tile_rows_log2`.
|
||||
pub tile_rows_log2: u8,
|
||||
/// `header_size_in_bytes`: the compressed header's.
|
||||
pub header_size_in_bytes: u16,
|
||||
/// The uncompressed header's bytes, `trailing_bits()` included.
|
||||
pub uncompressed_header_size: u8,
|
||||
}
|
||||
|
||||
impl FrameHeader {
|
||||
/// `FrameIsIntra`.
|
||||
pub fn is_intra(&self) -> bool {
|
||||
self.key_frame || self.intra_only
|
||||
}
|
||||
|
||||
/// A frame that shows slot `index`'s frame.
|
||||
fn show_existing(profile: u8, index: u8, state: &State, header_bytes: usize) -> Self {
|
||||
let color = state.color.unwrap_or(ColorConfig {
|
||||
bit_depth: 8,
|
||||
color_space: 0,
|
||||
full_range: false,
|
||||
subsampling_x: true,
|
||||
subsampling_y: true,
|
||||
});
|
||||
Self {
|
||||
profile,
|
||||
show_existing_frame: Some(index),
|
||||
key_frame: false,
|
||||
show_frame: true,
|
||||
error_resilient_mode: false,
|
||||
intra_only: false,
|
||||
reset_frame_context: 0,
|
||||
color,
|
||||
refresh_frame_flags: 0,
|
||||
ref_frame_idx: [0; 3],
|
||||
ref_frame_sign_bias: [false; 3],
|
||||
width: 0,
|
||||
height: 0,
|
||||
render_width: 0,
|
||||
render_height: 0,
|
||||
allow_high_precision_mv: false,
|
||||
interp_filter: 0,
|
||||
refresh_frame_context: false,
|
||||
frame_parallel_decoding_mode: false,
|
||||
frame_context_idx: 0,
|
||||
loop_filter: LoopFilter::default(),
|
||||
quantization: Quantization::default(),
|
||||
segmentation: state.segmentation,
|
||||
tile_cols_log2: 0,
|
||||
tile_rows_log2: 0,
|
||||
header_size_in_bytes: 0,
|
||||
uncompressed_header_size: u8::try_from(header_bytes).unwrap_or(u8::MAX),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `frame`'s uncompressed header against `state` and the sizes of the
|
||||
/// frames in the eight reference slots, which an inter frame's size may be
|
||||
/// taken from, and answers it with the state it leaves. `state` itself is
|
||||
/// left as it was, for a caller that drops a frame that does not decode.
|
||||
///
|
||||
/// A compressed header past the frame, or empty, is
|
||||
/// [`Error::BadHeaderSize`]; an inter frame before any frame gave a colour
|
||||
/// configuration, or taking its size from an empty slot, is
|
||||
/// [`Error::MissingReference`].
|
||||
pub fn parse(
|
||||
frame: &[u8],
|
||||
state: &State,
|
||||
ref_sizes: &[Option<(u32, u32)>; 8],
|
||||
) -> Result<(FrameHeader, State), Error> {
|
||||
let mut r = BitReader::new(frame);
|
||||
let mut next = state.clone();
|
||||
if r.u8(2)? != 2 {
|
||||
return Err(Error::OutOfRange("frame_marker"));
|
||||
}
|
||||
let low = u8::from(r.bit()?);
|
||||
let high = u8::from(r.bit()?);
|
||||
let profile = (high << 1) | low;
|
||||
if profile == 3 && r.bit()? {
|
||||
return Err(Error::OutOfRange("reserved_zero"));
|
||||
}
|
||||
if r.bit()? {
|
||||
let index = r.u8(3)?;
|
||||
let header = FrameHeader::show_existing(profile, index, state, r.bytes_read());
|
||||
return Ok((header, next));
|
||||
}
|
||||
let key_frame = !r.bit()?;
|
||||
let show_frame = r.bit()?;
|
||||
let error_resilient_mode = r.bit()?;
|
||||
let (intra_only, reset_frame_context) = if key_frame {
|
||||
(false, 0)
|
||||
} else {
|
||||
let intra_only = !show_frame && r.bit()?;
|
||||
let reset = if error_resilient_mode { 0 } else { r.u8(2)? };
|
||||
(intra_only, reset)
|
||||
};
|
||||
let mut ref_frame_idx = [0u8; 3];
|
||||
let mut ref_frame_sign_bias = [false; 3];
|
||||
let mut allow_high_precision_mv = false;
|
||||
let mut interp_filter = 0;
|
||||
// Each branch reads `render_size()` right after the frame's size, as
|
||||
// `frame_size_with_refs()` does (6.2.5).
|
||||
let (color, refresh_frame_flags, (width, height), (render_width, render_height)) = if key_frame
|
||||
{
|
||||
sync_code(&mut r)?;
|
||||
let color = color_config(&mut r, profile)?;
|
||||
let size = frame_size(&mut r)?;
|
||||
(color, 0xff, size, render_size(&mut r, size)?)
|
||||
} else if intra_only {
|
||||
sync_code(&mut r)?;
|
||||
let color = if profile > 0 {
|
||||
color_config(&mut r, profile)?
|
||||
} else {
|
||||
// Profile 0's intra-only frame codes no colour configuration:
|
||||
// 4:2:0 at 8 bits, BT.601, and libvpx's studio range.
|
||||
ColorConfig {
|
||||
bit_depth: 8,
|
||||
color_space: CS_BT_601,
|
||||
full_range: false,
|
||||
subsampling_x: true,
|
||||
subsampling_y: true,
|
||||
}
|
||||
};
|
||||
let refresh = r.u8(8)?;
|
||||
let size = frame_size(&mut r)?;
|
||||
(color, refresh, size, render_size(&mut r, size)?)
|
||||
} else {
|
||||
let color = state.color.ok_or(Error::MissingReference)?;
|
||||
let refresh = r.u8(8)?;
|
||||
for (index, bias) in ref_frame_idx.iter_mut().zip(&mut ref_frame_sign_bias) {
|
||||
*index = r.u8(3)?;
|
||||
*bias = r.bit()?;
|
||||
}
|
||||
let size = frame_size_with_refs(&mut r, &ref_frame_idx, ref_sizes)?;
|
||||
let render = render_size(&mut r, size)?;
|
||||
allow_high_precision_mv = r.bit()?;
|
||||
interp_filter = read_interpolation_filter(&mut r)?;
|
||||
(color, refresh, size, render)
|
||||
};
|
||||
let (refresh_frame_context, frame_parallel_decoding_mode) = if error_resilient_mode {
|
||||
(false, true)
|
||||
} else {
|
||||
(r.bit()?, r.bit()?)
|
||||
};
|
||||
let mut frame_context_idx = r.u8(2)?;
|
||||
if key_frame || intra_only {
|
||||
frame_context_idx = 0;
|
||||
}
|
||||
next.color = Some(color);
|
||||
if key_frame || intra_only || error_resilient_mode {
|
||||
next.setup_past_independence();
|
||||
}
|
||||
let loop_filter = loop_filter_params(&mut r, &mut next)?;
|
||||
let quantization = quantization_params(&mut r)?;
|
||||
let segmentation = segmentation_params(&mut r, &mut next)?;
|
||||
let (tile_cols_log2, tile_rows_log2) = tile_info(&mut r, width)?;
|
||||
let header_size_in_bytes = r.bits(16)?;
|
||||
let uncompressed = r.bytes_read();
|
||||
let past = uncompressed.checked_add(usize::from(header_size_in_bytes));
|
||||
if header_size_in_bytes == 0 || past.is_none_or(|end| end > frame.len()) {
|
||||
return Err(Error::BadHeaderSize);
|
||||
}
|
||||
let header = FrameHeader {
|
||||
profile,
|
||||
show_existing_frame: None,
|
||||
key_frame,
|
||||
show_frame,
|
||||
error_resilient_mode,
|
||||
intra_only,
|
||||
reset_frame_context,
|
||||
color,
|
||||
refresh_frame_flags,
|
||||
ref_frame_idx,
|
||||
ref_frame_sign_bias,
|
||||
width,
|
||||
height,
|
||||
render_width,
|
||||
render_height,
|
||||
allow_high_precision_mv,
|
||||
interp_filter,
|
||||
refresh_frame_context,
|
||||
frame_parallel_decoding_mode,
|
||||
frame_context_idx,
|
||||
loop_filter,
|
||||
quantization,
|
||||
segmentation,
|
||||
tile_cols_log2,
|
||||
tile_rows_log2,
|
||||
header_size_in_bytes,
|
||||
uncompressed_header_size: u8::try_from(uncompressed)
|
||||
.map_err(|_| Error::OutOfRange("the uncompressed header's size"))?,
|
||||
};
|
||||
Ok((header, next))
|
||||
}
|
||||
|
||||
/// `frame_sync_code()` (6.2.1).
|
||||
fn sync_code(r: &mut BitReader<'_>) -> Result<(), Error> {
|
||||
for expected in SYNC_CODE {
|
||||
if r.u8(8)? != expected {
|
||||
return Err(Error::OutOfRange("frame_sync_code"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `color_config()` (6.2.2).
|
||||
fn color_config(r: &mut BitReader<'_>, profile: u8) -> Result<ColorConfig, Error> {
|
||||
let bit_depth = if profile >= 2 {
|
||||
if r.bit()? { 12 } else { 10 }
|
||||
} else {
|
||||
8
|
||||
};
|
||||
let color_space = r.u8(3)?;
|
||||
let odd_profile = profile == 1 || profile == 3;
|
||||
let (full_range, subsampling_x, subsampling_y) = if color_space != CS_RGB {
|
||||
let full_range = r.bit()?;
|
||||
if odd_profile {
|
||||
let x = r.bit()?;
|
||||
let y = r.bit()?;
|
||||
if r.bit()? {
|
||||
return Err(Error::OutOfRange("reserved_zero"));
|
||||
}
|
||||
(full_range, x, y)
|
||||
} else {
|
||||
(full_range, true, true)
|
||||
}
|
||||
} else if odd_profile {
|
||||
if r.bit()? {
|
||||
return Err(Error::OutOfRange("reserved_zero"));
|
||||
}
|
||||
(true, false, false)
|
||||
} else {
|
||||
// 4:4:4 RGB is profile 1's and 3's alone (7.2.2).
|
||||
return Err(Error::Unsupported("RGB in profile 0 or 2"));
|
||||
};
|
||||
Ok(ColorConfig {
|
||||
bit_depth,
|
||||
color_space,
|
||||
full_range,
|
||||
subsampling_x,
|
||||
subsampling_y,
|
||||
})
|
||||
}
|
||||
|
||||
/// `frame_size()` (6.2.3): each side's `f(16)` plus one.
|
||||
fn frame_size(r: &mut BitReader<'_>) -> Result<(u32, u32), Error> {
|
||||
let width = u32::from(r.bits(16)?).saturating_add(1);
|
||||
let height = u32::from(r.bits(16)?).saturating_add(1);
|
||||
Ok((width, height))
|
||||
}
|
||||
|
||||
/// `render_size()` (6.2.4).
|
||||
fn render_size(r: &mut BitReader<'_>, frame: (u32, u32)) -> Result<(u32, u32), Error> {
|
||||
if r.bit()? { frame_size(r) } else { Ok(frame) }
|
||||
}
|
||||
|
||||
/// `frame_size_with_refs()` (6.2.5) up to its `render_size()`: the first
|
||||
/// reference whose `found_ref` is set gives the size, else it is coded.
|
||||
fn frame_size_with_refs(
|
||||
r: &mut BitReader<'_>,
|
||||
ref_frame_idx: &[u8; 3],
|
||||
ref_sizes: &[Option<(u32, u32)>; 8],
|
||||
) -> Result<(u32, u32), Error> {
|
||||
for &index in ref_frame_idx {
|
||||
if r.bit()? {
|
||||
return ref_sizes
|
||||
.get(usize::from(index))
|
||||
.copied()
|
||||
.flatten()
|
||||
.ok_or(Error::MissingReference);
|
||||
}
|
||||
}
|
||||
frame_size(r)
|
||||
}
|
||||
|
||||
/// `read_interpolation_filter()` (6.2.7), in libvpx's numbering: its
|
||||
/// `literal_to_filter` maps the coded 0 to `EIGHTTAP_SMOOTH` (1) and 1 to
|
||||
/// `EIGHTTAP` (0), and keeps 2 (sharp) and 3 (bilinear).
|
||||
fn read_interpolation_filter(r: &mut BitReader<'_>) -> Result<u8, Error> {
|
||||
if r.bit()? {
|
||||
return Ok(SWITCHABLE);
|
||||
}
|
||||
let literal = r.u8(2)?;
|
||||
Ok(if literal <= 1 { literal ^ 1 } else { literal })
|
||||
}
|
||||
|
||||
/// `loop_filter_params()` (6.2.8): the deltas coded update those `state`
|
||||
/// keeps.
|
||||
fn loop_filter_params(r: &mut BitReader<'_>, state: &mut State) -> Result<LoopFilter, Error> {
|
||||
let level = r.u8(6)?;
|
||||
let sharpness = r.u8(3)?;
|
||||
let delta_enabled = r.bit()?;
|
||||
if delta_enabled && r.bit()? {
|
||||
for delta in &mut state.ref_deltas {
|
||||
if r.bit()? {
|
||||
*delta = narrow_i8(r.su(6)?);
|
||||
}
|
||||
}
|
||||
for delta in &mut state.mode_deltas {
|
||||
if r.bit()? {
|
||||
*delta = narrow_i8(r.su(6)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(LoopFilter {
|
||||
level,
|
||||
sharpness,
|
||||
delta_enabled,
|
||||
ref_deltas: state.ref_deltas,
|
||||
mode_deltas: state.mode_deltas,
|
||||
})
|
||||
}
|
||||
|
||||
/// A value `su(6)` or `su(4)` read, at most 63 in magnitude.
|
||||
fn narrow_i8(value: i16) -> i8 {
|
||||
i8::try_from(value).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// `quantization_params()` (6.2.9).
|
||||
fn quantization_params(r: &mut BitReader<'_>) -> Result<Quantization, Error> {
|
||||
let base_q_idx = r.u8(8)?;
|
||||
let mut delta = || -> Result<i8, Error> { Ok(if r.bit()? { narrow_i8(r.su(4)?) } else { 0 }) };
|
||||
Ok(Quantization {
|
||||
base_q_idx,
|
||||
delta_q_y_dc: delta()?,
|
||||
delta_q_uv_dc: delta()?,
|
||||
delta_q_uv_ac: delta()?,
|
||||
})
|
||||
}
|
||||
|
||||
/// `read_prob()` (6.2.11).
|
||||
fn read_prob(r: &mut BitReader<'_>) -> Result<u8, Error> {
|
||||
if r.bit()? { r.u8(8) } else { Ok(255) }
|
||||
}
|
||||
|
||||
/// `segmentation_params()` (6.2.11): the probabilities and features coded
|
||||
/// update those `state` keeps.
|
||||
fn segmentation_params(r: &mut BitReader<'_>, state: &mut State) -> Result<Segmentation, Error> {
|
||||
let kept = &mut state.segmentation;
|
||||
kept.enabled = r.bit()?;
|
||||
kept.update_map = false;
|
||||
kept.temporal_update = false;
|
||||
if !kept.enabled {
|
||||
return Ok(*kept);
|
||||
}
|
||||
kept.update_map = r.bit()?;
|
||||
if kept.update_map {
|
||||
for prob in &mut kept.tree_probs {
|
||||
*prob = read_prob(r)?;
|
||||
}
|
||||
kept.temporal_update = r.bit()?;
|
||||
for prob in &mut kept.pred_probs {
|
||||
*prob = if kept.temporal_update {
|
||||
read_prob(r)?
|
||||
} else {
|
||||
255
|
||||
};
|
||||
}
|
||||
}
|
||||
if r.bit()? {
|
||||
kept.abs_or_delta_update = r.bit()?;
|
||||
for (enabled, data) in kept
|
||||
.feature_enabled
|
||||
.iter_mut()
|
||||
.zip(kept.feature_data.iter_mut())
|
||||
{
|
||||
for (((enabled, data), &bits), &signed) in enabled
|
||||
.iter_mut()
|
||||
.zip(data.iter_mut())
|
||||
.zip(&FEATURE_BITS)
|
||||
.zip(&FEATURE_SIGNED)
|
||||
{
|
||||
*enabled = r.bit()?;
|
||||
let mut value = 0;
|
||||
if *enabled {
|
||||
value = i16::try_from(r.bits(bits)?)
|
||||
.map_err(|_| Error::OutOfRange("feature_value"))?;
|
||||
if signed && r.bit()? {
|
||||
value = value.wrapping_neg();
|
||||
}
|
||||
}
|
||||
*data = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(*kept)
|
||||
}
|
||||
|
||||
/// `tile_info()` (6.2.12), for a frame `width` wide.
|
||||
fn tile_info(r: &mut BitReader<'_>, width: u32) -> Result<(u8, u8), Error> {
|
||||
// MiCols and Sb64Cols (7.2.6): at most 8192 and 1024 for a width of
|
||||
// 65536.
|
||||
let mi_cols = width.saturating_add(7) >> 3;
|
||||
let sb64_cols = mi_cols.saturating_add(7) >> 3;
|
||||
let mut min_log2 = 0u8;
|
||||
while (64u32 << min_log2) < sb64_cols {
|
||||
min_log2 = min_log2.saturating_add(1);
|
||||
}
|
||||
let mut max_log2 = 1u8;
|
||||
while (sb64_cols >> max_log2) >= 4 {
|
||||
max_log2 = max_log2.saturating_add(1);
|
||||
}
|
||||
let max_log2 = max_log2.saturating_sub(1);
|
||||
let mut cols = min_log2;
|
||||
while cols < max_log2 {
|
||||
if r.bit()? {
|
||||
cols = cols.saturating_add(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let mut rows = u8::from(r.bit()?);
|
||||
if rows == 1 {
|
||||
rows = rows.saturating_add(u8::from(r.bit()?));
|
||||
}
|
||||
Ok((cols, rows))
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Each segment's quantizer scales and loop filter levels, as VA-API's
|
||||
//! `VASegmentParameterVP9` takes them already derived: the quantizer index
|
||||
//! of the segment (`get_qindex()`, 8.6.1) looked up in the specification's
|
||||
//! tables, and the filter level of each reference frame and mode (8.8.1).
|
||||
//! NVDEC takes the header's own fields and derives these itself.
|
||||
|
||||
mod tables;
|
||||
|
||||
use super::header::{FrameHeader, MAX_SEGMENTS};
|
||||
|
||||
/// The segment feature that sets the quantizer (`SEG_LVL_ALT_Q`).
|
||||
const SEG_LVL_ALT_Q: usize = 0;
|
||||
/// The segment feature that sets the loop filter level (`SEG_LVL_ALT_L`).
|
||||
const SEG_LVL_ALT_L: usize = 1;
|
||||
/// The highest quantizer index.
|
||||
const MAX_Q_INDEX: i32 = 255;
|
||||
/// The highest loop filter level.
|
||||
const MAX_LOOP_FILTER: i32 = 63;
|
||||
|
||||
/// One segment's derived values.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SegmentParams {
|
||||
/// The luma DC coefficients' quantizer scale.
|
||||
pub luma_dc: i16,
|
||||
/// The luma AC coefficients' scale.
|
||||
pub luma_ac: i16,
|
||||
/// The chroma DC coefficients' scale.
|
||||
pub chroma_dc: i16,
|
||||
/// The chroma AC coefficients' scale.
|
||||
pub chroma_ac: i16,
|
||||
/// The loop filter level of each reference frame (intra, last, golden,
|
||||
/// altref) and mode delta (0: a zero motion vector, 1: another),
|
||||
/// `lvlSeg` with the deltas (8.8.1).
|
||||
pub filter_level: [[u8; 2]; 4],
|
||||
}
|
||||
|
||||
/// The DC and AC tables of `header`'s bit depth: 8, 10 or 12 bits.
|
||||
fn tables_of(header: &FrameHeader) -> (&'static [i16; 256], &'static [i16; 256]) {
|
||||
let [dc8, dc10, dc12] = &tables::DC_QLOOKUP;
|
||||
let [ac8, ac10, ac12] = &tables::AC_QLOOKUP;
|
||||
match header.color.bit_depth {
|
||||
8 => (dc8, ac8),
|
||||
10 => (dc10, ac10),
|
||||
_ => (dc12, ac12),
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` within `0..=max`.
|
||||
fn clip(value: i32, max: i32) -> i32 {
|
||||
value.clamp(0, max)
|
||||
}
|
||||
|
||||
/// The tables' entry at a clipped index.
|
||||
fn lookup(table: &[i16; 256], index: i32) -> i16 {
|
||||
usize::try_from(clip(index, MAX_Q_INDEX))
|
||||
.ok()
|
||||
.and_then(|index| table.get(index))
|
||||
.copied()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Every segment's values for `header`: those of each segment's features
|
||||
/// where segmentation is on, else the frame's own for all eight.
|
||||
pub fn segment_params(header: &FrameHeader) -> [SegmentParams; MAX_SEGMENTS] {
|
||||
let (dc_table, ac_table) = tables_of(header);
|
||||
let q = &header.quantization;
|
||||
let segmentation = &header.segmentation;
|
||||
let filter = &header.loop_filter;
|
||||
let mut out = [SegmentParams::default(); MAX_SEGMENTS];
|
||||
for (segment, params) in out.iter_mut().enumerate() {
|
||||
let feature = |level: usize| -> Option<i32> {
|
||||
let enabled = segmentation.feature_enabled.get(segment)?.get(level)?;
|
||||
let data = segmentation.feature_data.get(segment)?.get(level)?;
|
||||
(segmentation.enabled && *enabled).then_some(i32::from(*data))
|
||||
};
|
||||
// get_qindex() (8.6.1): the feature's value, absolute or a delta.
|
||||
let base = i32::from(q.base_q_idx);
|
||||
let q_index = match feature(SEG_LVL_ALT_Q) {
|
||||
Some(value) if segmentation.abs_or_delta_update => clip(value, MAX_Q_INDEX),
|
||||
Some(value) => clip(base.saturating_add(value), MAX_Q_INDEX),
|
||||
None => base,
|
||||
};
|
||||
params.luma_dc = lookup(dc_table, q_index.saturating_add(i32::from(q.delta_q_y_dc)));
|
||||
params.luma_ac = lookup(ac_table, q_index);
|
||||
params.chroma_dc = lookup(dc_table, q_index.saturating_add(i32::from(q.delta_q_uv_dc)));
|
||||
params.chroma_ac = lookup(ac_table, q_index.saturating_add(i32::from(q.delta_q_uv_ac)));
|
||||
// 8.8.1: the segment's level, then each reference's and mode's.
|
||||
let level = i32::from(filter.level);
|
||||
let segment_level = match feature(SEG_LVL_ALT_L) {
|
||||
Some(value) if segmentation.abs_or_delta_update => clip(value, MAX_LOOP_FILTER),
|
||||
Some(value) => clip(level.saturating_add(value), MAX_LOOP_FILTER),
|
||||
None => level,
|
||||
};
|
||||
let shift = if segment_level >= 32 { 1 } else { 0 };
|
||||
let narrow = |value: i32| u8::try_from(clip(value, MAX_LOOP_FILTER)).unwrap_or(0);
|
||||
for (reference, levels) in params.filter_level.iter_mut().enumerate() {
|
||||
let ref_delta = i32::from(filter.ref_deltas.get(reference).copied().unwrap_or(0));
|
||||
for (mode, level) in levels.iter_mut().enumerate() {
|
||||
*level = if !filter.delta_enabled {
|
||||
narrow(segment_level)
|
||||
} else if reference == 0 {
|
||||
// An intra block has no mode delta.
|
||||
narrow(segment_level.saturating_add(ref_delta << shift))
|
||||
} else {
|
||||
let mode_delta = i32::from(filter.mode_deltas.get(mode).copied().unwrap_or(0));
|
||||
narrow(
|
||||
segment_level.saturating_add(ref_delta.saturating_add(mode_delta) << shift),
|
||||
)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! The quantizer's lookup tables (8.6.1): `dc_qlookup` and `ac_qlookup`, for
|
||||
//! 8-, 10- and 12-bit samples, indexed by a quantizer index of 0 to 255.
|
||||
|
||||
/// `dc_qlookup`: 8, 10 and 12 bits.
|
||||
pub(super) const DC_QLOOKUP: [[i16; 256]; 3] = [
|
||||
[
|
||||
4, 8, 8, 9, 10, 11, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 23, 24, 25, 26, 26,
|
||||
27, 28, 29, 30, 31, 32, 32, 33, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42, 43, 43, 44, 45, 46,
|
||||
47, 48, 48, 49, 50, 51, 52, 53, 53, 54, 55, 56, 57, 57, 58, 59, 60, 61, 62, 62, 63, 64, 65,
|
||||
66, 66, 67, 68, 69, 70, 70, 71, 72, 73, 74, 74, 75, 76, 77, 78, 78, 79, 80, 81, 81, 82, 83,
|
||||
84, 85, 85, 87, 88, 90, 92, 93, 95, 96, 98, 99, 101, 102, 104, 105, 107, 108, 110, 111,
|
||||
113, 114, 116, 117, 118, 120, 121, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144,
|
||||
146, 148, 150, 152, 154, 156, 158, 161, 164, 166, 169, 172, 174, 177, 180, 182, 185, 187,
|
||||
190, 192, 195, 199, 202, 205, 208, 211, 214, 217, 220, 223, 226, 230, 233, 237, 240, 243,
|
||||
247, 250, 253, 257, 261, 265, 269, 272, 276, 280, 284, 288, 292, 296, 300, 304, 309, 313,
|
||||
317, 322, 326, 330, 335, 340, 344, 349, 354, 359, 364, 369, 374, 379, 384, 389, 395, 400,
|
||||
406, 411, 417, 423, 429, 435, 441, 447, 454, 461, 467, 475, 482, 489, 497, 505, 513, 522,
|
||||
530, 539, 549, 559, 569, 579, 590, 602, 614, 626, 640, 654, 668, 684, 700, 717, 736, 755,
|
||||
775, 796, 819, 843, 869, 896, 925, 955, 988, 1022, 1058, 1098, 1139, 1184, 1232, 1282,
|
||||
1336,
|
||||
],
|
||||
[
|
||||
4, 9, 10, 13, 15, 17, 20, 22, 25, 28, 31, 34, 37, 40, 43, 47, 50, 53, 57, 60, 64, 68, 71,
|
||||
75, 78, 82, 86, 90, 93, 97, 101, 105, 109, 113, 116, 120, 124, 128, 132, 136, 140, 143,
|
||||
147, 151, 155, 159, 163, 166, 170, 174, 178, 182, 185, 189, 193, 197, 200, 204, 208, 212,
|
||||
215, 219, 223, 226, 230, 233, 237, 241, 244, 248, 251, 255, 259, 262, 266, 269, 273, 276,
|
||||
280, 283, 287, 290, 293, 297, 300, 304, 307, 310, 314, 317, 321, 324, 327, 331, 334, 337,
|
||||
343, 350, 356, 362, 369, 375, 381, 387, 394, 400, 406, 412, 418, 424, 430, 436, 442, 448,
|
||||
454, 460, 466, 472, 478, 484, 490, 499, 507, 516, 525, 533, 542, 550, 559, 567, 576, 584,
|
||||
592, 601, 609, 617, 625, 634, 644, 655, 666, 676, 687, 698, 708, 718, 729, 739, 749, 759,
|
||||
770, 782, 795, 807, 819, 831, 844, 856, 868, 880, 891, 906, 920, 933, 947, 961, 975, 988,
|
||||
1001, 1015, 1030, 1045, 1061, 1076, 1090, 1105, 1120, 1137, 1153, 1170, 1186, 1202, 1218,
|
||||
1236, 1253, 1271, 1288, 1306, 1323, 1342, 1361, 1379, 1398, 1416, 1436, 1456, 1476, 1496,
|
||||
1516, 1537, 1559, 1580, 1601, 1624, 1647, 1670, 1692, 1717, 1741, 1766, 1791, 1817, 1844,
|
||||
1871, 1900, 1929, 1958, 1990, 2021, 2054, 2088, 2123, 2159, 2197, 2236, 2276, 2319, 2363,
|
||||
2410, 2458, 2508, 2561, 2616, 2675, 2737, 2802, 2871, 2944, 3020, 3102, 3188, 3280, 3375,
|
||||
3478, 3586, 3702, 3823, 3953, 4089, 4236, 4394, 4559, 4737, 4929, 5130, 5347,
|
||||
],
|
||||
[
|
||||
4, 12, 18, 25, 33, 41, 50, 60, 70, 80, 91, 103, 115, 127, 140, 153, 166, 180, 194, 208,
|
||||
222, 237, 251, 266, 281, 296, 312, 327, 343, 358, 374, 390, 405, 421, 437, 453, 469, 484,
|
||||
500, 516, 532, 548, 564, 580, 596, 611, 627, 643, 659, 674, 690, 706, 721, 737, 752, 768,
|
||||
783, 798, 814, 829, 844, 859, 874, 889, 904, 919, 934, 949, 964, 978, 993, 1008, 1022,
|
||||
1037, 1051, 1065, 1080, 1094, 1108, 1122, 1136, 1151, 1165, 1179, 1192, 1206, 1220, 1234,
|
||||
1248, 1261, 1275, 1288, 1302, 1315, 1329, 1342, 1368, 1393, 1419, 1444, 1469, 1494, 1519,
|
||||
1544, 1569, 1594, 1618, 1643, 1668, 1692, 1717, 1741, 1765, 1789, 1814, 1838, 1862, 1885,
|
||||
1909, 1933, 1957, 1992, 2027, 2061, 2096, 2130, 2165, 2199, 2233, 2267, 2300, 2334, 2367,
|
||||
2400, 2434, 2467, 2499, 2532, 2575, 2618, 2661, 2704, 2746, 2788, 2830, 2872, 2913, 2954,
|
||||
2995, 3036, 3076, 3127, 3177, 3226, 3275, 3324, 3373, 3421, 3469, 3517, 3565, 3621, 3677,
|
||||
3733, 3788, 3843, 3897, 3951, 4005, 4058, 4119, 4181, 4241, 4301, 4361, 4420, 4479, 4546,
|
||||
4612, 4677, 4742, 4807, 4871, 4942, 5013, 5083, 5153, 5222, 5291, 5367, 5442, 5517, 5591,
|
||||
5665, 5745, 5825, 5905, 5984, 6063, 6149, 6234, 6319, 6404, 6495, 6587, 6678, 6769, 6867,
|
||||
6966, 7064, 7163, 7269, 7376, 7483, 7599, 7715, 7832, 7958, 8085, 8214, 8352, 8492, 8635,
|
||||
8788, 8945, 9104, 9275, 9450, 9639, 9832, 10031, 10245, 10465, 10702, 10946, 11210, 11482,
|
||||
11776, 12081, 12409, 12750, 13118, 13501, 13913, 14343, 14807, 15290, 15812, 16356, 16943,
|
||||
17575, 18237, 18949, 19718, 20521, 21387,
|
||||
],
|
||||
];
|
||||
|
||||
/// `ac_qlookup`: 8, 10 and 12 bits.
|
||||
pub(super) const AC_QLOOKUP: [[i16; 256]; 3] = [
|
||||
[
|
||||
4, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
|
||||
30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
|
||||
53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
|
||||
76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
|
||||
99, 100, 101, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130,
|
||||
132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 155, 158, 161, 164, 167, 170, 173,
|
||||
176, 179, 182, 185, 188, 191, 194, 197, 200, 203, 207, 211, 215, 219, 223, 227, 231, 235,
|
||||
239, 243, 247, 251, 255, 260, 265, 270, 275, 280, 285, 290, 295, 300, 305, 311, 317, 323,
|
||||
329, 335, 341, 347, 353, 359, 366, 373, 380, 387, 394, 401, 408, 416, 424, 432, 440, 448,
|
||||
456, 465, 474, 483, 492, 501, 510, 520, 530, 540, 550, 560, 571, 582, 593, 604, 615, 627,
|
||||
639, 651, 663, 676, 689, 702, 715, 729, 743, 757, 771, 786, 801, 816, 832, 848, 864, 881,
|
||||
898, 915, 933, 951, 969, 988, 1007, 1026, 1046, 1066, 1087, 1108, 1129, 1151, 1173, 1196,
|
||||
1219, 1243, 1267, 1292, 1317, 1343, 1369, 1396, 1423, 1451, 1479, 1508, 1537, 1567, 1597,
|
||||
1628, 1660, 1692, 1725, 1759, 1793, 1828,
|
||||
],
|
||||
[
|
||||
4, 9, 11, 13, 16, 18, 21, 24, 27, 30, 33, 37, 40, 44, 48, 51, 55, 59, 63, 67, 71, 75, 79,
|
||||
83, 88, 92, 96, 100, 105, 109, 114, 118, 122, 127, 131, 136, 140, 145, 149, 154, 158, 163,
|
||||
168, 172, 177, 181, 186, 190, 195, 199, 204, 208, 213, 217, 222, 226, 231, 235, 240, 244,
|
||||
249, 253, 258, 262, 267, 271, 275, 280, 284, 289, 293, 297, 302, 306, 311, 315, 319, 324,
|
||||
328, 332, 337, 341, 345, 349, 354, 358, 362, 367, 371, 375, 379, 384, 388, 392, 396, 401,
|
||||
409, 417, 425, 433, 441, 449, 458, 466, 474, 482, 490, 498, 506, 514, 523, 531, 539, 547,
|
||||
555, 563, 571, 579, 588, 596, 604, 616, 628, 640, 652, 664, 676, 688, 700, 713, 725, 737,
|
||||
749, 761, 773, 785, 797, 809, 825, 841, 857, 873, 889, 905, 922, 938, 954, 970, 986, 1002,
|
||||
1018, 1038, 1058, 1078, 1098, 1118, 1138, 1158, 1178, 1198, 1218, 1242, 1266, 1290, 1314,
|
||||
1338, 1362, 1386, 1411, 1435, 1463, 1491, 1519, 1547, 1575, 1603, 1631, 1663, 1695, 1727,
|
||||
1759, 1791, 1823, 1859, 1895, 1931, 1967, 2003, 2039, 2079, 2119, 2159, 2199, 2239, 2283,
|
||||
2327, 2371, 2415, 2459, 2507, 2555, 2603, 2651, 2703, 2755, 2807, 2859, 2915, 2971, 3027,
|
||||
3083, 3143, 3203, 3263, 3327, 3391, 3455, 3523, 3591, 3659, 3731, 3803, 3876, 3952, 4028,
|
||||
4104, 4184, 4264, 4348, 4432, 4516, 4604, 4692, 4784, 4876, 4972, 5068, 5168, 5268, 5372,
|
||||
5476, 5584, 5692, 5804, 5916, 6032, 6148, 6268, 6388, 6512, 6640, 6768, 6900, 7036, 7172,
|
||||
7312,
|
||||
],
|
||||
[
|
||||
4, 13, 19, 27, 35, 44, 54, 64, 75, 87, 99, 112, 126, 139, 154, 168, 183, 199, 214, 230,
|
||||
247, 263, 280, 297, 314, 331, 349, 366, 384, 402, 420, 438, 456, 475, 493, 511, 530, 548,
|
||||
567, 586, 604, 623, 642, 660, 679, 698, 716, 735, 753, 772, 791, 809, 828, 846, 865, 884,
|
||||
902, 920, 939, 957, 976, 994, 1012, 1030, 1049, 1067, 1085, 1103, 1121, 1139, 1157, 1175,
|
||||
1193, 1211, 1229, 1246, 1264, 1282, 1299, 1317, 1335, 1352, 1370, 1387, 1405, 1422, 1440,
|
||||
1457, 1474, 1491, 1509, 1526, 1543, 1560, 1577, 1595, 1627, 1660, 1693, 1725, 1758, 1791,
|
||||
1824, 1856, 1889, 1922, 1954, 1987, 2020, 2052, 2085, 2118, 2150, 2183, 2216, 2248, 2281,
|
||||
2313, 2346, 2378, 2411, 2459, 2508, 2556, 2605, 2653, 2701, 2750, 2798, 2847, 2895, 2943,
|
||||
2992, 3040, 3088, 3137, 3185, 3234, 3298, 3362, 3426, 3491, 3555, 3619, 3684, 3748, 3812,
|
||||
3876, 3941, 4005, 4069, 4149, 4230, 4310, 4390, 4470, 4550, 4631, 4711, 4791, 4871, 4967,
|
||||
5064, 5160, 5256, 5352, 5448, 5544, 5641, 5737, 5849, 5961, 6073, 6185, 6297, 6410, 6522,
|
||||
6650, 6778, 6906, 7034, 7162, 7290, 7435, 7579, 7723, 7867, 8011, 8155, 8315, 8475, 8635,
|
||||
8795, 8956, 9132, 9308, 9484, 9660, 9836, 10028, 10220, 10412, 10604, 10812, 11020, 11228,
|
||||
11437, 11661, 11885, 12109, 12333, 12573, 12813, 13053, 13309, 13565, 13821, 14093, 14365,
|
||||
14637, 14925, 15213, 15502, 15806, 16110, 16414, 16734, 17054, 17390, 17726, 18062, 18414,
|
||||
18766, 19134, 19502, 19886, 20270, 20670, 21070, 21486, 21902, 22334, 22766, 23214, 23662,
|
||||
24126, 24590, 25070, 25551, 26047, 26559, 27071, 27599, 28143, 28687, 29247,
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Superframes (Annex B): one sample holding several frames, each but the
|
||||
//! last usually not shown, with an index of their sizes at its end. A
|
||||
//! container's sample, and VideoToolbox's sample buffer, hold the
|
||||
//! superframe whole; the host splits it here, from bytes the guest wrote,
|
||||
//! so every size is checked against the sample before a frame is cut.
|
||||
|
||||
use super::Error;
|
||||
|
||||
/// The most frames a superframe holds: `frames_in_superframe_minus_1` is
|
||||
/// 3 bits.
|
||||
pub const MAX_FRAMES: usize = 8;
|
||||
|
||||
/// The frames of `sample`: those its superframe index names, in order,
|
||||
/// or the sample whole where it ends in no index.
|
||||
///
|
||||
/// An index is its marker byte (`0b110` in its top bits, then
|
||||
/// `bytes_per_framesize_minus_1` and `frames_in_superframe_minus_1`), each
|
||||
/// frame's size in that many bytes, little-endian, then the marker byte
|
||||
/// again (B.2). A last byte that looks like a marker without its twin where
|
||||
/// the index would begin is no index, as libvpx reads it, and the sample is
|
||||
/// one frame. An index whose sizes run past the bytes before it, or that
|
||||
/// names a frame of no bytes, is [`Error::BadSuperframe`]; bytes after the
|
||||
/// last frame and before the index are left out. An empty sample is
|
||||
/// [`Error::EmptySample`].
|
||||
pub fn frames(sample: &[u8]) -> Result<Vec<&[u8]>, Error> {
|
||||
let Some(&marker) = sample.last() else {
|
||||
return Err(Error::EmptySample);
|
||||
};
|
||||
if marker & 0xe0 != 0xc0 {
|
||||
return Ok(vec![sample]);
|
||||
}
|
||||
let count = usize::from(marker & 7).saturating_add(1);
|
||||
let size_bytes = usize::from((marker >> 3) & 3).saturating_add(1);
|
||||
// At most 2 + 4 * 8 bytes: no overflow.
|
||||
let index_bytes = size_bytes.saturating_mul(count).saturating_add(2);
|
||||
let Some(frames_end) = sample.len().checked_sub(index_bytes) else {
|
||||
return Ok(vec![sample]);
|
||||
};
|
||||
if sample.get(frames_end) != Some(&marker) {
|
||||
return Ok(vec![sample]);
|
||||
}
|
||||
let sizes = sample
|
||||
.get(frames_end.saturating_add(1)..sample.len().saturating_sub(1))
|
||||
.ok_or(Error::BadSuperframe)?;
|
||||
let mut frames = Vec::with_capacity(count);
|
||||
let mut start = 0usize;
|
||||
for size in sizes.chunks_exact(size_bytes) {
|
||||
let size = size
|
||||
.iter()
|
||||
.rev()
|
||||
.fold(0usize, |value, &byte| (value << 8) | usize::from(byte));
|
||||
if size == 0 {
|
||||
return Err(Error::BadSuperframe);
|
||||
}
|
||||
let end = start.checked_add(size).ok_or(Error::BadSuperframe)?;
|
||||
if end > frames_end {
|
||||
return Err(Error::BadSuperframe);
|
||||
}
|
||||
frames.push(sample.get(start..end).ok_or(Error::BadSuperframe)?);
|
||||
start = end;
|
||||
}
|
||||
if frames.len() != count || count > MAX_FRAMES {
|
||||
return Err(Error::BadSuperframe);
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,318 @@
|
||||
//! VP9's superframes, headers and decoding process under seeded fuzzing, up
|
||||
//! to an accelerator that checks what the hardware is handed. Two kinds of
|
||||
//! input: streams of the tests' own frames with random fields, some
|
||||
//! straying from what the specification allows, in superframes and alone,
|
||||
//! mutated by sample; and libvpx's streams, with samples mutated among
|
||||
//! whole ones, so that the mutations meet the state real frames leave.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use super::*;
|
||||
use crate::codec::fuzz_support::{Rng, Target, long, maybe_mutate, quick};
|
||||
|
||||
const STREAMS: Target = Target::new("vp9-streams");
|
||||
const SAMPLES: Target = Target::new("vp9-samples");
|
||||
|
||||
/// Frames that reached the accelerator, which says how deep the inputs get.
|
||||
static FRAMES: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[test]
|
||||
fn streams() {
|
||||
let report = quick(&STREAMS, 3000, stream_case);
|
||||
eprintln!(
|
||||
"vp9: {} frames reached the accelerator in {} streams",
|
||||
FRAMES.load(Ordering::Relaxed),
|
||||
report.inputs
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "long: RVGV_FUZZ_CASES, RVGV_FUZZ_SECONDS, RVGV_FUZZ_SEED"]
|
||||
fn streams_long() {
|
||||
long(&STREAMS, stream_case);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn samples() {
|
||||
quick(&SAMPLES, 600, sample_case);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "long: RVGV_FUZZ_CASES, RVGV_FUZZ_SECONDS, RVGV_FUZZ_SEED"]
|
||||
fn samples_long() {
|
||||
long(&SAMPLES, sample_case);
|
||||
}
|
||||
|
||||
/// An accelerator that checks what the decoder gives it against what the
|
||||
/// hardware takes: a configuration of a format the decoder supports, each
|
||||
/// frame of that format, its headers within its bytes, references of its
|
||||
/// format at scales the hardware scales, and derived values in range. It
|
||||
/// fails one call in 64, as a driver may.
|
||||
#[derive(Default)]
|
||||
struct Checking {
|
||||
next: u32,
|
||||
configured: Option<Format>,
|
||||
failing: u64,
|
||||
}
|
||||
|
||||
impl Checking {
|
||||
fn fails(&mut self) -> bool {
|
||||
self.failing = self
|
||||
.failing
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1);
|
||||
self.failing >> 58 == 0
|
||||
}
|
||||
}
|
||||
|
||||
impl Accelerator for Checking {
|
||||
/// The picture's number and the format it was made for.
|
||||
type Picture = (u32, Format);
|
||||
type Error = Error;
|
||||
|
||||
fn configure(&mut self, format: &Format) -> Result<(), Error> {
|
||||
assert!(matches!(
|
||||
(format.profile, format.bit_depth),
|
||||
(0, 8) | (2, 10)
|
||||
));
|
||||
assert!((1..=MAX_SIDE).contains(&format.width));
|
||||
assert!((1..=MAX_SIDE).contains(&format.height));
|
||||
self.configured = None;
|
||||
if self.fails() {
|
||||
return Err(Error::Unsupported("the stand-in's configuration failure"));
|
||||
}
|
||||
self.configured = Some(*format);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new_picture(&mut self) -> Result<(u32, Format), Error> {
|
||||
let format = self.configured.expect("a picture before a configuration");
|
||||
if self.fails() {
|
||||
return Err(Error::Unsupported("the stand-in's picture failure"));
|
||||
}
|
||||
self.next += 1;
|
||||
Ok((self.next, format))
|
||||
}
|
||||
|
||||
fn decode_frame(
|
||||
&mut self,
|
||||
picture: &(u32, Format),
|
||||
params: &FrameParams<'_, (u32, Format)>,
|
||||
) -> Result<(), Error> {
|
||||
let format = self.configured.expect("a frame before a configuration");
|
||||
assert_eq!(picture.1, format, "a picture of another format");
|
||||
let header = params.header;
|
||||
assert!(header.show_existing_frame.is_none());
|
||||
assert_eq!((header.width, header.height), (format.width, format.height));
|
||||
assert!(header.header_size_in_bytes > 0);
|
||||
assert!(
|
||||
usize::from(header.uncompressed_header_size) + usize::from(header.header_size_in_bytes)
|
||||
<= params.frame.len(),
|
||||
"a compressed header past the frame"
|
||||
);
|
||||
assert!(header.tile_rows_log2 <= 2 && header.tile_cols_log2 <= 6);
|
||||
assert!(header.loop_filter.level <= 63 && header.loop_filter.sharpness <= 7);
|
||||
for segment in params.segments {
|
||||
assert!(segment.filter_level.iter().flatten().all(|&l| l <= 63));
|
||||
for scale in [
|
||||
segment.luma_dc,
|
||||
segment.luma_ac,
|
||||
segment.chroma_dc,
|
||||
segment.chroma_ac,
|
||||
] {
|
||||
assert!(scale > 0, "a quantizer scale of {scale}");
|
||||
}
|
||||
}
|
||||
if !header.is_intra() {
|
||||
for &index in &header.ref_frame_idx {
|
||||
let reference = params.references[usize::from(index)]
|
||||
.as_ref()
|
||||
.expect("an inter frame's reference is in its slot");
|
||||
assert_eq!(reference.picture.1.bit_depth, format.bit_depth);
|
||||
for (frame, of) in [
|
||||
(format.width, reference.width),
|
||||
(format.height, reference.height),
|
||||
] {
|
||||
assert!(2 * u64::from(frame) >= u64::from(of));
|
||||
assert!(u64::from(frame) <= 16 * u64::from(of));
|
||||
}
|
||||
}
|
||||
}
|
||||
FRAMES.fetch_add(1, Ordering::Relaxed);
|
||||
if self.fails() {
|
||||
return Err(Error::Unsupported("the stand-in's decode failure"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A side near `base`: most often `base`, else half or twice it, else
|
||||
/// anything VP9 codes.
|
||||
fn side(rng: &mut Rng, base: u32) -> u32 {
|
||||
match rng.below(8) {
|
||||
0 => (base / 2).max(1),
|
||||
1 => (base * 2).min(65536),
|
||||
2 => rng.range_u32(1, 65536),
|
||||
3 => *rng.pick(&[1, 8, 64, MAX_SIDE, MAX_SIDE + 1, 65536]),
|
||||
_ => base,
|
||||
}
|
||||
}
|
||||
|
||||
fn some_delta(rng: &mut Rng, magnitude: u32) -> Option<i32> {
|
||||
rng.bool()
|
||||
.then(|| rng.range(0, u64::from(2 * magnitude + 1)) as i32 - magnitude as i32)
|
||||
}
|
||||
|
||||
/// A frame's header with every field drawn: most often an inter frame of
|
||||
/// the stream's size, now and then a key frame, an intra-only frame or a
|
||||
/// frame that shows a slot, and in `stray` frames fields past their
|
||||
/// ranges.
|
||||
fn frame_spec(rng: &mut Rng, profile: u32, size: (u32, u32), show: bool) -> FrameSpec {
|
||||
let stray = rng.one_in(8);
|
||||
let mut spec = if rng.one_in(6) {
|
||||
FrameSpec::key(size.0, size.1)
|
||||
} else {
|
||||
FrameSpec::inter(size.0, size.1)
|
||||
};
|
||||
spec.profile = if stray { rng.below(4) as u32 } else { profile };
|
||||
spec.show = show;
|
||||
if rng.one_in(12) {
|
||||
spec.show_existing = Some(rng.below(8) as u32);
|
||||
return spec;
|
||||
}
|
||||
spec.error_resilient = rng.one_in(8);
|
||||
spec.intra_only = !spec.key && !show && rng.one_in(3);
|
||||
spec.reset_frame_context = rng.below(4) as u32;
|
||||
spec.twelve_bit = stray && rng.bool();
|
||||
spec.color_space = if stray { rng.below(8) as u32 } else { 2 };
|
||||
spec.full_range = rng.bool();
|
||||
spec.subsampling = (!stray || rng.bool(), !stray || rng.bool());
|
||||
if !spec.key {
|
||||
spec.refresh = rng.below(256) as u32;
|
||||
spec.refs = [0, 1, 2].map(|_| rng.below(8) as u32);
|
||||
spec.sign_bias = [rng.bool(), rng.bool(), rng.bool()];
|
||||
spec.size_from_ref = (!rng.one_in(4)).then(|| rng.below(3));
|
||||
}
|
||||
if spec.key || spec.intra_only || spec.size_from_ref.is_none() || stray {
|
||||
spec.size = (side(rng, size.0), side(rng, size.1));
|
||||
}
|
||||
spec.render = rng
|
||||
.one_in(8)
|
||||
.then(|| (rng.range_u32(1, 65536), rng.range_u32(1, 65536)));
|
||||
spec.high_precision_mv = rng.bool();
|
||||
spec.filter = (!rng.one_in(3)).then(|| rng.below(4) as u32);
|
||||
spec.refresh_context = rng.bool();
|
||||
spec.parallel = rng.bool();
|
||||
spec.context_idx = rng.below(4) as u32;
|
||||
spec.filter_level = rng.below(64) as u32;
|
||||
spec.sharpness = rng.below(8) as u32;
|
||||
spec.deltas = (!rng.one_in(4)).then(|| {
|
||||
(
|
||||
[0; 4].map(|_| some_delta(rng, 63)),
|
||||
[0; 2].map(|_| some_delta(rng, 63)),
|
||||
)
|
||||
});
|
||||
spec.base_q = rng.below(256) as u32;
|
||||
spec.delta_q = [0; 3].map(|_| some_delta(rng, 15).unwrap_or(0));
|
||||
if rng.one_in(3) {
|
||||
let prob = |rng: &mut Rng| rng.bool().then(|| rng.below(256) as u32);
|
||||
spec.segmentation = Some(SegmentationSpec {
|
||||
update_map: rng.bool().then(|| {
|
||||
(
|
||||
[0; 7].map(|_| prob(rng)),
|
||||
rng.bool().then(|| [0; 3].map(|_| prob(rng))),
|
||||
)
|
||||
}),
|
||||
update_data: rng.bool().then(|| {
|
||||
let features = [0; 8].map(|_| {
|
||||
[255, 63, 3, 0].map(|max| {
|
||||
some_delta(rng, max)
|
||||
.map(i32::abs)
|
||||
.map(|v| if max > 3 && rng.bool() { -v } else { v })
|
||||
})
|
||||
});
|
||||
(rng.bool(), features)
|
||||
}),
|
||||
});
|
||||
}
|
||||
spec.tile_cols_increments = rng.below(if stray { 8 } else { 3 }) as u32;
|
||||
spec.tile_rows = rng.below(3) as u32;
|
||||
spec.compressed = if stray {
|
||||
*rng.pick(&[0, 1, 65535])
|
||||
} else {
|
||||
rng.range_u32(1, 64)
|
||||
};
|
||||
spec.tile_bytes = rng.below(64);
|
||||
spec
|
||||
}
|
||||
|
||||
/// A stream of the tests' own frames: a key frame most often first, then
|
||||
/// samples of one frame, or of hidden frames and a shown one in a
|
||||
/// superframe, each mutated now and then.
|
||||
fn stream_case(rng: &mut Rng) {
|
||||
let profile = *rng.pick(&[0, 0, 2]);
|
||||
let size = (side(rng, 64), side(rng, 48));
|
||||
let size = (size.0.min(4096), size.1.min(4096));
|
||||
let mut decoder = Decoder::new(Checking::default());
|
||||
let donor = ivf_frames(PROFILE_0_IVF)[1].to_vec();
|
||||
let samples = 1 + rng.count(12);
|
||||
for id in 0..samples as u64 {
|
||||
let hidden = if rng.one_in(4) { 1 + rng.below(3) } else { 0 };
|
||||
let mut frames: Vec<Vec<u8>> = (0..hidden)
|
||||
.map(|_| frame_spec(rng, profile, size, false).write())
|
||||
.collect();
|
||||
let mut last = frame_spec(rng, profile, size, true);
|
||||
if id == 0 && !rng.one_in(8) {
|
||||
last = FrameSpec {
|
||||
key: true,
|
||||
refresh: 0xff,
|
||||
show_existing: None,
|
||||
intra_only: false,
|
||||
..last
|
||||
};
|
||||
}
|
||||
frames.push(last.write());
|
||||
let mut sample = if frames.len() > 1 {
|
||||
superframe(&frames, 1 + rng.below(4))
|
||||
} else {
|
||||
frames.concat()
|
||||
};
|
||||
maybe_mutate(rng, &mut sample, &donor, 3);
|
||||
match decoder.decode(&sample, id) {
|
||||
Ok(out) => assert!(out.len() <= superframe::MAX_FRAMES),
|
||||
Err(error) => {
|
||||
let _ = error.to_string();
|
||||
}
|
||||
}
|
||||
if rng.one_in(16) {
|
||||
decoder.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// libvpx's streams, a few samples mutated, dropped or repeated.
|
||||
fn sample_case(rng: &mut Rng) {
|
||||
let file = if rng.bool() {
|
||||
PROFILE_0_IVF
|
||||
} else {
|
||||
PROFILE_2_IVF
|
||||
};
|
||||
let samples = ivf_frames(file);
|
||||
let mut decoder = Decoder::new(Checking::default());
|
||||
for (id, whole) in (0u64..).zip(&samples) {
|
||||
let mut sample = whole.to_vec();
|
||||
if rng.one_in(4) {
|
||||
let donor = rng.pick(&samples);
|
||||
maybe_mutate(rng, &mut sample, donor, 8);
|
||||
}
|
||||
if rng.one_in(16) {
|
||||
continue;
|
||||
}
|
||||
let repeats = if rng.one_in(16) { 2 } else { 1 };
|
||||
for _ in 0..repeats {
|
||||
if let Ok(out) = decoder.decode(&sample, id) {
|
||||
assert!(out.len() <= superframe::MAX_FRAMES);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,30 @@
|
||||
2393fc801a884f7ac08b35e616fa7452
|
||||
caa0bbb69b3865e461a4321330eeccd1
|
||||
5e76f9761bb5d74c8d8d48380c10c270
|
||||
750f2b4d5835f068e1cd5683c8f35d15
|
||||
9e8b46bf185ecadd28f3a642ffd395d9
|
||||
778e96bf286a8697849cc2cb76e226b8
|
||||
368980a24892c55269b4456f2332e800
|
||||
65016446e1211cc69453fa55b22d3be7
|
||||
dffd692975fd95963f4d1ee3f711bc44
|
||||
fc6bd94a9bfc2802db8485ffd20f621c
|
||||
f86ec0887725abde3307c6ba2c56e206
|
||||
5f767710222b44a3e1e51684cafd105c
|
||||
dc48176b7a5136cecb9f35defd02b7fd
|
||||
475870ab3ee3b6aa569491263963b1db
|
||||
cbeb1e3515a238a0f421bd36c5ae72d1
|
||||
7cc06ae5a35725279083d4c3b4a3467b
|
||||
19b3c4d6e123c390575b975b2b2456b9
|
||||
97ed4d627c25a395d16f62363286bec0
|
||||
9273afd58fb8c78e3214d0b767a1107d
|
||||
d7dc44784b2c8087ec2ee5d057e597c0
|
||||
bcb5d5d6627d7543b405569e0b9f4f0a
|
||||
ebae837e33e73caf6ebf6f6c8e00e7f3
|
||||
624c790771059becbf11994c76d25bf0
|
||||
a1d5e1658f5ca2769bdbd7a972242231
|
||||
b3f702d893338503bc36e63672f51fb8
|
||||
44b89ad464f29b073f4f2015184fdbe7
|
||||
1ef42f397c281573b658de0c485e2bfd
|
||||
f5165a3b9cca966bfa727be2a6deb3e3
|
||||
d46de99c6c063f5ab84c4b8596fdb9e3
|
||||
d6893affcccac98971b2062984abd52d
|
||||
Binary file not shown.
@@ -0,0 +1,30 @@
|
||||
2b2f3119483cb3ba550217a2977c0234
|
||||
a9788dcd83b3349b85a67e8f06351b58
|
||||
0330dd00b67a23fa1ba437f67e17d54d
|
||||
c6134518e3975af889acfca149d68ffb
|
||||
bb4d38d6d7640c5c2b29ba28eb3f1a8c
|
||||
de75345af09b631aa223473e0d5be033
|
||||
c1abf454017688d81e9be33600d3de6b
|
||||
d106587021a4e71bb67c393ec300ec3b
|
||||
8f04261c129d20dc2043bc74fbf94fac
|
||||
cc8177cbdc5da975465d57d1bc7433aa
|
||||
232af9735990df6d326bde193cc2ac17
|
||||
9f939da4209ad8bdfdd4aaaee5da2dcd
|
||||
2d3c071bf305e493a38bbfbea90e024b
|
||||
c97a2f3eae5f2c6c6e7311b3669b96f9
|
||||
8406950d046537c219cbead32505f9c6
|
||||
fbd310574d9b2e9adc9d2e3cbea922e1
|
||||
14d13997c30f9256162b429a4d5745a9
|
||||
754a0f6078f2c20cd7b7e132ccae79d3
|
||||
bda7962e1fcef48e3317df2879e23b84
|
||||
e961c064ac25ea91793bf04357626bdf
|
||||
366cbf22b1e1dbfda3c8b625a88cedf0
|
||||
c3d676f176e3f445d1e83c6d55d0bde5
|
||||
1ac6aca72eac4af19c707affb68f3ab5
|
||||
7516177c1774bd8d4c8e046ea22011a0
|
||||
bb4052946c0123fb255af3801a3af087
|
||||
7bc0194236490d32e6b3f2da8cc406ad
|
||||
0092762967bf7c204c8754af5814f868
|
||||
131acfc5003e8b23a0f298cfb245d7b9
|
||||
faa3bc9fe3a9310bc25fa7586f2f6c47
|
||||
a9bd3ead02d0993a97ac0b6e5de23533
|
||||
@@ -34,6 +34,10 @@
|
||||
//! low-overhead format, after its record's `configOBUs` as its
|
||||
//! parameter sets (`nvdec::av1`); a picture NVDEC fails is followed by
|
||||
//! the next decodes, as an H.264 stream's is.
|
||||
//! - **A VP9 stream** is handed over as its container's samples, a frame
|
||||
//! or a superframe each, whole, with no parameter sets; each frame is sent
|
||||
//! where it lies in the sample (`nvdec::vp9`), and a frame NVDEC fails is
|
||||
//! followed by the next decodes, as an H.264 stream's is.
|
||||
//! - **A picture holds its decode surface** until it drops: the decoder has
|
||||
//! [`AnnexBDecoder::SPARE_PICTURES`] surfaces beyond its references and
|
||||
//! the picture being decoded, and a decode with none free is
|
||||
@@ -46,6 +50,7 @@ use crate::codec::PictureStart;
|
||||
use crate::codec::av1::{Decoder as Av1Decoder, Limits as Av1Limits};
|
||||
use crate::codec::h264::{Decoder as H264Decoder, nal::NalFormat};
|
||||
use crate::codec::hevc::Decoder as HevcDecoder;
|
||||
use crate::codec::vp9::Decoder as Vp9Decoder;
|
||||
use crate::core::device_memory::DeviceMemory;
|
||||
use crate::core::runtime::Runtime;
|
||||
use crate::core::surfaces::crop_within;
|
||||
@@ -60,6 +65,7 @@ use crate::nvidia::nvdec::decoder::{
|
||||
};
|
||||
use crate::nvidia::nvdec::h264::NvdecH264;
|
||||
use crate::nvidia::nvdec::hevc::NvdecHevc;
|
||||
use crate::nvidia::nvdec::vp9::NvdecVp9;
|
||||
use crate::nvidia::wait::Deadline;
|
||||
|
||||
/// A codec an [`AnnexBDecoder`] decodes.
|
||||
@@ -75,6 +81,9 @@ pub enum AnnexBCodec {
|
||||
/// limits (NVDEC's largest and smallest, as its capability query lists
|
||||
/// them).
|
||||
Av1(Av1Limits),
|
||||
/// VP9, profile 0 and profile 2 at 10 bits, 4:2:0: not Annex B, but
|
||||
/// samples of a frame or a superframe each (module doc).
|
||||
Vp9,
|
||||
}
|
||||
|
||||
/// One stream's decoder of whole Annex B access units on NVDEC (module
|
||||
@@ -95,6 +104,7 @@ enum Codec {
|
||||
Hevc(HevcDecoder<NvdecHevc>),
|
||||
/// Boxed: its eight slots' state is far larger than the other decoders.
|
||||
Av1(Box<Av1Decoder<NvdecAv1>>),
|
||||
Vp9(Vp9Decoder<NvdecVp9>),
|
||||
}
|
||||
|
||||
/// How an [`AnnexBDecoder`]'s pictures reached NVDEC: as a run of their
|
||||
@@ -133,6 +143,7 @@ impl AnnexBDecoder {
|
||||
NvdecAv1::new(Arc::clone(gpu)),
|
||||
limits,
|
||||
))),
|
||||
AnnexBCodec::Vp9 => Codec::Vp9(Vp9Decoder::new(NvdecVp9::new(Arc::clone(gpu)))),
|
||||
};
|
||||
Self {
|
||||
codec,
|
||||
@@ -178,8 +189,15 @@ impl AnnexBDecoder {
|
||||
|
||||
/// Takes parameter sets (H.264's SPS and PPS, HEVC's VPS, SPS and PPS),
|
||||
/// units in Annex B form; AV1's sequence header OBUs, a record's
|
||||
/// `configOBUs`; units that make a picture are an error.
|
||||
/// `configOBUs`; units that make a picture are an error, as is any byte
|
||||
/// for VP9, which has none.
|
||||
pub fn parameter_sets(&mut self, sets: &[u8]) -> Result<(), Error> {
|
||||
if matches!(self.codec, Codec::Vp9(_)) {
|
||||
return match sets {
|
||||
[] => Ok(()),
|
||||
_ => Err(Error::Bitstream("parameter sets for VP9".to_owned())),
|
||||
};
|
||||
}
|
||||
match self.decode_sample(sets, false)? {
|
||||
None => Ok(()),
|
||||
Some(_) => Err(Error::Bitstream(
|
||||
@@ -208,6 +226,7 @@ impl AnnexBDecoder {
|
||||
Codec::H264(decoder) => decoder.last_picture(),
|
||||
Codec::Hevc(decoder) => decoder.last_picture(),
|
||||
Codec::Av1(_) => None,
|
||||
Codec::Vp9(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,6 +236,7 @@ impl AnnexBDecoder {
|
||||
Codec::H264(decoder) => &decoder.accelerator().in_place,
|
||||
Codec::Hevc(decoder) => &decoder.accelerator().in_place,
|
||||
Codec::Av1(decoder) => &decoder.accelerator().in_place,
|
||||
Codec::Vp9(decoder) => &decoder.accelerator().in_place,
|
||||
};
|
||||
Bitstreams {
|
||||
in_place: in_place.in_place,
|
||||
@@ -276,6 +296,15 @@ impl AnnexBDecoder {
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
// A VP9 decoder decodes on after a frame NVDEC failed, from what
|
||||
// NVDEC left, as an H.264 one does; a sample shows one frame at
|
||||
// most, the whole of it.
|
||||
Codec::Vp9(decoder) => (decoder.decode(sample, id)?.into_iter())
|
||||
.map(|out| {
|
||||
let (width, height) = out.size;
|
||||
(out.picture, (0, 0, width, height))
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
};
|
||||
let mut outputs = outputs.into_iter();
|
||||
let picture = outputs.next();
|
||||
@@ -693,3 +722,5 @@ impl AnnexBPicture {
|
||||
mod av1_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod vp9_tests;
|
||||
@@ -0,0 +1,88 @@
|
||||
//! A VP9 [`AnnexBDecoder`] on the NVIDIA host: libvpx's streams
|
||||
//! (`crate::codec::vp9::tests`) decoded, each frame read back and hashed as
|
||||
//! libvpx's own decode of it hashes (NV12 and P010 planes, rows packed), MD5
|
||||
//! by MD5.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_video_conformance::md5::Md5;
|
||||
|
||||
use super::*;
|
||||
use crate::codec::vp9::tests::{
|
||||
PROFILE_0_IVF, PROFILE_0_MD5, PROFILE_2_IVF, PROFILE_2_MD5, ivf_frames,
|
||||
};
|
||||
use crate::core::runtime::Runtime;
|
||||
use crate::nvidia::cuda::GpuSelector;
|
||||
use crate::vaapi::gated::GatedRuntime;
|
||||
|
||||
fn gpu() -> Arc<Gpu> {
|
||||
Arc::new(Gpu::open(&GpuSelector::First).expect("an NVIDIA GPU"))
|
||||
}
|
||||
|
||||
/// Decodes `file` and hashes each frame read back.
|
||||
fn frame_md5s(gpu: &Arc<Gpu>, file: &[u8]) -> Vec<String> {
|
||||
let runtime: Arc<dyn Runtime> = Arc::new(GatedRuntime);
|
||||
let mut decoder = AnnexBDecoder::new(gpu, AnnexBCodec::Vp9, &runtime);
|
||||
let mut hashes = Vec::new();
|
||||
for (n, sample) in ivf_frames(file).into_iter().enumerate() {
|
||||
let picture = (decoder.decode(sample))
|
||||
.unwrap_or_else(|error| panic!("sample {n}: {error}"))
|
||||
.unwrap_or_else(|| panic!("sample {n} shows no frame"));
|
||||
let (x, y, width, height) = picture.crop();
|
||||
assert_eq!((x, y, width, height), (0, 0, 640, 360), "sample {n}");
|
||||
let read = picture.read_back((width, height)).expect("a read back");
|
||||
let mut md5 = Md5::new();
|
||||
for plane in read.planes() {
|
||||
md5.update(plane.bytes);
|
||||
}
|
||||
hashes.push(md5.hex());
|
||||
}
|
||||
assert_eq!(
|
||||
decoder.bitstreams(),
|
||||
Bitstreams {
|
||||
in_place: 33,
|
||||
gathered: 0
|
||||
},
|
||||
"every frame, the superframes' hidden ones too, sent in place"
|
||||
);
|
||||
hashes
|
||||
}
|
||||
|
||||
/// Each frame of profile 0, into NV12, and of profile 2, into P016 (P010's
|
||||
/// samples for 10 bits), is libvpx's.
|
||||
#[test]
|
||||
#[ignore = "needs an NVIDIA GPU that decodes VP9 profiles 0 and 2: run on the NVIDIA host"]
|
||||
fn libvpx_streams_decode_to_libvpx_frames() {
|
||||
let gpu = gpu();
|
||||
for (name, file, md5s) in [
|
||||
("profile 0", PROFILE_0_IVF, PROFILE_0_MD5),
|
||||
("profile 2", PROFILE_2_IVF, PROFILE_2_MD5),
|
||||
] {
|
||||
let got = frame_md5s(&gpu, file);
|
||||
let want: Vec<&str> = md5s.lines().collect();
|
||||
assert_eq!(got.len(), want.len(), "{name}: frames");
|
||||
for (frame, (got, want)) in got.iter().zip(&want).enumerate() {
|
||||
assert_eq!(got, want, "{name}: frame {frame}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A stream that starts after its key frame misses its references, as a
|
||||
/// picture's error, and decodes from the key frame on.
|
||||
#[test]
|
||||
#[ignore = "needs an NVIDIA GPU that decodes VP9 profile 0: run on the NVIDIA host"]
|
||||
fn a_stream_that_starts_after_its_key_frame_decodes_from_the_key_frame() {
|
||||
let gpu = gpu();
|
||||
let runtime: Arc<dyn Runtime> = Arc::new(GatedRuntime);
|
||||
let samples = ivf_frames(PROFILE_0_IVF);
|
||||
let mut decoder = AnnexBDecoder::new(&gpu, AnnexBCodec::Vp9, &runtime);
|
||||
let error = decoder.decode(samples[1]).err().expect("no reference");
|
||||
assert!(error.is_picture_error(), "{error}");
|
||||
assert!(decoder.decode(samples[0]).expect("the key frame").is_some());
|
||||
assert!(decoder.decode(samples[1]).expect("the next").is_some());
|
||||
assert!(decoder.parameter_sets(&[]).is_ok());
|
||||
assert!(matches!(
|
||||
decoder.parameter_sets(&[0, 0, 1]),
|
||||
Err(Error::Bitstream(_))
|
||||
));
|
||||
}
|
||||
@@ -125,7 +125,7 @@ macro_rules! from_codec {
|
||||
)*};
|
||||
}
|
||||
|
||||
from_codec!(h264, av1);
|
||||
from_codec!(h264, av1, vp9);
|
||||
|
||||
/// An HEVC error: as `from_codec`'s, and a RASL picture skipped is no
|
||||
/// malformed stream.
|
||||
|
||||
@@ -349,6 +349,7 @@ fn nvdec_checks(checks: &mut Checks) {
|
||||
size_of::<dec::CuvidCodecSpecific>(),
|
||||
);
|
||||
av1_checks(checks);
|
||||
vp9_checks(checks);
|
||||
layout!(checks, dec::CUVIDPROCPARAMS, "CUVIDPROCPARAMS" {
|
||||
progressive_frame, second_field, top_field_first, unpaired_field, reserved_flags,
|
||||
reserved_zero, raw_input_dptr, raw_input_pitch, raw_input_format, raw_output_dptr,
|
||||
@@ -497,6 +498,28 @@ fn av1_checks(checks: &mut Checks) {
|
||||
checks.constant("cudaVideoCodec_AV1", dec::cudaVideoCodec_AV1.into());
|
||||
}
|
||||
|
||||
/// `CUVIDVP9PICPARAMS`: its fields and its words' bit-fields.
|
||||
fn vp9_checks(checks: &mut Checks) {
|
||||
use dec::vp9::{self as vp9, CUVIDVP9PICPARAMS as P};
|
||||
layout!(checks, P, "CUVIDVP9PICPARAMS" {
|
||||
width, height, LastRefIdx, GoldenRefIdx, AltRefIdx, colorSpace, reserved16Bits,
|
||||
refFrameSignBias, bitDepthMinus8Luma, bitDepthMinus8Chroma, loopFilterLevel,
|
||||
loopFilterSharpness, modeRefLfEnabled, log2_tile_columns, log2_tile_rows,
|
||||
segmentFeatureEnable, segmentFeatureData, mb_segment_tree_probs, segment_pred_probs,
|
||||
reservedSegment16Bits, qpYAc, qpYDc, qpChDc, qpChAc, activeRefIdx, resetFrameContext,
|
||||
mcomp_filter_type, mbRefLfDelta, mbModeLfDelta, frameTagSize, offsetToDctParts,
|
||||
reserved128Bits,
|
||||
});
|
||||
bit_fields!(checks, P, "CUVIDVP9PICPARAMS", frame_word: u16, vp9::bits::frame {
|
||||
profile, frameContextIdx, frameType, showFrame, errorResilient, frameParallelDecoding,
|
||||
subSamplingX, subSamplingY, intraOnly, allow_high_precision_mv, refreshEntropyProbs,
|
||||
});
|
||||
bit_fields!(checks, P, "CUVIDVP9PICPARAMS", segmentation_word: u8, vp9::bits::segmentation {
|
||||
segmentEnabled, segmentMapUpdate, segmentMapTemporalUpdate, segmentFeatureMode,
|
||||
});
|
||||
checks.constant("cudaVideoCodec_VP9", dec::cudaVideoCodec_VP9.into());
|
||||
}
|
||||
|
||||
fn nvenc_checks(checks: &mut Checks) {
|
||||
layout!(checks, enc::GUID, "GUID" { Data1, Data2, Data3, Data4 });
|
||||
layout!(checks, enc::NV_ENC_CAPS_PARAM, "NV_ENC_CAPS_PARAM" {
|
||||
|
||||
@@ -9,6 +9,7 @@ pub(crate) mod decoder;
|
||||
pub(crate) mod ffi;
|
||||
pub(crate) mod h264;
|
||||
pub(crate) mod hevc;
|
||||
pub(crate) mod vp9;
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -51,17 +52,20 @@ pub enum NvdecCodec {
|
||||
Hevc,
|
||||
/// AV1.
|
||||
Av1,
|
||||
/// VP9.
|
||||
Vp9,
|
||||
}
|
||||
|
||||
impl NvdecCodec {
|
||||
/// Every codec, in `cudaVideoCodec`'s order.
|
||||
pub const ALL: [Self; 3] = [Self::H264, Self::Hevc, Self::Av1];
|
||||
pub const ALL: [Self; 4] = [Self::H264, Self::Hevc, Self::Av1, Self::Vp9];
|
||||
|
||||
pub(crate) fn raw(self) -> ffi::cudaVideoCodec {
|
||||
match self {
|
||||
Self::H264 => ffi::cudaVideoCodec_H264,
|
||||
Self::Hevc => ffi::cudaVideoCodec_HEVC,
|
||||
Self::Av1 => ffi::cudaVideoCodec_AV1,
|
||||
Self::Vp9 => ffi::cudaVideoCodec_VP9,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -901,6 +901,12 @@ impl Picture {
|
||||
&self.inner.gpu
|
||||
}
|
||||
|
||||
/// Whether it is one of `decoder`'s surfaces, which `decoder`'s
|
||||
/// pictures may name as a reference.
|
||||
pub(crate) fn is_of(&self, decoder: &Decoder) -> bool {
|
||||
Arc::ptr_eq(&self.inner, &decoder.inner)
|
||||
}
|
||||
|
||||
/// Another picture of this one's surface, to stand in for a lost frame
|
||||
/// that later frames predict from (ours). NVDEC's surfaces are written
|
||||
/// by a decode alone, and a decoded surface is decoded into again only
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! NVDEC's declarations (libnvcuvid's decoder half, `cuviddec.h`), the
|
||||
//! subset this crate uses: capabilities, the decoder, picture parameters
|
||||
//! for H.264, HEVC and AV1 ([`av1`]), mapping and status. NVIDIA's parser
|
||||
//! (`nvcuvid.h`) is not used: our own parsers fill the picture parameters.
|
||||
//! for H.264, HEVC, AV1 ([`av1`]) and VP9 ([`vp9`]), mapping and status.
|
||||
//! NVIDIA's parser (`nvcuvid.h`) is not used: our own parsers fill the
|
||||
//! picture parameters.
|
||||
//!
|
||||
//! Field names are the header's, so that `crate::nvidia::layout`'s test can check
|
||||
//! each size, offset and bit-field against ffnvcodec's `dynlink_cuviddec.h`
|
||||
@@ -25,6 +26,7 @@ pub(crate) use crate::nvidia::dl::Zeroed;
|
||||
use crate::nvidia::dl::functions;
|
||||
|
||||
pub(crate) mod av1;
|
||||
pub(crate) mod vp9;
|
||||
|
||||
/// `CUvideodecoder`.
|
||||
pub(crate) type CUvideodecoder = *mut c_void;
|
||||
@@ -46,6 +48,7 @@ pub(crate) type cuvidDecodeStatus = c_uint;
|
||||
pub(crate) const cudaVideoCodec_H264: cudaVideoCodec = 4;
|
||||
pub(crate) const cudaVideoCodec_HEVC: cudaVideoCodec = 8;
|
||||
pub(crate) const cudaVideoCodec_AV1: cudaVideoCodec = 11;
|
||||
pub(crate) const cudaVideoCodec_VP9: cudaVideoCodec = 10;
|
||||
|
||||
pub(crate) const cudaVideoChromaFormat_Monochrome: cudaVideoChromaFormat = 0;
|
||||
pub(crate) const cudaVideoChromaFormat_420: cudaVideoChromaFormat = 1;
|
||||
@@ -326,6 +329,7 @@ pub(crate) union CuvidCodecSpecific {
|
||||
pub(crate) h264: CUVIDH264PICPARAMS,
|
||||
pub(crate) hevc: CUVIDHEVCPICPARAMS,
|
||||
pub(crate) av1: av1::CUVIDAV1PICPARAMS,
|
||||
pub(crate) vp9: vp9::CUVIDVP9PICPARAMS,
|
||||
pub(crate) CodecReserved: [c_uint; 1024],
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
//! `CUVIDVP9PICPARAMS` (ffnvcodec's `dynlink_cuviddec.h`, NVDECAPI 13.1): one VP9 frame's
|
||||
//! parameters, `CUVIDPICPARAMS::CodecSpecific.vp9`. The header's bit-fields are held in
|
||||
//! words named for what they hold, each marked as ours, with their fields' positions in
|
||||
//! [`bits`]; `crate::nvidia::layout`'s test checks them against the header.
|
||||
|
||||
use std::ffi::{c_int, c_short, c_uint, c_ushort};
|
||||
|
||||
use super::Zeroed;
|
||||
|
||||
/// `CUVIDVP9PICPARAMS`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct CUVIDVP9PICPARAMS {
|
||||
pub(crate) width: c_uint,
|
||||
pub(crate) height: c_uint,
|
||||
pub(crate) LastRefIdx: u8,
|
||||
pub(crate) GoldenRefIdx: u8,
|
||||
pub(crate) AltRefIdx: u8,
|
||||
pub(crate) colorSpace: u8,
|
||||
/// The frame's bit-fields, `profile` to `reserved2Bits`: [`bits::frame`]. Name is ours.
|
||||
pub(crate) frame_word: c_ushort,
|
||||
pub(crate) reserved16Bits: c_ushort,
|
||||
pub(crate) refFrameSignBias: [u8; 4],
|
||||
pub(crate) bitDepthMinus8Luma: u8,
|
||||
pub(crate) bitDepthMinus8Chroma: u8,
|
||||
pub(crate) loopFilterLevel: u8,
|
||||
pub(crate) loopFilterSharpness: u8,
|
||||
pub(crate) modeRefLfEnabled: u8,
|
||||
pub(crate) log2_tile_columns: u8,
|
||||
pub(crate) log2_tile_rows: u8,
|
||||
/// The segmentation's bit-fields, `segmentEnabled` to `reserved4Bits`:
|
||||
/// [`bits::segmentation`]. Name is ours.
|
||||
pub(crate) segmentation_word: u8,
|
||||
pub(crate) segmentFeatureEnable: [[u8; 4]; 8],
|
||||
pub(crate) segmentFeatureData: [[c_short; 4]; 8],
|
||||
pub(crate) mb_segment_tree_probs: [u8; 7],
|
||||
pub(crate) segment_pred_probs: [u8; 3],
|
||||
pub(crate) reservedSegment16Bits: [u8; 2],
|
||||
pub(crate) qpYAc: c_int,
|
||||
pub(crate) qpYDc: c_int,
|
||||
pub(crate) qpChDc: c_int,
|
||||
pub(crate) qpChAc: c_int,
|
||||
pub(crate) activeRefIdx: [c_uint; 3],
|
||||
pub(crate) resetFrameContext: c_uint,
|
||||
pub(crate) mcomp_filter_type: c_uint,
|
||||
pub(crate) mbRefLfDelta: [c_uint; 4],
|
||||
pub(crate) mbModeLfDelta: [c_uint; 2],
|
||||
pub(crate) frameTagSize: c_uint,
|
||||
pub(crate) offsetToDctParts: c_uint,
|
||||
pub(crate) reserved128Bits: [c_uint; 4],
|
||||
}
|
||||
|
||||
// SAFETY: repr(C), and holds only integers and arrays of them (`Zeroed`'s contract).
|
||||
unsafe impl Zeroed for CUVIDVP9PICPARAMS {}
|
||||
|
||||
// The size ffnvcodec 13.1.15.0's header gives on x86-64 Linux; `crate::nvidia::layout`'s test
|
||||
// checks every offset and bit-field too.
|
||||
const _: () = assert!(size_of::<CUVIDVP9PICPARAMS>() == 220);
|
||||
|
||||
/// The positions of the header's bit-fields in the words above, from the least significant bit
|
||||
/// up in declaration order (GCC's x86-64 layout).
|
||||
pub(crate) mod bits {
|
||||
use super::super::bits::Bits;
|
||||
|
||||
const fn b(shift: u32, width: u32) -> Bits {
|
||||
Bits { shift, width }
|
||||
}
|
||||
|
||||
/// `CUVIDVP9PICPARAMS::frame_word`.
|
||||
pub(crate) mod frame {
|
||||
use super::{Bits, b};
|
||||
pub(crate) const profile: Bits = b(0, 3);
|
||||
pub(crate) const frameContextIdx: Bits = b(3, 2);
|
||||
pub(crate) const frameType: Bits = b(5, 1);
|
||||
pub(crate) const showFrame: Bits = b(6, 1);
|
||||
pub(crate) const errorResilient: Bits = b(7, 1);
|
||||
pub(crate) const frameParallelDecoding: Bits = b(8, 1);
|
||||
pub(crate) const subSamplingX: Bits = b(9, 1);
|
||||
pub(crate) const subSamplingY: Bits = b(10, 1);
|
||||
pub(crate) const intraOnly: Bits = b(11, 1);
|
||||
pub(crate) const allow_high_precision_mv: Bits = b(12, 1);
|
||||
pub(crate) const refreshEntropyProbs: Bits = b(13, 1);
|
||||
}
|
||||
|
||||
/// `CUVIDVP9PICPARAMS::segmentation_word`.
|
||||
pub(crate) mod segmentation {
|
||||
use super::{Bits, b};
|
||||
pub(crate) const segmentEnabled: Bits = b(0, 1);
|
||||
pub(crate) const segmentMapUpdate: Bits = b(1, 1);
|
||||
pub(crate) const segmentMapTemporalUpdate: Bits = b(2, 1);
|
||||
pub(crate) const segmentFeatureMode: Bits = b(3, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
//! VP9 on NVDEC: the codec crate's decoder over an accelerator that fills
|
||||
//! `CUVIDVP9PICPARAMS` from the frame's uncompressed header and the
|
||||
//! reference slots, and hands NVDEC the frame whole, its uncompressed header
|
||||
//! first, as one slice at its start, as ffmpeg's `nvdec_vp9.c` does. NVDEC
|
||||
//! reads the compressed header and the tiles itself; NVIDIA's own parser is
|
||||
//! not used. The frame is sent where it lies in the sample, with no copy.
|
||||
//!
|
||||
//! A decoder is made for each run of frames of one format and size (the
|
||||
//! codec crate's `Accelerator::configure`), at the frame's size, as ffmpeg
|
||||
//! makes one at a VP9 stream's `coded_width`, its frame's width. NVDEC names
|
||||
//! a frame's references by their surfaces in its decoder, so an inter frame
|
||||
//! whose references are another decoder's, a frame of another size than the
|
||||
//! frames it predicts from, is refused as a picture's error, as are the
|
||||
//! frames after it that predict from them, until an intra frame fills the
|
||||
//! slots again (docs/video/bugs.md).
|
||||
|
||||
use std::ffi::{c_int, c_short, c_uint, c_ushort};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::codec::vp9::header::FrameHeader;
|
||||
use crate::codec::vp9::{Accelerator, Format, FrameParams};
|
||||
|
||||
use super::decoder::{
|
||||
Decoder, DecoderSpec, InPlace, Picture, SPARE_SURFACES, Slices, active, surface_count,
|
||||
};
|
||||
use super::ffi::vp9::CUVIDVP9PICPARAMS;
|
||||
use super::ffi::vp9::bits::{frame, segmentation};
|
||||
use super::ffi::{self, Zeroed};
|
||||
use super::{ChromaFormat, NvdecCodec};
|
||||
use crate::nvidia::cuda::Gpu;
|
||||
use crate::nvidia::error::Error;
|
||||
|
||||
/// VP9's reference slots.
|
||||
const SLOTS: usize = 8;
|
||||
|
||||
/// A reference NVDEC is not to read: an intra frame's, as ffmpeg's
|
||||
/// `ff_nvdec_get_ref_idx` gives a missing one.
|
||||
const NO_REFERENCE: u8 = 0xff;
|
||||
|
||||
/// The NVDEC half of the VP9 decoder.
|
||||
pub(crate) struct NvdecVp9 {
|
||||
gpu: Arc<Gpu>,
|
||||
decoder: Option<Decoder>,
|
||||
/// The frames sent: each in place, its own bytes of the sample.
|
||||
pub(crate) in_place: InPlace,
|
||||
}
|
||||
|
||||
impl NvdecVp9 {
|
||||
pub(crate) fn new(gpu: Arc<Gpu>) -> Self {
|
||||
Self {
|
||||
gpu,
|
||||
decoder: None,
|
||||
in_place: InPlace::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The decoder a run of `format`'s frames needs: 4:2:0 at its depth and
|
||||
/// size, with a surface for each slot, the frame being decoded and the
|
||||
/// spares.
|
||||
pub(crate) fn spec(format: &Format) -> DecoderSpec {
|
||||
DecoderSpec {
|
||||
codec: NvdecCodec::Vp9,
|
||||
chroma: ChromaFormat::Yuv420,
|
||||
bit_depth: u32::from(format.bit_depth),
|
||||
width: format.width,
|
||||
height: format.height,
|
||||
surfaces: surface_count(SLOTS + 1 + SPARE_SURFACES),
|
||||
}
|
||||
}
|
||||
|
||||
impl Accelerator for NvdecVp9 {
|
||||
type Picture = Picture;
|
||||
type Error = Error;
|
||||
|
||||
fn configure(&mut self, format: &Format) -> Result<(), Error> {
|
||||
self.decoder = None;
|
||||
self.decoder = Some(Decoder::new(Arc::clone(&self.gpu), &spec(format))?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new_picture(&mut self) -> Result<Picture, Error> {
|
||||
active(self.decoder.as_ref())?.picture()
|
||||
}
|
||||
|
||||
fn decode_frame(
|
||||
&mut self,
|
||||
picture: &Picture,
|
||||
params: &FrameParams<'_, Picture>,
|
||||
) -> Result<(), Error> {
|
||||
let decoder = active(self.decoder.as_ref())?;
|
||||
let mut pic = picture_parameters(decoder, picture, params)?;
|
||||
// One slice, the frame whole, at its start.
|
||||
let decoded = decoder.decode(&mut pic, params.frame, Slices::Starts(&[0]));
|
||||
self.in_place.in_place += 1;
|
||||
decoded
|
||||
}
|
||||
}
|
||||
|
||||
fn int(value: u32) -> c_int {
|
||||
c_int::try_from(value).unwrap_or(c_int::MAX)
|
||||
}
|
||||
|
||||
/// The surface of the frame in `slot` that a frame of `decoder`'s names as
|
||||
/// a reference.
|
||||
fn reference(decoder: &Decoder, params: &FrameParams<'_, Picture>, slot: u8) -> Result<u8, Error> {
|
||||
let reference = (params.references.get(usize::from(slot)))
|
||||
.and_then(Option::as_ref)
|
||||
.ok_or_else(|| Error::Picture(format!("VP9: reference slot {slot} holds no frame")))?;
|
||||
if !reference.picture.is_of(decoder) {
|
||||
return Err(Error::Picture(format!(
|
||||
"VP9 on NVDEC: a {}x{} frame that predicts from a {}x{} one, of another decoder",
|
||||
params.header.width, params.header.height, reference.width, reference.height
|
||||
)));
|
||||
}
|
||||
u8::try_from(reference.picture.index())
|
||||
.map_err(|_| Error::Unsupported("a VP9 reference past surface 254".to_owned()))
|
||||
}
|
||||
|
||||
/// The frame's `CUVIDPICPARAMS`, all but its bitstream, filled as ffmpeg's
|
||||
/// `nvdec_vp9.c` fills them.
|
||||
fn picture_parameters(
|
||||
decoder: &Decoder,
|
||||
picture: &Picture,
|
||||
p: &FrameParams<'_, Picture>,
|
||||
) -> Result<ffi::CUVIDPICPARAMS, Error> {
|
||||
let h = p.header;
|
||||
let references = if h.is_intra() {
|
||||
[NO_REFERENCE; 3]
|
||||
} else {
|
||||
let [last, golden, alt] = h.ref_frame_idx;
|
||||
[
|
||||
reference(decoder, p, last)?,
|
||||
reference(decoder, p, golden)?,
|
||||
reference(decoder, p, alt)?,
|
||||
]
|
||||
};
|
||||
let mut out = ffi::CUVIDPICPARAMS::zeroed();
|
||||
out.PicWidthInMbs = int(h.width.div_ceil(16));
|
||||
out.FrameHeightInMbs = int(h.height.div_ceil(16));
|
||||
out.CurrPicIdx = picture.index();
|
||||
out.CodecSpecific.vp9 = vp9_parameters(h, references);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// `h`'s `CUVIDVP9PICPARAMS`, its last, golden and altref frames' surfaces
|
||||
/// `references`.
|
||||
fn vp9_parameters(h: &FrameHeader, references: [u8; 3]) -> CUVIDVP9PICPARAMS {
|
||||
let mut v = CUVIDVP9PICPARAMS::zeroed();
|
||||
v.width = h.width;
|
||||
v.height = h.height;
|
||||
[v.LastRefIdx, v.GoldenRefIdx, v.AltRefIdx] = references;
|
||||
// VP9's own `color_space`, which ffmpeg maps its colour spaces back to.
|
||||
v.colorSpace = h.color.color_space;
|
||||
let flag = u32::from;
|
||||
let frame_word = [
|
||||
(frame::profile, u32::from(h.profile)),
|
||||
(frame::frameContextIdx, u32::from(h.frame_context_idx)),
|
||||
// 0 a key frame, 1 another.
|
||||
(frame::frameType, flag(!h.key_frame)),
|
||||
(frame::showFrame, flag(h.show_frame)),
|
||||
(frame::errorResilient, flag(h.error_resilient_mode)),
|
||||
(
|
||||
frame::frameParallelDecoding,
|
||||
flag(h.frame_parallel_decoding_mode),
|
||||
),
|
||||
(frame::subSamplingX, flag(h.color.subsampling_x)),
|
||||
(frame::subSamplingY, flag(h.color.subsampling_y)),
|
||||
(frame::intraOnly, flag(h.intra_only)),
|
||||
(
|
||||
frame::allow_high_precision_mv,
|
||||
flag(h.allow_high_precision_mv),
|
||||
),
|
||||
(frame::refreshEntropyProbs, flag(h.refresh_frame_context)),
|
||||
]
|
||||
.into_iter()
|
||||
.fold(0, |word, (bits, value)| bits.put(word, value));
|
||||
// Its fields' 14 bits.
|
||||
v.frame_word = c_ushort::try_from(frame_word).unwrap_or(0);
|
||||
let [last_bias, golden_bias, alt_bias] = h.ref_frame_sign_bias.map(u8::from);
|
||||
v.refFrameSignBias = [0, last_bias, golden_bias, alt_bias];
|
||||
let depth_minus_8 = h.color.bit_depth.saturating_sub(8);
|
||||
(v.bitDepthMinus8Luma, v.bitDepthMinus8Chroma) = (depth_minus_8, depth_minus_8);
|
||||
|
||||
let lf = &h.loop_filter;
|
||||
v.loopFilterLevel = lf.level;
|
||||
v.loopFilterSharpness = lf.sharpness;
|
||||
v.modeRefLfEnabled = u8::from(lf.delta_enabled);
|
||||
// The deltas as `int`s in `unsigned int`s, as ffmpeg assigns them.
|
||||
v.mbRefLfDelta = lf.ref_deltas.map(|delta| i32::from(delta).cast_unsigned());
|
||||
v.mbModeLfDelta = lf.mode_deltas.map(|delta| i32::from(delta).cast_unsigned());
|
||||
v.log2_tile_columns = h.tile_cols_log2;
|
||||
v.log2_tile_rows = h.tile_rows_log2;
|
||||
|
||||
let seg = &h.segmentation;
|
||||
let segmentation_word = [
|
||||
(segmentation::segmentEnabled, flag(seg.enabled)),
|
||||
(segmentation::segmentMapUpdate, flag(seg.update_map)),
|
||||
(
|
||||
segmentation::segmentMapTemporalUpdate,
|
||||
flag(seg.temporal_update),
|
||||
),
|
||||
(
|
||||
segmentation::segmentFeatureMode,
|
||||
flag(seg.abs_or_delta_update),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.fold(0, |word, (bits, value)| bits.put(word, value));
|
||||
// Its fields' 4 bits.
|
||||
v.segmentation_word = u8::try_from(segmentation_word).unwrap_or(0);
|
||||
v.segmentFeatureEnable = seg.feature_enabled.map(|features| features.map(u8::from));
|
||||
// The quantizer, filter level and reference, and nothing for the skip
|
||||
// feature, which has no data.
|
||||
v.segmentFeatureData = seg
|
||||
.feature_data
|
||||
.map(|[q, lf, reference, _]| -> [c_short; 4] { [q, lf, reference, 0] });
|
||||
v.mb_segment_tree_probs = seg.tree_probs;
|
||||
// As the VA arm sends them: 255 where the map's prediction is not
|
||||
// temporal, where NVDEC does not read them.
|
||||
v.segment_pred_probs = if seg.temporal_update {
|
||||
seg.pred_probs
|
||||
} else {
|
||||
[255; 3]
|
||||
};
|
||||
|
||||
let q = &h.quantization;
|
||||
v.qpYAc = c_int::from(q.base_q_idx);
|
||||
v.qpYDc = c_int::from(q.delta_q_y_dc);
|
||||
v.qpChDc = c_int::from(q.delta_q_uv_dc);
|
||||
v.qpChAc = c_int::from(q.delta_q_uv_ac);
|
||||
v.activeRefIdx = h.ref_frame_idx.map(c_uint::from);
|
||||
v.resetFrameContext = c_uint::from(h.reset_frame_context);
|
||||
// libvpx's numbering, the header's.
|
||||
v.mcomp_filter_type = c_uint::from(h.interp_filter);
|
||||
v.frameTagSize = c_uint::from(h.uncompressed_header_size);
|
||||
v.offsetToDctParts = c_uint::from(h.header_size_in_bytes);
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::codec::vp9::header::{self, State};
|
||||
use crate::codec::vp9::tests::{FrameSpec, SegmentationSpec};
|
||||
|
||||
/// The value of the field `bits` in `word`.
|
||||
fn field(word: u16, bits: ffi::bits::Bits) -> u32 {
|
||||
(u32::from(word) & bits.mask()) >> bits.shift
|
||||
}
|
||||
|
||||
/// A key frame's fields reach `CUVIDVP9PICPARAMS` as ffmpeg's
|
||||
/// `nvdec_vp9.c` sets them, naming no reference.
|
||||
#[test]
|
||||
fn a_key_frames_header_fills_its_fields_as_ffmpeg_fills_them() {
|
||||
let mut spec = FrameSpec::key(640, 360);
|
||||
spec.filter_level = 36;
|
||||
spec.sharpness = 3;
|
||||
spec.base_q = 120;
|
||||
spec.delta_q = [-3, 2, 5];
|
||||
spec.tile_cols_increments = 1;
|
||||
let mut features = [[None; 4]; 8];
|
||||
features[2] = [Some(-20), Some(7), Some(1), Some(0)];
|
||||
spec.segmentation = Some(SegmentationSpec {
|
||||
update_map: None,
|
||||
update_data: Some((true, features)),
|
||||
});
|
||||
let bytes = spec.write();
|
||||
let (h, _) = header::parse(&bytes, &State::default(), &[None; 8]).unwrap();
|
||||
let v = vp9_parameters(&h, [NO_REFERENCE; 3]);
|
||||
assert_eq!((v.width, v.height), (640, 360));
|
||||
assert_eq!(
|
||||
[v.LastRefIdx, v.GoldenRefIdx, v.AltRefIdx],
|
||||
[NO_REFERENCE; 3]
|
||||
);
|
||||
assert_eq!(field(v.frame_word, frame::profile), 0);
|
||||
assert_eq!(field(v.frame_word, frame::frameType), 0);
|
||||
assert_eq!(field(v.frame_word, frame::showFrame), 1);
|
||||
assert_eq!(field(v.frame_word, frame::subSamplingX), 1);
|
||||
assert_eq!(field(v.frame_word, frame::subSamplingY), 1);
|
||||
assert_eq!(field(v.frame_word, frame::intraOnly), 0);
|
||||
assert_eq!(field(v.frame_word, frame::allow_high_precision_mv), 0);
|
||||
assert_eq!((v.bitDepthMinus8Luma, v.bitDepthMinus8Chroma), (0, 0));
|
||||
assert_eq!((v.loopFilterLevel, v.loopFilterSharpness), (36, 3));
|
||||
assert_eq!((v.log2_tile_columns, v.log2_tile_rows), (1, 0));
|
||||
assert_eq!((v.qpYAc, v.qpYDc, v.qpChDc, v.qpChAc), (120, -3, 2, 5));
|
||||
let seg = u16::from(v.segmentation_word);
|
||||
assert_eq!(field(seg, segmentation::segmentEnabled), 1);
|
||||
assert_eq!(field(seg, segmentation::segmentFeatureMode), 1);
|
||||
assert_eq!(v.segmentFeatureEnable[2], [1, 1, 1, 1]);
|
||||
assert_eq!(v.segmentFeatureData[2], [-20, 7, 1, 0]);
|
||||
assert_eq!(v.segmentFeatureEnable[0], [0; 4]);
|
||||
assert_eq!(v.segment_pred_probs, [255; 3]);
|
||||
// A key frame's deltas, as the specification sets them up, each an
|
||||
// `int` in an `unsigned int`.
|
||||
let minus_one = (-1i32).cast_unsigned();
|
||||
assert_eq!(v.mbRefLfDelta, [1, 0, minus_one, minus_one]);
|
||||
assert_eq!(v.mbModeLfDelta, [0, 0]);
|
||||
assert_eq!(v.frameTagSize, u32::from(h.uncompressed_header_size));
|
||||
assert_eq!(v.offsetToDctParts, u32::from(h.header_size_in_bytes));
|
||||
assert!(v.frameTagSize > 0 && v.offsetToDctParts > 0);
|
||||
}
|
||||
|
||||
/// An inter frame's references, their sign biases and slots, its
|
||||
/// filter in libvpx's numbering and its 10 bits reach their fields.
|
||||
#[test]
|
||||
fn an_inter_frames_references_and_filter_reach_their_fields() {
|
||||
let mut key = FrameSpec::key(64, 64);
|
||||
key.profile = 2;
|
||||
let (_, state) = header::parse(&key.write(), &State::default(), &[None; 8]).unwrap();
|
||||
let mut spec = FrameSpec::inter(64, 64);
|
||||
spec.profile = 2;
|
||||
spec.refs = [3, 5, 7];
|
||||
spec.sign_bias = [false, true, true];
|
||||
spec.high_precision_mv = true;
|
||||
spec.context_idx = 2;
|
||||
// The coded literal 0, EIGHTTAP_SMOOTH, 1 in libvpx's numbering.
|
||||
spec.filter = Some(0);
|
||||
let (h, _) = header::parse(&spec.write(), &state, &[Some((64, 64)); 8]).unwrap();
|
||||
let v = vp9_parameters(&h, [9, 4, 0]);
|
||||
assert_eq!([v.LastRefIdx, v.GoldenRefIdx, v.AltRefIdx], [9, 4, 0]);
|
||||
assert_eq!(v.activeRefIdx, [3, 5, 7]);
|
||||
assert_eq!(v.refFrameSignBias, [0, 0, 1, 1]);
|
||||
assert_eq!(field(v.frame_word, frame::profile), 2);
|
||||
assert_eq!(field(v.frame_word, frame::frameType), 1);
|
||||
assert_eq!(field(v.frame_word, frame::frameContextIdx), 2);
|
||||
assert_eq!(field(v.frame_word, frame::allow_high_precision_mv), 1);
|
||||
assert_eq!(v.mcomp_filter_type, 1);
|
||||
assert_eq!((v.bitDepthMinus8Luma, v.bitDepthMinus8Chroma), (2, 2));
|
||||
// Nothing past the fields' bits.
|
||||
assert_eq!(v.frame_word >> 14, 0);
|
||||
assert_eq!(v.segmentation_word >> 4, 0);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! codecs of [`crate::codec`].
|
||||
//!
|
||||
//! - The libva binding and the decoders on it: [`Display`],
|
||||
//! [`H264Decoder`], [`HevcDecoder`], [`Frame`].
|
||||
//! [`H264Decoder`], [`HevcDecoder`], [`Vp9Decoder`], [`Frame`].
|
||||
//! - [`VideoEncoder`] runs [`crate::codec::encode`]'s encoders on VA-API.
|
||||
|
||||
mod va;
|
||||
@@ -28,6 +28,8 @@ pub use va::SharedTexture;
|
||||
#[cfg(windows)]
|
||||
pub use va::{PlaneDraw, PlaneTargets};
|
||||
|
||||
pub use va::Vp9Decoder;
|
||||
|
||||
pub use va::{
|
||||
TARGET_ALIGNMENT, Target, TargetChecks, TargetCodec, TargetFor, TargetFormat, TargetPlane,
|
||||
TargetShape, TargetTiling,
|
||||
|
||||
@@ -53,6 +53,7 @@ mod target_check;
|
||||
pub(crate) mod target_probe;
|
||||
#[cfg(test)]
|
||||
mod teardown;
|
||||
mod vp9;
|
||||
mod vpp_ffi;
|
||||
mod wait;
|
||||
mod zero_copy;
|
||||
@@ -82,4 +83,5 @@ pub use libva::LoadError;
|
||||
pub use readback::{ReadbackTimes, ReadbackWay, read_back_by};
|
||||
pub use target::{Target, TargetFor, TargetFormat, TargetPlane, TargetShape, TargetTiling};
|
||||
pub use target_check::{ALIGNMENT as TARGET_ALIGNMENT, TargetChecks, TargetCodec};
|
||||
pub use vp9::Vp9Decoder;
|
||||
pub use zero_copy::PackedTarget;
|
||||
@@ -50,6 +50,10 @@ impl Profile {
|
||||
pub const HEVC_MAIN444_10: Self = Self(ffi::VAProfileHEVCMain444_10);
|
||||
/// `VAProfileHEVCMain444_12`: the range extensions' 4:4:4 at 12 bits.
|
||||
pub const HEVC_MAIN444_12: Self = Self(ffi::VAProfileHEVCMain444_12);
|
||||
/// `VAProfileVP9Profile0`: 4:2:0 at 8 bits.
|
||||
pub const VP9_PROFILE0: Self = Self(ffi::vp9::VAProfileVP9Profile0);
|
||||
/// `VAProfileVP9Profile2`: 4:2:0 at 10 or 12 bits.
|
||||
pub const VP9_PROFILE2: Self = Self(ffi::vp9::VAProfileVP9Profile2);
|
||||
|
||||
/// va.h's name for the profile, without its `VAProfile` prefix.
|
||||
pub fn name(self) -> Option<&'static str> {
|
||||
|
||||
@@ -48,6 +48,8 @@ pub enum Error {
|
||||
},
|
||||
/// The stream is malformed, or uses what the decoder refuses.
|
||||
Bitstream(crate::codec::h264::Error),
|
||||
/// The VP9 stream is malformed, or uses what the decoder refuses.
|
||||
Vp9Bitstream(crate::codec::vp9::Error),
|
||||
/// The HEVC stream is malformed, or uses what the decoder refuses.
|
||||
HevcBitstream(crate::codec::hevc::Error),
|
||||
/// The AV1 stream is malformed, or uses what the decoder refuses.
|
||||
@@ -78,6 +80,7 @@ impl std::fmt::Display for Error {
|
||||
status,
|
||||
message,
|
||||
} => write!(f, "{call} failed: {message} ({status:#x})"),
|
||||
Self::Vp9Bitstream(e) => write!(f, "{e}"),
|
||||
Self::Bitstream(e) => write!(f, "{e}"),
|
||||
Self::HevcBitstream(e) => write!(f, "{e}"),
|
||||
Self::Av1Bitstream(e) => write!(f, "{e}"),
|
||||
@@ -91,10 +94,11 @@ impl std::fmt::Display for Error {
|
||||
|
||||
impl Error {
|
||||
/// Whether the error is one picture's of the stream, after which the decoder goes on (the
|
||||
/// codec crate's `is_picture_error`, H.264's, HEVC's and AV1's): the rest are the decoder's own or
|
||||
/// the driver's.
|
||||
/// codec crate's `is_picture_error`, H.264's, HEVC's, AV1's and VP9's): the rest are the
|
||||
/// decoder's own or the driver's.
|
||||
pub fn is_picture_error(&self) -> bool {
|
||||
match self {
|
||||
Self::Vp9Bitstream(e) => e.is_picture_error(),
|
||||
Self::Bitstream(e) => e.is_picture_error(),
|
||||
Self::HevcBitstream(e) => e.is_picture_error(),
|
||||
Self::Av1Bitstream(e) => e.is_picture_error(),
|
||||
@@ -111,6 +115,12 @@ impl From<crate::codec::h264::Error> for Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl From<crate::codec::vp9::Error> for Error {
|
||||
fn from(e: crate::codec::vp9::Error) -> Self {
|
||||
Self::Vp9Bitstream(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<crate::codec::hevc::Error> for Error {
|
||||
fn from(e: crate::codec::hevc::Error) -> Self {
|
||||
Self::HevcBitstream(e)
|
||||
|
||||
@@ -18,6 +18,7 @@ use core::ffi::{c_char, c_int, c_uint, c_void};
|
||||
|
||||
pub(crate) mod av1;
|
||||
pub(crate) mod encode;
|
||||
pub(crate) mod vp9;
|
||||
|
||||
pub(crate) type VADisplay = *mut c_void;
|
||||
pub(crate) type VAStatus = c_int;
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
//! libva's VP9 decode interface (`va_dec_vp9.h`, and its profiles in
|
||||
//! `va.h`), hand-written from libva 2.24.1's headers (VA-API 1.24.0). The
|
||||
//! test at the end checks every struct's size and offsets, every
|
||||
//! bit-field's position and every constant's value against those headers
|
||||
//! with a C compiler, as the parent module's test does for H.264 and HEVC.
|
||||
//!
|
||||
//! Names keep libva's spelling; struct fields are snake-cased.
|
||||
|
||||
#![expect(
|
||||
non_upper_case_globals,
|
||||
reason = "libva's names, kept for grepping the headers"
|
||||
)]
|
||||
|
||||
use super::{BitField, VA_PADDING_LOW, VA_PADDING_MEDIUM, VAProfile, VASurfaceID};
|
||||
|
||||
// VAProfile.
|
||||
pub(crate) const VAProfileVP9Profile0: VAProfile = 19;
|
||||
pub(crate) const VAProfileVP9Profile2: VAProfile = 21;
|
||||
|
||||
/// `VADecPictureParameterBufferVP9`: a frame's uncompressed header, as
|
||||
/// the driver takes it.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct VADecPictureParameterBufferVP9 {
|
||||
pub(crate) frame_width: u16,
|
||||
pub(crate) frame_height: u16,
|
||||
/// The eight reference slots' surfaces, `VA_INVALID_SURFACE` for an
|
||||
/// empty one.
|
||||
pub(crate) reference_frames: [VASurfaceID; 8],
|
||||
/// [`vp9_pic_fields`].
|
||||
pub(crate) pic_fields: u32,
|
||||
pub(crate) filter_level: u8,
|
||||
pub(crate) sharpness_level: u8,
|
||||
pub(crate) log2_tile_rows: u8,
|
||||
pub(crate) log2_tile_columns: u8,
|
||||
/// The uncompressed header's bytes.
|
||||
pub(crate) frame_header_length_in_bytes: u8,
|
||||
/// The compressed header's bytes (`header_size_in_bytes`).
|
||||
pub(crate) first_partition_size: u16,
|
||||
pub(crate) mb_segment_tree_probs: [u8; 7],
|
||||
pub(crate) segment_pred_probs: [u8; 3],
|
||||
pub(crate) profile: u8,
|
||||
pub(crate) bit_depth: u8,
|
||||
pub(crate) va_reserved: [u32; VA_PADDING_MEDIUM],
|
||||
}
|
||||
|
||||
/// `VADecPictureParameterBufferVP9::pic_fields.bits`.
|
||||
pub(crate) mod vp9_pic_fields {
|
||||
use super::BitField;
|
||||
pub(crate) const SUBSAMPLING_X: BitField = BitField::new(0, 1);
|
||||
pub(crate) const SUBSAMPLING_Y: BitField = BitField::new(1, 1);
|
||||
pub(crate) const FRAME_TYPE: BitField = BitField::new(2, 1);
|
||||
pub(crate) const SHOW_FRAME: BitField = BitField::new(3, 1);
|
||||
pub(crate) const ERROR_RESILIENT_MODE: BitField = BitField::new(4, 1);
|
||||
pub(crate) const INTRA_ONLY: BitField = BitField::new(5, 1);
|
||||
pub(crate) const ALLOW_HIGH_PRECISION_MV: BitField = BitField::new(6, 1);
|
||||
pub(crate) const MCOMP_FILTER_TYPE: BitField = BitField::new(7, 3);
|
||||
pub(crate) const FRAME_PARALLEL_DECODING_MODE: BitField = BitField::new(10, 1);
|
||||
pub(crate) const RESET_FRAME_CONTEXT: BitField = BitField::new(11, 2);
|
||||
pub(crate) const REFRESH_FRAME_CONTEXT: BitField = BitField::new(13, 1);
|
||||
pub(crate) const FRAME_CONTEXT_IDX: BitField = BitField::new(14, 2);
|
||||
pub(crate) const SEGMENTATION_ENABLED: BitField = BitField::new(16, 1);
|
||||
pub(crate) const SEGMENTATION_TEMPORAL_UPDATE: BitField = BitField::new(17, 1);
|
||||
pub(crate) const SEGMENTATION_UPDATE_MAP: BitField = BitField::new(18, 1);
|
||||
pub(crate) const LAST_REF_FRAME: BitField = BitField::new(19, 3);
|
||||
pub(crate) const LAST_REF_FRAME_SIGN_BIAS: BitField = BitField::new(22, 1);
|
||||
pub(crate) const GOLDEN_REF_FRAME: BitField = BitField::new(23, 3);
|
||||
pub(crate) const GOLDEN_REF_FRAME_SIGN_BIAS: BitField = BitField::new(26, 1);
|
||||
pub(crate) const ALT_REF_FRAME: BitField = BitField::new(27, 3);
|
||||
pub(crate) const ALT_REF_FRAME_SIGN_BIAS: BitField = BitField::new(30, 1);
|
||||
pub(crate) const LOSSLESS_FLAG: BitField = BitField::new(31, 1);
|
||||
}
|
||||
|
||||
/// `VASegmentParameterVP9`: one segment's features and derived values.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct VASegmentParameterVP9 {
|
||||
/// [`vp9_segment_flags`], a `uint16_t` union.
|
||||
pub(crate) segment_flags: u16,
|
||||
/// The loop filter level of each reference frame and mode.
|
||||
pub(crate) filter_level: [[u8; 2]; 4],
|
||||
pub(crate) luma_ac_quant_scale: i16,
|
||||
pub(crate) luma_dc_quant_scale: i16,
|
||||
pub(crate) chroma_ac_quant_scale: i16,
|
||||
pub(crate) chroma_dc_quant_scale: i16,
|
||||
pub(crate) va_reserved: [u32; VA_PADDING_LOW],
|
||||
}
|
||||
|
||||
/// `VASegmentParameterVP9::segment_flags.fields`.
|
||||
pub(crate) mod vp9_segment_flags {
|
||||
use super::BitField;
|
||||
pub(crate) const SEGMENT_REFERENCE_ENABLED: BitField = BitField::new(0, 1);
|
||||
pub(crate) const SEGMENT_REFERENCE: BitField = BitField::new(1, 2);
|
||||
pub(crate) const SEGMENT_REFERENCE_SKIPPED: BitField = BitField::new(3, 1);
|
||||
}
|
||||
|
||||
/// `VASliceParameterBufferVP9`: the frame's bytes, and each segment's
|
||||
/// parameters.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct VASliceParameterBufferVP9 {
|
||||
pub(crate) slice_data_size: u32,
|
||||
pub(crate) slice_data_offset: u32,
|
||||
pub(crate) slice_data_flag: u32,
|
||||
pub(crate) seg_param: [VASegmentParameterVP9; 8],
|
||||
pub(crate) va_reserved: [u32; VA_PADDING_LOW],
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core::mem::{offset_of, size_of};
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// What the C side prints, line for line.
|
||||
const LAYOUT_C: &str = include_str!("vp9_layout.c");
|
||||
|
||||
macro_rules! layout {
|
||||
($out:ident, $ty:ty, $c:literal, { $($field:ident => $cfield:literal),* $(,)? }) => {
|
||||
$out.push(format!("{} size {}", $c, size_of::<$ty>()));
|
||||
$( $out.push(format!("{}.{} {}", $c, $cfield, offset_of!($ty, $field))); )*
|
||||
};
|
||||
}
|
||||
|
||||
fn fields(out: &mut Vec<String>, union: &str, list: &[(&str, BitField)]) {
|
||||
for (name, field) in list {
|
||||
out.push(format!("{union}.{name} {:#x}", field.put(u32::MAX)));
|
||||
}
|
||||
}
|
||||
|
||||
fn rust_layout() -> Vec<String> {
|
||||
let mut out = Vec::new();
|
||||
layout!(out, VADecPictureParameterBufferVP9, "VADecPictureParameterBufferVP9", {
|
||||
frame_width => "frame_width", frame_height => "frame_height",
|
||||
reference_frames => "reference_frames", pic_fields => "pic_fields",
|
||||
filter_level => "filter_level", sharpness_level => "sharpness_level",
|
||||
log2_tile_rows => "log2_tile_rows", log2_tile_columns => "log2_tile_columns",
|
||||
frame_header_length_in_bytes => "frame_header_length_in_bytes",
|
||||
first_partition_size => "first_partition_size",
|
||||
mb_segment_tree_probs => "mb_segment_tree_probs",
|
||||
segment_pred_probs => "segment_pred_probs", profile => "profile",
|
||||
bit_depth => "bit_depth", va_reserved => "va_reserved",
|
||||
});
|
||||
layout!(out, VASegmentParameterVP9, "VASegmentParameterVP9", {
|
||||
segment_flags => "segment_flags", filter_level => "filter_level",
|
||||
luma_ac_quant_scale => "luma_ac_quant_scale",
|
||||
luma_dc_quant_scale => "luma_dc_quant_scale",
|
||||
chroma_ac_quant_scale => "chroma_ac_quant_scale",
|
||||
chroma_dc_quant_scale => "chroma_dc_quant_scale", va_reserved => "va_reserved",
|
||||
});
|
||||
layout!(out, VASliceParameterBufferVP9, "VASliceParameterBufferVP9", {
|
||||
slice_data_size => "slice_data_size", slice_data_offset => "slice_data_offset",
|
||||
slice_data_flag => "slice_data_flag", seg_param => "seg_param",
|
||||
va_reserved => "va_reserved",
|
||||
});
|
||||
use vp9_pic_fields as pf;
|
||||
fields(
|
||||
&mut out,
|
||||
"vp9.pic_fields",
|
||||
&[
|
||||
("subsampling_x", pf::SUBSAMPLING_X),
|
||||
("subsampling_y", pf::SUBSAMPLING_Y),
|
||||
("frame_type", pf::FRAME_TYPE),
|
||||
("show_frame", pf::SHOW_FRAME),
|
||||
("error_resilient_mode", pf::ERROR_RESILIENT_MODE),
|
||||
("intra_only", pf::INTRA_ONLY),
|
||||
("allow_high_precision_mv", pf::ALLOW_HIGH_PRECISION_MV),
|
||||
("mcomp_filter_type", pf::MCOMP_FILTER_TYPE),
|
||||
(
|
||||
"frame_parallel_decoding_mode",
|
||||
pf::FRAME_PARALLEL_DECODING_MODE,
|
||||
),
|
||||
("reset_frame_context", pf::RESET_FRAME_CONTEXT),
|
||||
("refresh_frame_context", pf::REFRESH_FRAME_CONTEXT),
|
||||
("frame_context_idx", pf::FRAME_CONTEXT_IDX),
|
||||
("segmentation_enabled", pf::SEGMENTATION_ENABLED),
|
||||
(
|
||||
"segmentation_temporal_update",
|
||||
pf::SEGMENTATION_TEMPORAL_UPDATE,
|
||||
),
|
||||
("segmentation_update_map", pf::SEGMENTATION_UPDATE_MAP),
|
||||
("last_ref_frame", pf::LAST_REF_FRAME),
|
||||
("last_ref_frame_sign_bias", pf::LAST_REF_FRAME_SIGN_BIAS),
|
||||
("golden_ref_frame", pf::GOLDEN_REF_FRAME),
|
||||
("golden_ref_frame_sign_bias", pf::GOLDEN_REF_FRAME_SIGN_BIAS),
|
||||
("alt_ref_frame", pf::ALT_REF_FRAME),
|
||||
("alt_ref_frame_sign_bias", pf::ALT_REF_FRAME_SIGN_BIAS),
|
||||
("lossless_flag", pf::LOSSLESS_FLAG),
|
||||
],
|
||||
);
|
||||
use vp9_segment_flags as sf;
|
||||
fields(
|
||||
&mut out,
|
||||
"vp9.segment_flags",
|
||||
&[
|
||||
("segment_reference_enabled", sf::SEGMENT_REFERENCE_ENABLED),
|
||||
("segment_reference", sf::SEGMENT_REFERENCE),
|
||||
("segment_reference_skipped", sf::SEGMENT_REFERENCE_SKIPPED),
|
||||
],
|
||||
);
|
||||
out.push(format!("VAProfileVP9Profile0 {VAProfileVP9Profile0}"));
|
||||
out.push(format!("VAProfileVP9Profile2 {VAProfileVP9Profile2}"));
|
||||
out
|
||||
}
|
||||
|
||||
/// Compiles `vp9_layout.c` against the installed libva headers and
|
||||
/// compares its output with this module's layout. `CC` picks the
|
||||
/// compiler (`cc` by default).
|
||||
#[test]
|
||||
#[ignore = "needs libva's headers and a C compiler: run on the test host"]
|
||||
fn vp9_layouts_match_libva_headers() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let dir = std::env::temp_dir().join(format!("rvgv-va-vp9-layout-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let binary = dir.join("layout");
|
||||
let cc = std::env::var("CC").unwrap_or_else(|_| "cc".into());
|
||||
let mut compile = Command::new(cc)
|
||||
.args(["-Wno-overflow", "-x", "c", "-", "-o"])
|
||||
.arg(&binary)
|
||||
.stdin(Stdio::piped())
|
||||
.spawn()?;
|
||||
compile
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or("no stdin")?
|
||||
.write_all(LAYOUT_C.as_bytes())?;
|
||||
if !compile.wait()?.success() {
|
||||
return Err("the C compiler failed".into());
|
||||
}
|
||||
let output = Command::new(&binary).output()?;
|
||||
std::fs::remove_dir_all(&dir)?;
|
||||
let c_lines: Vec<String> = String::from_utf8(output.stdout)?
|
||||
.lines()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
assert_eq!(rust_layout(), c_lines);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* The layout of the libva VP9 decode structs ffi/vp9.rs declares, from the
|
||||
* installed headers: sizeof and offsetof of each, then the mask of each
|
||||
* bit-field, then the value of each constant. vp9.rs's
|
||||
* vp9_layouts_match_libva_headers test compiles this and compares its
|
||||
* output with Rust's, line for line.
|
||||
*/
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <va/va.h>
|
||||
#include <va/va_dec_vp9.h>
|
||||
|
||||
#define S(T) printf(#T " size %zu\n", sizeof(T))
|
||||
#define F(T, f) printf(#T "." #f " %zu\n", offsetof(T, f))
|
||||
#define C(c) printf(#c " %lld\n", (long long)(c))
|
||||
#define BITS(T, member, inner, label, f) \
|
||||
do { \
|
||||
T p; \
|
||||
memset(&p, 0, sizeof p); \
|
||||
p.member.inner.f = ~0u; \
|
||||
printf(label "." #f " %#x\n", (unsigned)p.member.value); \
|
||||
} while (0)
|
||||
#define PIC(f) BITS(VADecPictureParameterBufferVP9, pic_fields, bits, "vp9.pic_fields", f)
|
||||
#define SEG(f) BITS(VASegmentParameterVP9, segment_flags, fields, "vp9.segment_flags", f)
|
||||
|
||||
int main(void)
|
||||
{
|
||||
S(VADecPictureParameterBufferVP9);
|
||||
F(VADecPictureParameterBufferVP9, frame_width);
|
||||
F(VADecPictureParameterBufferVP9, frame_height);
|
||||
F(VADecPictureParameterBufferVP9, reference_frames);
|
||||
F(VADecPictureParameterBufferVP9, pic_fields);
|
||||
F(VADecPictureParameterBufferVP9, filter_level);
|
||||
F(VADecPictureParameterBufferVP9, sharpness_level);
|
||||
F(VADecPictureParameterBufferVP9, log2_tile_rows);
|
||||
F(VADecPictureParameterBufferVP9, log2_tile_columns);
|
||||
F(VADecPictureParameterBufferVP9, frame_header_length_in_bytes);
|
||||
F(VADecPictureParameterBufferVP9, first_partition_size);
|
||||
F(VADecPictureParameterBufferVP9, mb_segment_tree_probs);
|
||||
F(VADecPictureParameterBufferVP9, segment_pred_probs);
|
||||
F(VADecPictureParameterBufferVP9, profile);
|
||||
F(VADecPictureParameterBufferVP9, bit_depth);
|
||||
F(VADecPictureParameterBufferVP9, va_reserved);
|
||||
|
||||
S(VASegmentParameterVP9);
|
||||
F(VASegmentParameterVP9, segment_flags);
|
||||
F(VASegmentParameterVP9, filter_level);
|
||||
F(VASegmentParameterVP9, luma_ac_quant_scale);
|
||||
F(VASegmentParameterVP9, luma_dc_quant_scale);
|
||||
F(VASegmentParameterVP9, chroma_ac_quant_scale);
|
||||
F(VASegmentParameterVP9, chroma_dc_quant_scale);
|
||||
F(VASegmentParameterVP9, va_reserved);
|
||||
|
||||
S(VASliceParameterBufferVP9);
|
||||
F(VASliceParameterBufferVP9, slice_data_size);
|
||||
F(VASliceParameterBufferVP9, slice_data_offset);
|
||||
F(VASliceParameterBufferVP9, slice_data_flag);
|
||||
F(VASliceParameterBufferVP9, seg_param);
|
||||
F(VASliceParameterBufferVP9, va_reserved);
|
||||
|
||||
PIC(subsampling_x);
|
||||
PIC(subsampling_y);
|
||||
PIC(frame_type);
|
||||
PIC(show_frame);
|
||||
PIC(error_resilient_mode);
|
||||
PIC(intra_only);
|
||||
PIC(allow_high_precision_mv);
|
||||
PIC(mcomp_filter_type);
|
||||
PIC(frame_parallel_decoding_mode);
|
||||
PIC(reset_frame_context);
|
||||
PIC(refresh_frame_context);
|
||||
PIC(frame_context_idx);
|
||||
PIC(segmentation_enabled);
|
||||
PIC(segmentation_temporal_update);
|
||||
PIC(segmentation_update_map);
|
||||
PIC(last_ref_frame);
|
||||
PIC(last_ref_frame_sign_bias);
|
||||
PIC(golden_ref_frame);
|
||||
PIC(golden_ref_frame_sign_bias);
|
||||
PIC(alt_ref_frame);
|
||||
PIC(alt_ref_frame_sign_bias);
|
||||
PIC(lossless_flag);
|
||||
|
||||
SEG(segment_reference_enabled);
|
||||
SEG(segment_reference);
|
||||
SEG(segment_reference_skipped);
|
||||
|
||||
C(VAProfileVP9Profile0);
|
||||
C(VAProfileVP9Profile2);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
//! VP9 decoding on VA-API: [`crate::codec::vp9::Decoder`] over an accelerator
|
||||
//! that fills libva's VP9 buffers (va_dec_vp9.h) and decodes each frame into
|
||||
//! a pool of NV12 surfaces for profile 0, P010 ones for profile 2 at 10 bits.
|
||||
//!
|
||||
//! A frame goes to the driver whole, its uncompressed header first, as one
|
||||
//! slice (`VA_SLICE_DATA_FLAG_ALL`), with the header's fields in the picture
|
||||
//! parameters and each segment's derived quantizer scales and loop filter
|
||||
//! levels in the slice's, as ffmpeg sends them. The eight reference slots go
|
||||
//! as their surfaces, `VA_INVALID_SURFACE` for an empty one. A frame of
|
||||
//! another size or format than the last makes a new context and pool; the
|
||||
//! slots keep the surfaces of the frames before it, which the driver scales
|
||||
//! from as references.
|
||||
|
||||
use super::buffer::{Buffer, render_decode};
|
||||
use super::caps::{Context, Entrypoint, Profile};
|
||||
use super::display::{Display, Error};
|
||||
use super::ffi;
|
||||
use super::ffi::vp9::{
|
||||
VADecPictureParameterBufferVP9, VASegmentParameterVP9, VASliceParameterBufferVP9,
|
||||
vp9_pic_fields as pf, vp9_segment_flags as sf,
|
||||
};
|
||||
use super::frame::Frame;
|
||||
use super::surface::{Rect, Surface, SurfaceFormat, SurfacePool, end_context};
|
||||
use super::wait::{self, Deadline};
|
||||
use crate::codec::vp9::header::{FrameHeader, MAX_SEGMENTS};
|
||||
use crate::codec::vp9::quant::SegmentParams;
|
||||
use crate::codec::vp9::{Accelerator, Decoder, Format, FrameParams, Output};
|
||||
|
||||
/// The segment feature that names a reference frame (`SEG_LVL_REF_FRAME`).
|
||||
const SEG_LVL_REF_FRAME: usize = 2;
|
||||
/// The segment feature that skips the residual (`SEG_LVL_SKIP`).
|
||||
const SEG_LVL_SKIP: usize = 3;
|
||||
|
||||
/// A VP9 decoder on a VA display.
|
||||
///
|
||||
/// Samples are a container's: a frame, or a superframe of frames, whole.
|
||||
/// Frames come out as the stream shows them, which is decode order, at most
|
||||
/// one a sample a container holds.
|
||||
pub struct Vp9Decoder {
|
||||
inner: Decoder<VaVp9>,
|
||||
}
|
||||
|
||||
impl Vp9Decoder {
|
||||
/// The frames a caller is to hold at once, beyond those the decoder's
|
||||
/// eight slots hold: the decoder's pool makes a surface for a frame as it
|
||||
/// needs one, up to a bound past which a decode finds no free surface
|
||||
/// (`Error::OutOfSurfaces`).
|
||||
pub const SPARE_FRAMES: usize = 2;
|
||||
|
||||
/// A decoder on `display`. Each frame's profile, bit depth and size are
|
||||
/// checked against what the driver decodes as it comes.
|
||||
pub fn new(display: &Display) -> Self {
|
||||
Self {
|
||||
inner: Decoder::new(VaVp9 {
|
||||
display: display.clone_ref(),
|
||||
session: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the driver decodes none of a stream of VP9 `profile` at
|
||||
/// `bit_depth` and `width` by `height`, or `Ok` where its VLD config of
|
||||
/// the profile takes it.
|
||||
pub fn supports(
|
||||
display: &Display,
|
||||
profile: u8,
|
||||
bit_depth: u8,
|
||||
(width, height): (u32, u32),
|
||||
) -> Result<(), Error> {
|
||||
let format = Format {
|
||||
profile,
|
||||
bit_depth,
|
||||
width,
|
||||
height,
|
||||
};
|
||||
select_profile(display, &format).map(|_| ())
|
||||
}
|
||||
|
||||
/// Decodes one sample, tagged `id`, and returns the frames it shows. The
|
||||
/// decode may still be running on the GPU: a frame's readback waits for
|
||||
/// it.
|
||||
pub fn decode(&mut self, sample: &[u8], id: u64) -> Result<Vec<Frame>, Error> {
|
||||
// One deadline for the call's driver calls and its frames' read
|
||||
// backs (`super::wait`).
|
||||
let deadline = Deadline::default();
|
||||
let outputs = wait::by(&deadline, || self.inner.decode(sample, id))?;
|
||||
Ok(outputs
|
||||
.into_iter()
|
||||
.map(|output| frame_from_output(output, &deadline))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Forgets every slot, as for a seek: the next frame decodes only if it
|
||||
/// is a key frame.
|
||||
pub fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
|
||||
/// The VA profile the decoder runs, once it has decoded a frame.
|
||||
pub fn profile(&self) -> Option<Profile> {
|
||||
self.inner.accelerator().session.as_ref().map(|s| s.profile)
|
||||
}
|
||||
}
|
||||
|
||||
// Decoders move between threads: libva is thread-safe (va.h,
|
||||
// "Multithreading Guide"), and each decoder is used by one thread at a
|
||||
// time through `&mut`.
|
||||
const _: fn() = || {
|
||||
fn send<T: Send>() {}
|
||||
send::<Vp9Decoder>();
|
||||
};
|
||||
|
||||
/// The frame VA-API decoded for one of the decoder's outputs.
|
||||
fn frame_from_output(output: Output<Surface>, deadline: &Deadline) -> Frame {
|
||||
let (width, height) = output.size;
|
||||
Frame {
|
||||
surface: output.picture,
|
||||
id: output.id,
|
||||
poc: 0,
|
||||
idr: output.key_frame,
|
||||
reference: output.reference,
|
||||
rect: Rect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width,
|
||||
height,
|
||||
},
|
||||
coded_size: output.size,
|
||||
full_range: output.full_range,
|
||||
deadline: deadline.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The VA-API half of the decoder.
|
||||
struct VaVp9 {
|
||||
display: Display,
|
||||
session: Option<Session>,
|
||||
}
|
||||
|
||||
/// What one format's frames are decoded with.
|
||||
struct Session {
|
||||
profile: Profile,
|
||||
/// Destroyed first, before the surfaces it renders into: it holds its
|
||||
/// config.
|
||||
context: Option<Context>,
|
||||
pool: SurfacePool,
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
// The context goes first. The pool may outlive it: the slots and
|
||||
// the frames the caller holds keep their surfaces.
|
||||
end_context(self.context.take(), [&self.pool]);
|
||||
}
|
||||
}
|
||||
|
||||
impl VaVp9 {
|
||||
fn session(&self) -> Result<&Session, Error> {
|
||||
self.session
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::Unsupported("decoding before a format is configured".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The VA profile and surface format of `format`'s frames: profile 0 in
|
||||
/// NV12, profile 2 at 10 bits in P010. The codec's decoder has refused the
|
||||
/// rest.
|
||||
fn profile_for(format: &Format) -> Result<(Profile, SurfaceFormat), Error> {
|
||||
match (format.profile, format.bit_depth) {
|
||||
(0, 8) => Ok((Profile::VP9_PROFILE0, SurfaceFormat::Nv12)),
|
||||
(2, 10) => Ok((Profile::VP9_PROFILE2, SurfaceFormat::P010)),
|
||||
(profile, depth) => Err(Error::Unsupported(format!(
|
||||
"VP9 profile {profile} at {depth} bits: VA-API decodes profile 0, and 2 at 10 bits, \
|
||||
here"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The VA profile, where the driver decodes `format`'s frames at their size.
|
||||
fn select_profile(display: &Display, format: &Format) -> Result<Profile, Error> {
|
||||
let (profile, surfaces) = profile_for(format)?;
|
||||
let name = profile.name().unwrap_or("VP9");
|
||||
if !display.supports(profile, Entrypoint::VLD) {
|
||||
return Err(Error::Unsupported(format!(
|
||||
"{name}: the driver has no decoder"
|
||||
)));
|
||||
}
|
||||
let limits = display.config_attributes(
|
||||
profile,
|
||||
Entrypoint::VLD,
|
||||
&[
|
||||
ffi::VAConfigAttribRTFormat,
|
||||
ffi::VAConfigAttribMaxPictureWidth,
|
||||
ffi::VAConfigAttribMaxPictureHeight,
|
||||
],
|
||||
)?;
|
||||
if limits[0].is_some_and(|f| f & surfaces.rt_format() == 0) {
|
||||
return Err(Error::Unsupported(format!(
|
||||
"{name}: no {} render targets",
|
||||
surfaces.name()
|
||||
)));
|
||||
}
|
||||
let (width, height) = (format.width, format.height);
|
||||
if limits[1].is_some_and(|max| width > max) || limits[2].is_some_and(|max| height > max) {
|
||||
return Err(Error::Unsupported(format!(
|
||||
"{name} at {width}x{height}: the driver's maximum is {}x{}",
|
||||
limits[1].unwrap_or(0),
|
||||
limits[2].unwrap_or(0)
|
||||
)));
|
||||
}
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
impl Accelerator for VaVp9 {
|
||||
type Picture = Surface;
|
||||
type Error = Error;
|
||||
|
||||
fn configure(&mut self, format: &Format) -> Result<(), Error> {
|
||||
self.session = None;
|
||||
let profile = select_profile(&self.display, format)?;
|
||||
let (_, surfaces) = profile_for(format)?;
|
||||
let mut attribs = [ffi::VAConfigAttrib {
|
||||
type_: ffi::VAConfigAttribRTFormat,
|
||||
value: surfaces.rt_format(),
|
||||
}];
|
||||
// Eight slots and the frame being decoded.
|
||||
let references = 8;
|
||||
let (context, pool) = Context::new_decoder(
|
||||
&self.display,
|
||||
profile,
|
||||
&mut attribs,
|
||||
surfaces,
|
||||
(format.width, format.height),
|
||||
references,
|
||||
)?;
|
||||
self.session = Some(Session {
|
||||
profile,
|
||||
context: Some(context),
|
||||
pool,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn new_picture(&mut self) -> Result<Surface, Error> {
|
||||
self.session()?.pool.get()
|
||||
}
|
||||
|
||||
fn decode_frame(
|
||||
&mut self,
|
||||
picture: &Surface,
|
||||
params: &FrameParams<'_, Surface>,
|
||||
) -> Result<(), Error> {
|
||||
let session = self.session()?;
|
||||
let decoding = session
|
||||
.context
|
||||
.as_ref()
|
||||
.ok_or_else(|| Error::Unsupported("decoding without a context".into()))?;
|
||||
let context = decoding.id;
|
||||
let display = &self.display;
|
||||
let picture_parameters = picture_parameters(params)?;
|
||||
let slice_parameters = slice_parameters(params)?;
|
||||
let picture_buffer = Buffer::with_value(
|
||||
display,
|
||||
context,
|
||||
ffi::VAPictureParameterBufferType,
|
||||
&picture_parameters,
|
||||
)?;
|
||||
let slice_buffer = Buffer::with_value(
|
||||
display,
|
||||
context,
|
||||
ffi::VASliceParameterBufferType,
|
||||
&slice_parameters,
|
||||
)?;
|
||||
let data = Buffer::with_bytes(display, context, ffi::VASliceDataBufferType, params.frame)?;
|
||||
let groups: [&[&Buffer<'_>]; 2] = [&[&picture_buffer], &[&slice_buffer, &data]];
|
||||
// A first frame past its deadline may still be submitted: the pool
|
||||
// is kept until the GPU is done with it.
|
||||
picture.stalled_if(render_decode(display, decoding, picture.id(), &groups))
|
||||
}
|
||||
}
|
||||
|
||||
/// A value the uncompressed header bounds, narrowed.
|
||||
fn narrow_u8(value: u32, what: &'static str) -> Result<u8, Error> {
|
||||
u8::try_from(value).map_err(|_| Error::Unsupported(format!("VP9 {what} of {value}")))
|
||||
}
|
||||
|
||||
/// `VADecPictureParameterBufferVP9` of the frame, as ffmpeg's VA-API VP9
|
||||
/// decoder fills it.
|
||||
fn picture_parameters(
|
||||
params: &FrameParams<'_, Surface>,
|
||||
) -> Result<VADecPictureParameterBufferVP9, Error> {
|
||||
let h: &FrameHeader = params.header;
|
||||
let flag = u32::from;
|
||||
let seg = &h.segmentation;
|
||||
let [last, golden, alt] = h.ref_frame_idx;
|
||||
let [last_bias, golden_bias, alt_bias] = h.ref_frame_sign_bias;
|
||||
let pic_fields = pf::SUBSAMPLING_X.put(flag(h.color.subsampling_x))
|
||||
| pf::SUBSAMPLING_Y.put(flag(h.color.subsampling_y))
|
||||
// `frame_type`: 0 a key frame, 1 another.
|
||||
| pf::FRAME_TYPE.put(flag(!h.key_frame))
|
||||
| pf::SHOW_FRAME.put(flag(h.show_frame))
|
||||
| pf::ERROR_RESILIENT_MODE.put(flag(h.error_resilient_mode))
|
||||
| pf::INTRA_ONLY.put(flag(h.intra_only))
|
||||
| pf::ALLOW_HIGH_PRECISION_MV.put(flag(h.allow_high_precision_mv))
|
||||
| pf::MCOMP_FILTER_TYPE.put(u32::from(h.interp_filter))
|
||||
| pf::FRAME_PARALLEL_DECODING_MODE.put(flag(h.frame_parallel_decoding_mode))
|
||||
| pf::RESET_FRAME_CONTEXT.put(u32::from(h.reset_frame_context))
|
||||
| pf::REFRESH_FRAME_CONTEXT.put(flag(h.refresh_frame_context))
|
||||
| pf::FRAME_CONTEXT_IDX.put(u32::from(h.frame_context_idx))
|
||||
| pf::SEGMENTATION_ENABLED.put(flag(seg.enabled))
|
||||
| pf::SEGMENTATION_TEMPORAL_UPDATE.put(flag(seg.temporal_update))
|
||||
| pf::SEGMENTATION_UPDATE_MAP.put(flag(seg.update_map))
|
||||
| pf::LAST_REF_FRAME.put(u32::from(last))
|
||||
| pf::LAST_REF_FRAME_SIGN_BIAS.put(flag(last_bias))
|
||||
| pf::GOLDEN_REF_FRAME.put(u32::from(golden))
|
||||
| pf::GOLDEN_REF_FRAME_SIGN_BIAS.put(flag(golden_bias))
|
||||
| pf::ALT_REF_FRAME.put(u32::from(alt))
|
||||
| pf::ALT_REF_FRAME_SIGN_BIAS.put(flag(alt_bias))
|
||||
| pf::LOSSLESS_FLAG.put(flag(h.quantization.lossless()));
|
||||
let reference_frames = params.references.each_ref().map(|reference| {
|
||||
reference
|
||||
.as_ref()
|
||||
.map_or(ffi::VA_INVALID_SURFACE, |r| r.picture.id())
|
||||
});
|
||||
let narrow_u16 = |value: u32, what: &'static str| {
|
||||
u16::try_from(value).map_err(|_| Error::Unsupported(format!("VP9 {what} of {value}")))
|
||||
};
|
||||
Ok(VADecPictureParameterBufferVP9 {
|
||||
frame_width: narrow_u16(h.width, "a frame width")?,
|
||||
frame_height: narrow_u16(h.height, "a frame height")?,
|
||||
reference_frames,
|
||||
pic_fields,
|
||||
filter_level: h.loop_filter.level,
|
||||
sharpness_level: h.loop_filter.sharpness,
|
||||
log2_tile_rows: h.tile_rows_log2,
|
||||
log2_tile_columns: h.tile_cols_log2,
|
||||
frame_header_length_in_bytes: h.uncompressed_header_size,
|
||||
first_partition_size: h.header_size_in_bytes,
|
||||
mb_segment_tree_probs: seg.tree_probs,
|
||||
// ffmpeg sends 255 where the map's prediction is not temporal.
|
||||
segment_pred_probs: if seg.temporal_update {
|
||||
seg.pred_probs
|
||||
} else {
|
||||
[255; 3]
|
||||
},
|
||||
profile: h.profile,
|
||||
bit_depth: narrow_u8(u32::from(h.color.bit_depth), "bit depth")?,
|
||||
va_reserved: [0; ffi::VA_PADDING_MEDIUM],
|
||||
})
|
||||
}
|
||||
|
||||
/// One segment's `VASegmentParameterVP9`: its reference and skip features,
|
||||
/// where segmentation is on, and its derived values.
|
||||
fn segment_parameters(
|
||||
header: &FrameHeader,
|
||||
segment: usize,
|
||||
derived: &SegmentParams,
|
||||
) -> VASegmentParameterVP9 {
|
||||
let seg = &header.segmentation;
|
||||
let enabled = |level: usize| {
|
||||
seg.enabled
|
||||
&& seg
|
||||
.feature_enabled
|
||||
.get(segment)
|
||||
.and_then(|features| features.get(level))
|
||||
.is_some_and(|&on| on)
|
||||
};
|
||||
let reference = seg
|
||||
.feature_data
|
||||
.get(segment)
|
||||
.and_then(|data| data.get(SEG_LVL_REF_FRAME))
|
||||
.and_then(|&value| u32::try_from(value).ok())
|
||||
.unwrap_or(0);
|
||||
let flags = sf::SEGMENT_REFERENCE_ENABLED.put(u32::from(enabled(SEG_LVL_REF_FRAME)))
|
||||
| sf::SEGMENT_REFERENCE.put(reference)
|
||||
| sf::SEGMENT_REFERENCE_SKIPPED.put(u32::from(enabled(SEG_LVL_SKIP)));
|
||||
VASegmentParameterVP9 {
|
||||
// The flags' four bits.
|
||||
segment_flags: u16::try_from(flags).unwrap_or(0),
|
||||
filter_level: derived.filter_level,
|
||||
luma_ac_quant_scale: derived.luma_ac,
|
||||
luma_dc_quant_scale: derived.luma_dc,
|
||||
chroma_ac_quant_scale: derived.chroma_ac,
|
||||
chroma_dc_quant_scale: derived.chroma_dc,
|
||||
va_reserved: [0; ffi::VA_PADDING_LOW],
|
||||
}
|
||||
}
|
||||
|
||||
/// `VASliceParameterBufferVP9` of the frame: all of it one slice, and each
|
||||
/// segment's parameters.
|
||||
fn slice_parameters(params: &FrameParams<'_, Surface>) -> Result<VASliceParameterBufferVP9, Error> {
|
||||
let size = u32::try_from(params.frame.len())
|
||||
.map_err(|_| Error::Unsupported("a VP9 frame past 4 GiB".into()))?;
|
||||
let mut seg_param = [VASegmentParameterVP9::default(); MAX_SEGMENTS];
|
||||
for (segment, (out, derived)) in seg_param.iter_mut().zip(params.segments).enumerate() {
|
||||
*out = segment_parameters(params.header, segment, derived);
|
||||
}
|
||||
Ok(VASliceParameterBufferVP9 {
|
||||
slice_data_size: size,
|
||||
slice_data_offset: 0,
|
||||
slice_data_flag: ffi::VA_SLICE_DATA_FLAG_ALL,
|
||||
seg_param,
|
||||
va_reserved: [0; ffi::VA_PADDING_LOW],
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,132 @@
|
||||
//! The VP9 decoder's parameters, and its decode of libvpx's streams on the
|
||||
//! GPU: on the display `super::super::teardown`'s `display` opens, the render
|
||||
//! node `RVG_VAAPI_NODE` names. Each frame read back must hash as libvpx's
|
||||
//! own decode of it does (`crate::codec::vp9::tests`'s MD5s, over NV12 and
|
||||
//! P010 planes).
|
||||
|
||||
use reims_vgpu_video_conformance::md5::Md5;
|
||||
|
||||
use super::super::teardown::display;
|
||||
use super::*;
|
||||
use crate::codec::vp9::header::{self, State};
|
||||
use crate::codec::vp9::quant;
|
||||
use crate::codec::vp9::tests::{
|
||||
FrameSpec, PROFILE_0_IVF, PROFILE_0_MD5, PROFILE_2_IVF, PROFILE_2_MD5, SegmentationSpec,
|
||||
ivf_frames,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn profile_0_decodes_into_nv12_and_profile_2_into_p010() -> Result<(), Error> {
|
||||
let format = |profile, bit_depth| Format {
|
||||
profile,
|
||||
bit_depth,
|
||||
width: 64,
|
||||
height: 64,
|
||||
};
|
||||
assert_eq!(
|
||||
profile_for(&format(0, 8))?,
|
||||
(Profile::VP9_PROFILE0, SurfaceFormat::Nv12)
|
||||
);
|
||||
assert_eq!(
|
||||
profile_for(&format(2, 10))?,
|
||||
(Profile::VP9_PROFILE2, SurfaceFormat::P010)
|
||||
);
|
||||
for (profile, depth) in [(1, 8), (2, 12), (3, 10)] {
|
||||
assert!(matches!(
|
||||
profile_for(&format(profile, depth)),
|
||||
Err(Error::Unsupported(_))
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_carries_its_reference_and_skip_features_where_segmentation_is_on() {
|
||||
let mut features = [[None; 4]; 8];
|
||||
features[5] = [None, None, Some(2), Some(0)];
|
||||
let mut spec = FrameSpec::key(64, 64);
|
||||
spec.segmentation = Some(SegmentationSpec {
|
||||
update_map: None,
|
||||
update_data: Some((true, features)),
|
||||
});
|
||||
let frame = spec.write();
|
||||
let (header, _) = header::parse(&frame, &State::default(), &[None; 8]).unwrap();
|
||||
let derived = quant::segment_params(&header);
|
||||
let five = segment_parameters(&header, 5, &derived[5]);
|
||||
// Enabled (bit 0), the golden frame (2, bits 1 and 2), skipped (bit 3).
|
||||
assert_eq!(five.segment_flags, 0b1101);
|
||||
assert_eq!(five.luma_ac_quant_scale, derived[5].luma_ac);
|
||||
assert_eq!(five.filter_level, derived[5].filter_level);
|
||||
assert_eq!(segment_parameters(&header, 0, &derived[0]).segment_flags, 0);
|
||||
// With segmentation off, no segment has a feature.
|
||||
spec.segmentation = None;
|
||||
let frame = spec.write();
|
||||
let (off, _) = header::parse(&frame, &State::default(), &[None; 8]).unwrap();
|
||||
assert_eq!(segment_parameters(&off, 5, &derived[5]).segment_flags, 0);
|
||||
}
|
||||
|
||||
/// Decodes `file` and hashes each frame read back, NV12 or P010 by its
|
||||
/// depth.
|
||||
fn frame_md5s(display: &Display, file: &[u8]) -> Vec<String> {
|
||||
let mut decoder = Vp9Decoder::new(display);
|
||||
let mut hashes = Vec::new();
|
||||
for (id, sample) in (0u64..).zip(ivf_frames(file)) {
|
||||
let frames = decoder
|
||||
.decode(sample, id)
|
||||
.unwrap_or_else(|error| panic!("sample {id}: {error}"));
|
||||
assert_eq!(frames.len(), 1, "sample {id}'s frames");
|
||||
for frame in frames {
|
||||
let (width, height) = (frame.width() as usize, frame.height() as usize);
|
||||
let bytes = if frame.bit_depth() == 8 { 1 } else { 2 };
|
||||
let mut y = vec![0u8; width * height * bytes];
|
||||
let mut uv = vec![0u8; width * height.div_ceil(2) * bytes];
|
||||
let back = frame.read_back().expect("a read back");
|
||||
if bytes == 1 {
|
||||
back.copy_nv12_to(&mut y, width, &mut uv, width)
|
||||
} else {
|
||||
back.copy_p010_to(&mut y, width * 2, &mut uv, width * 2)
|
||||
}
|
||||
.expect("a copy");
|
||||
let mut md5 = Md5::new();
|
||||
md5.update(&y);
|
||||
md5.update(&uv);
|
||||
hashes.push(md5.hex());
|
||||
}
|
||||
}
|
||||
hashes
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs a VA-API driver that decodes VP9 profiles 0 and 2: run on a VA-API host"]
|
||||
fn libvpx_streams_decode_to_libvpx_frames() {
|
||||
let display = display();
|
||||
for (name, file, md5s) in [
|
||||
("profile 0", PROFILE_0_IVF, PROFILE_0_MD5),
|
||||
("profile 2", PROFILE_2_IVF, PROFILE_2_MD5),
|
||||
] {
|
||||
let got = frame_md5s(&display, file);
|
||||
let want: Vec<&str> = md5s.lines().collect();
|
||||
assert_eq!(got.len(), want.len(), "{name}: frames");
|
||||
for (frame, (got, want)) in got.iter().zip(&want).enumerate() {
|
||||
assert_eq!(got, want, "{name}: frame {frame}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "needs a VA-API driver that decodes VP9 profile 0: run on a VA-API host"]
|
||||
fn a_stream_that_starts_after_its_key_frame_decodes_from_the_next_one() {
|
||||
let display = display();
|
||||
let samples = ivf_frames(PROFILE_0_IVF);
|
||||
let mut decoder = Vp9Decoder::new(&display);
|
||||
let error = decoder
|
||||
.decode(samples[1], 1)
|
||||
.err()
|
||||
.expect("an inter frame with no reference");
|
||||
assert!(error.is_picture_error(), "{error}");
|
||||
assert_eq!(
|
||||
decoder.decode(samples[0], 0).expect("the key frame").len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(decoder.profile(), Some(Profile::VP9_PROFILE0));
|
||||
}
|
||||
@@ -11,7 +11,7 @@ crate, the traits between them, and how each is tested.
|
||||
| module | what it is |
|
||||
|---|---|
|
||||
| `core` (`src/core.rs`) | What the arms share: the threads and clock the host gives them, their locks, a guest surface's memory as a device reaches it, and their bounded waits ([core.md](core.md)) |
|
||||
| `codec` (`src/codec.rs`) | The codecs above the hardware, in plain Rust: H.264's and HEVC's syntax, order counts and DPB over an `Accelerator` that decodes the slice data, AV1's OBUs, headers, tile groups and reference slots over one that decodes the tile data, and the encoders' portable half: settings, GOP, parameter sets, slice headers and configuration records |
|
||||
| `codec` (`src/codec.rs`) | The codecs above the hardware, in plain Rust: H.264's and HEVC's syntax, order counts and DPB over an `Accelerator` that decodes the slice data, AV1's OBUs, headers, tile groups and reference slots over one that decodes the tile data, VP9's superframes, frame headers and reference slots over one that decodes a frame's compressed header and tiles, and the encoders' portable half: settings, GOP, parameter sets, slice headers and configuration records |
|
||||
| `vaapi` (`src/vaapi.rs`, Linux and Windows) | VA-API through libva, loaded at run time: the decoders and encoders on the codec module, the import check and zero copy ([vaapi.md](vaapi.md)) |
|
||||
| `nvidia` (`src/nvidia.rs`, Linux) | NVDEC and NVENC over the CUDA driver API, loaded at run time: the decoder of whole access units and the encoder ([nvidia.md](nvidia.md)) |
|
||||
| `paravirt` (`src/paravirt.rs`) | VideoToolbox's paravirtual protocol, the host's side: the `vtpv` messages an arm64 guest's VideoToolbox sends through the device's `VT_MESSAGE`, the decoder list and capabilities answered from the arm's decoders, the decoder sessions, each on a thread of its own over a backend that lands its pictures in the buffers the guest lends, and the encoder sessions, over a backend that encodes the source frames the guest lends (on VA-API, written by the GPU from a buffer over their pages into an input of the encoder's, memory of the runtime device's that the encoder's display imports, on NVENC into memory CUDA imported, which NVENC registers as input, else read through the host's view of the pages and uploaded), whose samples the session emits ([design.md](../graphics-kext/design.md), "Decided", 17) |
|
||||
@@ -106,5 +106,10 @@ decode, MD5 by MD5, and the streams the decoder must refuse refused ([vaapi.md](
|
||||
ignored hardware tests ([nvidia.md](nvidia.md)).
|
||||
|
||||
x264, x265, kvazaar and ffmpeg are test oracles alone: they write the test streams and the
|
||||
reference MD5s under `build/`, and nothing they write is committed. Each script runs in a potluck
|
||||
reference MD5s under `build/`, and nothing they write is committed. VP9 has no such suite: the
|
||||
codec module's VP9 tests carry two streams of their own, committed (`src/codec/vp9/tests`:
|
||||
ffmpeg's `testsrc2` encoded by libvpx at 640x360, profile 0 and profile 2, 60 and 56 KB), with
|
||||
vpxdec's MD5 of each frame, which ffmpeg's own VP9 decoder matched frame for frame; each arm's
|
||||
ignored VP9 tests decode them against those MD5s ([vaapi.md](vaapi.md), "The VP9 decoder";
|
||||
[nvidia.md](nvidia.md), "Tests"). Each script runs in a potluck
|
||||
job that holds the render node's GPU (`--gpu`).
|
||||
@@ -96,6 +96,12 @@ Everything known to be wrong, untested or put off in the reims-graphics device's
|
||||
- **Why it waits:** decoding a reference into its cache would have the decoder read memory that rt acquired for the device's GPU work. Vulkan leaves an acquired resource's contents undefined to other queue families, and lets the implementation write a resource it acquired even in an apparently read-only operation (Vulkan 7.7.6), so a decoder reading one is undocumented. The documented form releases the surface to the external queue family before each decode that names it as a reference, and acquires it again after (`external_writes_done`, `crates/reims-vgpu-vulkan/src/rt_platform/surface.rs`). It would tie every such decode to the completion of a submission of rt's. rt's surface makes, each of which waits for one, took 1.3 to 2.5 ms, 5.0 to 6.0 ms and 27 to 58 ms at the 4K start of three such boots (**measured**, the same GPU and file, 2026-11-19).
|
||||
- **Fix:** take the copy off the frame's chain. A reference lands at its decode's completion, with its copy running behind it, and a read of its output waits for the copy and its acquire: a commit that names the output's textures or buffer, and a guest lock. The next decode never waits for the copy, since its references are the decoder's own surfaces.
|
||||
|
||||
### B96. On NVDEC, a VP9 frame of another size than the frames it predicts from does not decode
|
||||
|
||||
- **What:** VP9 lets an inter frame change the stream's size and predict from frames of the old size, scaled (8.5.2.3), as senders that adapt their resolution do. The NVDEC accelerator makes a decoder for each run of frames of one size, and NVDEC names a frame's references by their surfaces in its own decoder, so such a frame's references lie in the decoder before. It is refused as a picture's error, and so is each frame after it that predicts from them, until an intra frame fills the slots (`src/nvidia/nvdec/vp9.rs`); the guest's VideoToolbox gets those frames as bad data. VA-API's VP9 decoder hands the driver the old context's surfaces as references, which no stream of ours checks either.
|
||||
- **Why it waits:** none of our streams resizes, and no run has shown one.
|
||||
- **Fix:** one decoder at the largest size the stream may reach, each frame decoded at its own size, checked with a stream that resizes on each arm.
|
||||
|
||||
## Upstream bugs
|
||||
|
||||
Bugs in drivers, libraries and tools that our code or our checks work around.
|
||||
|
||||
+25
-2
@@ -16,9 +16,9 @@ driver 13.4, on CachyOS) unless they say otherwise.
|
||||
|---|---|
|
||||
| Loading the driver's libraries, and the function tables | `src/nvidia/dl.rs` |
|
||||
| The CUDA driver API: a GPU, its primary context, copies | `src/nvidia/cuda.rs`, `src/nvidia/cuda/ffi.rs` |
|
||||
| NVDEC's binding: caps, decoder, pictures, mapping, status, reconfiguration | `src/nvidia/nvdec.rs`, `src/nvidia/nvdec/ffi.rs` |
|
||||
| NVDEC's binding: caps, decoder, pictures, mapping, status, reconfiguration | `src/nvidia/nvdec.rs`, `src/nvidia/nvdec/ffi.rs`, `src/nvidia/nvdec/ffi/vp9.rs` |
|
||||
| An NVDEC decoder and its pictures: surfaces, stand-ins, the copy out | `src/nvidia/nvdec/decoder.rs` |
|
||||
| The codec module's accelerators on NVDEC, one a codec | `src/nvidia/nvdec/h264.rs`, `hevc.rs`, and AV1's, for VideoToolbox's decoders alone ([devices.md](devices.md), "AV1 on arm64 guests"), `av1.rs` with its binding `src/nvidia/nvdec/ffi/av1.rs` |
|
||||
| The codec module's accelerators on NVDEC, one a codec | `src/nvidia/nvdec/h264.rs`, `hevc.rs`, and AV1's, for VideoToolbox's decoders alone ([devices.md](devices.md), "AV1 on arm64 guests"), `av1.rs` with its binding `src/nvidia/nvdec/ffi/av1.rs`, and VP9's, likewise, `vp9.rs` |
|
||||
| The decoder of whole Annex B access units, which the reims-graphics device's video drives | `src/nvidia/annex_b.rs` |
|
||||
| The failures NVDEC reports, which fail the pictures after them | `src/nvidia/decode.rs` |
|
||||
| Zero copy: guest memory registered with CUDA ("Zero copy") | `src/nvidia/zero_copy.rs` |
|
||||
@@ -232,6 +232,17 @@ the model.
|
||||
it. VideoToolbox's paravirtual decoders write it so into a scratch of the
|
||||
runtime device's, whose kernel then writes the guest's surface's two
|
||||
planes (reims-vgpu's `graphics::nvidia` and `graphics::gather`).
|
||||
- **VP9**, for VideoToolbox's paravirtual decoders alone (`src/nvidia/nvdec/vp9.rs`):
|
||||
`CUVIDVP9PICPARAMS` from the codec module's uncompressed header and slots, as ffmpeg's
|
||||
`nvdec_vp9.c` fills it: the last, golden and altref frames by surface index (255 in an intra
|
||||
frame), their slots in `activeRefIdx` and their sign biases from `refFrameSignBias[1]`, the
|
||||
filter in libvpx's numbering, the loop filter's deltas as `int`s in its `unsigned int`s, each
|
||||
segment's features as coded with the skip feature's data 0, and `frameTagSize` and
|
||||
`offsetToDctParts` the two headers' sizes. The frame goes whole, where it lies in the sample,
|
||||
as one slice at its start; NVDEC reads its compressed header and tiles. Profile 0 decodes into
|
||||
NV12 and profile 2 at 10 bits into P016, on a decoder made at the frame's size
|
||||
(`cudaVideoCodec_VP9`, 10); the caps' entry lists each profile where NVDEC answers VP9 at its
|
||||
depth.
|
||||
- **HEVC.** The references by surface index with their order counts and
|
||||
long-term flags; `RefPicSetStCurrBefore`, `StCurrAfter` and `LtCurr` as
|
||||
indices into them, in the order 8.3.2 derives them, which the codec
|
||||
@@ -312,6 +323,13 @@ DPB names it follows NVIDIA's parser, measured on 2026-10-24:
|
||||
- A stream past NVDEC's sizes, as unsupported, or under them, as too small
|
||||
(`Error::TooSmall`). The device's caps give the guest NVDEC's own sizes
|
||||
([bugs.md](bugs.md), D14).
|
||||
- A VP9 frame whose references lie in another decoder's surfaces, as a
|
||||
picture's error: a decoder is made for each run of frames of one size,
|
||||
and NVDEC names references by their surfaces, so a frame of another
|
||||
size than the frames it predicts from (a resize between key frames,
|
||||
which VP9 allows) does not decode, nor do the frames after it until an
|
||||
intra frame fills the slots ([bugs.md](bugs.md), B96). VP9's profiles 1
|
||||
and 3 and 12 bits, as unsupported, before NVDEC sees a frame.
|
||||
- An HEVC picture with more than 8 pictures in one of its current
|
||||
reference sets, as unsupported: `CUVIDHEVCPICPARAMS` holds 8 a set
|
||||
(`current_set`, `src/nvidia/nvdec/hevc.rs`, "NVDEC takes 8"). The caps answer 8 current references
|
||||
@@ -425,6 +443,11 @@ unmapped, freed or destroyed until it has.
|
||||
- `access_units_decode_in_place_and_land_by_the_gpu_as_they_read_back`
|
||||
(`src/nvidia/annex_b/tests.rs`): whole access units decoded in place, each
|
||||
picture written by the GPU equal to its read back;
|
||||
- `libvpx_streams_decode_to_libvpx_frames` and
|
||||
`a_stream_that_starts_after_its_key_frame_decodes_from_the_key_frame`
|
||||
(`src/nvidia/annex_b/vp9_tests.rs`): the codec module's two libvpx
|
||||
streams, every frame equal to vpxdec's MD5, each frame sent in place,
|
||||
the hidden ones too (an RTX 3090, potluck job m3-max-77353, 2026-11-27);
|
||||
- `what_each_lock_returns` and
|
||||
`a_lock_past_its_deadline_stalls_the_session_until_nvenc_is_done`
|
||||
(`src/nvidia/nvenc/encoder.rs`): NVENC's locks ([bugs.md](bugs.md), U19).
|
||||
|
||||
@@ -1273,6 +1273,60 @@ the driver's answer elsewhere. `HevcDecoder::new` checks the `hvcC` record's fir
|
||||
profile and its largest size, so that a session the driver cannot serve
|
||||
fails when it is made.
|
||||
|
||||
## The VP9 decoder
|
||||
|
||||
VP9 decodes for VideoToolbox's paravirtual decoders alone: the device has no VP9 op, and its
|
||||
caps entry (codec 3) is for the arm64 guest's decoder list ([devices.md](devices.md)).
|
||||
|
||||
### Shape
|
||||
|
||||
`vp9::Decoder<A: Accelerator>` (`src/codec/vp9`) does everything above a frame's compressed
|
||||
header:
|
||||
- a sample's frames: a superframe split by its index (Annex B), each frame's size checked
|
||||
against the bytes before the index; a sample with no index is one frame;
|
||||
- each frame's uncompressed header (6.2, 7.2): its size coded or taken from the reference it
|
||||
names, the render size, the loop filter's deltas and the segmentation's features kept from
|
||||
frame to frame and set up again at an intra or error-resilient frame
|
||||
(`setup_past_independence`), the quantizer, the tiles, and the compressed header's size, which
|
||||
must lie in the frame;
|
||||
- the eight reference slots, a frame that shows a slot (`show_existing_frame`), and each
|
||||
segment's quantizer scales and filter levels (8.6.1, 8.8.1, as libvpx derives them);
|
||||
- before the accelerator: an inter frame's references in their slots, of its depth and
|
||||
subsampling, at a scale it predicts from (twice its size to a sixteenth, 8.5.2.3); a frame
|
||||
past 16384 a side (`MAX_SIDE`), which no lab driver decodes.
|
||||
|
||||
A frame that does not decode leaves the slots and the kept state as they were. The
|
||||
interpolation filter goes in libvpx's numbering (EIGHTTAP 0, EIGHTTAP_SMOOTH 1), which
|
||||
va_dec_vp9.h and NVDEC take.
|
||||
|
||||
The VA accelerator (`src/vaapi/va/vp9.rs`) sends each frame whole, its uncompressed header
|
||||
first, as one slice (`VA_SLICE_DATA_FLAG_ALL`), with a `VADecPictureParameterBufferVP9` (the
|
||||
eight slots' surfaces, `VA_INVALID_SURFACE` for an empty one, and the two headers' sizes) and a
|
||||
`VASliceParameterBufferVP9` holding each segment's reference and skip features, where
|
||||
segmentation is on, and its derived scales and filter levels, as ffmpeg's `vaapi_vp9.c` fills
|
||||
them. The map's prediction probabilities go as 255 where its update is not temporal.
|
||||
|
||||
### Surfaces and what it refuses
|
||||
|
||||
- Profile 0 decodes into NV12 (`VAProfileVP9Profile0`), profile 2 at 10 bits into P010
|
||||
(`VAProfileVP9Profile2`, `VA_RT_FORMAT_YUV420_10`), where the driver's VLD config lists the
|
||||
format and the frame's size (`Vp9Decoder::supports`, which answers the guest's stream at its
|
||||
session's start).
|
||||
- A context is made for each run of frames of one format and size; a frame's references stay
|
||||
the surfaces of the frames its slots hold, of whichever context.
|
||||
- Refused with `Error::Vp9Bitstream(vp9::Error::Unsupported(..))`, before anything reaches the
|
||||
driver: profiles 1 and 3 (4:4:4, 4:2:2 and 4:4:0) and 12 bits. A frame that predicts from an
|
||||
empty slot, as a stream started after its key frame does, is a picture's error, until a key
|
||||
frame fills the slots.
|
||||
- Malformed superframe indexes and headers are refused as bad data, with nothing taken from a
|
||||
field before it is checked against the bytes (the codec module's fuzz targets `vp9-streams`
|
||||
and `vp9-samples`).
|
||||
|
||||
The tree's two libvpx streams (`src/codec/vp9/tests`: 640x360, profile 0 and profile 2, three
|
||||
superframes each with a hidden altref frame) decode frame by frame equal to vpxdec's MD5s
|
||||
(the ignored `vaapi::va::vp9` tests): on the RX 7900 XTX's radeonsi (potluck job m3-max-77352)
|
||||
and the Iris Xe's iHD (potluck job m3-max-77387), 2026-11-27.
|
||||
|
||||
## The encoders
|
||||
|
||||
H.264 (Constrained Baseline, Main, High) and HEVC (Main, Main 10) on
|
||||
|
||||
Reference in new issue
Block a user