From 74491d6ebe26a15d568106382a3019cfcee86932 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 22 Aug 2026 00:59:20 +0300 Subject: [PATCH] test(h264): add RD ablation controls --- crates/ec-h264/Cargo.toml | 4 ++ crates/ec-h264/src/enc/mb.rs | 84 +++++++++++++++------- crates/ec-h264/src/enc/mod.rs | 127 +++++++++++++++++++++++++++++++--- 3 files changed, 180 insertions(+), 35 deletions(-) diff --git a/crates/ec-h264/Cargo.toml b/crates/ec-h264/Cargo.toml index d9151dbe..3fc7431c 100644 --- a/crates/ec-h264/Cargo.toml +++ b/crates/ec-h264/Cargo.toml @@ -6,6 +6,10 @@ edition.workspace = true license.workspace = true authors.workspace = true +[features] +# Internal-only RD experiment switches, compiled only by the measurement harness. +rd-ablation = [] + [dependencies] ec-core = { workspace = true } ec-h264-syntax = { workspace = true } diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index bbbcfd8c..2eea9271 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -16,18 +16,18 @@ use ec_h264_syntax::SliceType; use wide::i16x16; use crate::decoder::{ - MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, + chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, MbNeighbors, }; -use crate::dpb::{BLK_SKIP, Picture}; +use crate::dpb::{Picture, BLK_SKIP}; use crate::entropy::{ - BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8, - MbCtx, MbInfo, + BlockCat, MbCtx, MbInfo, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, + FLAG_TRANS8X8, }; -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::inter::{integer_origin, mc_chroma, mc_luma, RefPlane}; +use crate::mv::{neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd, MvCtx}; use crate::pred::{ - PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16, - pred_chroma_8x8, + add_residual_4x4, add_residual_8x8, filter_nbr8, pred_16x16, pred_4x4, pred_8x8, + pred_chroma_8x8, PlaneWindow, }; use crate::tables::{BLK4_POS, CHROMA_QP}; use crate::transform::{ @@ -81,10 +81,19 @@ pub(crate) struct MbEnc<'a> { /// Lagrangian multiplier; it is in the squared-error domain when 8x8 /// transform decisions are enabled. pub lambda: f64, + /// Whether `lambda` is the standard squared-error multiplier. + pub lambda_standard: bool, + /// Extra rate saving an 8x8 trial must buy before it may replace 4x4. + pub t8x8_margin_bits: f64, 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, + /// Whether intra macroblocks may select 8x8. The PPS can remain enabled + /// while an ablation measures the classes independently. + pub transform_8x8_intra: bool, + /// Whether inter macroblocks may select 8x8. + pub transform_8x8_inter: bool, pub ls: LevelScale4x4, pub ls8: LevelScale8x8, /// Neighbourhood of the macroblock being written (CABAC). @@ -283,7 +292,7 @@ fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] { #[inline] fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 { - let lambda = if e.transform_8x8 { + let lambda = if e.lambda_standard { e.lambda.sqrt() } else { e.lambda @@ -688,7 +697,14 @@ fn code_luma_4x4( // half of rate-distortion optimised quantisation, and the half that // pays. Intra blocks are left alone: their reconstruction is what the // next block in the macroblock predicts from. - if !intra && !worth_coding(&source, &resid, &lv.luma[blk], zero_block_lambda(e, qp)) { + if !intra + && !worth_coding( + &source, + &resid, + &lv.luma[blk], + zero_block_lambda(e, qp, e.transform_8x8_inter), + ) + { lv.luma[blk] = [0; 16]; lv.luma_nz[blk] = 0; continue; @@ -708,8 +724,8 @@ fn code_luma_4x4( /// without costing camera content. const ZERO_BLOCK_LAMBDA: f64 = 0.4; -fn zero_block_lambda(e: &MbEnc<'_>, qp: i32) -> f64 { - if e.transform_8x8 { +fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 { + if transform_8x8 { e.lambda } else { ZERO_BLOCK_LAMBDA * lambda_ssd(qp) @@ -871,7 +887,20 @@ fn code_chroma( dequant_4x4(&mut raster, &e.ls, qp_c, true); let mut resid = [0i32; 16]; inverse_transform_4x4(&raster, &mut resid); - if !worth_coding(&source, &resid, &ac[comp][blk], zero_block_lambda(e, qp_c)) { + if !worth_coding( + &source, + &resid, + &ac[comp][blk], + zero_block_lambda( + e, + qp_c, + if intra { + e.transform_8x8_intra + } else { + e.transform_8x8_inter + }, + ), + ) { ac[comp][blk] = [0; 16]; nz = 0; } @@ -1125,7 +1154,14 @@ fn code_block_8x8( 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, zero_block_lambda(e, qp)) { + if !intra + && !worth_coding( + &d, + &resid, + out, + zero_block_lambda(e, qp, e.transform_8x8_inter), + ) + { *out = [0; 64]; return 0; } @@ -1265,7 +1301,6 @@ fn entropy_bits(w: &EncEntropy, write: impl FnOnce(&mut EncEntropy)) -> i64 { (probe.bit_len() - before) as i64 } - fn cost_luma_nz_pair( pic: &Picture, nbr: &MbNeighbors, @@ -1545,7 +1580,7 @@ fn encode_intra_mb( if cost.allow_i4 { let mut lv4 = chroma_lv.clone(); let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4); - let cost4 = if e.transform_8x8 { + let cost4 = if e.transform_8x8_intra { let bits = intra_mb_bits( pic, e, @@ -1573,7 +1608,7 @@ fn encode_intra_mb( // Intra_8x8 on the same terms, when the PPS allows it. let mut lv8 = chroma_lv.clone(); let mut recon8 = [0u8; 256]; - let cost8 = if e.transform_8x8 { + let cost8 = if e.transform_8x8_intra { let (m8, p8) = code_intra_8x8(pic, e, mb_x, mb_y, qp, &nbr, &mut lv8); modes8 = m8; pred_modes8 = p8; @@ -1596,7 +1631,7 @@ fn encode_intra_mb( let mut lv16 = chroma_lv; code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16); - let cost16 = if e.transform_8x8 { + let cost16 = if e.transform_8x8_intra { let bits = intra_mb_bits( pic, e, @@ -1614,7 +1649,9 @@ fn encode_intra_mb( + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64 }; - if cost8 <= cost4 && cost8 <= cost16 { + if cost8 + e.lambda * e.t8x8_margin_bits <= cost4 + && cost8 + e.lambda * e.t8x8_margin_bits <= cost16 + { use_i4 = true; use_i8 = true; restore_luma(pic, mb_x, mb_y, &recon8); @@ -1643,7 +1680,6 @@ fn encode_intra_mb( code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv); } - // ---- syntax ---- w.begin_mb(&e.mb_ctx); w.coded_mb(e.slice_type == SliceType::P, e.skip_inc); @@ -1698,7 +1734,6 @@ fn encode_intra_mb( qp, }, ); - } /// Squared error of the whole macroblock against the source, luma and chroma: @@ -1928,7 +1963,7 @@ fn encode_inter_mb( let mut chroma_lv = Levels::default(); code_chroma(pic, e, mb_x, mb_y, qp, false, &mut chroma_lv); let mut lv = chroma_lv.clone(); - if e.transform_8x8 { + if e.transform_8x8_inter { // Both transform sizes on the same prediction; the cheaper // rate-distortion cost is coded. let mut pred = [0u8; 256]; @@ -1944,7 +1979,7 @@ fn encode_inter_mb( code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8); let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8); let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64; - if cost8 < cost4 { + if cost8 + e.lambda * e.t8x8_margin_bits < cost4 { lv = lv8; } else { lv = lv4; @@ -1958,7 +1993,7 @@ fn encode_inter_mb( None => false, Some(_) if empty => true, Some(ssd_skip) => { - let coded = if e.transform_8x8 { + let coded = if e.transform_8x8_inter { let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv); ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 } else { @@ -2009,7 +2044,6 @@ fn encode_inter_mb( pic.i4_modes[base..base + 4].fill(2); } - // ---- syntax ---- w.begin_mb(&e.mb_ctx); w.coded_mb(true, e.skip_inc); diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index 8a4a563a..ff3ec911 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -30,7 +30,7 @@ mod vlc; use ec_core::error::{Error, Result}; use ec_core::BitWriter; -use ec_h264_syntax::nal::{NalUnitType, escape_rbsp}; +use ec_h264_syntax::nal::{escape_rbsp, NalUnitType}; use ec_h264_syntax::{SliceType, Sps}; use crate::decoder::deblock_picture; @@ -39,8 +39,8 @@ 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}; -use mb::{MbEnc, Source, encode_mb}; +use headers::{write_pps, write_slice_header, write_sps, SeqParams, SliceParams}; +use mb::{encode_mb, MbEnc, Source}; use rc::RateControl; pub use mb::Preset; @@ -79,6 +79,14 @@ pub struct EncoderConfig { /// rate-distortion cost. Leaving it off preserves the Baseline/Main-profile /// 4x4 path. pub transform_8x8: bool, + #[cfg(feature = "rd-ablation")] + rd_lambda_standard: bool, + #[cfg(feature = "rd-ablation")] + rd_transform_8x8_intra: bool, + #[cfg(feature = "rd-ablation")] + rd_transform_8x8_inter: bool, + #[cfg(feature = "rd-ablation")] + rd_transform_8x8_margin_bits: f64, } impl EncoderConfig { @@ -96,6 +104,14 @@ impl EncoderConfig { threads: 0, qp: 26, transform_8x8: false, + #[cfg(feature = "rd-ablation")] + rd_lambda_standard: false, + #[cfg(feature = "rd-ablation")] + rd_transform_8x8_intra: false, + #[cfg(feature = "rd-ablation")] + rd_transform_8x8_inter: false, + #[cfg(feature = "rd-ablation")] + rd_transform_8x8_margin_bits: 0.0, } } } @@ -170,6 +186,10 @@ impl<'a> PictureView<'a> { impl Encoder { /// Build an encoder for `cfg`, refusing what it cannot code. pub fn new(cfg: EncoderConfig) -> Result { + #[cfg(feature = "rd-ablation")] + let mut cfg = cfg; + #[cfg(feature = "rd-ablation")] + apply_rd_ablation(&mut cfg); if cfg.width < 16 || cfg.height < 16 { return Err(Error::unsupported( "picture smaller than one macroblock", @@ -510,9 +530,13 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { slice_id: job.slice_id, qp: job.qp, target_qp: job.qp, - lambda: lambda_for(job.qp, job.cfg.transform_8x8), + lambda: lambda_for(job.qp, rd_lambda_standard(job.cfg)), + t8x8_margin_bits: rd_transform_8x8_margin_bits(job.cfg), preset: job.cfg.preset, + lambda_standard: rd_lambda_standard(job.cfg), transform_8x8: job.cfg.transform_8x8, + transform_8x8_intra: rd_transform_8x8_intra(job.cfg), + transform_8x8_inter: rd_transform_8x8_inter(job.cfg), ls: LevelScale4x4::new(&[16; 16]), ls8: LevelScale8x8::new(&[16; 64]), mb_ctx: crate::entropy::MbCtx::default(), @@ -528,7 +552,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { let expected = job.band_target * n as f64 / rows as f64; let delta = job.rc.row_delta(spent, expected); e.target_qp = (job.qp + delta).clamp(10, 51); - e.lambda = lambda_for(e.target_qp, job.cfg.transform_8x8); + e.lambda = lambda_for(e.target_qp, rd_lambda_standard(job.cfg)); } for mb_x in 0..mb_w { let addr = mb_y * mb_w + mb_x; @@ -545,17 +569,90 @@ pub(crate) fn lambda_ssd(qp: i32) -> f64 { 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() } -/// Lagrangian multiplier; the 8x8 path uses the standard squared-error -/// multiplier, while the established 4x4 path keeps its byte-stable ladder. -fn lambda_for(qp: i32, transform_8x8: bool) -> f64 { - if transform_8x8 { +/// Lagrangian multiplier. Production uses the established byte-stable ladder; +/// the ablation feature can select the standard squared-error multiplier. +fn lambda_for(qp: i32, standard: bool) -> f64 { + if standard { lambda_ssd(qp) } else { - // The established 4x4 path stays byte-stable when the feature is off. (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0) } } +#[cfg(feature = "rd-ablation")] +fn apply_rd_ablation(cfg: &mut EncoderConfig) { + if let Ok(lambda) = std::env::var("EC_H264_RD_LAMBDA") { + cfg.rd_lambda_standard = match lambda.as_str() { + "ladder" => false, + "standard" => true, + _ => panic!("EC_H264_RD_LAMBDA must be ladder or standard"), + }; + } + if let Ok(transform) = std::env::var("EC_H264_RD_T8X8") { + let (intra, inter) = match transform.as_str() { + "off" => (false, false), + "on" => (true, true), + "intra" => (true, false), + "inter" => (false, true), + _ => panic!("EC_H264_RD_T8X8 must be off, on, intra, or inter"), + }; + cfg.rd_transform_8x8_intra = intra; + cfg.rd_transform_8x8_inter = inter; + cfg.transform_8x8 = intra || inter; + } else if cfg.transform_8x8 { + cfg.rd_transform_8x8_intra = true; + cfg.rd_transform_8x8_inter = true; + } + if let Ok(margin) = std::env::var("EC_H264_RD_T8X8_MARGIN_BITS") { + cfg.rd_transform_8x8_margin_bits = margin + .parse() + .expect("EC_H264_RD_T8X8_MARGIN_BITS must be a number"); + } +} + +#[cfg(feature = "rd-ablation")] +fn rd_lambda_standard(cfg: &EncoderConfig) -> bool { + cfg.rd_lambda_standard +} + +#[cfg(not(feature = "rd-ablation"))] +fn rd_lambda_standard(cfg: &EncoderConfig) -> bool { + cfg.transform_8x8 +} + +#[cfg(feature = "rd-ablation")] +fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool { + cfg.rd_transform_8x8_intra +} + +#[cfg(not(feature = "rd-ablation"))] +fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool { + cfg.transform_8x8 +} + +#[cfg(feature = "rd-ablation")] +fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool { + cfg.rd_transform_8x8_inter +} + +#[cfg(not(feature = "rd-ablation"))] +fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool { + cfg.transform_8x8 +} + +#[cfg(not(feature = "rd-ablation"))] +const TRANSFORM_8X8_MARGIN_BITS: f64 = 0.0; + +#[cfg(feature = "rd-ablation")] +fn rd_transform_8x8_margin_bits(cfg: &EncoderConfig) -> f64 { + cfg.rd_transform_8x8_margin_bits +} + +#[cfg(not(feature = "rd-ablation"))] +fn rd_transform_8x8_margin_bits(_: &EncoderConfig) -> f64 { + TRANSFORM_8X8_MARGIN_BITS +} + /// Split `mb_h` macroblock rows into at most `n` contiguous bands. fn split_bands(mb_h: usize, n: usize) -> Vec<(usize, usize)> { let n = n.clamp(1, mb_h); @@ -711,4 +808,14 @@ mod tests { assert!(matches!(err, Error::Unsupported { .. }), "{err}"); assert!(Encoder::new(EncoderConfig::new(640, 480)).is_ok()); } + #[test] + fn production_lambda_tracks_transform_mode() { + let mut cfg = EncoderConfig::new(640, 480); + assert_eq!( + lambda_for(26, rd_lambda_standard(&cfg)), + lambda_for(26, false) + ); + cfg.transform_8x8 = true; + assert_eq!(lambda_for(26, rd_lambda_standard(&cfg)), lambda_ssd(26)); + } }