From 655dfcc5224f6bad2b89007ebbf22abd11464857 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 21 Aug 2026 01:41:32 +0300 Subject: [PATCH] feat(h264-enc): transform_size_8x8_flag emission + cat-5 / interleaved-CAVLC 8x8 residual writers (E3) Flag written (always 0 for now) wherever the decoder reads it under transform_8x8_mode_flag; CABAC residual_block_8x8 mirrors the decoder's cat-5 path (no coded_block_flag for 4:2:0); CAVLC sub_block_4x4 interleave helper. Round-trip unit tests through the decoder's own readers; encode integration tests gain transform_8x8=true variants. --- crates/ec-h264/src/cabac.rs | 8 +- crates/ec-h264/src/enc/cabac_enc.rs | 111 ++++++++++++++++++++++++++-- crates/ec-h264/src/enc/entropy.rs | 27 +++++++ crates/ec-h264/src/enc/mb.rs | 12 +++ crates/ec-h264/src/enc/mod.rs | 1 + crates/ec-h264/src/enc/vlc.rs | 38 ++++++++++ crates/ec-h264/src/entropy.rs | 7 ++ crates/ec-h264/tests/encode.rs | 15 ++-- 8 files changed, 202 insertions(+), 17 deletions(-) diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index c237fef5..348bb70d 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -61,12 +61,12 @@ pub(crate) const OFF_CBF: usize = 85; pub(crate) const OFF_SIG: usize = 105; pub(crate) const OFF_LAST: usize = 166; pub(crate) const OFF_ABS: usize = 227; -const OFF_TRANSFORM_8X8: usize = 399; +pub(crate) 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; +pub(crate) const OFF_SIG_8X8: usize = 402; +pub(crate) const OFF_LAST_8X8: usize = 417; +pub(crate) 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, diff --git a/crates/ec-h264/src/enc/cabac_enc.rs b/crates/ec-h264/src/enc/cabac_enc.rs index 44b28435..10562570 100644 --- a/crates/ec-h264/src/enc/cabac_enc.rs +++ b/crates/ec-h264/src/enc/cabac_enc.rs @@ -20,12 +20,15 @@ use ec_core::BitWriter; use crate::cabac::{ - ABS_CAT_OFF, CBF_CAT_OFF, I_MB_TYPE_CTX, I_SUFFIX_CTX_P, NUM_CTX, OFF_ABS, OFF_CBF, - OFF_CBP_CHROMA, OFF_CBP_LUMA, OFF_CHROMA_PRED, OFF_LAST, OFF_MB_TYPE, OFF_MB_TYPE_P, OFF_MVD, - OFF_PREV_I4, OFF_QP_DELTA, OFF_REM_I4, OFF_SIG, OFF_SKIP_P, SIG_CAT_OFF, init_contexts, - qp_delta_inc, sig_inc, + ABS_CAT_OFF, CBF_CAT_OFF, I_MB_TYPE_CTX, I_SUFFIX_CTX_P, NUM_CTX, OFF_ABS, OFF_ABS_8X8, + OFF_CBF, OFF_CBP_CHROMA, OFF_CBP_LUMA, OFF_CHROMA_PRED, OFF_LAST, OFF_LAST_8X8, OFF_MB_TYPE, + OFF_MB_TYPE_P, OFF_MVD, OFF_PREV_I4, OFF_QP_DELTA, OFF_REM_I4, OFF_SIG, OFF_SIG_8X8, + OFF_SKIP_P, OFF_TRANSFORM_8X8, SIG_CAT_OFF, init_contexts, qp_delta_inc, sig_inc, +}; +use crate::cabac_tables::{LAST_8X8, SIG_8X8_FRAME}; +use crate::entropy::{ + BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8, MbCtx, MbInfo, }; -use crate::entropy::{BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_INTER, FLAG_PCM, MbCtx, MbInfo}; /// The arithmetic encoder of 9.3.4 plus the context state. pub(crate) struct CabacEnc { @@ -385,6 +388,38 @@ impl CabacEnc { } } + /// transform_size_8x8_flag (9.3.3.1.1.10), mirroring the decoder's + /// neighbour condition: available and carrying the flag itself. + pub(crate) fn transform_size_8x8_flag(&mut self, flag: bool) { + 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); + self.decision(OFF_TRANSFORM_8X8 + inc, flag); + } + + /// One luma 8x8 residual block in 8x8 zigzag order (ctxBlockCat 5). No + /// coded_block_flag: for 4:2:0 the coded_block_pattern bit is the whole + /// signal (7.3.5.3.3), so an all-zero block must not reach here. + pub(crate) fn residual_block_8x8(&mut self, coeff: &[i32; 64]) -> u8 { + let last = (0..64) + .rev() + .find(|&i| coeff[i] != 0) + .expect("an 8x8 block with cbp set has a coefficient"); + for i in 0..63 { + let significant = coeff[i] != 0; + self.decision(OFF_SIG_8X8 + usize::from(SIG_8X8_FRAME[i]), significant); + if significant { + self.decision(OFF_LAST_8X8 + usize::from(LAST_8X8[i]), i == last); + if i == last { + break; + } + } + } + self.encode_levels(coeff, last, OFF_ABS_8X8, false) + } + /// One residual block in scan order (7.3.5.3.3): coded_block_flag, the /// significance map, then the levels highest scanning position first. /// @@ -397,6 +432,7 @@ impl CabacEnc { na: Option, nb: Option, ) -> u8 { + debug_assert!(cat != BlockCat::Luma8x8, "cat 5 goes through residual_block_8x8"); let cat_i = cat.ctx_block_cat(); let max = cat.max_num_coeff(); let last = (0..max).rev().find(|&i| coeff[i] != 0); @@ -436,9 +472,13 @@ impl CabacEnc { } } - // Levels, highest scanning position first (9.3.3.1.3 counters). - let abs_base = OFF_ABS + ABS_CAT_OFF[cat_i]; - let chroma_dc = cat_i == 3; + self.encode_levels(coeff, last, OFF_ABS + ABS_CAT_OFF[cat_i], cat_i == 3) + } + + /// coeff_abs_level_minus1 and coeff_sign_flag of `coeff[..=last]`, highest + /// scanning position first (9.3.3.1.3 counters). Returns the number of + /// levels written. + fn encode_levels(&mut self, coeff: &[i32], last: usize, abs_base: usize, chroma_dc: bool) -> u8 { let mut num_eq1 = 0u32; let mut num_gt1 = 0u32; let mut total = 0u8; @@ -530,4 +570,59 @@ mod tests { assert!(dec.more_macroblocks().expect("terminate"), "bin {i} end"); } } + + /// transform_size_8x8_flag under every neighbour combination and ctxBlockCat + /// 5 blocks over a spread of densities and magnitudes all decode back + /// through the decoder's own syntax readers. + #[test] + fn cat5_blocks_and_transform_flag_round_trip() { + let mut state = 0x9E37_79B9u32; + let mut rand = move |m: u32| { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state % m + }; + let nbr = |t: bool| MbInfo { + flags: if t { FLAG_TRANS8X8 } else { 0 }, + cbp: 0, + dc_cbf: 0, + }; + let mut plan: Vec<(MbCtx, bool, [i32; 64])> = Vec::new(); + for n in 0..300 { + let ctx = MbCtx { + a: [None, Some(nbr(false)), Some(nbr(true))][rand(3) as usize], + b: [None, Some(nbr(false)), Some(nbr(true))][rand(3) as usize], + qp_delta_inc: 0, + }; + let mut c = [0i32; 64]; + let density = [1, 3, 8, 20, 64][rand(5) as usize]; + let mag = [1, 2, 5, 40, 3000][rand(5) as usize]; + for _ in 0..density { + let v = rand(mag) as i32 + 1; + c[rand(64) as usize] = if rand(2) == 0 { v } else { -v }; + } + c[if n % 7 == 0 { 63 } else { 0 }] = 1; // non-empty; exercise the last position + plan.push((ctx, rand(2) == 1, c)); + } + let mut enc = CabacEnc::new(BitWriter::new(), 30, 0); + for (ctx, flag, c) in &plan { + enc.begin_mb(ctx); + enc.transform_size_8x8_flag(*flag); + let tc = enc.residual_block_8x8(c); + assert_eq!(usize::from(tc), c.iter().filter(|&&v| v != 0).count()); + enc.not_end_of_slice(); + } + let bytes = enc.finish().into_bytes(); + + let mut dec = Cabac::new(&bytes, 0, 30, 0).expect("decoder starts"); + for (i, (ctx, flag, c)) in plan.iter().enumerate() { + dec.begin_mb(ctx); + assert_eq!(dec.transform_size_8x8_flag().expect("flag"), *flag, "flag {i}"); + let mut got = [0i32; 64]; + dec.residual_block_8x8(&mut got).expect("block"); + assert_eq!(&got[..], &c[..], "block {i}"); + assert!(dec.more_macroblocks().expect("terminate"), "block {i} end"); + } + } } diff --git a/crates/ec-h264/src/enc/entropy.rs b/crates/ec-h264/src/enc/entropy.rs index 017a98cd..01141e70 100644 --- a/crates/ec-h264/src/enc/entropy.rs +++ b/crates/ec-h264/src/enc/entropy.rs @@ -13,6 +13,12 @@ use crate::entropy::{BlockCat, MbCtx}; use super::cabac_enc::CabacEnc; use super::vlc::{write_cbp, write_residual_block}; +/// CAVLC's 4x4 sub-block `j` of an 8x8 block in 8x8 zigzag order (7.3.5.3.1, +/// 8.5.7): coefficient `i` of sub-block `j` is `c8[4 * i + j]`. +pub(crate) fn sub_block_4x4(c8: &[i32; 64], j: usize) -> [i32; 16] { + std::array::from_fn(|i| c8[4 * i + j]) +} + pub(crate) enum EncEntropy { Cavlc { w: BitWriter, @@ -109,6 +115,16 @@ impl EncEntropy { } } + /// `transform_size_8x8_flag` (7.3.5), where the decoder reads it: after + /// mb_type for an Intra_NxN macroblock, after coded_block_pattern for an + /// eligible inter one. + pub(crate) fn transform_size_8x8_flag(&mut self, flag: bool) { + match self { + EncEntropy::Cavlc { w, .. } => w.write_bit(flag), + EncEntropy::Cabac(c) => c.transform_size_8x8_flag(flag), + } + } + pub(crate) fn intra_chroma_pred_mode(&mut self, mode: u8) { match self { EncEntropy::Cavlc { w, .. } => w.write_ue(u32::from(mode)), @@ -141,6 +157,11 @@ impl EncEntropy { /// One residual block in scan order; returns its non-zero count, which the /// caller records for the neighbours. + /// + /// `Luma8x8` (64 coefficients, 8x8 zigzag order) is CABAC only; the decoder + /// records its count in all four 4x4 slots. Under CAVLC the caller writes + /// the four [`sub_block_4x4`] blocks as `Luma4x4`, each with its own nC + /// and its own count (decoder.rs finish_macroblock, CAVLC branch). pub(crate) fn residual_block( &mut self, coeff: &[i32], @@ -148,6 +169,12 @@ impl EncEntropy { na: Option, nb: Option, ) -> u8 { + if cat == BlockCat::Luma8x8 { + let EncEntropy::Cabac(c) = self else { + unreachable!("CAVLC codes an 8x8 block as four interleaved 4x4 blocks"); + }; + return c.residual_block_8x8(coeff.try_into().expect("64 coefficients")); + } match self { EncEntropy::Cavlc { w, .. } => { let nc = if matches!(cat, BlockCat::ChromaDc(_)) { diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 860424bf..24577435 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -71,6 +71,9 @@ pub(crate) struct MbEnc<'a> { /// Lagrangian multiplier in the SATD domain. pub lambda: i32, pub preset: Preset, + /// The PPS carries transform_8x8_mode_flag: transform_size_8x8_flag must + /// be written for every eligible macroblock (7.3.5). + pub transform_8x8: bool, pub ls: LevelScale4x4, /// Neighbourhood of the macroblock being written (CABAC). pub mb_ctx: MbCtx, @@ -1157,6 +1160,10 @@ fn encode_intra_mb( let offset = if p_slice { 5 } else { 0 }; w.mb_type(p_slice, intra_type + offset); if use_i4 { + if e.transform_8x8 { + // corner-cut: always 0 until Intra_8x8 prediction exists (E4). + w.transform_size_8x8_flag(false); + } for blk in 0..16 { let rem = if modes[blk] == pred_modes[blk] { None @@ -1473,6 +1480,11 @@ fn encode_inter_mb( } } w.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false); + // Every shape this encoder emits is 8x8-aligned, so the decoder reads the + // flag whenever luma is coded. corner-cut: always 0 until E4 decides. + if lv.cbp_luma != 0 && e.transform_8x8 { + w.transform_size_8x8_flag(false); + } finish_mb( pic, e, diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index cdcb89f6..562965fa 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -499,6 +499,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { target_qp: job.qp, lambda: lambda_for(job.qp), preset: job.cfg.preset, + transform_8x8: job.cfg.transform_8x8, ls: LevelScale4x4::new(&[16; 16]), mb_ctx: crate::entropy::MbCtx::default(), skip_inc: 0, diff --git a/crates/ec-h264/src/enc/vlc.rs b/crates/ec-h264/src/enc/vlc.rs index dfaa780c..2963d181 100644 --- a/crates/ec-h264/src/enc/vlc.rs +++ b/crates/ec-h264/src/enc/vlc.rs @@ -248,6 +248,44 @@ mod tests { } } + /// An 8x8 block written as four interleaved 4x4 blocks reads back through + /// the decoder's 4x4 path into the same 64 coefficients, with the + /// decoder's reassembly rule (`scan8[4 * i + i4] = scan[i]`). + #[test] + fn interleaved_8x8_round_trips() { + let mut state = 0xC0FF_EE00u32; + let mut rand = move |m: u32| { + state = state.wrapping_mul(1664525).wrapping_add(1013904223); + (state >> 16) % m + }; + for _ in 0..200 { + let mut c8 = [0i32; 64]; + for _ in 0..rand(64) { + let v = rand(70) as i32 + 1; + c8[rand(64) as usize] = if rand(2) == 0 { v } else { -v }; + } + let mut w = BitWriter::new(); + let mut tcs = [0u8; 4]; + for j in 0..4 { + tcs[j] = write_residual_block(&mut w, &super::super::entropy::sub_block_4x4(&c8, j), 16, j as i32 * 3); + } + w.write_bit(true); + w.align_to_byte(); + let bytes = w.into_bytes(); + let mut r = BitCursor::new(&bytes, 0); + let mut got = [0i32; 64]; + for j in 0..4 { + let mut scan = [0i32; 16]; + let tc = residual_block(&mut r, &mut scan, 16, j as i32 * 3).expect("decodes"); + assert_eq!(tc, tcs[j]); + for i in 0..16 { + got[4 * i + j] = scan[i]; + } + } + assert_eq!(got, c8); + } + } + /// Every block this writer emits decodes back to the same levels, over a /// spread that covers empty blocks, trailing ones, long runs, the /// suffix-length ladder and the escape codes. diff --git a/crates/ec-h264/src/entropy.rs b/crates/ec-h264/src/entropy.rs index 75baee04..58345e36 100644 --- a/crates/ec-h264/src/entropy.rs +++ b/crates/ec-h264/src/entropy.rs @@ -55,6 +55,11 @@ pub(crate) enum BlockCat { ChromaDc(u8), /// ChromaACLevel, `ctxBlockCat` 4. ChromaAc, + /// LumaLevel8x8, `ctxBlockCat` 5: one 64-coefficient block under + /// transform_size_8x8_flag. CABAC codes it whole (no coded_block_flag for + /// 4:2:0); CAVLC never sees this category, it codes the block as four + /// interleaved `Luma4x4` blocks (7.3.5.3.1). + Luma8x8, } impl BlockCat { @@ -64,6 +69,7 @@ impl BlockCat { BlockCat::LumaDc | BlockCat::Luma4x4 => 16, BlockCat::LumaAc | BlockCat::ChromaAc => 15, BlockCat::ChromaDc(_) => 4, + BlockCat::Luma8x8 => 64, } } @@ -75,6 +81,7 @@ impl BlockCat { BlockCat::Luma4x4 => 2, BlockCat::ChromaDc(_) => 3, BlockCat::ChromaAc => 4, + BlockCat::Luma8x8 => 5, } } } diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index c1469b6b..c52ef299 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -129,11 +129,13 @@ fn reconstruction_matches_the_decoder() { for (w, h) in [(176, 144), (208, 122), (64, 48)] { let mut clip = Clip::new(w, h); for qp in [12, 24, 33, 44] { - for (threads, preset, cabac) in [ - (1usize, Preset::Fast, true), - (4, Preset::Balanced, true), - (1, Preset::Fast, false), - (3, Preset::Balanced, false), + for (threads, preset, cabac, t8x8) in [ + (1usize, Preset::Fast, true, false), + (4, Preset::Balanced, true, false), + (1, Preset::Fast, false, false), + (3, Preset::Balanced, false, false), + (2, Preset::Balanced, true, true), + (2, Preset::Balanced, false, true), ] { let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.qp = qp; @@ -141,6 +143,7 @@ fn reconstruction_matches_the_decoder() { cfg.threads = threads; cfg.preset = preset; cfg.cabac = cabac; + cfg.transform_8x8 = t8x8; let mut enc = Encoder::new(cfg).expect("encoder"); let mut stream = Vec::new(); let mut recons = Vec::new(); @@ -344,9 +347,11 @@ fn ffmpeg_decodes_bit_exactly() { for (w, h) in [(176, 144), (322, 242)] { for qp in [10, 20, 28, 37, 47] { let cavlc = qp % 2 == 0; // both entropy coders across the sweep + let t8x8 = qp % 3 == 1; // High-profile PPS with the per-MB flag let (stream, recons) = encode_clip(w, h, 6, |cfg| { cfg.qp = qp; cfg.cabac = !cavlc; + cfg.transform_8x8 = t8x8; }); let decoded = ffmpeg_decode(&stream, w, h, &[]).expect("ffmpeg decodes our stream"); assert_eq!(decoded.len(), recons.len(), "{w}x{h} qp {qp}: frame count");