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/cabac_enc.rs b/crates/ec-h264/src/enc/cabac_enc.rs index 0a76052b..45c67033 100644 --- a/crates/ec-h264/src/enc/cabac_enc.rs +++ b/crates/ec-h264/src/enc/cabac_enc.rs @@ -30,6 +30,7 @@ use crate::entropy::{ BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8, MbCtx, MbInfo, }; +#[derive(Clone)] /// The arithmetic encoder of 9.3.4 plus the context state. pub(crate) struct CabacEnc { w: BitWriter, diff --git a/crates/ec-h264/src/enc/entropy.rs b/crates/ec-h264/src/enc/entropy.rs index d548e929..8b093002 100644 --- a/crates/ec-h264/src/enc/entropy.rs +++ b/crates/ec-h264/src/enc/entropy.rs @@ -19,6 +19,7 @@ pub(crate) fn sub_block_4x4(c8: &[i32; 64], j: usize) -> [i32; 16] { std::array::from_fn(|i| c8[4 * i + j]) } +#[derive(Clone)] pub(crate) enum EncEntropy { Cavlc { w: BitWriter, diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 72b0f2d4..b5162d1d 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -16,31 +16,34 @@ 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::{ - LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8, - inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, - unzigzag_ac15, + chroma_dc_transform_420, dequant_4x4, dequant_8x8, inverse_transform_4x4, + inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, unzigzag_ac15, LevelScale4x4, + LevelScale8x8, }; -use super::entropy::{EncEntropy, sub_block_4x4}; use super::quant::{ forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_8x8, quant_chroma_dc, quant_luma_dc, }; +use super::{ + entropy::{sub_block_4x4, EncEntropy}, + lambda_ssd, +}; /// Speed/quality ladder. Two rungs, because the two the incumbent exposed are /// the two edith actually picks between. @@ -75,12 +78,25 @@ pub(crate) struct MbEnc<'a> { pub qp: i32, /// What rate control wants this macroblock coded at. pub target_qp: i32, - /// Lagrangian multiplier in the SATD domain. - pub lambda: i32, + /// 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, + /// Whether the ablation restricts 8x8 eligibility to even macroblock + /// rows; odd rows then code exactly as they would with 8x8 disabled. + pub transform_8x8_roweven: bool, pub ls: LevelScale4x4, pub ls8: LevelScale8x8, /// Neighbourhood of the macroblock being written (CABAC). @@ -92,7 +108,20 @@ pub(crate) struct MbEnc<'a> { pub qp_delta_inc: u8, } +impl MbEnc<'_> { + /// Intra 8x8 eligibility of macroblock row `mb_y`. + fn t8x8_intra(&self, mb_y: usize) -> bool { + self.transform_8x8_intra && (mb_y % 2 == 0 || !self.transform_8x8_roweven) + } + + /// Inter 8x8 eligibility of macroblock row `mb_y`. + fn t8x8_inter(&self, mb_y: usize) -> bool { + self.transform_8x8_inter && (mb_y % 2 == 0 || !self.transform_8x8_roweven) + } +} + /// Quantised levels of one macroblock, scan order per block. +#[derive(Clone)] struct Levels { /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16. luma: [[i32; 16]; 16], @@ -276,6 +305,16 @@ 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.lambda_standard { + e.lambda.sqrt() + } else { + e.lambda + }; + (lambda * bits).round() as i32 +} + /// Code one macroblock: decide its mode, reconstruct it into `pic` and write /// its syntax into `w`. pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy, mb_addr: usize) { @@ -323,7 +362,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y); let go_intra = match &inter { None => true, - Some(i) => intra_cost.best() + e.lambda * 8 < i.cost, + Some(i) => intra_cost.best() + motion_rate(e, 8.0) < i.cost, }; if go_intra { @@ -502,9 +541,11 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter // which is what a search can afford; the winner is re-costed on SATD // because the intra candidates are SATD and the two scales differ. let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 { - let bits = e.lambda - * (se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1]))) - / 2; + let bits = motion_rate( + e, + f64::from(se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1]))) + / 2.0, + ); if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 { let o = integer_origin( &plane, @@ -592,7 +633,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter let skip_cost = { let mut buf = [0u8; 256]; mc_luma(&plane, sx as i32, sy as i32, skip_mv, 16, 16, 16, &mut buf); - satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - e.lambda * 4 + satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 4.0) }; let mut best = (PShape::Whole, [mv16, mv16], cost16); @@ -607,7 +648,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter // time. That is a Balanced trade, not a Fast one. if e.preset == Preset::Balanced && cost16 > 16 * 16 { for shape in [PShape::Horizontal, PShape::Vertical] { - let mut total = e.lambda * 6; // the partition's own signalling + let mut total = motion_rate(e, 6.0); // the partition's own signalling let mut mvs = [[0i16; 2]; 2]; for part in 0..2 { let ((bx, by), (w, h)) = shape.geometry(part); @@ -671,7 +712,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], qp) { + if !intra + && !worth_coding( + &source, + &resid, + &lv.luma[blk], + zero_block_lambda(e, qp, e.t8x8_inter(mb_y)), + ) + { lv.luma[blk] = [0; 16]; lv.luma_nz[blk] = 0; continue; @@ -691,9 +739,17 @@ fn code_luma_4x4( /// without costing camera content. const ZERO_BLOCK_LAMBDA: f64 = 0.4; +fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 { + if transform_8x8 { + e.lambda + } else { + ZERO_BLOCK_LAMBDA * lambda_ssd(qp) + } +} + /// 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], resid: &[i32], levels: &[i32], qp: i32) -> bool { +fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool { let mut ssd_zero = 0i64; let mut ssd_coded = 0i64; for i in 0..source.len() { @@ -702,8 +758,7 @@ fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], qp: i32) -> bool ssd_zero += z * z; ssd_coded += c * c; } - ssd_coded as f64 + ZERO_BLOCK_LAMBDA * lambda_ssd(qp) * (block_bits(levels) as f64) - < ssd_zero as f64 + ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64 } /// Predict and code the luma of an Intra_16x16 macroblock. @@ -847,7 +902,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], qp_c) { + if !worth_coding( + &source, + &resid, + &ac[comp][blk], + zero_block_lambda( + e, + qp_c, + if intra { + e.t8x8_intra(mb_y) + } else { + e.t8x8_inter(mb_y) + }, + ), + ) { ac[comp][blk] = [0; 16]; nz = 0; } @@ -1019,7 +1087,7 @@ fn code_intra_4x4( } pred_4x4(mode, &n, &mut p); let bits = if mode == predicted { 1 } else { 4 }; - let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * bits; + let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits)); if c < best.0 { best = (c, mode); } @@ -1101,7 +1169,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, qp) { + if !intra + && !worth_coding( + &d, + &resid, + out, + zero_block_lambda(e, qp, e.transform_8x8_inter), + ) + { *out = [0; 64]; return 0; } @@ -1140,7 +1215,7 @@ fn code_intra_8x8( } pred_8x8(mode, &n, &mut p); let bits = if mode == predicted { 1 } else { 4 }; - let mut c = e.lambda * bits; + let mut c = motion_rate(e, f64::from(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); @@ -1220,13 +1295,9 @@ 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], &[u8])>) -> i64 { +fn rough_intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 { let mut bits = estimate_luma_bits(lv); match i4 { - // 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..modes.len() { @@ -1238,6 +1309,256 @@ fn intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 { bits } +fn entropy_bits(w: &EncEntropy, write: impl FnOnce(&mut EncEntropy)) -> i64 { + let mut probe = w.clone(); + let before = probe.bit_len(); + write(&mut probe); + (probe.bit_len() - before) as i64 +} + +fn cost_luma_nz_pair( + pic: &Picture, + nbr: &MbNeighbors, + local: &[u8; 16], + bx0: usize, + by0: usize, + bx: usize, + by: usize, +) -> (Option, Option) { + let w4 = pic.mb_w * 4; + let left_avail = if bx.is_multiple_of(4) { nbr.a } else { true }; + let top_avail = if by.is_multiple_of(4) { nbr.b } else { true }; + let left = (left_avail && bx > 0).then(|| { + if bx > bx0 { + local[(by - by0) * 4 + (bx - bx0 - 1)] + } else { + pic.nz_y[by * w4 + bx - 1] + } + }); + let top = (top_avail && by > 0).then(|| { + if by > by0 { + local[(by - by0 - 1) * 4 + (bx - bx0)] + } else { + pic.nz_y[(by - 1) * w4 + bx] + } + }); + (left, top) +} + +fn write_luma_for_cost( + pic: &Picture, + nbr: &MbNeighbors, + w: &mut EncEntropy, + mb_x: usize, + mb_y: usize, + lv: &Levels, + is_i16: bool, +) { + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let mut nz = [0u8; 16]; + if is_i16 { + let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx0, by0); + nz[0] = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb); + } + if lv.trans8 { + for blk8 in 0..4 { + let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2); + if lv.cbp_luma & (1 << blk8) == 0 { + continue; + } + if w.is_cabac() { + let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None); + for dy in 0..2 { + let base = (by - by0 + dy) * 4 + bx - bx0; + nz[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) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, sx, sy); + let sub = sub_block_4x4(&lv.luma8[blk8], i4); + nz[(sy - by0) * 4 + (sx - bx0)] = + w.residual_block(&sub, BlockCat::Luma4x4, na, nb); + } + } + } + return; + } + for blk in 0..16 { + let (dx, dy) = BLK4_POS[blk]; + let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); + let group = 1 << (blk >> 2); + let coded_block = if is_i16 { + lv.cbp_luma != 0 + } else { + lv.cbp_luma & group != 0 + }; + if coded_block { + let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx, by); + let (levels, cat) = if is_i16 { + (&lv.luma[blk][..15], BlockCat::LumaAc) + } else { + (&lv.luma[blk][..16], BlockCat::Luma4x4) + }; + nz[(by - by0) * 4 + (bx - bx0)] = w.residual_block(levels, cat, na, nb); + } + } +} +fn cost_chroma_nz_pair( + pic: &Picture, + nbr: &MbNeighbors, + local: &[[u8; 4]; 2], + comp: usize, + cx0: usize, + cy0: usize, + cx: usize, + cy: usize, +) -> (Option, Option) { + let w2 = pic.mb_w * 2; + let left_avail = if cx.is_multiple_of(2) { nbr.a } else { true }; + let top_avail = if cy.is_multiple_of(2) { nbr.b } else { true }; + let left = (left_avail && cx > 0).then(|| { + if cx > cx0 { + local[comp][(cy - cy0) * 2 + (cx - cx0 - 1)] + } else { + pic.nz_c[comp][cy * w2 + cx - 1] + } + }); + let top = (top_avail && cy > 0).then(|| { + if cy > cy0 { + local[comp][(cy - cy0 - 1) * 2 + (cx - cx0)] + } else { + pic.nz_c[comp][(cy - 1) * w2 + cx] + } + }); + (left, top) +} + +fn write_chroma_for_cost( + pic: &Picture, + nbr: &MbNeighbors, + w: &mut EncEntropy, + mb_x: usize, + mb_y: usize, + lv: &Levels, +) { + if lv.cbp_chroma != 0 { + for comp in 0..2 { + w.residual_block( + &lv.chroma_dc[comp][..4], + BlockCat::ChromaDc(comp as u8), + None, + None, + ); + } + } + if lv.cbp_chroma != 2 { + return; + } + let (cx0, cy0) = (mb_x * 2, mb_y * 2); + let mut nz = [[0u8; 4]; 2]; + for comp in 0..2 { + for blk in 0..4 { + let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); + let (na, nb) = cost_chroma_nz_pair(pic, nbr, &nz, comp, cx0, cy0, cx, cy); + nz[comp][blk] = + w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb); + } + } +} + +fn intra_mb_bits( + pic: &Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + mb_addr: usize, + nbr: &MbNeighbors, + lv: &Levels, + i4: Option<(&[u8], &[u8])>, + i16_mode: u8, + chroma_mode: u8, +) -> i64 { + let use_i4 = i4.is_some(); + let p_slice = e.slice_type == SliceType::P; + let offset = if p_slice { 5 } else { 0 }; + let intra_type = if use_i4 { + 0 + } else { + 1 + u32::from(i16_mode) + + 4 * u32::from(lv.cbp_chroma) + + if lv.cbp_luma != 0 { 12 } else { 0 } + }; + entropy_bits(w, |cw| { + cw.begin_mb(&e.mb_ctx); + cw.coded_mb(p_slice, e.skip_inc); + cw.set_intra(true); + cw.mb_type(p_slice, intra_type + offset); + if let Some((modes, pred)) = i4 { + if e.transform_8x8 { + cw.transform_size_8x8_flag(lv.trans8); + } + for blk in 0..modes.len() { + let rem = if modes[blk] == pred[blk] { + None + } else if modes[blk] > pred[blk] { + Some(modes[blk] - 1) + } else { + Some(modes[blk]) + }; + cw.intra4x4_pred_mode(rem); + } + } + cw.intra_chroma_pred_mode(chroma_mode); + if use_i4 { + cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true); + } + let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || !use_i4; + if coded { + cw.mb_qp_delta(e.target_qp - e.qp); + } + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, !use_i4); + write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv); + }) +} + +fn inter_mb_bits( + pic: &Picture, + e: &MbEnc<'_>, + w: &EncEntropy, + mb_addr: usize, + nbr: &MbNeighbors, + shape: PShape, + mvd: &[[i16; 2]; 2], + inc: &[[usize; 2]; 2], + lv: &Levels, +) -> i64 { + entropy_bits(w, |cw| { + cw.begin_mb(&e.mb_ctx); + cw.coded_mb(true, e.skip_inc); + cw.set_intra(false); + cw.mb_type(true, shape.mb_type()); + for part in 0..shape.parts() { + for comp in 0..2 { + cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp])); + } + } + cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false); + if lv.cbp_luma != 0 && e.transform_8x8 { + cw.transform_size_8x8_flag(lv.trans8); + } + if lv.cbp_luma != 0 || lv.cbp_chroma != 0 { + cw.mb_qp_delta(e.target_qp - e.qp); + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, false); + write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv); + } + }) +} + /// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real /// rate and real distortion. /// @@ -1260,19 +1581,37 @@ fn encode_intra_mb( let (bx0, by0) = (mb_x * 4, mb_y * 4); let qp = e.target_qp; write_intra_mb(pic, mb_x, mb_y); - let mut lv = Levels::default(); + let mut lv: Levels; 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 chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y); + let mut chroma_lv = Levels::default(); + code_chroma(pic, e, mb_x, mb_y, qp, true, &mut chroma_lv); let mut use_i8 = false; if cost.allow_i4 { - let mut lv4 = Levels::default(); + let mut lv4 = chroma_lv.clone(); let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4); - let cost4 = ssd_luma(pic, e, mb_x, mb_y) as f64 - + lambda_ssd(qp) * intra_bits(&lv4, Some((&m4, &p4))) as f64; + let cost4 = if e.t8x8_intra(mb_y) { + let bits = intra_mb_bits( + pic, + e, + w, + mb_addr, + &nbr, + &lv4, + Some((&m4, &p4)), + cost.i16_mode, + chroma_mode, + ); + ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 + } else { + ssd_luma(pic, e, mb_x, mb_y) as f64 + + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64 + }; let mut recon4 = [0u8; 256]; save_luma(pic, mb_x, mb_y, &mut recon4); let mut modes4 = [2u8; 16]; @@ -1282,25 +1621,52 @@ fn encode_intra_mb( } // Intra_8x8 on the same terms, when the PPS allows it. - let mut lv8 = Levels::default(); + let mut lv8 = chroma_lv.clone(); let mut recon8 = [0u8; 256]; - let cost8 = if e.transform_8x8 { + let cost8 = if e.t8x8_intra(mb_y) { 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 + let bits = intra_mb_bits( + pic, + e, + w, + mb_addr, + &nbr, + &lv8, + Some((&m8, &p8)), + cost.i16_mode, + chroma_mode, + ); + ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 } else { f64::INFINITY }; - let mut lv16 = Levels::default(); + let mut lv16 = chroma_lv; 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; + let cost16 = if e.t8x8_intra(mb_y) { + let bits = intra_mb_bits( + pic, + e, + w, + mb_addr, + &nbr, + &lv16, + None, + cost.i16_mode, + chroma_mode, + ); + ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 + } else { + ssd_luma(pic, e, mb_x, mb_y) as f64 + + 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); @@ -1325,12 +1691,10 @@ fn encode_intra_mb( lv = lv16; } } else { + lv = chroma_lv; code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv); } - let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y); - code_chroma(pic, e, mb_x, mb_y, qp, true, &mut lv); - // ---- syntax ---- w.begin_mb(&e.mb_ctx); w.coded_mb(e.slice_type == SliceType::P, e.skip_inc); @@ -1455,7 +1819,11 @@ fn block_bits(b: &[i32]) -> i64 { n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1; } } - if n > 0 { n + 6 } else { 2 } + if n > 0 { + n + 6 + } else { + 2 + } } /// Rough bit cost of a macroblock's residual, for the skip decision: a level @@ -1475,12 +1843,6 @@ fn estimate_bits(lv: &Levels) -> i64 { bits } -/// Lagrangian multiplier in the squared-error domain, paired with -/// [`super::lambda_for`] in the SATD one. -fn lambda_ssd(qp: i32) -> f64 { - 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() -} - /// Motion-compensate one partition into the picture planes. fn compensate_part( pic: &mut Picture, @@ -1613,38 +1975,45 @@ fn encode_inter_mb( // quantisation churn costs bits every picture and improves nothing. 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(); - if e.transform_8x8 { + 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.t8x8_inter(mb_y) { // 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 lv4 = chroma_lv.clone(); + code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv4); + let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4); + let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 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(); + let mut lv8 = chroma_lv; 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 { + 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 + e.lambda * e.t8x8_margin_bits < cost4 { lv = lv8; } else { + lv = lv4; 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 { None => false, Some(_) if empty => true, Some(ssd_skip) => { - let coded = - ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64; + let coded = if e.t8x8_inter(mb_y) { + 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 { + ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64 + }; if ssd_skip as f64 <= coded { // Put the prediction back: the residual has been added to it. compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv); diff --git a/crates/ec-h264/src/enc/mod.rs b/crates/ec-h264/src/enc/mod.rs index 0196aee6..27abb338 100644 --- a/crates/ec-h264/src/enc/mod.rs +++ b/crates/ec-h264/src/enc/mod.rs @@ -28,19 +28,21 @@ mod quant; mod rc; mod vlc; -use ec_core::BitWriter; use ec_core::error::{Error, Result}; -use ec_h264_syntax::nal::{NalUnitType, escape_rbsp}; +use ec_core::BitWriter; +use ec_h264_syntax::nal::{escape_rbsp, NalUnitType}; use ec_h264_syntax::{SliceType, Sps}; use crate::decoder::deblock_picture; use crate::dpb::{Picture, SliceParams as DeblockParams}; use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8}; +#[cfg(feature = "rd-ablation")] +use crate::entropy::FLAG_SKIP; 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; @@ -74,17 +76,21 @@ pub struct EncoderConfig { 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. + /// When enabled, eligible intra and inter luma macroblocks write + /// `transform_size_8x8_flag` and choose the 8x8 path with a squared-error + /// 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_roweven: bool, + #[cfg(feature = "rd-ablation")] + rd_transform_8x8_margin_bits: f64, } impl EncoderConfig { @@ -102,6 +108,16 @@ 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_roweven: false, + #[cfg(feature = "rd-ablation")] + rd_transform_8x8_margin_bits: 0.0, } } } @@ -176,6 +192,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", @@ -385,7 +405,16 @@ impl Encoder { } } } + // H5 measurement hook: the chosen candidate's trial SSD is the + // pre-deblock SSD of the macroblock in this picture (round 4 verified + // trial bits and SSD against the final picture), so capturing the + // per-macroblock SSD right before and right after the filter is the + // exact pre/post comparison with no hooks inside the RD trials. + #[cfg(feature = "rd-ablation")] + let rd_pre = rd_trace_capture(master, &self.src); deblock_picture(master); + #[cfg(feature = "rd-ablation")] + rd_trace_write(master, &self.src, self.frames, rd_pre); master.extend_borders(); master.complete = true; std::mem::swap(master, &mut self.reference); @@ -516,9 +545,14 @@ 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), + 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), + transform_8x8_roweven: rd_transform_8x8_roweven(job.cfg), ls: LevelScale4x4::new(&[16; 16]), ls8: LevelScale8x8::new(&[16; 64]), mb_ctx: crate::entropy::MbCtx::default(), @@ -534,7 +568,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); + 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; @@ -546,10 +580,174 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec { w.finish(job.slice_type == SliceType::P) } -/// Lagrangian multiplier for mode decision in the SATD domain. -fn lambda_for(qp: i32) -> i32 { - // 2^((qp - 12) / 6), the usual ladder, floored at 1. - (((f64::from(qp) - 12.0) / 6.0).exp2().round() as i32).max(1) +/// Standard Lagrangian multiplier in the squared-error domain. +pub(crate) fn lambda_ssd(qp: i32) -> f64 { + 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2() +} + +/// 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 { + (((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, roweven) = match transform.as_str() { + "off" => (false, false, false), + "on" => (true, true, false), + "roweven" => (true, true, true), + "intra" => (true, false, false), + "inter" => (false, true, false), + _ => panic!("EC_H264_RD_T8X8 must be off, on, roweven, intra, or inter"), + }; + cfg.rd_transform_8x8_intra = intra; + cfg.rd_transform_8x8_inter = inter; + cfg.rd_transform_8x8_roweven = roweven; + 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"); + } +} + +/// Luma and chroma SSD of every macroblock against the source, before the +/// deblocking filter — the distortion the RD decision actually paid. +#[cfg(feature = "rd-ablation")] +fn rd_trace_capture(pic: &Picture, src: &Source) -> Option> { + if std::env::var_os("EC_H264_RD_TRACE").is_none() { + return None; + } + let mut out = Vec::with_capacity(pic.mb_w * pic.mb_h); + for mb_y in 0..pic.mb_h { + for mb_x in 0..pic.mb_w { + out.push(rd_trace_ssd(pic, src, mb_x, mb_y)); + } + } + Some(out) +} + +/// One line per macroblock: `frame addr intra trans8 skip qp pre_luma +/// pre_chroma post_luma post_chroma`, appended to `$EC_H264_RD_TRACE`. +#[cfg(feature = "rd-ablation")] +fn rd_trace_write(pic: &Picture, src: &Source, frame: u64, pre: Option>) { + use std::io::Write; + let Some(pre) = pre else { return }; + let mut out = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(std::env::var_os("EC_H264_RD_TRACE").expect("checked in capture")) + .expect("open EC_H264_RD_TRACE"); + for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() { + let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w); + let f = pic.mb_flags[addr]; + let _ = writeln!( + out, + "{frame} {addr} {} {} {} {} {pre_luma} {pre_chroma} {post_luma} {post_chroma}", + u8::from(f & FLAG_INTER == 0), + u8::from(f & FLAG_TRANS8X8 != 0), + u8::from(f & FLAG_SKIP != 0), + pic.mb_qp[addr] + ); + } +} + +/// Luma and chroma SSD of one macroblock against the source planes. +#[cfg(feature = "rd-ablation")] +fn rd_trace_ssd(pic: &Picture, src: &Source, mb_x: usize, mb_y: usize) -> (i64, i64) { + let mut luma = 0i64; + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + for row in 0..16 { + let s = (mb_y * 16 + row) * src.stride + mb_x * 16; + for x in 0..16 { + let d = i64::from(src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]); + luma += d * d; + } + } + let mut chroma = 0i64; + for (plane, source) in [(&pic.cb, &src.u), (&pic.cr, &src.v)] { + let stride = plane.stride; + let origin = plane.at(mb_x * 8, mb_y * 8); + for row in 0..8 { + let s = (mb_y * 8 + row) * src.c_stride + mb_x * 8; + for x in 0..8 { + let d = i64::from(source[s + x]) - i64::from(plane.data[origin + row * stride + x]); + chroma += d * d; + } + } + } + (luma, chroma) +} + +#[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(feature = "rd-ablation")] +fn rd_transform_8x8_roweven(cfg: &EncoderConfig) -> bool { + cfg.rd_transform_8x8_roweven +} + +#[cfg(not(feature = "rd-ablation"))] +fn rd_transform_8x8_roweven(_: &EncoderConfig) -> bool { + false +} + +#[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. @@ -707,4 +905,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)); + } } diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index ba57aed4..50be5e2e 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -122,6 +122,66 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 { } } +fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { + let mut a = [[0.0; 5]; 4]; + for i in 0..4 { + a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; + } + for col in 0..4 { + let mut pivot = col; + for row in col + 1..4 { + if a[row][col].abs() > a[pivot][col].abs() { + pivot = row; + } + } + a.swap(col, pivot); + let div = a[col][col]; + assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); + for j in col..5 { + a[col][j] /= div; + } + for row in 0..4 { + if row == col { + continue; + } + let f = a[row][col]; + for j in col..5 { + a[row][j] -= f * a[col][j]; + } + } + } + [a[0][4], a[1][4], a[2][4], a[3][4]] +} + +fn cubic_integral(c: [f64; 4], x: f64) -> f64 { + c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 +} + +fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 { + let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); + let ys_candidate = std::array::from_fn(|i| candidate[i].1); + let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); + let ys_anchor = std::array::from_fn(|i| anchor[i].1); + let lo = xs_candidate + .iter() + .copied() + .fold(f64::INFINITY, f64::min) + .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); + let hi = xs_candidate + .iter() + .copied() + .fold(f64::NEG_INFINITY, f64::max) + .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); + assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate"); + let c_candidate = cubic_fit(xs_candidate, ys_candidate); + let c_anchor = cubic_fit(xs_anchor, ys_anchor); + (cubic_integral(c_candidate, hi) + - cubic_integral(c_candidate, lo) + - cubic_integral(c_anchor, hi) + + cubic_integral(c_anchor, lo)) + / (hi - lo) +} + /// The encoder's reconstruction and a decode of its bitstream agree sample for /// sample, over a QP sweep, both presets, single and multi threaded. #[test] @@ -350,8 +410,8 @@ fn encode_clip( } /// 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. +/// exists for. A 10-frame clip with the flag on must keep a clear positive +/// gain at equal bits, or cut bits at equal PSNR. #[test] fn eight_by_eight_gains_on_flat_and_text() { let (w, h) = (320, 240); @@ -382,11 +442,12 @@ fn eight_by_eight_gains_on_flat_and_text() { clip.u.fill(128); clip.v.fill(128); }; - let run = |t8x8: bool, qp: i32| { + let run = |t8x8: bool, qp: i32, cabac: bool| { let mut cfg = EncoderConfig::new(w as u32, h as u32); cfg.qp = qp; cfg.gop_size = 10; cfg.transform_8x8 = t8x8; + cfg.cabac = cabac; let mut enc = Encoder::new(cfg).expect("encoder"); let mut clip = Clip::new(w, h); let (mut bits, mut sum_psnr) = (0usize, 0.0); @@ -404,31 +465,23 @@ fn eight_by_eight_gains_on_flat_and_text() { } (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; + let qps = [22, 26, 30, 34]; + let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect(); + let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect(); + let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); + let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); + let bd = bd_psnr_delta(&on_curve, &off_curve); + let share = on.iter().map(|&(_, _, share)| share).sum::() / on.len() as f64; + const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.255_347; 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, + "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", share * 100.0 ); assert!(share > 0.0, "no 8x8 macroblocks were coded"); + assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off"); assert!( - gain_db >= 0.3 || saving >= 0.05, - "8x8 gain {gain_db:+.2} dB / {:.1}% is below the bar", - saving * 100.0 + bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB, + "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate" ); }