diff --git a/crates/ec-h265-syntax/src/sei.rs b/crates/ec-h265-syntax/src/sei.rs index 815063dd..798ef4ca 100644 --- a/crates/ec-h265-syntax/src/sei.rs +++ b/crates/ec-h265-syntax/src/sei.rs @@ -11,7 +11,6 @@ //! RBSP, and refuses a malformed one rather than guessing. use crate::md5::Md5; -use crate::nal::{NalHeader, NalUnitType}; use crate::ps::rbsp_trailing_bits; use ec_core::bitio::BitWriter; use ec_core::color::ContentLight; @@ -48,19 +47,14 @@ fn sei_rbsp(messages: &[(u32, Vec)]) -> Vec { } /// The prefix SEI RBSP describing HDR mastering metadata, or `None` when there -/// is nothing to say. +/// is nothing to say. When `display` is given it is written verbatim (chromaticities +/// and luminances), and the mastering pair inside `light` is ignored. The content light +/// level comes from `light`. /// /// Both messages are written whole or not at all: a `mastering_display_colour_volume` /// with a zero luminance pair is what the oracle writes when it knows nothing, and a /// tone map that believes it maps the film to black. -pub fn hdr_metadata_rbsp(light: ContentLight) -> Option> { - hdr_metadata_rbsp_with(None, light) -} - -/// [`hdr_metadata_rbsp`] with an explicit mastering display: when `display` is -/// given it is written verbatim (chromaticities and luminances), and the mastering -/// pair inside `light` is ignored. The content light level comes from `light`. -pub fn hdr_metadata_rbsp_with( +pub fn hdr_metadata_rbsp( display: Option, light: ContentLight, ) -> Option> { @@ -126,16 +120,6 @@ pub fn decoded_picture_hash_rbsp(planes: &[(&[u8], usize, usize, usize)]) -> Vec sei_rbsp(&[(PAYLOAD_DECODED_PICTURE_HASH, payload)]) } -/// The NAL header a prefix SEI travels under. -pub fn prefix_sei_header() -> NalHeader { - NalHeader::new(NalUnitType::PrefixSei) -} - -/// The NAL header a suffix SEI (the picture hash) travels under. -pub fn suffix_sei_header() -> NalHeader { - NalHeader::new(NalUnitType::SuffixSei) -} - /// `payloadType` of the alternative transfer characteristics message (D.2.x). const PAYLOAD_ALTERNATIVE_TRANSFER: u32 = 147; @@ -373,16 +357,21 @@ mod tests { mastering_min: Some(0.005), ..ContentLight::default() }; - let rbsp = hdr_metadata_rbsp(light).unwrap(); + let rbsp = hdr_metadata_rbsp(None, light).unwrap(); let mut annex_b = Vec::new(); - crate::nal::write_annex_b(&mut annex_b, prefix_sei_header(), &rbsp, true); + crate::nal::write_annex_b( + &mut annex_b, + crate::nal::NalHeader::new(crate::nal::NalUnitType::PrefixSei), + &rbsp, + true, + ); // ec-core's reader is the consumer this exists for. let read = ec_core::color::hevc_sei_light(&annex_b); assert_eq!(read.max_cll, Some(1000.0)); assert_eq!(read.max_fall, Some(400.0)); assert_eq!(read.mastering_max, Some(1000.0)); assert_eq!(read.mastering_min, Some(0.005)); - assert!(hdr_metadata_rbsp(ContentLight::default()).is_none()); + assert!(hdr_metadata_rbsp(None, ContentLight::default()).is_none()); } #[test] diff --git a/crates/ec-h265-syntax/tests/sei_sweep.rs b/crates/ec-h265-syntax/tests/sei_sweep.rs deleted file mode 100644 index e96c8749..00000000 --- a/crates/ec-h265-syntax/tests/sei_sweep.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! The SEI reader over the JCT-VC conformance streams. -//! -//! Every prefix and suffix SEI NAL unit of every stream must parse without error, - -use std::path::{Path, PathBuf}; - -use ec_h265_syntax::nal::split_annex_b; -use ec_h265_syntax::sei::{SeiMessage, parse_sei_rbsp}; - -fn streams() -> Vec { - let root = ec_testkit::fixture("vectors/hevc-jctvc"); - fn walk(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - walk(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let mut out = Vec::new(); - walk(&root, 2, &mut out); - out -} - -#[test] -fn every_sei_in_the_conformance_streams_parses() { - let streams = streams(); - assert!(!streams.is_empty(), "no streams under vectors/hevc-jctvc"); - let mut with_hash = 0usize; - let mut hash_streams = Vec::new(); - let mut sei_nals = 0usize; - let mut messages = 0usize; - let mut hashes = 0usize; - let mut failures = Vec::new(); - for path in &streams { - let name = path.file_name().unwrap_or_default().to_string_lossy().to_string(); - let data = match std::fs::read(path) { - Ok(d) => d, - Err(e) => { - failures.push(format!("{name}: read: {e}")); - continue; - } - }; - let mut stream_hashes = 0usize; - for nal in split_annex_b(&data) { - if nal.header.layer_id > 0 || !matches!(nal.header.nal_type.code(), 39 | 40) { - continue; - } - sei_nals += 1; - match parse_sei_rbsp(&nal.rbsp()) { - Ok(msgs) => { - messages += msgs.len(); - for msg in &msgs { - if matches!(msg, SeiMessage::DecodedPictureHash(_)) { - stream_hashes += 1; - } - } - } - Err(e) => failures.push(format!("{name}: SEI NAL #{sei_nals}: {e}")), - } - } - if stream_hashes > 0 { - with_hash += 1; - hash_streams.push(name.clone()); - } - hashes += stream_hashes; - } - eprintln!( - "SEI sweep: {} streams, {with_hash} carry decoded_picture_hash ({hashes} hash messages), \ - {sei_nals} SEI NAL units, {messages} messages, {} parse failures", - streams.len(), - failures.len() - ); - eprintln!("streams with decoded_picture_hash: {}", hash_streams.join(" ")); - assert!(failures.is_empty(), "SEI that failed to parse:\n{}", failures.join("\n")); - assert!(with_hash > 0, "no conformance stream carries decoded_picture_hash SEI"); -} diff --git a/crates/ec-h265/Cargo.toml b/crates/ec-h265/Cargo.toml index 4e42e6b7..41b2d4c9 100644 --- a/crates/ec-h265/Cargo.toml +++ b/crates/ec-h265/Cargo.toml @@ -16,4 +16,3 @@ multiversion = "0.9" [dev-dependencies] ec-testkit.workspace = true -ec-h265-syntax.workspace = true diff --git a/crates/ec-h265/src/dec/amvp.rs b/crates/ec-h265/src/dec/amvp.rs index ffd1a917..a9546c43 100644 --- a/crates/ec-h265/src/dec/amvp.rs +++ b/crates/ec-h265/src/dec/amvp.rs @@ -146,233 +146,3 @@ fn wrap16(v: i32) -> i16 { let signed = if u >= 1 << 15 { u - (1 << 16) } else { u }; signed as i16 } - -#[cfg(test)] -mod tests { - use super::super::cu_syntax::InterPredIdc; - use super::super::motion_field::{MotionField, MotionParams, SliceRefs, test_shared}; - use super::super::rps::{RefEntry, RefPicLists}; - use super::super::shared::SharedPic; - use super::*; - use std::sync::Arc; - - fn entry(id: u32, poc: i32, long_term: bool) -> RefEntry { - RefEntry { id, poc, long_term } - } - - fn params(temporal: bool) -> MotionParams { - MotionParams { - is_b: false, - max_merge_cand: 5, - log2_par_mrg_level: 2, - ctb_log2: 6, - collocated_from_l0: true, - temporal_mvp: temporal, - no_backward_pred: true, - } - } - - fn l0(ref_idx: i8, mv: [i16; 2]) -> PbMotion { - PbMotion::new([true, false], [ref_idx, -1], [mv, [0, 0]]) - } - - /// An AMVP PU at (16,16) of size 16x16 with list 0, reference `ref_idx` and - /// difference `mvd`, using predictor `flag`. - fn pu(mvd: [i32; 2], flag: u8) -> PredictionUnit { - PredictionUnit { - x: 16, - y: 16, - width: 16, - height: 16, - inter_pred_idc: InterPredIdc::PredL0, - mvp_flag: [flag, 0], - mvd: [mvd, [0, 0]], - ..PredictionUnit::default() - } - } - - /// Run the AMVP derivation for `pu` with `field` as the current motion field. - fn run( - field: &mut MotionField, - lists: &RefPicLists, - cur_poc: i32, - col: Option>, - temporal: bool, - pu: &PredictionUnit, - ) -> PbMotion { - let src = SliceMotion { - params: params(temporal), - lists, - cur_poc, - field, - col, - publish: None, - slice: 0, - }; - derive_amvp(&src, pu) - } - - fn lists(poc: i32, long_term: bool) -> RefPicLists { - RefPicLists { - l0: vec![entry(0, poc, long_term)], - l1: Vec::new(), - } - } - - #[test] - fn spatial_a_with_the_same_reference_is_used_unscaled() { - // A1 = (15,31) refers to POC 4, the target. Its vector is the predictor. - let mut field = MotionField::new(64, 64); - field.store(0, 16, 16, 16, 0, l0(0, [40, -12])); - let got = run(&mut field, &lists(4, false), 8, None, false, &pu([1, 1], 0)); - assert_eq!(got, l0(0, [41, -11])); - } - - #[test] - fn spatial_a_scales_by_distance() { - // Current POC 8, target POC 4 (tb = 4). A1 refers to POC 0 (td = 8), mv 64: - // tx = (16384 + 4) / 8 = 2048, dsf = (4 * 2048 + 32) >> 6 = 128, mv' = 32. - // L0[0] is the target (POC 4); the neighbour uses L0[1] (POC 0). - let lists = RefPicLists { - l0: vec![entry(0, 4, false), entry(1, 0, false)], - l1: Vec::new(), - }; - let mut field = MotionField::new(64, 64); - field.store(0, 16, 16, 16, 0, l0(1, [64, 0])); - let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0)); - assert_eq!(got, l0(0, [32, 0])); - } - - #[test] - fn spatial_a_scales_with_negative_distance() { - // Current POC 8, target POC 4 (tb = 4). A1 refers to POC 12 (td = -4), mv 64: - // tx = (16384 + 2) / -4 = -4096, dsf = (4 * -4096 + 32) >> 6 = -256, - // mv' = -64. - let lists = RefPicLists { - l0: vec![entry(0, 4, false), entry(1, 12, false)], - l1: Vec::new(), - }; - let mut field = MotionField::new(64, 64); - field.store(0, 16, 16, 16, 0, l0(1, [64, 0])); - let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0)); - assert_eq!(got, l0(0, [-64, 0])); - } - - #[test] - fn long_term_neighbour_is_not_scaled() { - // The target is long-term (POC 4) and so is the neighbour's reference (POC 0): - // the vector is used as it is. - let lists = RefPicLists { - l0: vec![entry(0, 4, true), entry(1, 0, true)], - l1: Vec::new(), - }; - let mut field = MotionField::new(64, 64); - field.store(0, 16, 16, 16, 0, l0(1, [64, 0])); - let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0)); - assert_eq!(got, l0(0, [64, 0])); - } - - #[test] - fn long_term_mismatch_skips_the_neighbour() { - // The target is long-term but the neighbour's reference is short-term: the - // neighbour gives no predictor, and the list is zero-filled. - let lists = RefPicLists { - l0: vec![entry(0, 4, true), entry(1, 0, false)], - l1: Vec::new(), - }; - let mut field = MotionField::new(64, 64); - field.store(0, 16, 16, 16, 0, l0(1, [64, 0])); - let got = run(&mut field, &lists, 8, None, false, &pu([0, 0], 0)); - assert_eq!(got, l0(0, [0, 0])); - } - - #[test] - fn b_candidate_fills_the_a_slot_when_no_a_neighbour() { - // No A neighbour. B1 = (31,15) refers to the target POC 4: it fills the A slot, - // and the second B pass scales it back to itself (td = tb), so the list is - // [B, 0] and flag 0 picks B. - let mut field = MotionField::new(64, 64); - field.store(16, 0, 16, 16, 0, l0(0, [20, 6])); - let got = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 0)); - assert_eq!(got, l0(0, [20, 6])); - let other = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 1)); - assert_eq!(other, l0(0, [0, 0])); - } - - #[test] - fn equal_a_and_b_collapse_to_one_predictor() { - // A1 and B1 carry the same vector toward the target: the list is [A, 0]. - let mut field = MotionField::new(64, 64); - field.store(0, 16, 16, 16, 0, l0(0, [7, 7])); - field.store(16, 0, 16, 16, 0, l0(0, [7, 7])); - let got = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 1)); - assert_eq!(got, l0(0, [0, 0])); - let first = run(&mut field, &lists(4, false), 8, None, false, &pu([0, 0], 0)); - assert_eq!(first, l0(0, [7, 7])); - } - - #[test] - fn temporal_fills_the_second_slot() { - // A1 gives one predictor, so the collocated vector is the second. The collocated - // picture is POC 8 with a vector toward POC 4 (td = 4), and the target is POC 4 - // (tb = 4): no scaling. - let mut col_field = MotionField::new(64, 64); - col_field.slices.push(SliceRefs { - poc: [vec![4], vec![]], - long_term: [vec![false], vec![]], - }); - col_field.store(32, 32, 16, 16, 0, l0(0, [-9, 5])); - let col = test_shared(&col_field, 8); - let mut field = MotionField::new(64, 64); - field.store(0, 16, 16, 16, 0, l0(0, [1, 1])); - let got = run( - &mut field, - &lists(4, false), - 8, - Some(col), - true, - &pu([0, 0], 1), - ); - assert_eq!(got, l0(0, [-9, 5])); - } - - #[test] - fn mv_wraps_at_sixteen_bits() { - // mvp 32000 plus mvd 1000 is 33000, which wraps to 33000 - 65536 = -32536. - // mvp -32000 plus mvd -1000 is -33000, which wraps to 32536. - assert_eq!(wrap16(33000), -32536); - assert_eq!(wrap16(-33000), 32536); - // The boundaries: 32767 stays, 32768 becomes -32768. - assert_eq!(wrap16(32767), 32767); - assert_eq!(wrap16(32768), -32768); - assert_eq!(wrap16(-32768), -32768); - assert_eq!(wrap16(-32769), 32767); - } - - #[test] - fn mvd_wrap_through_the_full_derivation() { - let mut field = MotionField::new(64, 64); - field.store(0, 16, 16, 16, 0, l0(0, [32000, -32000])); - let got = run( - &mut field, - &lists(4, false), - 8, - None, - false, - &pu([1000, -1000], 0), - ); - assert_eq!(got, l0(0, [-32536, 32536])); - } - - #[test] - fn scale_mv_with_negative_and_positive_distances() { - // tb / td = 1/2 with td > 0: half the vector. - assert_eq!(scale_mv([64, 0], 4, 2), [32, 0]); - // td < 0, tb > 0: the vector flips. - assert_eq!(scale_mv([64, 0], -4, 4), [-64, 0]); - // Both negative, ratio 1: the vector is unchanged. - assert_eq!(scale_mv([-30, 7], -4, -4), [-30, 7]); - // The result is clipped to 16 bits. - assert_eq!(scale_mv([32767, 0], 1, 127), [32767, 0]); - } -} diff --git a/crates/ec-h265/src/dec/cu_syntax.rs b/crates/ec-h265/src/dec/cu_syntax.rs index 299031fd..c5783aa4 100644 --- a/crates/ec-h265/src/dec/cu_syntax.rs +++ b/crates/ec-h265/src/dec/cu_syntax.rs @@ -1,14 +1,11 @@ -//! CABAC syntax of slice data for P and B slices (and for I slices when the -//! syntax check runs): coding quadtree, coding units, prediction units, the +//! CABAC syntax of slice data for I, P and B slices: coding quadtree, coding units, prediction units, the //! transform tree, SAO parameters and the slice-segment loop (H.265 7.3.8.1 to //! 7.3.8.12, bin binarisations of 9.3.3 and context selection of 9.3.4.2). //! //! The parser reads every bin, keeps the syntax of each coding unit, and turns //! each transform block's coefficients into residual samples through the same //! dequantisation and inverse transform the intra path uses. It does not -//! predict. Motion for each prediction unit comes from a [`MotionSource`]; the -//! merge and AMVP lane implements that trait, and [`ZeroMotion`] stands in until -//! then. +//! predict. Motion for each prediction unit comes from a [`SliceMotion`]. //! //! Slices, slice segments, tiles and wavefront substreams are followed: CTBs //! are visited in tile scan order, contexts are initialised, synced or restored @@ -17,7 +14,7 @@ use super::inter::{self, InterRefs}; use super::mc::{Block, McScratch}; -use super::motion_field::MotionField; +use super::motion_field::SliceMotion; use super::pic::{BlockInfo, CtbInfo, EDGE_PU, EDGE_TU, PicState, SaoParams, SliceFilter}; use super::rext; use super::tiles::TileScan; @@ -93,7 +90,7 @@ pub struct PredictionUnit { pub mvd: [[i32; 2]; 2], } -/// Motion of one prediction unit, as a [`MotionSource`] returns it. +/// Motion of one prediction unit, as [`SliceMotion::derive_motion`] returns it. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Motion { /// `predFlagLX` for list 0 and list 1. @@ -104,75 +101,6 @@ pub struct Motion { pub mv: [[i32; 2]; 2], } -/// The geometry of a coding unit, as a [`MotionSource`] needs it. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct CuGeometry { - /// Luma position of the coding unit. - pub x: usize, - /// Luma position of the coding unit. - pub y: usize, - /// Luma size of the coding unit. - pub size: usize, - /// The partitioning. - pub part_mode: PartMode, - /// Whether the coding unit is skipped. - pub skip: bool, -} - -/// Derives the motion of each prediction unit. Called once per unit, in decoding -/// order, after the unit's syntax has been parsed (so merge candidates from -/// earlier units are available to the implementation). Merge and AMVP derivation -/// (8.5.3) is the job of the implementation; the parser does not look inside. -pub trait MotionSource { - /// The motion of unit `pu_index` of the coding unit `cu`. - fn derive_motion(&mut self, cu: &CuGeometry, pu_index: usize, pu: &PredictionUnit) -> Motion; - - /// Called once the CTB row that ends at luma row `row_end` is fully parsed. Only - /// pictures with one tile get the call (their CTBs come in raster order). - fn row_done(&mut self, _pic: &mut PicState, _row_end: usize) {} - - /// The motion field this source writes, when it is a wavefront band (see [`wpp`]). - fn band_cells(&mut self) -> Option<&mut MotionField> { - None - } -} - -/// The placeholder [`MotionSource`]: zero motion vectors and reference index 0 for -/// every list the unit uses. Replace it with the merge/AMVP derivation. -#[derive(Clone, Copy, Debug, Default)] -pub struct ZeroMotion; - -impl MotionSource for ZeroMotion { - fn derive_motion(&mut self, _cu: &CuGeometry, _pu_index: usize, pu: &PredictionUnit) -> Motion { - let pred_flags = if pu.merge_flag { - [true, false] - } else { - match pu.inter_pred_idc { - InterPredIdc::PredL0 => [true, false], - InterPredIdc::PredL1 => [false, true], - InterPredIdc::PredBi => [true, true], - } - }; - let ref_idx = [ - if pred_flags[0] { - i8::try_from(pu.ref_idx[0]).unwrap_or(0) - } else { - -1 - }, - if pred_flags[1] { - i8::try_from(pu.ref_idx[1]).unwrap_or(0) - } else { - -1 - }, - ]; - Motion { - pred_flags, - ref_idx, - mv: [[0, 0], [0, 0]], - } - } -} - /// The residual samples of one transform block, after dequantisation and the /// inverse transform. Samples are row-major, `size * size`. #[derive(Clone, Debug, PartialEq, Eq)] @@ -212,7 +140,7 @@ pub struct CodingUnit { pub chroma_mode: u8, /// The prediction units, in order. pub pus: Vec, - /// The motion of each prediction unit, from the [`MotionSource`]. + /// The motion of each prediction unit, from [`SliceMotion`]. pub motion: Vec, /// `rqt_root_cbf` (inferred 1 for intra). pub rqt_root_cbf: bool, @@ -244,38 +172,8 @@ pub struct SliceStats { pub trailing_bits_ok: bool, } -/// Parse one slice segment's data, from the byte after its header, to -/// `end_of_slice_segment_flag`. `sink` sees every coding unit in decoding order. -/// `motion` derives the motion of each prediction unit. -/// -/// A desync shows up as an `end_of_slice_segment_flag` at the wrong CTB, or as a -/// trailing-bit pattern that is not the stop bit; both are errors. This form -/// keeps only the syntax: no samples are produced. -pub fn parse_slice( - sps: &Sps, - pps: &Pps, - header: &SliceHeader, - data: &[u8], - motion: &mut dyn MotionSource, - sink: &mut dyn FnMut(&CodingUnit), -) -> Result { - let mut pic = PicState::for_sps_pps(sps, pps, false); - parse_slice_into( - sps, - pps, - header, - data, - motion, - &mut pic, - None, - sink, - &mut |_, _| {}, - ) -} - /// Parse one slice segment's data into `pic`. The block maps are always -/// filled. When `pic` has sample planes (pixel decode), intra coding units are -/// reconstructed in decoding order, and inter coding units are predicted from +/// filled. Intra coding units are reconstructed in decoding order, and inter coding units are predicted from /// `refs` (8.5.3.3) per prediction unit, then get their residual added. #[allow(clippy::too_many_arguments)] // the slice, the picture it decodes into, and its references pub fn parse_slice_into( @@ -283,7 +181,7 @@ pub fn parse_slice_into( pps: &Pps, header: &SliceHeader, data: &[u8], - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, pic: &mut PicState, refs: Option<&InterRefs>, sink: &mut dyn FnMut(&CodingUnit), @@ -485,15 +383,15 @@ pub(super) fn trailing_bits_ok(data: &[u8], read: usize) -> bool { } /// The coding-tree walk of one slice segment, starting with `last_qp` as qPY_PREV. -fn new_parser<'a>( +fn new_parser<'a, 'm>( sps: &'a Sps, pps: &'a Pps, header: &'a SliceHeader, pic: &'a mut PicState, refs: Option<&'a InterRefs>, - motion: &'a mut dyn MotionSource, + motion: &'a mut SliceMotion<'m>, last_qp: i32, -) -> Parser<'a> { +) -> Parser<'a, 'm> { let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3; let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size; let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2; @@ -584,7 +482,7 @@ struct Cbf { } /// The coding-tree walk state for one slice segment. -struct Parser<'a> { +struct Parser<'a, 'm> { sps: &'a Sps, pps: &'a Pps, header: &'a SliceHeader, @@ -628,11 +526,11 @@ struct Parser<'a> { cu_bypass: bool, /// The chroma modes of the intra coding unit being parsed, with their DM flags. chroma_modes: ([u8; 4], [bool; 4]), - motion: &'a mut dyn MotionSource, + motion: &'a mut SliceMotion<'m>, stats: SliceStats, } -impl Parser<'_> { +impl Parser<'_, '_> { fn info_at(&self, x: usize, y: usize) -> BlockInfo { self.pic.info[self.pic.unit(x, y)] } @@ -794,15 +692,10 @@ impl Parser<'_> { if skip { self.stats.skip_cus += 1; - let geom = CuGeometry { - x: x0, - y: y0, - size: n, - part_mode: PartMode::Part2Nx2N, - skip: true, - }; let pu = self.prediction_unit(dec, x0, y0, n, n, depth, true)?; - let m = self.motion.derive_motion(&geom, 0, &pu); + let m = self + .motion + .derive_motion(x0, y0, n, PartMode::Part2Nx2N, 0, &pu); self.predict_pu(x0, y0, n, n, &m)?; cu.motion.push(m); cu.pus.push(pu); @@ -852,16 +745,9 @@ impl Parser<'_> { } else { PartMode::Part2Nx2N }; - let geom = CuGeometry { - x: x0, - y: y0, - size: n, - part_mode: cu.part_mode, - skip: false, - }; for (i, (px, py, pw, ph)) in pu_rects(cu.part_mode, x0, y0, n).into_iter().enumerate() { let pu = self.prediction_unit(dec, px, py, pw, ph, depth, false)?; - let m = self.motion.derive_motion(&geom, i, &pu); + let m = self.motion.derive_motion(x0, y0, n, cu.part_mode, i, &pu); self.predict_pu(px, py, pw, ph, &m)?; self.pic.mark_edges(px, py, pw, ph, EDGE_PU); cu.motion.push(m); @@ -890,11 +776,8 @@ impl Parser<'_> { } /// Motion-compensated prediction of one prediction unit (8.5.3.3) into the - /// picture's samples. Nothing happens without pixel decode. + /// picture's samples. fn predict_pu(&mut self, x: usize, y: usize, w: usize, h: usize, m: &Motion) -> Result<()> { - if !self.pic.has_pixels() { - return Ok(()); - } let Some(refs) = self.refs else { return Err(Error::corrupt( "HEVC decode: an inter prediction unit in a slice with no reference lists", @@ -1249,7 +1132,7 @@ impl Parser<'_> { } /// The transform unit (7.3.8.10): the QP delta, then each coded block's - /// residual. With pixel decode on, an intra block is predicted and + /// residual. An intra block is predicted and /// reconstructed here, in the order luma, Cb, Cr that its neighbours need. fn transform_unit( &mut self, @@ -1284,7 +1167,7 @@ impl Parser<'_> { { self.cu_chroma_qp_offset(dec); } - let recon = tx.intra && self.pic.has_pixels(); + let recon = tx.intra; let luma_mode = tx .intra .then(|| self.pic.info[self.pic.unit(x0, y0)].intra_mode); @@ -1680,13 +1563,11 @@ impl Parser<'_> { } else { (x0 >> sx, y0 >> sy) }; - if self.pic.has_pixels() { - let origin = self.pic.plane_origin(c); - let (stride, plane) = self.pic.plane_view_mut(c); - for j in 0..sh { - let start = (y + j - origin) * stride + x; - plane[start..start + sw].copy_from_slice(&samples[j * sw..j * sw + sw]); - } + let origin = self.pic.plane_origin(c); + let (stride, plane) = self.pic.plane_view_mut(c); + for j in 0..sh { + let start = (y + j - origin) * stride + x; + plane[start..start + sw].copy_from_slice(&samples[j * sw..j * sw + sw]); } } self.pic.update_info(x0, y0, n, n, |b| b.pcm = true); diff --git a/crates/ec-h265/src/dec/cu_syntax/wpp.rs b/crates/ec-h265/src/dec/cu_syntax/wpp.rs index 5d7d2995..d1c372c6 100644 --- a/crates/ec-h265/src/dec/cu_syntax/wpp.rs +++ b/crates/ec-h265/src/dec/cu_syntax/wpp.rs @@ -18,13 +18,12 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Condvar, Mutex, MutexGuard}; -use super::{MotionSource, SliceStats, new_parser, trailing_bits_ok}; +use super::{SliceStats, new_parser, trailing_bits_ok}; use crate::cabac::{CabacDecoder, Contexts}; use crate::dec::inter::InterRefs; use crate::dec::motion_field::{FieldCell, MotionField, SliceMotion}; use crate::dec::pic::{BlockInfo, CtbInfo, PicState, SliceFilter}; use crate::dec::tiles::TileScan; -use crate::dec::trace::{self, Phase}; use ec_core::error::{Error, Result}; use ec_h265_syntax::slice::{SliceHeader, SliceType}; use ec_h265_syntax::{Pps, Sps}; @@ -105,13 +104,11 @@ impl Board { let cw = self.width.div_ceil(1 << self.sub_x); let mut st = lock(&self.state); let slot = &mut st.slots[ry]; - if pic.has_pixels() { - let lr = (y0 + ctb - 1) - pic.origin_y; - slot.luma = pic.planes.y[lr * self.width..(lr + 1) * self.width].to_vec(); - let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c; - slot.cb = pic.planes.cb[lc * cw..(lc + 1) * cw].to_vec(); - slot.cr = pic.planes.cr[lc * cw..(lc + 1) * cw].to_vec(); - } + let lr = (y0 + ctb - 1) - pic.origin_y; + slot.luma = pic.planes.y[lr * self.width..(lr + 1) * self.width].to_vec(); + let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c; + slot.cb = pic.planes.cb[lc * cw..(lc + 1) * cw].to_vec(); + slot.cr = pic.planes.cr[lc * cw..(lc + 1) * cw].to_vec(); let ur = (y0 + ctb - 4) / 4; let band_row = ur - pic.origin_unit / 4; slot.units = pic.info[band_row * self.w4..(band_row + 1) * self.w4].to_vec(); @@ -130,7 +127,7 @@ impl Board { ry: usize, x: usize, pic: &mut PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, ) -> Result> { if ry == 0 { return Ok(None); @@ -139,7 +136,6 @@ impl Board { let cols = self.cols; let need = (x + 2).min(cols); let mut st = lock(&self.state); - let t = trace::now(); loop { if let Some(why) = &st.failed { return Err(Error::corrupt(format!("HEVC slice (wavefront): {why}"))); @@ -149,7 +145,6 @@ impl Board { } st = self.changed.wait(st).unwrap_or_else(|e| e.into_inner()); } - trace::since(Phase::WaitSync, t); let slot = &st.slots[ry - 1]; let k0 = x.saturating_sub(1); let k1 = (x + 1).min(cols - 1); @@ -160,19 +155,15 @@ impl Board { (k * ctb) >> self.sub_x, (((k + 1) * ctb) >> self.sub_x).min(cw), ); - if pic.has_pixels() { - pic.planes.y[a..b].copy_from_slice(&slot.luma[a..b]); - pic.planes.cb[ca..cb_end].copy_from_slice(&slot.cb[ca..cb_end]); - pic.planes.cr[ca..cb_end].copy_from_slice(&slot.cr[ca..cb_end]); - } + pic.planes.y[a..b].copy_from_slice(&slot.luma[a..b]); + pic.planes.cb[ca..cb_end].copy_from_slice(&slot.cb[ca..cb_end]); + pic.planes.cr[ca..cb_end].copy_from_slice(&slot.cr[ca..cb_end]); let (ua, ub) = (k * ctb / 4, ((k + 1) * ctb / 4).min(self.w4)); pic.info[ua..ub].copy_from_slice(&slot.units[ua..ub]); pic.ctb[(ry - 1) * cols + k] = slot.ctb[k]; } let unit_row = (ry << self.ctb_log2) / 4 - 1; - let field = motion - .band_cells() - .ok_or_else(|| Error::corrupt("HEVC slice (wavefront): a row without a motion band"))?; + let field = &mut *motion.field; for k in k0..=k1 { let (ua, ub) = (k * ctb / 4, ((k + 1) * ctb / 4).min(self.w4)); field.cell_row_mut(unit_row)[ua..ub].copy_from_slice(&slot.cells[ua..ub]); @@ -187,7 +178,7 @@ impl Board { ry: usize, x: usize, pic: &PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, wpp: Option<&Contexts>, ) -> Result<()> { let ctb = 1usize << self.ctb_log2; @@ -200,13 +191,7 @@ impl Board { (((x + 1) * ctb) >> self.sub_x).min(cw), ); let (ua, ub) = (x * ctb / 4, ((x + 1) * ctb / 4).min(self.w4)); - let field = if full { - Some(motion.band_cells().ok_or_else(|| { - Error::corrupt("HEVC slice (wavefront): a row without a motion band") - })?) - } else { - None - }; + let field = if full { Some(&mut *motion.field) } else { None }; let mut st = lock(&self.state); let slot = &mut st.slots[ry]; if slot.ctb.is_empty() { @@ -219,14 +204,12 @@ impl Board { } if full { // Band rows: the sample rows and unit row of the CTB row's last rows. - if pic.has_pixels() { - let lr = (y0 + ctb - 1) - pic.origin_y; - slot.luma[a..b] - .copy_from_slice(&pic.planes.y[lr * self.width + a..lr * self.width + b]); - let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c; - slot.cb[ca..cb_end].copy_from_slice(&pic.planes.cb[lc * cw + ca..lc * cw + cb_end]); - slot.cr[ca..cb_end].copy_from_slice(&pic.planes.cr[lc * cw + ca..lc * cw + cb_end]); - } + let lr = (y0 + ctb - 1) - pic.origin_y; + slot.luma[a..b] + .copy_from_slice(&pic.planes.y[lr * self.width + a..lr * self.width + b]); + let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c; + slot.cb[ca..cb_end].copy_from_slice(&pic.planes.cb[lc * cw + ca..lc * cw + cb_end]); + slot.cr[ca..cb_end].copy_from_slice(&pic.planes.cr[lc * cw + ca..lc * cw + cb_end]); let ur = (y0 + ctb - 4) / 4; let band_row = ur - pic.origin_unit / 4; slot.units[ua..ub] @@ -263,13 +246,13 @@ trait RowSync { fn enter( &mut self, pic: &mut PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, x: usize, ) -> Result>; fn leave( &mut self, pic: &PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, x: usize, wpp: Option<&Contexts>, ) -> Result<()>; @@ -279,7 +262,7 @@ impl RowSync for Link<'_> { fn enter( &mut self, pic: &mut PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, x: usize, ) -> Result> { self.board.enter(self.ry, x, pic, motion) @@ -288,7 +271,7 @@ impl RowSync for Link<'_> { fn leave( &mut self, pic: &PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, x: usize, wpp: Option<&Contexts>, ) -> Result<()> { @@ -328,7 +311,7 @@ fn parse_row( pps: &Pps, header: &SliceHeader, pic: &mut PicState, - motion: &mut dyn MotionSource, + motion: &mut SliceMotion<'_>, refs: Option<&InterRefs>, seg: &SegConsts, data: &[u8], @@ -504,7 +487,6 @@ pub(in crate::dec) fn parse_segment( if ry0 > 0 { board.prefill(ry0 - 1, pic, &*source.field); } - let pixels = pic.has_pixels(); let next = AtomicUsize::new(0); let lists = source.lists; let cur_poc = source.cur_poc; @@ -520,7 +502,7 @@ pub(in crate::dec) fn parse_segment( let y0 = ry << ctb_log2; let bound = usize::from(ry > 0); let own = ctb.min(global.height - y0); - let mut band = global.band(y0, own, pixels); + let mut band = global.band(y0, own); let mut field = field_global.band((y0 - 4 * bound) / 4, bound + own.div_ceil(4)); let row_start = if i == 0 { 0 } else { starts[i - 1] }; let row_len = (!last).then(|| starts[i] - row_start); @@ -569,9 +551,7 @@ pub(in crate::dec) fn parse_segment( break; } let ry = ry0 + i; - let t = trace::now(); let outcome = catch_unwind(AssertUnwindSafe(|| do_row(ry))); - trace::since(Phase::Decode, t); match outcome { Ok(Ok(row)) => done.push(row), Ok(Err(e)) => { @@ -587,14 +567,7 @@ pub(in crate::dec) fn parse_segment( Ok(done) }; let results: Vec>> = std::thread::scope(|s| { - let helpers: Vec<_> = (1..workers.clamp(1, nrows)) - .map(|_| { - s.spawn(|| { - trace::set_role("wpp-helper"); - run() - }) - }) - .collect(); + let helpers: Vec<_> = (1..workers.clamp(1, nrows)).map(|_| s.spawn(run)).collect(); let mut all = vec![run()]; for h in helpers { all.push(h.join().unwrap_or_else(|_| { @@ -625,16 +598,14 @@ pub(in crate::dec) fn parse_segment( let (sx, sy) = (pic.sub_x(), pic.sub_y()); let own_c = own.div_ceil(1 << sy); let cw = pic.width.div_ceil(1 << sx); - if pixels { - let w = pic.width; - pic.planes.y[y0 * w..(y0 + own) * w] - .copy_from_slice(&done.band.planes.y[bound * w..(bound + own) * w]); - let (c0, c1) = (y0 >> sy, (y0 >> sy) + own_c); - pic.planes.cb[c0 * cw..c1 * cw] - .copy_from_slice(&done.band.planes.cb[bound * cw..(bound + own_c) * cw]); - pic.planes.cr[c0 * cw..c1 * cw] - .copy_from_slice(&done.band.planes.cr[bound * cw..(bound + own_c) * cw]); - } + let w = pic.width; + pic.planes.y[y0 * w..(y0 + own) * w] + .copy_from_slice(&done.band.planes.y[bound * w..(bound + own) * w]); + let (c0, c1) = (y0 >> sy, (y0 >> sy) + own_c); + pic.planes.cb[c0 * cw..c1 * cw] + .copy_from_slice(&done.band.planes.cb[bound * cw..(bound + own_c) * cw]); + pic.planes.cr[c0 * cw..c1 * cw] + .copy_from_slice(&done.band.planes.cr[bound * cw..(bound + own_c) * cw]); let u0 = y0 / 4; let units = own.div_ceil(4); pic.info[u0 * pic.w4..(u0 + units) * pic.w4] diff --git a/crates/ec-h265/src/dec/deblock.rs b/crates/ec-h265/src/dec/deblock.rs index 45f838c2..6285fb7e 100644 --- a/crates/ec-h265/src/dec/deblock.rs +++ b/crates/ec-h265/src/dec/deblock.rs @@ -432,9 +432,6 @@ pub fn deblock_picture(pic: &mut PicState) { /// side is in the rows above are filtered after those rows' own vertical edges, which /// is the order 8.7.2 gives for the whole picture. pub fn deblock_rows(pic: &mut PicState, rows: Range) { - if !pic.has_pixels() { - return; - } let (w, h) = (pic.width, pic.height); let (sx, sy) = (pic.sub_x(), pic.sub_y()); let (cw, ch) = (w.div_ceil(1 << sx), h.div_ceil(1 << sy)); @@ -484,7 +481,7 @@ mod tests { /// A 16x16 picture whose luma column `x` holds `value(x)`, with flat chroma, /// every unit intra at QP 37 and an edge on every unit. fn picture(value: impl Fn(usize) -> u16) -> PicState { - let mut pic = PicState::new(16, 16, 4, 2, 8, 8, true); + let mut pic = PicState::new(16, 16, 4, 2, 8, 8); for y in 0..16 { for x in 0..16 { pic.planes.y[y * 16 + x] = value(x); diff --git a/crates/ec-h265/src/dec/dpb.rs b/crates/ec-h265/src/dec/dpb.rs index 7d05a503..3c1013cb 100644 --- a/crates/ec-h265/src/dec/dpb.rs +++ b/crates/ec-h265/src/dec/dpb.rs @@ -40,8 +40,7 @@ pub struct DpbPicture { pub au_index: u32, /// Cropping of the SPS the picture was decoded under. pub window: ConformanceWindow, - /// The samples and the collocated motion (8.5.3.2.8). Empty samples when the decoder - /// runs without pixel decode. The samples may still be being decoded. + /// The samples and the collocated motion (8.5.3.2.8). The samples may still be being decoded. pub picture: Arc, /// HDR, colour and hash metadata of the picture. pub meta: Arc, @@ -97,7 +96,10 @@ impl Frame { pub fn cropped(&self) -> DecodedPicture { let p = &self.picture; let (sx, sy) = crate::decode::chroma_shifts(p.chroma_format_idc); - let (left, top) = ((self.window.left << sx) as usize, (self.window.top << sy) as usize); + let (left, top) = ( + (self.window.left << sx) as usize, + (self.window.top << sy) as usize, + ); let width = p.width - left - ((self.window.right << sx) as usize); let height = p.height - top - ((self.window.bottom << sy) as usize); let crop = |plane: &[u16], stride: usize, x: usize, y: usize, w: usize, h: usize| { diff --git a/crates/ec-h265/src/dec/inter.rs b/crates/ec-h265/src/dec/inter.rs index 7b9e33be..8052e86d 100644 --- a/crates/ec-h265/src/dec/inter.rs +++ b/crates/ec-h265/src/dec/inter.rs @@ -168,9 +168,6 @@ fn ref_picture(pic: &DecodedPicture) -> RefPicture<'_> { /// Add the residual blocks of an inter coding unit to the samples its prediction /// units already wrote. pub fn add_residuals(pic: &mut PicState, residuals: &[ResidualBlock]) { - if !pic.has_pixels() { - return; - } for block in residuals { pic.add_residual( block.component, @@ -196,7 +193,7 @@ mod tests { let (tx, rx) = mpsc::channel(); std::thread::spawn(move || { let (w, h) = (64usize, 64usize); - let pic = Arc::new(SharedPic::new(0, w, h, (8, 8), true, 1)); + let pic = Arc::new(SharedPic::new(0, w, h, (8, 8), 1)); let src = DecodedPicture { width: w, height: h, diff --git a/crates/ec-h265/src/dec/mc.rs b/crates/ec-h265/src/dec/mc.rs index d35e85a3..c9b6387f 100644 --- a/crates/ec-h265/src/dec/mc.rs +++ b/crates/ec-h265/src/dec/mc.rs @@ -474,7 +474,3 @@ pub(super) fn check_out(dst: &PlaneMut<'_>, blk: Block) -> Result<()> { } check_depth(dst.bit_depth) } - -#[cfg(test)] -#[path = "mc_tests.rs"] -mod tests; diff --git a/crates/ec-h265/src/dec/mc_tests.rs b/crates/ec-h265/src/dec/mc_tests.rs deleted file mode 100644 index 13f6b893..00000000 --- a/crates/ec-h265/src/dec/mc_tests.rs +++ /dev/null @@ -1,1137 +0,0 @@ -//! Tests of the motion compensation: hand-computed values for every fraction, -//! edge clamping, weighted prediction, a per-sample reference model compared on -//! random blocks, and a 1080p timing run. - -use crate::dec::cu_syntax::Motion; -use crate::dec::mc::{ - Block, McScratch, PlaneMut, PlaneRef, RefPicture, interp_chroma, interp_luma, predict_pu, -}; -use crate::dec::weighted::{ExplicitWeights, Weight, store}; -use ec_h265_syntax::{PredWeightTable, WeightEntry}; - -/// A plane of `w x h` samples from `f(x, y)`, stride `w`. -fn plane_from(w: usize, h: usize, bd: u32, f: impl Fn(usize, usize) -> u16) -> Vec { - (0..h) - .flat_map(|y| (0..w).map(move |x| (x, y))) - .map(|(x, y)| f(x, y)) - .map(|v| v.min((1 << bd) - 1)) - .collect() -} - -fn view(samples: &[u16], w: usize, h: usize, bd: u32) -> PlaneRef<'_> { - PlaneRef { - samples, - stride: w, - width: w, - height: h, - bit_depth: bd, - } -} - -fn motion(pred_flags: [bool; 2], ref_idx: [i8; 2], mv: [[i32; 2]; 2]) -> Motion { - Motion { - pred_flags, - ref_idx, - mv, - } -} - -/// A 16x16 luma plane that is zero except for `value` at (8, 8). -fn impulse16(value: u16) -> Vec { - plane_from(16, 16, 10, |x, y| if (x, y) == (8, 8) { value } else { 0 }) -} - -#[test] -fn luma_impulse_fractions_8bit_hand_values() { - // Impulse of 100 at column 8; the block starts at column 4 on row 8, so output - // j reads the impulse with tap index 7 - j. shift1 = 0 at 8 bits. - let p = impulse16(100); - let pl = view(&p, 16, 16, 8); - let blk = Block { - x: 4, - y: 8, - width: 4, - height: 1, - }; - let mut scratch = McScratch::new(); - let mut out = [0i32; 4]; - let cases: [(i32, [i32; 4]); 3] = [ - (1, [0, 100, -500, 1700]), - (2, [-100, 400, -1100, 4000]), - (3, [-100, 400, -1000, 5800]), - ]; - for (frac, want) in cases { - interp_luma(&pl, blk, [frac, 0], &mut scratch, &mut out).unwrap(); - assert_eq!(out, want, "luma horizontal fraction {frac}"); - } - // Full-sample position: the impulse shifted by shift3 = 14 - 8 = 6. - let full = Block { - x: 8, - y: 8, - width: 1, - height: 1, - }; - interp_luma(&pl, full, [0, 0], &mut scratch, &mut out).unwrap(); - assert_eq!(out[0], 100 << 6); -} - -#[test] -fn luma_impulse_fractions_10bit_hand_values() { - // shift1 = 2 at 10 bits, so each tap sum is divided by 4 (exact here). - let p = impulse16(1000); - let pl = view(&p, 16, 16, 10); - let blk = Block { - x: 4, - y: 8, - width: 4, - height: 1, - }; - let mut scratch = McScratch::new(); - let mut out = [0i32; 4]; - let cases: [(i32, [i32; 4]); 3] = [ - (1, [0, 250, -1250, 4250]), - (2, [-250, 1000, -2750, 10000]), - (3, [-250, 1000, -2500, 14500]), - ]; - for (frac, want) in cases { - interp_luma(&pl, blk, [frac, 0], &mut scratch, &mut out).unwrap(); - assert_eq!(out, want, "10-bit luma horizontal fraction {frac}"); - } - let full = Block { - x: 8, - y: 8, - width: 1, - height: 1, - }; - interp_luma(&pl, full, [0, 0], &mut scratch, &mut out).unwrap(); - assert_eq!(out[0], 1000 << 4, "10-bit full sample shift3 = 4"); -} - -#[test] -fn luma_vertical_only_matches_horizontal_by_symmetry() { - let p = impulse16(100); - let pl = view(&p, 16, 16, 8); - // Block column 8, rows 4..8: output row k reads the impulse at tap 7 - k. - let blk = Block { - x: 8, - y: 4, - width: 1, - height: 4, - }; - let mut scratch = McScratch::new(); - let mut out = [0i32; 4]; - interp_luma(&pl, blk, [0, 1], &mut scratch, &mut out).unwrap(); - assert_eq!(out, [0, 100, -500, 1700]); - interp_luma(&pl, blk, [0, 3], &mut scratch, &mut out).unwrap(); - assert_eq!(out, [-100, 400, -1000, 5800]); -} - -#[test] -fn luma_two_dimensional_hand_values() { - // 10 bits, impulse 4096 at (8, 8), block at (4, 4), fractions (2, 2). - // Horizontal pass on the impulse row gives tmp = [-1024, 4096, -11264, 40960] - // (shift1 = 2), and the vertical pass with shift2 = 6 yields the 4x4 block. - // Built raw: plane_from would clamp the impulse to the 10-bit range. - let mut p = vec![0u16; 16 * 16]; - p[8 * 16 + 8] = 4096; - let pl = view(&p, 16, 16, 10); - let blk = Block { - x: 4, - y: 4, - width: 4, - height: 4, - }; - let mut scratch = McScratch::new(); - let mut out = [0i32; 16]; - interp_luma(&pl, blk, [2, 2], &mut scratch, &mut out).unwrap(); - assert_eq!( - out, - [ - 16, -64, 176, -640, // - -64, 256, -704, 2560, // - 176, -704, 1936, -7040, // - -640, 2560, -7040, 25600, - ] - ); -} - -#[test] -fn chroma_impulse_fractions_hand_values() { - // 8 bits, impulse 100 at (8, 8) in the chroma plane; block at column 5 (so - // output j reads tap 4 - j), the four taps that land in range being j = 1..=3. - let p = plane_from(16, 16, 8, |x, y| if (x, y) == (8, 8) { 100 } else { 0 }); - let pl = view(&p, 16, 16, 8); - let blk = Block { - x: 5, - y: 8, - width: 4, - height: 1, - }; - let mut scratch = McScratch::new(); - let mut out = [0i32; 4]; - let cases: [(i32, [i32; 4]); 7] = [ - (1, [0, -200, 1000, 5800]), - (2, [0, -200, 1600, 5400]), - (3, [0, -400, 2800, 4600]), - (4, [0, -400, 3600, 3600]), - (5, [0, -600, 4600, 2800]), - (6, [0, -400, 5400, 1600]), - (7, [0, -200, 5800, 1000]), - ]; - for (frac, want) in cases { - interp_chroma(&pl, blk, [frac, 0], &mut scratch, &mut out).unwrap(); - assert_eq!(out, want, "chroma horizontal eighth {frac}"); - } - let full = Block { - x: 8, - y: 8, - width: 1, - height: 1, - }; - interp_chroma(&pl, full, [0, 0], &mut scratch, &mut out).unwrap(); - assert_eq!(out[0], 100 << 6); -} - -#[test] -fn chroma_motion_vector_splits_integer_and_eighth() { - // A chroma mv of 8 + 3 eighths moves one whole sample plus the eighth-3 filter. - let p = plane_from(16, 16, 8, |x, y| if (x, y) == (8, 8) { 100 } else { 0 }); - let pl = view(&p, 16, 16, 8); - let mut scratch = McScratch::new(); - let mut a = [0i32; 4]; - let mut b = [0i32; 4]; - let start = Block { - x: 4, - y: 8, - width: 4, - height: 1, - }; - interp_chroma(&pl, start, [11, 0], &mut scratch, &mut a).unwrap(); - let shifted = Block { - x: 5, - y: 8, - width: 4, - height: 1, - }; - interp_chroma(&pl, shifted, [3, 0], &mut scratch, &mut b).unwrap(); - assert_eq!(a, b); -} - -#[test] -fn luma_edges_clamp_at_all_four_borders() { - // v(x, y) = 10 * y + x on an 8x8 plane: every border has distinct values. - let p = plane_from(8, 8, 8, |x, y| (10 * y + x) as u16); - let pl = view(&p, 8, 8, 8); - let mut scratch = McScratch::new(); - let mut out = [0i32; 16]; - // Far left: every column reads column 0, so each row is v(0, y) << 6. - let blk = Block { - x: 0, - y: 0, - width: 4, - height: 4, - }; - interp_luma(&pl, blk, [-4000, 0], &mut scratch, &mut out).unwrap(); - for r in 0..4 { - for c in 0..4 { - assert_eq!(out[r * 4 + c], (10 * r as i32) << 6, "far left"); - } - } - // Far right: every column reads column 7. - let blk = Block { - x: 4, - y: 0, - width: 4, - height: 4, - }; - interp_luma(&pl, blk, [4000, 0], &mut scratch, &mut out).unwrap(); - for r in 0..4 { - for c in 0..4 { - assert_eq!(out[r * 4 + c], (10 * r as i32 + 7) << 6, "far right"); - } - } - // Far up: every row reads row 0, so each column is v(x, 0) = x. - let blk = Block { - x: 4, - y: 0, - width: 4, - height: 4, - }; - interp_luma(&pl, blk, [0, -4000], &mut scratch, &mut out).unwrap(); - for r in 0..4 { - for c in 0..4 { - assert_eq!(out[r * 4 + c], (4 + c as i32) << 6, "far up"); - } - } - // Far down: every row reads row 7. - let blk = Block { - x: 4, - y: 4, - width: 4, - height: 4, - }; - interp_luma(&pl, blk, [0, 4000], &mut scratch, &mut out).unwrap(); - for r in 0..4 { - for c in 0..4 { - assert_eq!(out[r * 4 + c], ((70 + 4 + c) as i32) << 6, "far down"); - } - } - // Far outside in both directions, to each corner. - let corners = [ - (0, 0, -4000, -4000, 0), - (4, 0, 4000, -4000, 7), - (0, 4, -4000, 4000, 70), - (4, 4, 4000, 4000, 77), - ]; - for (x, y, mx, my, want) in corners { - let blk = Block { - x, - y, - width: 4, - height: 4, - }; - interp_luma(&pl, blk, [mx, my], &mut scratch, &mut out).unwrap(); - assert!(out.iter().all(|&v| v == want << 6), "corner {want}"); - } -} - -#[test] -fn luma_fractional_edges_clamp_to_the_border_sample() { - // A fractional mv far outside reads one border column (or row) only, so the - // filter sums to 64 times that border sample. - let p = plane_from(8, 8, 8, |x, y| (10 * y + x) as u16); - let pl = view(&p, 8, 8, 8); - let mut scratch = McScratch::new(); - let mut out = [0i32; 16]; - let blk = Block { - x: 0, - y: 0, - width: 4, - height: 4, - }; - // -4001 quarter samples: integer part -1001, fraction 3. - interp_luma(&pl, blk, [-4001, 0], &mut scratch, &mut out).unwrap(); - for r in 0..4 { - assert!( - out[r * 4..r * 4 + 4] - .iter() - .all(|&v| v == 64 * 10 * r as i32) - ); - } - interp_luma(&pl, blk, [0, -4001], &mut scratch, &mut out).unwrap(); - for c in 0..4 { - assert!((0..4).all(|r| out[r * 4 + c] == 64 * c as i32)); - } -} - -#[test] -fn chroma_edges_clamp_at_all_four_borders() { - let p = plane_from(8, 8, 8, |x, y| (10 * y + x) as u16); - let pl = view(&p, 8, 8, 8); - let mut scratch = McScratch::new(); - let mut out = [0i32; 4]; - let blk = Block { - x: 0, - y: 0, - width: 2, - height: 2, - }; - // Eighth-sample mv of -8001: integer part -1001, fraction 7. - interp_chroma(&pl, blk, [-8001, 0], &mut scratch, &mut out).unwrap(); - assert_eq!(out, [0, 0, 640, 640]); - let blk = Block { - x: 6, - y: 6, - width: 2, - height: 2, - }; - interp_chroma(&pl, blk, [8000, 8000], &mut scratch, &mut out).unwrap(); - assert!(out.iter().all(|&v| v == 77 << 6)); -} - -#[test] -fn default_uni_and_bi_hand_values() { - let mut buf = [0u16; 4]; - let blk = Block { - x: 0, - y: 0, - width: 4, - height: 1, - }; - // 8 bits: shift1 = 6 for uni, shift2 = 7 for bi. - let mut dst = PlaneMut { - samples: &mut buf, - stride: 4, - bit_depth: 8, - origin: 0, - }; - store( - &mut dst, - blk, - [Some(&[6400, -100, 16320, 16384]), None], - None, - ) - .unwrap(); - assert_eq!(buf, [100, 0, 255, 255]); - - let mut buf = [0u16; 2]; - let blk2 = Block { - x: 0, - y: 0, - width: 2, - height: 1, - }; - let mut dst = PlaneMut { - samples: &mut buf, - stride: 2, - bit_depth: 8, - origin: 0, - }; - store( - &mut dst, - blk2, - [Some(&[6400, 6400]), Some(&[6400, 6464])], - None, - ) - .unwrap(); - assert_eq!(buf, [100, 101]); - - // 10 bits: shift1 = 4 for uni, shift2 = 5 for bi. - let mut buf = [0u16; 3]; - let blk3 = Block { - x: 0, - y: 0, - width: 3, - height: 1, - }; - let mut dst = PlaneMut { - samples: &mut buf, - stride: 3, - bit_depth: 10, - origin: 0, - }; - store(&mut dst, blk3, [Some(&[6400, 16368, 16384]), None], None).unwrap(); - assert_eq!(buf, [400, 1023, 1023]); - let mut dst = PlaneMut { - samples: &mut buf, - stride: 3, - bit_depth: 10, - origin: 0, - }; - store( - &mut dst, - blk3, - [Some(&[6400, 0, 0]), Some(&[12800, 0, 0])], - None, - ) - .unwrap(); - assert_eq!(buf[0], 600); -} - -#[test] -fn explicit_uni_and_bi_hand_values_8bit() { - let blk = Block { - x: 0, - y: 0, - width: 1, - height: 1, - }; - let mut buf = [0u16; 1]; - // denom 2, w = 3, o = 5: ((6400*3 + 128) >> 8) + 5 = 75 + 5. - let mut dst = PlaneMut { - samples: &mut buf, - stride: 1, - bit_depth: 8, - origin: 0, - }; - let w = [Weight { w: 3, o: 5 }, Weight::default()]; - store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap(); - assert_eq!(buf[0], 80); - - // Negative weight -1 and offset 200: ((-6400 + 128) >> 8) + 200 = -25 + 200. - let w = [Weight { w: -1, o: 200 }, Weight::default()]; - let mut dst = PlaneMut { - samples: &mut buf, - stride: 1, - bit_depth: 8, - origin: 0, - }; - store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap(); - assert_eq!(buf[0], 175); - - // Negative offset clipping at zero: w = -1, o = -200 gives -225 -> 0. - let w = [Weight { w: -1, o: -200 }, Weight::default()]; - let mut dst = PlaneMut { - samples: &mut buf, - stride: 1, - bit_depth: 8, - origin: 0, - }; - store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap(); - assert_eq!(buf[0], 0); - - // Bi: w0 = -2, o0 = -3 with p0 = 6400; w1 = 6, o1 = 7 with p1 = 12800. - // (-12800 + 76800 + ((-3 + 7 + 1) << 8)) >> 9 = 127. - let w = [Weight { w: -2, o: -3 }, Weight { w: 6, o: 7 }]; - let mut dst = PlaneMut { - samples: &mut buf, - stride: 1, - bit_depth: 8, - origin: 0, - }; - store(&mut dst, blk, [Some(&[6400]), Some(&[12800])], Some((2, w))).unwrap(); - assert_eq!(buf[0], 127); -} - -#[test] -fn explicit_uni_hand_value_10bit_with_scaled_offset() { - // The caller scales offsets by 1 << (BitDepth - 8); 5 << 2 = 20. - // shift1 = 4 at 10 bits, log2WD = 2 + 4 = 6: ((6400*3 + 32) >> 6) + 20 = 300 + 20. - let blk = Block { - x: 0, - y: 0, - width: 1, - height: 1, - }; - let mut buf = [0u16; 1]; - let mut dst = PlaneMut { - samples: &mut buf, - stride: 1, - bit_depth: 10, - origin: 0, - }; - let w = [Weight { w: 3, o: 20 }, Weight::default()]; - store(&mut dst, blk, [Some(&[6400]), None], Some((2, w))).unwrap(); - assert_eq!(buf[0], 320); -} - -#[test] -fn weight_table_derivation_with_chroma_offsets() { - // luma denom 2, chroma denom 3. Entry 0: luma delta -1 offset 5; chroma deltas - // 3 and -2 with the ChromaOffset values the parser already derived (-7, 9). - // Entry 1 has no flags, so every weight is the default and offsets are 0. - let table = PredWeightTable { - luma_log2_weight_denom: 2, - delta_chroma_log2_weight_denom: 1, - l0: vec![ - WeightEntry { - luma: Some((-1, 5)), - chroma: Some([(3, -7), (-2, 9)]), - }, - WeightEntry::default(), - ], - l1: vec![], - }; - let ew = ExplicitWeights::from_table(&table, 8, 8, false).unwrap(); - assert_eq!(ew.log2_denom, [2, 3, 3]); - assert_eq!( - ew.entries[0][0], - [ - Weight { w: 3, o: 5 }, - Weight { w: 11, o: -7 }, - Weight { w: 6, o: 9 }, - ] - ); - assert_eq!( - ew.entries[0][1], - [ - Weight { w: 4, o: 0 }, - Weight { w: 8, o: 0 }, - Weight { w: 8, o: 0 } - ] - ); - // At 10 bits every offset is scaled by 4. - let ew10 = ExplicitWeights::from_table(&table, 10, 10, false).unwrap(); - assert_eq!(ew10.entries[0][0][0], Weight { w: 3, o: 20 }); - assert_eq!(ew10.entries[0][0][1].o, -28); - assert_eq!(ew10.entries[0][0][2].o, 36); - // A coded weight delta outside -128..=127 is corrupt. - let bad = PredWeightTable { - luma_log2_weight_denom: 0, - delta_chroma_log2_weight_denom: 0, - l0: vec![WeightEntry { - luma: Some((200, 0)), - chroma: None, - }], - l1: vec![], - }; - assert!(ExplicitWeights::from_table(&bad, 8, 8, false).is_err()); -} - -#[test] -fn predict_pu_constant_planes_recover_the_value() { - // A constant picture predicts itself for any motion and any weighting that is - // the identity: default bi of 100 and 100 gives 100. - let bd = 8; - let luma = plane_from(64, 64, bd, |_, _| 100); - let chroma = plane_from(32, 32, bd, |_, _| 100); - let pic: RefPicture<'_> = [ - view(&luma, 64, 64, bd), - view(&chroma, 32, 32, bd), - view(&chroma, 32, 32, bd), - ]; - let refs = [&[pic][..], &[pic][..]]; - let mut oy = vec![0u16; 64 * 64]; - let mut ou = vec![0u16; 32 * 32]; - let mut ov = vec![0u16; 32 * 32]; - let mut out = [ - PlaneMut { - samples: &mut oy, - stride: 64, - bit_depth: bd, - origin: 0, - }, - PlaneMut { - samples: &mut ou, - stride: 32, - bit_depth: bd, - origin: 0, - }, - PlaneMut { - samples: &mut ov, - stride: 32, - bit_depth: bd, - origin: 0, - }, - ]; - let mut scratch = McScratch::new(); - let pu = Block { - x: 16, - y: 8, - width: 8, - height: 4, - }; - let m = motion([true, true], [0, 0], [[-13, 7], [22, -5]]); - predict_pu(refs, &m, None, pu, &mut out, &mut scratch).unwrap(); - for (plane, stride, w, h, x, y) in [ - (&oy, 64, 8, 4, 16, 8), - (&ou, 32, 4, 2, 8, 4), - (&ov, 32, 4, 2, 8, 4), - ] { - for r in 0..h { - for c in 0..w { - assert_eq!(plane[(y + r) * stride + x + c], 100); - } - } - } -} - -#[test] -fn predict_pu_rejects_bad_input() { - let bd = 8; - let luma = plane_from(16, 16, bd, |_, _| 1); - let chroma = plane_from(8, 8, bd, |_, _| 1); - let pic: RefPicture<'_> = [ - view(&luma, 16, 16, bd), - view(&chroma, 8, 8, bd), - view(&chroma, 8, 8, bd), - ]; - let refs = [&[pic][..], &[][..]]; - let mut oy = vec![0u16; 16 * 16]; - let mut ou = vec![0u16; 8 * 8]; - let mut ov = vec![0u16; 8 * 8]; - let mut out = [ - PlaneMut { - samples: &mut oy, - stride: 16, - bit_depth: bd, - origin: 0, - }, - PlaneMut { - samples: &mut ou, - stride: 8, - bit_depth: bd, - origin: 0, - }, - PlaneMut { - samples: &mut ov, - stride: 8, - bit_depth: bd, - origin: 0, - }, - ]; - let mut scratch = McScratch::new(); - let pu = Block { - x: 0, - y: 0, - width: 8, - height: 8, - }; - // No list in use. - let none = motion([false, false], [0, 0], [[0; 2]; 2]); - assert!(predict_pu(refs, &none, None, pu, &mut out, &mut scratch).is_err()); - // refIdxL1 names a picture list 1 does not have. - let l1 = motion([false, true], [0, 0], [[0; 2]; 2]); - assert!(predict_pu(refs, &l1, None, pu, &mut out, &mut scratch).is_err()); - // A rectangle past the plane edge. - let off = Block { - x: 12, - y: 0, - width: 8, - height: 8, - }; - let ok = motion([true, false], [0, 0], [[0; 2]; 2]); - assert!(predict_pu(refs, &ok, None, off, &mut out, &mut scratch).is_err()); -} - -// --------------------------------------------------------------------------- -// Reference model: a deliberately naive transcription of 8.5.3.3 per sample. -// It shares no code with the optimised path and copies the filter tables from -// the spec again, so a transcription error in either shows up as a mismatch. -// --------------------------------------------------------------------------- - -mod naive { - use crate::dec::cu_syntax::Motion; - use crate::dec::mc::{Block, PlaneRef, RefPicture}; - use crate::dec::weighted::ExplicitWeights; - - /// Table 8-11, luma. Row 0 is unused. - const LUMA: [[i64; 8]; 4] = [ - [0, 0, 0, 64, 0, 0, 0, 0], - [-1, 4, -10, 58, 17, -5, 1, 0], - [-1, 4, -11, 40, 40, -11, 4, -1], - [0, 1, -5, 17, 58, -10, 4, -1], - ]; - /// Table 8-12, chroma. Row 0 is unused. - const CHROMA: [[i64; 4]; 8] = [ - [0, 64, 0, 0], - [-2, 58, 10, -2], - [-4, 54, 16, -2], - [-6, 46, 28, -4], - [-4, 36, 36, -4], - [-4, 28, 46, -6], - [-2, 16, 54, -4], - [-2, 10, 58, -2], - ]; - - /// `ref[Clip3(0, W-1, x)][Clip3(0, H-1, y)]`, one sample. - fn sample(p: &PlaneRef<'_>, x: i64, y: i64) -> i64 { - let cx = x.clamp(0, p.width as i64 - 1) as usize; - let cy = y.clamp(0, p.height as i64 - 1) as usize; - i64::from(p.samples[cy * p.stride + cx]) - } - - /// One predSampleLX at integer position (xi, yi) with fractions (fx, fy). - fn interp(p: &PlaneRef<'_>, xi: i64, yi: i64, fx: usize, fy: usize, luma: bool) -> i64 { - let bd = i64::from(p.bit_depth); - let shift1 = (bd - 8).min(4); - let shift2 = 6; - let shift3 = (14 - bd).max(2); - let taps: i64 = if luma { 8 } else { 4 }; - let pad = taps / 2 - 1; - let coef = |frac: usize, i: i64| -> i64 { - if luma { - LUMA[frac][i as usize] - } else { - CHROMA[frac][i as usize] - } - }; - if fx == 0 && fy == 0 { - return sample(p, xi, yi) << shift3; - } - if fy == 0 { - let mut s = 0; - for i in 0..taps { - s += coef(fx, i) * sample(p, xi + i - pad, yi); - } - return s >> shift1; - } - if fx == 0 { - let mut s = 0; - for i in 0..taps { - s += coef(fy, i) * sample(p, xi, yi + i - pad); - } - return s >> shift1; - } - let mut s = 0; - for n in 0..taps { - let mut temp = 0; - for i in 0..taps { - temp += coef(fx, i) * sample(p, xi + i - pad, yi + n - pad); - } - s += coef(fy, n) * (temp >> shift1); - } - s >> shift2 - } - - /// The weighted sample prediction of 8.5.3.3.4 for one sample. - /// `preds[list]` is `Some(predSamplesLX)` for each list in use. - fn weight(bd: i64, preds: [Option; 2], explicit: Option<(i64, [(i64, i64); 2])>) -> i64 { - let max = (1 << bd) - 1; - let shift1 = 14 - bd; - let clip = |v: i64| v.clamp(0, max); - match (preds, explicit) { - ([Some(p0), Some(p1)], None) => { - let shift2 = 15 - bd; - clip((p0 + p1 + (1 << (shift2 - 1))) >> shift2) - } - ([Some(p0), Some(p1)], Some((denom, [(w0, o0), (w1, o1)]))) => { - let log2wd = denom + shift1; - clip((p0 * w0 + p1 * w1 + ((o0 + o1 + 1) << log2wd)) >> (log2wd + 1)) - } - ([Some(p), None], None) | ([None, Some(p)], None) => { - clip((p + (1 << (shift1 - 1))) >> shift1) - } - ([Some(p), None], Some((denom, [(w, o), _]))) => { - let log2wd = denom + shift1; - clip(if log2wd >= 1 { - ((p * w + (1 << (log2wd - 1))) >> log2wd) + o - } else { - p * w + o - }) - } - ([None, Some(p)], Some((denom, [_, (w, o)]))) => { - let log2wd = denom + shift1; - clip(if log2wd >= 1 { - ((p * w + (1 << (log2wd - 1))) >> log2wd) + o - } else { - p * w + o - }) - } - _ => panic!("naive model: no prediction"), - } - } - - /// The final samples of one PU component, row-major `blk.width * blk.height`. - pub fn predict_component( - refs: [&[RefPicture<'_>]; 2], - motion: &Motion, - weights: Option<&ExplicitWeights>, - blk: Block, - comp: usize, - ) -> Vec { - let luma = comp == 0; - let bd = i64::from( - refs.iter() - .enumerate() - .find_map(|(l, r)| { - motion.pred_flags[l].then(|| r[motion.ref_idx[l] as usize][comp].bit_depth) - }) - .unwrap(), - ); - let mut out = Vec::with_capacity(blk.width * blk.height); - for r in 0..blk.height { - for c in 0..blk.width { - let mut preds = [None, None]; - let mut wts = [(0i64, 0i64); 2]; - for list in 0..2 { - if !motion.pred_flags[list] { - continue; - } - let pic = &refs[list][motion.ref_idx[list] as usize]; - let p = &pic[comp]; - let mv = motion.mv[list]; - let (xi, yi, fx, fy) = if luma { - ( - blk.x as i64 + i64::from(mv[0] >> 2) + c as i64, - blk.y as i64 + i64::from(mv[1] >> 2) + r as i64, - (mv[0] & 3) as usize, - (mv[1] & 3) as usize, - ) - } else { - ( - blk.x as i64 + i64::from(mv[0] >> 3) + c as i64, - blk.y as i64 + i64::from(mv[1] >> 3) + r as i64, - (mv[0] & 7) as usize, - (mv[1] & 7) as usize, - ) - }; - preds[list] = Some(interp(p, xi, yi, fx, fy, luma)); - if let Some(ew) = weights { - let w = ew.entries[list][motion.ref_idx[list] as usize][comp]; - wts[list] = (i64::from(w.w), i64::from(w.o)); - } - } - let explicit = weights.map(|ew| (i64::from(ew.log2_denom[comp]), wts)); - out.push(weight(bd, preds, explicit)); - } - } - out - } -} - -/// SplitMix64: a fixed-seed generator, so every run sees the same blocks. -struct Rng(u64); - -impl Rng { - fn next_u64(&mut self) -> u64 { - self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); - let mut z = self.0; - z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - z ^ (z >> 31) - } - - fn below(&mut self, n: u64) -> u64 { - self.next_u64() % n - } - - fn range(&mut self, lo: i64, hi: i64) -> i64 { - lo + (self.next_u64() % (hi - lo + 1) as u64) as i64 - } -} - -/// An owned picture: Y, Cb, Cr planes at the 4:2:0 sizes of a `w x h` luma picture. -struct Pic { - planes: [Vec; 3], - w: usize, - h: usize, - bd: u32, -} - -impl Pic { - fn random(rng: &mut Rng, w: usize, h: usize, bd: u32) -> Pic { - let max = (1u64 << bd) - 1; - let mut fill = - |n: usize| -> Vec { (0..n).map(|_| rng.below(max + 1) as u16).collect() }; - let planes = [fill(w * h), fill(w * h / 4), fill(w * h / 4)]; - Pic { planes, w, h, bd } - } - - fn view(&self) -> RefPicture<'_> { - let dims = [ - (self.w, self.h), - (self.w / 2, self.h / 2), - (self.w / 2, self.h / 2), - ]; - std::array::from_fn(|c| PlaneRef { - samples: &self.planes[c], - stride: dims[c].0, - width: dims[c].0, - height: dims[c].1, - bit_depth: self.bd, - }) - } -} - -#[test] -fn random_blocks_match_the_reference_model() { - let mut rng = Rng(0x5eed_1234_abcd_0001); - let mut scratch = McScratch::new(); - let mut checked = 0usize; - let mut sizes_8x4_or_4x8 = 0usize; - let mut uni = 0usize; - let mut bi = 0usize; - let mut explicit = 0usize; - for case in 0..10_000 { - let bd = if rng.below(2) == 0 { 8 } else { 10 }; - let pw = 8 * rng.range(8, 28) as usize; - let ph = 8 * rng.range(8, 28) as usize; - // Sizes 4..=64 in steps of 4; every eighth case is forced to 8x4 or 4x8. - let (w, h) = if case % 8 == 0 { - if rng.below(2) == 0 { (8, 4) } else { (4, 8) } - } else { - (4 * rng.range(1, 16) as usize, 4 * rng.range(1, 16) as usize) - }; - if (w, h) == (8, 4) || (w, h) == (4, 8) { - sizes_8x4_or_4x8 += 1; - } - let x = 4 * rng.below(((pw - w) / 4 + 1) as u64) as usize; - let y = 4 * rng.below(((ph - h) / 4 + 1) as u64) as usize; - - let lists: [Vec; 2] = [ - (0..rng.range(1, 3)) - .map(|_| Pic::random(&mut rng, pw, ph, bd)) - .collect(), - (0..rng.range(1, 3)) - .map(|_| Pic::random(&mut rng, pw, ph, bd)) - .collect(), - ]; - let views: [Vec>; 2] = [ - lists[0].iter().map(Pic::view).collect(), - lists[1].iter().map(Pic::view).collect(), - ]; - - let pred_flags = match rng.below(3) { - 0 => [true, false], - 1 => [false, true], - _ => [true, true], - }; - if pred_flags[0] && pred_flags[1] { - bi += 1; - } else { - uni += 1; - } - let mut ref_idx = [0i8; 2]; - let mut mv = [[0i32; 2]; 2]; - let reach = 4 * (pw.max(ph) as i64 + 96); - for (list, mv_list) in mv.iter_mut().enumerate() { - ref_idx[list] = rng.below(lists[list].len() as u64) as i8; - *mv_list = std::array::from_fn(|_| { - if rng.below(2) == 0 { - rng.range(-reach, reach) as i32 - } else { - rng.range(-40, 40) as i32 - } - }); - } - let m = Motion { - pred_flags, - ref_idx, - mv, - }; - - let weights = if rng.below(2) == 0 { - None - } else { - explicit += 1; - let shift = bd - 8; - let denom: [u32; 3] = [ - rng.below(8) as u32, - rng.below(8) as u32, - rng.below(8) as u32, - ]; - let mut entries: [Vec<[Weight; 3]>; 2] = [Vec::new(), Vec::new()]; - for (list, slot) in entries.iter_mut().enumerate() { - *slot = (0..lists[list].len()) - .map(|_| { - std::array::from_fn(|_| Weight { - w: rng.range(-128, 127) as i32, - o: (rng.range(-128, 127) as i32) << shift, - }) - }) - .collect(); - } - Some(ExplicitWeights { - log2_denom: denom, - entries, - }) - }; - - let pu = Block { - x, - y, - width: w, - height: h, - }; - let mut planes = [ - vec![0u16; pw * ph], - vec![0u16; pw * ph / 4], - vec![0u16; pw * ph / 4], - ]; - let dims = [(pw, ph), (pw / 2, ph / 2), (pw / 2, ph / 2)]; - { - let [a, b, c] = &mut planes; - let mut out = [ - PlaneMut { - samples: a, - stride: pw, - bit_depth: bd, - origin: 0, - }, - PlaneMut { - samples: b, - stride: pw / 2, - bit_depth: bd, - origin: 0, - }, - PlaneMut { - samples: c, - stride: pw / 2, - bit_depth: bd, - origin: 0, - }, - ]; - let refs = [&views[0][..], &views[1][..]]; - predict_pu(refs, &m, weights.as_ref(), pu, &mut out, &mut scratch).unwrap(); - } - - let refs = [&views[0][..], &views[1][..]]; - for comp in 0..3 { - let blk = if comp == 0 { - pu - } else { - Block { - x: x / 2, - y: y / 2, - width: w / 2, - height: h / 2, - } - }; - let want = naive::predict_component(refs, &m, weights.as_ref(), blk, comp); - let stride = dims[comp].0; - for r in 0..blk.height { - for c in 0..blk.width { - let got = i64::from(planes[comp][(blk.y + r) * stride + blk.x + c]); - assert_eq!( - got, - want[r * blk.width + c], - "case {case} bd {bd} comp {comp} pu {pu:?} mv {mv:?} refs {ref_idx:?} flags {pred_flags:?} r {r} c {c}" - ); - } - } - } - checked += 1; - } - assert_eq!(checked, 10_000); - eprintln!( - "mc reference model: {checked} random PUs agree ({uni} uni, {bi} bi, {explicit} explicit weighted, {sizes_8x4_or_4x8} of 8x4/4x8)" - ); -} - -/// One 1080p frame of 8x8 bi-predicted PUs, luma and 4:2:0 chroma. Timing only; -/// run with `--release --nocapture` to see the figure. -#[test] -fn bench_1080p_bipred_8x8_frame() { - let (pw, ph, bd) = (1920usize, 1080usize, 10u32); - let mut rng = Rng(42); - let pic0 = Pic::random(&mut rng, pw, ph, bd); - let pic1 = Pic::random(&mut rng, pw, ph, bd); - let l0 = [pic0.view()]; - let l1 = [pic1.view()]; - let mut planes = [ - vec![0u16; pw * ph], - vec![0u16; pw * ph / 4], - vec![0u16; pw * ph / 4], - ]; - let [a, b, c] = &mut planes; - let mut out = [ - PlaneMut { - samples: a, - stride: pw, - bit_depth: bd, - origin: 0, - }, - PlaneMut { - samples: b, - stride: pw / 2, - bit_depth: bd, - origin: 0, - }, - PlaneMut { - samples: c, - stride: pw / 2, - bit_depth: bd, - origin: 0, - }, - ]; - let mut scratch = McScratch::new(); - let start = std::time::Instant::now(); - for by in 0..ph / 8 { - for bx in 0..pw / 8 { - let m = Motion { - pred_flags: [true, true], - ref_idx: [0, 0], - mv: [ - [(bx as i32 * 7 % 61) - 30, (by as i32 * 5 % 53) - 26], - [(by as i32 * 3 % 47) - 23, (bx as i32 * 11 % 59) - 29], - ], - }; - let pu = Block { - x: bx * 8, - y: by * 8, - width: 8, - height: 8, - }; - predict_pu([&l0, &l1], &m, None, pu, &mut out, &mut scratch).unwrap(); - } - } - let elapsed = start.elapsed(); - let checksum: u64 = planes.iter().flatten().map(|&v| u64::from(v)).sum(); - assert!(checksum > 0); - eprintln!( - "bench: 1080p frame, {} bi-pred 8x8 PUs (luma + 4:2:0 chroma): {:.2} ms (checksum {checksum})", - (pw / 8) * (ph / 8), - elapsed.as_secs_f64() * 1e3 - ); -} diff --git a/crates/ec-h265/src/dec/merge.rs b/crates/ec-h265/src/dec/merge.rs index 163ffa3e..eb113e84 100644 --- a/crates/ec-h265/src/dec/merge.rs +++ b/crates/ec-h265/src/dec/merge.rs @@ -3,7 +3,7 @@ //! temporal candidate, combined bi-predictive candidates for B slices, zero //! candidates, and the 8x4 / 4x8 restriction on bi-prediction. -use super::cu_syntax::{CuGeometry, PartMode, PredictionUnit}; +use super::cu_syntax::{PartMode, PredictionUnit}; use super::motion_field::{PbMotion, SliceMotion, to16}; /// Table 8-7: `l0CandIdx` for `combIdx` 0 to 11. @@ -15,21 +15,24 @@ const COMB_L1: [usize; 12] = [1, 0, 2, 0, 2, 1, 3, 0, 3, 1, 3, 2]; /// the merge candidate list (8.5.3.2.2). pub fn derive_merge( src: &SliceMotion<'_>, - cu: &CuGeometry, + cu_x: usize, + cu_y: usize, + cu_size: usize, + part_mode: PartMode, pu_index: usize, pu: &PredictionUnit, ) -> PbMotion { let params = src.params; // 8.5.3.2.2: with a parallel merge level above 4x4, every 8x8 coding unit shares // one merge list, derived as if it were a single prediction unit. - let single_list = params.log2_par_mrg_level > 2 && cu.size == 8; + let single_list = params.log2_par_mrg_level > 2 && cu_size == 8; let (x, y, w, h, part_idx) = if single_list { - (cu.x, cu.y, cu.size, cu.size, 0) + (cu_x, cu_y, cu_size, cu_size, 0) } else { (pu.x, pu.y, pu.width, pu.height, pu_index) }; - let mut cands = spatial_candidates(src, cu.part_mode, x, y, w, h, part_idx); + let mut cands = spatial_candidates(src, part_mode, x, y, w, h, part_idx); if let Some(col) = temporal_candidate(src, x, y, w, h) { cands.push(col); } @@ -193,365 +196,3 @@ fn zero_candidate(is_b: bool, ref_idx: usize) -> PbMotion { PbMotion::new([true, false], [r, -1], [[0, 0], [0, 0]]) } } - -#[cfg(test)] -mod tests { - use super::super::cu_syntax::InterPredIdc; - use super::super::motion_field::{MotionField, MotionParams, SliceRefs, test_shared}; - use super::super::rps::{RefEntry, RefPicLists}; - use super::super::shared::SharedPic; - use super::*; - use std::sync::Arc; - - fn entry(id: u32, poc: i32, long_term: bool) -> RefEntry { - RefEntry { id, poc, long_term } - } - - fn params(is_b: bool, max: usize, par: u32) -> MotionParams { - MotionParams { - is_b, - max_merge_cand: max, - log2_par_mrg_level: par, - ctb_log2: 6, - collocated_from_l0: true, - temporal_mvp: false, - no_backward_pred: false, - } - } - - fn uni(list: usize, ref_idx: i8, mv: [i16; 2]) -> PbMotion { - let mut pred = [false, false]; - pred[list] = true; - let mut r = [-1, -1]; - r[list] = ref_idx; - let mut m = [[0i16; 2]; 2]; - m[list] = mv; - PbMotion::new(pred, r, m) - } - - fn pu_at(x: usize, y: usize, w: usize, h: usize, merge_idx: u8) -> PredictionUnit { - PredictionUnit { - x, - y, - width: w, - height: h, - merge_flag: true, - merge_idx, - inter_pred_idc: InterPredIdc::PredL0, - ..PredictionUnit::default() - } - } - - fn cu(x: usize, y: usize, size: usize, part: PartMode) -> CuGeometry { - CuGeometry { - x, - y, - size, - part_mode: part, - skip: false, - } - } - - fn p_lists() -> RefPicLists { - RefPicLists { - l0: vec![entry(0, 0, false)], - l1: Vec::new(), - } - } - - /// The merge result for one PU, in a 64x64 picture with `field` as the current - /// motion field and `col` as the collocated picture. - fn merge_with( - field: &mut MotionField, - lists: &RefPicLists, - p: MotionParams, - col: Option>, - geom: CuGeometry, - pu: PredictionUnit, - pu_index: usize, - ) -> PbMotion { - let src = SliceMotion { - params: p, - lists, - cur_poc: 4, - field, - col, - publish: None, - slice: 0, - }; - derive_merge(&src, &geom, pu_index, &pu) - } - - #[test] - fn no_neighbours_gives_zero_candidate() { - let mut field = MotionField::new(64, 64); - let got = merge_with( - &mut field, - &p_lists(), - params(false, 5, 2), - None, - cu(16, 16, 16, PartMode::Part2Nx2N), - pu_at(16, 16, 16, 16, 0), - 0, - ); - assert_eq!(got, uni(0, 0, [0, 0])); - } - - #[test] - fn a1_is_first_and_intra_or_missing_neighbour_is_skipped() { - let mut field = MotionField::new(64, 64); - // A1 of the 16x16 block at (16,16) is (15,31): store motion there. - let m = uni(0, 0, [12, -7]); - field.store(0, 16, 16, 16, 0, m); - // B1 (31,15) stays missing (intra or not decoded). - let got = merge_with( - &mut field, - &p_lists(), - params(false, 5, 2), - None, - cu(16, 16, 16, PartMode::Part2Nx2N), - pu_at(16, 16, 16, 16, 0), - 0, - ); - assert_eq!(got, m); - } - - #[test] - fn neighbour_in_other_slice_is_unavailable() { - let mut field = MotionField::new(64, 64); - field.store(0, 16, 16, 16, 1, uni(0, 0, [12, -7])); - let got = merge_with( - &mut field, - &p_lists(), - params(false, 5, 2), - None, - cu(16, 16, 16, PartMode::Part2Nx2N), - pu_at(16, 16, 16, 16, 0), - 0, - ); - assert_eq!(got, uni(0, 0, [0, 0])); - } - - #[test] - fn b1_identical_to_a1_is_pruned() { - let mut field = MotionField::new(64, 64); - let a = uni(0, 0, [1, 2]); - let n = uni(0, 0, [5, 6]); - field.store(0, 16, 16, 16, 0, a); // A1 - field.store(16, 0, 16, 16, 0, a); // B1 (31,15): same as A1, pruned - field.store(32, 0, 16, 16, 0, n); // B0 (32,15) - // merge_idx 1 is B0, since B1 is pruned. - let got = merge_with( - &mut field, - &p_lists(), - params(false, 5, 2), - None, - cu(16, 16, 16, PartMode::Part2Nx2N), - pu_at(16, 16, 16, 16, 1), - 0, - ); - assert_eq!(got, n); - } - - #[test] - fn parallel_merge_level_hides_neighbours_in_the_same_region() { - // Log2ParMrgLevel 4 (16x16 regions). The 8x8 CU at (8,8) shares one list - // (singleMCLFlag), so A1 (7,15) and B1 (15,7) are in its own region and gone. - let mut field = MotionField::new(64, 64); - field.store(0, 8, 8, 8, 0, uni(0, 0, [9, 9])); // A1 position, same region - field.store(8, 0, 8, 8, 0, uni(0, 0, [8, 8])); // B1 position, same region - let far = uni(0, 0, [-3, 4]); - field.store(16, 0, 8, 8, 0, far); // B0 (16,7), another region - let got = merge_with( - &mut field, - &p_lists(), - params(false, 5, 4), - None, - cu(8, 8, 8, PartMode::Part2Nx2N), - pu_at(8, 8, 8, 8, 0), - 0, - ); - assert_eq!(got, far); - } - - #[test] - fn parallel_merge_level_two_uses_the_neighbour() { - // The same layout with Log2ParMrgLevel 2: nothing is in the same region, so A1 is used. - let mut field = MotionField::new(64, 64); - let a = uni(0, 0, [9, 9]); - field.store(0, 8, 8, 8, 0, a); - field.store(8, 0, 8, 8, 0, uni(0, 0, [8, 8])); - let got = merge_with( - &mut field, - &p_lists(), - params(false, 5, 2), - None, - cu(8, 8, 8, PartMode::Part2Nx2N), - pu_at(8, 8, 8, 8, 0), - 0, - ); - assert_eq!(got, a); - } - - #[test] - fn second_vertical_partition_skips_a1() { - // Nx2N, partIdx 1 at (x+8,y): A1 is the first partition, so it is not a candidate. - let mut field = MotionField::new(64, 64); - field.store(16, 16, 8, 16, 0, uni(0, 0, [1, 1])); // the first partition - let got = merge_with( - &mut field, - &p_lists(), - params(false, 5, 2), - None, - cu(16, 16, 16, PartMode::PartNx2N), - pu_at(24, 16, 8, 16, 0), - 1, - ); - assert_eq!(got, uni(0, 0, [0, 0])); - } - - #[test] - fn temporal_candidate_scales_with_negative_distance() { - // Current POC 2; the collocated picture is POC 8 and its vector points to POC 4. - // The current L0[0] is POC 6, after the current picture: tb = -4, td = 4. - // mv 64: tx = (16384 + 2) / 4 = 4096, dsf = (-4 * 4096 + 32) >> 6 = -256, - // mv' = Sign(-256 * 64) * ((16384 + 127) >> 8) = -64. - let mut col_field = MotionField::new(64, 64); - col_field.slices.push(SliceRefs { - poc: [vec![4], vec![]], - long_term: [vec![false], vec![]], - }); - col_field.store(32, 32, 16, 16, 0, uni(0, 0, [64, 0])); - let col = test_shared(&col_field, 8); - let lists = RefPicLists { - l0: vec![entry(0, 6, false)], - l1: Vec::new(), - }; - let mut field = MotionField::new(64, 64); - let mut p = params(false, 5, 2); - p.temporal_mvp = true; - let src = SliceMotion { - params: p, - lists: &lists, - cur_poc: 2, - field: &mut field, - col: Some(col), - publish: None, - slice: 0, - }; - // A 16x16 block at (16,16): bottom-right (32,32) is inside the picture and CTB row. - let got = derive_merge( - &src, - &cu(16, 16, 16, PartMode::Part2Nx2N), - 0, - &pu_at(16, 16, 16, 16, 0), - ); - assert_eq!(got, uni(0, 0, [-64, 0])); - } - - #[test] - fn temporal_candidate_with_long_term_mismatch_is_unavailable() { - // The current L0[0] is long-term, the collocated reference is short-term: - // the candidate is unavailable and the zero candidate is used. - let mut col_field = MotionField::new(64, 64); - col_field.slices.push(SliceRefs { - poc: [vec![4], vec![]], - long_term: [vec![false], vec![]], - }); - col_field.store(32, 32, 16, 16, 0, uni(0, 0, [64, 0])); - let col = test_shared(&col_field, 8); - let lists = RefPicLists { - l0: vec![entry(0, 0, true)], - l1: Vec::new(), - }; - let mut field = MotionField::new(64, 64); - let mut p = params(false, 5, 2); - p.temporal_mvp = true; - let src = SliceMotion { - params: p, - lists: &lists, - cur_poc: 4, - field: &mut field, - col: Some(col), - publish: None, - slice: 0, - }; - let got = derive_merge( - &src, - &cu(16, 16, 16, PartMode::Part2Nx2N), - 0, - &pu_at(16, 16, 16, 16, 0), - ); - assert_eq!(got, uni(0, 0, [0, 0])); - } - - #[test] - fn combined_bi_candidate_from_l0_and_l1_neighbours() { - // A1 is L0-only (POC 0), B1 is L1-only (POC 6): they pair into a bi candidate. - let lists = RefPicLists { - l0: vec![entry(0, 0, false)], - l1: vec![entry(1, 6, false)], - }; - let mut field = MotionField::new(64, 64); - let m0 = uni(0, 0, [2, 2]); - let m1 = uni(1, 0, [-5, 9]); - field.store(0, 16, 16, 16, 0, m0); // A1 - field.store(16, 0, 16, 16, 0, m1); // B1 (31,15) - let got = merge_with( - &mut field, - &lists, - params(true, 5, 2), - None, - cu(16, 16, 16, PartMode::Part2Nx2N), - pu_at(16, 16, 16, 16, 2), - 0, - ); - let expect = PbMotion::new([true, true], [0, 0], [[2, 2], [-5, 9]]); - assert_eq!(got, expect); - } - - #[test] - fn bi_candidate_becomes_uni_for_an_8x4_block() { - // A B slice whose A1 is bi-predicted: an 8x4 block keeps only L0. - let lists = RefPicLists { - l0: vec![entry(0, 0, false)], - l1: vec![entry(1, 8, false)], - }; - let mut field = MotionField::new(64, 64); - let bi = PbMotion::new([true, true], [0, 0], [[3, -3], [4, 4]]); - field.store(0, 16, 16, 16, 0, bi); // A1 of an 8x4 PU at (16,16) - let got = merge_with( - &mut field, - &lists, - params(true, 5, 2), - None, - cu(16, 16, 8, PartMode::Part2Nx2N), - pu_at(16, 16, 8, 4, 0), - 0, - ); - assert_eq!( - got, - PbMotion::new([true, false], [0, -1], [[3, -3], [0, 0]]) - ); - } - - #[test] - fn zero_candidates_use_increasing_reference_indices() { - // Two L0 references and merge_idx 1 with no spatial candidates: zero ref 1. - let lists = RefPicLists { - l0: vec![entry(0, 0, false), entry(1, 2, false)], - l1: Vec::new(), - }; - let mut field = MotionField::new(64, 64); - let got = merge_with( - &mut field, - &lists, - params(false, 5, 2), - None, - cu(16, 16, 16, PartMode::Part2Nx2N), - pu_at(16, 16, 16, 16, 1), - 0, - ); - assert_eq!(got, uni(0, 1, [0, 0])); - } -} diff --git a/crates/ec-h265/src/dec/mod.rs b/crates/ec-h265/src/dec/mod.rs index cb92670f..b54ca6fc 100644 --- a/crates/ec-h265/src/dec/mod.rs +++ b/crates/ec-h265/src/dec/mod.rs @@ -5,12 +5,7 @@ //! Scope is the base layer of Main, Main 10 and range extension streams. Every slice //! goes through [`cu_syntax::parse_slice_into`], which parses the slice data //! and pixel-decodes it. Inter slices write placeholder samples (see -//! [`inter::placeholder_cu`]) until motion compensation lands. With pixel -//! decode off ([`Decoder::set_pixel_decode`]) every slice is -//! parsed and every picture is managed, but no samples are produced; that is -//! the mode the picture-management tests use. [`Decoder::set_syntax_check`] -//! adds the slice-data parse ([`cu_syntax::parse_slice`]) to that mode, for -//! every slice type. +//! [`inter::placeholder_cu`]) until motion compensation lands. //! //! Decoded: Main, Main 10 and the range extension formats (4:0:0, 4:2:0, 4:2:2, 4:4:4 at //! 8 to 12 bits) with transform-skip extensions, implicit and explicit RDPCM, persistent @@ -47,7 +42,6 @@ pub mod sao; pub mod shared; pub mod slice_seg; pub mod tiles; -pub mod trace; pub mod weighted; use std::collections::VecDeque; @@ -65,9 +59,8 @@ pub use meta::PictureMeta; use picjob::{PicJob, SliceJob}; use rps::RpsInput; pub use rps::{RefEntry, RefPicLists, RefPicSet}; -use runner::{Budget, Checksum, Runner}; +use runner::{Budget, Runner}; use shared::SharedPic; -use std::sync::Mutex; use std::thread::JoinHandle; /// What [`Decoder::push_nal`] did with a NAL unit. @@ -100,8 +93,6 @@ struct CurPicture { runner: Runner, /// The published picture (the samples and collocated motion that later pictures read). shared: Arc, - /// The motion checksum, set when the picture finishes. - checksum: Arc, /// The header of the picture's latest independent slice segment; the /// dependent segments after it take their values from it. header: Option, @@ -132,15 +123,11 @@ fn picture_limit(threads: usize) -> usize { } } -/// The worker-thread budget: `EC_H265_THREADS` when it is a positive number, else -/// the machine's available parallelism. Either way capped at [`MAX_THREADS`]. +/// The worker-thread budget: the machine's available parallelism, capped at [`MAX_THREADS`]. pub fn configured_threads() -> usize { - let requested = std::env::var("EC_H265_THREADS") - .ok() - .and_then(|v| v.trim().parse::().ok()) - .filter(|&n| n > 0) - .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())); - requested.min(MAX_THREADS) + std::thread::available_parallelism() + .map_or(1, |n| n.get()) + .min(MAX_THREADS) } /// Streaming HEVC decoder with the same surface as the H.264 one: feed NAL @@ -149,13 +136,10 @@ pub struct Decoder { vps: Vec>, sps: Vec>>, pps: Vec>>, - pixel_decode: bool, /// Worker threads for the in-loop filters (see [`configured_threads`]). threads: usize, /// The worker threads the pictures and their wavefront rows share. budget: Arc, - /// Parse every slice's data (all types) with [`cu_syntax`] when pixel decode is off. - syntax_check: bool, dpb: Dpb, cur: Option, /// Set while the slices of a skipped RASL picture go by. @@ -174,23 +158,12 @@ pub struct Decoder { hdr_pending: PictureMeta, /// The HDR SEI in force in the current coded video sequence. hdr_persist: PictureMeta, - /// The motion checksum of the finished pictures (see [`Decoder::motion_checksum`]). - checksums: Mutex, /// Worker threads of the pictures that finished but may still run, oldest first. in_flight: VecDeque>, /// The most pictures in flight (see [`picture_limit`]). max_in_flight: usize, } -/// The motion checksum folded over the finished pictures in decoding order. -#[derive(Default)] -struct ChecksumFold { - /// The fold of every picture whose checksum has been waited for. - fold: u64, - /// The checksums of the finished pictures not yet folded, in decoding order. - pending: VecDeque>, -} - impl Default for Decoder { fn default() -> Self { Decoder::new() @@ -198,16 +171,14 @@ impl Default for Decoder { } impl Decoder { - /// A decoder with no parameter sets and pixel decode on. + /// A decoder with no parameter sets. pub fn new() -> Decoder { Decoder { vps: vec![None; 16], sps: vec![None; 16], pps: vec![None; 64], - pixel_decode: true, threads: configured_threads(), budget: Budget::new(configured_threads()), - syntax_check: false, dpb: Dpb::new(), cur: None, skipping: false, @@ -219,7 +190,6 @@ impl Decoder { out: VecDeque::new(), hdr_pending: PictureMeta::default(), hdr_persist: PictureMeta::default(), - checksums: Mutex::new(ChecksumFold::default()), in_flight: VecDeque::new(), max_in_flight: picture_limit(configured_threads()), } @@ -232,38 +202,6 @@ impl Decoder { self.budget = Budget::new(self.threads); } - /// Turn pixel decode on or off. Off parses every slice and manages every - /// picture (RPS, POC, bumping) without producing samples; inter slices are - /// accepted in that mode. - pub fn set_pixel_decode(&mut self, on: bool) { - self.pixel_decode = on; - } - - /// Whether pixel decode is on. - pub fn pixel_decode(&self) -> bool { - self.pixel_decode - } - - /// A hash of the motion field of every picture finished so far, in decoding order. - /// Two decodes of the same stream give the same value; a change in any derived - /// motion vector, reference index or prediction flag changes it. - pub fn motion_checksum(&self) -> u64 { - let mut fold = self.checksums.lock().unwrap_or_else(|e| e.into_inner()); - while let Some(slot) = fold.pending.pop_front() { - if let Some(sum) = slot.wait() { - fold.fold = (fold.fold ^ sum).wrapping_mul(0x0000_0100_0000_01b3); - } - } - fold.fold - } - - /// With pixel decode off, also parse every slice's data with the CU syntax - /// parser. A parse that does not reach `end_of_slice_segment_flag` at the - /// end of the slice is an error from [`Decoder::push_nal`]. - pub fn set_syntax_check(&mut self, on: bool) { - self.syntax_check = on; - } - /// The VPS stored under `id`. pub fn vps(&self, id: u32) -> Option<&Vps> { self.vps.get(id as usize)?.as_ref() @@ -279,17 +217,6 @@ impl Decoder { self.pps.get(id as usize)?.as_deref() } - /// `RefPicList0` and `RefPicList1` of the most recent slice of the picture - /// being decoded. - pub fn ref_pic_lists(&self) -> Option<&RefPicLists> { - self.cur.as_ref().map(|c| &c.lists) - } - - /// The reference picture set of the picture being decoded. - pub fn ref_pic_set(&self) -> Option<&RefPicSet> { - self.cur.as_ref().map(|c| &c.rps) - } - /// A picture in the decoded picture buffer, by id. pub fn picture(&self, id: u32) -> Option<&DpbPicture> { self.dpb.get(id) @@ -324,12 +251,9 @@ impl Decoder { for pending in &self.out { pending.picture.wait_done()?; } - let t = trace::now(); for handle in self.in_flight.drain(..) { let _ = handle.join(); } - trace::since(trace::Phase::WaitJoin, t); - trace::report(); Ok(()) } @@ -531,10 +455,10 @@ impl Decoder { irap_no_rasl: irap && no_rasl, width: sps.pic_width_in_luma_samples as usize, height: sps.pic_height_in_luma_samples as usize, - fill: self.pixel_decode.then_some(( + fill: ( sps.bit_depth_luma_minus8 + 8, sps.bit_depth_chroma_minus8 + 8, - )), + ), chroma_format_idc: sps.chroma_format_idc, }; let rps = self.dpb.apply_rps(&input); @@ -569,15 +493,13 @@ impl Decoder { } // Frame threads: at most `threads` pictures in flight, so wait for the oldest. - let threaded = self.threads > 1 && self.pixel_decode; + let threaded = self.threads > 1; if threaded { - let t = trace::now(); while self.in_flight.len() >= self.max_in_flight { if let Some(handle) = self.in_flight.pop_front() { let _ = handle.join(); } } - trace::since(trace::Phase::WaitAdmit, t); } let shared = Arc::new(SharedPic::new( poc, @@ -587,13 +509,10 @@ impl Decoder { 8 + sps.bit_depth_luma_minus8, 8 + sps.bit_depth_chroma_minus8, ), - self.pixel_decode, sps.chroma_format_idc, )); - let checksum = Arc::new(Checksum::default()); let runner = Runner::start( PicJob::new(Arc::clone(&shared), Arc::clone(&self.budget)), - Arc::clone(&checksum), threaded, ); self.cur = Some(CurPicture { @@ -606,7 +525,6 @@ impl Decoder { lists: RefPicLists::default(), runner, shared, - checksum, all_intra: true, meta, }); @@ -614,7 +532,7 @@ impl Decoder { } /// Build the slice's reference lists, then hand the slice data to the picture's - /// job. Nothing runs when pixel decode and the syntax check are both off. + /// job. fn decode_slice( &mut self, slice: &SliceHeader, @@ -624,7 +542,6 @@ impl Decoder { sps: &Arc, pps: &Arc, ) -> Result<()> { - let pixel = self.pixel_decode; let dpb = &self.dpb; let cur = self .cur @@ -636,9 +553,6 @@ impl Decoder { if slice.slice_type != SliceType::I { cur.all_intra = false; } - if !pixel && !self.syntax_check { - return Ok(()); - } let data_off = (pos.header_bits / 8) as usize; if data_off > rbsp.len() { return Err(Error::corrupt( @@ -660,14 +574,13 @@ impl Decoder { }) .collect() }; - let refs = if pixel && slice.slice_type != SliceType::I { + let refs = if slice.slice_type != SliceType::I { [lookup(&cur.lists.l0)?, lookup(&cur.lists.l1)?] } else { [Vec::new(), Vec::new()] }; let col = motion_field::collocated(dpb, slice, &cur.lists); - let t = trace::now(); - let submitted = cur.runner.submit(SliceJob { + cur.runner.submit(SliceJob { rbsp, data_off, header: slice.clone(), @@ -677,20 +590,15 @@ impl Decoder { refs, col, cur_poc: cur.poc, - pixel, substreams, - }); - trace::since(trace::Phase::Decode, t); - submitted + }) } /// C.5.2.3: store the open picture in the buffer and run the additional /// bumping. Idempotent when no picture is open. The picture's samples may still be /// being decoded (on its worker); output waits for them. fn finish_picture(&mut self) { - let t = trace::now(); self.finish_picture_inner(); - trace::since(trace::Phase::Serial, t); } fn finish_picture_inner(&mut self) { @@ -704,17 +612,11 @@ impl Decoder { output, runner, shared, - checksum, all_intra, mut meta, .. } = cur; meta.intra_only = all_intra; - self.checksums - .lock() - .unwrap_or_else(|e| e.into_inner()) - .pending - .push_back(checksum); if let Some(handle) = runner.finish() { self.in_flight.push_back(handle); } diff --git a/crates/ec-h265/src/dec/motion_field.rs b/crates/ec-h265/src/dec/motion_field.rs index a87cfc27..00811d0c 100644 --- a/crates/ec-h265/src/dec/motion_field.rs +++ b/crates/ec-h265/src/dec/motion_field.rs @@ -15,7 +15,7 @@ use std::sync::Arc; -use super::cu_syntax::{CuGeometry, Motion, MotionSource, PredictionUnit}; +use super::cu_syntax::{Motion, PartMode, PredictionUnit}; use super::dpb::Dpb; use super::pic::{PicState, PuMotion}; use super::rps::{RefEntry, RefPicLists}; @@ -24,9 +24,6 @@ use super::{amvp, merge}; use ec_h265_syntax::slice::{SliceHeader, SliceType}; use ec_h265_syntax::{Pps, Sps}; -const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; -const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; - /// The motion of one prediction block: `predFlagLX`, `refIdxLX` and `mvLX` for both /// lists. An unused list has reference index -1 and a zero vector, so two blocks /// with the same motion compare equal. @@ -58,7 +55,7 @@ impl PbMotion { PbMotion::new(m.pred_flags, m.ref_idx, [to16(m.mv[0]), to16(m.mv[1])]) } - /// The [`Motion`] a [`MotionSource`] returns for this block. + /// The [`Motion`] [`SliceMotion::derive_motion`] returns for this block. pub fn to_motion(self) -> Motion { Motion { pred_flags: self.pred, @@ -116,7 +113,6 @@ pub struct MotionField { cells: Vec>, /// The reference lists of each slice of the picture, indexed by `FieldCell::slice`. pub slices: Vec, - checksum: u64, /// `TileId` of each CTB, raster order; empty when the picture has one tile. tiles: Vec, /// `CtbLog2SizeY` and the CTBs per row, for the tile lookup. @@ -127,18 +123,6 @@ pub struct MotionField { /// The 4x4 unit row of `cells[0..width4]`: zero for a whole picture, and the row above /// the band for a wavefront row band (see [`MotionField::band`]). origin4: usize, - /// A wavefront band: its stores are kept in `words` for the picture's checksum, which - /// folds them in decoding order once the band is merged. - band: bool, - words: Vec, -} - -/// The collocated view of a finished test field, as a picture of its own. -#[cfg(test)] -pub fn test_shared(field: &MotionField, poc: i32) -> Arc { - let shared = SharedPic::new(poc, field.width(), field.height(), (8, 8), false, 1); - shared.publish_col(field, field.height()); - Arc::new(shared) } impl MotionField { @@ -152,14 +136,11 @@ impl MotionField { width4, cells: vec![None; width4 * height4], slices: Vec::new(), - checksum: FNV_OFFSET, tiles: Vec::new(), ctb_log2: 0, ctb_cols: 0, cur_tile: 0, origin4: 0, - band: false, - words: Vec::new(), } } @@ -173,14 +154,11 @@ impl MotionField { width4: self.width4, cells: vec![None; unit_rows * self.width4], slices: Vec::new(), - checksum: FNV_OFFSET, tiles: self.tiles.clone(), ctb_log2: self.ctb_log2, ctb_cols: self.ctb_cols, cur_tile: 0, origin4, - band: true, - words: Vec::new(), } } @@ -206,18 +184,12 @@ impl MotionField { } /// Merge a finished band into this field: its cells from unit row `first_unit_row` on - /// are copied, and its stores are folded into the checksum in decoding order. Bands - /// merged in decoding order give the checksum a whole-picture decode would give. + /// are copied. pub fn merge_band(&mut self, band: &MotionField, first_unit_row: usize) { let from = (first_unit_row - band.origin4) * self.width4; let to = first_unit_row - self.origin4; let n = band.cells.len() - from; self.cells[to * self.width4..to * self.width4 + n].copy_from_slice(&band.cells[from..]); - for words in band.words.as_chunks::<8>().0 { - for &word in words { - self.checksum = (self.checksum ^ word).wrapping_mul(FNV_PRIME); - } - } } /// The tile of each CTB (raster order), so that a neighbour in another tile is @@ -321,30 +293,6 @@ impl MotionField { Some(FieldCell { motion, slice }); } } - let mut words = [0u64; 8]; - words[0] = x as u64; - words[1] = y as u64; - words[2] = w as u64; - words[3] = h as u64; - words[4] = u64::from(slice); - words[5] = u64::from(motion.pred[0]) | (u64::from(motion.pred[1]) << 1); - words[6] = (motion.ref_idx[0] as u8 as u64) | ((motion.ref_idx[1] as u8 as u64) << 8); - words[7] = (motion.mv[0][0] as u16 as u64) - | ((motion.mv[0][1] as u16 as u64) << 16) - | ((motion.mv[1][0] as u16 as u64) << 32) - | ((motion.mv[1][1] as u16 as u64) << 48); - if self.band { - self.words.extend_from_slice(&words); - return; - } - for word in words { - self.checksum = (self.checksum ^ word).wrapping_mul(FNV_PRIME); - } - } - - /// A hash of every stored block, in decoding order. Equal for equal derivations. - pub fn checksum(&self) -> u64 { - self.checksum } /// The motion of every 4x4 unit in the form the deblocking filter reads (8.7.2.4). @@ -479,7 +427,7 @@ pub struct MotionParams { pub no_backward_pred: bool, } -/// The [`MotionSource`] of the decoder: derives each prediction unit's motion with +/// The motion source of the decoder: derives each prediction unit's motion with /// the merge or AMVP process and stores it in the picture's motion field. pub struct SliceMotion<'a> { /// Slice parameters. @@ -493,7 +441,7 @@ pub struct SliceMotion<'a> { /// The collocated picture, if temporal prediction applies. pub col: Option>, /// The picture this slice belongs to, when its rows are published as they are - /// decoded (see [`MotionSource::row_done`]). + /// decoded (see [`SliceMotion::row_done`]). pub publish: Option>, /// Index of this slice in the picture's slice list. pub slice: u16, @@ -586,9 +534,7 @@ impl<'a> SliceMotion<'a> { // Both candidates lie in the CTB row of `y` (the bottom-right one only when it // stays in that row), so the collocated rows up to the end of that row suffice. let need = (((y >> ctb) + 1) << ctb).min(self.field.height()); - let t = super::trace::now(); let waited = shared.wait_col_rows(need); - super::trace::since(super::trace::Phase::WaitCol, t); waited.ok()?; let col = shared.read_col(); if (y >> ctb) == (ybr >> ctb) && ybr < self.field.height() && xbr < self.field.width() { @@ -643,28 +589,33 @@ impl<'a> SliceMotion<'a> { } } -impl MotionSource for SliceMotion<'_> { - fn row_done(&mut self, pic: &mut PicState, row_end: usize) { +impl SliceMotion<'_> { + /// Called once the CTB row that ends at luma row `row_end` is fully parsed. + pub fn row_done(&mut self, pic: &mut PicState, row_end: usize) { // The CTB row that ended is `row_end - ctb`; its motion is final. let ctb = 1usize << self.params.ctb_log2; let y0 = row_end.saturating_sub(ctb); - if pic.has_pixels() { - let (u0, u1) = (y0, row_end.min(self.field.height())); - self.field.deblock_rows(&mut pic.motion, u0, u1); - } + let (u0, u1) = (y0, row_end.min(self.field.height())); + self.field.deblock_rows(&mut pic.motion, u0, u1); if let Some(shared) = &self.publish { shared.publish_col(self.field, row_end); } } - fn band_cells(&mut self) -> Option<&mut MotionField> { - Some(&mut *self.field) - } - - fn derive_motion(&mut self, cu: &CuGeometry, pu_index: usize, pu: &PredictionUnit) -> Motion { - self.field.cur_tile = self.field.tile_at(cu.x, cu.y); + /// The motion of unit `pu_index` of the coding unit at `(x, y)`, `size` luma samples + /// square, derived and stored. + pub fn derive_motion( + &mut self, + x: usize, + y: usize, + size: usize, + part_mode: PartMode, + pu_index: usize, + pu: &PredictionUnit, + ) -> Motion { + self.field.cur_tile = self.field.tile_at(x, y); let derived = if pu.merge_flag { - merge::derive_merge(self, cu, pu_index, pu) + merge::derive_merge(self, x, y, size, part_mode, pu_index, pu) } else { amvp::derive_amvp(self, pu) }; @@ -692,12 +643,6 @@ pub fn scale_mv(mv: [i32; 2], td: i32, tb: i32) -> [i32; 2] { }) } -/// The chroma vector of 4:2:0 content, in 1/8 chroma sample units (8.5.3.2.10): -/// the luma quarter-sample vector, unchanged in value. -pub fn chroma_mv_420(mv: [i16; 2]) -> [i32; 2] { - to32(mv) -} - /// A vector widened to `i32`. pub fn to32(mv: [i16; 2]) -> [i32; 2] { [i32::from(mv[0]), i32::from(mv[1])] diff --git a/crates/ec-h265/src/dec/pic.rs b/crates/ec-h265/src/dec/pic.rs index 45ecdfff..b4d314e6 100644 --- a/crates/ec-h265/src/dec/pic.rs +++ b/crates/ec-h265/src/dec/pic.rs @@ -163,7 +163,7 @@ pub struct PicState { pub pps_cb_qp_offset: i32, /// See `pps_cb_qp_offset`. pub pps_cr_qp_offset: i32, - /// The samples. Empty planes when the decoder runs without pixel decode. + /// The samples. pub planes: DecodedPicture, /// Per 4x4 unit, `w4 * h4`. pub info: Vec, @@ -189,8 +189,7 @@ pub struct PicState { } impl PicState { - /// The state of a `width` x `height` picture. With `pixels` false the - /// sample planes are left empty and only the maps are kept. + /// The state of a `width` x `height` picture. #[allow(clippy::too_many_arguments)] // one value per picture-level SPS/PPS fact pub fn new( width: usize, @@ -199,27 +198,13 @@ impl PicState { min_tb_log2: u32, bit_depth_y: u32, bit_depth_c: u32, - pixels: bool, ) -> PicState { let ctb = 1usize << ctb_log2; let ctb_cols = width.div_ceil(ctb); let ctb_rows = height.div_ceil(ctb); let w4 = width.div_ceil(4); let h4 = height.div_ceil(4); - let planes = if pixels { - DecodedPicture::grey_planes(width, height, bit_depth_y, bit_depth_c) - } else { - DecodedPicture { - width, - height, - bit_depth: bit_depth_y, - bit_depth_c, - chroma_format_idc: 1, - y: Vec::new(), - cb: Vec::new(), - cr: Vec::new(), - } - }; + let planes = DecodedPicture::grey_planes(width, height, bit_depth_y, bit_depth_c, 1); PicState { width, height, @@ -262,11 +247,6 @@ impl PicState { crate::decode::chroma_shifts(self.chroma_format_idc).1 } - /// Whether the sample planes are allocated (pixel decode is on). - pub fn has_pixels(&self) -> bool { - !self.planes.y.is_empty() - } - /// The three writable sample planes, for motion compensation. pub fn planes_mut(&mut self) -> [PlaneMut<'_>; 3] { let (bd_y, bd_c) = (self.bit_depth_y, self.bit_depth_c); @@ -384,9 +364,8 @@ impl PicState { } } - /// The state of a picture of `sps` and `pps`. With `pixels` on, the sample - /// planes are allocated, grey. - pub fn for_sps_pps(sps: &Sps, pps: &Pps, pixels: bool) -> PicState { + /// The state of a picture of `sps` and `pps`, its sample planes grey. + pub fn for_sps_pps(sps: &Sps, pps: &Pps) -> PicState { let min_cb_log2 = sps.log2_min_cb_size_minus3 + 3; let ctb_log2 = min_cb_log2 + sps.log2_diff_max_min_cb_size; let min_tb_log2 = sps.log2_min_tb_size_minus2 + 2; @@ -397,19 +376,16 @@ impl PicState { min_tb_log2, 8 + sps.bit_depth_luma_minus8, 8 + sps.bit_depth_chroma_minus8, - pixels, ); if sps.chroma_format_idc != 1 { pic.chroma_format_idc = sps.chroma_format_idc; - if pixels { - pic.planes = DecodedPicture::grey_planes_fmt( - pic.width, - pic.height, - pic.bit_depth_y, - pic.bit_depth_c, - sps.chroma_format_idc, - ); - } + pic.planes = DecodedPicture::grey_planes( + pic.width, + pic.height, + pic.bit_depth_y, + pic.bit_depth_c, + sps.chroma_format_idc, + ); } pic.constrained_intra_pred = pps.constrained_intra_pred; pic.strong_intra_smoothing = sps.strong_intra_smoothing; @@ -426,7 +402,7 @@ impl PicState { /// first, so the band's first sample, unit and CTB rows are that row (copied in by /// the wavefront driver). The maps cover only the band; the CTB table is the /// whole picture's shape, and the tile scan and slice state are copied. - pub fn band(&self, y0: usize, own: usize, pixels: bool) -> PicState { + pub fn band(&self, y0: usize, own: usize) -> PicState { let bound = usize::from(y0 > 0); let own_units = own.div_ceil(4); let (sx, sy) = crate::decode::chroma_shifts(self.chroma_format_idc); @@ -438,21 +414,9 @@ impl PicState { bit_depth: self.bit_depth_y, bit_depth_c: self.bit_depth_c, chroma_format_idc: self.chroma_format_idc, - y: if pixels { - vec![0; (bound + own) * self.width] - } else { - Vec::new() - }, - cb: if pixels { - vec![0; (bound + own_c) * cw] - } else { - Vec::new() - }, - cr: if pixels { - vec![0; (bound + own_c) * cw] - } else { - Vec::new() - }, + y: vec![0; (bound + own) * self.width], + cb: vec![0; (bound + own_c) * cw], + cr: vec![0; (bound + own_c) * cw], }; PicState { width: self.width, diff --git a/crates/ec-h265/src/dec/picjob.rs b/crates/ec-h265/src/dec/picjob.rs index 5c9e19ff..461c4554 100644 --- a/crates/ec-h265/src/dec/picjob.rs +++ b/crates/ec-h265/src/dec/picjob.rs @@ -42,8 +42,6 @@ pub struct SliceJob { pub col: Option>, /// `PicOrderCntVal` of the picture. pub cur_poc: i32, - /// Reconstruct the samples (pixel decode). Off parses the syntax and the motion only. - pub pixel: bool, /// Where the substreams after the first start, relative to `data_off` (one per CTB row /// after the segment's first, from the entry points). Empty when there are none. pub substreams: Vec, @@ -95,7 +93,7 @@ impl PicJob { .. } = self; let (sps, pps) = (&*job.sps, &*job.pps); - let pic = pic.get_or_insert_with(|| PicState::for_sps_pps(sps, pps, job.pixel)); + let pic = pic.get_or_insert_with(|| PicState::for_sps_pps(sps, pps)); let (w, h) = ( sps.pic_width_in_luma_samples as usize, sps.pic_height_in_luma_samples as usize, @@ -112,7 +110,7 @@ impl PicJob { field.slices.push(SliceRefs::from_lists(&job.lists)); } let slice = u16::try_from(field.slices.len().saturating_sub(1)).unwrap_or(u16::MAX); - let refs = if job.pixel && job.header.slice_type != SliceType::I { + let refs = if job.header.slice_type != SliceType::I { Some(InterRefs::new(job.refs, &job.header, sps)?) } else { None @@ -181,10 +179,9 @@ impl PicJob { Ok(()) } - /// The picture is complete: run the rest of the in-loop filters, publish every - /// row and the collocated motion, and return the picture's motion checksum (`None` - /// when no slice ran). - pub fn finish(&mut self) -> Option { + /// The picture is complete: run the rest of the in-loop filters, and publish every + /// row and the collocated motion. + pub fn finish(&mut self) { let PicJob { shared, pic, @@ -194,22 +191,18 @@ impl PicJob { } = self; let Some(mut pic) = pic.take() else { shared.complete(); - return None; + return; }; let h = shared.height; // Slices that finished no CTB row (or several tiles) left the motion of the // units for the filter to read; fill every unit now. - let checksum = motion.take().map(|field| { - if pic.has_pixels() { - field.deblock_rows(&mut pic.motion, 0, h); - } + if let Some(field) = motion.take() { + field.deblock_rows(&mut pic.motion, 0, h); shared.publish_col(&field, h); - field.checksum() - }); + } let rows = pic.ctb_rows; let final_rows = filter.advance(&mut pic, rows); shared.publish_rows(&pic.planes, final_rows); shared.complete(); - checksum } } diff --git a/crates/ec-h265/src/dec/recon.rs b/crates/ec-h265/src/dec/recon.rs index c0905809..b9bb318d 100644 --- a/crates/ec-h265/src/dec/recon.rs +++ b/crates/ec-h265/src/dec/recon.rs @@ -118,16 +118,6 @@ impl PicState { } } - /// Write `value` into every sample of an `n` x `n` block of component `c`. - pub fn fill_plane(&mut self, c: usize, x: usize, y: usize, n: usize, value: u16) { - let origin = self.plane_origin(c); - let (stride, plane) = self.plane_view_mut(c); - for j in 0..n { - let start = (y + j - origin) * stride + x; - plane[start..start + n].fill(value); - } - } - /// The row stride of the chroma planes. fn chroma_stride(&self) -> usize { self.width.div_ceil(1 << self.sub_x()) diff --git a/crates/ec-h265/src/dec/rowfilter.rs b/crates/ec-h265/src/dec/rowfilter.rs index 423d85a6..6f7e7a47 100644 --- a/crates/ec-h265/src/dec/rowfilter.rs +++ b/crates/ec-h265/src/dec/rowfilter.rs @@ -53,9 +53,7 @@ impl RowFilter { let ctb = 1usize << pic.ctb_log2; while self.deblocked < rows && (self.deblocked + 2 <= complete || all) { let r = self.deblocked; - if pic.has_pixels() { - deblock::deblock_rows(pic, r * ctb..(r + 1) * ctb); - } + deblock::deblock_rows(pic, r * ctb..(r + 1) * ctb); self.deblocked += 1; } while self.filtered < rows @@ -74,9 +72,6 @@ impl RowFilter { /// SAO of CTB row `r` for the three planes, then remember its last deblocked line. fn sao_row(&mut self, pic: &mut PicState, r: usize) { - if !pic.has_pixels() { - return; - } let ctb = 1usize << pic.ctb_log2; // Does any CTB of the row use SAO? Without one the row is final as it is. let sao_on = (r * pic.ctb_cols..(r + 1) * pic.ctb_cols).any(|i| { diff --git a/crates/ec-h265/src/dec/rps.rs b/crates/ec-h265/src/dec/rps.rs index e2bfc751..2cd34392 100644 --- a/crates/ec-h265/src/dec/rps.rs +++ b/crates/ec-h265/src/dec/rps.rs @@ -27,9 +27,8 @@ pub struct RpsInput<'a> { /// Luma height of the picture, for generated pictures. pub height: usize, /// Bit depths (luma, chroma) of a generated (8.3.3) picture, whose samples are - /// grey. `None` generates a picture without samples, for a decoder that does - /// not decode pixels. - pub fill: Option<(u32, u32)>, + /// grey. + pub fill: (u32, u32), /// `chroma_format_idc` of the generated picture. pub chroma_format_idc: u32, } @@ -236,25 +235,14 @@ impl Dpb { /// Generate a missing reference picture (8.3.3.2): grey samples, no output. fn generate(&mut self, poc: i32, marking: Marking, input: &RpsInput<'_>) -> u32 { - let picture = match input.fill { - Some((bit_depth, bit_depth_c)) => DecodedPicture::grey_planes_fmt( - input.width, - input.height, - bit_depth, - bit_depth_c, - input.chroma_format_idc, - ), - None => DecodedPicture { - width: input.width, - height: input.height, - bit_depth: 8, - bit_depth_c: 8, - chroma_format_idc: input.chroma_format_idc, - y: Vec::new(), - cb: Vec::new(), - cr: Vec::new(), - }, - }; + let (bit_depth, bit_depth_c) = input.fill; + let picture = DecodedPicture::grey_planes( + input.width, + input.height, + bit_depth, + bit_depth_c, + input.chroma_format_idc, + ); self.insert( poc, marking, diff --git a/crates/ec-h265/src/dec/runner.rs b/crates/ec-h265/src/dec/runner.rs index 606ca204..db79af6d 100644 --- a/crates/ec-h265/src/dec/runner.rs +++ b/crates/ec-h265/src/dec/runner.rs @@ -15,11 +15,10 @@ use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::mpsc::{self, Receiver, Sender}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard}; +use std::sync::{Arc, Mutex, MutexGuard}; use std::thread::JoinHandle; use super::picjob::{PicJob, SliceJob}; -use super::trace::{self, Phase}; use ec_core::error::{Error, Result}; fn lock(m: &Mutex) -> MutexGuard<'_, T> { @@ -107,34 +106,6 @@ impl Drop for PictureSlot { } } -/// The motion checksum of one picture (see [`super::Decoder::motion_checksum`]), set when -/// the picture finishes. The value is `None` for a picture no slice ran in, and also for a -/// picture that failed. -#[derive(Debug, Default)] -pub struct Checksum { - value: Mutex>>, - changed: Condvar, -} - -impl Checksum { - /// Store the picture's value and wake the readers. - pub fn set(&self, value: Option) { - *lock(&self.value) = Some(value); - self.changed.notify_all(); - } - - /// Wait until the value is stored. - pub fn wait(&self) -> Option { - let mut value = lock(&self.value); - loop { - if let Some(v) = *value { - return v; - } - value = self.changed.wait(value).unwrap_or_else(|e| e.into_inner()); - } - } -} - /// A message to a picture's worker. pub enum Msg { /// Run this slice segment. @@ -149,8 +120,6 @@ pub enum Runner { Inline { /// The picture's job. job: Box, - /// Set when the picture finishes. - checksum: Arc, }, /// On a worker thread that owns the job. Worker { @@ -163,15 +132,12 @@ pub enum Runner { impl Runner { /// Start the decoding of the picture of `job`. `threaded` gives it a worker thread. - pub fn start(job: PicJob, checksum: Arc, threaded: bool) -> Runner { + pub fn start(job: PicJob, threaded: bool) -> Runner { if !threaded { - return Runner::Inline { - job: Box::new(job), - checksum, - }; + return Runner::Inline { job: Box::new(job) }; } let (tx, rx) = mpsc::channel(); - let handle = std::thread::spawn(move || run_worker(rx, job, checksum)); + let handle = std::thread::spawn(move || run_worker(rx, job)); Runner::Worker { tx, handle } } @@ -193,8 +159,8 @@ impl Runner { /// goes on in the background; its handle is returned to be joined later. pub fn finish(self) -> Option> { match self { - Runner::Inline { mut job, checksum } => { - checksum.set(job.finish()); + Runner::Inline { mut job } => { + job.finish(); None } Runner::Worker { tx, handle } => { @@ -207,39 +173,27 @@ impl Runner { /// The body of a picture's worker thread. A failure, a panic, or a picture dropped before /// its finish marks the picture as failed, so that nothing waits on it forever. -fn run_worker(rx: Receiver, mut job: PicJob, checksum: Arc) { +fn run_worker(rx: Receiver, mut job: PicJob) { let shared = Arc::clone(job.shared()); - trace::set_role("picture"); - let outcome = catch_unwind(AssertUnwindSafe(|| -> Result> { + let outcome = catch_unwind(AssertUnwindSafe(|| -> Result<()> { loop { - let idle = trace::now(); let msg = rx.recv(); - trace::since(Phase::WaitMsg, idle); let Ok(msg) = msg else { break }; - let busy = trace::now(); match msg { Msg::Slice(slice) => job.run_slice(*slice)?, Msg::Finish => { - let sum = job.finish(); - trace::since(Phase::Decode, busy); - return Ok(sum); + job.finish(); + return Ok(()); } } - trace::since(Phase::Decode, busy); } Err(Error::corrupt( "HEVC decode: a picture was dropped before it finished".to_string(), )) })); match outcome { - Ok(Ok(sum)) => checksum.set(sum), - Ok(Err(e)) => { - shared.fail(&e.to_string()); - checksum.set(None); - } - Err(_) => { - shared.fail("HEVC decode: the picture's worker thread panicked"); - checksum.set(None); - } + Ok(Ok(())) => {} + Ok(Err(e)) => shared.fail(&e.to_string()), + Err(_) => shared.fail("HEVC decode: the picture's worker thread panicked"), } } diff --git a/crates/ec-h265/src/dec/sao.rs b/crates/ec-h265/src/dec/sao.rs index d075e09c..4fd34c23 100644 --- a/crates/ec-h265/src/dec/sao.rs +++ b/crates/ec-h265/src/dec/sao.rs @@ -40,9 +40,6 @@ pub fn sao_picture(pic: &mut PicState) { /// in parallel. A band reads the deblocked input (shared, read-only) and writes only /// its own rows of the output, so the bands never touch the same sample. pub fn sao_picture_threads(pic: &mut PicState, threads: usize) { - if !pic.has_pixels() { - return; - } let ro: &PicState = pic; let y = filter_plane(ro, 0, &ro.planes.y, threads); let cb = filter_plane(ro, 1, &ro.planes.cb, threads); @@ -362,7 +359,7 @@ mod tests { /// A 16x16 8-bit picture with one 16x16 CTB and no slices. fn picture() -> PicState { - PicState::new(16, 16, 4, 2, 8, 8, true) + PicState::new(16, 16, 4, 2, 8, 8) } /// SAO parameters for the luma component only. diff --git a/crates/ec-h265/src/dec/shared.rs b/crates/ec-h265/src/dec/shared.rs index ea8380b5..c9159a10 100644 --- a/crates/ec-h265/src/dec/shared.rs +++ b/crates/ec-h265/src/dec/shared.rs @@ -55,41 +55,26 @@ fn lock(m: &Mutex) -> MutexGuard<'_, T> { } impl SharedPic { - /// The storage of a `width` by `height` picture of POC `poc`. With `pixels` - /// false no sample planes are allocated (the motion-only decode). + /// The storage of a `width` by `height` picture of POC `poc`. pub fn new( poc: i32, width: usize, height: usize, bit_depth: (u32, u32), - pixels: bool, chroma_format_idc: u32, ) -> SharedPic { - let planes = if pixels { - let (sx, sy) = crate::decode::chroma_shifts(chroma_format_idc); - let cw = width.div_ceil(1 << sx); - let ch = height.div_ceil(1 << sy); - DecodedPicture { - width, - height, - bit_depth: bit_depth.0, - bit_depth_c: bit_depth.1, - chroma_format_idc, - y: vec![0; width * height], - cb: vec![0; cw * ch], - cr: vec![0; cw * ch], - } - } else { - DecodedPicture { - width, - height, - bit_depth: 8, - bit_depth_c: 8, - chroma_format_idc, - y: Vec::new(), - cb: Vec::new(), - cr: Vec::new(), - } + let (sx, sy) = crate::decode::chroma_shifts(chroma_format_idc); + let cw = width.div_ceil(1 << sx); + let ch = height.div_ceil(1 << sy); + let planes = DecodedPicture { + width, + height, + bit_depth: bit_depth.0, + bit_depth_c: bit_depth.1, + chroma_format_idc, + y: vec![0; width * height], + cb: vec![0; cw * ch], + cr: vec![0; cw * ch], }; SharedPic { width, @@ -122,10 +107,7 @@ impl SharedPic { /// Wait until at least `rows` luma rows are final. Returns the picture's failure /// instead when it has one. pub fn wait_rows(&self, rows: usize) -> Result<()> { - let t = super::trace::now(); - let r = self.wait_for(rows, |p| p.rows); - super::trace::since(super::trace::Phase::WaitRows, t); - r + self.wait_for(rows, |p| p.rows) } /// Wait until the collocated motion of at least `rows` luma rows is published. diff --git a/crates/ec-h265/src/dec/trace.rs b/crates/ec-h265/src/dec/trace.rs deleted file mode 100644 index 1ac64bd7..00000000 --- a/crates/ec-h265/src/dec/trace.rs +++ /dev/null @@ -1,155 +0,0 @@ -//! Opt-in timing of the decoder's threads, for finding where they sit idle. -//! -//! `EC_H265_TRACE=1` turns it on. Off (the default), every hook is one check of a cached -//! flag and no clock is read. On, each thread adds the time it spends in each [`Phase`] to -//! its own totals. A thread's totals are merged into the table of its role when the thread -//! ends (or, for the calling thread, when [`report`] runs), and [`report`] prints the table -//! to stderr at the end of the stream. - -use std::cell::RefCell; -use std::collections::BTreeMap; -use std::sync::{Mutex, MutexGuard, OnceLock}; -use std::time::{Duration, Instant}; - -/// The phases a thread's time is split into. -#[derive(Clone, Copy, Debug)] -pub enum Phase { - /// Decoding a slice, a wavefront row, or finishing a picture (wall time; it includes - /// the waits below that happen inside it). - Decode = 0, - /// Blocked until a reference picture has the rows a motion compensation reads. - WaitRows = 1, - /// Blocked joining the oldest in-flight picture to free a picture slot. - WaitAdmit = 2, - /// Blocked on the CABAC row-sync: the row above must be two CTBs ahead. - WaitSync = 3, - /// A picture worker idle, waiting for the next slice or the finish message. - WaitMsg = 4, - /// Blocked joining the picture workers at end of stream. - WaitJoin = 5, - /// Serial work on the calling thread outside the slice decode: picture start and - /// finish (RPS, bumping, DPB insert). - Serial = 6, - /// Blocked until the collocated picture has the motion rows temporal prediction reads. - WaitCol = 7, -} - -const N: usize = 8; -/// Whether tracing is on (`EC_H265_TRACE` set to anything but `0`). -pub fn on() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("EC_H265_TRACE").is_some_and(|v| v != "0")) -} - -/// The start of a timed span, or `None` when tracing is off (no clock is read). -#[inline] -pub fn now() -> Option { - if on() { Some(Instant::now()) } else { None } -} - -/// Add the time since `start` to `phase` of this thread. -#[inline] -pub fn since(phase: Phase, start: Option) { - if let Some(t) = start { - add(phase, t.elapsed()); - } -} - -fn add(phase: Phase, d: Duration) { - let _ = ACC.try_with(|a| { - a.borrow_mut().ns[phase as usize] += d.as_nanos() as u64; - }); -} - -/// Name this thread's role in the report (the default is `caller`). -pub fn set_role(role: &'static str) { - if on() { - let _ = ACC.try_with(|a| a.borrow_mut().role = role); - } -} - -#[derive(Default)] -struct Totals { - threads: usize, - ns: [u64; N], -} - -fn totals() -> MutexGuard<'static, BTreeMap<&'static str, Totals>> { - static T: Mutex> = Mutex::new(BTreeMap::new()); - T.lock().unwrap_or_else(|e| e.into_inner()) -} - -struct Acc { - role: &'static str, - ns: [u64; N], -} - -impl Acc { - /// Merge this thread's totals into its role's table and clear them. - fn merge(&mut self) { - if self.ns.iter().all(|&n| n == 0) { - return; - } - let mut t = totals(); - let e = t.entry(self.role).or_default(); - e.threads += 1; - for (dst, src) in e.ns.iter_mut().zip(self.ns.iter()) { - *dst += src; - } - self.ns = [0; N]; - } -} - -impl Drop for Acc { - fn drop(&mut self) { - self.merge(); - } -} - -thread_local! { - static ACC: RefCell = const { RefCell::new(Acc { role: "caller", ns: [0; N] }) }; -} - -/// Merge the calling thread's totals, then print every role's table to stderr and clear -/// the tables. Worker threads have merged already: they are joined before this runs. -pub fn report() { - if !on() { - return; - } - let _ = ACC.try_with(|a| a.borrow_mut().merge()); - let mut t = totals(); - if t.is_empty() { - return; - } - eprintln!("EC_H265_TRACE (ms, summed over the threads of each role)"); - eprintln!( - "{:<12}{:>8}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}{:>12}", - "role", - "threads", - "decode", - "wait_rows", - "wait_col", - "wait_admit", - "wait_sync", - "wait_msg", - "wait_join", - "serial" - ); - for (role, tot) in t.iter() { - let ms = |p: Phase| tot.ns[p as usize] as f64 / 1e6; - eprintln!( - "{:<12}{:>8}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}{:>12.1}", - role, - tot.threads, - ms(Phase::Decode), - ms(Phase::WaitRows), - ms(Phase::WaitCol), - ms(Phase::WaitAdmit), - ms(Phase::WaitSync), - ms(Phase::WaitMsg), - ms(Phase::WaitJoin), - ms(Phase::Serial), - ); - } - t.clear(); -} diff --git a/crates/ec-h265/src/decode.rs b/crates/ec-h265/src/decode.rs index 09316513..068b8bd8 100644 --- a/crates/ec-h265/src/decode.rs +++ b/crates/ec-h265/src/decode.rs @@ -51,10 +51,6 @@ impl DecodedPicture { let (sx, sy) = self.chroma_shifts(); (self.width.div_ceil(1 << sx), self.height.div_ceil(1 << sy)) } - /// A picture of mid-grey samples (`1 << (bit_depth - 1)`). - pub fn grey(width: usize, height: usize, bit_depth: u32) -> DecodedPicture { - Self::grey_planes(width, height, bit_depth, bit_depth) - } /// A picture of mid-grey samples, each plane at its own bit depth. pub fn grey_planes( @@ -62,16 +58,6 @@ impl DecodedPicture { height: usize, bit_depth: u32, bit_depth_c: u32, - ) -> DecodedPicture { - Self::grey_planes_fmt(width, height, bit_depth, bit_depth_c, 1) - } - - /// [`Self::grey_planes`] for any `chroma_format_idc`. - pub fn grey_planes_fmt( - width: usize, - height: usize, - bit_depth: u32, - bit_depth_c: u32, chroma_format_idc: u32, ) -> DecodedPicture { let mid = 1u16 << (bit_depth - 1); @@ -89,20 +75,6 @@ impl DecodedPicture { cr: vec![mid_c; cw * ch], } } - - /// The bit depth of component `c` (0 luma, 1 and 2 chroma). - pub fn bit_depth_of(&self, c: usize) -> u32 { - if c == 0 { - self.bit_depth - } else { - self.bit_depth_c - } - } - - /// The luma plane as 8-bit samples. Only meaningful for 8-bit pictures. - pub fn y_u8(&self) -> Vec { - self.y.iter().map(|&v| v as u8).collect() - } } /// Decode one IDR access unit: VPS/SPS/PPS/slice NALs in Annex-B framing, one diff --git a/crates/ec-h265/src/enc_p.rs b/crates/ec-h265/src/enc_p.rs index b8def5f7..6241ccde 100644 --- a/crates/ec-h265/src/enc_p.rs +++ b/crates/ec-h265/src/enc_p.rs @@ -22,7 +22,7 @@ use crate::cabac::{CabacEncoder, Contexts, ctx}; use crate::ctu::{Pel, lambda_for}; use crate::dec::amvp::derive_amvp; -use crate::dec::cu_syntax::{CuGeometry, PartMode, PredictionUnit}; +use crate::dec::cu_syntax::{PartMode, PredictionUnit}; use crate::dec::deblock::{deblock_picture, deblock_rows}; use crate::dec::mc::{Block, McScratch, PlaneMut, PlaneRef, RefPicture, predict_pu}; use crate::dec::merge::derive_merge; @@ -71,8 +71,22 @@ const EARLY_SKIP_COST: f64 = 4.0; /// Mean absolute difference per sample below which a motion-searched block is not split. const EARLY_SPLIT_SAD: f64 = 0.25; -/// Search thresholds of the P-picture decision. The defaults are the measured -/// values; the `EC_H265_*` overrides exist for the sweep in the lane report. +/// Intra modes costed in full, the best by SAD of their prediction. +const INTRA_K: usize = 1; +/// Residual energy bound below which a transform block is taken to quantise to zero. +const ZERO_ALPHA: f64 = 24.0; +/// First pattern step (quarter samples) of the search for 16x16 blocks. +const STEP16: i16 = 16; +/// First pattern step (quarter samples) of the search for 8x8 blocks. +const STEP8: i16 = 16; +/// First pattern step (quarter samples) of the search for split partitions. +const STEP_PART: i16 = 16; +/// Whole-sample scan stride. +const FULL_STRIDE: i16 = 4; +/// Sub-sample refinement passes. +const SUB_PASSES: u32 = 1; + +/// Search thresholds of the P-picture decision, per speed preset. #[derive(Clone, Copy)] pub(crate) struct PKnobs { /// Whole-sample scan half-width for blocks of 32 and up. @@ -87,80 +101,74 @@ pub(crate) struct PKnobs { full_gate: f64, /// Cost per sample below which the best inter candidate ends the intra search. intra_gate: f64, - /// Intra luma modes costed in full, the best by SAD of their prediction. - intra_k: usize, - /// A transform block whose residual energy times the transform gain is below this many - /// squares of the smallest non-zero coefficient is taken to quantise to zero without - /// transforming it (1 is the bound that is exact; larger trades a little accuracy). - zero_alpha: f64, - /// First pattern step (quarter samples) of the search for 16x16 and 8x8 blocks, and halves. - step16: i16, - step8: i16, - step_part: i16, - full_stride: i16, - res_proxy: bool, - sub_passes: u32, /// Most distinct merge candidates costed in full. merge_max: usize, /// Cost both AMVP predictor flags (otherwise only the one with the smaller vector difference). amvp_both: bool, /// log2 of the smallest inter coding unit the analysis searches (3 = 8x8). min_log2: u32, - /// Smallest square (samples) whose horizontal and vertical halves are searched and costed. - halves_min: usize, /// Most intra luma modes considered (MPMs first) before the SAD ranking. intra_modes: usize, /// Cost per sample below which the sub-sample refinement is skipped. sub_gate: f64, /// Skip the quarter-sample refinement step. no_quarter: bool, + /// Smallest square (samples) whose horizontal and vertical halves are searched and costed. + halves_min: usize, } +const PKNOBS: [PKnobs; 3] = [ + PKnobs { + full_large: FULL_RANGE_LARGE, + full_small: FULL_RANGE_SMALL, + split_sad: EARLY_SPLIT_SAD, + skip_cost: EARLY_SKIP_COST, + full_gate: 4.0, + intra_gate: 0.0, + merge_max: 5, + amvp_both: true, + min_log2: 3, + intra_modes: 7, + sub_gate: 0.0, + no_quarter: false, + halves_min: 16, + }, + PKnobs { + full_large: 8, + full_small: 4, + split_sad: 1.0, + skip_cost: 16.0, + full_gate: 12.0, + intra_gate: 6.0, + merge_max: 3, + amvp_both: false, + min_log2: 3, + intra_modes: 3, + sub_gate: 1.0, + no_quarter: false, + halves_min: 32, + }, + PKnobs { + full_large: 4, + full_small: 0, + split_sad: 2.0, + skip_cost: 32.0, + full_gate: 16.0, + intra_gate: 12.0, + merge_max: 2, + amvp_both: false, + min_log2: 4, + intra_modes: 2, + sub_gate: 2.0, + no_quarter: true, + halves_min: 1024, + }, +]; + impl PKnobs { - /// The knobs of a speed preset. `Default` is the measured set; `EC_H265_*` - /// environment variables override any of them (sweeps only). + /// The knobs of a speed preset. pub(crate) fn for_preset(p: Preset) -> PKnobs { - let f = |name: &str, d: f64| { - std::env::var(name) - .ok() - .and_then(|v| v.parse::().ok()) - .unwrap_or(d) - }; - // (fast, faster) values against the default. - let pick = |d: f64, fast: f64, faster: f64| match p { - Preset::Default => d, - Preset::Fast => fast, - Preset::Faster => faster, - }; - PKnobs { - full_large: f( - "EC_H265_FULL_LARGE", - pick(f64::from(FULL_RANGE_LARGE), 8.0, 4.0), - ) as i16, - full_small: f( - "EC_H265_FULL_SMALL", - pick(f64::from(FULL_RANGE_SMALL), 4.0, 0.0), - ) as i16, - split_sad: f("EC_H265_SPLIT_SAD", pick(EARLY_SPLIT_SAD, 1.0, 2.0)), - skip_cost: f("EC_H265_SKIP_COST", pick(EARLY_SKIP_COST, 16.0, 32.0)), - full_gate: f("EC_H265_FULL_GATE", pick(4.0, 12.0, 16.0)), - intra_gate: f("EC_H265_INTRA_GATE", pick(0.0, 6.0, 12.0)), - intra_k: f("EC_H265_INTRA_K", 1.0) as usize, - zero_alpha: f("EC_H265_ZERO_ALPHA", pick(24.0, 24.0, 24.0)), - step16: f("EC_H265_STEP16", 16.0) as i16, - step8: f("EC_H265_STEP8", 16.0) as i16, - step_part: f("EC_H265_STEPP", 16.0) as i16, - full_stride: f("EC_H265_FULL_STRIDE", 4.0) as i16, - sub_passes: f("EC_H265_SUB_PASSES", pick(1.0, 1.0, 1.0)) as u32, - res_proxy: f("EC_H265_RES_PROXY", 1.0) != 0.0, - merge_max: f("EC_H265_MERGE_MAX", pick(5.0, 3.0, 2.0)) as usize, - amvp_both: f("EC_H265_AMVP_BOTH", pick(1.0, 0.0, 0.0)) != 0.0, - min_log2: f("EC_H265_MIN_LOG2", pick(3.0, 3.0, 4.0)) as u32, - intra_modes: f("EC_H265_INTRA_MODES", pick(7.0, 3.0, 2.0)) as usize, - sub_gate: f("EC_H265_SUB_GATE", pick(0.0, 1.0, 2.0)), - no_quarter: f("EC_H265_NO_QUARTER", pick(0.0, 0.0, 1.0)) != 0.0, - halves_min: f("EC_H265_HALVES_MIN", pick(16.0, 32.0, 1024.0)) as usize, - } + PKNOBS[p as usize] } } @@ -577,7 +585,7 @@ impl<'a> PCoder<'a> { bit_depth: bd, }, ]; - let mut pic = PicState::new(w, h, ctb_log2, 2, bd, bd, true); + let mut pic = PicState::new(w, h, ctb_log2, 2, bd, bd); pic.strong_intra_smoothing = true; // as the sequence parameter set says pic.slices = vec![SliceFilter { deblock_disabled: !enc.cfg.deblock, @@ -728,14 +736,14 @@ impl<'a> PCoder<'a> { self.k.full_small }, full_gate: self.k.full_gate, - full_stride: self.k.full_stride, - sub_passes: self.k.sub_passes, + full_stride: FULL_STRIDE, + sub_passes: SUB_PASSES, sub_gate: self.k.sub_gate, no_quarter: self.k.no_quarter, first_step: match n { 32.. => 16, - 16.. => self.k.step16, - _ => self.k.step8, + 16.. => STEP16, + _ => STEP8, }, }; let best = search.run((x, y), (n, n), mvp, &seeds); @@ -800,10 +808,10 @@ impl<'a> PCoder<'a> { full_range: 0, full_gate: 0.0, full_stride: 1, - sub_passes: self.k.sub_passes, + sub_passes: SUB_PASSES, sub_gate: self.k.sub_gate, no_quarter: self.k.no_quarter, - first_step: self.k.step_part, + first_step: STEP_PART, }; let best = search.run((rx, ry), (rw, rh), mvp, &seeds); total += best.cost; @@ -905,13 +913,6 @@ impl<'a> PCoder<'a> { ) -> Result<()> { let n = 1usize << log2; let analysis_mv = analysis.mv; - let geom = CuGeometry { - x, - y, - size: n, - part_mode: PartMode::Part2Nx2N, - skip: false, - }; // Candidate motions: each distinct merge candidate, then AMVP with the // analysed vector under either predictor. let mut merge_motions: Vec<(u8, PbMotion)> = Vec::new(); @@ -927,7 +928,7 @@ impl<'a> PCoder<'a> { }; let m = { let sm = self.sm(); - derive_merge(&sm, &geom, 0, &pu) + derive_merge(&sm, x, y, n, PartMode::Part2Nx2N, 0, &pu) }; if merge_motions.iter().all(|(_, prev)| *prev != m) { merge_motions.push((idx, m)); @@ -1009,7 +1010,7 @@ impl<'a> PCoder<'a> { let inter_best = best.as_ref().map_or(f64::MAX, |(c, _, _)| *c); if inter_best < self.k.intra_gate * (n * n) as f64 { modes.clear(); - } else if self.k.intra_k < modes.len() { + } else if INTRA_K < modes.len() { let mut ranked: Vec<(u64, u8)> = modes .iter() .map(|&m| { @@ -1018,11 +1019,7 @@ impl<'a> PCoder<'a> { }) .collect(); ranked.sort_unstable(); - modes = ranked - .into_iter() - .take(self.k.intra_k) - .map(|(_, m)| m) - .collect(); + modes = ranked.into_iter().take(INTRA_K).map(|(_, m)| m).collect(); } let no_motion = PbMotion::new([false, false], [-1, -1], [[0, 0], [0, 0]]); for mode in modes { @@ -1182,7 +1179,7 @@ impl<'a> PCoder<'a> { self.bd, sh, (0, false), - self.k.zero_alpha, + ZERO_ALPHA, ); let cb = code_tb( &src.cb, @@ -1195,7 +1192,7 @@ impl<'a> PCoder<'a> { self.bd, sh, (0, false), - self.k.zero_alpha, + ZERO_ALPHA, ); let cr = code_tb( &src.cr, @@ -1208,7 +1205,7 @@ impl<'a> PCoder<'a> { self.bd, sh, (0, false), - self.k.zero_alpha, + ZERO_ALPHA, ); ssd += luma.ssd + cb.ssd + cr.ssd; for r in 0..half { @@ -1278,7 +1275,7 @@ impl<'a> PCoder<'a> { self.bd, sh, (0, false), - self.k.zero_alpha, + ZERO_ALPHA, ); let cb = code_tb( &src.cb, @@ -1291,7 +1288,7 @@ impl<'a> PCoder<'a> { self.bd, sh, (0, false), - self.k.zero_alpha, + ZERO_ALPHA, ); let cr = code_tb( &src.cr, @@ -1304,7 +1301,7 @@ impl<'a> PCoder<'a> { self.bd, sh, (0, false), - self.k.zero_alpha, + ZERO_ALPHA, ); let cbf = [luma.cbf, cb.cbf, cr.cbf]; let any = cbf.iter().any(|&c| c); @@ -1430,7 +1427,7 @@ impl<'a> PCoder<'a> { self.bd, sh, (scan, n == 4), - self.k.zero_alpha, + ZERO_ALPHA, ); let cb = code_tb( &src.cb, @@ -1443,7 +1440,7 @@ impl<'a> PCoder<'a> { self.bd, sh, (cscan, false), - self.k.zero_alpha, + ZERO_ALPHA, ); let cr = code_tb( &src.cr, @@ -1456,7 +1453,7 @@ impl<'a> PCoder<'a> { self.bd, sh, (cscan, false), - self.k.zero_alpha, + ZERO_ALPHA, ); let syntax = CuSyntax { skip: false, @@ -1589,7 +1586,7 @@ impl<'a> PCoder<'a> { c_idx: usize, scan: usize, ) { - if e.is_estimating() && self.k.res_proxy { + if e.is_estimating() { e.add_estimated_bits(estimate_residual_bits(levels, log2, scan)); } else { encode_residual(e, levels, log2, c_idx, scan, self.sign_hiding, None); @@ -1835,7 +1832,7 @@ pub(crate) fn code_p_picture( true, ); write_annex_b(&mut au, NalHeader::new(NalUnitType::TrailR), &rbsp, true); - let shared = Arc::new(SharedPic::new(poc, w, h, (8, 8), false, 1)); + let shared = Arc::new(SharedPic::new(poc, w, h, (8, 8), 1)); shared.publish_col(&field, h); Ok((au, recon, PrevPic { field, shared })) } diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index fe162e62..56261806 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -989,9 +989,9 @@ impl Encoder { true, ); if let Some(rbsp) = - sei::hdr_metadata_rbsp_with(self.cfg.mastering_display, self.cfg.content_light) + sei::hdr_metadata_rbsp(self.cfg.mastering_display, self.cfg.content_light) { - write_annex_b(&mut au, sei::prefix_sei_header(), &rbsp, true); + write_annex_b(&mut au, NalHeader::new(NalUnitType::PrefixSei), &rbsp, true); } // Entry points count the bytes as they appear in the NAL, emulation @@ -1033,7 +1033,12 @@ impl Encoder { (&bcb, w / 2 * bps, w / 2 * bps, h / 2), (&bcr, w / 2 * bps, w / 2 * bps, h / 2), ]); - write_annex_b(&mut au, sei::suffix_sei_header(), &rbsp, false); + write_annex_b( + &mut au, + NalHeader::new(NalUnitType::SuffixSei), + &rbsp, + false, + ); } au } diff --git a/crates/ec-h265/src/residual.rs b/crates/ec-h265/src/residual.rs index 35670a42..500d1fad 100644 --- a/crates/ec-h265/src/residual.rs +++ b/crates/ec-h265/src/residual.rs @@ -1618,262 +1618,4 @@ mod tests { } } } - - /// [`rdoq`], but every trial re-derives the whole block's bits from `base` - /// (the pre-change behaviour) instead of using the sub-block frozen-prefix - /// cursor. Kept only for - /// [`sub_block_cursor_matches_full_recompute`] to check the cursor against. - #[allow(clippy::too_many_arguments)] - fn rdoq_full_recompute( - coeffs: &[i32], - levels: &mut [i32], - n: usize, - qp: i32, - bit_depth: u32, - c_idx: usize, - scan_idx: usize, - cbf_ctx: usize, - lambda: f64, - transform_skip: Option, - enc: &mut CabacEncoder, - ) -> usize { - let log2_size = n.trailing_zeros(); - let scale = coeff_ssd_scale(n); - let lambda = RDOQ_LAMBDA * lambda; - let base = enc.snapshot(); - let err = |level: i32, coeff: i32| { - let d = f64::from(dequant_level_bd(level, n, qp, bit_depth) - coeff); - d * d - }; - - let mut dist: f64 = (0..n * n).map(|i| err(levels[i], coeffs[i])).sum(); - let bits = levels_bits( - enc, - &base, - levels, - log2_size, - c_idx, - scan_idx, - cbf_ctx, - true, - transform_skip, - ); - let mut cost = scale * dist + lambda * bits; - - let sub_scan = scan(log2_size - 2, scan_idx); - let pos_scan = scan(2, scan_idx); - let order: Vec = sub_scan - .iter() - .flat_map(|&(xs, ys)| { - pos_scan.iter().map(move |&(xp, yp)| { - (ys as usize * 4 + yp as usize) * n + xs as usize * 4 + xp as usize - }) - }) - .collect(); - - let sub_wide = n >> 2; - let mut csbf = [false; 64]; - let mut sub_count = [0i32; 64]; - let mut nz_positions: Vec = Vec::new(); - for (k, &i) in order.iter().enumerate().rev() { - if levels[i] != 0 { - nz_positions.push(k as i32); - let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2); - sub_count[sub_idx] += 1; - csbf[sub_idx] = true; - } - } - let mut cur_last = nz_positions.first().copied().unwrap_or(0); - let mut nz_idx = 0usize; - - for (k, &i) in order.iter().enumerate().rev() { - let level = levels[i]; - if level == 0 { - continue; - } - let next_last = nz_positions.get(nz_idx + 1).copied().unwrap_or(0); - nz_idx += 1; - if level.abs() > RDOQ_MAX_LEVEL { - continue; - } - let sub_idx = ((i / n) >> 2) * sub_wide + ((i % n) >> 2); - let mut tried = level.abs(); - for candidate in [level.abs() - 1, 0] { - if candidate == tried { - continue; - } - tried = candidate; - let keep = levels[i]; - levels[i] = candidate * level.signum(); - let now_zero = levels[i] == 0; - let sub_count_before = sub_count[sub_idx]; - let csbf_before = csbf[sub_idx]; - if now_zero { - sub_count[sub_idx] -= 1; - csbf[sub_idx] = sub_count[sub_idx] > 0; - } - let trial_last = if now_zero && k as i32 == cur_last { - next_last - } else { - cur_last - }; - let trial_dist = dist - err(keep, coeffs[i]) + err(levels[i], coeffs[i]); - let any = sub_count.iter().any(|&c| c > 0); - let trial_bits = levels_bits_with( - enc, - &base, - levels, - log2_size, - c_idx, - scan_idx, - cbf_ctx, - any, - transform_skip, - trial_last, - csbf, - ); - let trial = scale * trial_dist + lambda * trial_bits; - if trial < cost { - cost = trial; - dist = trial_dist; - if now_zero { - cur_last = trial_last; - } - } else { - levels[i] = keep; - sub_count[sub_idx] = sub_count_before; - csbf[sub_idx] = csbf_before; - } - } - } - let zero_dist: f64 = (0..n * n).map(|i| err(0, coeffs[i])).sum(); - let zero_bits = levels_bits( - enc, - &base, - levels, - log2_size, - c_idx, - scan_idx, - cbf_ctx, - false, - transform_skip, - ); - if scale * zero_dist + lambda * zero_bits <= cost { - levels[..n * n].fill(0); - enc.restore(&base); - return 0; - } - enc.restore(&base); - levels[..n * n].iter().filter(|&&l| l != 0).count() - } - - /// A tiny xorshift RNG — deterministic across runs, no extra dependency. - struct Xorshift(u32); - impl Xorshift { - fn next(&mut self) -> u32 { - self.0 ^= self.0 << 13; - self.0 ^= self.0 >> 17; - self.0 ^= self.0 << 5; - self.0 - } - } - - /// ENTRY GATE for lane-h265rdoq r3: the sub-block frozen-prefix cursor - /// [`rdoq`] now uses must produce bit-for-bit the same trial decisions — - /// and so the same final `levels` and the same final bitstream — as - /// always re-deriving every trial's bits from the block's start - /// ([`rdoq_full_recompute`], this round's pre-change behaviour). Covers - /// every block size with a sub-block split (8/16/32 — 4x4 has none), - /// every scan, 8 seeds, sign-hiding on/off on the final bitstream, and - /// deliberately includes levels of magnitude 1-3 so some trials drop the - /// last significant coefficient, some empty a whole sub-block (csbf - /// flips), and some sit right at the greater1/greater2 escape boundary. - #[test] - fn sub_block_cursor_matches_full_recompute() { - for log2 in [3u32, 4, 5] { - let n = 1usize << log2; - for scan_idx in 0..3 { - for seed in 1..=8u32 { - let mut rng = Xorshift(seed.wrapping_mul(2654435761).max(1)); - let mut coeffs = vec![0i32; n * n]; - for c in coeffs.iter_mut() { - // Skewed toward small magnitudes (0..=3) so RDOQ_MAX_LEVEL's - // trial window and the greater1/greater2 boundary both fire - // often, with occasional larger outliers left untouched. - let r = rng.next(); - *c = match r % 5 { - 0 => 0, - 1 => (r >> 8) as i32 % 2 + 1, - 2 => -(((r >> 8) as i32 % 2) + 1), - 3 => (r >> 8) as i32 % 6 + 1, - _ => -(((r >> 8) as i32 % 6) + 1), - }; - } - let qp = 20 + (seed as i32 % 20); - - let mut levels_a = coeffs.clone(); - let mut enc_a = CabacEncoder::counter(Contexts::new(30)); - let count_a = rdoq( - &coeffs, - &mut levels_a, - n, - qp, - 8, - 0, - scan_idx, - ctx::CBF_LUMA, - 1.0, - None, - &mut enc_a, - ); - - let mut levels_b = coeffs.clone(); - let mut enc_b = CabacEncoder::counter(Contexts::new(30)); - let count_b = rdoq_full_recompute( - &coeffs, - &mut levels_b, - n, - qp, - 8, - 0, - scan_idx, - ctx::CBF_LUMA, - 1.0, - None, - &mut enc_b, - ); - - assert_eq!( - count_a, count_b, - "log2={log2} scan={scan_idx} seed={seed}: non-zero count differs" - ); - assert_eq!( - levels_a, levels_b, - "log2={log2} scan={scan_idx} seed={seed}: decided levels differ" - ); - - if count_a == 0 { - continue; - } - for sign_hiding in [false, true] { - let mut final_levels = levels_a.clone(); - if sign_hiding { - hide_signs(&coeffs, &mut final_levels, n, 30, scan_idx); - } - let mut fenc = CabacEncoder::counter(Contexts::new(30)); - encode_residual( - &mut fenc, - &final_levels, - log2, - 0, - scan_idx, - sign_hiding, - None, - ); - assert!(fenc.bit_count() > 0); - } - } - } - } - } } diff --git a/crates/ec-h265/src/transform.rs b/crates/ec-h265/src/transform.rs index 946f704c..aa9ba7d5 100644 --- a/crates/ec-h265/src/transform.rs +++ b/crates/ec-h265/src/transform.rs @@ -686,13 +686,6 @@ pub fn dequantize_bd(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32, bit_ dequantize_weighted(levels, scaled, n, qp, bit_depth, None); } -/// [`dequantize`] with a scaling matrix (8.6.4.2): `m` is the block's -/// `ScalingFactor` in raster order, or `None` for the flat 16 that a stream -/// without scaling lists (or a transform-skipped block larger than 4x4) uses. -pub fn dequantize_with(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32, m: Option<&[u8]>) { - dequantize_weighted(levels, scaled, n, qp, 8, m); -} - /// The loop behind every dequantize entry point: one block at `bit_depth`, with /// the weight matrix `m` (or flat 16 for `None`). pub fn dequantize_weighted( diff --git a/crates/ec-h265/tests/it/common.rs b/crates/ec-h265/tests/it/common.rs index aca1526c..4b593beb 100644 --- a/crates/ec-h265/tests/it/common.rs +++ b/crates/ec-h265/tests/it/common.rs @@ -192,9 +192,18 @@ pub fn pin_or_panic(site: &str, path: &std::path::Path, bytes: &[u8]) { pub const PLANE_NAMES: [&str; 3] = ["Y", "Cb", "Cr"]; +/// The bit depth of component `c` (0 luma, 1 and 2 chroma). +pub fn bit_depth_of(pic: &DecodedPicture, c: usize) -> u32 { + if c == 0 { + pic.bit_depth + } else { + pic.bit_depth_c + } +} + /// Bytes per sample of component `c`: 1 for 8-bit, 2 (little endian) above 8 bits. pub fn bytes_per_sample(pic: &DecodedPicture, c: usize) -> usize { - if pic.bit_depth_of(c) > 8 { 2 } else { 1 } + if bit_depth_of(pic, c) > 8 { 2 } else { 1 } } /// The samples of a picture cropped to its conformance window, as the bytes a YUV @@ -424,7 +433,7 @@ pub fn plane_matches(pic: &DecodedPicture, expected: &PictureHash) -> Vec .map(|(i, &w)| { planes .get(i) - .is_some_and(|p| plane_crc(p, pic.bit_depth_of(i)) == w) + .is_some_and(|p| plane_crc(p, bit_depth_of(pic, i)) == w) }) .collect(), PictureHash::Checksum(want) => want @@ -433,7 +442,7 @@ pub fn plane_matches(pic: &DecodedPicture, expected: &PictureHash) -> Vec .map(|(i, &w)| { planes .get(i) - .is_some_and(|p| plane_checksum(p, dims[i].0, pic.bit_depth_of(i)) == w) + .is_some_and(|p| plane_checksum(p, dims[i].0, bit_depth_of(pic, i)) == w) }) .collect(), } diff --git a/crates/ec-h265/tests/it/conformance.rs b/crates/ec-h265/tests/it/conformance.rs deleted file mode 100644 index 8b1f45fd..00000000 --- a/crates/ec-h265/tests/it/conformance.rs +++ /dev/null @@ -1,964 +0,0 @@ -//! Conformance: every access unit this encoder writes must decode in ffmpeg, -//! and the picture ffmpeg produces must be *bit-identical* to the encoder's own -//! reconstruction. That equality is the whole point of coding with the in-loop -//! filters off: it turns "the file plays" into "the decoder and the encoder -//! agree on every sample". - -use crate::common::{natural_frame, pin_or_panic, test_frame}; -use ec_core::frame::VideoFrame; -use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl, TransformSkip}; -use std::path::{Path, PathBuf}; - -fn scratch_dir() -> PathBuf { - let dir = std::env::temp_dir().join("ec-h265-tests"); - std::fs::create_dir_all(&dir).expect("scratch dir"); - dir -} - -/// Decode an Annex-B file with ffmpeg into planar 8-bit 4:2:0. -fn ffmpeg_decode(path: &Path) -> Result, String> { - let out = path.with_extension("yuv"); - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(path) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&out) - .output() - .map_err(|e| e.to_string())?; - if !status.status.success() { - return Err(String::from_utf8_lossy(&status.stderr).to_string()); - } - let stderr = String::from_utf8_lossy(&status.stderr).to_string(); - if !stderr.trim().is_empty() { - return Err(format!("ffmpeg complained: {stderr}")); - } - std::fs::read(&out).map_err(|e| e.to_string()) -} - -/// Pin one access unit as an Annex-B file for [`ffmpeg_decode`]. -/// -/// lane-h26xpinloud: this used `File::create(..).expect(..)` + -/// `write_all(..).expect("write bitstream")`, which closes only the ERROR path. -/// A write that reports success and leaves a short file put a truncated stream -/// at exactly the path ffmpeg then decoded, so the shortfall now carries the -/// path, both counts, and the OS error. Panic semantics kept: this caller -/// panicked before and still does, with the failure line as the message. -fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf { - let path = scratch_dir().join(format!("{name}.265")); - pin_or_panic("write_au", &path, &picture.au); - path -} - -fn planes_of(frame: &VideoFrame) -> Vec { - let mut out = Vec::new(); - let (w, h) = (frame.width as usize, frame.height as usize); - for (i, plane) in frame.planes.iter().enumerate() { - let (pw, ph) = if i == 0 { - (w, h) - } else { - (w.div_ceil(2), h.div_ceil(2)) - }; - for row in 0..ph { - out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); - } - } - out -} - -fn psnr(a: &[u8], b: &[u8]) -> f64 { - assert_eq!(a.len(), b.len()); - let mse: f64 = a - .iter() - .zip(b) - .map(|(x, y)| { - let d = f64::from(*x) - f64::from(*y); - d * d - }) - .sum::() - / a.len() as f64; - if mse == 0.0 { - 99.0 - } else { - 10.0 * (255.0 * 255.0 / mse).log10() - } -} - -/// Encode one picture; `ctb` of `None` takes the configured default. -fn encode(width: u32, height: u32, qp: i32, ctb: Option) -> (VideoFrame, EncodedPicture) { - encode_with(width, height, qp, ctb, false, false) -} - -fn encode_with( - width: u32, - height: u32, - qp: i32, - ctb: Option, - chroma_mode_search: bool, - intra_nxn: bool, -) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.chroma_mode_search = chroma_mode_search; - cfg.intra_nxn = intra_nxn; - cfg.rate_control = RateControl::ConstantQp(qp); - if let Some(ctb) = ctb { - cfg.ctb_size = ctb; - } - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = test_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// Same as `encode_with`, but on the grainy natural frame and with no chroma -/// mode search — the synthetic test frame is flat enough that the quadtree -/// never keeps an 8x8 coding unit, which is the only size PART_NxN applies to. -fn encode_natural( - width: u32, - height: u32, - qp: i32, - intra_nxn: bool, -) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.intra_nxn = intra_nxn; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// The chroma mode search is off by default (it loses on screen content, see -/// `EncoderConfig::chroma_mode_search`), so the shapes above never code an -/// `intra_chroma_pred_mode` other than the derived one. This exercises the four -/// explicit modes: the stream has to differ from the derived-only one — proving -/// the search actually fired — and still decode bit-exactly. -#[test] -fn chroma_mode_search_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_with(w, h, 27, None, true, false); - let (_, derived) = encode_with(w, h, 27, None, false, false); - let name = format!("chroma-rd-{w}x{h}"); - assert_ne!( - coded.au, derived.au, - "{name}: the search never picked a mode other than the derived one, so this decode proves nothing" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); - } -} - -/// PART_NxN is off by default, so nothing else here codes a four-partition -/// coding unit. This does: the stream has to differ from the 2Nx2N-only one — -/// proving the partition actually fired — and still decode bit-exactly, which -/// is the only check that the inferred transform split, the four `cbf_luma` -/// flags at transform depth 1 and the chroma residual riding on the last -/// partition are all where the decoder looks for them. -#[test] -fn intra_nxn_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_natural(w, h, 22, true); - let (_, square) = encode_natural(w, h, 22, false); - let name = format!("intra-nxn-{w}x{h}"); - assert_ne!( - coded.au, square.au, - "{name}: no coding unit ever chose PART_NxN, so this decode proves nothing" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); - } -} - -/// Sign data hiding drops one bypass bin per qualifying sub-block and pays for -/// it by nudging a level, so the encoder and the decoder only agree if the -/// parity the encoder wrote is the parity the decoder reads. The stream has to -/// differ from the hiding-off one, and ffmpeg's decode has to match the -/// encoder's reconstruction sample for sample. -/// -/// Size is deliberately not asserted here: hiding is not optional per -/// sub-block, so a single small picture can come out a few bytes longer when -/// the nudges cost more than the signs saved. Whether it pays is what the -/// `EC_H265_SDH` arm of the clip gate measures. -#[test] -fn sign_hiding_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_sdh(w, h, 22, true); - let (_, plain) = encode_sdh(w, h, 22, false); - let name = format!("sign-hiding-{w}x{h}"); - assert_ne!( - coded.au, plain.au, - "{name}: no sub-block ever qualified, so this decode proves nothing" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); - } -} - -/// The natural frame coded with sign data hiding on or off, everything else -/// left at its default. -fn encode_sdh(width: u32, height: u32, qp: i32, sign_hiding: bool) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.sign_hiding = sign_hiding; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// The natural frame coded with transform skip on or off, everything else -/// left at its default. -fn encode_tskip( - width: u32, - height: u32, - qp: i32, - tskip: TransformSkip, -) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.transform_skip = tskip; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// Transform skip bypasses the integer transform on 4x4 TUs, coding residual -/// samples directly with a fixed shift. The encoder and decoder agree only if -/// the shift matches on both sides; the stream has to differ from the -/// skip-off one, and ffmpeg's decode has to match the encoder's reconstruction -/// sample for sample. -#[test] -fn transform_skip_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_tskip(w, h, 22, TransformSkip::AlwaysFor4x4); - let (_, plain) = encode_tskip(w, h, 22, TransformSkip::Off); - let name = format!("transform-skip-{w}x{h}"); - assert_ne!( - coded.au, plain.au, - "{name}: no TU ever skipped, so this decode proves nothing" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); - } -} -#[test] -fn ffmpeg_decodes_bit_exactly_at_every_shape() { - // 1920x1080 needs the conformance window on the bottom (1088 coded rows are - // not used: 1080 is a multiple of 8, but 64x64 CTBs still overhang), 1916 - // needs it on the right, 130x66 exercises a partial CTB in both directions. - // Both tree sizes are coded: the default is 32, and 64 is still offered. - for &(w, h, ctb) in &[ - (64u32, 64u32, None), - (130, 66, None), - (1916, 1080, None), - (352, 288, None), - (1916, 1080, Some(64)), - (130, 66, Some(64)), - ] { - let (source, coded) = encode(w, h, 27, ctb); - let name = format!( - "shape-{w}x{h}-ctb{}", - ctb.map_or("default".to_string(), |c| c.to_string()) - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!( - decoded.len(), - recon.len(), - "{name}: decoded {} bytes, reconstruction {} bytes", - decoded.len(), - recon.len() - ); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - // And the encode is worth something: PSNR against the source. - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); - } -} - -/// A 64x64 coding unit predicts and transforms in four 32x32 blocks under one -/// luma mode, with the transform split inferred rather than signalled -/// (`log2TrafoSize > MaxTbLog2SizeY`, 7.4.9.8). That inference is the part a -/// decoder disagrees with loudly, so it is gated against ffmpeg -- and the -/// stream has to differ from the same encode with `cu64` off, or the test would -/// pass without a single 64x64 coding unit ever being kept. -#[test] -fn cu64_decodes_bit_exactly() { - // 130x66 is here for the partial coding tree blocks, not for the decision: - // at that size only two tree blocks are whole and the search keeps neither, - // so its stream is allowed to come out identical. - for &(w, h, qp, fires) in &[ - (352u32, 288u32, 32i32, true), - (256, 256, 37, true), - (130, 66, 32, false), - ] { - let (source, off) = encode_cu64(w, h, qp, false); - let (_, on) = encode_cu64(w, h, qp, true); - let name = format!("cu64-{w}x{h}-qp{qp}"); - if fires { - assert_ne!(off.au, on.au, "{name}: no 64x64 coding unit was ever kept"); - } - - let path = write_au(&name, &on); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(on.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let luma = (w * h) as usize; - panic!( - "{name}: {mismatches} samples differ, first at {first} ({}, {}), {} of them luma", - first % w as usize, - first / w as usize, - decoded[..luma] - .iter() - .zip(&recon[..luma]) - .filter(|(a, b)| a != b) - .count(), - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP {qp}"); - } -} - -fn encode_cu64(width: u32, height: u32, qp: i32, cu64: bool) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.ctb_size = 64; - cfg.cu64 = cu64; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// The 32x32 default buys wavefront rows (see `perf.rs`) by coding a shallower -/// tree; that trade is only worth taking if the bits it costs are noise. -#[test] -fn the_default_tree_costs_almost_nothing_against_64() { - let source = natural_frame(1920, 1080, 0); - let mut coded = Vec::new(); - for ctb in [32usize, 64] { - let mut cfg = EncoderConfig::new(1920, 1080); - cfg.rate_control = RateControl::ConstantQp(27); - cfg.ctb_size = ctb; - cfg.keep_recon = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let picture = encoder.encode_idr(&source).expect("encode"); - let quality = psnr( - &planes_of(&source), - &planes_of(picture.recon.as_ref().unwrap()), - ); - coded.push((picture.au.len(), quality)); - } - let ((bits32, psnr32), (bits64, psnr64)) = (coded[0], coded[1]); - println!( - "1080p at QP 27: CTB 32 {bits32} bytes / {psnr32:.2} dB, CTB 64 {bits64} bytes / {psnr64:.2} dB \ - ({:+.1}% bits, {:+.2} dB)", - (bits32 as f64 / bits64 as f64 - 1.0) * 100.0, - psnr32 - psnr64 - ); - assert!( - // Measured 1.0% on this fixture; the bound leaves room for the shape of - // the picture, not for a change of coding behaviour. - (bits32 as f64) < bits64 as f64 * 1.03, - "CTB 32 spent {bits32} bytes against 64's {bits64}" - ); - assert!( - (psnr32 - psnr64).abs() < 0.1, - "CTB 32 landed {psnr32:.2} dB against 64's {psnr64:.2} dB" - ); -} - -#[test] -fn ffmpeg_verifies_the_decoded_picture_hash() { - // The MD5 SEI is the encoder's claim about its own reconstruction; ffmpeg's - // decoder checks that claim against what it decoded when asked to. This is - // the one oracle that does not depend on this crate being right about - // anything except the hash itself. - let (_, coded) = encode(352, 288, 30, None); - let path = write_au("hash-352x288", &coded); - let output = ec_testkit::ffmpeg() - .args(["-v", "debug", "-err_detect", "crccheck", "-y", "-i"]) - .arg(&path) - .args(["-f", "null", "-"]) - .output() - .expect("run ffmpeg"); - let log = String::from_utf8_lossy(&output.stderr).to_string(); - let checks: Vec<&str> = log - .lines() - .filter(|line| line.contains("Verifying checksum")) - .collect(); - assert!(!checks.is_empty(), "ffmpeg checked no picture hash: {log}"); - for line in checks { - assert_eq!(line.matches("correct").count(), 3, "hash mismatch: {line}"); - } -} - -#[test] -fn vaapi_hardware_decodes_the_stream() { - // The other half of "it decodes": a GPU decoder is a different - // implementation with different tolerances, and it is what edith's HEVC - // path actually uses. Skipped where there is no render node. - if !Path::new("/dev/dri/renderD128").exists() { - eprintln!("skipping: no VA-API render node"); - return; - } - let (_, coded) = encode(1920, 1080, 27, None); - let path = write_au("vaapi-1080p", &coded); - let output = ec_testkit::ffmpeg() - .args([ - "-v", - "error", - "-hwaccel", - "vaapi", - "-hwaccel_device", - "/dev/dri/renderD128", - "-i", - ]) - .arg(&path) - .args(["-f", "null", "-"]) - .output() - .expect("run ffmpeg"); - let stderr = String::from_utf8_lossy(&output.stderr).to_string(); - if stderr.contains("Failed to initialise VAAPI") - || stderr.contains("No VA display found") - || stderr.contains("Device creation failed") - { - eprintln!("skipping: VA-API unavailable here ({})", stderr.trim()); - return; - } - assert!( - output.status.success() && stderr.trim().is_empty(), - "VA-API decode failed: {stderr}" - ); -} - -#[test] -fn quality_rises_as_qp_falls() { - let mut previous = 0.0; - for &qp in &[40i32, 32, 27, 22] { - let (source, coded) = encode(256, 144, qp, None); - let recon = planes_of(coded.recon.as_ref().expect("recon")); - let quality = psnr(&planes_of(&source), &recon); - assert!( - quality > previous, - "QP {qp}: PSNR {quality:.2} dB is not above {previous:.2}" - ); - previous = quality; - } - assert!( - previous > 40.0, - "QP 22 should clear 40 dB, got {previous:.2}" - ); -} - -#[test] -fn threads_do_not_change_the_bitstream() { - let mut cfg = EncoderConfig::new(320, 192); - cfg.rate_control = RateControl::ConstantQp(30); - cfg.threads = 1; - let single = Encoder::new(cfg.clone()).unwrap(); - cfg.threads = 8; - let many = Encoder::new(cfg).unwrap(); - let frame = test_frame(320, 192, 3); - let a = single.encode_idr(&frame).unwrap(); - let b = many.encode_idr(&frame).unwrap(); - assert_eq!(a.au, b.au, "wavefront changed the bitstream"); -} - -#[test] -fn a_bit_target_lands_near_its_target() { - // The model picks a QP from bits-per-pixel; a picture that comes out more - // than a quarter off is coded once more at a corrected QP. What is asserted - // is the contract that mode offers — near the target, monotonic in it — not - // a bitrate to the byte, which no single-picture encoder can promise. - let mut previous = 0usize; - for target in [400_000u64, 1_200_000, 3_000_000] { - let mut cfg = EncoderConfig::new(640, 360); - cfg.rate_control = RateControl::TargetBits(target); - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = test_frame(640, 360, 5); - let coded = encoder.encode_idr(&frame).expect("encode"); - let bits = coded.au.len() * 8; - assert!( - bits > previous, - "target {target}: {bits} bits did not grow with the target" - ); - previous = bits; - let ratio = bits as f64 / target as f64; - assert!( - (0.4..2.5).contains(&ratio), - "target {target}: got {bits} bits (x{ratio:.2}) at QP {}", - coded.qp - ); - } -} - -#[test] -fn the_batch_helper_codes_every_picture_as_its_own_access_unit() { - let cfg = EncoderConfig::new(128, 96); - let encoder = Encoder::new(cfg).expect("encoder"); - let frames: Vec = (0..3).map(|i| test_frame(128, 96, i * 11)).collect(); - let coded = encoder.encode_batch(frames.iter()).expect("batch encode"); - assert_eq!(coded.len(), 3); - for picture in &coded { - // Every access unit stands alone: parameter sets, then an IDR slice. - let nals = ec_h265_syntax::split_annex_b(&picture.au); - let types: Vec<_> = nals.iter().map(|n| n.header.nal_type).collect(); - assert_eq!( - &types[..4], - &[ - ec_h265_syntax::NalUnitType::Vps, - ec_h265_syntax::NalUnitType::Sps, - ec_h265_syntax::NalUnitType::Pps, - ec_h265_syntax::NalUnitType::IdrWRadl, - ], - "access unit is not self-contained" - ); - } - // Different pictures, different bitstreams. - assert_ne!(coded[0].au, coded[1].au); -} - -/// Rate-distortion quantisation changes which levels are coded, so the streams -/// it produces are a different set of bins from the plain quantiser's; ffmpeg -/// has to read them back to the same samples the encoder reconstructed. -#[test] -fn rdoq_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_rdoq(w, h, 27, true); - let (_, plain) = encode_rdoq(w, h, 27, false); - let name = format!("rdoq-{w}x{h}"); - assert_ne!( - coded.au, plain.au, - "{name}: the level search changed no byte, so it is not running" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); - } -} - -/// The natural frame coded with the level search on or off, everything else -/// left at its default. -fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.rdoq = rdoq; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// RQT must produce a bitstream a conformant decoder reads back to the exact -/// samples the encoder reconstructed. -#[test] -fn rqt_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_rqt(w, h, 27, true); - let (_, plain) = encode_rqt(w, h, 27, false); - let name = format!("rqt-{w}x{h}"); - assert_ne!( - coded.au, plain.au, - "{name}: RQT changed no byte, so the split path is not running" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); - } -} - -/// The natural frame coded with RQT on or off, everything else left at its -/// default. -fn encode_rqt(width: u32, height: u32, qp: i32, rqt: bool) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.rqt = rqt; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} diff --git a/crates/ec-h265/tests/it/conformance_intra.rs b/crates/ec-h265/tests/it/conformance_intra.rs deleted file mode 100644 index d9e1200a..00000000 --- a/crates/ec-h265/tests/it/conformance_intra.rs +++ /dev/null @@ -1,276 +0,0 @@ -//! Checks every output picture of each JCT-VC conformance stream against the -//! MD5 in its decoded picture hash SEI (D.3.19). -//! -//! Streams the decoder refuses are reported with the error text. Mismatches are -//! reported, never asserted. The digest is computed with the SEI writer of -//! `ec-h265-syntax`, which is the same MD5 the hash message carries. - -use crate::common::{cropped_bytes, describe, plane_matches, whole_output_digest}; -use std::panic::{self, AssertUnwindSafe}; -use std::path::{Path, PathBuf}; - -use ec_h265::dec::Decoder; - -/// The outcome of one stream, one row of the report. -struct Row { - name: String, - accepted: &'static str, - checked: usize, - exact: usize, - detail: String, - /// Whether any picture was checked against the reference YUV (no hash SEI). - by_reference: bool, - /// Wall time of decode and flush, in seconds (0 when the stream was refused early). - decode_secs: f64, -} - -fn jctvc_root() -> PathBuf { - ec_testkit::fixture("vectors/hevc-jctvc") -} - -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's -/// directory under the root, sorted by name. Some zips extract one directory -/// deeper, so two levels are searched. -fn streams() -> Vec { - let root = jctvc_root(); - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - bitstreams_in(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let dirs = std::fs::read_dir(&root).expect("fixture directory"); - let mut dirs: Vec = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); - dirs.sort(); - dirs.into_iter() - .filter(|d| d.is_dir()) - .filter_map(|d| { - let mut found = Vec::new(); - bitstreams_in(&d, 2, &mut found); - found.into_iter().next() - }) - .collect() -} - -/// Decodes one stream and checks every output picture against its MD5 SEI. -fn check_stream(path: &Path, name: &str) -> Row { - let mut row = Row { - name: name.to_string(), - accepted: "no", - checked: 0, - exact: 0, - detail: String::new(), - by_reference: false, - decode_secs: 0.0, - }; - let data = match std::fs::read(path) { - Ok(d) => d, - Err(e) => { - row.detail = format!("read error: {e}"); - return row; - } - }; - let reference = std::fs::read(path.with_extension("yuv")).ok(); - // A `_md5.txt` beside the bitstream is the authority for frames without a hash SEI. It - // takes precedence over the ffmpeg reference YUV, which ffmpeg cannot reproduce for such a - // stream (VPSSPSPPS_A: ffmpeg outputs 2 of its 6 frames). - let whole_output = std::fs::read_to_string(path.with_file_name(format!("{name}_md5.txt"))) - .ok() - .and_then(|text| whole_output_digest(&text)); - let mut whole_output_md5 = ec_h265_syntax::md5::Md5::new(); - let mut whole_output_checked = 0usize; - - let started = std::time::Instant::now(); - let mut dec = Decoder::new(); - if let Err(e) = dec.decode_annex_b(&data) { - row.detail = format!("error: {e}"); - return row; - } - if let Err(e) = dec.flush() { - row.detail = format!("error: {e}"); - return row; - } - row.accepted = "yes"; - - let mut out_index = 0usize; - let mut first: Option = None; - while let Some(frame) = dec.next_frame() { - let index = out_index; - out_index += 1; - let Some(expected) = frame.meta.picture_hash.as_ref() else { - if whole_output.is_some() { - whole_output_md5.update(&cropped_bytes(&frame.picture, &frame.window)); - whole_output_checked += 1; - continue; - } - // No hash SEI: the frame is checked against the reference YUV, when there is one. - if let Some(reference) = reference.as_deref() { - let want = cropped_bytes(&frame.picture, &frame.window); - let start = index * want.len(); - row.checked += 1; - if reference.get(start..start + want.len()) == Some(&want[..]) { - row.exact += 1; - } else if first.is_none() { - let at = (0..3) - .find_map(|plane| { - let d = - describe(Some(reference), index, &frame.picture, frame.poc, plane); - (!d.contains("no sample differs")).then_some(d) - }) - .unwrap_or_else(|| format!("reference YUV frame {index} differs")); - first = Some(format!("{at} (reference YUV, cropped)")); - } - row.by_reference = true; - } - continue; - }; - row.checked += 1; - let pic = &*frame.picture; - let mut exact = true; - for (plane, ok) in plane_matches(pic, expected).into_iter().enumerate() { - if ok { - continue; - } - exact = false; - if first.is_none() { - let kind = if frame.meta.intra_only { "I" } else { "P/B" }; - let at = describe(reference.as_deref(), index, pic, frame.poc, plane); - first = Some(format!("{at} slices={kind}")); - } - } - if exact { - row.exact += 1; - } - } - row.decode_secs = started.elapsed().as_secs_f64(); - if let Some(want) = whole_output { - let got = whole_output_md5.finish(); - row.checked += whole_output_checked; - if got == want { - row.exact += whole_output_checked; - } else { - let hex: String = got.iter().map(|b| format!("{b:02x}")).collect(); - first.get_or_insert(format!( - "whole-output MD5 {hex} differs from {name}_md5.txt" - )); - } - row.by_reference = true; - } - row.detail = match (first, row.checked) { - (Some(f), _) => format!("first mismatch {f}"), - (None, 0) => "no pictures with a hash SEI or reference YUV".to_string(), - (None, _) if whole_output.is_some() => { - "ok (whole-output MD5 from the conformance package)".to_string() - } - (None, _) if row.by_reference => "ok (against the reference YUV)".to_string(), - (None, _) => "ok".to_string(), - }; - row -} - -#[test] -fn conformance_pictures_match_the_sei_hash() { - let root = jctvc_root(); - let streams = streams(); - assert!( - !streams.is_empty(), - "no conformance streams under {}", - root.display() - ); - - let mut rows = Vec::new(); - for path in &streams { - let name = path - .file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(); - let outcome = panic::catch_unwind(AssertUnwindSafe(|| check_stream(path, &name))); - let mut row = match outcome { - Ok(row) => row, - Err(payload) => { - let msg = payload - .downcast_ref::<&str>() - .map(|s| s.to_string()) - .or_else(|| payload.downcast_ref::().cloned()) - .unwrap_or_default(); - Row { - name: name.clone(), - accepted: "panic", - checked: 0, - exact: 0, - detail: format!("panic: {msg}"), - by_reference: false, - decode_secs: 0.0, - } - } - }; - row.detail = row.detail.replace(['\t', '\n'], " "); - rows.push(row); - } - - let mut table = - String::from("stream\taccepted\tpictures_checked\tpictures_exact\tdetail\tdecode_s\n"); - for r in &rows { - println!( - "{} | {} | {} | {} | {} | {:.2}s", - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs - ); - table.push_str(&format!( - "{}\t{}\t{}\t{}\t{}\t{:.2}\n", - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs - )); - } - let checked: usize = rows.iter().map(|r| r.checked).sum(); - let exact: usize = rows.iter().map(|r| r.exact).sum(); - let accepted = rows.iter().filter(|r| r.accepted == "yes").count(); - println!( - "total: {checked} pictures checked, {exact} exact, {accepted}/{} streams accepted", - rows.len() - ); - let report = std::env::var("EC_H265_INTRA_REPORT") - .ok() - .filter(|p| !p.is_empty()); - let written = report.map(|path| std::fs::write(&path, &table).map_err(|e| (path, e))); - if let Some(Err((path, e))) = written { - eprintln!("could not write report {path}: {e}"); - } - - // Every accepted stream must be fully exact, except the streams named in KNOWN_INEXACT. - let failing: Vec = rows - .iter() - .filter(|r| r.accepted == "yes" && r.checked > 0 && r.exact != r.checked) - .filter(|r| !KNOWN_INEXACT.iter().any(|(name, _)| *name == r.name)) - .map(|r| format!("{} ({}/{} exact: {})", r.name, r.exact, r.checked, r.detail)) - .collect(); - assert!( - failing.is_empty(), - "accepted streams that are not exact and not in KNOWN_INEXACT:\n{}", - failing.join("\n") - ); -} - -#[test] -fn whole_output_digest_reads_the_first_word() { - let digest = whole_output_digest("1ddf74263cb4953cfdfcf99c563d88ea").unwrap(); - assert_eq!(digest[0], 0x1d); - assert_eq!(digest[15], 0xea); - let with_name = whole_output_digest("1ddf74263cb4953cfdfcf99c563d88ea out.yuv\n"); - assert_eq!(with_name, Some(digest)); - assert_eq!(whole_output_digest("1ddf7426"), None); - assert_eq!( - whole_output_digest("zzdf74263cb4953cfdfcf99c563d88ea"), - None - ); -} - -/// Accepted streams that are knowingly not fully exact, each with the reason. Remove an entry -/// once the stream is exact. Nothing else may be listed. -const KNOWN_INEXACT: &[(&str, &str)] = &[]; diff --git a/crates/ec-h265/tests/it/conformance_rext.rs b/crates/ec-h265/tests/it/conformance_rext.rs deleted file mode 100644 index ad752f0e..00000000 --- a/crates/ec-h265/tests/it/conformance_rext.rs +++ /dev/null @@ -1,325 +0,0 @@ -//! Checks every output picture of each JCT-VC range extension conformance stream -//! (D.3.19), or against the whole-output MD5 of the package when the stream has no hash. -//! -//! A stream the decoder refuses must be refused by name: the error text has to be one of -//! `REFUSED`. Every other stream has to decode exactly, picture for picture. - -use crate::common::{cropped_bytes, describe, plane_matches, whole_output_digest}; -use std::panic::{self, AssertUnwindSafe}; -use std::path::{Path, PathBuf}; - -use ec_h265::dec::Decoder; - -/// The outcome of one stream, one row of the report. -struct Row { - name: String, - accepted: &'static str, - checked: usize, - exact: usize, - detail: String, - /// Whether any picture was checked against the reference YUV (no hash SEI). - by_reference: bool, - /// Wall time of decode and flush, in seconds (0 when the stream was refused early). - decode_secs: f64, -} - -fn jctvc_root() -> PathBuf { - ec_testkit::fixture("vectors/hevc-rext") -} - -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's -/// directory under the root, sorted by name. Some zips extract one directory -/// deeper, so two levels are searched. -fn streams() -> Vec { - let root = jctvc_root(); - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - bitstreams_in(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let dirs = std::fs::read_dir(&root).expect("fixture directory"); - let mut dirs: Vec = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); - dirs.sort(); - dirs.into_iter() - .filter(|d| d.is_dir()) - .filter(|d| { - std::env::var("EC_H265_REXT_ONLY") - .map_or(true, |only| d.to_string_lossy().contains(&only)) - }) - .filter_map(|d| { - let mut found = Vec::new(); - bitstreams_in(&d, 2, &mut found); - found.into_iter().next() - }) - .collect() -} - -/// Every 32-digit hex word of the MD5 files beside the bitstream (`*md5*`): one of them is the -/// MD5 of the whole decoded output, the others are the bitstream's own. -fn candidate_digests(path: &Path) -> Vec<[u8; 16]> { - let mut out = Vec::new(); - let Some(dir) = path.parent() else { - return out; - }; - let Ok(entries) = std::fs::read_dir(dir) else { - return out; - }; - for e in entries.flatten() { - let name = e.file_name().to_string_lossy().to_lowercase(); - if !name.contains("md5") { - continue; - } - if let Ok(text) = std::fs::read_to_string(e.path()) { - for word in text.split_whitespace() { - if let Some(d) = whole_output_digest(word) { - out.push(d); - } - } - } - } - out -} - -/// The stream cut at its start codes: each chunk is one NAL unit with its start code. -fn nal_chunks(data: &[u8]) -> Vec<&[u8]> { - let mut starts: Vec = (0..data.len().saturating_sub(2)) - .filter(|&i| data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) - .collect(); - starts.push(data.len()); - starts.windows(2).map(|w| &data[w[0]..w[1]]).collect() -} - -/// Decodes one stream and checks every output picture against its MD5 SEI. -fn check_stream(path: &Path, name: &str) -> Row { - let mut row = Row { - name: name.to_string(), - accepted: "no", - checked: 0, - exact: 0, - detail: String::new(), - by_reference: false, - decode_secs: 0.0, - }; - let data = match std::fs::read(path) { - Ok(d) => d, - Err(e) => { - row.detail = format!("read error: {e}"); - return row; - } - }; - let reference = std::fs::read(path.with_extension("yuv")).ok(); - // A `_md5.txt` beside the bitstream is the authority for frames without a hash SEI. It - // takes precedence over the ffmpeg reference YUV, which ffmpeg cannot reproduce for such a - // stream (VPSSPSPPS_A: ffmpeg outputs 2 of its 6 frames). - let whole_output = Some(candidate_digests(path)).filter(|d| !d.is_empty()); - let mut whole_output_md5 = ec_h265_syntax::md5::Md5::new(); - let mut whole_output_checked = 0usize; - - let started = std::time::Instant::now(); - let mut dec = Decoder::new(); - let mut out_index = 0usize; - let mut first: Option = None; - let mut handle = |frame: ec_h265::dec::Frame| { - let index = out_index; - out_index += 1; - if whole_output.is_some() { - whole_output_md5.update(&cropped_bytes(&frame.picture, &frame.window)); - } - let Some(expected) = frame.meta.picture_hash.as_ref() else { - if whole_output.is_some() { - whole_output_checked += 1; - return; - } - // No hash SEI: the frame is checked against the reference YUV, when there is one. - if let Some(reference) = reference.as_deref() { - let want = cropped_bytes(&frame.picture, &frame.window); - let start = index * want.len(); - row.checked += 1; - if reference.get(start..start + want.len()) == Some(&want[..]) { - row.exact += 1; - } else if first.is_none() { - let at = (0..3) - .find_map(|plane| { - let d = - describe(Some(reference), index, &frame.picture, frame.poc, plane); - (!d.contains("no sample differs")).then_some(d) - }) - .unwrap_or_else(|| format!("reference YUV frame {index} differs")); - first = Some(format!("{at} (reference YUV, cropped)")); - } - row.by_reference = true; - } - return; - }; - row.checked += 1; - let pic = &*frame.picture; - let mut exact = true; - for (plane, ok) in plane_matches(pic, expected).into_iter().enumerate() { - if ok { - continue; - } - exact = false; - if first.is_none() { - let kind = if frame.meta.intra_only { "I" } else { "P/B" }; - let at = describe(reference.as_deref(), index, pic, frame.poc, plane); - first = Some(format!("{at} slices={kind}")); - } - } - if exact { - row.exact += 1; - } - }; - // Frames are drained after every NAL unit, so the output of a long stream is not held. - for unit in nal_chunks(&data) { - if let Err(e) = dec.decode_annex_b(unit) { - row.detail = format!("error: {e}"); - return row; - } - while let Some(frame) = dec.next_frame() { - handle(frame); - } - } - if let Err(e) = dec.flush() { - row.detail = format!("error: {e}"); - return row; - } - row.accepted = "yes"; - while let Some(frame) = dec.next_frame() { - handle(frame); - } - row.decode_secs = started.elapsed().as_secs_f64(); - if let Some(want) = whole_output.as_ref().filter(|_| whole_output_checked > 0) { - let got = whole_output_md5.finish(); - row.checked += whole_output_checked; - if want.contains(&got) { - row.exact += whole_output_checked; - } else { - let hex: String = got.iter().map(|b| format!("{b:02x}")).collect(); - first.get_or_insert(format!( - "whole-output MD5 {hex} differs from {name}_md5.txt" - )); - } - row.by_reference = true; - } - row.detail = match (first, row.checked) { - (Some(f), _) => format!("first mismatch {f}"), - (None, 0) => "no pictures with a hash SEI or reference YUV".to_string(), - (None, _) if whole_output.is_some() && whole_output_checked > 0 => { - "ok (whole-output MD5 from the conformance package)".to_string() - } - (None, _) if row.by_reference => "ok (against the reference YUV)".to_string(), - (None, _) => "ok".to_string(), - }; - row -} - -#[test] -fn rext_conformance_pictures_match_the_sei_hash() { - let root = jctvc_root(); - let streams = streams(); - assert!( - !streams.is_empty(), - "no conformance streams under {}", - root.display() - ); - - let mut rows = Vec::new(); - for path in &streams { - let name = path - .file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(); - eprintln!("stream {name}"); - let outcome = panic::catch_unwind(AssertUnwindSafe(|| check_stream(path, &name))); - let mut row = match outcome { - Ok(row) => row, - Err(payload) => { - let msg = payload - .downcast_ref::<&str>() - .map(|s| s.to_string()) - .or_else(|| payload.downcast_ref::().cloned()) - .unwrap_or_default(); - Row { - name: name.clone(), - accepted: "panic", - checked: 0, - exact: 0, - detail: format!("panic: {msg}"), - by_reference: false, - decode_secs: 0.0, - } - } - }; - row.detail = row.detail.replace(['\t', '\n'], " "); - rows.push(row); - } - - let mut table = - String::from("stream\taccepted\tpictures_checked\tpictures_exact\tdetail\tdecode_s\n"); - for r in &rows { - println!( - "{} | {} | {} | {} | {} | {:.2}s", - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs - ); - table.push_str(&format!( - "{}\t{}\t{}\t{}\t{}\t{:.2}\n", - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs - )); - } - let checked: usize = rows.iter().map(|r| r.checked).sum(); - let exact: usize = rows.iter().map(|r| r.exact).sum(); - let accepted = rows.iter().filter(|r| r.accepted == "yes").count(); - println!( - "total: {checked} pictures checked, {exact} exact, {accepted}/{} streams accepted", - rows.len() - ); - let report = std::env::var("EC_H265_REXT_REPORT") - .ok() - .filter(|p| !p.is_empty()); - let written = report.map(|path| std::fs::write(&path, &table).map_err(|e| (path, e))); - if let Some(Err((path, e))) = written { - eprintln!("could not write report {path}: {e}"); - } - - // Every accepted stream must be fully exact; a refusal must name a tool in REFUSED. - let failing: Vec = rows - .iter() - .filter(|r| r.accepted == "yes" && (r.checked == 0 || r.exact != r.checked)) - .map(|r| format!("{} ({}/{} exact: {})", r.name, r.exact, r.checked, r.detail)) - .collect(); - assert!( - failing.is_empty(), - "accepted streams that are not exact:\n{}", - failing.join("\n") - ); - let unexpected: Vec = rows - .iter() - .filter(|r| r.accepted != "yes") - .filter(|r| !REFUSED.iter().any(|name| r.detail.contains(name))) - .map(|r| format!("{} ({}: {})", r.name, r.accepted, r.detail)) - .collect(); - assert!( - unexpected.is_empty(), - "streams refused for a reason not in REFUSED:\n{}", - unexpected.join("\n") - ); -} - -/// The refusals a conformance stream may end in: tools this decoder names and does not decode. -const REFUSED: &[&str] = &[ - "extended_precision_processing_flag", - "cabac_bypass_alignment_enabled_flag", - "high_precision_offsets_enabled_flag", - "bit depth 16", - "bit depth 14", - "bit depth 13", -]; diff --git a/crates/ec-h265/tests/it/conformance_rext422.rs b/crates/ec-h265/tests/it/conformance_rext422.rs deleted file mode 100644 index 9f7ed2c2..00000000 --- a/crates/ec-h265/tests/it/conformance_rext422.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! HEVC RExt 4:2:2 (Main 4:2:2 10 and the 8-bit generated clips) against ffmpeg. -//! -//! The committed 64x64 stream is decoded by ffmpeg at run time and compared sample for -//! sample. The Sony RExt conformance streams and the generated GOP/intra clips live in the - -use std::path::{Path, PathBuf}; - -use ec_h265::Decoder; - -const YUV422_10: &[u8] = include_bytes!("../data/refusals/yuv422_10.265"); - -fn decode(data: &[u8]) -> Vec { - let mut dec = Decoder::new(); - dec.decode_annex_b(data).expect("decode"); - dec.flush().expect("flush"); - let mut out = Vec::new(); - while let Some(f) = dec.next_frame() { - out.push((*f.picture).clone()); - } - out -} - -/// The first coded-size-cropped `w` x `h` window of every picture, as planar little-endian -/// samples (one byte per sample at 8 bit, two above), the layout of ffmpeg's rawvideo. -fn raw(pictures: &[ec_h265::decode::DecodedPicture], w: usize, h: usize) -> Vec { - let mut out = Vec::new(); - for p in pictures { - let wide = p.bit_depth > 8; - for (plane, pw, cw) in [ - (&p.y, p.width, w), - (&p.cb, p.width / 2, w / 2), - (&p.cr, p.width / 2, w / 2), - ] { - for y in 0..h { - for x in 0..cw { - let v = plane[y * pw + x]; - if wide { - out.extend_from_slice(&v.to_le_bytes()); - } else { - out.push(v as u8); - } - } - } - } - } - out -} - -fn first_diff(a: &[u8], b: &[u8]) -> Option { - if a.len() != b.len() { - return Some(a.len().min(b.len())); - } - a.iter().zip(b).position(|(x, y)| x != y) -} - -fn ffmpeg_422_10(src: &Path, reference: &Path) { - let st = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(src) - .args(["-f", "rawvideo", "-pix_fmt", "yuv422p10le"]) - .arg(reference) - .status() - .unwrap(); - assert!(st.success(), "ffmpeg failed on {}", src.display()); -} - -#[test] -fn committed_422_stream_matches_ffmpeg() { - let dir = std::env::temp_dir().join("ec-h265-rext422"); - std::fs::create_dir_all(&dir).unwrap(); - let src = dir.join("yuv422_10.265"); - let reference = dir.join("yuv422_10.yuv"); - std::fs::write(&src, YUV422_10).unwrap(); - ffmpeg_422_10(&src, &reference); - let want = std::fs::read(&reference).unwrap(); - let got = raw(&decode(YUV422_10), 64, 64); - assert_eq!( - first_diff(&got, &want), - None, - "4:2:2 10-bit differs from ffmpeg" - ); -} - -fn rext_root() -> PathBuf { - ec_testkit::fixture("vectors/hevc-rext") -} - -fn find_stream(dir: &Path) -> Option { - for e in std::fs::read_dir(dir).ok()?.flatten() { - let p = e.path(); - if p.is_dir() { - if let Some(f) = find_stream(&p) { - return Some(f); - } - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - return Some(p); - } - } - None -} - -#[test] -fn rext_422_vectors_are_byte_exact() { - let root = rext_root(); - let dir = std::env::temp_dir().join("ec-h265-rext422-vectors"); - std::fs::create_dir_all(&dir).unwrap(); - let mut checked = 0; - for (name, w, h) in [ - ("GENERAL_10b_422_RExt_Sony_1", 400, 384), - ("Main_422_10_A_RExt_Sony_2", 1920, 1080), - ("Main_422_10_B_RExt_Sony_2", 2560, 1600), - ] { - let stream = find_stream(&root.join(name)).unwrap_or_else(|| panic!("{name}: no stream")); - let reference = dir.join(format!("{name}.yuv")); - ffmpeg_422_10(&stream, &reference); - let data = std::fs::read(&stream).unwrap_or_else(|e| panic!("{}: {e}", stream.display())); - let want = std::fs::read(&reference).unwrap(); - let got = raw(&decode(&data), w, h); - assert_eq!( - first_diff(&got, &want), - None, - "{} differs from ffmpeg", - stream.display() - ); - checked += 1; - } - eprintln!("4:2:2 vectors checked byte-exact: {checked}"); -} diff --git a/crates/ec-h265/tests/it/cu_syntax.rs b/crates/ec-h265/tests/it/cu_syntax.rs deleted file mode 100644 index 29ff6133..00000000 --- a/crates/ec-h265/tests/it/cu_syntax.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! CU syntax tests over the JCT-VC conformance streams: the P/B slice syntax with the -//! zero-motion stand-in (the sweep, pixel-pipeline and motion-determinism tests were removed by -//! testcut Phase 2). - -use ec_core::error::Error; -use ec_h265::dec::Decoder; -use std::path::{Path, PathBuf}; - -/// The conformance streams: the first `.bin` or `.bit` bitstream of each directory -fn streams() -> Vec { - let root = ec_testkit::fixture("vectors/hevc-jctvc"); - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - bitstreams_in(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let dirs = std::fs::read_dir(&root).expect("fixture directory"); - let mut dirs: Vec = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); - dirs.sort(); - dirs.into_iter() - .filter(|d| d.is_dir()) - .filter_map(|d| { - let mut found = Vec::new(); - bitstreams_in(&d, 2, &mut found); - found.into_iter().next() - }) - .collect() -} - -/// Split an Annex-B byte stream into NAL units (header included, start codes and -/// trailing zero bytes removed). -fn nal_units(data: &[u8]) -> Vec<&[u8]> { - let mut starts = Vec::new(); - let mut i = 0; - while i + 3 <= data.len() { - if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 { - starts.push(i + 3); - i += 3; - } else { - i += 1; - } - } - let mut out = Vec::new(); - for (k, &s) in starts.iter().enumerate() { - let mut e = starts.get(k + 1).map_or(data.len(), |&next| next - 3); - while e > s && data[e - 1] == 0 { - e -= 1; - } - if e > s { - out.push(&data[s..e]); - } - } - out -} - -/// Whether a NAL unit is a coded slice segment (types 0 to 9 and 16 to 21). -fn is_slice(nal: &[u8]) -> bool { - let t = (nal[0] >> 1) & 0x3f; - t <= 9 || (16..=21).contains(&t) -} - -/// The P/B slice syntax ([`ec_h265::dec::cu_syntax::parse_slice`] with the zero-motion -/// stand-in, no DPB to derive motion from) over every P and B slice segment of every -/// stream. Pixel decode is off so the decoder only keeps parameter sets. Refusals are -/// fine; any other error is a failure. -#[test] -fn inter_placeholder_runs_over_pb_slices() { - use ec_core::bitio::BitReader; - use ec_h265_syntax::nal::{NalUnitType, unescape_rbsp}; - use ec_h265_syntax::slice::{SliceHeader, SliceType}; - let streams = streams(); - assert!(!streams.is_empty(), "no conformance streams"); - let (mut pb_slices, mut decoded, mut refused) = (0usize, 0usize, 0usize); - for path in &streams { - let data = std::fs::read(path).expect("read bitstream"); - let mut dec = Decoder::new(); - dec.set_pixel_decode(false); - for nal in nal_units(&data) { - let code = (nal[0] >> 1) & 0x3f; - if is_slice(nal) { - let rbsp = unescape_rbsp(&nal[2..]); - let mut r = BitReader::new(&rbsp); - let _first = r.read_bit(); - if (16..=21).contains(&code) { - let _no_output_of_prior_pics = r.read_bit(); - } - let pps_id = r.read_ue().unwrap_or(u32::MAX); - if let Some(pps) = dec.pps(pps_id) - && let Some(sps) = dec.sps(pps.sps_id) - && let Ok((header, pos)) = - SliceHeader::parse(&rbsp, sps, pps, NalUnitType::from_code(code)) - && header.slice_type != SliceType::I - && header.first_slice_segment_in_pic - { - pb_slices += 1; - let off = (pos.header_bits / 8) as usize; - let slice_data = rbsp.get(off..).unwrap_or(&[]); - let mut zero = ec_h265::dec::cu_syntax::ZeroMotion; - match ec_h265::dec::cu_syntax::parse_slice( - sps, - pps, - &header, - slice_data, - &mut zero, - &mut |_| {}, - ) { - Ok(_) => decoded += 1, - Err(Error::Unsupported { .. }) => refused += 1, - Err(err) => { - panic!("{}: P/B placeholder failed: {err}", path.display()) - } - } - } - } - let _ = dec.push_nal(nal); - } - } - println!( - "inter syntax: {decoded} P/B slices parsed, {refused} refused by name, of {pb_slices} first-slice P/B segments" - ); -} diff --git a/crates/ec-h265/tests/it/dec_meta.rs b/crates/ec-h265/tests/it/dec_meta.rs deleted file mode 100644 index c7a2bd55..00000000 --- a/crates/ec-h265/tests/it/dec_meta.rs +++ /dev/null @@ -1,244 +0,0 @@ -//! Metadata on the decoder's output frames: HDR SEI from the IRAP on, the VUI -//! colour description, the decoded picture hash, and the rule that Dolby Vision -//! NAL units (62, 63) and malformed SEI change nothing. -//! -//! The streams come from `fixtures/vectors/hevc-jctvc`. Without them the tests - -use std::path::{Path, PathBuf}; - -use ec_h265::dec::{Decoder, Frame}; -use ec_h265_syntax::nal::{escape_rbsp, split_annex_b}; -use ec_h265_syntax::sei::{ContentLightLevel, MasteringDisplay, PictureHash}; - -fn stream_files() -> Vec { - let root = ec_testkit::fixture("vectors/hevc-jctvc"); - fn walk(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - walk(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let mut out = Vec::new(); - walk(&root, 2, &mut out); - out -} - -/// The raw NAL units (two-byte header and escaped payload) of an Annex-B stream. -fn raw_nals(data: &[u8]) -> Vec> { - split_annex_b(data) - .iter() - .map(|n| { - let mut v = n.header.to_bytes().to_vec(); - v.extend_from_slice(n.payload); - v - }) - .collect() -} - -/// Decode with picture management only, returning every frame, or the first error. -fn decode(nals: &[Vec]) -> Result, String> { - let mut dec = Decoder::new(); - dec.set_pixel_decode(false); - for nal in nals { - dec.push_nal(nal).map_err(|e| e.to_string())?; - } - dec.flush().map_err(|e| e.to_string())?; - let mut frames = Vec::new(); - while let Some(f) = dec.next_frame() { - frames.push(f); - } - Ok(frames) -} - -/// The first conformance stream that decodes without error, with its NAL units. -fn clean_stream() -> Option<(String, Vec>)> { - for path in stream_files() { - let Ok(data) = std::fs::read(&path) else { - continue; - }; - let nals = raw_nals(&data); - if decode(&nals).is_ok() { - let name = path - .file_name() - .unwrap_or_default() - .to_string_lossy() - .to_string(); - return Some((name, nals)); - } - } - None -} - -fn require_stream() -> (String, Vec>) { - clean_stream().expect("no clean conformance stream") -} - -/// What a frame looks like to a caller, for comparing two decodes. -fn key(f: &Frame) -> (i32, u32, usize, usize, Vec, Vec, Vec) { - ( - f.poc, - f.au_index, - f.picture.width, - f.picture.height, - f.picture.y.clone(), - f.picture.cb.clone(), - f.picture.cr.clone(), - ) -} - -/// A NAL unit of the given type, with the payload escaped. -fn nal_unit(nal_type: u8, rbsp: &[u8]) -> Vec { - let mut v = vec![nal_type << 1, 1]; - escape_rbsp(rbsp, &mut v); - v -} - -fn is_vcl(nal: &[u8]) -> bool { - matches!((nal[0] >> 1) & 0x3f, 0..=21) -} - -/// The HDR10 mastering display of a 1000 nit, 0.0050 nit BT.2020 grade, then a -/// content light level of MaxCLL 1000 and MaxFALL 400, as one prefix SEI RBSP. -fn hdr10_prefix_rbsp() -> Vec { - let mut mdcv = Vec::new(); - for (x, y) in [ - (8500u16, 39_850u16), - (6550, 2300), - (35_400, 14_600), - (15_635, 16_450), - ] { - mdcv.extend_from_slice(&x.to_be_bytes()); - mdcv.extend_from_slice(&y.to_be_bytes()); - } - mdcv.extend_from_slice(&10_000_000u32.to_be_bytes()); - mdcv.extend_from_slice(&50u32.to_be_bytes()); - let mut rbsp = vec![137, 24]; - rbsp.extend_from_slice(&mdcv); - rbsp.extend_from_slice(&[144, 4, 0x03, 0xe8, 0x01, 0x90, 0x80]); - rbsp -} - -#[test] -fn dolby_vision_nal_units_change_nothing() { - let (name, nals) = require_stream(); - let base = decode(&nals).unwrap(); - let mut injected = Vec::new(); - for nal in &nals { - injected.push(vec![62 << 1, 1, 0xde, 0xad, 0xbe, 0xef]); - injected.push(vec![63 << 1, 1, 0x80]); - injected.push(nal.clone()); - } - let with_rpu = decode(&injected).unwrap(); - assert!(!base.is_empty(), "{name}: no frames"); - assert_eq!(base.len(), with_rpu.len(), "{name}: frame count changed"); - for (a, b) in base.iter().zip(&with_rpu) { - assert_eq!( - key(a), - key(b), - "{name}: a frame changed with type 62/63 NAL units" - ); - } -} - -#[test] -fn malformed_sei_is_skipped_and_the_stream_decodes_the_same() { - let (name, nals) = require_stream(); - let base = decode(&nals).unwrap(); - let mut injected = Vec::new(); - for nal in &nals { - // A message that runs past the RBSP, a suffix SEI with a reserved hash type, - // and one with a short mastering display payload. - injected.push(nal_unit(39, &[5, 9, 1, 2, 0x80])); - injected.push(nal_unit(40, &[132, 2, 3, 0, 0x80])); - let mut short_mdcv = vec![137, 23]; - short_mdcv.extend_from_slice(&[0; 23]); - short_mdcv.push(0x80); - injected.push(nal_unit(39, &short_mdcv)); - injected.push(nal.clone()); - } - let with_bad = decode(&injected).unwrap(); - assert_eq!(base.len(), with_bad.len(), "{name}: frame count changed"); - for (a, b) in base.iter().zip(&with_bad) { - assert_eq!(key(a), key(b), "{name}: a frame changed with malformed SEI"); - assert!( - b.mastering_display().is_none(), - "{name}: a malformed SEI produced metadata" - ); - } -} - -#[test] -fn hdr_sei_applies_to_every_frame_from_the_irap_on() { - let (name, nals) = require_stream(); - let mut injected = Vec::new(); - let mut placed = false; - for nal in &nals { - if !placed && is_vcl(nal) { - // A prefix SEI in the first access unit, before its first slice. - injected.push(nal_unit(39, &hdr10_prefix_rbsp())); - placed = true; - } - injected.push(nal.clone()); - } - let frames = decode(&injected).unwrap(); - assert!(!frames.is_empty(), "{name}: no frames"); - for f in &frames { - let md: &MasteringDisplay = f.mastering_display().expect("MDCV on every frame"); - assert_eq!(md.display_primaries[0], (8500, 39_850)); - assert_eq!(md.white_point, (15_635, 16_450)); - assert_eq!(md.max_nits(), 1000.0); - assert!((md.min_nits() - 0.005).abs() < 1e-6); - let cll: &ContentLightLevel = f.content_light_level().expect("CLL on every frame"); - assert_eq!( - (cll.max_content_light_level, cll.max_pic_average_light_level), - (1000, 400) - ); - assert_eq!(f.alternative_transfer_characteristics(), None); - } -} - -#[test] -fn picture_hash_attaches_to_the_picture_it_follows() { - let (name, nals) = require_stream(); - // One MD5 plane: payloadType 132, payloadSize 17, hash_type 0, the digest. - let digest = [0x5au8; 16]; - let mut hash_rbsp = vec![132, 17, 0]; - hash_rbsp.extend_from_slice(&digest); - hash_rbsp.push(0x80); - - let mut injected = Vec::new(); - let mut placed = false; - for nal in &nals { - injected.push(nal.clone()); - // A suffix SEI right after the first slice: it belongs to access unit 0. - if !placed && is_vcl(nal) { - injected.push(nal_unit(40, &hash_rbsp)); - placed = true; - } - } - let frames = decode(&injected).unwrap(); - assert!(placed, "{name}: no slice NAL unit"); - let first = frames - .iter() - .find(|f| f.au_index == 0) - .expect("access unit 0 is output"); - match first.picture_hash() { - Some(PictureHash::Md5(d)) => assert_eq!(d, &[digest]), - other => panic!("{name}: access unit 0 hash is {other:?}"), - } - assert!( - frames - .iter() - .filter(|f| f.au_index != 0) - .all(|f| f.picture_hash().is_none()), - "{name}: a hash leaked to another picture" - ); -} diff --git a/crates/ec-h265/tests/it/dec_shell.rs b/crates/ec-h265/tests/it/dec_shell.rs deleted file mode 100644 index 027386b4..00000000 --- a/crates/ec-h265/tests/it/dec_shell.rs +++ /dev/null @@ -1,454 +0,0 @@ -//! Picture management of the stateful decoder (`ec_h265::dec`): POC, RPS and -//! marking, bumping, reference lists, and the JCT-VC conformance sweep. -//! -//! The sweep parses every slice of every stream through the picture-management -//! path (pixel decode off) and checks the output order against ffprobe. Streams -//! whose slices are all intra are also pixel-decoded and compared with ffmpeg's - -use std::collections::VecDeque; -use std::path::{Path, PathBuf}; - -use ec_h265::dec::dpb::{Dpb, DpbLimits, Marking, PendingFrame}; -use ec_h265::dec::poc::derive_poc; -use ec_h265::dec::rps::{RpsInput, build_ref_lists}; -use ec_h265::dec::shared::SharedPic; -use ec_h265::dec::{Decoder, NalOutcome}; -use ec_h265::decode::DecodedPicture; -use ec_h265_syntax::slice::{LongTermRef, SliceHeader, SliceType}; -use ec_h265_syntax::{ConformanceWindow, Pps, ShortTermRefPicSet}; - -fn picture(w: usize, h: usize) -> DecodedPicture { - DecodedPicture { - width: w, - height: h, - bit_depth: 8, - bit_depth_c: 8, - chroma_format_idc: 1, - y: Vec::new(), - cb: Vec::new(), - cr: Vec::new(), - } -} - -fn st_set(before: &[i32], after: &[i32]) -> ShortTermRefPicSet { - let mut st = ShortTermRefPicSet { - num_negative: before.len() as u32, - num_positive: after.len() as u32, - ..ShortTermRefPicSet::default() - }; - for (i, &d) in before.iter().enumerate() { - st.delta_poc_s0[i] = d; - st.used_s0[i] = true; - } - for (i, &d) in after.iter().enumerate() { - st.delta_poc_s1[i] = d; - st.used_s1[i] = true; - } - st -} - -fn rps_input<'a>( - poc: i32, - st: &'a ShortTermRefPicSet, - lt: &'a [LongTermRef], - fill: Option<(u32, u32)>, -) -> RpsInput<'a> { - RpsInput { - poc, - log2_max_poc_lsb: 4, - st, - lt, - irap_no_rasl: false, - width: 16, - height: 16, - chroma_format_idc: 1, - fill, - } -} - -fn add(dpb: &mut Dpb, poc: i32, marking: Marking, output: bool) -> u32 { - dpb.insert( - poc, - marking, - output, - std::sync::Arc::new(SharedPic::from_planes(poc, picture(16, 16))), - ConformanceWindow::default(), - poc as u32, - ) -} - -#[test] -fn poc_follows_the_lsb_without_wrapping() { - assert_eq!(derive_poc(5, 4, 7, false), 7); - assert_eq!(derive_poc(0, 4, 0, false), 0); -} - -#[test] -fn poc_msb_wraps_forward_at_the_half_window() { - // prevTid0 = 0, lsb 14 of 16: 14 - 0 > 8, so the MSB is -16 and POC is -2. - assert_eq!(derive_poc(0, 4, 14, false), -2); -} - -#[test] -fn poc_msb_wraps_backward_past_the_maximum() { - // prevTid0 = 14 (lsb 14), lsb 2: 14 - 2 >= 8, so the MSB advances to 16. - assert_eq!(derive_poc(14, 4, 2, false), 18); -} - -#[test] -fn poc_of_an_irap_with_no_rasl_output_has_no_msb() { - assert_eq!(derive_poc(37, 4, 5, true), 5); -} - -#[test] -fn rps_marks_what_it_names_and_drops_the_rest() { - let mut dpb = Dpb::new(); - let ids: Vec = [0, 1, 2, 3, 4, 5, 6, 7] - .iter() - .map(|&p| add(&mut dpb, p, Marking::ShortTerm, false)) - .collect(); - // Current POC 8 names 7, 5 and 4 (deltas -1, -3, -4). 0..3 and 6 drop out. - let st = st_set(&[-1, -3, -4], &[]); - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); - let before: Vec = set.st_curr_before.iter().map(|e| e.poc).collect(); - assert_eq!(before, vec![7, 5, 4]); - assert!(set.st_curr_after.is_empty()); - assert!(set.lt_curr.is_empty()); - assert_eq!(set.st_curr_before[0].id, ids[7]); - for &p in &[0usize, 1, 2, 3, 6] { - assert_eq!(dpb.get(ids[p]).unwrap().marking, Marking::Unused, "POC {p}"); - } - assert_eq!(dpb.get(ids[5]).unwrap().marking, Marking::ShortTerm); - dpb.remove_unneeded(); - assert_eq!(dpb.len(), 3); -} - -#[test] -fn rps_generates_a_missing_reference_as_grey() { - let mut dpb = Dpb::new(); - add(&mut dpb, 4, Marking::ShortTerm, false); - // Current POC 8 names POC 6 (absent) and POC 4. - let st = st_set(&[-2, -4], &[]); - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); - assert_eq!(set.st_curr_before.len(), 2); - let generated = dpb - .get(set.st_curr_before[0].id) - .expect("generated picture"); - assert_eq!(generated.poc, 6); - assert!(!generated.needed_for_output); - let planes = generated.picture.read_planes(); - assert_eq!(planes.y.len(), 16 * 16); - assert!(planes.y.iter().all(|&v| v == 128)); -} - -#[test] -fn rps_long_term_entry_matches_by_lsb_and_converts_marking() { - let mut dpb = Dpb::new(); - let lt_id = add(&mut dpb, 16, Marking::ShortTerm, false); - // PocLsbLt 0 with no MSB: the picture with POC & 15 == 0 is POC 16. - let lt = [LongTermRef { - poc_lsb_lt: 0, - used_by_curr: true, - delta_poc_msb_present: false, - delta_poc_msb_cycle: 0, - }]; - let st = ShortTermRefPicSet::default(); - let set = dpb.apply_rps(&rps_input(20, &st, <, Some((8, 8)))); - assert_eq!(set.lt_curr.len(), 1); - assert_eq!(set.lt_curr[0].id, lt_id); - assert!(set.lt_curr[0].long_term); - assert_eq!(dpb.get(lt_id).unwrap().marking, Marking::LongTerm); -} - -#[test] -fn bumping_outputs_in_poc_order_under_the_reorder_limit() { - let limits = DpbLimits { - max_dec_pic_buffering: 6, - max_num_reorder: 2, - max_latency_plus1: 0, - }; - let mut dpb = Dpb::new(); - let mut out: VecDeque = VecDeque::new(); - // Decode order 0, 8, 4, 2: a reorder limit of 2 forces output as it goes. - for poc in [0, 8, 4, 2] { - add(&mut dpb, poc, Marking::Unused, true); - while dpb.needs_bumping(&limits, false) && dpb.bump(&mut out) {} - } - let early: Vec = out.iter().map(|f| f.poc).collect(); - assert_eq!(early, vec![0, 2]); - dpb.drain(&mut out); - let all: Vec = out.iter().map(|f| f.poc).collect(); - assert_eq!(all, vec![0, 2, 4, 8]); - assert!(dpb.is_empty()); -} - -#[test] -fn bumping_honours_the_latency_limit() { - let limits = DpbLimits { - max_dec_pic_buffering: 6, - max_num_reorder: 4, - max_latency_plus1: 1, - }; - let mut dpb = Dpb::new(); - let mut out = VecDeque::new(); - add(&mut dpb, 0, Marking::Unused, true); - assert!(!dpb.needs_bumping(&limits, false)); - // SpsMaxLatencyPictures = 4 + 1 - 1 = 4: a picture that waited 4 times goes out. - dpb.pictures_mut()[0].latency = 4; - assert!(dpb.needs_bumping(&limits, false)); - assert!(dpb.bump(&mut out)); - assert_eq!(out.len(), 1); -} - -#[test] -fn bumping_drops_a_full_buffer_only_when_asked() { - let limits = DpbLimits { - max_dec_pic_buffering: 2, - max_num_reorder: 8, - max_latency_plus1: 0, - }; - let mut dpb = Dpb::new(); - add(&mut dpb, 0, Marking::ShortTerm, false); - add(&mut dpb, 2, Marking::ShortTerm, false); - assert!(dpb.needs_bumping(&limits, true)); - assert!(!dpb.needs_bumping(&limits, false)); -} - -#[test] -fn reference_lists_cycle_and_follow_the_modification() { - let mut dpb = Dpb::new(); - let a = add(&mut dpb, 4, Marking::ShortTerm, false); - let b = add(&mut dpb, 6, Marking::ShortTerm, false); - let c = add(&mut dpb, 10, Marking::ShortTerm, false); - let st = st_set(&[-4, -2], &[2]); - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); - assert_eq!( - set.st_curr_before.iter().map(|e| e.id).collect::>(), - vec![a, b] - ); - assert_eq!( - set.st_curr_after.iter().map(|e| e.id).collect::>(), - vec![c] - ); - - let pps = Pps::default(); - let mut header = SliceHeader::intra(&pps, 0); - header.slice_type = SliceType::B; - header.num_ref_idx_l0_active_minus1 = 3; - header.num_ref_idx_l1_active_minus1 = 1; - let lists = build_ref_lists(&set, &header).expect("lists"); - let l0: Vec = lists.l0.iter().map(|e| e.id).collect(); - assert_eq!(l0, vec![a, b, c, a]); - let l1: Vec = lists.l1.iter().map(|e| e.id).collect(); - assert_eq!(l1, vec![c, a]); - - header.list_entry = [vec![2, 2, 0, 1], vec![1, 0]]; - let lists = build_ref_lists(&set, &header).expect("modified lists"); - assert_eq!( - lists.l0.iter().map(|e| e.id).collect::>(), - vec![c, c, a, b] - ); - assert_eq!( - lists.l1.iter().map(|e| e.id).collect::>(), - vec![a, c] - ); -} - -#[test] -fn decoder_refuses_out_of_scope_parameter_sets_and_skips_layers() { - let mut dec = Decoder::new(); - // A VPS-typed NAL on layer 1 is skipped whatever its payload. - let layer1 = [32u8 << 1, 0b0000_1001, 0xff]; - assert_eq!(dec.push_nal(&layer1).unwrap(), NalOutcome::Skipped); - // SEI and filler are ignored. - assert_eq!( - dec.push_nal(&[39 << 1, 1, 0x80]).unwrap(), - NalOutcome::Skipped - ); - assert_eq!( - dec.push_nal(&[62 << 1, 1, 0x80]).unwrap(), - NalOutcome::Skipped - ); - assert!(dec.next_frame().is_none()); -} - -fn run(args: &[&str], file: &Path) -> Result, String> { - let out = ec_testkit::ffprobe() - .args(["-v", "error"]) - .args(args) - .arg(file) - .output() - .map_err(|e| e.to_string())?; - if !out.status.success() { - return Err(String::from_utf8_lossy(&out.stderr).trim().to_string()); - } - Ok(out.stdout) -} - -fn numbers(text: &[u8]) -> Vec { - String::from_utf8_lossy(text) - .lines() - .filter_map(|l| l.trim().trim_end_matches(',').parse().ok()) - .collect() -} - -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's -/// by name. Some zips extract one directory deeper, so two levels are searched. -fn streams() -> Vec { - let root = ec_testkit::fixture("vectors/hevc-jctvc"); - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - bitstreams_in(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let dirs = std::fs::read_dir(&root).expect("fixture directory"); - let mut dirs: Vec = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); - dirs.sort(); - dirs.into_iter() - .filter(|d| d.is_dir()) - .filter_map(|d| { - let mut found = Vec::new(); - bitstreams_in(&d, 2, &mut found); - found.into_iter().next() - }) - .collect() -} - -/// Output order from our decoder, picture management only: (POC, AU index). -fn our_order(data: &[u8]) -> Result, String> { - let mut dec = Decoder::new(); - dec.set_pixel_decode(false); - dec.decode_annex_b(data).map_err(|e| e.to_string())?; - dec.flush().map_err(|e| e.to_string())?; - let mut order = Vec::new(); - while let Some(f) = dec.next_frame() { - order.push((f.poc, f.au_index)); - } - Ok(order) -} - -/// Output order from ffprobe: the access-unit index (by packet position in -/// decode order) of each frame, in display order. -fn ffprobe_order(path: &Path) -> Result, String> { - let packets = numbers(&run( - &[ - "-select_streams", - "v:0", - "-show_entries", - "packet=pos", - "-of", - "csv=p=0", - ], - path, - )?); - let frames = numbers(&run( - &[ - "-select_streams", - "v:0", - "-show_entries", - "frame=pkt_pos", - "-of", - "csv=p=0", - ], - path, - )?); - frames - .iter() - .map(|pos| { - packets - .iter() - .position(|p| p == pos) - .map(|i| i as u32) - .ok_or_else(|| format!("frame position {pos} is no packet position")) - }) - .collect() -} - -/// Streams where ffprobe is not the reference: the spec's frame count (from the -/// conformance description) and why ffprobe differs. Our count must equal the spec's. -fn spec_expectation(name: &str) -> Option<(usize, &'static str)> { - match name { - // Unequal luma (10) and chroma (9) bit depth: ffmpeg decodes nothing. - "TSUNEQBD_A_MAIN10_Technicolor_2" => Some((8, "ffmpeg unsupported (unequal bit depths)")), - // Six IDR pictures, each with its own VPS/SPS/PPS and resolution: ffmpeg outputs 2. - "VPSSPSPPS_A_MainConcept_1" => Some((6, "ffmpeg outputs 2")), - _ => None, - } -} - -#[test] -fn conformance_output_order_matches_ffprobe() { - let streams = streams(); - assert!(!streams.is_empty(), "no conformance streams"); - let mut table = String::from("stream\tpictures_out\tffprobe_out\tresult\tdetail\n"); - let mut pass = 0usize; - let mut spec_ok = 0usize; - for path in &streams { - let name = path - .file_stem() - .unwrap_or_default() - .to_string_lossy() - .to_string(); - let data = match std::fs::read(path) { - Ok(d) => d, - Err(e) => { - table.push_str(&format!("{name}\t-\t-\tFAIL\tread: {e}\n")); - continue; - } - }; - let ours = our_order(&data); - let theirs = ffprobe_order(path); - let row = match (ours, theirs) { - (Ok(ours), Ok(theirs)) => { - let our_aus: Vec = ours.iter().map(|(_, au)| *au).collect(); - let pocs: Vec = ours.iter().take(8).map(|(p, _)| p.to_string()).collect(); - let detail = format!("first POCs {}", pocs.join(",")); - match spec_expectation(&name) { - // The spec's own count is the reference where ffprobe is wrong. - Some((frames, why)) => { - let verdict = if ours.len() == frames { "SPEC" } else { "FAIL" }; - if verdict == "SPEC" { - spec_ok += 1; - } - format!( - "{name}\t{}\t{}\t{verdict}\tspec: {frames} frames, {why}; {detail}\n", - ours.len(), - theirs.len(), - ) - } - None => { - let verdict = if our_aus == theirs { "PASS" } else { "FAIL" }; - if verdict == "PASS" { - pass += 1; - } - format!( - "{name}\t{}\t{}\t{verdict}\t{detail}\n", - ours.len(), - theirs.len(), - ) - } - } - } - (Err(e), _) => format!("{name}\t-\t-\tREFUSED\t{e}\n"), - (_, Err(e)) => format!("{name}\t-\t-\tSKIP\tffprobe: {e}\n"), - }; - table.push_str(&row); - } - match std::env::var("EC_H265_POC_TABLE") { - Ok(path) => std::fs::write(&path, &table).expect("write POC table"), - Err(_) => print!("{table}"), - } - eprintln!( - "POC/output order: {pass}/{} streams PASS, {spec_ok} SPEC (spec frame count, ffprobe differs)", - streams.len() - ); -} diff --git a/crates/ec-h265/tests/it/dolby_vision_p8.rs b/crates/ec-h265/tests/it/dolby_vision_p8.rs deleted file mode 100644 index ebf9bf1e..00000000 --- a/crates/ec-h265/tests/it/dolby_vision_p8.rs +++ /dev/null @@ -1,197 +0,0 @@ -//! Dolby Vision profile 8 layout: the HEVC base layer decodes, and the RPU NAL -//! units (type 62) are ignored. -//! -//! The base layer is generated here with ffmpeg's libx265 from a test pattern, so no -//! copyrighted media is involved. Type 62 NAL units with arbitrary payload are then -//! inserted in front of every VCL NAL unit. ec-h265 must decode the injected stream -//! to exactly the pictures it decodes from the clean one, and ffmpeg must decode the -//! injected stream to the same bytes. - -use ec_h265::Decoder; -use ec_h265::dec::Frame; -use ec_h265_syntax::nal::{escape_rbsp, split_annex_b}; -use std::path::Path; - -const WIDTH: usize = 352; -const HEIGHT: usize = 288; -const FRAMES: usize = 12; - -/// The base layer: libx265, an IDR every 4 pictures, P pictures in between, no B. -fn encode_base_layer(dir: &Path) -> Result, String> { - let out = dir.join("base.hevc"); - let frames = FRAMES.to_string(); - let source = format!("testsrc2=size={WIDTH}x{HEIGHT}:rate=30"); - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi", "-i"]) - .arg(&source) - .arg("-frames:v") - .arg(&frames) - .args([ - "-c:v", "libx265", "-preset", "veryfast", "-pix_fmt", "yuv420p", - ]) - .args([ - "-x265-params", - "keyint=4:min-keyint=4:bframes=0:scenecut=0:log-level=error", - "-f", - "hevc", - ]) - .arg(&out) - .output() - .map_err(|e| e.to_string())?; - if !status.status.success() { - return Err(String::from_utf8_lossy(&status.stderr).to_string()); - } - std::fs::read(&out).map_err(|e| e.to_string()) -} - -/// A type 62 NAL unit with arbitrary payload: zero runs, start-code-like bytes and -/// a trailing zero, escaped as a NAL unit must be. `seed` varies it per slice. -fn rpu_nal(seed: u8) -> Vec { - let rbsp = [ - 0x19, 0x08, 0x00, 0x00, 0x01, seed, 0x00, 0x00, 0x03, 0xff, 0x80, 0x00, - ]; - let mut v = vec![62 << 1, 1]; - escape_rbsp(&rbsp, &mut v); - v -} - -/// The stream with a type 62 NAL unit in front of every VCL NAL unit, each with -/// a four-byte start code. -fn inject_rpu(annex_b: &[u8]) -> Vec { - let mut out = Vec::with_capacity(annex_b.len() * 2); - let mut slice = 0u8; - for n in split_annex_b(annex_b) { - let mut nal = n.header.to_bytes().to_vec(); - nal.extend_from_slice(n.payload); - if matches!((nal[0] >> 1) & 0x3f, 0..=21) { - out.extend_from_slice(&[0, 0, 0, 1]); - out.extend_from_slice(&rpu_nal(slice)); - slice = slice.wrapping_add(1); - } - out.extend_from_slice(&[0, 0, 0, 1]); - out.extend_from_slice(&nal); - } - out -} - -/// Count of NAL units of `nal_type` in an Annex B stream. -fn count_nal_type(annex_b: &[u8], nal_type: u8) -> usize { - split_annex_b(annex_b) - .iter() - .filter(|n| (n.header.to_bytes()[0] >> 1) & 0x3f == nal_type) - .count() -} - -/// One picture as 4:2:0 bytes, cropped to the conformance window. -fn cropped_yuv(frame: &Frame) -> Vec { - let pic = &frame.picture; - let win = &frame.window; - let (lx0, lx1) = (2 * win.left as usize, pic.width - 2 * win.right as usize); - let (ly0, ly1) = (2 * win.top as usize, pic.height - 2 * win.bottom as usize); - let (cx0, cx1) = (win.left as usize, pic.width / 2 - win.right as usize); - let (cy0, cy1) = (win.top as usize, pic.height / 2 - win.bottom as usize); - let mut out = Vec::new(); - for row in ly0..ly1 { - out.extend( - pic.y[row * pic.width + lx0..row * pic.width + lx1] - .iter() - .map(|&v| v as u8), - ); - } - let cw = pic.width / 2; - for plane in [&pic.cb, &pic.cr] { - for row in cy0..cy1 { - out.extend( - plane[row * cw + cx0..row * cw + cx1] - .iter() - .map(|&v| v as u8), - ); - } - } - out -} - -/// Every picture ec-h265 outputs, as one yuv420p byte string, and the picture count. -fn decode_ec(annex_b: &[u8]) -> Result<(Vec, usize), String> { - let mut dec = Decoder::new(); - dec.decode_annex_b(annex_b).map_err(|e| e.to_string())?; - dec.flush().map_err(|e| e.to_string())?; - let mut out = Vec::new(); - let mut count = 0; - while let Some(frame) = dec.next_frame() { - out.extend(cropped_yuv(&frame)); - count += 1; - } - Ok((out, count)) -} - -/// Every picture ffmpeg outputs, as yuv420p. -fn decode_ffmpeg(path: &Path, out: &Path) -> Result, String> { - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(path) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(out) - .output() - .map_err(|e| e.to_string())?; - if !status.status.success() { - return Err(String::from_utf8_lossy(&status.stderr).to_string()); - } - std::fs::read(out).map_err(|e| e.to_string()) -} - -fn first_difference(a: &[u8], b: &[u8]) -> Option { - a.iter() - .zip(b) - .position(|(x, y)| x != y) - .or_else(|| (a.len() != b.len()).then(|| a.len().min(b.len()))) -} - -#[test] -fn dolby_vision_p8_base_layer_decodes_and_rpu_is_ignored() { - let dir = std::env::temp_dir().join(format!("ec-h265-dvp8-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("temp dir"); - - let clean = encode_base_layer(&dir).expect("libx265 base layer"); - let injected = inject_rpu(&clean); - let vcl = split_annex_b(&clean) - .iter() - .filter(|n| matches!((n.header.to_bytes()[0] >> 1) & 0x3f, 0..=21)) - .count(); - assert_eq!( - count_nal_type(&clean, 62), - 0, - "clean base layer has type 62 NAL units" - ); - assert_eq!( - count_nal_type(&injected, 62), - vcl, - "one type 62 NAL unit per slice" - ); - - let (ec_clean, n_clean) = decode_ec(&clean).expect("ec-h265 decodes the clean base layer"); - let (ec_injected, n_injected) = - decode_ec(&injected).expect("ec-h265 decodes the stream with type 62 NAL units"); - assert_eq!(n_clean, FRAMES, "clean stream picture count"); - assert_eq!(n_injected, FRAMES, "injected stream picture count"); - let frame_bytes = WIDTH * HEIGHT * 3 / 2; - assert_eq!(ec_clean.len(), FRAMES * frame_bytes); - if let Some(at) = first_difference(&ec_clean, &ec_injected) { - panic!("type 62 NAL units changed ec-h265's output at byte {at}"); - } - - let injected_path = dir.join("dv-p8.hevc"); - std::fs::write(&injected_path, &injected).expect("write injected stream"); - let ffmpeg = decode_ffmpeg(&injected_path, &dir.join("ffmpeg.yuv")) - .expect("ffmpeg decodes the injected stream"); - assert_eq!( - ffmpeg.len(), - ec_injected.len(), - "ffmpeg picture bytes differ from ec-h265's" - ); - if let Some(at) = first_difference(&ec_injected, &ffmpeg) { - panic!("ec-h265 and ffmpeg differ on the injected stream at byte {at}"); - } - - let _ = std::fs::remove_dir_all(&dir); -} diff --git a/crates/ec-h265/tests/it/encode.rs b/crates/ec-h265/tests/it/encode.rs deleted file mode 100644 index 6c4b2f51..00000000 --- a/crates/ec-h265/tests/it/encode.rs +++ /dev/null @@ -1,922 +0,0 @@ -//! Encoder rate-quality gate: BD-PSNR of this encoder against x265 at matched -//! features over a QP sweep, modelled on ec-h264's `bd_psnr_vs_x264`. -//! -//! Both encoders code the same synthetic 352x288 24-picture clip, both are read -//! the same way — on ffmpeg's decode of the stream, not on either encoder's -//! own reconstruction — and x265's psychovisual and adaptive tools are off so -//! the comparison is at matched features, not at matched marketing. - -use crate::common::{pin_loud, pin_or_bail}; -use ec_core::frame::VideoFrame; -use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip}; - -/// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed. -type Planes = (Vec, Vec, Vec); - -/// Floor for [`bd_psnr_vs_x265`] on the synthetic clip. Calibrated on the -/// measured value with 0.15 dB of room for platform noise, so the advantage can -/// shrink but not grow unnoticed; it is not a claim that the number is fine. -/// -/// Measured +2.507 dB luma / +3.238 dB YUV at `rdo_candidates: 5` (352x288, -/// 24 pictures of `Clip::render_smooth`, x265 at QP 22/26/30/34, our ladder -/// auto-shifted from a QP-26 probe to 16/20/24/28, both sides decoded through -/// ffmpeg, union-range BD-PSNR, 0% extrapolation both sides). This is a -/// smooth-gradient result: it does NOT hold on real content, where our -/// encoder is no leaner than x265 at matched QP (the probe measures a shift of -/// 0) and the aligned BD is negative. Real-clip numbers, 24 pictures after -/// 1500, ladders auto-aligned to 22/26/30/34, 0% extrapolation both sides: -/// • 3840x1608 film: -0.685 dB luma / -0.703 dB YUV -/// • 1138x640 web clip: -0.507 dB luma / -0.556 dB YUV -/// • 2560x1440 screen capture: -2.465 dB luma / -2.360 dB YUV -/// • 1080p phone clip: -0.366 dB luma / -0.387 dB YUV -/// Those two are the real gap to close; the synthetic number only guards -/// against regression on a clip whose content is pinned. -/// -/// Previous run measured -38.258 dB luma with both sides at QP 22/26/30/34; -/// that number was meaningless because the two curves' bitrate ranges did not -/// overlap (50% extrapolation on our side) — a fixed QP offset could not -/// bridge encoders whose relative leanness varies with content. The shallow -/// all-intra rate-quality slope is genuine content behaviour (x264 forced -/// all-intra shows the same shape); the fix is to auto-align the ladders from -/// a probe encode, not to change x265's rate control. -const BD_PSNR_VS_X265_FLOOR: f64 = 2.357; - -/// A synthetic source with real structure: smooth gradients, a band of -/// sinusoidal texture and a translating box, so prediction matters — the half -/// a rate-quality comparison is about. Ported verbatim from ec-h264's `Clip` -/// (minus the `view()` method this encoder's `encode_idr_planes` does not -/// need). -struct Clip { - w: usize, - h: usize, - y: Vec, - u: Vec, - v: Vec, -} - -impl Clip { - fn new(w: usize, h: usize) -> Clip { - Clip { - w, - h, - y: vec![0; w * h], - u: vec![0; w / 2 * h / 2], - v: vec![0; w / 2 * h / 2], - } - } - - /// Frame `t` without a per-sample noise field: smooth gradients, a band of - /// sinusoidal texture and a box translating by whole and sub-sample - /// amounts. Content where prediction matters, not where residual is - /// incompressible. - fn render_smooth(&mut self, t: usize) { - let (w, h) = (self.w, self.h); - let ft = t as f64; - for y in 0..h { - for x in 0..w { - let (fx, fy) = (x as f64, y as f64); - let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; - let texture = if y > h / 3 && y < 2 * h / 3 { - 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) - } else { - 0.0 - }; - let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); - let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; - let v = if inside { - 196.0 - texture * 0.5 - } else { - 40.0 + (ramp % 90.0).abs() + texture - }; - self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; - } - } - for y in 0..h / 2 { - for x in 0..w / 2 { - let (fx, fy) = (x as f64, y as f64); - self.u[y * (w / 2) + x] = - (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; - self.v[y * (w / 2) + x] = - (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; - } - } - } -} - -/// Crop and tightly pack the Y, Cb and Cr planes of a reconstruction. -fn planes_of(frame: &VideoFrame) -> Planes { - let (w, h) = (frame.width as usize, frame.height as usize); - let mut out = Vec::new(); - for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)] - .into_iter() - .enumerate() - { - let plane = &frame.planes[i]; - let mut buf = Vec::with_capacity(pw * ph); - for row in 0..ph { - buf.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); - } - out.push(buf); - } - let v = out.pop().unwrap(); - let u = out.pop().unwrap(); - let y = out.pop().unwrap(); - (y, u, v) -} - -/// Mean squared error between two equal-length planes. -fn plane_mse(a: &[u8], b: &[u8]) -> f64 { - a.iter() - .zip(b) - .map(|(&x, &y)| { - let d = f64::from(x) - f64::from(y); - d * d - }) - .sum::() - / a.len() as f64 -} - -/// PSNR over all three planes, pooled by sample count the way x265 reports it: -/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number -/// rewards an encoder for throwing chroma away, so any decision that can move -/// chroma bits is read here instead. -fn psnr_yuv(a: &Planes, b: &Planes) -> f64 { - let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); - let sse = - plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; - let mse = sse / (n_y + 2.0 * n_c); - if mse == 0.0 { - 99.0 - } else { - 10.0 * (255.0 * 255.0 / mse).log10() - } -} - -fn psnr(a: &[u8], b: &[u8]) -> f64 { - let mse: f64 = a - .iter() - .zip(b) - .map(|(&x, &y)| { - let d = f64::from(x) - f64::from(y); - d * d - }) - .sum::() - / a.len() as f64; - if mse == 0.0 { - 99.0 - } else { - 10.0 * (255.0 * 255.0 / mse).log10() - } -} - -#[allow(clippy::needless_range_loop)] -fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { - let mut a = [[0.0; 5]; 4]; - for i in 0..4 { - a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; - } - for col in 0..4 { - let mut pivot = col; - for row in col + 1..4 { - if a[row][col].abs() > a[pivot][col].abs() { - pivot = row; - } - } - a.swap(col, pivot); - let div = a[col][col]; - assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); - for j in col..5 { - a[col][j] /= div; - } - for row in 0..4 { - if row == col { - continue; - } - let f = a[row][col]; - for j in col..5 { - a[row][j] -= f * a[col][j]; - } - } - } - [a[0][4], a[1][4], a[2][4], a[3][4]] -} - -fn cubic_integral(c: [f64; 4], x: f64) -> f64 { - c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 -} - -/// BD-PSNR: average PSNR difference between two rate-quality curves over a -/// shared bitrate range. Modelled on ec-h264's `bd_psnr_delta`, with one -/// departure: the integration range is the *union* of the two curves' bitrate -/// extents, not their intersection. -/// -/// The h264 gate's encoders land in the same bitrate band at the same QP, so -/// the intersection is non-empty and the standard Bjøntegaard cubic integral -/// over it is well defined. Our h265 encoder's bitrate at matched QP can be -/// leaner or fatter than x265's depending on content, so the QP-ladder shift -/// is measured from a probe encode, not fixed — the union range is kept (not -/// clipped to the intersection) so the extrapolation share can be measured: -/// if either curve is extrapolated over more than 20% of the range, the test -/// fails with a named message instead of reporting a BD number that is a cubic -/// guess, not a measurement. The extrapolation shares are returned alongside -/// the number. -/// -/// Returns `(bd, cand_extrap, anc_extrap)` where the extrap shares are the -/// fraction of the integration range that each curve's measured bitrate span -/// does not cover (0 = fully measured, 1 = entirely extrapolated). -fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> (f64, f64, f64) { - let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); - let ys_candidate = std::array::from_fn(|i| candidate[i].1); - let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); - let ys_anchor = std::array::from_fn(|i| anchor[i].1); - // Union, not intersection: see the doc comment above. - let lo = xs_candidate - .iter() - .copied() - .fold(f64::INFINITY, f64::min) - .min(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); - let hi = xs_candidate - .iter() - .copied() - .fold(f64::NEG_INFINITY, f64::max) - .max(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); - let c_candidate = cubic_fit(xs_candidate, ys_candidate); - let c_anchor = cubic_fit(xs_anchor, ys_anchor); - let (cand_lo, cand_hi) = ( - xs_candidate.iter().copied().fold(f64::INFINITY, f64::min), - xs_candidate - .iter() - .copied() - .fold(f64::NEG_INFINITY, f64::max), - ); - let (anc_lo, anc_hi) = ( - xs_anchor.iter().copied().fold(f64::INFINITY, f64::min), - xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max), - ); - let cand_extrap = ((lo - cand_lo).max(0.0) + (hi - cand_hi).max(0.0)) / (cand_hi - cand_lo); - let anc_extrap = ((lo - anc_lo).max(0.0) + (hi - anc_hi).max(0.0)) / (anc_hi - anc_lo); - eprintln!( - " cubic extrapolation: candidate {cand_extrap:.0}% anchor {anc_extrap:.0}% of measured range" - ); - let bd = (cubic_integral(c_candidate, hi) - - cubic_integral(c_candidate, lo) - - cubic_integral(c_anchor, hi) - + cubic_integral(c_anchor, lo)) - / (hi - lo); - (bd, cand_extrap, anc_extrap) -} - -fn have_x265() -> bool { - ec_testkit::ffmpeg() - .args(["-v", "error", "-hide_banner", "-encoders"]) - .output() - .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265")) -} - -#[cfg(unix)] -#[test] -fn pin_loud_reds_on_an_ok_but_short_write() { - // The shape the two sites above left open: a write that reports success and - // leaves a file of a different length. A symlink to /dev/null accepts every - // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes -- - // a stream path, silently empty. - let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let path = dir.join("ok-but-short.265"); - let _ = std::fs::remove_file(&path); - std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null"); - let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err(); - assert!(why.contains(&path.display().to_string()), "{why}"); - assert!(why.contains("file holds 0 of 1234 bytes"), "{why}"); - std::fs::remove_file(&path).ok(); - - // The control: the same call on a real file succeeds and leaves every byte. - let good = dir.join("whole.265"); - let bytes = vec![7u8; 1234]; - pin_loud("control", &good, &bytes).expect("a whole write is not short"); - assert_eq!(std::fs::read(&good).expect("read back"), bytes); - std::fs::remove_file(&good).ok(); - std::fs::remove_dir_all(&dir).ok(); -} - -#[cfg(unix)] -#[test] -fn pin_loud_reports_what_landed_under_a_size_cap() { - // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores - // everything up to the cap and only then returns EFBIG. The line must carry - // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count - // the writer confirmed, which is zero. - use std::process::Command; - let Ok(exe) = std::env::current_exe() else { - return; - }; - // SIGXFSZ's default action would kill the child before it can print; - // `trap '' XFSZ` sets SIG_IGN, which survives the exec. - let script = format!( - "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture", - exe.display() - ); - let out = Command::new("sh") - .args(["-c", &script]) - .env("EC_PINLOUD_CHILD", "1") - .output() - .expect("run the capped child"); - let text = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - assert!(!out.status.success(), "the capped write must fail: {text}"); - assert!(text.contains("file holds 512 of 4096 bytes"), "{text}"); - assert!( - text.contains("EFBIG") || text.contains("File too large"), - "{text}" - ); -} - -/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under -/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails -/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`. -#[test] -fn pin_loud_cap_child() { - if std::env::var_os("EC_PINLOUD_CHILD").is_none() { - return; - } - let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-cap-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let path = dir.join("capped.265"); - let why = - pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap"); - std::fs::remove_file(&path).ok(); - std::fs::remove_dir_all(&dir).ok(); - panic!("{why}"); -} - -/// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture. -fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option> { - let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id())); - std::fs::create_dir_all(&dir).ok()?; - let path = dir.join(format!("s{}.265", stream.len())); - pin_or_bail("ffmpeg_decode", &path, stream)?; - let out = ec_testkit::ffmpeg() - .args(["-v", "error"]) - .arg("-i") - .arg(&path) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]) - .output() - .ok()?; - let _ = std::fs::remove_file(&path); - if !out.status.success() { - eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); - return None; - } - let frame = w * h * 3 / 2; - if frame == 0 || out.stdout.len() % frame != 0 { - eprintln!( - "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", - out.stdout.len() - ); - return None; - } - Some( - out.stdout - .chunks(frame) - .map(|f| { - let (y, rest) = f.split_at(w * h); - let (u, v) = rest.split_at(w / 2 * h / 2); - (y.to_vec(), u.to_vec(), v.to_vec()) - }) - .collect(), - ) -} - -/// Encode raw I420 pictures with x265 at constant QP, matched to what this -/// encoder actually does: intra-only (keyint 1), no B pictures, no scene cut -/// or lookahead, in-loop filters (SAO, deblock) off, adaptive quantisation off, -/// psychovisual RD and RDOQ off, RDOQ itself off, the shallowest intra TU -/// depth x265 allows (1, the closest it has to our -/// `max_transform_hierarchy_depth_intra=0`), and ipratio/pbratio/qcomp 1.0 so -/// constant-QP codes I pictures at the QP asked for. Returns the Annex-B -/// stream. -fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option> { - let dir = std::env::temp_dir().join(format!("ec-h265-x265-{}", std::process::id())); - std::fs::create_dir_all(&dir).ok()?; - let raw = dir.join(format!("in-q{qp}.yuv")); - let out = dir.join(format!("out-q{qp}.265")); - let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); - for (y, u, v) in sources { - buf.extend_from_slice(y); - buf.extend_from_slice(u); - buf.extend_from_slice(v); - } - pin_or_bail("x265_encode_qp", &raw, &buf)?; - // The param list is the h264 gate's x264 list translated to x265's option - // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off, - // plus the in-loop filters x265 adds and x264 does not have (no-sao, - // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits - // the same way ours does. The quantiser goes inside the param string as - // `qp=N`; `-x265-params qp=22` and `-x265-params rc=cqp:qp=22` produce - // byte-identical streams, so the `rc=cqp:` prefix is unnecessary. - // EC_H265_X265_PARAMS appends to attribute a single feature the same way - // EC_H264_X264_PARAMS does. - let params = format!( - "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:{deblock}\ - aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\ - pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{extra}", - // x265 deblocks by default; `no-deblock` matches an encoder that does - // not, and EC_H265_X265_DEBLOCK=1 drops it so both sides filter. - deblock = if std::env::var("EC_H265_X265_DEBLOCK").is_ok_and(|v| v != "0") { - "" - } else { - "no-deblock:" - }, - extra = match std::env::var("EC_H265_X265_PARAMS") { - Ok(extra) if !extra.trim().trim_matches(':').is_empty() => - format!(":{}", extra.trim().trim_matches(':')), - _ => String::new(), - } - ); - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y"]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "1"]) - .arg("-i") - .arg(&raw) - .args(["-c:v", "libx265", "-preset", "medium"]) - .args(["-x265-params", ¶ms]) - .args(["-f", "hevc"]) - .arg(&out) - .status() - .ok()?; - let _ = std::fs::remove_file(&raw); - if !status.success() { - return None; - } - let stream = std::fs::read(&out).ok(); - let _ = std::fs::remove_file(&out); - stream -} - -/// BD-PSNR of this encoder against x265 at matched features. x265 is anchored -/// at QP 22/26/30/34; our ladder is shifted by a QP delta measured from a -/// probe encode at QP 26 (both sides), so the bitrate ranges overlap and the -/// cubic fit interpolates instead of extrapolating — regardless of whether -/// our encoder is leaner or fatter than x265 at matched QP on the content at -/// hand. Runs on the synthetic clip by default, so the number cannot rot -/// behind an `#[ignore]`; point `EC_H265_CLIP` at a media file to measure the -/// same thing on real content. -/// -/// Both curves are (bits, luma PSNR against the same source pictures), and -/// both are measured on ffmpeg's decode of the stream rather than on an -/// encoder's own reconstruction, so the two halves are read the same way. -/// BD-PSNR-YUV pools all three planes by sample count (luma weighted 6, each -/// chroma 1 for 4:2:0), the way x265 reports it. -/// -/// cargo test --release -p ec-h265 --test encode bd_psnr_vs_x265 -- --nocapture -/// EC_H265_CLIP= cargo test --release -p ec-h265 --test encode \ -/// bd_psnr_vs_x265 -- --nocapture -#[test] -fn bd_psnr_vs_x265() { - assert!(have_x265(), "the pinned ffmpeg has no libx265"); - let (w, h, sources) = match std::env::var_os("EC_H265_CLIP") { - Some(path) => clip_sources(&path, 24), - None => { - let (w, h, frames) = (352, 288, 24); - let mut clip = Clip::new(w, h); - let mut sources = Vec::with_capacity(frames); - for t in 0..frames { - clip.render_smooth(t); - sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); - } - eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); - (w, h, sources) - } - }; - - let ours = |qp: i32| { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.threads = 0; - // Ablation knob: how many SATD survivors reach the full rate-distortion - // trial in the luma mode search. The shipped default is 5. - if let Ok(v) = std::env::var("EC_H265_CHROMA_RD") { - cfg.chroma_mode_search = v != "0"; - } - if let Ok(w) = std::env::var("EC_H265_CHROMA_W") { - cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number"); - } - if let Ok(v) = std::env::var("EC_H265_SDH") { - cfg.sign_hiding = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_RDOQ") { - cfg.rdoq = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_RDOQ_ESTIMATE") { - cfg.rdoq_estimate = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_TSKIP") { - cfg.transform_skip = match v.as_str() { - "0" => TransformSkip::Off, - "always" => TransformSkip::AlwaysFor4x4, - _ => TransformSkip::Rd, - }; - } - if let Ok(v) = std::env::var("EC_H265_NXN") { - cfg.intra_nxn = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_CTB") { - cfg.ctb_size = v.parse().expect("EC_H265_CTB must be 32 or 64"); - } - if let Ok(v) = std::env::var("EC_H265_CU64") { - cfg.cu64 = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_DEBLOCK") { - cfg.deblock = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_RQT") { - cfg.rqt = v != "0"; - } - if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") { - cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number"); - } - let enc = Encoder::new(cfg).expect("encoder"); - let (mut stream, mut sum_recon) = (Vec::new(), 0.0); - for (y, u, v) in &sources { - let coded = enc - .encode_idr_planes(y, w, u, w / 2, v, w / 2) - .expect("encode"); - stream.extend_from_slice(&coded.au); - let recon = coded.recon.as_ref().expect("reconstruction"); - let (ry, _ru, _rv) = planes_of(recon); - sum_recon += psnr(y, &ry); - } - // Measured the same way x265 is: on what a decoder shows, not on the - // encoder's own reconstruction. The two are printed together because a - // gap between them is a bug in one of the halves, not a rate-quality - // result. - let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes our stream"); - assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); - let n = sources.len() as f64; - let sum: f64 = sources - .iter() - .zip(&decoded) - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) - .sum(); - let sum_yuv: f64 = sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr_yuv(s, d)) - .sum(); - let (sum_u, sum_v) = ( - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.1, &d.1)) - .sum::(), - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.2, &d.2)) - .sum::(), - ); - eprintln!( - " ours qp {qp}: u {:.2} dB v {:.2} dB", - sum_u / n, - sum_v / n - ); - let (decoded_psnr, recon_psnr) = (sum / n, sum_recon / n); - assert!( - (decoded_psnr - recon_psnr).abs() < 0.05, - "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ - stream decodes to {decoded_psnr:.2} dB" - ); - ((stream.len() * 8) as f64, decoded_psnr, sum_yuv / n) - }; - let x265 = |qp: i32| { - let stream = x265_encode_qp(&sources, w, h, qp).expect("x265 encodes"); - let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes x265's own stream"); - assert_eq!( - decoded.len(), - sources.len(), - "x265 returned {} pictures for {} sources", - decoded.len(), - sources.len() - ); - let n = sources.len() as f64; - let sum: f64 = sources - .iter() - .zip(&decoded) - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) - .sum(); - let sum_yuv: f64 = sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr_yuv(s, d)) - .sum(); - eprintln!( - " x265 qp {qp}: u {:.2} dB v {:.2} dB", - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.1, &d.1)) - .sum::() - / n, - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.2, &d.2)) - .sum::() - / n - ); - ((stream.len() * 8) as f64, sum / n, sum_yuv / n) - }; - - // x265 stays anchored at QP 22/26/30/34. Our ladder is shifted by a QP - // delta measured from a single probe encode, not a constant: both sides - // are encoded at QP 26, the bit ratio is converted to a QP shift (≈6 QP - // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that - // shift. If the extrapolation share still exceeds 20% after measuring, the - // shift is re-estimated from the geometric-mean bit ratio of the two full - // curves and the ladder is rebuilt; once the rates match and the curves - // still do not meet, our ladder is drawn in towards its own centre until - // its bitrate range fits inside the anchor's — at most 8 alignment rounds - // before the existing panic fires. - const EXTRAP_LIMIT: f64 = 0.20; - let x265_qps = [22, 26, 30, 34]; - let probe_qp = 26; - - // Probe both encoders at QP 26 to measure the bit ratio. - let probe_ours = ours(probe_qp); - let probe_x265 = x265(probe_qp); - // A sample window with nothing in it (a film's black head, a fade) codes - // to a handful of bits and decodes back to the source exactly, so every - // point on both curves sits at the PSNR cap and the BD number is a flat - // +0.000 that looks like a measurement. Refuse it by name. - const FLAT_WINDOW_DB: f64 = 90.0; - assert!( - probe_x265.1 < FLAT_WINDOW_DB && probe_ours.1 < FLAT_WINDOW_DB, - "the sample window is flat — both encoders reach the PSNR cap on it \ - (ours {:.2} dB, x265 {:.2} dB at qp {probe_qp}); this is a black head \ - or a fade, not content: pass EC_H265_CLIP_SKIP to sample past it", - probe_ours.1, - probe_x265.1, - ); - let mut shift = (6.0 * (probe_ours.0 / probe_x265.0).log2()).round() as i32; - eprintln!( - "ladder shift {shift:+} (probe q{probe_qp}: ours {:.1} Mbit vs x265 {:.1} Mbit)", - probe_ours.0 / 1e6, - probe_x265.0 / 1e6, - ); - - let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { - v.iter() - .map(|&(b, p, y)| (b, if luma { p } else { y })) - .collect() - }; - - // x265 ladder is fixed; reuse the probe for its QP-26 point. - let theirs: Vec<(f64, f64, f64)> = x265_qps - .iter() - .map(|&q| if q == probe_qp { probe_x265 } else { x265(q) }) - .collect(); - - let gm = |v: &[(f64, f64, f64)]| (v[0].0 * v[1].0 * v[2].0 * v[3].0).powf(0.25); - let qps_str = |qs: &[i32; 4]| { - qs.iter() - .map(|q| q.to_string()) - .collect::>() - .join("/") - }; - - #[allow(unused_assignments)] - let ( - mut bd, - mut bd_yuv, - mut cand_extrap, - mut anc_extrap, - mut cand_extrap_yuv, - mut anc_extrap_yuv, - ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0); - let mut mine: Vec<(f64, f64, f64)>; - let mut our_qps: [i32; 4]; - // How wide our QP ladder is against the anchor's, as a fraction of its - // spacing: one encoder can answer a QP step with far more bitrate than the - // other, and a BD number needs both curves over the same range. - let mut spread = 1.0_f64; - - for round in 0..=8u32 { - our_qps = x265_qps.map(|q| { - let centre = f64::from(probe_qp + shift); - let offset = f64::from(q - probe_qp) * spread; - ((centre + offset).round() as i32).clamp(1, 45) - }); - let mut distinct = our_qps; - distinct.sort_unstable(); - let collapsed = distinct.windows(2).any(|w| w[0] == w[1]); - assert!( - !collapsed, - "our QP ladder collapsed to {:?}: the shift has pushed it into the \ - qp floor, so two points share an x and the cubic has no unique fit", - our_qps, - ); - mine = our_qps - .iter() - .map(|&q| if q == probe_qp { probe_ours } else { ours(q) }) - .collect(); - for (i, &qp) in our_qps.iter().enumerate() { - let (ob, op, oy) = mine[i]; - eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)"); - } - for (i, &qp) in x265_qps.iter().enumerate() { - let (xb, xp, xy) = theirs[i]; - eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)"); - } - (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); - (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) = - bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); - eprintln!( - "BD-PSNR ours (q{}) vs x265 (q{}): {bd:+.3} dB", - qps_str(&our_qps), - qps_str(&x265_qps), - ); - eprintln!( - "BD-PSNR-YUV ours (q{}) vs x265 (q{}): {bd_yuv:+.3} dB", - qps_str(&our_qps), - qps_str(&x265_qps), - ); - let aligned = cand_extrap <= EXTRAP_LIMIT - && anc_extrap <= EXTRAP_LIMIT - && cand_extrap_yuv <= EXTRAP_LIMIT - && anc_extrap_yuv <= EXTRAP_LIMIT; - if aligned || round == 8 { - break; - } - // Re-estimate the shift from the geometric-mean bit ratio of the two - // full curves, then rebuild the ladder. A single-QP correction is - // ignored: it is within the rounding of the estimate and only makes the - // ladder oscillate between two neighbouring shifts. - let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32; - if delta.abs() > 1 { - shift += delta; - eprintln!( - "alignment round {}: shift {delta:+} -> {shift:+} \ - (gm ours {:.1} Mbit vs x265 {:.1} Mbit)", - round + 1, - gm(&mine) / 1e6, - gm(&theirs) / 1e6, - ); - continue; - } - // The rates match and the curves still do not overlap, so our ladder - // spans a much wider bitrate range than the anchor's: their union is - // then mostly outside what x265 measured and the cubic through its four - // points extrapolates over most of it. Draw our ladder in. - spread *= 0.5; - eprintln!( - "alignment round {}: ladder spread -> {spread:.2} of the anchor's", - round + 1 - ); - } - - // A BD number over a range where the two QP ladders do not overlap is not a - // measurement — the cubic is extrapolating, not interpolating. Fail loudly - // with the side that is out of range instead of reporting a meaningless gap. - let out_of_range = |c: f64, a: f64| { - let mut parts = Vec::new(); - if c > EXTRAP_LIMIT { - parts.push(format!("ours {:.0}%", c * 100.0)); - } - if a > EXTRAP_LIMIT { - parts.push(format!("x265 {:.0}%", a * 100.0)); - } - parts - }; - let luma_oor = out_of_range(cand_extrap, anc_extrap); - let yuv_oor = out_of_range(cand_extrap_yuv, anc_extrap_yuv); - if !luma_oor.is_empty() { - panic!( - "BD-PSNR luma: the two QP ladders do not overlap — {} of the \ - integration range is extrapolated (limit {:.0}%); widen the QP \ - sweep until the curves meet", - luma_oor.join(", "), - EXTRAP_LIMIT * 100.0 - ); - } - if !yuv_oor.is_empty() { - panic!( - "BD-PSNR-YUV: the two QP ladders do not overlap — {} of the \ - integration range is extrapolated (limit {:.0}%); widen the QP \ - sweep until the curves meet", - yuv_oor.join(", "), - EXTRAP_LIMIT * 100.0 - ); - } - - // The floor is calibrated on the synthetic clip; a clip of the user's is a - // measurement, not a gate, because its content is not pinned. - if std::env::var_os("EC_H265_CLIP").is_none() { - assert!( - bd > BD_PSNR_VS_X265_FLOOR, - "BD-PSNR against x265 fell to {bd:+.3} dB, past the \ - {BD_PSNR_VS_X265_FLOOR:+.3} dB floor" - ); - } -} - -/// Decode `want` pictures from a media file as tightly packed I420 triples. -/// `EC_H265_CLIP_SKIP` passes over that many pictures before sampling (film -/// heads are titles and fades). -fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec) { - let dims = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "v:0", - "-show_entries", - "stream=width,height", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .expect("ffprobe"); - assert!( - dims.status.success(), - "ffprobe failed: {}", - String::from_utf8_lossy(&dims.stderr) - ); - let csv = String::from_utf8_lossy(&dims.stdout); - // ffprobe prints one comma-separated line per stream, and recent builds - // end it with a trailing separator, so the fields are taken by position - // rather than by splitting the line in two. - let mut fields = csv.lines().next().unwrap_or_default().split(','); - let (w, h) = (|| { - Some(( - fields.next()?.trim().parse::().ok()?, - fields.next()?.trim().parse::().ok()?, - )) - })() - .unwrap_or_else(|| panic!("ffprobe returned dimensions, got {csv:?}")); - // Pictures to pass over before sampling: the head of a film is titles and - // fades, which are not what a codec is measured on. - let skip: usize = std::env::var("EC_H265_CLIP_SKIP") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(0); - // Trim on ffmpeg's side, not ours. Asking for the whole file and slicing - // afterwards buffers the entire decoded clip in memory: a 1080p feature is - // hundreds of gigabytes of raw I420, which the kernel answers with the OOM - // killer. `select` drops the skipped pictures inside ffmpeg and - // `-frames:v` stops the decode once `want` have come out, so what reaches - // this process is exactly `want` frames. - let raw = ec_testkit::ffmpeg() - .args(["-v", "error", "-i"]) - .arg(path) - .args([ - "-vf", - &format!("select=gte(n\\,{skip})"), - "-fps_mode", - "passthrough", - "-frames:v", - &want.to_string(), - "-f", - "rawvideo", - "-pix_fmt", - "yuv420p", - "pipe:1", - ]) - .output() - .expect("ffmpeg raw extract"); - assert!( - raw.status.success(), - "ffmpeg failed: {}", - String::from_utf8_lossy(&raw.stderr) - ); - let frame = w * h * 3 / 2; - assert!( - raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want, - "clip {} yielded {} bytes after skipping {skip}, need {want}x{frame}", - path.to_string_lossy(), - raw.stdout.len() - ); - let sources: Vec = raw - .stdout - .chunks(frame) - .take(want) - .map(|f| { - let (y, rest) = f.split_at(w * h); - let (u, v) = rest.split_at(w / 2 * h / 2); - (y.to_vec(), u.to_vec(), v.to_vec()) - }) - .collect(); - eprintln!( - "{}: {}x{}, {} pictures (skipped {skip})", - path.to_string_lossy(), - w, - h, - sources.len() - ); - (w, h, sources) -} diff --git a/crates/ec-h265/tests/it/encode_threads.rs b/crates/ec-h265/tests/it/encode_threads.rs index 8624d39b..d2a5bf24 100644 --- a/crates/ec-h265/tests/it/encode_threads.rs +++ b/crates/ec-h265/tests/it/encode_threads.rs @@ -183,7 +183,8 @@ fn end_picture_outputs_each_access_unit_cropped() { cfg.keyint = 4; cfg.keep_recon = true; cfg.threads = 1; - let mut seq = ec_h265::SequenceEncoder::new(Encoder::new(cfg).expect("encoder")).expect("sequence"); + let mut seq = + ec_h265::SequenceEncoder::new(Encoder::new(cfg).expect("encoder")).expect("sequence"); let mut dec = Decoder::new(); for f in &frames { let pic = seq.encode(f, false).expect("encode"); @@ -193,6 +194,9 @@ fn end_picture_outputs_each_access_unit_cropped() { assert_eq!((out.width, out.height), (200, 120)); let recon = pic.recon.expect("recon"); let y: Vec = out.y.iter().map(|&v| v as u8).collect(); - assert!(*y == *recon.planes[0].data, "cropped luma differs from the reconstruction"); + assert!( + *y == *recon.planes[0].data, + "cropped luma differs from the reconstruction" + ); } } diff --git a/crates/ec-h265/tests/it/main.rs b/crates/ec-h265/tests/it/main.rs index 08bba744..79a6dce7 100644 --- a/crates/ec-h265/tests/it/main.rs +++ b/crates/ec-h265/tests/it/main.rs @@ -5,23 +5,10 @@ #![forbid(unsafe_code)] mod common; -mod conformance; -mod conformance_intra; -mod conformance_rext; -mod conformance_rext422; -mod cu_syntax; -mod dec_meta; -mod dec_shell; mod decode; -mod dolby_vision_p8; mod enc8_bitstream_hash; -mod encode; mod encode_threads; mod fuzz_regressions; mod main10; -mod rate_control; -mod rdoq_cache_hash; -mod real_library; mod refusals; mod rext_generated; -mod scaling_lists; diff --git a/crates/ec-h265/tests/it/rate_control.rs b/crates/ec-h265/tests/it/rate_control.rs deleted file mode 100644 index 33891ff1..00000000 --- a/crates/ec-h265/tests/it/rate_control.rs +++ /dev/null @@ -1,207 +0,0 @@ -//! Bitrate control of the sequence encoder: a clip coded at a target lands within -//! 5% of that target, and the output does not depend on the worker count. -//! -//! The clip is a textured pattern that moves a few samples per picture, so the -//! pictures differ in cost and the model has to follow them. The 5% bound is the -//! same one the 60 s measurement is held to (`scripts/hevc-rc.sh`). - -use ec_core::frame::{PixelFormat, Plane, VideoFrame}; -use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl}; - -const W: usize = 320; -const H: usize = 240; -const FPS: f64 = 30.0; -const FRAMES: usize = 150; -const KEYINT: usize = 30; - -fn moving_clip(frames: usize) -> Vec { - let (cw, ch) = (W / 2, H / 2); - (0..frames) - .map(|t| { - let mut y = vec![0u8; W * H]; - for r in 0..H { - for c in 0..W { - let (x, yy) = (c + 3 * t, r + t); - let mut v = (x * 7 + yy * 5) as u32; - v ^= (x as u32).wrapping_mul(0x9e37) ^ (yy as u32).wrapping_mul(0x85eb); - y[r * W + c] = (v.wrapping_mul(2_654_435_761) >> 24) as u8; - } - } - let chroma = |scale: usize| -> Vec { - (0..cw * ch) - .map(|i| { - let (c, r) = (i % cw, i / cw); - ((c * scale + r * 3 + t * 2) % 251) as u8 - }) - .collect() - }; - VideoFrame::try_new( - PixelFormat::I420, - W as u32, - H as u32, - vec![ - Plane::new(y, W), - Plane::new(chroma(5), cw), - Plane::new(chroma(9), cw), - ], - ) - .expect("I420 planes at the stated size") - }) - .collect() -} - -/// Encode the clip at `kbps` with `threads` workers; returns the stream bytes. -fn encode_at(frames: &[VideoFrame], kbps: u32, threads: usize) -> Vec { - let mut cfg = EncoderConfig::new(W as u32, H as u32); - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; - cfg.keyint = KEYINT; - cfg.threads = threads; - let enc = Encoder::new(cfg).expect("encoder"); - let coded = enc.encode_sequence(frames).expect("encode"); - coded.iter().flat_map(|p| p.au.iter().copied()).collect() -} - -#[test] -fn bitrate_lands_within_five_percent_of_each_target() { - let frames = moving_clip(FRAMES); - for kbps in [1000u32, 2500, 5000] { - let stream = encode_at(&frames, kbps, 1); - let seconds = FRAMES as f64 / FPS; - let achieved = stream.len() as f64 * 8.0 / seconds / 1000.0; - let error = (achieved - f64::from(kbps)) / f64::from(kbps); - eprintln!( - "target {kbps} kbps: achieved {achieved:.1} kbps ({:+.2}%)", - error * 100.0 - ); - assert!( - error.abs() <= 0.05, - "target {kbps} kbps: achieved {achieved:.1} kbps is {:+.2}% off", - error * 100.0 - ); - } -} - -/// A flat picture at `luma` (chroma at 128): nothing in it costs more than a skipped block -/// at any QP, so it is the case where the rate cannot be spent. -fn flat_clip(frames: usize, luma: u8) -> Vec { - let (cw, ch) = (W / 2, H / 2); - (0..frames) - .map(|_| { - VideoFrame::try_new( - PixelFormat::I420, - W as u32, - H as u32, - vec![ - Plane::new(vec![luma; W * H], W), - Plane::new(vec![128; cw * ch], cw), - Plane::new(vec![128; cw * ch], cw), - ], - ) - .expect("I420 planes at the stated size") - }) - .collect() -} - -/// A flat clip at 2000 kbps cannot spend its budget even at QP 0, so the rate model must -/// walk the quantiser down to the HEVC floor and hold it there, rather than stall high. -/// The floor is the codec's, not a rate floor of this encoder: whatever bits remain are the -/// content's own cost at QP 0. -#[test] -fn flat_near_black_descends_to_the_qp_floor() { - let frames = flat_clip(60, 16); - let pics: Vec = encode_pictures(&frames, 2000); - // The first predicted pictures walk the quantiser down from the IDR's QP (at most four - // steps each); from picture 10 on, every predicted picture must sit at QP 0. - let tail: Vec<(usize, i32)> = pics - .iter() - .enumerate() - .filter(|(i, _)| i % KEYINT != 0 && *i >= 10) - .map(|(i, p)| (i, p.qp)) - .collect(); - assert!(!tail.is_empty()); - let stalled: Vec<&(usize, i32)> = tail.iter().filter(|(_, qp)| *qp != 0).collect(); - assert!( - stalled.is_empty(), - "QP did not reach the floor: {stalled:?}" - ); -} - -/// Encode `frames` at `kbps` and return the coded pictures, so the test can see each QP. -fn encode_pictures(frames: &[VideoFrame], kbps: u32) -> Vec { - let mut cfg = EncoderConfig::new(W as u32, H as u32); - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; - cfg.keyint = KEYINT; - cfg.threads = 1; - Encoder::new(cfg) - .expect("encoder") - .encode_sequence(frames) - .expect("encode") -} - -#[test] -fn bitrate_output_is_identical_at_any_thread_count() { - let frames = moving_clip(FRAMES); - let one = encode_at(&frames, 2500, 1); - for threads in [2usize, 4] { - assert!( - encode_at(&frames, 2500, threads) == one, - "stream differs at {threads} threads" - ); - } -} - -/// Near-black with temporal noise at 720p: luma 16 plus a deterministic PRNG offset of -2..=2 -/// that differs every picture. Cost against QP is a cliff here (a few hundred bytes per -/// picture above QP ~17, tens of kilobytes a few steps below), so the `2^(QP/6)` model alone -/// dives into the cliff after a run of cheap pictures and the stream overshoots. The cliff -/// only shows at this size, which is why this clip is not 320x240. -fn noisy_black_clip(frames: usize, w: usize, h: usize) -> Vec { - let (cw, ch) = (w / 2, h / 2); - let mut state = 0x2545_f491_4f6c_dd1du64; - let mut next = move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - (state >> 33) as u32 - }; - (0..frames) - .map(|_| { - let y: Vec = (0..w * h).map(|_| (14 + next() % 5) as u8).collect(); - VideoFrame::try_new( - PixelFormat::I420, - w as u32, - h as u32, - vec![ - Plane::new(y, w), - Plane::new(vec![128; cw * ch], cw), - Plane::new(vec![128; cw * ch], cw), - ], - ) - .expect("I420 planes at the stated size") - }) - .collect() -} - -#[test] -fn noisy_near_black_lands_within_five_percent() { - let (w, h, frames) = (1280usize, 720usize, noisy_black_clip(90, 1280, 720)); - for kbps in [500u32, 2000] { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; - cfg.keyint = KEYINT; - cfg.threads = 1; - let pics = Encoder::new(cfg) - .expect("encoder") - .encode_sequence(&frames) - .expect("encode"); - let bytes: usize = pics.iter().map(|p| p.au.len()).sum(); - let achieved = bytes as f64 * 8.0 / (frames.len() as f64 / FPS) / 1000.0; - let error = (achieved - f64::from(kbps)) / f64::from(kbps); - eprintln!("target {kbps}: {achieved:.1} kbps ({:+.2}%)", error * 100.0); - assert!( - error.abs() <= 0.05, - "target {kbps} kbps: achieved {achieved:.1} kbps is {:+.2}% off", - error * 100.0 - ); - } -} diff --git a/crates/ec-h265/tests/it/rdoq_cache_hash.rs b/crates/ec-h265/tests/it/rdoq_cache_hash.rs deleted file mode 100644 index 9d47af33..00000000 --- a/crates/ec-h265/tests/it/rdoq_cache_hash.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! lane-h265rdoq r3: the sub-block frozen-prefix cursor must not change a -//! single output byte. Hashes two natural-content encodes (1920x1080 and -//! 416x240) with FNV-1a; the number itself means nothing, only that it is the -//! same before and after this round's change to `rdoq()` (checked by hand: -//! stash `residual.rs`, rerun, compare). - -use crate::common::{fnv1a, natural_frame}; -use ec_h265::encoder::{Encoder, EncoderConfig, RateControl}; - -fn encode_hash(width: u32, height: u32) -> u64 { - let mut cfg = EncoderConfig::new(width, height); - cfg.rate_control = RateControl::ConstantQp(24); - cfg.threads = 1; - let encoder = Encoder::new(cfg).expect("encoder"); - let mut all = Vec::new(); - for i in 0..3u32 { - let frame = natural_frame(width, height, i * 5); - all.extend(encoder.encode_idr(&frame).expect("encode").au); - } - fnv1a(&all) -} - -#[test] -fn rdoq_cache_hash_1920x1080() { - println!("hash 1920x1080 = {:016x}", encode_hash(1920, 1080)); -} - -#[test] -fn rdoq_cache_hash_416x240() { - println!("hash 416x240 = {:016x}", encode_hash(416, 240)); -} - -/// lane-h265simd: pinned bit-identity gate for the transform's hot path. The -/// value is the same hash the two tests above print, verified by hand -/// (`git stash` the transform.rs change, rerun, compare) to be identical -/// before and after replacing `m32()`'s per-element branch with a -/// compile-time-mirrored flat table in `forward_1d`/`inverse_1d` — this pins -/// that equality so a future change to the hot path is caught if it ever -/// produces a different byte. -/// -/// lane-h265prune: re-pinned after the RQT split trial gained an all-zero-CBF -/// early out (mirrors the CU-quadtree's existing `last_cu_empty` skip one -/// level down at the transform tree): a coding unit whose luma+chroma already -/// quantised to nothing is committed as one leaf transform unit without -/// trying the four-child split first, since splitting a zero-SSD block can -/// only add split_transform_flag and mode-signalling bits. This changes the -/// bitstream on any content where that trial used to flip a leaf to split -/// (BD-gated, not bit-identical — see `EncoderConfig::rqt` and this crate's -/// `bd_psnr_vs_x265`). -/// -/// lane-h265rdoq: re-pinned after RDOQ's trial costing switched from exact -/// per-trial CABAC replay to an estimated per-context fracbits table -/// (`EncoderConfig::rdoq_estimate`, now on by default) — deliberately -/// bit-different, not exact-mode-preserving; see that field's doc comment -/// for the BD/speed numbers that justified flipping the default. -/// -/// lane-h265screen: re-pinned after every committed 4x4 luma block gained a -/// rate-distortion decision on `transform_skip_flag` (`TransformSkip::Rd`, now -/// the default) — deliberately bit-different; see that field's doc comment for -/// the BD numbers per clip. -/// -/// lane-hevcenctools: re-pinned after the sequence parameter set's -/// `sps_temporal_mvp_enabled_flag` went on, which the P pictures' slice headers -/// need. That is one SPS bit; the intra slices are otherwise unchanged, and the -/// 9203-picture conformance check still matches. -#[test] -fn rdoq_cache_hash_is_pinned() { - assert_eq!(encode_hash(416, 240), 0xd501713b57091906); - assert_eq!(encode_hash(1920, 1080), 0x5eb50f5a747ca1c2); -} diff --git a/crates/ec-h265/tests/it/real_library.rs b/crates/ec-h265/tests/it/real_library.rs deleted file mode 100644 index a2ca81bc..00000000 --- a/crates/ec-h265/tests/it/real_library.rs +++ /dev/null @@ -1,367 +0,0 @@ -//! Every file either decodes bit-exactly, is refused by name (a pixel format or -//! a bit depth outside 4:2:0 8/10-bit, or a decoder refusal that says -//! "unsupported"), or fails. A refusal is reported, not counted as a failure. - -use std::io::Read; -use std::path::{Path, PathBuf}; -use std::process::Stdio; - -use ec_h265::dec::Decoder; -use ec_h265::decode::DecodedPicture; -use ec_h265_syntax::{ConformanceWindow, split_annex_b}; - -/// Pictures compared per file. -const FRAMES: usize = 300; - -/// Pixel formats inside the decoder's scope: 4:2:0 at 8 or 10 bits. -const IN_SCOPE_PIX_FMTS: [&str; 2] = ["yuv420p", "yuv420p10le"]; - -fn scratch(tag: &str) -> PathBuf { - let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from); - let dir = base.join(format!("ec-h265-{tag}-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - dir -} - -/// One manifest row: the columns the sweep reads. -struct Entry { - path: PathBuf, - container: String, - width: String, - height: String, - pix_fmt: String, -} - -fn hevc_entries() -> Vec { - [ - ( - "derived/sintel720-x265-main10.mp4", - "yuv420p10le", - "1280", - "720", - ), - ("open/sintel_trailer-1080p.mp4", "yuv420p", "1920", "1080"), - ] - .into_iter() - .map(|(rel, pix_fmt, width, height)| Entry { - path: ec_testkit::fixture(rel), - container: "mp4".to_string(), - width: width.to_string(), - height: height.to_string(), - pix_fmt: pix_fmt.to_string(), - }) - .collect() -} - -/// The samples of a picture cropped to its conformance window, as the bytes of a -/// planar rawvideo frame: one byte per sample at 8 bits, little-endian u16 above. -fn cropped(pic: &DecodedPicture, win: &ConformanceWindow, bps: usize) -> Vec { - let (l, r, t, b) = ( - win.left as usize, - win.right as usize, - win.top as usize, - win.bottom as usize, - ); - let (w, h) = (pic.width, pic.height); - // Conformance offsets are in chroma units for 4:2:0: luma is twice as large. - let planes = [ - ( - &pic.y, - w, - h, - 2 * l, - w.saturating_sub(2 * r), - 2 * t, - h.saturating_sub(2 * b), - ), - ( - &pic.cb, - w / 2, - h / 2, - l, - (w / 2).saturating_sub(r), - t, - (h / 2).saturating_sub(b), - ), - ( - &pic.cr, - w / 2, - h / 2, - l, - (w / 2).saturating_sub(r), - t, - (h / 2).saturating_sub(b), - ), - ]; - let mut out = Vec::new(); - for (samples, pw, ph, x0, x1, y0, y1) in planes { - for y in y0..y1.min(ph) { - for x in x0..x1.min(pw) { - let s = samples.get(y * pw + x).copied().unwrap_or(0); - if bps == 1 { - out.push(s as u8); - } else { - out.extend_from_slice(&s.to_le_bytes()); - } - } - } - } - out -} - -/// Where byte `offset` of a cropped frame lies: plane name, x and y in that plane. -fn locate(offset: usize, bps: usize, lw: usize, lh: usize) -> (&'static str, usize, usize) { - let s = offset / bps; - let (cw, ch) = (lw / 2, lh / 2); - if s < lw * lh { - ("Y", s % lw, s / lw) - } else if s < lw * lh + cw * ch { - let c = s - lw * lh; - ("Cb", c % cw, c / cw) - } else { - let c = s - lw * lh - cw * ch; - ("Cr", c % cw, c / cw) - } -} - -/// Running comparison of decoded frames against the oracle's rawvideo stream. -#[derive(Default)] -struct Compare { - compared: usize, - /// First mismatch: "frame N plane P x= y= (poc)". - first_diff: Option, - differing_frames: usize, - oracle_short: bool, -} - -/// The oracle's stream and the decoder's frames, compared frame by frame. -struct Sweep { - out: std::process::ChildStdout, - child: std::process::Child, - open: bool, - cmp: Compare, - index: usize, - frame_len: usize, - bps: usize, -} - -impl Sweep { - fn take(&mut self, pic: &DecodedPicture, win: &ConformanceWindow, poc: i32) { - let want = cropped(pic, win, self.bps); - let index = self.index; - self.index += 1; - if !self.open { - return; - } - let mut oracle = vec![0u8; want.len()]; - if self.out.read_exact(&mut oracle).is_err() { - self.open = false; - self.cmp.oracle_short = true; - return; - } - self.frame_len = want.len(); - self.cmp.compared += 1; - if want != oracle { - self.cmp.differing_frames += 1; - if self.cmp.first_diff.is_none() { - let lw = pic.width - 2 * (win.left as usize + win.right as usize); - let lh = pic.height - 2 * (win.top as usize + win.bottom as usize); - let at = want - .iter() - .zip(&oracle) - .position(|(a, b)| a != b) - .unwrap_or(0); - let (plane, x, y) = locate(at, self.bps, lw, lh); - self.cmp.first_diff = Some(format!( - "frame {index} plane {plane} x={x} y={y} (poc {poc})" - )); - } - } - } - - /// End of the decoder's output: any frame still in the oracle is missing here. - fn finish(mut self) -> Compare { - if self.open { - let mut probe = vec![0u8; self.frame_len.max(1)]; - if self.frame_len > 0 && self.out.read_exact(&mut probe).is_ok() { - self.cmp.first_diff.get_or_insert(format!( - "decoder produced {} frames, ffmpeg produced more", - self.index - )); - self.cmp.oracle_short = false; - self.cmp.differing_frames += 1; - } - } - let _ = self.child.kill(); - let _ = self.child.wait(); - self.cmp - } -} - -fn short_name(path: &Path) -> String { - path.file_name() - .map(|n| n.to_string_lossy().chars().take(38).collect()) - .unwrap_or_default() -} - -/// Decodes one file and compares it with ffmpeg. `Err` is a refusal or an error, -/// with the text the table prints. -fn sweep_file(entry: &Entry, es: &Path, bit_depth: u32) -> Result { - let bps = if bit_depth > 8 { 2 } else { 1 }; - let mut child = ec_testkit::ffmpeg() - .args(["-v", "error", "-c:v", "hevc", "-i"]) - .arg(es) - .args([ - "-frames:v", - &FRAMES.to_string(), - "-f", - "rawvideo", - "-pix_fmt", - ]) - .arg(&entry.pix_fmt) - .arg("-") - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn() - .map_err(|e| e.to_string())?; - let out = child.stdout.take().expect("piped stdout"); - let mut sweep = Sweep { - out, - child, - open: true, - cmp: Compare::default(), - index: 0, - frame_len: 0, - bps, - }; - - let data = std::fs::read(es).map_err(|e| e.to_string())?; - let mut dec = Decoder::new(); - let drain = |dec: &mut Decoder, sweep: &mut Sweep| { - while let Some(frame) = dec.next_frame() { - sweep.take(&frame.picture, &frame.window, frame.poc); - } - }; - let result = (|| -> Result<(), String> { - for nal in split_annex_b(&data) { - let mut bytes = nal.header.to_bytes().to_vec(); - bytes.extend_from_slice(nal.payload); - if let Err(e) = dec.push_nal(&bytes) { - return Err(format!("{e}")); - } - drain(&mut dec, &mut sweep); - } - dec.flush().map_err(|e| format!("{e}"))?; - drain(&mut dec, &mut sweep); - Ok(()) - })(); - let cmp = sweep.finish(); - result?; - Ok(cmp) -} - -/// Extracts the first `FRAMES` pictures of the video as Annex B. -fn extract(src: &Path, dst: &Path) -> bool { - ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(src) - .args([ - "-map", - "0:v:0", - "-c", - "copy", - "-bsf:v", - "hevc_mp4toannexb", - "-frames:v", - &FRAMES.to_string(), - "-f", - "hevc", - ]) - .arg(dst) - .status() - .is_ok_and(|s| s.success()) -} - -#[test] -#[ignore = "slow: decodes and compares two open clips with ffmpeg; run with --ignored."] -fn real_library_hevc_streams_match_ffmpeg() { - let entries = hevc_entries(); - let dir = scratch("real-library-hevc"); - let mut table = String::new(); - let mut decoded = 0usize; - let mut refused = 0usize; - let mut failures = Vec::new(); - - for entry in &entries { - let name = short_name(&entry.path); - let res = format!("{}x{}", entry.width, entry.height); - let bit_depth: u32 = if entry.pix_fmt == "yuv420p10le" { - 10 - } else { - 8 - }; - if !IN_SCOPE_PIX_FMTS.contains(&entry.pix_fmt.as_str()) { - refused += 1; - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: pixel format {} is outside 4:2:0 8/10-bit\n", - entry.container, "-", entry.pix_fmt - )); - continue; - } - let es = dir.join("stream.265"); - if !extract(&entry.path, &es) { - failures.push(format!("{name}: extraction failed")); - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR extraction\n", - entry.container, "-" - )); - continue; - } - match sweep_file(entry, &es, bit_depth) { - Ok(c) if c.differing_frames > 0 => { - failures.push(format!("{name}: {} frames differ", c.differing_frames)); - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} MISMATCH {} of {} frames; first: {}\n", - entry.container, c.compared, c.differing_frames, c.compared, - c.first_diff.clone().unwrap_or_default() - )); - } - Ok(c) => { - decoded += 1; - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} bit-exact{}\n", - entry.container, - c.compared, - if c.oracle_short { - " (ffmpeg stopped early)" - } else { - "" - } - )); - } - Err(e) if e.contains("unsupported") => { - refused += 1; - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: {e}\n", - entry.container, "-" - )); - } - Err(e) => { - failures.push(format!("{name}: {e}")); - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR {e}\n", - entry.container, "-" - )); - } - } - let _ = std::fs::remove_file(&es); - } - let _ = std::fs::remove_dir_all(&dir); - eprintln!("{table}"); - eprintln!( - "real library hevc: {decoded} bit-exact, {refused} refused by name, {} failed", - failures.len() - ); - assert!(failures.is_empty(), "{failures:#?}"); - assert!(decoded >= 1, "no real HEVC file was swept end to end"); -} diff --git a/crates/ec-h265/tests/it/rext_generated.rs b/crates/ec-h265/tests/it/rext_generated.rs index 2701c1f3..1618bcda 100644 --- a/crates/ec-h265/tests/it/rext_generated.rs +++ b/crates/ec-h265/tests/it/rext_generated.rs @@ -7,6 +7,8 @@ use std::path::Path; use ec_h265::Decoder; use ec_h265_syntax::md5::Md5; +use crate::common::bit_depth_of; + fn hex(d: [u8; 16]) -> String { d.iter().map(|b| format!("{b:02x}")).collect() } @@ -67,7 +69,7 @@ fn output_md5(data: &[u8]) -> Result<(String, usize), String> { if plane.is_empty() { continue; } - let wide = p.bit_depth_of(c) > 8; + let wide = bit_depth_of(p, c) > 8; let mut bytes = Vec::new(); for y in y0..y1 { for x in x0..x1 { diff --git a/crates/ec-h265/tests/it/scaling_lists.rs b/crates/ec-h265/tests/it/scaling_lists.rs deleted file mode 100644 index 426bad59..00000000 --- a/crates/ec-h265/tests/it/scaling_lists.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Scaling-list streams, checked against ffmpeg. -//! -//! The SLIST conformance streams code their own lists in the SPS and PPS. Most of -//! their pictures are B slices, which this decoder does not pixel-decode yet, so the -//! check is on the first picture in output order: an IDR, intra only, decoded with -//! the stream's lists. It must match ffmpeg sample for sample after cropping. - -use ec_h265::Decoder; -use ec_h265::dec::Frame; -use std::path::{Path, PathBuf}; - -/// The four scaling-list streams the picture-management sweep covers; `str` is -/// the SLIST_D stream. -const STREAMS: [&str; 4] = [ - "SLIST_A_Sony_5/SLIST_A_Sony_5/SLIST_A_Sony_5.bin", - "SLIST_B_Sony_9/SLIST_B_Sony_9/SLIST_B_Sony_9.bin", - "SLIST_C_Sony_4/SLIST_C_Sony_4/SLIST_C_Sony_4.bin", - "SLIST_D_Sony_9/SLIST_D_Sony_9/str.bin", -]; - -fn vectors_dir() -> PathBuf { - ec_testkit::fixture("vectors/hevc-jctvc") -} - -/// The first output picture as 4:2:0 bytes cropped to the conformance window. -fn cropped_yuv(frame: &Frame) -> Vec { - let pic = &frame.picture; - let win = &frame.window; - // Conformance window offsets are in chroma samples for 4:2:0. - let (lx0, lx1) = (2 * win.left as usize, pic.width - 2 * win.right as usize); - let (ly0, ly1) = (2 * win.top as usize, pic.height - 2 * win.bottom as usize); - let (cx0, cx1) = (win.left as usize, pic.width / 2 - win.right as usize); - let (cy0, cy1) = (win.top as usize, pic.height / 2 - win.bottom as usize); - let mut out = Vec::new(); - for row in ly0..ly1 { - out.extend( - pic.y[row * pic.width + lx0..row * pic.width + lx1] - .iter() - .map(|&v| v as u8), - ); - } - let cw = pic.width / 2; - for plane in [&pic.cb, &pic.cr] { - for row in cy0..cy1 { - out.extend( - plane[row * cw + cx0..row * cw + cx1] - .iter() - .map(|&v| v as u8), - ); - } - } - out -} - -/// The first frame of `path` as ffmpeg decodes it, in yuv420p. -fn ffmpeg_first_frame(path: &Path, tag: &str) -> Result, String> { - let out = std::env::temp_dir().join(format!("ec-h265-scaling-{tag}.yuv")); - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(path) - .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&out) - .output() - .map_err(|e| e.to_string())?; - if !status.status.success() { - return Err(String::from_utf8_lossy(&status.stderr).to_string()); - } - std::fs::read(&out).map_err(|e| e.to_string()) -} - -// Ignored until the intra path decodes the syntax these streams use: the decode -// desyncs at the last CTB of the IDR, and the intra CTU loop has no SAO or -// cu_qp_delta parsing. Run with `--ignored` to see the failure. -#[ignore = "intra path lacks the syntax these streams use (desync at the IDR's last CTB)"] -#[test] -fn first_picture_of_each_scaling_list_stream_matches_ffmpeg() { - let dir = vectors_dir(); - let mut checked = 0usize; - for rel in STREAMS { - let path = dir.join(rel); - let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{rel}: {e}")); - let mut decoder = Decoder::new(); - decoder - .decode_annex_b(&data) - .unwrap_or_else(|e| panic!("{rel}: decode failed: {e}")); - decoder - .flush() - .unwrap_or_else(|e| panic!("{rel}: flush failed: {e}")); - let frame = decoder - .next_frame() - .unwrap_or_else(|| panic!("{rel}: no picture out")); - let ours = cropped_yuv(&frame); - let tag = rel.replace('/', "_"); - let theirs = - ffmpeg_first_frame(&path, &tag).unwrap_or_else(|e| panic!("{rel}: ffmpeg failed: {e}")); - assert_eq!( - ours.len(), - theirs.len(), - "{rel}: picture is {} bytes, ffmpeg's is {}", - ours.len(), - theirs.len() - ); - let differing = ours.iter().zip(&theirs).filter(|(a, b)| a != b).count(); - assert_eq!( - differing, 0, - "{rel}: {differing} samples differ from ffmpeg in the first picture" - ); - checked += 1; - } - eprintln!("scaling-list check: {checked} first pictures bit-exact against ffmpeg"); -}