From b397db55ecedba0a41b126382b6382e8732248f6 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:59:54 +0300 Subject: [PATCH] feat(h264-enc): honest 8x8 rate term, dead-zone 8x8 quantiser, 8x8 gain test The 8x8 quantiser now rounds with the same 1/3 (intra) / 1/6 (inter) dead zone as the 4x4 one, and the mode decision charges a level's position in a 64-coefficient significance map: without it Intra_8x8 was picked on 28 macroblocks that cost 44 real bits more each. The gain test codes curved shading, a 20-sample texture and glyph rows at qp 26: +0.30 dB at equal bits, 7.4% of macroblocks 8x8 (100 intra, 123 inter). The conformance gates assert 8x8 macroblocks of both kinds across their sweeps, and the VA-API decode runs with the flag on. --- crates/ec-h264/src/enc/mb.rs | 7 +++- crates/ec-h264/src/enc/quant.rs | 4 +- crates/ec-h264/tests/encode.rs | 71 +++++++++++++++++++++++---------- 3 files changed, 58 insertions(+), 24 deletions(-) diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 129573a9..72b0f2d4 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -1425,7 +1425,12 @@ fn estimate_luma_bits(lv: &Levels) -> i64 { if lv.trans8 { for blk8 in 0..4 { if lv.cbp_luma & (1 << blk8) != 0 { - bits += block_bits(&lv.luma8[blk8]); + // 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; diff --git a/crates/ec-h264/src/enc/quant.rs b/crates/ec-h264/src/enc/quant.rs index 5f7c8d35..bd23233a 100644 --- a/crates/ec-h264/src/enc/quant.rs +++ b/crates/ec-h264/src/enc/quant.rs @@ -152,8 +152,8 @@ pub(crate) fn forward_8x8(d: &[i32; 64]) -> [i64; 64] { /// 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 / 2) / denom +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 diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index 546b32b9..ba57aed4 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -126,6 +126,7 @@ 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] { @@ -155,10 +156,8 @@ fn reconstruction_matches_the_decoder() { } 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}" - ); + t8x8_mbs.0 += intra; + t8x8_mbs.1 += inter; } let decoded = decode_all(&stream); assert_eq!( @@ -183,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 @@ -326,12 +332,11 @@ 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; 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(); @@ -341,11 +346,7 @@ 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) + (stream, recons, enc.transform_8x8_mbs()) } /// Flat gradients and glyph-like rectangles: the content the 8x8 transform @@ -355,13 +356,27 @@ fn encode_clip( 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 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 }; + 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); @@ -384,14 +399,18 @@ fn eight_by_eight_gains_on_flat_and_text() { } 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 = 30; + 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 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); @@ -421,15 +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 t8x8 = qp % 3 == 1; // High-profile PPS with the per-MB flag - let (stream, recons) = encode_clip(w, h, 6, |cfg| { + 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() { @@ -439,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. @@ -449,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; }); @@ -475,10 +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,