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/decoder.rs b/crates/ec-h264/src/decoder.rs index 01f5abb9..12bf028f 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -327,7 +327,9 @@ impl Decoder { .ok_or_else(|| Error::corrupt("active SPS vanished"))?; let pic = core::mem::take(&mut self.cur); let marking = self.has_marking.then_some(&self.cur_marking); - let stored = self.dpb.store(pic, &sps, &self.cur_info, marking, output_ok); + let stored = self + .dpb + .store(pic, &sps, &self.cur_info, marking, output_ok); self.sps_map[sps_id] = Some(sps); stored?; self.has_picture = false; @@ -2309,7 +2311,13 @@ pub(crate) fn gather_nbr4( /// `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 { +pub(crate) 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; diff --git a/crates/ec-h264/src/enc/cabac_enc.rs b/crates/ec-h264/src/enc/cabac_enc.rs index 44b28435..0a76052b 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,10 @@ 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 +475,19 @@ 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 +579,63 @@ 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..d548e929 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(_)) { @@ -166,6 +193,10 @@ impl EncEntropy { } } + pub(crate) fn is_cabac(&self) -> bool { + matches!(self, EncEntropy::Cabac(_)) + } + /// `end_of_slice_flag` after a macroblock (CABAC only). pub(crate) fn end_of_slice(&mut self, last: bool) { if let (EncEntropy::Cabac(c), false) = (self, last) { diff --git a/crates/ec-h264/src/enc/headers.rs b/crates/ec-h264/src/enc/headers.rs index a56cf27f..9fe3784c 100644 --- a/crates/ec-h264/src/enc/headers.rs +++ b/crates/ec-h264/src/enc/headers.rs @@ -26,6 +26,10 @@ pub(crate) struct SeqParams { pub bitrate: u32, /// CABAC, which Baseline does not allow: the sequence is then Main. pub cabac: bool, + /// 8x8 transform (High profile). Forces `profile_idc` 100 with no + /// constraint flags, and the High-profile SPS tail (7.3.2.1.1 subset: + /// 4:2:0 8-bit, no scaling matrices, no transform bypass). + pub transform_8x8: bool, } /// `log2_max_frame_num`, fixed: 8 bits of frame_num wrap far beyond the one @@ -73,10 +77,23 @@ pub(crate) fn write_sps(p: &SeqParams) -> Vec { let mut w = BitWriter::with_capacity(32); // Main when CABAC is in force (Baseline has no CABAC), Baseline otherwise; // constraint_set1_flag says the stream also obeys the Main constraints. - w.write_bits(if p.cabac { 77 } else { 66 }, 8); - w.write_bits(if p.cabac { 0b0100_0000 } else { 0b1100_0000 }, 8); + // 8x8 transform needs High profile (100), which sets no constraint flags. + if p.transform_8x8 { + w.write_bits(100, 8); + w.write_bits(0, 8); + } else { + w.write_bits(if p.cabac { 77 } else { 66 }, 8); + w.write_bits(if p.cabac { 0b0100_0000 } else { 0b1100_0000 }, 8); + } w.write_bits(u32::from(level_idc(p)), 8); w.write_ue(0); // seq_parameter_set_id + if p.transform_8x8 { + w.write_ue(1); // chroma_format_idc: 4:2:0 + w.write_ue(0); // bit_depth_luma_minus8 + w.write_ue(0); // bit_depth_chroma_minus8 + w.write_bit(false); // qpprime_y_zero_transform_bypass_flag + w.write_bit(false); // seq_scaling_matrix_present_flag + } w.write_ue(LOG2_MAX_FRAME_NUM - 4); w.write_ue(2); // pic_order_cnt_type 2: output order is decode order w.write_ue(1); // max_num_ref_frames @@ -114,7 +131,7 @@ pub(crate) fn write_sps(p: &SeqParams) -> Vec { } /// Write the picture parameter set RBSP (7.3.2.2). -pub(crate) fn write_pps(cabac: bool) -> Vec { +pub(crate) fn write_pps(cabac: bool, transform_8x8: bool) -> Vec { let mut w = BitWriter::with_capacity(8); w.write_ue(0); // pic_parameter_set_id w.write_ue(0); // seq_parameter_set_id @@ -131,6 +148,11 @@ pub(crate) fn write_pps(cabac: bool) -> Vec { w.write_bit(false); // deblocking_filter_control_present_flag w.write_bit(false); // constrained_intra_pred_flag w.write_bit(false); // redundant_pic_cnt_present_flag + if transform_8x8 { + w.write_bit(true); // transform_8x8_mode_flag + w.write_bit(false); // pic_scaling_matrix_present_flag + w.write_se(0); // second_chroma_qp_index_offset + } trailing(&mut w); w.into_bytes() } @@ -199,6 +221,7 @@ mod tests { timing: (1000, 60000), bitrate: 8_000_000, cabac: true, + transform_8x8: false, } } @@ -206,15 +229,18 @@ mod tests { /// parser reads back, geometry, cropping, profile and entropy coder alike. #[test] fn parameter_sets_parse_back() { - for (w, h, cabac) in [ - (1920, 1080, true), - (1920, 1080, false), - (640, 480, true), - (854, 482, false), - (16, 16, true), + for (w, h, cabac, t8x8) in [ + (1920, 1080, true, false), + (1920, 1080, false, false), + (640, 480, true, false), + (854, 482, false, false), + (16, 16, true, false), + (640, 480, true, true), + (640, 480, false, true), ] { let mut p = params(w, h); p.cabac = cabac; + p.transform_8x8 = t8x8; let sps = Sps::parse(&write_sps(&p)).expect("SPS parses"); assert_eq!((sps.width, sps.height), (w, h), "{w}x{h} crop"); assert_eq!(sps.mb_width, p.mb_w); @@ -224,10 +250,24 @@ mod tests { assert!(sps.frame_mbs_only); let vui = sps.vui.as_ref().expect("VUI present"); assert_eq!(vui.timing_info, Some((1000, 60000, true))); - assert_eq!(sps.profile_idc, if cabac { 77 } else { 66 }); - let pps = Pps::parse(&write_pps(cabac), |_| Some(&sps)).expect("PPS parses"); + assert_eq!( + sps.profile_idc, + if t8x8 { + 100 + } else if cabac { + 77 + } else { + 66 + } + ); + if t8x8 { + assert_eq!(sps.chroma_format_idc, 1); + assert_eq!(sps.bit_depth_luma, 8); + } + let pps = Pps::parse(&write_pps(cabac, t8x8), |_| Some(&sps)).expect("PPS parses"); assert_eq!(pps.entropy_coding_mode, cabac); assert_eq!(pps.pic_init_qp, 26); + assert_eq!(pps.transform_8x8_mode, t8x8); } } @@ -246,7 +286,7 @@ mod tests { fn slice_header_parses_back() { let p = params(320, 240); let sps = Sps::parse(&write_sps(&p)).unwrap(); - let pps = Pps::parse(&write_pps(true), |_| Some(&sps)).unwrap(); + let pps = Pps::parse(&write_pps(true, false), |_| Some(&sps)).unwrap(); for (idr, slice_type, first_mb, qp) in [ (true, SliceType::I, 0u32, 30i32), (false, SliceType::P, 40, 18), diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 860424bf..72b0f2d4 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -15,24 +15,31 @@ use ec_h264_syntax::SliceType; use wide::i16x16; -use crate::decoder::{MbNeighbors, chroma_nz_pair, gather_nbr4, luma_nz_pair, mb_neighbors}; +use crate::decoder::{ + MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, +}; use crate::dpb::{BLK_SKIP, Picture}; use crate::entropy::{ - BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, MbCtx, MbInfo, + BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8, + MbCtx, MbInfo, }; use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma}; use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd}; -use crate::pred::{PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; +use crate::pred::{ + 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, }; -use super::entropy::EncEntropy; +use super::entropy::{EncEntropy, sub_block_4x4}; use super::quant::{ - forward_4x4, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_chroma_dc, - quant_luma_dc, + forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_8x8, + quant_chroma_dc, quant_luma_dc, }; /// Speed/quality ladder. Two rungs, because the two the incumbent exposed are @@ -71,7 +78,11 @@ 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, + pub ls8: LevelScale8x8, /// Neighbourhood of the macroblock being written (CABAC). pub mb_ctx: MbCtx, /// ctxIdxInc for this macroblock's mb_skip_flag. @@ -82,12 +93,15 @@ pub(crate) struct MbEnc<'a> { } /// Quantised levels of one macroblock, scan order per block. -#[derive(Default)] struct Levels { /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16. luma: [[i32; 16]; 16], /// Non-zero count per luma block, Z-order. luma_nz: [u8; 16], + /// transform_size_8x8_flag: the luma residual is `luma8`, not `luma`. + trans8: bool, + /// Luma 8x8 blocks in 8x8 zig-zag order. + luma8: [[i32; 64]; 4], /// Intra_16x16 luma DC, scan order. dc: [i32; 16], /// Chroma DC per component. @@ -99,6 +113,23 @@ struct Levels { cbp_chroma: u8, } +impl Default for Levels { + fn default() -> Levels { + Levels { + luma: [[0; 16]; 16], + luma_nz: [0; 16], + trans8: false, + luma8: [[0; 64]; 4], + dc: [0; 16], + chroma_dc: [[0; 16]; 2], + chroma: [[[0; 16]; 4]; 2], + chroma_nz: [[0; 4]; 2], + cbp_luma: 0, + cbp_chroma: 0, + } + } +} + /// 4x4 Hadamard sum of absolute transformed differences between the source at /// `(sx, sy)` and a 4x4 prediction. fn satd4(src: &[u8], sstride: usize, sx: usize, sy: usize, pred: &[u8], pstride: usize) -> i32 { @@ -662,10 +693,10 @@ const ZERO_BLOCK_LAMBDA: f64 = 0.4; /// The rate-distortion test behind the per-block zero decision: coding the /// block has to buy more squared error than its bits are worth. -fn worth_coding(source: &[i32; 16], resid: &[i32; 16], levels: &[i32; 16], qp: i32) -> bool { +fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], qp: i32) -> bool { let mut ssd_zero = 0i64; let mut ssd_coded = 0i64; - for i in 0..16 { + for i in 0..source.len() { let z = i64::from(source[i]); let c = i64::from(source[i] - resid[i]); ssd_zero += z * z; @@ -1027,6 +1058,136 @@ fn code_intra_4x4( (modes, pred_modes) } +/// Predicted Intra_8x8 mode of `blk8` (8.3.2.1): the decoder's rule, read +/// from the 4x4 slots every size writes its mode into. +fn predicted_mode8(pic: &Picture, nbr: &MbNeighbors, bx: usize, by: usize, blk8: usize) -> u8 { + let w4 = pic.mb_w * 4; + let left_avail = if blk8.is_multiple_of(2) { nbr.a } else { true }; + let top_avail = if blk8 < 2 { nbr.b } else { true }; + if left_avail && top_avail { + pic.i4_modes[by * w4 + bx - 1].min(pic.i4_modes[(by - 1) * w4 + bx]) + } else { + 2 + } +} + +/// Residual of one 8x8 luma block against the prediction already in the +/// plane: forward transform, quantise, and — when anything survives — +/// reconstruct with the decoder's own inverse. Returns the non-zero count. +fn code_block_8x8( + pic: &mut Picture, + e: &MbEnc<'_>, + x: usize, + y: usize, + qp: i32, + intra: bool, + out: &mut [i32; 64], +) -> u8 { + let stride = pic.y.stride; + let origin = pic.y.at(x, y); + let mut d = [0i32; 64]; + for ry in 0..8 { + for rx in 0..8 { + d[ry * 8 + rx] = i32::from(e.src.y[(y + ry) * e.src.stride + x + rx]) + - i32::from(pic.y.data[origin + ry * stride + rx]); + } + } + let nz = quant_8x8(&forward_8x8(&d), &e.ls8, qp, intra, out); + if nz == 0 { + return 0; + } + let mut raster = [0i32; 64]; + unzigzag_8x8(out, &mut raster); + dequant_8x8(&mut raster, &e.ls8, qp); + let mut resid = [0i32; 64]; + inverse_transform_8x8(&raster, &mut resid); + if !intra && !worth_coding(&d, &resid, out, qp) { + *out = [0; 64]; + return 0; + } + add_residual_8x8(&mut pic.y.data, stride, origin, &resid); + nz +} + +/// Code the luma of an Intra_8x8 macroblock, the 8x8 sibling of +/// [`code_intra_4x4`]: neighbours are the decoder's filtered reference +/// samples, and every 4x4 mode slot of a block carries its mode. +fn code_intra_8x8( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp: i32, + nbr: &MbNeighbors, + lv: &mut Levels, +) -> ([u8; 4], [u8; 4]) { + let w4 = pic.mb_w * 4; + let mut modes = [2u8; 4]; + let mut pred_modes = [2u8; 4]; + lv.trans8 = true; + for blk8 in 0..4 { + let (bx, by) = (mb_x * 4 + (blk8 % 2) * 2, mb_y * 4 + (blk8 / 2) * 2); + let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8); + let predicted = predicted_mode8(pic, nbr, bx, by, blk8); + pred_modes[blk8] = predicted; + let n = filter_nbr8(&gather_nbr8(pic, nbr, blk8, x, y)); + let allowed = modes_allowed(n.have_top, n.have_left, n.have_tl); + let mut best = (i32::MAX, predicted.min(2)); + let mut p = [0u8; 64]; + for mode in 0..9u8 { + if !allowed[mode as usize] { + continue; + } + pred_8x8(mode, &n, &mut p); + let bits = if mode == predicted { 1 } else { 4 }; + let mut c = e.lambda * bits; + for q in 0..4 { + let (ox, oy) = ((q % 2) * 4, (q / 2) * 4); + c += satd4(&e.src.y, e.src.stride, x + ox, y + oy, &p[oy * 8 + ox..], 8); + } + if c < best.0 { + best = (c, mode); + } + } + let mode = best.1; + modes[blk8] = mode; + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + pic.i4_modes[base..base + 2].fill(mode); + } + pred_8x8(mode, &n, &mut p); + let stride = pic.y.stride; + let origin = pic.y.at(x, y); + 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 code_block_8x8(pic, e, x, y, qp, true, &mut lv.luma8[blk8]) > 0 { + lv.cbp_luma |= 1 << blk8; + } + } + (modes, pred_modes) +} + +/// The inter residual under the 8x8 transform, prediction already in the +/// plane: the sibling of [`code_luma_4x4`]. +fn code_luma_8x8( + pic: &mut Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + qp: i32, + lv: &mut Levels, +) { + lv.trans8 = true; + for blk8 in 0..4 { + let (x, y) = (mb_x * 16 + (blk8 % 2) * 8, mb_y * 16 + (blk8 / 2) * 8); + if code_block_8x8(pic, e, x, y, qp, false, &mut lv.luma8[blk8]) > 0 { + lv.cbp_luma |= 1 << blk8; + } + } +} + /// Squared error of the luma macroblock against the source. fn ssd_luma(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { let stride = pic.y.stride; @@ -1061,14 +1222,14 @@ fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) { /// Bits the luma residual and the mode signalling of an intra macroblock cost, /// to the accuracy the mode decision needs. -fn intra_bits(lv: &Levels, i4: Option<(&[u8; 16], &[u8; 16])>) -> i64 { +fn intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 { let mut bits = estimate_luma_bits(lv); match i4 { - // Sixteen mode signals plus the coded_block_pattern the 16x16 form - // derives from its macroblock type instead. + // Sixteen (or four) mode signals plus the coded_block_pattern the + // 16x16 form derives from its macroblock type instead. Some((modes, pred)) => { bits += 6; - for blk in 0..16 { + for blk in 0..modes.len() { bits += if modes[blk] == pred[blk] { 1 } else { 4 }; } } @@ -1102,7 +1263,10 @@ fn encode_intra_mb( let mut lv = Levels::default(); let mut modes = [2u8; 16]; let mut pred_modes = [2u8; 16]; + let mut modes8 = [2u8; 4]; + let mut pred_modes8 = [2u8; 4]; let mut use_i4 = false; + let mut use_i8 = false; if cost.allow_i4 { let mut lv4 = Levels::default(); @@ -1117,12 +1281,37 @@ fn encode_intra_mb( modes4[blk] = pic.i4_modes[(by0 + dy as usize) * w4 + bx0 + dx as usize]; } + // Intra_8x8 on the same terms, when the PPS allows it. + let mut lv8 = Levels::default(); + let mut recon8 = [0u8; 256]; + let cost8 = if e.transform_8x8 { + let (m8, p8) = code_intra_8x8(pic, e, mb_x, mb_y, qp, &nbr, &mut lv8); + modes8 = m8; + pred_modes8 = p8; + save_luma(pic, mb_x, mb_y, &mut recon8); + ssd_luma(pic, e, mb_x, mb_y) as f64 + + lambda_ssd(qp) * intra_bits(&lv8, Some((&m8, &p8))) as f64 + } else { + f64::INFINITY + }; + let mut lv16 = Levels::default(); code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); let cost16 = ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * intra_bits(&lv16, None) as f64; - if cost4 <= cost16 { + if cost8 <= cost4 && cost8 <= cost16 { + use_i4 = true; + use_i8 = true; + restore_luma(pic, mb_x, mb_y, &recon8); + for blk8 in 0..4 { + for dy in 0..2 { + let base = (by0 + (blk8 / 2) * 2 + dy) * w4 + bx0 + (blk8 % 2) * 2; + pic.i4_modes[base..base + 2].fill(modes8[blk8]); + } + } + lv = lv8; + } else if cost4 <= cost16 { use_i4 = true; restore_luma(pic, mb_x, mb_y, &recon4); for blk in 0..16 { @@ -1157,7 +1346,17 @@ fn encode_intra_mb( let offset = if p_slice { 5 } else { 0 }; w.mb_type(p_slice, intra_type + offset); if use_i4 { - for blk in 0..16 { + if e.transform_8x8 { + w.transform_size_8x8_flag(use_i8); + } + // prev_intra8x8_pred_mode_flag / rem_intra8x8_pred_mode share the 4x4 + // elements' binarisation and contexts (9.3.2.2, Table 9-34). + let (modes, pred_modes): (&[u8], &[u8]) = if use_i8 { + (&modes8, &pred_modes8) + } else { + (&modes, &pred_modes) + }; + for blk in 0..modes.len() { let rem = if modes[blk] == pred_modes[blk] { None } else if modes[blk] > pred_modes[blk] { @@ -1223,6 +1422,19 @@ fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { /// Rough bit cost of a macroblock's luma residual. fn estimate_luma_bits(lv: &Levels) -> i64 { let mut bits = 0; + if lv.trans8 { + for blk8 in 0..4 { + if lv.cbp_luma & (1 << blk8) != 0 { + // A level's position costs two more bits in a 64-coefficient + // significance map than in a 16-coefficient one; measured + // against the coded size on the text clip, without this the + // estimate undercharges Intra_8x8 by ~44 bits a macroblock. + let b = &lv.luma8[blk8]; + bits += block_bits(b) + 2 * b.iter().filter(|&&l| l != 0).count() as i64; + } + } + return bits; + } for blk in 0..16 { if lv.cbp_luma & (1 << (blk >> 2)) != 0 { bits += block_bits(&lv.luma[blk]); @@ -1249,12 +1461,7 @@ fn block_bits(b: &[i32]) -> i64 { /// Rough bit cost of a macroblock's residual, for the skip decision: a level /// costs its magnitude's exp-Golomb-ish width, a coded block its token. fn estimate_bits(lv: &Levels) -> i64 { - let mut bits = 10i64; - for blk in 0..16 { - if lv.cbp_luma & (1 << (blk >> 2)) != 0 { - bits += block_bits(&lv.luma[blk]); - } - } + let mut bits = 10 + estimate_luma_bits(lv); if lv.cbp_chroma != 0 { for comp in 0..2 { bits += block_bits(&lv.chroma_dc[comp][..4]); @@ -1407,7 +1614,29 @@ fn encode_inter_mb( let may_skip = choice.prefer_skip; let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y)); let mut lv = Levels::default(); - code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); + if e.transform_8x8 { + // Both transform sizes on the same prediction; the cheaper + // rate-distortion cost is coded. + let mut pred = [0u8; 256]; + save_luma(pic, mb_x, mb_y, &mut pred); + code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); + let cost4 = + ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv) as f64; + let mut recon4 = [0u8; 256]; + save_luma(pic, mb_x, mb_y, &mut recon4); + restore_luma(pic, mb_x, mb_y, &pred); + let mut lv8 = Levels::default(); + code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8); + let cost8 = + ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv8) as f64; + if cost8 < cost4 { + lv = lv8; + } else { + restore_luma(pic, mb_x, mb_y, &recon4); + } + } else { + code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv); + } code_chroma(pic, e, mb_x, mb_y, qp, false, &mut lv); let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0; let skip = match ssd_skip { @@ -1473,6 +1702,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. + if lv.cbp_luma != 0 && e.transform_8x8 { + w.transform_size_8x8_flag(lv.trans8); + } finish_mb( pic, e, @@ -1533,6 +1767,12 @@ fn finish_mb( pic.mb_flags[mb_addr] = FLAG_DECODED | if m.is_i16 { FLAG_I16 } else { 0 } | if m.intra { 0 } else { FLAG_INTER } + // The flag only reaches the stream when the decoder reads it (7.3.5). + | if lv.trans8 && (m.intra || lv.cbp_luma != 0) { + FLAG_TRANS8X8 + } else { + 0 + } | if m.intra && m.chroma_mode != 0 { FLAG_CHROMA_PRED } else { @@ -1549,7 +1789,38 @@ fn finish_mb( let tc = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb); dc_cbf |= u8::from(tc != 0); } + if lv.trans8 { + // The decoder's 8x8 branch: CABAC codes one cat-5 block and reports + // its count in every 4x4 slot; CAVLC codes four interleaved 4x4 + // blocks, each with its own nC and count. + for blk8 in 0..4 { + let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); + if lv.cbp_luma & (1 << blk8) == 0 { + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + pic.nz_y[base..base + 2].fill(0); + } + } else if w.is_cabac() { + let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None); + for dy in 0..2 { + let base = (by + dy) * w4 + bx; + pic.nz_y[base..base + 2].fill(tc.min(16)); + } + } else { + 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 sub = sub_block_4x4(&lv.luma8[blk8], i4); + pic.nz_y[sy * w4 + sx] = w.residual_block(&sub, BlockCat::Luma4x4, na, nb); + } + } + } + } for blk in 0..16 { + if lv.trans8 { + break; + } let (dx, dy) = BLK4_POS[blk]; let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); let group = 1 << (blk >> 2); diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index 7d571fc3..623b44e8 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -35,7 +35,8 @@ use ec_h264_syntax::{SliceType, Sps}; use crate::decoder::deblock_picture; use crate::dpb::{Picture, SliceParams as DeblockParams}; -use crate::transform::LevelScale4x4; +use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8}; +use crate::transform::{LevelScale4x4, LevelScale8x8}; use entropy::EncEntropy; use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps}; @@ -71,6 +72,19 @@ pub struct EncoderConfig { pub threads: usize, /// Quantiser for constant-QP mode (`bitrate` zero). pub qp: i32, + /// 8x8 transform (High profile). Off by default. + /// + /// NOT SAFE TO SET YET: this only flips the SPS/PPS High-profile tail + /// (`profile_idc` 100, `transform_8x8_mode_flag`). Once the PPS carries + /// that flag, a conformant decoder unconditionally reads an extra + /// `transform_size_8x8_flag` per macroblock (7.3.5: every non-I16x16 + /// intra macroblock, and every inter macroblock with a nonzero luma cbp — + /// see `decoder.rs:1151` and `:1789-1793`). Nothing in `enc::entropy` / + /// `enc::mb` writes that bit yet, so turning this on desyncs every real + /// stream (headers.rs's own tests only exercise the parameter sets, not a + /// full encode). Wiring that emission — and then the mode decision that + /// actually picks 8x8 blocks — is later work. + pub transform_8x8: bool, } impl EncoderConfig { @@ -87,6 +101,7 @@ impl EncoderConfig { cabac: true, threads: 0, qp: 26, + transform_8x8: false, } } } @@ -125,6 +140,8 @@ pub struct Encoder { next_id: i32, /// True once a reference picture exists. have_reference: bool, + /// Macroblocks coded with transform_size_8x8_flag set: (intra, inter). + t8x8_mbs: (u64, u64), } /// A picture handed to the encoder: three planes, no padding assumptions. @@ -193,10 +210,11 @@ impl Encoder { timing, bitrate: cfg.bitrate, cabac: cfg.cabac, + transform_8x8: cfg.transform_8x8, }; let sps_rbsp = write_sps(&seq); let sps = Sps::parse(&sps_rbsp)?; - let pps_rbsp = write_pps(cfg.cabac); + let pps_rbsp = write_pps(cfg.cabac, cfg.transform_8x8); let threads = if cfg.threads == 0 { std::thread::available_parallelism().map_or(1, |n| n.get()) } else { @@ -227,11 +245,18 @@ impl Encoder { idr_pic_id: 0, next_id: 0, have_reference: false, + t8x8_mbs: (0, 0), cfg, }) } /// The configuration in force. + /// Macroblocks coded so far with `transform_size_8x8_flag` set, as + /// `(intra, inter)`: the 8x8 transform's share of the stream. + pub fn transform_8x8_mbs(&self) -> (u64, u64) { + self.t8x8_mbs + } + pub fn config(&self) -> &EncoderConfig { &self.cfg } @@ -351,6 +376,15 @@ impl Encoder { for (band, worker) in bands.iter().skip(1).zip(rest.iter()) { merge_band(master, worker, *band); } + for &f in &master.mb_flags { + if f & FLAG_TRANS8X8 != 0 { + if f & FLAG_INTER != 0 { + self.t8x8_mbs.1 += 1; + } else { + self.t8x8_mbs.0 += 1; + } + } + } deblock_picture(master); master.extend_borders(); master.complete = true; @@ -484,7 +518,9 @@ 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]), + ls8: LevelScale8x8::new(&[16; 64]), mb_ctx: crate::entropy::MbCtx::default(), skip_inc: 0, qp_delta_inc: 0, diff --git a/crates/ec-h264/src/enc/quant.rs b/crates/ec-h264/src/enc/quant.rs index 483d405b..bd23233a 100644 --- a/crates/ec-h264/src/enc/quant.rs +++ b/crates/ec-h264/src/enc/quant.rs @@ -11,7 +11,8 @@ //! 16 ~= 2^21`, which is what makes `level = (|c| * MF + f) >> (15 + qp / 6)` //! invert the decoder's dequantisation. -use crate::tables::{NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4}; +use crate::tables::{NORM_ADJUST_CLASS_4X4, ZIGZAG_4X4, ZIGZAG_8X8}; +use crate::transform::LevelScale8x8; /// Quantisation multipliers per `qp % 6`, indexed by the same position class /// as [`NORM_ADJUST_CLASS_4X4`] (0 = even/even, 1 = odd/odd, 2 = mixed). @@ -85,6 +86,112 @@ pub(crate) fn forward_hadamard_2x2(d: &mut [i32; 4]) { d[3] = a - b - c + e; } +/// Forward 8x8 core transform (the exact algebraic inverse of `idct8_1d` / +/// [`crate::transform::inverse_transform_8x8`]), raster in, scaled coefficients +/// out. +/// +/// `idct8_1d`'s matrix `M` (one 1D pass) is not its own transpose-inverse pair +/// the way the 4x4 transform's small butterfly nearly is: `M^T * M` is +/// diagonal but `M * M^T` is not, so a hand-picked small-integer transpose +/// leaks between frequencies by ~15%, which is too much for the ±1-per-sample +/// tolerance this encoder's residuals need (up to ±255, far past the small +/// ranges a 4x4 block sees). [`FWD8`] is `11560 * M^-1`, computed once by +/// exact rational matrix inversion (`M^-1 * M = I` exactly), so applying it in +/// the same row-then-column order `idct8_1d` uses, then the real inverse +/// transform, reproduces the input exactly, scaled by a single known constant +/// (`11560^2 / 64 = 2_088_025`, see [`quant_8x8`]) — no leakage at all, only +/// the ordinary quantiser rounding. +const FWD8: [[i64; 8]; 8] = [ + [1445, 1445, 1445, 1445, 1445, 1445, 1445, 1445], + [1920, 1600, 960, 480, -480, -960, -1600, -1920], + [2312, 1156, -1156, -2312, -2312, -1156, 1156, 2312], + [1600, -480, -1920, -960, 960, 1920, 480, -1600], + [1445, -1445, -1445, 1445, 1445, -1445, -1445, 1445], + [960, -1920, 480, 1600, -1600, -480, 1920, -960], + [1156, -2312, 2312, -1156, -1156, 2312, -2312, 1156], + [480, -960, 1600, -1920, 1920, -1600, 960, -480], +]; + +/// One 1D pass of [`FWD8`] over eight values. +#[inline] +fn fwd8_1d(d: [i64; 8]) -> [i64; 8] { + std::array::from_fn(|i| (0..8).map(|j| FWD8[i][j] * d[j]).sum()) +} + +/// Forward 8x8 transform (raster in, raster out), unnormalised: the caller +/// (`quant_8x8`) divides out the `2_088_025` gain along with the usual +/// per-position quantiser scale. +pub(crate) fn forward_8x8(d: &[i32; 64]) -> [i64; 64] { + let mut g = [0i64; 64]; + for i in 0..8 { + let o = i * 8; + let row: [i64; 8] = std::array::from_fn(|k| i64::from(d[o + k])); + g[o..o + 8].copy_from_slice(&fwd8_1d(row)); + } + let mut r = [0i64; 64]; + 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], + ]; + for (i, v) in fwd8_1d(col).into_iter().enumerate() { + r[i * 8 + j] = v; + } + } + r +} + +/// `raw / denom`, rounded with the same 1/3 (intra) or 1/6 (inter) dead zone +/// as [`round_offset`], expressed as plain division instead of a +/// precomputed shift because [`forward_8x8`]'s coefficients already carry +/// far more headroom than a `<<15`-ish fixed point would give. +#[inline] +fn round_div(raw: i64, denom: i64, intra: bool) -> i64 { + (raw + denom / if intra { 3 } else { 6 }) / denom +} + +/// Quantise an 8x8 [`forward_8x8`] output into scan (zig-zag) order, undoing +/// both the `2_088_025` transform gain and the per-position [`LevelScale8x8`] +/// / QP scale that [`crate::transform::dequant_8x8`] will re-apply. +pub(crate) fn quant_8x8( + coef: &[i64; 64], + ls: &LevelScale8x8, + qp: i32, + intra: bool, + out: &mut [i32; 64], +) -> u8 { + // 11560^2 / 64, see FWD8's doc comment. + const TOTAL_SCALE: i64 = 2_088_025; + let m = (qp % 6) as usize; + let shift = qp / 6; + let p = 6 - shift; // dequant_8x8's exponent, mirrored; qp >= 36 makes it negative. + let scale = &ls.scale[m]; + let mut nz = 0; + *out = [0; 64]; + for k in 0..64 { + let raster = ZIGZAG_8X8[k] as usize; + let c = coef[raster]; + let denom = TOTAL_SCALE * i64::from(scale[raster]); + let (num, denom) = if p >= 0 { + ((c.unsigned_abs() as i64) << p, denom) + } else { + (c.unsigned_abs() as i64, denom << -p) + }; + let level = round_div(num, denom, intra) as i32; + if level != 0 { + nz += 1; + } + out[k] = if c < 0 { -level } else { level }; + } + nz +} + /// Quantise a transformed 4x4 block into scan (zig-zag) order. /// /// `skip_dc` leaves scan position 0 out and writes the fifteen AC levels into @@ -159,6 +266,77 @@ pub(crate) fn quant_chroma_dc(coef: &[i32; 4], qp: i32, intra: bool, out: &mut [ #[cfg(test)] mod tests { use super::*; + use crate::transform::{LevelScale8x8, dequant_8x8, inverse_transform_8x8, unzigzag_8x8}; + + fn ls8() -> LevelScale8x8 { + LevelScale8x8::new(&[16; 64]) + } + + /// `forward_8x8` -> `quant_8x8` -> [`dequant_8x8`] -> [`inverse_transform_8x8`] + /// lands within the same dead-zone-quantiser bound as the 4x4 path (one + /// step, which doubles every six QP — see `ac_round_trip_within_a_quantiser_step` + /// above), at every QP, for 1000+ trials of random content across the full + /// 8-bit residual range: the property that makes `FWD8` a valid forward + /// companion to the normative inverse. With no quantisation at all + /// (`round_trip_8x8_identity_within_one_sample` below) the bound tightens + /// to the inverse transform's own `+32 >> 6` rounding, ±1. + #[test] + fn round_trip_8x8_within_a_quantiser_step() { + let ls = ls8(); + for qp in 0..52 { + let step = 1 << (qp / 6); + let mut worst = 0i32; + for seed in 0..20u32 { + let src: [i32; 64] = std::array::from_fn(|i| { + let v = (seed.wrapping_mul(2654435761)) + .wrapping_add((i as u32).wrapping_mul(2654435761)) + >> 20; + (v as i32 % 511) - 255 + }); + let coef = forward_8x8(&src); + let mut scan = [0i32; 64]; + quant_8x8(&coef, &ls, qp, true, &mut scan); + let mut raster = [0i32; 64]; + unzigzag_8x8(&scan, &mut raster); + dequant_8x8(&mut raster, &ls, qp); + let mut out = [0i32; 64]; + inverse_transform_8x8(&raster, &mut out); + for i in 0..64 { + worst = worst.max((out[i] - src[i]).abs()); + } + } + assert!( + worst <= 2 + 2 * step, + "qp {qp}: worst error {worst} over step {step}" + ); + } + } + + /// With no quantisation at all (level = raw coefficient), the round trip + /// is exact up to the inverse transform's own `+32 >> 6` rounding. + #[test] + fn round_trip_8x8_identity_within_one_sample() { + let src: [i32; 64] = std::array::from_fn(|i| ((i * 7) % 511) as i32 - 255); + let coef = forward_8x8(&src); + // coef = 2_088_025 * exact_pre_shift_value; divide that out directly, + // bypassing any QP-driven quantiser step. + let mut raster = [0i32; 64]; + for i in 0..64 { + let v = coef[i] as f64 / 2_088_025.0; + raster[i] = v.round() as i32; + } + let mut out = [0i32; 64]; + inverse_transform_8x8(&raster, &mut out); + for i in 0..64 { + assert!( + (out[i] - src[i]).abs() <= 1, + "i {i}: {} vs {}", + out[i], + src[i] + ); + } + } + use crate::transform::{ LevelScale4x4, chroma_dc_transform_420, dequant_4x4, inverse_transform_4x4, luma_dc_transform, unzigzag, diff --git a/crates/ec-h264/src/enc/vlc.rs b/crates/ec-h264/src/enc/vlc.rs index dfaa780c..7e048c15 100644 --- a/crates/ec-h264/src/enc/vlc.rs +++ b/crates/ec-h264/src/enc/vlc.rs @@ -248,6 +248,49 @@ 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..ba57aed4 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -126,14 +126,17 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { /// sample, over a QP sweep, both presets, single and multi threaded. #[test] fn reconstruction_matches_the_decoder() { + let mut t8x8_mbs = (0, 0); 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 +144,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(); @@ -150,6 +154,11 @@ fn reconstruction_matches_the_decoder() { stream.extend_from_slice(&picture.au); recons.push(enc.reconstruction().expect("a reconstruction")); } + if t8x8 { + let (intra, inter) = enc.transform_8x8_mbs(); + t8x8_mbs.0 += intra; + t8x8_mbs.1 += inter; + } let decoded = decode_all(&stream); assert_eq!( decoded.len(), @@ -173,6 +182,13 @@ fn reconstruction_matches_the_decoder() { } } } + // The flag-on streams above really carried 8x8 macroblocks of both kinds. + assert!( + t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, + "8x8 MBs across the sweep: intra {} inter {}", + t8x8_mbs.0, + t8x8_mbs.1 + ); } /// Quality tracks the quantiser, and a low QP is close to lossless: a stream @@ -316,7 +332,7 @@ fn encode_clip( h: usize, frames: usize, configure: impl FnOnce(&mut EncoderConfig), -) -> (Vec, Vec) { +) -> (Vec, Vec, (u64, u64)) { let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.gop_size = 10; cfg.threads = 3; @@ -330,7 +346,90 @@ fn encode_clip( stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au); recons.push(enc.reconstruction().expect("reconstruction")); } - (stream, recons) + (stream, recons, enc.transform_8x8_mbs()) +} + +/// Flat gradients and glyph-like rectangles: the content the 8x8 transform +/// exists for. A 10-frame clip with the flag on must beat the flag off by at +/// least 0.3 dB at equal bits, or by 5% fewer bits at equal PSNR. +#[test] +fn eight_by_eight_gains_on_flat_and_text() { + let (w, h) = (320, 240); + let render = |t: usize, clip: &mut Clip| { + // A half-sample pan per frame: inter prediction has a residual to code. + let sx = |x: usize| x * 2 + t; + for y in 0..h { + for x in 0..w { + let (px, py) = (sx(x) as f64 / 2.0, y as f64); + // Curved shading: smooth but not a plane, so no 16x16 mode + // predicts it for free. + let shade = 70.0 + px * px / 900.0 + py * py / 700.0 - px * py / 1500.0; + // Gentle texture with a 20-sample period: residual energy that + // spans more than a 4x4 block, which is what the 8x8 transform + // is for. + let tri = |v: f64| ((v % 20.0) - 10.0).abs() - 5.0; + let shade = shade + tri(px) * tri(py) / 1.5; + // Glyph rows: 16x24 cells, stroke pattern hashed per cell. + let (cell, cx, cy) = (sx(x) / 32, (sx(x) / 2) % 16, y % 24); + let hash = (cell * 2654435761usize.wrapping_add(y / 24 * 40503)) >> 7; + let stem = (2..5).contains(&cx); + let bar = (10..13).contains(&cy) && cx < 12 && hash & 1 == 1; + let foot = cy >= 19 && (2..13).contains(&cx) && hash & 2 == 2; + let glyph = y > h / 3 && (3..22).contains(&cy) && (stem || bar || foot); + clip.y[y * w + x] = if glyph { 24 } else { shade.min(235.0) as u8 }; + } + } + clip.u.fill(128); + clip.v.fill(128); + }; + let run = |t8x8: bool, qp: i32| { + let mut cfg = EncoderConfig::new(w as u32, h as u32); + cfg.qp = qp; + cfg.gop_size = 10; + cfg.transform_8x8 = t8x8; + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut clip = Clip::new(w, h); + let (mut bits, mut sum_psnr) = (0usize, 0.0); + let mut share = 0.0; + for t in 0..10 { + render(t, &mut clip); + bits += enc.encode(&clip.view()).expect("encode").au.len() * 8; + let rec = enc.reconstruction().expect("reconstruction"); + sum_psnr += psnr(&clip.y, &rec.0); + } + if t8x8 { + let (i, p) = enc.transform_8x8_mbs(); + eprintln!("8x8 MBs: intra {i} inter {p}"); + share = (i + p) as f64 / (10.0 * (w / 16 * h / 16) as f64); + } + (bits as f64, sum_psnr / 10.0, share) + }; + // Interpolate the off curve at the on point's bits / PSNR. + let qp = 26; + let (bits_on, psnr_on, share) = run(true, qp); + let off: Vec<_> = [qp - 2, qp, qp + 2] + .iter() + .map(|&q| run(false, q)) + .collect(); + let (bits_off, psnr_off, _) = off[1]; + // Local slopes of the off curve, from the neighbouring QPs. + let dpsnr_dbits = (off[0].1 - off[2].1) / (off[0].0 - off[2].0); + let psnr_off_at_on_bits = psnr_off + (bits_on - bits_off) * dpsnr_dbits; + let bits_off_at_on_psnr = bits_off + (psnr_on - psnr_off) / dpsnr_dbits; + let gain_db = psnr_on - psnr_off_at_on_bits; + let saving = 1.0 - bits_on / bits_off_at_on_psnr; + eprintln!( + "8x8 qp {qp}: on {bits_on:.0} bits {psnr_on:.2} dB, off {bits_off:.0} bits {psnr_off:.2} dB; \ + gain at equal bits {gain_db:+.2} dB, saving at equal PSNR {:.1}%, 8x8 MB share {:.1}%", + saving * 100.0, + share * 100.0 + ); + assert!(share > 0.0, "no 8x8 macroblocks were coded"); + assert!( + gain_db >= 0.3 || saving >= 0.05, + "8x8 gain {gain_db:+.2} dB / {:.1}% is below the bar", + saving * 100.0 + ); } /// ffmpeg's decode of our stream is our reconstruction, sample for sample, @@ -341,13 +440,18 @@ fn ffmpeg_decodes_bit_exactly() { eprintln!("SKIP ffmpeg_decodes_bit_exactly: no ffmpeg on PATH"); return; } + let mut t8x8_mbs = (0, 0); 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 (stream, recons) = encode_clip(w, h, 6, |cfg| { + let t8x8 = qp % 3 == 1; // High-profile PPS with the per-MB flag + let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { cfg.qp = qp; cfg.cabac = !cavlc; + cfg.transform_8x8 = t8x8; }); + t8x8_mbs.0 += intra; + t8x8_mbs.1 += inter; 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"); for (i, (dec, rec)) in decoded.iter().zip(&recons).enumerate() { @@ -357,6 +461,12 @@ fn ffmpeg_decodes_bit_exactly() { } } } + assert!( + t8x8_mbs.0 > 0 && t8x8_mbs.1 > 0, + "8x8 MBs across the sweep: intra {} inter {}", + t8x8_mbs.0, + t8x8_mbs.1 + ); } /// The same stream under constant bitrate, which is the mode edith exports in. @@ -367,7 +477,7 @@ fn ffmpeg_decodes_a_cbr_stream_bit_exactly() { return; } let (w, h) = (352, 288); - let (stream, recons) = encode_clip(w, h, 12, |cfg| { + let (stream, recons, _) = encode_clip(w, h, 12, |cfg| { cfg.bitrate = 2_000_000; cfg.framerate = 25.0; }); @@ -393,9 +503,11 @@ fn vaapi_decodes_our_stream() { return; } let (w, h) = (352, 288); - let (stream, recons) = encode_clip(w, h, 6, |cfg| { + let (stream, recons, (intra, inter)) = encode_clip(w, h, 6, |cfg| { cfg.qp = 26; + cfg.transform_8x8 = true; }); + assert!(intra + inter > 0, "no 8x8 macroblocks in the VA-API stream"); let Some(decoded) = ffmpeg_decode( &stream, w,