From 250a6ac468c83d9e441a193f3a9e3a3893050fa3 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:23:32 +0300 Subject: [PATCH] feat(h264-enc): High-profile SPS/PPS tail + 8x8 forward transform/quant (E1+E2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SPS/PPS now write the High-profile 8x8-transform syntax (profile_idc 100, chroma/bit-depth/scaling-matrix fields, transform_8x8_mode_flag) behind a new EncoderConfig::transform_8x8 flag, and quant.rs gains forward_8x8/quant_8x8: an exact algebraic inverse of the decoder's idct8_1d (verified by rational matrix inversion, not a hand-tuned butterfly, since the small-integer transpose leaks ~15% between frequencies — too much for full-range residuals) paired with a plain-division dead-zone quantiser against the existing LevelScale8x8/dequant_8x8. transform_8x8 is NOT yet safe to turn on for a real encode: a conformant decoder unconditionally expects a transform_size_8x8_flag per eligible macroblock once the PPS advertises it (7.3.5), and enc::entropy/enc::mb don't write that bit yet (confirmed by a failing round trip, not left implicit). That emission, and the mode decision that actually picks 8x8 blocks, are later work. --- crates/ec-h264/src/enc/headers.rs | 65 +++++++++-- crates/ec-h264/src/enc/mod.rs | 17 ++- crates/ec-h264/src/enc/quant.rs | 177 +++++++++++++++++++++++++++++- 3 files changed, 245 insertions(+), 14 deletions(-) diff --git a/crates/ec-h264/src/enc/headers.rs b/crates/ec-h264/src/enc/headers.rs index a56cf27f..6bd50aba 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,25 @@ 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 +287,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/mod.rs b/crates/ec-h264/src/enc/mod.rs index 7d571fc3..cdcb89f6 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -71,6 +71,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 +100,7 @@ impl EncoderConfig { cabac: true, threads: 0, qp: 26, + transform_8x8: false, } } } @@ -193,10 +207,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 { diff --git a/crates/ec-h264/src/enc/quant.rs b/crates/ec-h264/src/enc/quant.rs index 483d405b..6f7d7ab6 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 / 2) / 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,74 @@ 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,