use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Arc;
use anyhow::{anyhow, bail, Context as _};
use crate::codec::h264::dpb::{Dpb, DpbEntry, DpbPicRefList, MmcoError, ReferencePicLists};
use crate::codec::h264::picture::{PictureData, Reference};
use crate::codec::Codec;
use crate::pool::{PooledSurface, SurfacePool};
use crate::{
bindings, Buffer, BufferType, Config as VaConfig, Context, Display, DrmPrimeSurfaceDescriptor, H264PicFields,
H264SeqFields, IQMatrix, IQMatrixBufferH264, Image, Picture, PictureH264, PictureParameter,
PictureParameterBufferH264, SliceParameter, SliceParameterBufferH264, Surface, UsageHint, VAConfigAttrib,
VAConfigAttribType, VAEntrypoint, VAProfile, VA_FOURCC_NV12, VA_INVALID_ID, VA_PICTURE_H264_INVALID,
VA_PICTURE_H264_LONG_TERM_REFERENCE, VA_PICTURE_H264_SHORT_TERM_REFERENCE, VA_RT_FORMAT_YUV420,
VA_SLICE_DATA_FLAG_ALL,
};
use kodecs_h264::{
Marking, Matrix, Mmco, Modification, Nalu, NaluHeader, NaluType, Parser, PicOrderCnt, Pps, Profile, SliceHeader,
SliceType, Sps, Unit,
};
mod h265;
#[derive(Clone, Debug)]
pub struct Config {
pub codec: Codec,
pub device: Option<PathBuf>,
}
impl Config {
pub fn new() -> Self {
Self {
codec: Codec::H264,
device: None,
}
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone)]
pub struct Frame {
pub timestamp: u64,
pub width: u32,
pub height: u32,
pub data: Vec<u8>,
}
pub struct ExportedFrame {
pub timestamp: u64,
pub width: u32,
pub height: u32,
pub descriptor: DrmPrimeSurfaceDescriptor,
surface: Arc<PooledSurface>,
}
impl ExportedFrame {
pub fn from_surface(surface: Surface<()>, timestamp: u64) -> anyhow::Result<Self> {
let size = surface.size();
Self::export(Arc::new(PooledSurface::unpooled(surface)), timestamp, size)
}
pub(crate) fn export(
surface: Arc<PooledSurface>,
timestamp: u64,
(width, height): (u32, u32),
) -> anyhow::Result<Self> {
surface.get().sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
let descriptor = surface
.get()
.export_prime()
.map_err(|e| anyhow!("export the surface: {e:?}"))?;
if descriptor.fourcc != VA_FOURCC_NV12 {
anyhow::bail!("exported fourcc {:#010x}, expected NV12", descriptor.fourcc);
}
Ok(Self {
timestamp,
width,
height,
descriptor,
surface,
})
}
pub fn download(&self) -> anyhow::Result<Frame> {
read_back(self.surface.get(), self.timestamp, self.width, self.height)
}
}
impl std::fmt::Debug for ExportedFrame {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExportedFrame")
.field("timestamp", &self.timestamp)
.field("width", &self.width)
.field("height", &self.height)
.field("fourcc", &self.descriptor.fourcc)
.finish()
}
}
impl std::fmt::Debug for Frame {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Frame")
.field("timestamp", &self.timestamp)
.field("width", &self.width)
.field("height", &self.height)
.field("bytes", &self.data.len())
.finish()
}
}
pub struct Decoder {
inner: Inner,
}
enum Inner {
H264(H264),
H265(h265::Decoder),
}
struct H264 {
parser: Parser,
in_scope: Option<Arc<Sps>>,
dpb: Dpb<Handle>,
prev_ref_pic_info: PrevReferencePicInfo,
prev_pic_info: PrevPicInfo,
max_long_term_frame_idx_plus1: u32,
sequence: Option<Sequence>,
ready: Vec<Handle>,
display: Arc<Display>,
}
impl Decoder {
pub fn new(config: Config) -> anyhow::Result<Self> {
let codec = config.codec;
let (device, display) = match config.device {
Some(device) => {
let display =
Display::open_drm_display(&device).map_err(|e| anyhow!("open DRM display {device:?}: {e:?}"))?;
probe(&display, codec)?;
(device, display)
}
None => crate::display::open_first(|display| probe(display, codec))
.map_err(|e| e.context(format!("find a render node that decodes {codec:?}")))?,
};
tracing::info!("opened VA-API {codec:?} decoder on {device:?}");
let inner = match codec {
Codec::H264 => Inner::H264(H264::new(display)),
Codec::H265 => Inner::H265(h265::Decoder::new(display)),
};
Ok(Self { inner })
}
pub fn decode(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<Frame>> {
self.submit(access_unit, timestamp)?;
self.take_frames()
}
pub fn decode_exported(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<Vec<ExportedFrame>> {
self.submit(access_unit, timestamp)?;
self.take_exported()
}
fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<()> {
let nalus = match &mut self.inner {
Inner::H264(decoder) => decoder.submit(access_unit, timestamp)?,
Inner::H265(decoder) => decoder.submit(access_unit, timestamp)?,
};
if nalus == 0 && !access_unit.is_empty() {
tracing::warn!(
"access unit of {} bytes holds no Annex-B NAL unit; length-prefixed input has to be converted first",
access_unit.len()
);
}
Ok(())
}
pub fn flush(&mut self) -> anyhow::Result<Vec<Frame>> {
self.reset();
self.take_frames()
}
pub fn flush_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
self.reset();
self.take_exported()
}
fn reset(&mut self) {
match &mut self.inner {
Inner::H264(decoder) => decoder.reset(),
Inner::H265(decoder) => decoder.reset(),
}
}
fn ready(&mut self) -> &mut Vec<Handle> {
match &mut self.inner {
Inner::H264(decoder) => &mut decoder.ready,
Inner::H265(decoder) => &mut decoder.ready,
}
}
fn take_frames(&mut self) -> anyhow::Result<Vec<Frame>> {
std::mem::take(self.ready()).iter().map(download).collect()
}
fn take_exported(&mut self) -> anyhow::Result<Vec<ExportedFrame>> {
std::mem::take(self.ready()).iter().map(export).collect()
}
#[cfg(test)]
fn sequence(&self) -> Option<&Sequence> {
match &self.inner {
Inner::H264(decoder) => decoder.sequence.as_ref(),
Inner::H265(decoder) => decoder.sequence.as_ref(),
}
}
}
impl H264 {
fn new(display: Arc<Display>) -> Self {
Self {
parser: Parser::new(usize::MAX),
in_scope: None,
dpb: Dpb::default(),
prev_ref_pic_info: PrevReferencePicInfo::default(),
prev_pic_info: PrevPicInfo::default(),
max_long_term_frame_idx_plus1: 0,
sequence: None,
ready: Vec::new(),
display,
}
}
fn submit(&mut self, access_unit: &[u8], timestamp: u64) -> anyhow::Result<usize> {
let mut stream = access_unit;
let mut current: Option<CurrentPicture> = None;
let mut nalus = 0usize;
loop {
let before = stream;
let Some(nalu) = next_nalu(&mut stream, self.parser.max_nal_bytes())? else {
break;
};
nalus += 1;
let nal = nalu.header;
match nal.type_ {
NaluType::Sps | NaluType::Pps | NaluType::Slice | NaluType::SliceIdr => {}
NaluType::SliceDpa => bail!("H.264 data partitioning is outside what VA-API decodes"),
other => {
tracing::trace!("ignoring NAL unit of type {other:?}");
continue;
}
}
let mut sent = &before[..before.len() - stream.len()];
let unit = self
.parser
.next(&mut sent)
.map_err(|e| anyhow!(e).context(format!("parse a {:?} NAL unit", nal.type_)))?
.expect("the unit framed above");
let Unit::Slice { header, sps, pps, .. } = unit else {
continue;
};
if !self.in_scope.as_ref().is_some_and(|checked| Arc::ptr_eq(checked, &sps)) {
check_scope(&sps)?;
self.in_scope = Some(Arc::clone(&sps));
}
if matches!(header.slice_type, SliceType::Sp | SliceType::Si) {
bail!("H.264 {:?} slice: {SCOPE}", header.slice_type);
}
let start = nalu.payload.as_ptr() as usize - before.as_ptr() as usize - 1;
let slice = Slice {
header,
sps,
pps,
nal,
data: before[start..start + 1 + nalu.payload.len()].to_vec(),
};
let mut picture = match current.take() {
Some(picture) if slice.header.first_mb_in_slice == 0 => {
self.finish_picture(picture)?;
self.begin_picture(&slice, timestamp)?
}
Some(picture) => picture,
None => self.begin_picture(&slice, timestamp)?,
};
self.decode_slice(&mut picture, slice)?;
current = Some(picture);
}
if let Some(picture) = current.take() {
self.finish_picture(picture)?;
}
Ok(nalus)
}
fn reset(&mut self) {
self.drain();
self.prev_ref_pic_info = PrevReferencePicInfo::default();
self.prev_pic_info = PrevPicInfo::default();
self.max_long_term_frame_idx_plus1 = 0;
}
fn drain(&mut self) {
self.ready.extend(self.dpb.drain().into_iter().flatten());
}
fn apply_sps(&mut self, sps: &Sps) -> anyhow::Result<()> {
let info = SequenceInfo::new(sps)?;
self.dpb
.set_limits(info.max_dpb_frames, reorder_limit(sps, info.max_dpb_frames));
let format = Format {
codec: Codec::H264,
profile: va_profile(info.profile)?,
coded: info.coded,
visible: info.visible,
max_dpb_frames: info.max_dpb_frames,
};
if self.sequence.as_ref().map(|sequence| &sequence.format) == Some(&format) {
return Ok(());
}
self.drain();
self.sequence = Some(Sequence::new(&self.display, format)?);
Ok(())
}
fn begin_picture(&mut self, slice: &Slice, timestamp: u64) -> anyhow::Result<CurrentPicture> {
let (sps, pps) = (Arc::clone(&slice.sps), Arc::clone(&slice.pps));
self.apply_sps(&sps)?;
if slice.nal.type_ == NaluType::SliceIdr {
self.prev_ref_pic_info.frame_num = 0;
}
let frame_num = slice.header.frame_num;
if frame_num != self.prev_ref_pic_info.frame_num
&& frame_num != (self.prev_ref_pic_info.frame_num + 1) % max_frame_num(&sps)
{
self.handle_frame_num_gap(&sps, frame_num)?;
}
let pic = self.init_current_pic(slice, &sps)?;
let ref_pic_lists = self.dpb.build_ref_pic_lists(&pic, &sps);
let sequence = self.sequence.as_ref().expect("sequence built by apply_sps");
let context = Rc::clone(&sequence.context);
let handle = sequence.handle(timestamp)?;
let mut picture = Picture::new(timestamp, Rc::clone(&context), handle.clone());
let pic_param = build_pic_param(&slice.header, &pic, handle.surface.id(), &self.dpb, &sps, &pps);
picture.add_buffer(create_buffer(&context, pic_param)?);
picture.add_buffer(create_buffer(&context, build_iq_matrix(&sps, &pps))?);
tracing::trace!("starting picture POC {}", pic.pic_order_cnt);
Ok(CurrentPicture {
pic,
sps,
pps,
handle,
picture,
ref_pic_lists,
})
}
fn decode_slice(&mut self, current: &mut CurrentPicture, slice: Slice) -> anyhow::Result<()> {
if slice.header.first_mb_in_slice > u32::from(u16::MAX) {
bail!(
"slice starts at macroblock {}, past what a VA slice parameter addresses",
slice.header.first_mb_in_slice
);
}
if slice.header.header_bit_size > usize::from(u16::MAX) {
bail!(
"slice header is {} bits long, past what a VA slice parameter addresses",
slice.header.header_bit_size
);
}
if !Arc::ptr_eq(&slice.sps, ¤t.sps) && SequenceInfo::new(&slice.sps)? != SequenceInfo::new(¤t.sps)?
{
bail!("invalid stream: the sequence changed between slices of one picture");
}
current.sps = slice.sps;
current.pps = slice.pps;
let (list0, list1) =
self.create_ref_pic_lists(¤t.pic, &slice.header, ¤t.sps, ¤t.ref_pic_lists)?;
let context = &self.sequence.as_ref().expect("sequence built by apply_sps").context;
let slice_param = build_slice_param(&slice.header, slice.data.len(), &list0, &list1, ¤t.pps);
current.picture.add_buffer(create_buffer(context, slice_param)?);
current
.picture
.add_buffer(create_buffer(context, BufferType::SliceData(slice.data))?);
Ok(())
}
fn finish_picture(&mut self, current: CurrentPicture) -> anyhow::Result<()> {
let CurrentPicture {
mut pic,
sps,
handle,
picture,
..
} = current;
run(picture)?;
tracing::trace!("decoded picture POC {}", pic.pic_order_cnt);
if pic.is_ref() {
self.reference_pic_marking(&mut pic, &sps)?;
self.prev_ref_pic_info.fill(&pic);
}
self.prev_pic_info.fill(&pic);
if pic.has_mmco_5 {
self.drain();
}
self.dpb
.finish_picture(pic, handle, &mut self.ready)
.map_err(|e| anyhow!("store picture in DPB: {e}"))?;
Ok(())
}
fn init_current_pic(&mut self, slice: &Slice, sps: &Sps) -> anyhow::Result<PictureData> {
let mut pic = PictureData::new_from_slice(&slice.header, slice.nal, &sps.pic_order_cnt);
self.compute_pic_order_count(&mut pic, sps)?;
if pic.idr {
if matches!(pic.marking, Some(Marking::Idr(true, _))) {
self.dpb.clear();
} else {
self.drain();
}
}
self.dpb.update_pic_nums(slice.header.frame_num, max_frame_num(sps));
Ok(pic)
}
fn handle_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> anyhow::Result<()> {
if self.dpb.is_empty() {
return Ok(());
}
if !sps.gaps_in_frame_num_allowed {
bail!("invalid frame_num {frame_num}: assuming unintentional loss of pictures");
}
tracing::debug!("frame_num gap up to {frame_num}");
let max_frame_num = max_frame_num(sps);
let mut unused = first_invented(self.prev_ref_pic_info.frame_num, frame_num, sps);
while unused != frame_num {
let mut pic = PictureData::new_non_existing(unused);
self.compute_pic_order_count(&mut pic, sps)?;
self.dpb.update_pic_nums(unused, max_frame_num);
self.dpb.sliding_window_marking(sps);
self.ready.extend(self.dpb.bump_as_needed(&pic).into_iter().flatten());
self.dpb
.store_picture(pic, None)
.map_err(|e| anyhow!("store non-existing picture in DPB: {e}"))?;
unused = (unused + 1) % max_frame_num;
}
Ok(())
}
fn compute_pic_order_count(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
pic_order_count(&self.prev_ref_pic_info, &mut self.prev_pic_info, pic, sps)
}
fn reference_pic_marking(&mut self, pic: &mut PictureData, sps: &Sps) -> anyhow::Result<()> {
if pic.idr {
self.dpb.mark_all_as_unused_for_ref();
if matches!(pic.marking, Some(Marking::Idr(_, true))) {
pic.set_reference(Reference::LongTerm);
pic.long_term_frame_idx = 0;
self.max_long_term_frame_idx_plus1 = 1;
} else {
pic.set_reference(Reference::ShortTerm);
self.max_long_term_frame_idx_plus1 = 0;
}
return Ok(());
}
match pic.marking.take() {
Some(Marking::Adaptive(mmcos)) => self.handle_memory_management_ops(pic, &mmcos)?,
_ => self.dpb.sliding_window_marking(sps),
}
Ok(())
}
fn handle_memory_management_ops(&mut self, pic: &mut PictureData, mmcos: &[Mmco]) -> Result<(), MmcoError> {
for &mmco in mmcos {
match mmco {
Mmco::ForgetShort(difference) => self.dpb.mmco_op_1(pic, difference)?,
Mmco::ForgetLong(long_term_pic_num) => self.dpb.mmco_op_2(long_term_pic_num)?,
Mmco::ShortToLong(difference, idx) => self.dpb.mmco_op_3(pic, difference, idx)?,
Mmco::MaxLong(plus1) => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_4(plus1),
Mmco::ForgetAll => self.max_long_term_frame_idx_plus1 = self.dpb.mmco_op_5(pic),
Mmco::CurrentToLong(idx) => self.dpb.mmco_op_6(pic, idx),
}
}
Ok(())
}
fn create_ref_pic_lists<'a>(
&'a self,
pic: &PictureData,
hdr: &SliceHeader,
sps: &Sps,
lists: &ReferencePicLists,
) -> anyhow::Result<(DpbPicRefList<'a, Handle>, DpbPicRefList<'a, Handle>)> {
let max_pic_num = max_frame_num(sps) as i32;
let list0 = match hdr.slice_type {
SliceType::P => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_p0, max_pic_num)?,
SliceType::B => self.modify_ref_pic_list(pic, hdr, false, &lists.ref_pic_list_b0, max_pic_num)?,
SliceType::I | SliceType::Sp | SliceType::Si => Vec::new(),
};
let list1 = match hdr.slice_type {
SliceType::B => self.modify_ref_pic_list(pic, hdr, true, &lists.ref_pic_list_b1, max_pic_num)?,
SliceType::P | SliceType::I | SliceType::Sp | SliceType::Si => Vec::new(),
};
Ok((list0, list1))
}
fn modify_ref_pic_list<'a>(
&'a self,
pic: &PictureData,
hdr: &SliceHeader,
list1: bool,
indices: &[usize],
max_pic_num: i32,
) -> anyhow::Result<DpbPicRefList<'a, Handle>> {
let (active, modifications) = match list1 {
true => (hdr.num_ref_idx_l1_active, &hdr.modification_l1),
false => (hdr.num_ref_idx_l0_active, &hdr.modification_l0),
};
let active = usize::from(active);
let mut list: DpbPicRefList<'a, Handle> =
indices.iter().map(|&i| &self.dpb.entries()[i]).take(active).collect();
let Some(modifications) = modifications else {
return Ok(list);
};
let mut pic_num_pred = pic.pic_num;
let mut ref_idx = 0;
for modification in modifications {
match modification.idc {
idc @ (0 | 1) => self.short_term_modification(
pic,
&mut list,
active,
max_pic_num,
idc,
modification,
&mut pic_num_pred,
&mut ref_idx,
)?,
2 => self.long_term_modification(&mut list, active, modification, &mut ref_idx)?,
other => bail!("unexpected modification_of_pic_nums_idc {other}"),
}
}
Ok(list)
}
fn short_term_modification<'a>(
&'a self,
pic: &PictureData,
list: &mut DpbPicRefList<'a, Handle>,
active: usize,
max_pic_num: i32,
idc: u8,
modification: &Modification,
pic_num_pred: &mut i32,
ref_idx: &mut usize,
) -> anyhow::Result<()> {
let abs_diff_pic_num = modification.value as i32 + 1;
let pic_num_no_wrap = if idc == 0 {
if *pic_num_pred - abs_diff_pic_num < 0 {
*pic_num_pred - abs_diff_pic_num + max_pic_num
} else {
*pic_num_pred - abs_diff_pic_num
}
} else if *pic_num_pred + abs_diff_pic_num >= max_pic_num {
*pic_num_pred + abs_diff_pic_num - max_pic_num
} else {
*pic_num_pred + abs_diff_pic_num
};
*pic_num_pred = pic_num_no_wrap;
let pic_num = if pic_num_no_wrap > pic.pic_num {
pic_num_no_wrap - max_pic_num
} else {
pic_num_no_wrap
};
let entry = self
.dpb
.find_short_term_with_pic_num(pic_num)
.with_context(|| format!("no short-term reference with pic_num {pic_num}"))?;
Self::insert_modification(list, entry, active, ref_idx, |target| {
target.pic_num_f(max_pic_num) != pic_num
});
Ok(())
}
fn long_term_modification<'a>(
&'a self,
list: &mut DpbPicRefList<'a, Handle>,
active: usize,
modification: &Modification,
ref_idx: &mut usize,
) -> anyhow::Result<()> {
let long_term_pic_num = modification.value;
let max_long_term_frame_idx_plus1 = self.max_long_term_frame_idx_plus1;
let entry = self
.dpb
.find_long_term_with_long_term_pic_num(long_term_pic_num)
.with_context(|| format!("no long-term reference with long_term_pic_num {long_term_pic_num}"))?;
Self::insert_modification(list, entry, active, ref_idx, |target| {
target.long_term_pic_num_f(max_long_term_frame_idx_plus1) != u64::from(long_term_pic_num)
});
Ok(())
}
fn insert_modification<'a>(
list: &mut DpbPicRefList<'a, Handle>,
entry: &'a DpbEntry<Handle>,
active: usize,
ref_idx: &mut usize,
keep: impl Fn(&PictureData) -> bool,
) {
let at = (*ref_idx).min(list.len());
list.insert(at, entry);
*ref_idx = at + 1;
let mut next = *ref_idx;
for current in *ref_idx..=active {
if current >= list.len() {
break;
}
if keep(&list[current].pic) {
list[next] = list[current];
next += 1;
}
}
list.truncate(active);
}
}
struct Slice {
header: SliceHeader,
sps: Arc<Sps>,
pps: Arc<Pps>,
nal: NaluHeader,
data: Vec<u8>,
}
struct CurrentPicture {
pic: PictureData,
sps: Arc<Sps>,
pps: Arc<Pps>,
handle: Handle,
picture: Picture<crate::PictureNew, Handle>,
ref_pic_lists: ReferencePicLists,
}
#[derive(Clone)]
struct Handle {
surface: Arc<PooledSurface>,
timestamp: u64,
width: u32,
height: u32,
}
impl std::borrow::Borrow<Surface<()>> for Handle {
fn borrow(&self) -> &Surface<()> {
self.surface.get()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct SequenceInfo {
visible: (u32, u32),
coded: (u32, u32),
profile: Profile,
max_dpb_frames: usize,
}
const SCOPE: &str = "only progressive 8-bit 4:2:0 up to High profile, within its level, decodes";
fn check_scope(sps: &Sps) -> anyhow::Result<()> {
sps.check_decoder_scope()
.map_err(|e| anyhow!("H.264 SPS {}: {e}: {SCOPE}", sps.id))
}
impl SequenceInfo {
fn new(sps: &Sps) -> anyhow::Result<Self> {
let (right, bottom) = match sps.crop {
Some(crop) if crop.left != 0 || crop.top != 0 => bail!("left and top H.264 cropping is not supported"),
Some(crop) => (crop.right, crop.bottom),
None => (0, 0),
};
let coded = (16 * sps.width_mbs, 16 * sps.height_mbs);
Ok(Self {
visible: (coded.0 - right, coded.1 - bottom),
coded,
profile: sps.profile,
max_dpb_frames: max_dpb_frames(sps),
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Format {
codec: Codec,
profile: VAProfile::Type,
coded: (u32, u32),
visible: (u32, u32),
max_dpb_frames: usize,
}
struct Sequence {
format: Format,
pool: SurfacePool,
context: Rc<Context>,
_config: VaConfig,
}
impl Sequence {
fn new(display: &Arc<Display>, format: Format) -> anyhow::Result<Self> {
let attrs = vec![VAConfigAttrib {
type_: VAConfigAttribType::VAConfigAttribRTFormat,
value: VA_RT_FORMAT_YUV420,
}];
let config = display
.create_config(attrs, format.profile, VAEntrypoint::VAEntrypointVLD)
.map_err(|e| anyhow!("create VA config: {e:?}"))?;
let (coded_width, coded_height) = format.coded;
let context = display
.create_context::<()>(&config, coded_width, coded_height, None, true)
.map_err(|e| anyhow!("create VA context: {e:?}"))?;
let (width, height) = format.visible;
tracing::info!(
"VA-API {:?} sequence: {width}x{height} visible, {coded_width}x{coded_height} coded, \
VA profile {}, DPB {} frames",
format.codec,
format.profile,
format.max_dpb_frames
);
let capacity = format.max_dpb_frames + 1;
Ok(Self {
pool: SurfacePool::new(
display,
(coded_width, coded_height),
UsageHint::USAGE_HINT_DECODER,
capacity,
),
format,
context,
_config: config,
})
}
fn handle(&self, timestamp: u64) -> anyhow::Result<Handle> {
let (width, height) = self.format.visible;
Ok(Handle {
surface: Arc::new(self.pool.alloc()?),
timestamp,
width,
height,
})
}
}
fn run(picture: Picture<crate::PictureNew, Handle>) -> anyhow::Result<()> {
let picture = picture.begin::<()>().map_err(|e| anyhow!("picture begin: {e:?}"))?;
let picture = picture.render().map_err(|e| anyhow!("picture render: {e:?}"))?;
let picture = picture.end().map_err(|e| anyhow!("picture end: {e:?}"))?;
drop(picture.sync::<()>().map_err(|(e, _)| anyhow!("picture sync: {e:?}"))?);
Ok(())
}
fn max_dpb_frames(sps: &Sps) -> usize {
match sps.vui.as_ref().and_then(|vui| vui.restriction) {
Some(restriction) => usize::from(restriction.max_dec_frame_buffering.max(1)),
None => usize::from(sps.max_dpb_frames),
}
}
fn reorder_limit(sps: &Sps, max_dpb_frames: usize) -> usize {
if matches!(sps.pic_order_cnt, PicOrderCnt::Decode) {
return 0;
}
let declared = match sps.vui.as_ref().and_then(|vui| vui.restriction) {
Some(restriction) => usize::from(restriction.max_num_reorder_frames),
None if matches!(sps.profile.value(), 44 | 86 | 100 | 110 | 122 | 244) && sps.constraint_flags & 0x10 != 0 => 0,
None => max_dpb_frames,
};
declared.min(max_dpb_frames)
}
fn max_frame_num(sps: &Sps) -> u32 {
1 << sps.log2_max_frame_num
}
fn export(handle: &Handle) -> anyhow::Result<ExportedFrame> {
ExportedFrame::export(
Arc::clone(&handle.surface),
handle.timestamp,
(handle.width, handle.height),
)
}
fn download(handle: &Handle) -> anyhow::Result<Frame> {
read_back(handle.surface.get(), handle.timestamp, handle.width, handle.height)
}
fn read_back(surface: &Surface<()>, timestamp: u64, width: u32, height: u32) -> anyhow::Result<Frame> {
surface.sync().map_err(|e| anyhow!("surface sync: {e:?}"))?;
let visible = (width, height);
match unsafe { Image::derive_shared(surface, visible) } {
Ok(image) if image.image().format.fourcc == VA_FOURCC_NV12 => {
return pack_nv12(&image, timestamp, width, height);
}
Ok(_) => tracing::debug!("derived image is not NV12, falling back to vaGetImage"),
Err(e) => tracing::debug!("vaDeriveImage failed ({e:?}), falling back to vaGetImage"),
}
let format = surface
.display()
.query_image_formats()
.map_err(|e| anyhow!("query image formats: {e:?}"))?
.into_iter()
.find(|format| format.fourcc == VA_FOURCC_NV12)
.context("driver has no NV12 image format")?;
let image = Image::create_from(surface, format, surface.size(), visible)
.map_err(|e| anyhow!("vaGetImage into an NV12 image: {e:?}"))?;
pack_nv12(&image, timestamp, width, height)
}
fn pack_nv12(image: &Image<'_>, timestamp: u64, frame_width: u32, frame_height: u32) -> anyhow::Result<Frame> {
let va_image = image.image();
let src: &[u8] = image.as_ref();
let (width, height) = (frame_width as usize, frame_height as usize);
let chroma_rows = height / 2;
let mut data = vec![0u8; width * (height + chroma_rows)];
let (luma, chroma) = data.split_at_mut(width * height);
copy_plane(
luma,
src,
va_image.offsets[0] as usize,
va_image.pitches[0] as usize,
width,
height,
)?;
copy_plane(
chroma,
src,
va_image.offsets[1] as usize,
va_image.pitches[1] as usize,
width,
chroma_rows,
)?;
Ok(Frame {
timestamp,
width: frame_width,
height: frame_height,
data,
})
}
fn copy_plane(
dst: &mut [u8],
src: &[u8],
offset: usize,
pitch: usize,
width: usize,
rows: usize,
) -> anyhow::Result<()> {
if rows == 0 {
return Ok(());
}
let end = offset + pitch * (rows - 1) + width;
if pitch < width || src.len() < end {
bail!("VA image plane (offset {offset}, pitch {pitch}) does not hold {rows} rows of {width} bytes");
}
for row in 0..rows {
let from = offset + row * pitch;
dst[row * width..][..width].copy_from_slice(&src[from..from + width]);
}
Ok(())
}
pub fn probe(display: &Display, codec: Codec) -> anyhow::Result<()> {
let profiles = display
.query_config_profiles()
.map_err(|e| anyhow!("query VA profiles: {e:?}"))?;
let supported = profiles
.into_iter()
.filter(|profile| match codec {
Codec::H264 => matches!(
*profile,
VAProfile::VAProfileH264ConstrainedBaseline
| VAProfile::VAProfileH264Main
| VAProfile::VAProfileH264High
),
Codec::H265 => *profile == VAProfile::VAProfileHEVCMain,
})
.any(|profile| {
display
.query_config_entrypoints(profile)
.is_ok_and(|entrypoints| entrypoints.contains(&VAEntrypoint::VAEntrypointVLD))
});
if !supported {
bail!("driver exposes no {codec:?} decode entrypoint");
}
Ok(())
}
fn va_profile(profile: Profile) -> anyhow::Result<VAProfile::Type> {
Ok(match profile {
Profile::Baseline => VAProfile::VAProfileH264ConstrainedBaseline,
Profile::Main | Profile::Extended => VAProfile::VAProfileH264Main,
Profile::High | Profile::High10 | Profile::High422P => VAProfile::VAProfileH264High,
other => bail!("unsupported H.264 profile {other:?}"),
})
}
fn create_buffer(context: &Rc<Context>, buffer: BufferType) -> anyhow::Result<Buffer> {
context
.create_buffer(buffer)
.map_err(|e| anyhow!("create VA buffer: {e:?}"))
}
fn first_invented(prev_frame_num: u32, frame_num: u32, sps: &Sps) -> u32 {
let max_frame_num = max_frame_num(sps);
let first = (prev_frame_num + 1) % max_frame_num;
let missing = (frame_num + max_frame_num - first) % max_frame_num;
let window = u32::from(sps.max_num_ref_frames).max(1);
let skipped = missing.saturating_sub(window);
(first + skipped) % max_frame_num
}
fn pic_order_count(
prev_ref: &PrevReferencePicInfo,
prev: &mut PrevPicInfo,
pic: &mut PictureData,
sps: &Sps,
) -> anyhow::Result<()> {
let overflow = || anyhow!("picture order count overflows");
match &sps.pic_order_cnt {
PicOrderCnt::Lsb { log2_max_lsb } => {
let (prev_pic_order_cnt_msb, prev_pic_order_cnt_lsb) = if pic.idr {
(0, 0)
} else if prev_ref.has_mmco_5 {
(0, prev_ref.top_field_order_cnt)
} else {
(prev_ref.pic_order_cnt_msb, prev_ref.pic_order_cnt_lsb)
};
let max_pic_order_cnt_lsb: i32 = 1 << log2_max_lsb;
let lsb_delta = i64::from(prev_pic_order_cnt_lsb) - i64::from(pic.pic_order_cnt_lsb);
let half = i64::from(max_pic_order_cnt_lsb / 2);
pic.pic_order_cnt_msb = if lsb_delta >= half {
prev_pic_order_cnt_msb.checked_add(max_pic_order_cnt_lsb)
} else if -lsb_delta > half {
prev_pic_order_cnt_msb.checked_sub(max_pic_order_cnt_lsb)
} else {
Some(prev_pic_order_cnt_msb)
}
.ok_or_else(overflow)?;
pic.top_field_order_cnt = pic
.pic_order_cnt_msb
.checked_add(pic.pic_order_cnt_lsb)
.ok_or_else(overflow)?;
pic.bottom_field_order_cnt = pic
.top_field_order_cnt
.checked_add(pic.delta_pic_order_cnt_bottom)
.ok_or_else(overflow)?;
}
PicOrderCnt::Cycle {
offset_for_non_ref_pic,
offset_for_top_to_bottom_field,
offset_for_ref_frame,
..
} => {
if prev.has_mmco_5 {
prev.frame_num_offset = 0;
}
pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
let mut abs_frame_num = if !offset_for_ref_frame.is_empty() {
pic.frame_num_offset.checked_add(pic.frame_num).ok_or_else(overflow)?
} else {
0
};
if pic.nal_ref_idc == 0 && abs_frame_num > 0 {
abs_frame_num -= 1;
}
let mut expected_pic_order_cnt: i128 = 0;
if abs_frame_num > 0 {
let cycle_len = offset_for_ref_frame.len() as u32;
let cycles = (abs_frame_num - 1) / cycle_len;
let position_in_cycle = (abs_frame_num - 1) % cycle_len;
let expected_delta_per_cycle: i128 =
offset_for_ref_frame.iter().map(|&offset| i128::from(offset)).sum();
expected_pic_order_cnt = i128::from(cycles) * expected_delta_per_cycle;
for &offset in &offset_for_ref_frame[..=position_in_cycle as usize] {
expected_pic_order_cnt += i128::from(offset);
}
}
if pic.nal_ref_idc == 0 {
expected_pic_order_cnt += i128::from(*offset_for_non_ref_pic);
}
let count = |cnt: i128| i32::try_from(cnt).map_err(|_| overflow());
let top = expected_pic_order_cnt + i128::from(pic.delta_pic_order_cnt0);
let to_bottom = i128::from(*offset_for_top_to_bottom_field);
pic.top_field_order_cnt = count(top)?;
pic.bottom_field_order_cnt = count(top + to_bottom + i128::from(pic.delta_pic_order_cnt1))?;
}
PicOrderCnt::Decode => {
if prev.has_mmco_5 {
prev.frame_num_offset = 0;
}
pic.frame_num_offset = frame_num_offset(prev, pic, sps)?;
let pic_order_cnt = if pic.idr {
0
} else {
let abs_frame_num = i64::from(pic.frame_num_offset) + i64::from(pic.frame_num);
i32::try_from(2 * abs_frame_num - i64::from(pic.nal_ref_idc == 0)).map_err(|_| overflow())?
};
pic.top_field_order_cnt = pic_order_cnt;
pic.bottom_field_order_cnt = pic_order_cnt;
}
}
pic.pic_order_cnt = std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt);
Ok(())
}
fn frame_num_offset(prev: &PrevPicInfo, pic: &PictureData, sps: &Sps) -> anyhow::Result<u32> {
Ok(if pic.idr {
0
} else if prev.frame_num > pic.frame_num {
prev.frame_num_offset
.checked_add(max_frame_num(sps))
.context("FrameNumOffset overflows")?
} else {
prev.frame_num_offset
})
}
#[derive(Debug, Default)]
struct PrevReferencePicInfo {
frame_num: u32,
has_mmco_5: bool,
top_field_order_cnt: i32,
pic_order_cnt_msb: i32,
pic_order_cnt_lsb: i32,
}
impl PrevReferencePicInfo {
fn fill(&mut self, pic: &PictureData) {
self.has_mmco_5 = pic.has_mmco_5;
self.top_field_order_cnt = pic.top_field_order_cnt;
self.pic_order_cnt_msb = pic.pic_order_cnt_msb;
self.pic_order_cnt_lsb = pic.pic_order_cnt_lsb;
self.frame_num = pic.frame_num;
}
}
#[derive(Debug, Default)]
struct PrevPicInfo {
frame_num: u32,
frame_num_offset: u32,
has_mmco_5: bool,
}
impl PrevPicInfo {
fn fill(&mut self, pic: &PictureData) {
self.frame_num = pic.frame_num;
self.has_mmco_5 = pic.has_mmco_5;
self.frame_num_offset = pic.frame_num_offset;
}
}
fn va_surface_id(handle: &Option<Handle>) -> bindings::VASurfaceID {
match handle {
Some(handle) => handle.surface.id(),
None => VA_INVALID_ID,
}
}
fn fill_va_h264_pic(pic: &PictureData, surface_id: bindings::VASurfaceID) -> PictureH264 {
let mut flags = 0;
let frame_idx = match pic.reference() {
Reference::LongTerm => {
flags |= VA_PICTURE_H264_LONG_TERM_REFERENCE;
pic.long_term_frame_idx
}
Reference::ShortTerm => {
flags |= VA_PICTURE_H264_SHORT_TERM_REFERENCE;
pic.frame_num
}
Reference::None => pic.frame_num,
};
PictureH264::new(
surface_id,
frame_idx,
flags,
pic.top_field_order_cnt,
pic.bottom_field_order_cnt,
)
}
fn build_invalid_va_h264_pic() -> PictureH264 {
PictureH264::new(VA_INVALID_ID, 0, VA_PICTURE_H264_INVALID, 0, 0)
}
fn build_iq_matrix(sps: &Sps, pps: &Pps) -> BufferType {
const ZIGZAG_4X4: [usize; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
#[rustfmt::skip]
const ZIGZAG_8X8: [usize; 64] = [
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51,
58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
];
let flat = Matrix {
lists_4x4: vec![16; 6 * 16],
lists_8x8: vec![16; 2 * 64],
};
let matrix = pps.scaling.as_ref().or(sps.scaling.as_ref()).unwrap_or(&flat);
let mut scaling_list4x4 = [[0u8; 16]; 6];
for (list, src) in scaling_list4x4.iter_mut().zip(matrix.lists_4x4.chunks_exact(16)) {
for (i, &value) in src.iter().enumerate() {
list[ZIGZAG_4X4[i]] = value;
}
}
let mut scaling_list8x8 = [[0u8; 64]; 2];
for (list, src) in scaling_list8x8.iter_mut().zip(matrix.lists_8x8.chunks_exact(64)) {
for (i, &value) in src.iter().enumerate() {
list[ZIGZAG_8X8[i]] = value;
}
}
BufferType::IQMatrix(IQMatrix::H264(IQMatrixBufferH264::new(
scaling_list4x4,
scaling_list8x8,
)))
}
fn build_pic_param(
hdr: &SliceHeader,
pic: &PictureData,
surface_id: bindings::VASurfaceID,
dpb: &Dpb<Handle>,
sps: &Sps,
pps: &Pps,
) -> BufferType {
let curr_pic = fill_va_h264_pic(pic, surface_id);
let short_term = dpb.short_term_refs_iter().filter(|entry| !entry.pic.nonexisting);
let mut refs: Vec<PictureH264> = short_term
.chain(dpb.long_term_refs_iter())
.take(16)
.map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
.collect();
refs.resize_with(16, build_invalid_va_h264_pic);
let refs: [PictureH264; 16] = refs.try_into().unwrap_or_else(|_| unreachable!("resized to 16"));
let (pic_order_cnt_type, log2_max_lsb, delta_always_zero) = match sps.pic_order_cnt {
PicOrderCnt::Lsb { log2_max_lsb } => (0, log2_max_lsb, false),
PicOrderCnt::Cycle { delta_always_zero, .. } => (1, 4, delta_always_zero),
PicOrderCnt::Decode => (2, 4, false),
};
let seq_fields = H264SeqFields::new(
1, 0, sps.gaps_in_frame_num_allowed as u32,
1, 0, sps.direct_8x8_inference as u32,
(sps.level.value() >= 31) as u32,
u32::from(sps.log2_max_frame_num - 4),
pic_order_cnt_type,
u32::from(log2_max_lsb - 4),
delta_always_zero as u32,
);
let pic_fields = H264PicFields::new(
pps.entropy_coding_mode as u32,
pps.weighted_pred as u32,
u32::from(pps.weighted_bipred_idc),
pps.transform_8x8_mode as u32,
0, pps.constrained_intra_pred as u32,
pps.bottom_field_pic_order_in_frame_present as u32,
pps.deblocking_filter_control_present as u32,
pps.redundant_pic_cnt_present as u32,
(pic.nal_ref_idc != 0) as u32,
);
BufferType::PictureParameter(PictureParameter::H264(PictureParameterBufferH264::new(
curr_pic,
refs,
(sps.width_mbs - 1) as u16,
(sps.height_mbs - 1) as u16,
0, 0, sps.max_num_ref_frames,
&seq_fields,
0,
0,
0,
(pps.pic_init_qp - 26) as i8,
(pps.pic_init_qs - 26) as i8,
pps.chroma_qp_index_offset as i8,
pps.second_chroma_qp_index_offset as i8,
&pic_fields,
hdr.frame_num as u16,
)))
}
fn fill_ref_pic_list(list: &[&DpbEntry<Handle>]) -> [PictureH264; 32] {
let mut pics: Vec<PictureH264> = list
.iter()
.take(32)
.map(|entry| fill_va_h264_pic(&entry.pic, va_surface_id(&entry.reference)))
.collect();
pics.resize_with(32, build_invalid_va_h264_pic);
pics.try_into().unwrap_or_else(|_| unreachable!("resized to 32"))
}
fn build_slice_param(
hdr: &SliceHeader,
slice_size: usize,
list0: &[&DpbEntry<Handle>],
list1: &[&DpbEntry<Handle>],
pps: &Pps,
) -> BufferType {
let mut luma_weight_l0 = [0i16; 32];
let mut luma_offset_l0 = [0i16; 32];
let mut chroma_weight_l0 = [[0i16; 2]; 32];
let mut chroma_offset_l0 = [[0i16; 2]; 32];
let mut luma_weight_l1 = [0i16; 32];
let mut luma_offset_l1 = [0i16; 32];
let mut chroma_weight_l1 = [[0i16; 2]; 32];
let mut chroma_offset_l1 = [[0i16; 2]; 32];
let weights = hdr.weights.as_ref();
let fill = |weights: &[kodecs_h264::Weight],
luma_weight: &mut [i16; 32],
luma_offset: &mut [i16; 32],
chroma_weight: &mut [[i16; 2]; 32],
chroma_offset: &mut [[i16; 2]; 32]| {
for (i, weight) in weights.iter().take(32).enumerate() {
luma_weight[i] = weight.luma_weight as i16;
luma_offset[i] = weight.luma_offset as i16;
chroma_weight[i] = weight.chroma_weight.map(|w| w as i16);
chroma_offset[i] = weight.chroma_offset.map(|o| o as i16);
}
};
if let Some(weights) = weights {
fill(
&weights.l0,
&mut luma_weight_l0,
&mut luma_offset_l0,
&mut chroma_weight_l0,
&mut chroma_offset_l0,
);
fill(
&weights.l1,
&mut luma_weight_l1,
&mut luma_offset_l1,
&mut chroma_weight_l1,
&mut chroma_offset_l1,
);
}
let fill_l0 = weights.is_some();
let fill_l1 = weights.is_some() && hdr.slice_type == SliceType::B;
BufferType::SliceParameter(SliceParameter::H264(SliceParameterBufferH264::new(
slice_size as u32,
0,
VA_SLICE_DATA_FLAG_ALL,
hdr.header_bit_size as u16,
hdr.first_mb_in_slice as u16,
hdr.slice_type_raw % 5,
hdr.direct_spatial_mv_pred as u8,
hdr.num_ref_idx_l0_active.saturating_sub(1),
hdr.num_ref_idx_l1_active.saturating_sub(1),
hdr.cabac_init_idc,
(hdr.slice_qp - pps.pic_init_qp) as i8,
hdr.disable_deblocking_filter_idc,
hdr.slice_alpha_c0_offset_div2 as i8,
hdr.slice_beta_offset_div2 as i8,
fill_ref_pic_list(list0),
fill_ref_pic_list(list1),
weights.map_or(0, |w| w.luma_log2_denom),
weights.map_or(0, |w| w.chroma_log2_denom),
fill_l0 as u8,
luma_weight_l0,
luma_offset_l0,
fill_l0 as u8,
chroma_weight_l0,
chroma_offset_l0,
fill_l1 as u8,
luma_weight_l1,
luma_offset_l1,
fill_l1 as u8,
chroma_weight_l1,
chroma_offset_l1,
)))
}
fn next_nalu<'a>(stream: &mut &'a [u8], max_bytes: usize) -> anyhow::Result<Option<Nalu<'a>>> {
loop {
let Some(raw) = kodecs_h264::split_annex_b(stream, max_bytes).context("frame a NAL unit")? else {
return Ok(None);
};
if !raw.is_empty() {
return Ok(Some(Nalu::new(raw, max_bytes).context("parse a NAL unit header")?));
}
}
}
#[cfg(test)]
mod tests {
use std::os::fd::OwnedFd;
use std::process::Command;
use super::*;
#[test]
fn a_malformed_header_is_an_error() {
let bytes = [0, 0, 1, 0, 0, 0, 1, 0x09, 0x10, 0, 0, 0, 1, 0x07, 0x42, 0x00, 0x1e];
let mut stream = &bytes[..];
let nalu = next_nalu(&mut stream, usize::MAX).unwrap().expect("a unit");
assert_eq!(nalu.header.type_, NaluType::AuDelimiter);
assert!(next_nalu(&mut stream, usize::MAX).is_err());
assert!(next_nalu(&mut stream, usize::MAX).unwrap().is_none());
}
fn progressive_sps() -> Sps {
kodecs_h264::SpsBuilder::new(Profile::Main, kodecs_h264::Level::L3)
.resolution(320, 240)
.build()
.unwrap()
}
#[test]
fn a_frame_num_gap_invents_only_the_reference_window() {
let mut sps = progressive_sps();
sps.max_num_ref_frames = 2;
assert_eq!(first_invented(3, 4, &sps), 4);
assert_eq!(first_invented(3, 5, &sps), 4);
assert_eq!(first_invented(3, 10, &sps), 8);
assert_eq!(first_invented(14, 3, &sps), 1);
assert_eq!(first_invented(4, 3, &sps), 1);
sps.max_num_ref_frames = 0;
assert_eq!(first_invented(0, 3, &sps), 2);
}
fn type0_poc(prev: PrevReferencePicInfo, lsb: i32) -> anyhow::Result<i32> {
let mut sps = progressive_sps();
sps.pic_order_cnt = PicOrderCnt::Lsb { log2_max_lsb: 8 };
let mut pic = PictureData::default();
pic.pic_order_cnt_lsb = lsb;
pic.nal_ref_idc = 1;
pic_order_count(&prev, &mut PrevPicInfo::default(), &mut pic, &sps)?;
Ok(pic.pic_order_cnt)
}
fn prev_ref(msb: i32, lsb: i32) -> PrevReferencePicInfo {
PrevReferencePicInfo {
pic_order_cnt_msb: msb,
pic_order_cnt_lsb: lsb,
..Default::default()
}
}
#[test]
fn the_picture_order_count_wraps_and_never_overflows() {
assert_eq!(type0_poc(prev_ref(0, 250), 2).unwrap(), 256 + 2);
assert_eq!(type0_poc(prev_ref(512, 2), 250).unwrap(), 256 + 250);
assert!(type0_poc(prev_ref(i32::MAX - 255, 250), 2).is_err());
assert!(type0_poc(prev_ref(i32::MIN, 2), 250).is_err());
assert!(type0_poc(prev_ref(i32::MAX - 100, 100), 200).is_err());
let after_mmco5 = PrevReferencePicInfo {
has_mmco_5: true,
top_field_order_cnt: i32::MIN,
..Default::default()
};
assert_eq!(type0_poc(after_mmco5, 2).unwrap(), -256 + 2);
}
#[test]
fn the_frame_num_offset_never_overflows() {
let mut sps = progressive_sps();
sps.pic_order_cnt = PicOrderCnt::Decode;
let order_count = |frame_num_offset| {
let mut prev = PrevPicInfo {
frame_num: 5,
frame_num_offset,
has_mmco_5: false,
};
let mut pic = PictureData::default();
pic.frame_num = 1;
pic.nal_ref_idc = 1;
pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
};
assert_eq!(order_count(0).unwrap(), 2 * (16 + 1));
assert!(order_count(u32::MAX - 3).is_err());
assert!(order_count(i32::MAX as u32 / 2).is_err());
}
#[test]
fn the_type2_order_count_is_checked_whole() {
let mut sps = progressive_sps();
sps.pic_order_cnt = PicOrderCnt::Decode;
let order_count = |nal_ref_idc| {
let mut prev = PrevPicInfo {
frame_num: 5,
frame_num_offset: (1 << 30) - 17,
has_mmco_5: false,
};
let mut pic = PictureData::default();
pic.frame_num = 1;
pic.nal_ref_idc = nal_ref_idc;
pic_order_count(&prev_ref(0, 0), &mut prev, &mut pic, &sps).map(|()| pic.pic_order_cnt)
};
assert_eq!(order_count(0).unwrap(), i32::MAX);
assert!(order_count(1).is_err());
}
#[test]
fn the_type1_bottom_field_is_checked_whole() {
let mut sps = progressive_sps();
sps.pic_order_cnt = PicOrderCnt::Cycle {
delta_always_zero: false,
offset_for_non_ref_pic: 0,
offset_for_top_to_bottom_field: i32::MAX,
offset_for_ref_frame: Vec::new(),
};
let bottom = |delta0, delta1| {
let mut pic = PictureData::default();
pic.nal_ref_idc = 1;
pic.delta_pic_order_cnt0 = delta0;
pic.delta_pic_order_cnt1 = delta1;
pic_order_count(&prev_ref(0, 0), &mut PrevPicInfo::default(), &mut pic, &sps)
.map(|()| pic.bottom_field_order_cnt)
};
assert_eq!(bottom(2, -i32::MAX).unwrap(), 2);
assert!(bottom(2, 0).is_err());
}
#[test]
fn rejects_nonzero_crop_origins() {
for (left, top) in [(2, 0), (0, 2)] {
let mut sps = progressive_sps();
sps.crop = Some(kodecs_h264::Crop {
left,
right: 0,
top,
bottom: 0,
});
assert!(SequenceInfo::new(&sps)
.unwrap_err()
.to_string()
.contains("left and top"));
}
}
#[test]
fn crop_only_updates_change_sequence_identity() {
let original = SequenceInfo::new(&progressive_sps()).unwrap();
for (right, bottom, expected) in [(2, 0, (318, 240)), (0, 2, (320, 238))] {
let mut sps = progressive_sps();
sps.crop = Some(kodecs_h264::Crop {
left: 0,
right,
top: 0,
bottom,
});
let cropped = SequenceInfo::new(&sps).unwrap();
assert_eq!(original.coded, cropped.coded);
assert_eq!(cropped.visible, expected);
assert_ne!(original, cropped);
}
}
fn encoder_config(width: u32, height: u32) -> crate::encode::Config {
crate::encode::Config {
device: Some(crate::testing::device()),
..crate::encode::Config::new(width, height, 30, 2_000_000, std::num::NonZeroU32::new(30).unwrap())
}
}
fn config() -> Config {
Config {
device: Some(crate::testing::device()),
..Config::new()
}
}
fn nv12_frame(width: u32, height: u32, step: u32) -> Vec<u8> {
let (w, h) = (width as usize, height as usize);
let mut data = vec![128u8; w * h * 3 / 2];
let x0 = (step * 16) as usize % (w / 2);
for y in h / 4..h / 2 {
for x in x0..x0 + w / 4 {
data[y * w + x] = 235;
}
}
data
}
#[test]
#[ignore = "requires a VA-API render node"]
fn exported_pictures_do_not_share_a_surface() {
let (width, height) = (320u32, 240u32);
let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
let mut exported = Vec::new();
for step in 0..8 {
let unit = encoder
.encode_nv12(&nv12_frame(width, height, step), step == 0)
.expect("encode a picture");
exported.extend(decoder.decode_exported(&unit, step as u64).expect("decode a picture"));
}
exported.extend(decoder.flush_exported().expect("flush the decoder"));
assert!(!exported.is_empty(), "the decoder produced no pictures");
let first = &exported[0];
eprintln!(
"exported {} pictures: {}x{} fourcc {:#x} modifier {:#x}",
exported.len(),
first.width,
first.height,
first.descriptor.fourcc,
first.descriptor.objects[0].drm_format_modifier
);
let mut seen = Vec::new();
for (index, frame) in exported.iter().enumerate() {
assert_eq!((frame.width, frame.height), (width, height));
assert_eq!(frame.descriptor.fourcc, VA_FOURCC_NV12);
assert_eq!(frame.descriptor.objects.len(), 1, "a composed export is one object");
assert_eq!(frame.descriptor.layers[0].num_planes, 2, "NV12 is two planes");
let inode = inode(&frame.descriptor.objects[0].fd);
assert!(
!seen.contains(&inode),
"picture {index} was decoded into an allocation an earlier one still holds"
);
seen.push(inode);
}
}
#[test]
#[ignore = "requires a VA-API render node"]
fn the_render_node_is_found_or_named() {
if let Err(err) = Decoder::new(Config::new()) {
panic!("no VA-API H.264 decoder: {err:#}");
}
let named = Config {
device: Some(PathBuf::from("/dev/null")),
..Config::new()
};
assert!(
Decoder::new(named).is_err(),
"a named node that is not a render node was swapped for one that is"
);
}
#[test]
#[ignore = "requires a VA-API render node and FFmpeg"]
fn flush_returns_the_pictures_the_dpb_still_holds() {
const PICTURES: usize = 10;
let stream = software_encode(Codec::H264, (320, 240), PICTURES, true).expect("no ffmpeg that encodes H.264");
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
let mut streamed = Vec::new();
for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
streamed.extend(decoder.decode(unit, index as u64).expect("decode a picture"));
}
assert!(
streamed.len() < PICTURES,
"the DPB held nothing back, so this test proves nothing"
);
let flushed = decoder.flush().expect("flush the decoder");
let mut timestamps: Vec<u64> = streamed
.iter()
.chain(&flushed)
.map(|picture| picture.timestamp)
.collect();
timestamps.sort_unstable();
assert_eq!(
timestamps,
(0..PICTURES as u64).collect::<Vec<_>>(),
"the stream lost pictures at its end"
);
assert!(decoder.flush().expect("flush an empty decoder").is_empty());
}
#[test]
#[ignore = "requires a VA-API render node and FFmpeg"]
fn h264_without_reordering_comes_out_as_it_decodes() {
const PICTURES: usize = 10;
let (width, height) = (320u32, 240u32);
let mut streams = Vec::new();
match crate::encode::Encoder::new(encoder_config(width, height)) {
Ok(mut encoder) => {
let units = (0..PICTURES)
.map(|step| {
encoder
.encode_nv12(&nv12_frame(width, height, step as u32), step == 0)
.expect("encode a picture")
})
.collect::<Vec<_>>();
streams.push(("VA-API", units));
}
Err(err) => panic!("open VA-API H.264 encoder: {err:#}"),
}
match software_encode(Codec::H264, (width, height), PICTURES, false) {
Some(stream) => streams.push(("libx264", split_access_units(Codec::H264, &stream))),
None => panic!("FFmpeg with libx264 is required"),
}
for (encoder, units) in streams {
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
for (index, unit) in units.iter().enumerate() {
let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
assert_eq!(
timestamps,
[index as u64],
"{encoder}: access unit {index} was held back"
);
}
assert!(decoder.flush().expect("flush the decoder").is_empty());
}
}
#[test]
fn the_reorder_limit_follows_the_sps() {
let sps = progressive_sps();
assert_eq!(sps.max_dpb_frames, 16);
assert_eq!(max_dpb_frames(&sps), 16);
assert_eq!(
reorder_limit(&sps, 16),
16,
"without a VUI, the inference is the DPB size"
);
let mut intra = progressive_sps();
intra.profile = Profile::High;
intra.constraint_flags = 0x10;
assert_eq!(
reorder_limit(&intra, 16),
0,
"without a VUI, a High intra profile reorders nothing"
);
let restriction = |max_num_reorder_frames, max_dec_frame_buffering| kodecs_h264::Restriction {
motion_vectors_over_pic_boundaries: true,
max_bytes_per_pic_denom: 2,
max_bits_per_mb_denom: 1,
log2_max_mv_length_horizontal: 16,
log2_max_mv_length_vertical: 16,
max_num_reorder_frames,
max_dec_frame_buffering,
};
let mut declared = progressive_sps();
declared.vui = Some(kodecs_h264::Vui {
aspect_ratio: None,
overscan_appropriate: None,
video_signal: None,
chroma_loc: None,
timing: None,
nal_hrd: None,
vcl_hrd: None,
low_delay_hrd: false,
pic_struct_present: false,
restriction: Some(restriction(0, 1)),
});
assert_eq!(max_dpb_frames(&declared), 1, "the VUI's buffering is the DPB size");
assert_eq!(
reorder_limit(&declared, max_dpb_frames(&declared)),
0,
"the VUI's limit applies"
);
if let Some(vui) = declared.vui.as_mut() {
vui.restriction = Some(restriction(5, 2));
}
assert_eq!(
reorder_limit(&declared, max_dpb_frames(&declared)),
2,
"the DPB size bounds the VUI's limit"
);
let mut derived = progressive_sps();
derived.pic_order_cnt = PicOrderCnt::Decode;
assert_eq!(
reorder_limit(&derived, 16),
0,
"an order count from frame_num reorders nothing"
);
}
#[test]
#[ignore = "requires a VA-API render node"]
fn a_dropped_export_is_decoded_into_again() {
const PICTURES: u32 = 60;
let (width, height) = (320u32, 240u32);
let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
let mut exporting = Decoder::new(config()).expect("no VA-API H.264 decoder");
let mut downloading = Decoder::new(config()).expect("a second decoder");
let mut compared = 0;
for step in 0..PICTURES {
let unit = encoder
.encode_nv12(&nv12_frame(width, height, step), step == 0)
.expect("encode a picture");
let exported = exporting
.decode_exported(&unit, step as u64)
.expect("decode to a descriptor");
let downloaded = downloading.decode(&unit, step as u64).expect("decode to client memory");
assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
for (gpu, cpu) in exported.iter().zip(&downloaded) {
let read_back = gpu.download().expect("read the exported surface back");
assert!(read_back.data == cpu.data, "picture {} came back wrong", gpu.timestamp);
compared += 1;
}
}
assert!(compared > 0, "the decoder produced no pictures");
let pool = &exporting.sequence().expect("a sequence").pool;
let allocated = pool.allocated.get();
eprintln!("{allocated} surfaces allocated for {PICTURES} exported pictures");
assert!(
allocated <= pool.free.capacity,
"{allocated} surfaces for {PICTURES} pictures; a full DPB and the picture in flight need {}",
pool.free.capacity
);
}
#[test]
#[ignore = "requires a VA-API render node"]
fn the_pool_keeps_a_bounded_number_of_free_surfaces() {
const HELD: u32 = 40;
let (width, height) = (320u32, 240u32);
let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
let mut step = 0;
let mut decode = |decoder: &mut Decoder| {
let unit = encoder
.encode_nv12(&nv12_frame(width, height, step), step == 0)
.expect("encode a picture");
step += 1;
decoder.decode_exported(&unit, step as u64).expect("decode a picture")
};
let mut held = Vec::new();
for _ in 0..HELD {
held.extend(decode(&mut decoder));
}
let pool = &decoder.sequence().expect("a sequence").pool;
let allocated = pool.allocated.get();
assert!(
allocated >= held.len(),
"{} pictures held on {allocated} surfaces",
held.len()
);
drop(held);
let free = pool.free.surfaces.lock().unwrap().len();
assert!(
free <= pool.free.capacity,
"{free} surfaces left free, more than the capacity of {}",
pool.free.capacity
);
for _ in 0..10 {
drop(decode(&mut decoder));
}
let pool = &decoder.sequence().expect("a sequence").pool;
assert_eq!(
pool.allocated.get(),
allocated,
"pictures after the release did not reuse the free surfaces"
);
}
#[test]
fn an_exported_frame_is_send_and_sync() {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<ExportedFrame>();
}
#[test]
#[ignore = "requires a VA-API render node"]
fn an_exported_picture_downloads_to_the_same_pixels() {
let (width, height) = (320u32, 240u32);
let mut encoder = crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
let mut exporting = Decoder::new(config()).expect("no VA-API H.264 decoder");
let mut downloading = Decoder::new(config()).expect("a second decoder");
let mut exported = Vec::new();
let mut downloaded = Vec::new();
for step in 0..8 {
let unit = encoder
.encode_nv12(&nv12_frame(width, height, step), step == 0)
.expect("encode a picture");
exported.extend(
exporting
.decode_exported(&unit, step as u64)
.expect("decode to a descriptor"),
);
downloaded.extend(downloading.decode(&unit, step as u64).expect("decode to client memory"));
}
exported.extend(exporting.flush_exported().expect("flush the exporting decoder"));
downloaded.extend(downloading.flush().expect("flush the downloading decoder"));
assert!(!exported.is_empty(), "the decoder produced no pictures");
assert_eq!(exported.len(), downloaded.len(), "the two decoders disagreed");
for (index, (gpu, cpu)) in exported.iter().zip(&downloaded).enumerate() {
let read_back = gpu.download().expect("read the exported surface back");
assert_eq!(read_back.timestamp, cpu.timestamp, "picture {index} lost its timestamp");
assert_eq!((read_back.width, read_back.height), (cpu.width, cpu.height));
assert!(
read_back.data == cpu.data,
"picture {index} read back differently than it downloaded"
);
}
}
#[test]
#[ignore = "requires a VA-API render node and FFmpeg"]
fn decoded_pictures_match_a_software_decoder() {
const PICTURES: usize = 30;
for codec in [Codec::H264, Codec::H265] {
for (width, height) in [(320u32, 240u32), (852, 478)] {
let Some(stream) = software_encode(codec, (width, height), PICTURES, true) else {
panic!("no ffmpeg that encodes {codec:?}");
};
let reference = software_decode(codec, &stream);
let picture_len = (width * height * 3 / 2) as usize;
assert_eq!(
reference.len(),
PICTURES * picture_len,
"ffmpeg decoded a different count"
);
let Ok(mut decoder) = Decoder::new(Config { codec, ..config() }) else {
panic!("no VA-API {codec:?} decoder");
};
let units = split_access_units(codec, &stream);
let mut decoded = Vec::new();
for (index, unit) in units.iter().enumerate() {
if index % 2 == 0 {
decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
} else {
for exported in decoder
.decode_exported(unit, index as u64)
.expect("decode an access unit")
{
decoded.push(exported.download().expect("download an exported picture"));
}
}
}
decoded.extend(decoder.flush().expect("flush the decoder"));
assert_eq!(decoded.len(), PICTURES, "{codec:?} lost or invented pictures");
let mut timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
assert!(
timestamps.windows(2).any(|pair| pair[0] > pair[1]),
"the {codec:?} stream came out in decode order, so nothing here tests reordering"
);
timestamps.sort_unstable();
assert_eq!(
timestamps,
(0..PICTURES as u64).collect::<Vec<_>>(),
"a {codec:?} picture's timestamp did not survive reordering"
);
for (index, picture) in decoded.iter().enumerate() {
assert_eq!((picture.width, picture.height), (width, height));
assert!(
picture.data == reference[index * picture_len..][..picture_len],
"{codec:?} picture {index} of {PICTURES} at {width}x{height} differs from the software decoder"
);
}
}
}
}
#[test]
#[ignore = "requires a VA-API render node and FFmpeg"]
fn h264_coding_tools_match_a_software_decoder() {
const PICTURES: usize = 40;
let (width, height) = (852u32, 478u32);
let source = format!("testsrc2=size={width}x{height}:rate=30,fade=in:0:20,fade=out:25:15");
let pictures = PICTURES.to_string();
#[rustfmt::skip]
let stream = ffmpeg(&[
"-f", "lavfi", "-i", &source, "-frames:v", &pictures, "-pix_fmt", "yuv420p",
"-c:v", "libx264", "-profile:v", "high", "-bf", "3", "-refs", "4", "-g", "20",
"-x264-params", "slices=3:weightp=2:weightb=1:cqm=jvt:b-pyramid=strict:log-level=error",
"-f", "h264", "-",
])
.expect("no ffmpeg that encodes H.264");
let reference = software_decode(Codec::H264, &stream);
let picture_len = (width * height * 3 / 2) as usize;
assert_eq!(
reference.len(),
PICTURES * picture_len,
"ffmpeg decoded a different count"
);
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
let mut decoded = Vec::new();
for (index, unit) in split_access_units(Codec::H264, &stream).iter().enumerate() {
decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
}
decoded.extend(decoder.flush().expect("flush the decoder"));
assert_eq!(decoded.len(), PICTURES, "lost or invented pictures");
for (index, picture) in decoded.iter().enumerate() {
assert!(
picture.data == reference[index * picture_len..][..picture_len],
"picture {index} differs from the software decoder"
);
}
}
#[test]
#[ignore = "requires a VA-API render node and FFmpeg"]
fn h265_without_reordering_comes_out_as_it_decodes() {
const PICTURES: usize = 10;
let stream = software_encode(Codec::H265, (320, 240), PICTURES, false).expect("no ffmpeg that encodes H.265");
let mut decoder = Decoder::new(Config {
codec: Codec::H265,
..config()
})
.expect("no VA-API H.265 decoder");
for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
let decoded = decoder.decode(unit, index as u64).expect("decode an access unit");
let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
assert_eq!(timestamps, [index as u64], "access unit {index} was held back");
}
assert!(decoder.flush().expect("flush the decoder").is_empty());
}
#[test]
#[ignore = "requires a VA-API render node and FFmpeg"]
fn a_4k_h265_wavefront_stream_decodes() {
const PICTURES: usize = 2;
let size = (3840, 2160);
let stream = software_encode(Codec::H265, size, PICTURES, false).expect("no ffmpeg that encodes H.265");
let mut decoder = Decoder::new(Config {
codec: Codec::H265,
..config()
})
.expect("no VA-API H.265 decoder");
let mut decoded = Vec::new();
for (index, unit) in split_access_units(Codec::H265, &stream).iter().enumerate() {
decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
}
decoded.extend(decoder.flush().expect("flush the decoder"));
assert_eq!(decoded.len(), PICTURES);
assert!(decoded.iter().all(|picture| (picture.width, picture.height) == size));
}
#[test]
#[ignore = "requires a VA-API render node and FFmpeg"]
fn a_new_h265_sequence_decodes_at_its_own_size() {
const PER_SEQUENCE: usize = 6;
let sizes = [(320u32, 240u32), (192u32, 144u32)];
let mut stream = Vec::new();
for &size in &sizes {
let sequence =
software_encode(Codec::H265, size, PER_SEQUENCE, true).expect("no ffmpeg that encodes H.265");
stream.extend(sequence);
}
let mut decoder = Decoder::new(Config {
codec: Codec::H265,
..config()
})
.expect("no VA-API H.265 decoder");
let mut decoded = Vec::new();
let units = split_access_units(Codec::H265, &stream);
for (index, unit) in units.iter().enumerate() {
decoded.extend(decoder.decode(unit, index as u64).expect("decode an access unit"));
}
decoded.extend(decoder.flush().expect("flush the decoder"));
let expected: Vec<(u32, u32)> = sizes
.iter()
.flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE))
.collect();
let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
for picture in &decoded {
let expected_len = (picture.width * picture.height * 3 / 2) as usize;
assert_eq!(
picture.data.len(),
expected_len,
"a picture was read back at the wrong size"
);
}
}
#[test]
#[ignore = "requires a VA-API render node"]
fn a_new_sequence_decodes_at_its_own_size() {
const PER_SEQUENCE: u32 = 6;
let sizes = [(320u32, 240u32), (192u32, 144u32)];
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
let mut decoded = Vec::new();
let mut timestamp = 0u64;
for &(width, height) in &sizes {
let mut encoder =
crate::encode::Encoder::new(encoder_config(width, height)).expect("no VA-API H.264 encoder");
for step in 0..PER_SEQUENCE {
let unit = encoder
.encode_nv12(&nv12_frame(width, height, step), step == 0)
.expect("encode a picture");
decoded.extend(decoder.decode(&unit, timestamp).expect("decode a picture"));
timestamp += 1;
}
}
decoded.extend(decoder.flush().expect("flush the decoder"));
let expected: Vec<(u32, u32)> = sizes
.iter()
.flat_map(|&size| std::iter::repeat_n(size, PER_SEQUENCE as usize))
.collect();
let actual: Vec<(u32, u32)> = decoded.iter().map(|picture| (picture.width, picture.height)).collect();
assert_eq!(actual, expected, "a picture came out at the wrong size or out of order");
let timestamps: Vec<u64> = decoded.iter().map(|picture| picture.timestamp).collect();
assert_eq!(timestamps, (0..timestamp).collect::<Vec<_>>());
for picture in &decoded {
let expected_len = (picture.width * picture.height * 3 / 2) as usize;
assert_eq!(
picture.data.len(),
expected_len,
"a picture was read back at the wrong size"
);
}
}
#[test]
#[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
fn a_refused_sequence_resumes_once_sent_again() {
let (width, height) = (320u32, 240u32);
let stream = software_encode(Codec::H264, (width, height), 4, false).expect("no ffmpeg that encodes H.264");
let units = split_access_units(Codec::H264, &stream);
let source = format!("testsrc2=size={width}x{height}:rate=30");
#[rustfmt::skip]
let high422 = ffmpeg(&[
"-f", "lavfi", "-i", &source, "-frames:v", "1", "-pix_fmt", "yuv422p",
"-c:v", "libx264", "-profile:v", "high422", "-f", "h264", "-",
])
.expect("no ffmpeg that encodes H.264 4:2:2");
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
decoder.decode(&units[0], 0).expect("decode the IDR");
let refused = decoder.decode(&high422, 1).expect_err("a 4:2:2 slice decodes");
assert!(format!("{refused:#}").contains("SPS 0: unsupported"), "{refused:#}");
let stale = decoder
.decode(&units[1], 2)
.expect_err("a slice decoded against a replaced SPS");
assert!(format!("{stale:#}").contains("Slice"), "{stale:#}");
decoder.decode(&units[0], 3).expect("decode the resent IDR");
}
#[test]
#[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
fn sequences_outside_the_scope_are_refused() {
let source = "testsrc2=size=320x240:rate=30";
#[rustfmt::skip]
let streams = [
&["-flags", "+ildct+ilme", "-x264-params", "interlaced=1", "-pix_fmt", "yuv420p"][..],
&["-pix_fmt", "yuv420p10le", "-profile:v", "high10"][..],
];
for args in streams {
let mut command = vec!["-f", "lavfi", "-i", source, "-frames:v", "2", "-c:v", "libx264"];
command.extend_from_slice(args);
command.extend_from_slice(&["-f", "h264", "-"]);
let stream = ffmpeg(&command).expect("no ffmpeg that encodes H.264");
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
let refused = decoder.decode(&stream, 0).expect_err("decoded out of scope");
assert!(format!("{refused:#}").contains("SPS 0: unsupported"), "{refused:#}");
}
}
#[test]
#[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
fn a_pps_outlasts_a_sequence_that_cant_read_it() {
let annex_b = |nals: &[&[u8]]| {
nals.iter()
.flat_map(|nal| [&[0, 0, 0, 1][..], nal].concat())
.collect::<Vec<u8>>()
};
let nals = |stream: &[u8]| {
let mut rest = stream;
let mut nals = Vec::new();
while let Some(nal) = kodecs_h264::split_annex_b(&mut rest, usize::MAX).unwrap() {
nals.push((Nalu::new(nal, usize::MAX).unwrap().header.type_, nal.to_vec()));
}
nals
};
let of = |nals: &[(NaluType, Vec<u8>)], type_| -> Vec<Vec<u8>> {
nals.iter()
.filter(|(t, _)| *t == type_)
.map(|(_, nal)| nal.clone())
.collect()
};
let encode = |pix_fmt| {
let source = "testsrc2=size=320x240:rate=30";
#[rustfmt::skip]
let args = ["-f", "lavfi", "-i", source, "-frames:v", "1", "-c:v", "libx264", "-pix_fmt", pix_fmt, "-f", "h264", "-"];
nals(&ffmpeg(&args).expect("no ffmpeg that encodes H.264"))
};
let first = encode("yuv420p");
let (sps, pps, idr) = (
&of(&first, NaluType::Sps)[0],
&of(&first, NaluType::Pps)[0],
of(&first, NaluType::SliceIdr),
);
let idr: Vec<&[u8]> = idr.iter().map(Vec::as_slice).collect();
let mut parser = Parser::new(usize::MAX);
parser.parse(sps).unwrap();
parser.parse(pps).unwrap();
let mut scaled = Pps::clone(parser.pps(0).unwrap());
assert!(scaled.transform_8x8_mode);
scaled.scaling = Some(Matrix {
lists_4x4: vec![16; 96],
lists_8x8: vec![16; 128],
});
let mut scaled_pps = Vec::new();
scaled.write(3, &mut scaled_pps).unwrap();
let sps_444 = &of(&encode("yuv444p"), NaluType::Sps)[0];
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
let unit = [annex_b(&[sps]), scaled_pps, annex_b(&idr)].concat();
decoder.decode(&unit, 0).expect("decode the IDR");
decoder.decode(&annex_b(&[sps_444]), 1).expect("take the 4:4:4 SPS");
let refused = decoder
.decode(&annex_b(&idr), 2)
.expect_err("decoded against the 4:4:4 SPS");
assert!(format!("{refused:#}").contains("missing parameter set"), "{refused:#}");
decoder
.decode(&[annex_b(&[sps]), annex_b(&idr)].concat(), 3)
.expect("decode the IDR once its sequence is back");
}
#[test]
#[ignore = "requires a VA-API H.264 decoder, and ffmpeg with libx264"]
fn a_refused_pps_leaves_the_other_sets_usable() {
let stream = software_encode(Codec::H264, (320, 240), 4, false).expect("no ffmpeg that encodes H.264");
let units = split_access_units(Codec::H264, &stream);
let mut decoder = Decoder::new(config()).expect("no VA-API H.264 decoder");
let mut decoded = decoder.decode(&units[0], 0).expect("decode the IDR");
let refused = decoder
.decode(&[0, 0, 0, 1, 0x68, 0b0100_1010], 1)
.expect_err("a PPS naming a missing SPS decodes");
assert!(format!("{refused:#}").contains("Pps"), "{refused:#}");
for (timestamp, unit) in (2..).zip(&units[1..]) {
decoded.extend(
decoder
.decode(unit, timestamp)
.expect("decode a picture after the refused PPS"),
);
}
decoded.extend(decoder.flush().expect("flush the decoder"));
assert_eq!(decoded.len(), units.len());
}
fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
let output = Command::new("ffmpeg").arg("-v").arg("error").args(args).output().ok()?;
if !output.status.success() {
eprintln!("ffmpeg {args:?} failed: {}", String::from_utf8_lossy(&output.stderr));
return None;
}
Some(output.stdout)
}
fn software_encode(codec: Codec, (width, height): (u32, u32), pictures: usize, reorder: bool) -> Option<Vec<u8>> {
let source = format!("testsrc2=size={width}x{height}:rate=30");
let pictures = pictures.to_string();
let mut args = vec![
"-f",
"lavfi",
"-i",
&source,
"-frames:v",
&pictures,
"-pix_fmt",
"yuv420p",
];
let x265;
match codec {
Codec::H264 => args.extend([
"-c:v",
"libx264",
"-profile:v",
"main",
"-bf",
if reorder { "2" } else { "0" },
"-refs",
if reorder { "3" } else { "1" },
"-g",
"15",
"-f",
"h264",
]),
Codec::H265 => {
x265 = if reorder {
"bframes=2:ref=3:keyint=15:min-keyint=15:log-level=error"
} else {
"bframes=0:ref=1:keyint=15:min-keyint=15:log-level=error"
};
args.extend(["-c:v", "libx265", "-x265-params", x265, "-f", "hevc"]);
}
}
args.push("-");
ffmpeg(&args)
}
fn software_decode(codec: Codec, stream: &[u8]) -> Vec<u8> {
static COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let count = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let extension = match codec {
Codec::H264 => "264",
Codec::H265 => "265",
};
let path = std::env::temp_dir().join(format!(
"kodecs-vaapi-decode-{}-{count}.{extension}",
std::process::id()
));
std::fs::write(&path, stream).expect("write the elementary stream");
let decoded = ffmpeg(&[
"-i",
path.to_str().expect("a UTF-8 temporary path"),
"-pix_fmt",
"nv12",
"-f",
"rawvideo",
"-",
]);
let _ = std::fs::remove_file(&path);
decoded.expect("ffmpeg decodes what it just encoded")
}
fn split_access_units(codec: Codec, stream: &[u8]) -> Vec<Vec<u8>> {
let starts: Vec<usize> = (0..stream.len().saturating_sub(3))
.filter(|&i| stream[i..i + 3] == [0, 0, 1])
.collect();
let mut units = Vec::new();
let mut current: Vec<u8> = Vec::new();
let mut current_has_picture = false;
for (index, &start) in starts.iter().enumerate() {
let end = starts.get(index + 1).copied().unwrap_or(stream.len());
let nal = &stream[start + 3..end];
let (is_slice, starts_picture, starts_unit) = match codec {
Codec::H264 => {
let nal_type = nal[0] & 0x1f;
let is_slice = (1..=5).contains(&nal_type);
(is_slice, is_slice && nal[1] & 0x80 != 0, matches!(nal_type, 6..=9))
}
Codec::H265 => {
let nal_type = (nal[0] >> 1) & 0x3f;
let is_slice = nal_type <= 31;
(
is_slice,
is_slice && nal[2] & 0x80 != 0,
matches!(nal_type, 32..=35 | 39),
)
}
};
if current_has_picture && (starts_picture || starts_unit) {
units.push(std::mem::take(&mut current));
current_has_picture = false;
}
current.extend_from_slice(&stream[start..end]);
current_has_picture |= is_slice;
}
if !current.is_empty() {
units.push(current);
}
units
}
fn inode(fd: &OwnedFd) -> u64 {
use std::os::unix::fs::MetadataExt as _;
let file = std::fs::File::from(fd.try_clone().expect("duplicate the descriptor"));
file.metadata().expect("stat the descriptor").ino()
}
}