From 4e4673b796d321a7b959c555a0a71e26c7dabe62 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:50:12 +0300 Subject: [PATCH] feat(h264-enc): Intra_8x8 prediction and the 8x8 transform for inter residuals, chosen on rate-distortion cost transform_size_8x8_flag now follows a real decision: Intra_8x8 is coded alongside Intra_4x4 and Intra_16x16 (decoder's filtered reference samples and neighbour-mode rule), P macroblocks try both transform sizes on the same prediction, and the residual writer takes the cat-5 / interleaved path. Encoder::transform_8x8_mbs() counts what was chosen; the reconstruction, ffmpeg and VA-API gates run with 8x8 macroblocks present. --- crates/ec-h264/src/decoder.rs | 12 +- crates/ec-h264/src/enc/cabac_enc.rs | 19 +- crates/ec-h264/src/enc/entropy.rs | 4 + crates/ec-h264/src/enc/headers.rs | 3 +- crates/ec-h264/src/enc/mb.rs | 310 +++++++++++++++++++++++++--- crates/ec-h264/src/enc/mod.rs | 22 +- crates/ec-h264/src/enc/quant.rs | 11 +- crates/ec-h264/src/enc/vlc.rs | 7 +- crates/ec-h264/tests/encode.rs | 78 +++++++ fixtures | 1 + 10 files changed, 426 insertions(+), 41 deletions(-) create mode 120000 fixtures 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 10562570..0a76052b 100644 --- a/crates/ec-h264/src/enc/cabac_enc.rs +++ b/crates/ec-h264/src/enc/cabac_enc.rs @@ -432,7 +432,10 @@ impl CabacEnc { na: Option, nb: Option, ) -> u8 { - debug_assert!(cat != BlockCat::Luma8x8, "cat 5 goes through residual_block_8x8"); + 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); @@ -478,7 +481,13 @@ impl CabacEnc { /// 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 { + 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; @@ -618,7 +627,11 @@ mod tests { 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}"); + 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}"); diff --git a/crates/ec-h264/src/enc/entropy.rs b/crates/ec-h264/src/enc/entropy.rs index 01141e70..d548e929 100644 --- a/crates/ec-h264/src/enc/entropy.rs +++ b/crates/ec-h264/src/enc/entropy.rs @@ -193,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 6bd50aba..9fe3784c 100644 --- a/crates/ec-h264/src/enc/headers.rs +++ b/crates/ec-h264/src/enc/headers.rs @@ -264,8 +264,7 @@ mod tests { 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"); + 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); diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 24577435..129573a9 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 @@ -75,6 +82,7 @@ pub(crate) struct MbEnc<'a> { /// 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. @@ -85,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. @@ -102,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 { @@ -665,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; @@ -1030,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; @@ -1064,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 }; } } @@ -1105,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(); @@ -1120,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 { @@ -1161,10 +1347,16 @@ fn encode_intra_mb( 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); + w.transform_size_8x8_flag(use_i8); } - for blk in 0..16 { + // 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] { @@ -1230,6 +1422,14 @@ 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 { + bits += block_bits(&lv.luma8[blk8]); + } + } + return bits; + } for blk in 0..16 { if lv.cbp_luma & (1 << (blk >> 2)) != 0 { bits += block_bits(&lv.luma[blk]); @@ -1256,12 +1456,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]); @@ -1414,7 +1609,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 { @@ -1481,9 +1698,9 @@ 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. + // flag whenever luma is coded. if lv.cbp_luma != 0 && e.transform_8x8 { - w.transform_size_8x8_flag(false); + w.transform_size_8x8_flag(lv.trans8); } finish_mb( pic, @@ -1545,6 +1762,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 { @@ -1561,7 +1784,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 562965fa..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}; @@ -139,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. @@ -242,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 } @@ -366,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; @@ -501,6 +520,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { 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 6f7d7ab6..5f7c8d35 100644 --- a/crates/ec-h264/src/enc/quant.rs +++ b/crates/ec-h264/src/enc/quant.rs @@ -266,9 +266,7 @@ 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, - }; + use crate::transform::{LevelScale8x8, dequant_8x8, inverse_transform_8x8, unzigzag_8x8}; fn ls8() -> LevelScale8x8 { LevelScale8x8::new(&[16; 64]) @@ -330,7 +328,12 @@ mod tests { 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]); + assert!( + (out[i] - src[i]).abs() <= 1, + "i {i}: {} vs {}", + out[i], + src[i] + ); } } diff --git a/crates/ec-h264/src/enc/vlc.rs b/crates/ec-h264/src/enc/vlc.rs index 2963d181..7e048c15 100644 --- a/crates/ec-h264/src/enc/vlc.rs +++ b/crates/ec-h264/src/enc/vlc.rs @@ -267,7 +267,12 @@ mod tests { 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); + 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(); diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index c52ef299..546b32b9 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -153,6 +153,13 @@ 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(); + assert!( + intra > 0 && inter > 0, + "{w}x{h} qp {qp} cabac {cabac}: 8x8 MBs intra {intra} inter {inter}" + ); + } let decoded = decode_all(&stream); assert_eq!( decoded.len(), @@ -324,6 +331,7 @@ fn encode_clip( cfg.gop_size = 10; cfg.threads = 3; configure(&mut cfg); + let t8x8 = cfg.transform_8x8; let mut enc = Encoder::new(cfg).expect("encoder"); let mut clip = Clip::new(w, h); let mut stream = Vec::new(); @@ -333,9 +341,78 @@ fn encode_clip( stream.extend_from_slice(&enc.encode(&clip.view()).expect("encode").au); recons.push(enc.reconstruction().expect("reconstruction")); } + if t8x8 { + let (intra, inter) = enc.transform_8x8_mbs(); + assert!(intra > 0 && inter > 0, "8x8 MBs intra {intra} inter {inter}"); + } (stream, recons) } +/// 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| { + for y in 0..h { + for x in 0..w { + let grad = (x * 3 / 4 + y / 2 + t) as u8 / 2 + 40; + // Glyph rows: 12x16 cells, a 2-sample stem and a bar. + let (cx, cy) = ((x + t) % 12, y % 16); + let glyph = y > h / 3 && cy >= 3 && cy < 13 && (cx < 2 || (cy == 8 && cx < 8)); + clip.y[y * w + x] = if glyph { 20 } else { grad }; + } + } + 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(); + 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 = 30; + 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, /// across a QP sweep and at a size that is not a multiple of a macroblock. #[test] @@ -400,6 +477,7 @@ fn vaapi_decodes_our_stream() { let (w, h) = (352, 288); let (stream, recons) = encode_clip(w, h, 6, |cfg| { cfg.qp = 26; + cfg.transform_8x8 = true; }); let Some(decoded) = ffmpeg_decode( &stream, diff --git a/fixtures b/fixtures new file mode 120000 index 00000000..9b6d05cf --- /dev/null +++ b/fixtures @@ -0,0 +1 @@ +/home/user/Documents/Code/Rust/edith_codecs/fixtures \ No newline at end of file