From 49bb32ea04bed31fa638f09b8512b7c86155507e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 14:42:48 +0300 Subject: [PATCH] feat(h264): High-profile 8x8 transform, both entropy coders transform_size_8x8_flag (7.3.5) in the intra and inter positions with the neighbour context of 9.3.3.1.1.10, Intra_8x8 prediction with the reference sample filter of 8.3.2.2.1, the 8x8 residual under CAVLC (four interleaved 4x4 blocks) and CABAC (ctxBlockCat 5, ctxIdx 402..435 transcribed from Table 9-24, no coded_block_flag), the 8x8 scaling and inverse transform of 8.5.13 with the 8x8 scaling lists, and the 8.7 rule that an 8x8 macroblock has no transform edge at luma 4 or 12. This is what real content needs: every H.264 file in the library that is not Main profile uses it, so eight of twelve were refused by name before and all twelve now decode 500 frames bit-exactly against ffmpeg. The MP4 whose Annex B extraction ffmpeg itself could only decode three frames of is demuxed by ec-mp4 instead, which restores the oracle. Coverage: 51 quantisers x both coders all-intra, P and B sequences with and without sub-8x8 partitions, and a parameter-set assertion so an encoder silently dropping back to 4x4 cannot make the sweep vacuous. --- crates/ec-h264-syntax/src/lib.rs | 4 +- crates/ec-h264/Cargo.toml | 3 + crates/ec-h264/src/cabac.rs | 86 ++++++-- crates/ec-h264/src/cabac_tables.rs | 62 +++++- crates/ec-h264/src/decoder.rs | 253 +++++++++++++++++++-- crates/ec-h264/src/entropy.rs | 16 +- crates/ec-h264/src/pred.rs | 303 +++++++++++++++++++++++++ crates/ec-h264/src/tables.rs | 15 ++ crates/ec-h264/src/transform.rs | 139 +++++++++++- crates/ec-h264/tests/conformance.rs | 328 +++++++++++++++++++++++++--- 10 files changed, 1129 insertions(+), 80 deletions(-) diff --git a/crates/ec-h264-syntax/src/lib.rs b/crates/ec-h264-syntax/src/lib.rs index e796dc99..84f8cac5 100644 --- a/crates/ec-h264-syntax/src/lib.rs +++ b/crates/ec-h264-syntax/src/lib.rs @@ -23,8 +23,8 @@ pub mod sps; pub use nal::{AnnexBIter, NalHeader, NalUnitType, unescape_rbsp}; pub use pps::Pps; pub use slice::{ - DeblockControl, DecRefPicMarking, Mmco, PredWeightTable, RefPicListMod, SliceHeader, - SliceType, WeightEntry, + DeblockControl, DecRefPicMarking, Mmco, PredWeightTable, RefPicListMod, SliceHeader, SliceType, + WeightEntry, }; pub use sps::{BitstreamRestriction, Hrd, ScalingLists, Sps, Vui}; diff --git a/crates/ec-h264/Cargo.toml b/crates/ec-h264/Cargo.toml index 97605f74..d9151dbe 100644 --- a/crates/ec-h264/Cargo.toml +++ b/crates/ec-h264/Cargo.toml @@ -14,3 +14,6 @@ wide = { workspace = true } [dev-dependencies] # The conformance harness walks Annex B itself to drive push_nal. ec-h264-syntax = { workspace = true } +# ... and demuxes an MP4 directly where ffmpeg's own Annex B extraction of it +# produces a stream ffmpeg then cannot decode. +ec-mp4 = { workspace = true } diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index 2378b064..32dbfe56 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -1,10 +1,11 @@ //! CABAC slice-data parsing (spec clause 9.3): arithmetic decoding engine, //! context variables, binarizations and context selection. //! -//! Scope is what a frame-coded 4:2:0 8-bit stream needs, I, P and B; every -//! other tool the decoder refuses by name before reaching this module, so the -//! contexts, block categories and initialisation columns that only field or -//! 8x8-transform coding reads are absent rather than transcribed untested. +//! Scope is what a frame-coded 4:2:0 8-bit stream needs, I, P and B, with or +//! without the High-profile 8x8 transform; every other tool the decoder refuses +//! by name before reaching this module, so the contexts, block categories and +//! initialisation columns that only field or 4:4:4 coding reads are absent +//! rather than transcribed untested. //! //! The engine keeps codIRange and codIOffset in `u32` with the spec's exact //! integer steps — no probability floats, no shortcuts — and reads its bits @@ -17,16 +18,19 @@ use ec_core::error::{Error, Result}; use crate::bits::BitCursor; use crate::cabac_tables::{ - INIT_11_59, INIT_60_69, INIT_70_275, INIT_399_401, INIT_MB_TYPE_I, RANGE_LPS, TRANS_LPS, - TRANS_MPS, + INIT_11_59, INIT_60_69, INIT_70_275, INIT_399_401, INIT_402_435, INIT_MB_TYPE_I, LAST_8X8, + RANGE_LPS, SIG_8X8_FRAME, TRANS_LPS, TRANS_MPS, }; use crate::entropy::{ - BlockCat, FLAG_CHROMA_PRED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, MbCtx, MbInfo, + BlockCat, FLAG_CHROMA_PRED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8, MbCtx, + MbInfo, }; -/// Highest ctxIdx this decoder can address, plus one (399..401 is the -/// transform_size_8x8_flag block, the last range a frame-coded slice reaches). -const NUM_CTX: usize = 402; +/// Highest ctxIdx this decoder can address, plus one (426..435 is +/// coeff_abs_level_minus1 of the 8x8 luma category, the last range a +/// frame-coded 4:2:0 slice reaches; 436 and up are the field-coded and 4:4:4 +/// categories this decoder refuses by name). +const NUM_CTX: usize = 436; /// ctxIdx 276 (end_of_slice_flag and the I_PCM bin of mb_type) is decoded by /// DecodeTerminate and has no adapting state. @@ -58,6 +62,11 @@ const OFF_SIG: usize = 105; const OFF_LAST: usize = 166; const OFF_ABS: usize = 227; const OFF_TRANSFORM_8X8: usize = 399; +/// significant_coeff_flag / last_significant_coeff_flag / coeff_abs_level_minus1 +/// of ctxBlockCat 5 (frame coded), Table 9-34. +const OFF_SIG_8X8: usize = 402; +const OFF_LAST_8X8: usize = 417; +const OFF_ABS_8X8: usize = 426; /// The ctxIdx values the Intra_16x16 part of an mb_type bin string uses, in /// bin order: `[b0, CodedBlockPatternLuma, chroma bin 0, chroma bin 1, @@ -146,6 +155,9 @@ impl<'a> Cabac<'a> { for (i, &mn) in INIT_399_401.iter().enumerate() { set(&mut self.state, OFF_TRANSFORM_8X8 + i, mn[column]); } + for (i, &mn) in INIT_402_435.iter().enumerate() { + set(&mut self.state, OFF_SIG_8X8 + i, mn[column]); + } } /// 9.3.1.2: codIRange = 510, codIOffset = read_bits(9). @@ -415,11 +427,15 @@ impl<'a> Cabac<'a> { Ok(if self.bypass() { -value } else { value }) } - /// transform_size_8x8_flag (9.3.3.1.1.10). + /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is + /// available and carried the flag itself. pub(crate) fn transform_size_8x8_flag(&mut self) -> Result { - // No neighbour can carry the flag: a macroblock that set it is refused - // before its state is ever stored, so ctxIdxInc is always 0 here. - Ok(self.decision(OFF_TRANSFORM_8X8)) + let cond = |n: Option| match n { + None => 0, + Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0), + }; + let inc = cond(self.ctx.a) + cond(self.ctx.b); + Ok(self.decision(OFF_TRANSFORM_8X8 + inc)) } /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7 @@ -580,8 +596,44 @@ impl<'a> Cabac<'a> { } sig[num - 1] = true; - // Levels, highest scanning position first (9.3.3.1.3 counters). - let abs_base = OFF_ABS + ABS_CAT_OFF[cat_i]; + self.decode_levels(coeff, &sig, num, OFF_ABS + ABS_CAT_OFF[cat_i], cat_i == 3) + } + + /// residual_block_cabac for a luma 8x8 block (ctxBlockCat 5). + /// + /// There is no coded_block_flag here: with ChromaArrayType other than 3, + /// 7.3.5.3.3 sends the flag only when maxNumCoeff differs from 64, so the + /// coded_block_pattern bit that selected this block is the whole signal and + /// the flag is inferred to be 1. + pub(crate) fn residual_block_8x8(&mut self, coeff: &mut [i32; 64]) -> Result { + *coeff = [0; 64]; + let mut sig = [false; 64]; + let mut num = 64; + let mut i = 0; + while i + 1 < num { + if self.decision(OFF_SIG_8X8 + usize::from(SIG_8X8_FRAME[i])) { + sig[i] = true; + if self.decision(OFF_LAST_8X8 + usize::from(LAST_8X8[i])) { + num = i + 1; + } + } + i += 1; + } + sig[num - 1] = true; + self.decode_levels(coeff, &sig, num, OFF_ABS_8X8, false) + } + + /// coeff_abs_level_minus1 and coeff_sign_flag over a decoded significance + /// map, highest scanning position first (9.3.3.1.3 counters). Returns the + /// number of levels written. + fn decode_levels( + &mut self, + coeff: &mut [i32], + sig: &[bool], + num: usize, + abs_base: usize, + chroma_dc: bool, + ) -> Result { let mut num_eq1 = 0u32; let mut num_gt1 = 0u32; let mut total = 0u8; @@ -594,7 +646,7 @@ impl<'a> Cabac<'a> { } else { 4.min(1 + num_eq1) as usize }; - let inc1 = 5 + (4 - u32::from(cat_i == 3)).min(num_gt1) as usize; + let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize; // Prefix: TU with cMax = uCoff = 14. let mut prefix = 0u32; while prefix < 14 { diff --git a/crates/ec-h264/src/cabac_tables.rs b/crates/ec-h264/src/cabac_tables.rs index 794284a4..344abe42 100644 --- a/crates/ec-h264/src/cabac_tables.rs +++ b/crates/ec-h264/src/cabac_tables.rs @@ -3,15 +3,16 @@ //! The initialisation values of Tables 9-12 to 9-21 for every ctxIdx a //! frame-coded 4:2:0 slice can reach: 0..10 (I-slice mb_type), 11..59 (the //! inter elements: mb_skip_flag, P and B mb_type and sub_mb_type, mvd, -//! ref_idx), 60..69 (shared by all slice types), 70..275 and 399..401. +//! ref_idx), 60..69 (shared by all slice types), 70..275, 399..401 (the +//! transform size flag) and 402..435 (the frame-coded 8x8 luma residual). //! //! Where a ctxIdx has cabac_init_idc columns they are stored as //! `[I/SI, idc 0, idc 1, idc 2]` and [`crate::cabac::Cabac`] selects the column //! once per slice. ctxIdx 11..53 are never read by an I slice; their I column //! repeats the idc-0 values so the arrays stay rectangular. //! -//! Absent on purpose: the field-coded significance contexts (277..398) and the -//! 8x8 transform categories (402..1023) — both tools are refused by name, so +//! Absent on purpose: the field-coded significance contexts (277..398, 436..459) +//! and the 4:4:4 categories (460..1023) — both tools are refused by name, so //! transcribing their numbers would ship values no oracle here exercises. /// Table 9-12, ctxIdx 0..10: mb_type in I slices. @@ -310,6 +311,61 @@ pub(crate) const INIT_70_275: [[(i8, i8); 4]; 206] = [ [(-14, 97), (-8, 85), (-4, 78), (-10, 87)], ]; +/// Table 9-24, ctxIdx 402..435: the frame-coded 8x8 luma residual contexts +/// (significant_coeff_flag 402..416, last_significant_coeff_flag 417..425, +/// coeff_abs_level_minus1 426..435), all four initialisation columns. +pub(crate) const INIT_402_435: [[(i8, i8); 4]; 34] = [ + [(-17, 120), (-4, 79), (-5, 85), (-3, 78)], + [(-20, 112), (-7, 71), (-6, 81), (-8, 74)], + [(-18, 114), (-5, 69), (-10, 77), (-9, 72)], + [(-11, 85), (-9, 70), (-7, 81), (-10, 72)], + [(-15, 92), (-8, 66), (-17, 80), (-18, 75)], + [(-14, 89), (-10, 68), (-18, 73), (-12, 71)], + [(-26, 71), (-19, 73), (-4, 74), (-11, 63)], + [(-15, 81), (-12, 69), (-10, 83), (-5, 70)], + [(-14, 80), (-16, 70), (-9, 71), (-17, 75)], + [(0, 68), (-15, 67), (-9, 67), (-14, 72)], + [(-14, 70), (-20, 62), (-1, 61), (-16, 67)], + [(-24, 56), (-19, 70), (-8, 66), (-8, 53)], + [(-23, 68), (-16, 66), (-14, 66), (-14, 59)], + [(-24, 50), (-22, 65), (0, 59), (-9, 52)], + [(-11, 74), (-20, 63), (2, 59), (-11, 68)], + [(23, -13), (9, -2), (17, -10), (9, -2)], + [(26, -13), (26, -9), (32, -13), (30, -10)], + [(40, -15), (33, -9), (42, -9), (31, -4)], + [(49, -14), (39, -7), (49, -5), (33, -1)], + [(44, 3), (41, -2), (53, 0), (33, 7)], + [(45, 6), (45, 3), (64, 3), (31, 12)], + [(44, 34), (49, 9), (68, 10), (37, 23)], + [(33, 54), (45, 27), (66, 27), (31, 38)], + [(19, 82), (36, 59), (47, 57), (20, 64)], + [(-3, 75), (-6, 66), (-5, 71), (-9, 71)], + [(-1, 23), (-7, 35), (0, 24), (-7, 37)], + [(1, 34), (-7, 42), (-1, 36), (-8, 44)], + [(1, 43), (-8, 45), (-2, 42), (-11, 49)], + [(0, 54), (-5, 48), (-2, 52), (-10, 56)], + [(-2, 55), (-12, 56), (-9, 57), (-12, 59)], + [(0, 61), (-6, 60), (-6, 63), (-8, 63)], + [(1, 64), (-5, 62), (-4, 65), (-9, 67)], + [(0, 68), (-8, 66), (-4, 67), (-6, 68)], + [(-9, 92), (-8, 76), (-7, 82), (-10, 79)], +]; + +/// Table 9-43, frame-coded column: ctxIdxInc of significant_coeff_flag for +/// ctxBlockCat 5, indexed by levelListIdx 0..62. +pub(crate) const SIG_8X8_FRAME: [u8; 63] = [ + 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, + 7, 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, + 13, 11, 14, 10, 12, +]; + +/// Table 9-43, last column: ctxIdxInc of last_significant_coeff_flag for +/// ctxBlockCat 5, indexed by levelListIdx 0..62. +pub(crate) const LAST_8X8: [u8; 63] = [ + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, +]; + /// Table 9-16, ctxIdx 399..401: transform_size_8x8_flag. pub(crate) const INIT_399_401: [[(i8, i8); 4]; 3] = [ [(31, 21), (12, 40), (25, 32), (21, 33)], diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index beead04a..664c0442 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -38,18 +38,22 @@ use crate::dpb::{ }; use crate::entropy::{ BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, - FLAG_SKIP, MbCtx, MbInfo, + FLAG_SKIP, FLAG_TRANS8X8, MbCtx, MbInfo, }; use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma}; use crate::mv::{ B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, neighbour_mvd, predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd, }; -use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; +use crate::pred::{ + Nbr4, Nbr8, PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, + pred_16x16, pred_chroma_8x8, +}; use crate::tables::{BLK4_POS, CHROMA_QP}; use crate::transform::{ - LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform, - unzigzag, unzigzag_ac15, + LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8, + inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, + unzigzag_ac15, }; /// Where a 4x4 block's top-right neighbour samples come from, per @@ -110,6 +114,9 @@ pub struct Decoder { has_picture: bool, /// Scaling factors of the active PPS/SPS, `[intra, inter][Y, Cb, Cr]`. ls: [[LevelScale4x4; 3]; 2], + /// The same for the 8x8 luma transform, `[intra, inter]` (4:2:0 has no 8x8 + /// chroma transform). + ls8: [LevelScale8x8; 2], active_pps: Option, /// `seq_parameter_set_id` of the most recently stored SPS, so a container /// entry path can publish the picture size before the first slice. @@ -174,6 +181,7 @@ impl Decoder { dpb: Dpb::default(), has_picture: false, ls: flat_scaling(), + ls8: [LevelScale8x8::new(&[16; 64]), LevelScale8x8::new(&[16; 64])], active_pps: None, last_sps: None, cur_info: PicInfo { @@ -526,6 +534,7 @@ impl Decoder { &mut self.cur, &self.dpb.frames, &self.ls, + &self.ls8, &mut r, &mut ctx, mb_addr, @@ -543,6 +552,7 @@ impl Decoder { &mut self.cur, &self.dpb.frames, &self.ls, + &self.ls8, &mut r, &mut ctx, mb_addr, @@ -566,6 +576,7 @@ impl Decoder { &mut self.cur, &self.dpb.frames, &self.ls, + &self.ls8, &mut r, &mut ctx, mb_addr, @@ -678,6 +689,11 @@ impl Decoder { LevelScale4x4::new(weights[1][2]), ], ]; + let w8 = match lists { + Some(l) => [&l.list_8x8[0], &l.list_8x8[1]], + None => [&[16u8; 64]; 2], + }; + self.ls8 = [LevelScale8x8::new(w8[0]), LevelScale8x8::new(w8[1])]; self.active_pps = Some(pps.id); } Ok(()) @@ -865,12 +881,16 @@ impl SliceCtx { } } -/// Neighbour-availability snapshot for one macroblock (left, top, top-right). +/// Neighbour-availability snapshot for one macroblock (left, top, top-right, +/// top-left). The top-left neighbour is only read by the Intra_8x8 reference +/// filter of 8.3.2.2.1, which changes its end taps when the corner sample is +/// missing. #[derive(Clone, Copy)] struct MbNeighbors { a: bool, b: bool, c: bool, + d: bool, } fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNeighbors { @@ -881,6 +901,7 @@ fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNei a: mb_x > 0 && same(addr - 1), b: mb_y > 0 && same(addr - w), c: mb_y > 0 && mb_x + 1 < w && same(addr - w + 1), + d: mb_y > 0 && mb_x > 0 && same(addr - w - 1), } } @@ -894,6 +915,7 @@ fn intra_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, n: MbNeighbors) -> M a: n.a && intra(addr - 1), b: n.b && intra(addr - w), c: n.c && intra(addr - w + 1), + d: n.d && intra(addr - w - 1), } } @@ -950,6 +972,7 @@ fn decode_macroblock( pic: &mut Picture, refs: &[Picture], ls: &[[LevelScale4x4; 3]; 2], + ls8: &[LevelScale8x8; 2], r: &mut Entropy<'_>, ctx: &mut SliceCtx, mb_addr: usize, @@ -1023,7 +1046,9 @@ fn decode_macroblock( }; r.set_intra(intra_type.is_some()); if let Some(shape) = shape { - return decode_inter_mb(pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr); + return decode_inter_mb( + pic, refs, ls, ls8, r, ctx, mb_addr, shape, skipped, mb_type, nbr, + ); } let mb_type = intra_type.expect("an intra macroblock type"); write_intra_mb(pic, mb_x, mb_y); @@ -1082,18 +1107,45 @@ fn decode_macroblock( (0, 0, 0) // read below via me(v) }; - // I_NxN transform size flag (High profile only). - if !is_i16 && ctx.transform_8x8_mode && r.transform_size_8x8_flag()? { - return Err(Error::unsupported( - "8x8 transform", - "transform_size_8x8_flag 1 selects the 8x8 intra prediction of \ - clause 8.3.2 and the 8x8 transform of 8.5.13; not implemented", - )); - } + // I_NxN transform size flag (7.3.5, High profile only): it selects + // Intra_8x8 prediction and the 8x8 transform for this macroblock. + let trans8x8 = !is_i16 && ctx.transform_8x8_mode && r.transform_size_8x8_flag()?; - // mb_pred (7.3.5.1): intra 4x4 modes, then chroma mode. + // mb_pred (7.3.5.1): intra 4x4 or 8x8 modes, then chroma mode. let mut modes = [2u8; 16]; - if !is_i16 { + let mut modes8 = [2u8; 4]; + if trans8x8 { + // Intra_8x8: four modes, predicted by 8.3.2.1 from the neighbouring + // block modes. Every 4x4 slot of an 8x8 block carries its mode, which + // is exactly what 8.3.1.1 and 8.3.2.1 read back from a neighbour + // whichever size that neighbour used. + for blk8 in 0..4 { + let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); + let left_avail = if blk8.is_multiple_of(2) { + intra_nbr.a + } else { + true + }; + let top_avail = if blk8 < 2 { intra_nbr.b } else { true }; + let pred = if left_avail && top_avail { + let ma = pic.i4_modes[by * w4 + bx - 1]; + let mb = pic.i4_modes[(by - 1) * w4 + bx]; + ma.min(mb) + } else { + 2 + }; + let mode = match r.intra4x4_pred_mode()? { + None => pred, + Some(rem) if rem < pred => rem, + Some(rem) => rem + 1, + }; + modes8[blk8] = mode; + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + pic.i4_modes[base..base + 2].fill(mode); + } + } + } else if !is_i16 { for blk in 0..16 { let (dx, dy) = BLK4_POS[blk]; let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); @@ -1134,6 +1186,7 @@ fn decode_macroblock( finish_macroblock( pic, &ls[0], + &ls8[0], r, ctx, mb_addr, @@ -1145,9 +1198,11 @@ fn decode_macroblock( cbp_luma, cbp_chroma, modes, + modes8, + trans8x8, chroma_mode, intra: true, - flags: if is_i16 { FLAG_I16 } else { 0 }, + flags: if is_i16 { FLAG_I16 } else { 0 } | if trans8x8 { FLAG_TRANS8X8 } else { 0 }, }, ) } @@ -1165,6 +1220,10 @@ struct MbFinish { cbp_luma: u8, cbp_chroma: u8, modes: [u8; 16], + /// Intra8x8PredMode per 8x8 block, when `trans8x8` and `intra`. + modes8: [u8; 4], + /// transform_size_8x8_flag: the luma residual is four 8x8 transform blocks. + trans8x8: bool, chroma_mode: u8, intra: bool, flags: u8, @@ -1183,6 +1242,7 @@ struct MbFinish { fn finish_macroblock( pic: &mut Picture, ls: &[LevelScale4x4; 3], + ls8: &LevelScale8x8, r: &mut Entropy<'_>, ctx: &mut SliceCtx, mb_addr: usize, @@ -1265,6 +1325,69 @@ fn finish_macroblock( .at(mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); add_residual_4x4(&mut pic.y.data, pic.y.stride, origin, &resid); } + } else if m.trans8x8 { + // 8x8 transform (8.5.13): predict, parse and reconstruct one 8x8 block + // at a time, because an Intra_8x8 block predicts from the reconstructed + // samples of the blocks before it. + let mut scan8 = [0i32; 64]; + let mut raster8 = [0i32; 64]; + let mut resid8 = [0i32; 64]; + for blk8 in 0..4 { + let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8); + let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); + let origin = pic.y.at(x, y); + let stride = pic.y.stride; + if m.intra { + let n = filter_nbr8(&gather_nbr8(pic, &m.pred_nbr, blk8, x, y)); + let mut p = [0u8; 64]; + pred_8x8(m.modes8[blk8], &n, &mut p); + for ry in 0..8 { + let row = origin + ry * stride; + pic.y.data[row..row + 8].copy_from_slice(&p[ry * 8..ry * 8 + 8]); + } + } + if cbp_luma & (1 << blk8) == 0 { + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + pic.nz_y[base..base + 2].fill(0); + } + continue; + } + let tc = if r.is_cabac() { + // ctxBlockCat 5: one 64-coefficient block, and every 4x4 slot + // of it reports the block's own count to the neighbours + // (9.3.3.1.1.9 resolves them to the 8x8 transform block). + let tc = r.residual_block_8x8(&mut scan8)?; + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + pic.nz_y[base..base + 2].fill(tc.min(16)); + } + tc + } else { + // CAVLC codes the same 64 coefficients as four interleaved 4x4 + // blocks (7.3.5.3.1), each with its own nC neighbourhood. + let mut tc = 0u8; + for i4 in 0..4 { + let (dx, dy) = BLK4_POS[blk8 * 4 + i4]; + let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize); + let (na, nb) = luma_nz_pair(pic, nbr, sx, sy); + let n = r.residual_block(&mut scan, BlockCat::Luma4x4, na, nb)?; + pic.nz_y[sy * w4 + sx] = n; + tc += n; + for i in 0..16 { + scan8[4 * i + i4] = scan[i]; + } + } + tc + }; + if tc == 0 { + continue; + } + unzigzag_8x8(&scan8, &mut raster8); + dequant_8x8(&mut raster8, ls8, qp_y); + inverse_transform_8x8(&raster8, &mut resid8); + add_residual_8x8(&mut pic.y.data, stride, origin, &resid8); + } } else { for blk in 0..16 { let (dx, dy) = BLK4_POS[blk]; @@ -1388,6 +1511,7 @@ fn decode_inter_mb( pic: &mut Picture, refs: &[Picture], ls: &[[LevelScale4x4; 3]; 2], + ls8: &[LevelScale8x8; 2], r: &mut Entropy<'_>, ctx: &mut SliceCtx, mb_addr: usize, @@ -1611,10 +1735,28 @@ fn decode_inter_mb( pic.i4_modes[base..base + 4].fill(2); } let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?; + // transform_size_8x8_flag (7.3.5): only when every 8x8 of this macroblock + // is predicted as a whole, because an 8x8 transform block may not straddle + // two motion partitions. + let no_sub_lt_8x8 = !shape.sub + || (0..4).all(|p| { + let s = motion.sub[p]; + if s.pred == Pred::Direct { + ctx.direct_8x8_inference + } else { + s.parts == 1 + } + }); + let trans8x8 = cbp_luma != 0 + && ctx.transform_8x8_mode + && no_sub_lt_8x8 + && (!direct_mb || ctx.direct_8x8_inference) + && r.transform_size_8x8_flag()?; // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual. finish_macroblock( pic, &ls[1], + &ls8[1], r, ctx, mb_addr, @@ -1626,9 +1768,12 @@ fn decode_inter_mb( cbp_luma, cbp_chroma, modes: [2; 16], + modes8: [2; 4], + trans8x8, chroma_mode: 0, intra: false, - flags: if b && mb_type == 0 { FLAG_DIRECT } else { 0 }, + flags: if b && mb_type == 0 { FLAG_DIRECT } else { 0 } + | if trans8x8 { FLAG_TRANS8X8 } else { 0 }, }, ) } @@ -2042,6 +2187,52 @@ fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) } } +/// Gather the 25 neighbour samples of an Intra_8x8 luma block (spec 8.3.2.2), +/// including the top-right substitution rule, unfiltered. +/// +/// `blk8` is luma8x8BlkIdx: block 1 reaches the above-right macroblock for its +/// top-right run, block 2 finds it inside this macroblock, and block 3 has none +/// (the samples right of it are not decoded yet). +fn gather_nbr8(pic: &Picture, nbr: &MbNeighbors, blk8: usize, x: usize, y: usize) -> Nbr8 { + let stride = pic.y.stride; + let o = pic.y.at(x, y); + let data = &pic.y.data; + let have_top = if blk8 < 2 { nbr.b } else { true }; + let have_left = if blk8.is_multiple_of(2) { nbr.a } else { true }; + let have_tr = match blk8 { + 0 => nbr.b, + 1 => nbr.c, + 2 => true, + _ => false, + }; + let have_tl = match blk8 { + 0 => nbr.d, + 1 => nbr.b, + 2 => nbr.a, + _ => true, + }; + let mut top = [0u8; 16]; + top[..8].copy_from_slice(&data[o - stride..o - stride + 8]); + if have_tr { + top[8..].copy_from_slice(&data[o - stride + 8..o - stride + 16]); + } else { + let t7 = top[7]; + top[8..].fill(t7); + } + let mut left = [0u8; 8]; + for (i, l) in left.iter_mut().enumerate() { + *l = data[o + i * stride - 1]; + } + Nbr8 { + top, + left, + top_left: data[o - stride - 1], + have_top, + have_left, + have_tl, + } +} + /// Whole-picture deblocking (spec 8.7): macroblocks in raster order, all /// vertical edges then all horizontal edges per macroblock, then chroma. // `e` and `j` are edge and segment positions inside the macroblock, used to @@ -2074,6 +2265,11 @@ fn deblock_picture(pic: &mut Picture) { } }; let qp_q = qp_of(addr); + // 8.7: an 8x8-transform macroblock has no transform edge at luma + // 4 or 12, so those internal edges are not filtered. Chroma is + // unaffected for 4:2:0 (its internal edge sits on luma edge 8). + let internal = + |e: usize| e.is_multiple_of(2) || pic.mb_flags[addr] & FLAG_TRANS8X8 == 0; // Boundary strengths, per 4-sample segment of each edge (8.7.2.1). let mut bs_v = [[0u8; 4]; 4]; @@ -2098,6 +2294,9 @@ fn deblock_picture(pic: &mut Picture) { if e == 0 && !filter_left { continue; } + if !internal(e) { + continue; + } let qp_p = if e == 0 { qp_of(addr - 1) } else { qp_q }; let qp_avg = (qp_p + qp_q + 1) >> 1; // Vertical edges stay scalar: a gather/scatter SIMD @@ -2128,6 +2327,9 @@ fn deblock_picture(pic: &mut Picture) { if e == 0 && !filter_top { continue; } + if !internal(e) { + continue; + } let qp_p = if e == 0 { qp_of(addr - mb_w) } else { qp_q }; let qp_avg = (qp_p + qp_q + 1) >> 1; let bs = bs_h[e]; @@ -2271,7 +2473,20 @@ fn boundary_strength( if intra { return if mb_edge { 4 } else { 3 }; } - if pic.nz_y[p] != 0 || pic.nz_y[q] != 0 { + // "the transform block containing the sample has non-zero levels": for an + // 8x8-transform macroblock that is the whole 8x8, whose four 4x4 slots + // carry per-slot counts under CAVLC (7.3.5.3.1 splits it into four blocks). + let coded = |mb: usize, bx: usize, by: usize| -> bool { + if pic.mb_flags[mb] & FLAG_TRANS8X8 == 0 { + return pic.nz_y[by * w4 + bx] != 0; + } + let (ox, oy) = (bx & !1, by & !1); + pic.nz_y[oy * w4 + ox] != 0 + || pic.nz_y[oy * w4 + ox + 1] != 0 + || pic.nz_y[(oy + 1) * w4 + ox] != 0 + || pic.nz_y[(oy + 1) * w4 + ox + 1] != 0 + }; + if coded(p_mb, pbx, pby) || coded(q_mb, qbx, qby) { return 2; } let (pr, qr) = (pic.ref_id[p], pic.ref_id[q]); diff --git a/crates/ec-h264/src/entropy.rs b/crates/ec-h264/src/entropy.rs index c4491c40..75baee04 100644 --- a/crates/ec-h264/src/entropy.rs +++ b/crates/ec-h264/src/entropy.rs @@ -38,6 +38,9 @@ pub(crate) const FLAG_INTER: u8 = 16; pub(crate) const FLAG_DIRECT: u8 = 32; /// mb_type is P_Skip or B_Skip (9.3.3.1.1.1). pub(crate) const FLAG_SKIP: u8 = 64; +/// transform_size_8x8_flag is 1: the luma residual is four 8x8 transform +/// blocks, and an Intra_NxN macroblock predicts in 8x8 blocks (8.3.2). +pub(crate) const FLAG_TRANS8X8: u8 = 128; /// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes). #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -101,7 +104,7 @@ pub(crate) struct MbCtx { /// The slice-data syntax reader. /// -/// The CABAC variant is much the larger of the two (it carries 402 context +/// The CABAC variant is much the larger of the two (it carries 436 context /// variables), and stays inline on purpose: one of these lives per slice on the /// stack, so boxing it would trade a compile-time size warning for a heap /// allocation in a decode loop that is otherwise allocation free. @@ -372,6 +375,17 @@ impl<'a> Entropy<'a> { } } + /// Decode one 8x8 luma residual block into `coeff[0..64]` in scan order, + /// returning the number of non-zero coefficients. CABAC only: a CAVLC 8x8 + /// block is coded as four interleaved 4x4 blocks (7.3.5.3.1), which the + /// caller reads through [`Entropy::residual_block`]. + pub(crate) fn residual_block_8x8(&mut self, coeff: &mut [i32; 64]) -> Result { + match self { + Entropy::Cavlc(_) => Err(Error::corrupt("8x8 residual block read from a CAVLC slice")), + Entropy::Cabac(c) => c.residual_block_8x8(coeff), + } + } + /// The 384 raw bytes of an I_PCM macroblock (256 luma, 2x64 chroma), after /// alignment. A CABAC reader restarts its arithmetic engine afterwards /// (clause 9.3.1.2). diff --git a/crates/ec-h264/src/pred.rs b/crates/ec-h264/src/pred.rs index 2da646ba..bb500d94 100644 --- a/crates/ec-h264/src/pred.rs +++ b/crates/ec-h264/src/pred.rs @@ -163,6 +163,216 @@ pub fn pred_4x4(mode: u8, n: &Nbr4, out: &mut [u8; 16]) { } } +/// Neighbour samples of an 8x8 luma block (spec 8.3.2.2's 25 samples), already +/// low-pass filtered by [`filter_nbr8`]. `top[8..16]` carries the top-right +/// substitution rule. +#[derive(Debug, Clone, Copy)] +pub struct Nbr8 { + /// p'[0..15, -1]. + pub top: [u8; 16], + /// p'[-1, 0..7]. + pub left: [u8; 8], + /// p'[-1, -1]. + pub top_left: u8, + /// p[x, -1] available. + pub have_top: bool, + /// p[-1, y] available. + pub have_left: bool, + /// p[-1, -1] available. Its own neighbour (the above-left macroblock for + /// block 0), not the conjunction of the two runs. + pub have_tl: bool, +} + +/// Reference sample filtering for Intra_8x8 prediction (spec 8.3.2.2.1). +/// +/// Input is the unfiltered neighbourhood; each of the three runs (top row, +/// corner, left column) is filtered only when it is wholly available, exactly +/// as the clause states, so an edge block keeps the raw samples the prediction +/// modes it is allowed to signal actually read. +pub fn filter_nbr8(n: &Nbr8) -> Nbr8 { + let mut out = *n; + let have_tl = n.have_tl; + if n.have_top { + let t = |i: usize| i32::from(n.top[i]); + out.top[0] = if have_tl { + ((i32::from(n.top_left) + 2 * t(0) + t(1) + 2) >> 2) as u8 + } else { + ((3 * t(0) + t(1) + 2) >> 2) as u8 + }; + for x in 1..15 { + out.top[x] = ((t(x - 1) + 2 * t(x) + t(x + 1) + 2) >> 2) as u8; + } + out.top[15] = ((t(14) + 3 * t(15) + 2) >> 2) as u8; + } + if have_tl { + // 8-82 to 8-84: which taps the corner takes depends on which of its two + // adjacent samples exist. + let (tl, t0, l0) = ( + i32::from(n.top_left), + i32::from(n.top[0]), + i32::from(n.left[0]), + ); + out.top_left = match (n.have_top, n.have_left) { + (true, true) => ((t0 + 2 * tl + l0 + 2) >> 2) as u8, + (true, false) => ((3 * tl + t0 + 2) >> 2) as u8, + (false, true) => ((3 * tl + l0 + 2) >> 2) as u8, + (false, false) => n.top_left, + }; + } + if n.have_left { + let l = |i: usize| i32::from(n.left[i]); + out.left[0] = if have_tl { + ((i32::from(n.top_left) + 2 * l(0) + l(1) + 2) >> 2) as u8 + } else { + ((3 * l(0) + l(1) + 2) >> 2) as u8 + }; + for y in 1..7 { + out.left[y] = ((l(y - 1) + 2 * l(y) + l(y + 1) + 2) >> 2) as u8; + } + out.left[7] = ((l(6) + 3 * l(7) + 2) >> 2) as u8; + } + out +} + +/// Predict an 8x8 luma block (spec 8.3.2.2.2 - 8.3.2.2.10) into `out` in raster +/// order. `n` must already be filtered by [`filter_nbr8`]. +// x and y are sample coordinates that also index the neighbour runs; the +// clause's index arithmetic is what the loops spell out. +#[allow(clippy::needless_range_loop)] +pub fn pred_8x8(mode: u8, n: &Nbr8, out: &mut [u8; 64]) { + let t = |x: i32| i32::from(n.top[x as usize]); + let l = |y: i32| i32::from(n.left[y as usize]); + let tl = i32::from(n.top_left); + // Index -1 of either run is the corner sample. + let te = |i: i32| if i < 0 { tl } else { t(i) }; + let le = |i: i32| if i < 0 { tl } else { l(i) }; + match mode { + // Vertical (8-89). + 0 => { + for y in 0..8 { + out[y * 8..y * 8 + 8].copy_from_slice(&n.top[..8]); + } + } + // Horizontal (8-90). + 1 => { + for y in 0..8 { + out[y * 8..y * 8 + 8].fill(n.left[y]); + } + } + // DC (8-91..8-94). + 2 => { + let sum_t: i32 = (0..8).map(t).sum(); + let sum_l: i32 = (0..8).map(l).sum(); + let v = match (n.have_top, n.have_left) { + (true, true) => (sum_t + sum_l + 8) >> 4, + (true, false) => (sum_t + 4) >> 3, + (false, true) => (sum_l + 4) >> 3, + (false, false) => 128, + }; + out.fill(v as u8); + } + // Diagonal down-left (8-95, 8-96). + 3 => { + for y in 0..8i32 { + for x in 0..8i32 { + let v = if x == 7 && y == 7 { + (t(14) + 3 * t(15) + 2) >> 2 + } else { + (t(x + y) + 2 * t(x + y + 1) + t(x + y + 2) + 2) >> 2 + }; + out[(y * 8 + x) as usize] = v as u8; + } + } + } + // Diagonal down-right (8-97..8-99). + 4 => { + for y in 0..8i32 { + for x in 0..8i32 { + let v = if x > y { + (te(x - y - 2) + 2 * te(x - y - 1) + t(x - y) + 2) >> 2 + } else if x < y { + (le(y - x - 2) + 2 * le(y - x - 1) + l(y - x) + 2) >> 2 + } else { + (t(0) + 2 * tl + l(0) + 2) >> 2 + }; + out[(y * 8 + x) as usize] = v as u8; + } + } + } + // Vertical-right (8-100..8-103). + 5 => { + for y in 0..8i32 { + for x in 0..8i32 { + let z = 2 * x - y; + let i = x - (y >> 1); + let v = if z >= 0 && z % 2 == 0 { + (te(i - 1) + te(i) + 1) >> 1 + } else if z >= 0 { + (te(i - 2) + 2 * te(i - 1) + te(i) + 2) >> 2 + } else if z == -1 { + (l(0) + 2 * tl + t(0) + 2) >> 2 + } else { + (l(y - 2 * x - 1) + 2 * l(y - 2 * x - 2) + le(y - 2 * x - 3) + 2) >> 2 + }; + out[(y * 8 + x) as usize] = v as u8; + } + } + } + // Horizontal-down (8-104..8-107). + 6 => { + for y in 0..8i32 { + for x in 0..8i32 { + let z = 2 * y - x; + let i = y - (x >> 1); + let v = if z >= 0 && z % 2 == 0 { + (le(i - 1) + le(i) + 1) >> 1 + } else if z >= 0 { + (le(i - 2) + 2 * le(i - 1) + le(i) + 2) >> 2 + } else if z == -1 { + (l(0) + 2 * tl + t(0) + 2) >> 2 + } else { + (t(x - 2 * y - 1) + 2 * t(x - 2 * y - 2) + te(x - 2 * y - 3) + 2) >> 2 + }; + out[(y * 8 + x) as usize] = v as u8; + } + } + } + // Vertical-left (8-108, 8-109). + 7 => { + for y in 0..8i32 { + for x in 0..8i32 { + let i = x + (y >> 1); + let v = if y % 2 == 0 { + (t(i) + t(i + 1) + 1) >> 1 + } else { + (t(i) + 2 * t(i + 1) + t(i + 2) + 2) >> 2 + }; + out[(y * 8 + x) as usize] = v as u8; + } + } + } + // Horizontal-up (8-110..8-113). + _ => { + for y in 0..8i32 { + for x in 0..8i32 { + let z = x + 2 * y; + let i = y + (x >> 1); + let v = if z < 13 && z % 2 == 0 { + (l(i) + l(i + 1) + 1) >> 1 + } else if z < 13 { + (l(i) + 2 * l(i + 1) + l(i + 2) + 2) >> 2 + } else if z == 13 { + (l(6) + 3 * l(7) + 2) >> 2 + } else { + l(7) + }; + out[(y * 8 + x) as usize] = v as u8; + } + } + } + } +} + /// A borrowed window into a picture plane for whole-MB prediction: `data` /// spans the plane, `stride` its pitch, `origin` the index of this MB's /// top-left sample. @@ -324,10 +534,103 @@ pub fn add_residual_4x4(data: &mut [u8], stride: usize, origin: usize, r: &[i32; } } +/// Add an 8x8 residual to the plane with clamping (spec 8.5.13 / picture +/// construction). +#[inline] +pub fn add_residual_8x8(data: &mut [u8], stride: usize, origin: usize, r: &[i32; 64]) { + for y in 0..8 { + let row = origin + y * stride; + for x in 0..8 { + let p = i32::from(data[row + x]) + r[y * 8 + x]; + data[row + x] = p.clamp(0, 255) as u8; + } + } +} + #[cfg(test)] mod tests { use super::*; + /// A constant neighbourhood survives the reference filter and every 8x8 + /// mode reproduces it: the filters are normalised (1+2+1)/4 and the modes + /// are weighted averages of the same samples. + #[test] + fn constant_neighbourhood_is_a_fixed_point() { + let n = Nbr8 { + top: [77; 16], + left: [77; 8], + top_left: 77, + have_top: true, + have_left: true, + have_tl: true, + }; + let f = filter_nbr8(&n); + assert_eq!(f.top, [77; 16]); + assert_eq!(f.left, [77; 8]); + assert_eq!(f.top_left, 77); + for mode in 0..9u8 { + let mut out = [0u8; 64]; + pred_8x8(mode, &f, &mut out); + assert!(out.iter().all(|&v| v == 77), "mode {mode}: {out:?}"); + } + } + + /// The reference filter of 8.3.2.2.1 with the corner unavailable uses the + /// 3:1 end taps, and never runs over a run that is not wholly available. + #[test] + fn reference_filter_edges() { + let mut top = [0u8; 16]; + for (x, t) in top.iter_mut().enumerate() { + *t = (x * 4) as u8; + } + let n = Nbr8 { + top, + left: [100; 8], + top_left: 9, + have_top: true, + have_left: false, + have_tl: false, + }; + let f = filter_nbr8(&n); + // No left run: p'[0, -1] takes 8-79, and the left column is untouched. + // 8-79 with p[0, -1] = 0 and p[1, -1] = 4. + assert_eq!(f.top[0], ((4 + 2) >> 2) as u8); + // 8-80 over p[0..2, -1] = 0, 4, 8. + assert_eq!(f.top[1], ((2 * 4 + 8 + 2) >> 2) as u8); + assert_eq!(f.top[15], ((56 + 3 * 60 + 2) >> 2) as u8); + assert_eq!(f.left, [100; 8]); + assert_eq!(f.top_left, 9); + // DC with no left run averages the top run alone (8-93). + let mut out = [0u8; 64]; + pred_8x8(2, &f, &mut out); + let sum: i32 = (0..8).map(|i| i32::from(f.top[i])).sum(); + assert!(out.iter().all(|&v| i32::from(v) == (sum + 4) >> 3)); + } + + /// Vertical and horizontal 8x8 copy the filtered runs. + #[test] + fn vertical_horizontal_8x8() { + let mut top = [0u8; 16]; + for (x, t) in top.iter_mut().enumerate() { + *t = (x * 3) as u8; + } + let n = Nbr8 { + top, + left: [1, 2, 3, 4, 5, 6, 7, 8], + top_left: 0, + have_top: true, + have_left: true, + have_tl: true, + }; + let mut out = [0u8; 64]; + pred_8x8(0, &n, &mut out); + assert_eq!(&out[..8], &n.top[..8]); + assert_eq!(&out[56..], &n.top[..8]); + pred_8x8(1, &n, &mut out); + assert_eq!(out[0], 1); + assert_eq!(out[63], 8); + } + #[test] fn dc_4x4_fallbacks() { let n = Nbr4 { diff --git a/crates/ec-h264/src/tables.rs b/crates/ec-h264/src/tables.rs index 09fba7c8..18c9acfc 100644 --- a/crates/ec-h264/src/tables.rs +++ b/crates/ec-h264/src/tables.rs @@ -503,6 +503,17 @@ pub const NORM_ADJUST_4X4: [[u16; 3]; 6] = [ /// (i % 2, j % 2) == (0,0) -> 0, (1,1) -> 1, else 2 (Equation 8-314). pub const NORM_ADJUST_CLASS_4X4: [u8; 16] = [0, 2, 0, 2, 2, 1, 2, 1, 0, 2, 0, 2, 2, 1, 2, 1]; +/// Equation 8-318: normAdjust8x8 v matrix, rows m = qP % 6, columns the six +/// position classes of Equation 8-317. +pub const NORM_ADJUST_8X8: [[u16; 6]; 6] = [ + [20, 18, 32, 19, 25, 24], + [22, 19, 35, 21, 28, 26], + [26, 23, 42, 24, 33, 31], + [28, 25, 45, 26, 35, 33], + [32, 28, 51, 30, 40, 38], + [36, 32, 58, 34, 46, 43], +]; + /// Table 8-16: alpha' by indexA. pub const ALPHA: [u8; 52] = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, 20, @@ -540,6 +551,10 @@ pub const TC0: [[u8; 52]; 3] = [ /// 4x4 zig-zag scan: scan position -> raster index (Table 8-13, frame scan). pub const ZIGZAG_4X4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; +/// 8x8 zig-zag scan: scan position -> raster index (Table 8-14, frame scan). +/// Shared with the scaling-list parser, which reads the same scan. +pub use ec_h264_syntax::sps::ZIGZAG_8X8; + /// luma4x4BlkIdx -> (x, y) position in 4-sample units within the macroblock /// (spec 6.4.3 inverse 4x4 luma block scan). pub const BLK4_POS: [(u8, u8); 16] = [ diff --git a/crates/ec-h264/src/transform.rs b/crates/ec-h264/src/transform.rs index f595697b..cd7eea3b 100644 --- a/crates/ec-h264/src/transform.rs +++ b/crates/ec-h264/src/transform.rs @@ -1,6 +1,8 @@ -//! Inverse transforms and scaling (spec 8.5.9 - 8.5.12). +//! Inverse transforms and scaling (spec 8.5.9 - 8.5.13). -use crate::tables::{NORM_ADJUST_4X4, NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4}; +use crate::tables::{ + NORM_ADJUST_4X4, NORM_ADJUST_8X8, NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4, ZIGZAG_8X8, +}; /// Per-QP scaling factors for one 4x4 weight list: `LevelScale4x4(m, i, j) = /// weightScale(i, j) * normAdjust4x4(m, i, j)` (Equation 8-313), in raster @@ -50,6 +52,139 @@ pub fn dequant_4x4(block: &mut [i32; 16], ls: &LevelScale4x4, qp: i32, skip_dc: } } +/// Per-QP scaling factors for one 8x8 weight list: `LevelScale8x8(m, i, j) = +/// weightScale8x8(i, j) * normAdjust8x8(m, i, j)` (Equation 8-316), in raster +/// order, for m = qP % 6. +#[derive(Debug, Clone)] +pub struct LevelScale8x8 { + /// `[m][raster]`. + pub scale: [[i32; 64]; 6], +} + +/// `normAdjust8x8` position class of raster position `(i, j)` (Equation 8-317), +/// where `i` is the row and `j` the column. +const fn norm_class_8x8(i: usize, j: usize) -> usize { + let (i4, j4, i2, j2) = (i % 4, j % 4, i % 2, j % 2); + if i4 == 0 && j4 == 0 { + 0 + } else if i2 == 1 && j2 == 1 { + 1 + } else if i4 == 2 && j4 == 2 { + 2 + } else if (i4 == 0 && j2 == 1) || (i2 == 1 && j4 == 0) { + 3 + } else if (i4 == 0 && j4 == 2) || (i4 == 2 && j4 == 0) { + 4 + } else { + 5 + } +} + +impl LevelScale8x8 { + /// Build from a raster-order 8x8 weight list (flat 16s when no scaling + /// matrix is in force). + pub fn new(weight: &[u8; 64]) -> LevelScale8x8 { + let mut scale = [[0i32; 64]; 6]; + for (m, row) in scale.iter_mut().enumerate() { + for (idx, s) in row.iter_mut().enumerate() { + let class = norm_class_8x8(idx / 8, idx % 8); + *s = i32::from(weight[idx]) * i32::from(NORM_ADJUST_8X8[m][class]); + } + } + LevelScale8x8 { scale } + } +} + +/// Scale an 8x8 luma block in place (spec 8.5.13.1), raster order. +#[inline] +pub fn dequant_8x8(block: &mut [i32; 64], ls: &LevelScale8x8, qp: i32) { + let scale = &ls.scale[(qp % 6) as usize]; + if qp >= 36 { + let sh = (qp / 6 - 6) as u32; + for i in 0..64 { + block[i] = (block[i] * scale[i]) << sh; + } + } else { + let sh = (6 - qp / 6) as u32; + let round = 1i32 << (5 - qp / 6); + for i in 0..64 { + block[i] = (block[i] * scale[i] + round) >> sh; + } + } +} + +/// Place scan-order coefficients of an 8x8 block into raster order using the +/// 8x8 zig-zag (Table 8-14). +#[inline] +pub fn unzigzag_8x8(scan: &[i32; 64], out: &mut [i32; 64]) { + for (s, &raster) in ZIGZAG_8X8.iter().enumerate() { + out[raster as usize] = scan[s]; + } +} + +/// One pass of the 8x8 inverse core transform (Equations 8-358 to 8-381) over +/// eight values. +#[inline] +fn idct8_1d(d: [i32; 8]) -> [i32; 8] { + let e = [ + d[0] + d[4], + -d[3] + d[5] - d[7] - (d[7] >> 1), + d[0] - d[4], + d[1] + d[7] - d[3] - (d[3] >> 1), + (d[2] >> 1) - d[6], + -d[1] + d[7] + d[5] + (d[5] >> 1), + d[2] + (d[6] >> 1), + d[3] + d[5] + d[1] + (d[1] >> 1), + ]; + let f = [ + e[0] + e[6], + e[1] + (e[7] >> 2), + e[2] + e[4], + e[3] + (e[5] >> 2), + e[2] - e[4], + (e[3] >> 2) - e[5], + e[0] - e[6], + e[7] - (e[1] >> 2), + ]; + [ + f[0] + f[7], + f[2] + f[5], + f[4] + f[3], + f[6] + f[1], + f[6] - f[1], + f[4] - f[3], + f[2] - f[5], + f[0] - f[7], + ] +} + +/// Inverse 8x8 core transform (spec 8.5.13.2): raster-order input `d`, output +/// residuals `r` including the final `(x + 32) >> 6`. +pub fn inverse_transform_8x8(d: &[i32; 64], r: &mut [i32; 64]) { + let mut g = [0i32; 64]; + for i in 0..8 { + let o = i * 8; + let row: [i32; 8] = d[o..o + 8].try_into().expect("eight coefficients"); + g[o..o + 8].copy_from_slice(&idct8_1d(row)); + } + for j in 0..8 { + let col = [ + g[j], + g[8 + j], + g[16 + j], + g[24 + j], + g[32 + j], + g[40 + j], + g[48 + j], + g[56 + j], + ]; + let m = idct8_1d(col); + for (i, &v) in m.iter().enumerate() { + r[i * 8 + j] = (v + 32) >> 6; + } + } +} + /// Place scan-order coefficients into raster order using the 4x4 zig-zag. #[inline] pub fn unzigzag(scan: &[i32; 16], out: &mut [i32; 16]) { diff --git a/crates/ec-h264/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs index 8d1a1f52..619ae22d 100644 --- a/crates/ec-h264/tests/conformance.rs +++ b/crates/ec-h264/tests/conformance.rs @@ -866,34 +866,6 @@ fn refusals_name_a_feature_the_stream_really_uses() { ], "frame_mbs_only_flag 0", ), - ( - "transform8x8", - &[ - "-profile:v", - "high", - "-qp", - "26", - "-x264-params", - "cabac=0:8x8dct=1", - ], - "8x8 transform", - ), - // The 8x8 transform is refused under CABAC too, where the flag is a - // context-coded bin rather than a raw one. - ( - "transform8x8-cabac", - &[ - "-profile:v", - "high", - "-qp", - "26", - "-coder", - "ac", - "-x264-params", - "8x8dct=1", - ], - "8x8 transform", - ), ( "yuv422", &[ @@ -1735,6 +1707,94 @@ fn extract_annexb(src: &Path, dst: &Path, frames: usize) -> bool { ) } +/// The same comparison, but demuxed from the container by [`ec_mp4`] instead +/// of extracted to Annex B by ffmpeg's bitstream filter. +/// +/// Some real MP4s produce an elementary stream that ffmpeg itself then decodes +/// only three frames of, silently. That is a property of the extraction, not of +/// the file: reading the sample table directly and handing the `avcC` and the +/// length-prefixed samples to the packet entry surface leaves the oracle able to +/// decode the original file, so the comparison is real again. +fn compare_container_streamed( + source: &Path, + frames_wanted: usize, +) -> Result { + use ec_core::registry::{Decoder as _, Demuxer as _}; + use std::io::Read; + + let file = std::fs::File::open(source).map_err(|e| e.to_string())?; + let mut demux = ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)) + .map_err(|e| format!("ec-mp4 open: {e}"))?; + let (stream_index, params) = demux + .streams() + .iter() + .find(|s| s.params.codec == ec_core::registry::CodecId::H264) + .map(|s| (s.index, s.params.clone())) + .ok_or("no H.264 track")?; + let mut dec = ec_h264::H264Decoder::new(params).map_err(|e| format!("{e}"))?; + + let mut child = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(source) + .args([ + "-map", + "0:v:0", + "-frames:v", + &frames_wanted.to_string(), + "-f", + "rawvideo", + "-pix_fmt", + "yuv420p", + "-", + ]) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .spawn() + .map_err(|e| e.to_string())?; + let mut out = child.stdout.take().expect("piped stdout"); + + let mut reference = Vec::new(); + let mut result = StreamedResult::default(); + let mut oracle_open = true; + let mut take = |frame: Vec, result: &mut StreamedResult, reference: &mut Vec| { + result.produced += 1; + if !oracle_open || result.compared >= frames_wanted { + return; + } + reference.resize(frame.len(), 0); + if out.read_exact(reference).is_err() { + oracle_open = false; + return; + } + if let Some(pos) = first_diff(&frame, reference) { + result.diffs.push((result.compared, pos)); + } + result.compared += 1; + }; + let mut drain = + |dec: &mut ec_h264::H264Decoder, result: &mut StreamedResult, reference: &mut Vec| { + while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { + take(frame_bytes(&f), result, reference); + } + }; + while result.produced < frames_wanted { + let packet = match demux.next_packet() { + Ok(p) => p, + Err(_) => break, + }; + if packet.stream != stream_index { + continue; + } + dec.send_packet(&packet).map_err(|e| format!("{e}"))?; + drain(&mut dec, &mut result, &mut reference); + } + dec.flush().map_err(|e| format!("{e}"))?; + drain(&mut dec, &mut result, &mut reference); + let _ = child.kill(); + let _ = child.wait(); + Ok(result) +} + /// Decode real H.264 files from this machine's library, several hundred frames /// each, frame for frame against ffmpeg. /// @@ -1802,15 +1862,47 @@ fn real_library_streams_match_ffmpeg() { r.compared )); } - // The oracle stopped before we did. That is ffmpeg giving up on the - // elementary stream the bitstream filter produced, not a claim about - // this decoder, so the file is reported and not counted either way. + // The oracle stopped before we did: ffmpeg gave up on the elementary + // stream its own bitstream filter produced. That is a property of + // the extraction, so the file is re-run straight out of the + // container, where the oracle can read the original samples. Ok(r) if r.compared < r.produced.min(MIN_FRAMES) => { - table.push_str(&format!( - "{name:<40} {container:<12} {width:>5}px oracle short: ffmpeg gave \ - {} frames, we decoded {}\n", - r.compared, r.produced - )); + match compare_container_streamed(Path::new(path), FRAMES) { + Ok(c) if !c.diffs.is_empty() => { + failures.push(format!( + "{name} (container demux): {} of {} frames differ", + c.diffs.len(), + c.compared + )); + table.push_str(&format!( + "{name:<40} {container:<12} {width:>5}px MISMATCH {} of {} \ + (container demux)\n", + c.diffs.len(), + c.compared + )); + } + Ok(c) if c.compared >= MIN_FRAMES => { + decoded += 1; + table.push_str(&format!( + "{name:<40} {container:<12} {width:>5}px {:>4} frames bit-exact \ + (container demux)\n", + c.compared + )); + } + Ok(c) => { + table.push_str(&format!( + "{name:<40} {container:<12} {width:>5}px oracle short both ways: \ + ffmpeg gave {} frames, we decoded {}\n", + c.compared, c.produced + )); + } + Err(e) => { + table.push_str(&format!( + "{name:<40} {container:<12} {width:>5}px oracle short, container \ + demux failed: {e}\n" + )); + } + } } Ok(r) => { decoded += 1; @@ -1989,3 +2081,167 @@ fn spatial_direct_over_a_b_reference_matches_ffmpeg() { let _ = std::fs::remove_dir_all(&dir); assert!(failures.is_empty(), "{failures:#?}"); } + +/// True when the stream's picture parameter set enables the 8x8 transform. +/// +/// Without this the sweep below would silently prove nothing: an encoder that +/// quietly dropped back to 4x4 would pass every comparison while never coding +/// a single transform_size_8x8_flag. +fn pps_enables_8x8(stream: &Path) -> bool { + let bytes = std::fs::read(stream).unwrap_or_default(); + let mut rbsp = Vec::new(); + let mut sps = None; + for nal in ec_h264_syntax::AnnexBIter::new(&bytes) { + let Some((&header, payload)) = nal.split_first() else { + continue; + }; + let Ok(h) = ec_h264_syntax::NalHeader::parse(header) else { + continue; + }; + ec_h264_syntax::unescape_rbsp(payload, &mut rbsp); + match h.unit_type { + ec_h264_syntax::NalUnitType::Sps => sps = ec_h264_syntax::Sps::parse(&rbsp).ok(), + ec_h264_syntax::NalUnitType::Pps => { + if let Ok(p) = ec_h264_syntax::Pps::parse(&rbsp, |_| sps.as_ref()) { + return p.transform_8x8_mode; + } + } + _ => {} + } + } + false +} + +/// The High-profile 8x8 transform, which every real-world encoder turns on by +/// default: transform_size_8x8_flag, Intra_8x8 prediction with its reference +/// filter (8.3.2), the 8x8 residual under both entropy coders and the 8x8 +/// inverse transform of 8.5.13. +/// +/// The quantiser sweep matters twice over here: the 8x8 dequant ladder of +/// 8.5.13.1 has its own rounding branch at QP 36, and under CABAC the whole +/// ctxIdx 402..435 initialisation is a function of SliceQPY. +#[test] +fn high_profile_8x8_matches_ffmpeg() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = scratch("high8x8"); + let mut failures = Vec::new(); + // High profile with the 8x8 transform forced on, in both entropy coders. + let modes: [(&str, &[&str]); 2] = [ + ("cabac", &["-profile:v", "high", "-coder", "ac"]), + ("cavlc", &["-profile:v", "high", "-coder", "0"]), + ]; + for (mode, profile) in modes { + let mut checked = 0usize; + for qp in 1..=51u32 { + let mut extra = profile.to_vec(); + let qp_string = qp.to_string(); + extra.extend(["-qp", &qp_string, "-x264-params", "8x8dct=1:i8x8=1"]); + let tag = format!("i8-{mode}-q{qp}"); + match round_trip(&dir, &tag, "176x144", &extra) { + Ok(0) => { + assert!( + pps_enables_8x8(&dir.join(format!("{tag}.264"))), + "{tag}: encoder did not enable the 8x8 transform" + ); + checked += 1; + } + Ok(n) => failures.push(format!("intra {mode} qp {qp}: {n} bytes differ")), + Err(e) => failures.push(e), + } + } + assert!( + checked >= 40, + "too few {mode} quantisers exercised: {checked}" + ); + eprintln!("8x8 intra {mode}: {checked} quantisers bit-exact against ffmpeg"); + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +} + +/// The same transform in inter macroblocks: P and B partitions carry the flag +/// only when no 8x8 is split further (7.3.5), the residual rides the inter +/// scaling list, and the deblocker must leave the internal 4-sample edges of an +/// 8x8 macroblock alone (8.7). +#[test] +fn high_profile_8x8_inter_sequences_match_ffmpeg() { + if !have_ffmpeg() { + eprintln!("SKIP: ffmpeg not on PATH"); + return; + } + let dir = scratch("high8x8-seq"); + let mut failures = Vec::new(); + let cases: &[(&str, &[&str])] = &[ + ( + "p-cabac", + &["-profile:v", "high", "-coder", "ac", "-bf", "0"], + ), + ( + "p-cavlc", + &["-profile:v", "high", "-coder", "0", "-bf", "0"], + ), + ( + "b-cabac", + &[ + "-profile:v", + "high", + "-coder", + "ac", + "-bf", + "2", + "-x264-params", + "b-adapt=0", + ], + ), + ( + "b-cavlc", + &[ + "-profile:v", + "high", + "-coder", + "0", + "-bf", + "2", + "-x264-params", + "b-adapt=0", + ], + ), + // Sub-8x8 partitions: every macroblock that splits below 8x8 must not + // carry the flag, and the neighbouring context has to agree. + ( + "subpart", + &[ + "-profile:v", + "high", + "-coder", + "ac", + "-bf", + "0", + "-x264-params", + "partitions=all:8x8dct=1", + ], + ), + ]; + for (tag, extra) in cases { + let mut args = extra.to_vec(); + args.extend(["-qp", "26"]); + match x264_encode_gop(&dir, tag, "176x144", 12, &args) { + None => failures.push(format!("{tag}: ffmpeg cannot encode")), + Some(stream) => match compare_sequence(&stream) { + Ok(n) => { + assert!( + pps_enables_8x8(&stream), + "{tag}: encoder did not enable the 8x8 transform" + ); + eprintln!("8x8 {tag}: {n} frames bit-exact"); + } + Err(e) => failures.push(format!("{tag}: {e}")), + }, + } + } + let _ = std::fs::remove_dir_all(&dir); + assert!(failures.is_empty(), "{failures:#?}"); +}