forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h264rd': transform-8x8 RD priced by full syntax bit delta and standard lambda, QP clamp removed, rd-ablation instrumentation

Browse files at this commit

5aa2305cb2f58876967b7ca5bfaa062ae563ec32Ahmet Kaan GümüşParent: 90d597a817a995
Default output is byte-identical to main (16/16 SHA pairs across two sources, four QPs, CABAC and CAVLC). The opt-in transform_8x8 path now prices 4x4-vs-8x8 and intra mode choices with the cloned entropy writer's whole-macroblock bit delta and the reconstruction SSD at a standard lambda, and the qp>=30 clamp that hid the QP-30 over-purchase is gone. The non-default rd-ablation feature adds env-driven lambda/eligibility/row-parity knobs and a pre/post-deblock SSD trace; without the feature the knob code is compiled out. Measured and documented: under CABAC the opt-in 8x8 path still trails flag-off on real content at matched rate (-0.10 dB natural-720p, -0.02 obs-1440p), the loss is super-linear in 8x8 adoption, and intra 4x4 on screen text is deblock-under-costed — the named follow-up slice.
crates/ec-h264/Cargo.tomlmodified+4 -0
@@ -6,6 +6,10 @@ edition.workspace = true
66 license.workspace = true
77 authors.workspace = true
88
9+[features]
10+# Internal-only RD experiment switches, compiled only by the measurement harness.
11+rd-ablation = []
12+
913 [dependencies]
1014 ec-core = { workspace = true }
1115 ec-h264-syntax = { workspace = true }
crates/ec-h264/src/enc/cabac_enc.rsmodified+1 -0
@@ -30,6 +30,7 @@ use crate::entropy::{
3030 BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8, MbCtx, MbInfo,
3131 };
3232
33+#[derive(Clone)]
3334 /// The arithmetic encoder of 9.3.4 plus the context state.
3435 pub(crate) struct CabacEnc {
3536 w: BitWriter,
crates/ec-h264/src/enc/entropy.rsmodified+1 -0
@@ -19,6 +19,7 @@ pub(crate) fn sub_block_4x4(c8: &[i32; 64], j: usize) -> [i32; 16] {
1919 std::array::from_fn(|i| c8[4 * i + j])
2020 }
2121
22+#[derive(Clone)]
2223 pub(crate) enum EncEntropy {
2324 Cavlc {
2425 w: BitWriter,
crates/ec-h264/src/enc/mb.rsmodified+436 -67
@@ -16,31 +16,34 @@ use ec_h264_syntax::SliceType;
1616 use wide::i16x16;
1717
1818 use crate::decoder::{
19- MbNeighbors, chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors,
19+ chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, MbNeighbors,
2020 };
21-use crate::dpb::{BLK_SKIP, Picture};
21+use crate::dpb::{Picture, BLK_SKIP};
2222 use crate::entropy::{
23- BlockCat, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP, FLAG_TRANS8X8,
24- MbCtx, MbInfo,
23+ BlockCat, MbCtx, MbInfo, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_INTER, FLAG_SKIP,
24+ FLAG_TRANS8X8,
2525 };
26-use crate::inter::{RefPlane, integer_origin, mc_chroma, mc_luma};
27-use crate::mv::{MvCtx, neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd};
26+use crate::inter::{integer_origin, mc_chroma, mc_luma, RefPlane};
27+use crate::mv::{neighbour_mvd, predict_mv, write_block, write_intra_mb, write_mvd, MvCtx};
2828 use crate::pred::{
29- PlaneWindow, add_residual_4x4, add_residual_8x8, filter_nbr8, pred_4x4, pred_8x8, pred_16x16,
30- pred_chroma_8x8,
29+ add_residual_4x4, add_residual_8x8, filter_nbr8, pred_16x16, pred_4x4, pred_8x8,
30+ pred_chroma_8x8, PlaneWindow,
3131 };
3232 use crate::tables::{BLK4_POS, CHROMA_QP};
3333 use crate::transform::{
34- LevelScale4x4, LevelScale8x8, chroma_dc_transform_420, dequant_4x4, dequant_8x8,
35- inverse_transform_4x4, inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8,
36- unzigzag_ac15,
34+ chroma_dc_transform_420, dequant_4x4, dequant_8x8, inverse_transform_4x4,
35+ inverse_transform_8x8, luma_dc_transform, unzigzag, unzigzag_8x8, unzigzag_ac15, LevelScale4x4,
36+ LevelScale8x8,
3737 };
3838
39-use super::entropy::{EncEntropy, sub_block_4x4};
4039 use super::quant::{
4140 forward_4x4, forward_8x8, forward_hadamard_2x2, forward_hadamard_4x4, quant_4x4, quant_8x8,
4241 quant_chroma_dc, quant_luma_dc,
4342 };
43+use super::{
44+ entropy::{sub_block_4x4, EncEntropy},
45+ lambda_ssd,
46+};
4447
4548 /// Speed/quality ladder. Two rungs, because the two the incumbent exposed are
4649 /// the two edith actually picks between.
@@ -75,12 +78,25 @@ pub(crate) struct MbEnc<'a> {
7578 pub qp: i32,
7679 /// What rate control wants this macroblock coded at.
7780 pub target_qp: i32,
78- /// Lagrangian multiplier in the SATD domain.
79- pub lambda: i32,
81+ /// Lagrangian multiplier; it is in the squared-error domain when 8x8
82+ /// transform decisions are enabled.
83+ pub lambda: f64,
84+ /// Whether `lambda` is the standard squared-error multiplier.
85+ pub lambda_standard: bool,
86+ /// Extra rate saving an 8x8 trial must buy before it may replace 4x4.
87+ pub t8x8_margin_bits: f64,
8088 pub preset: Preset,
8189 /// The PPS carries transform_8x8_mode_flag: transform_size_8x8_flag must
8290 /// be written for every eligible macroblock (7.3.5).
8391 pub transform_8x8: bool,
92+ /// Whether intra macroblocks may select 8x8. The PPS can remain enabled
93+ /// while an ablation measures the classes independently.
94+ pub transform_8x8_intra: bool,
95+ /// Whether inter macroblocks may select 8x8.
96+ pub transform_8x8_inter: bool,
97+ /// Whether the ablation restricts 8x8 eligibility to even macroblock
98+ /// rows; odd rows then code exactly as they would with 8x8 disabled.
99+ pub transform_8x8_roweven: bool,
84100 pub ls: LevelScale4x4,
85101 pub ls8: LevelScale8x8,
86102 /// Neighbourhood of the macroblock being written (CABAC).
@@ -92,7 +108,20 @@ pub(crate) struct MbEnc<'a> {
92108 pub qp_delta_inc: u8,
93109 }
94110
111+impl MbEnc<'_> {
112+ /// Intra 8x8 eligibility of macroblock row `mb_y`.
113+ fn t8x8_intra(&self, mb_y: usize) -> bool {
114+ self.transform_8x8_intra && (mb_y % 2 == 0 || !self.transform_8x8_roweven)
115+ }
116+
117+ /// Inter 8x8 eligibility of macroblock row `mb_y`.
118+ fn t8x8_inter(&self, mb_y: usize) -> bool {
119+ self.transform_8x8_inter && (mb_y % 2 == 0 || !self.transform_8x8_roweven)
120+ }
121+}
122+
95123 /// Quantised levels of one macroblock, scan order per block.
124+#[derive(Clone)]
96125 struct Levels {
97126 /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16.
98127 luma: [[i32; 16]; 16],
@@ -276,6 +305,16 @@ fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] {
276305 ]
277306 }
278307
308+#[inline]
309+fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 {
310+ let lambda = if e.lambda_standard {
311+ e.lambda.sqrt()
312+ } else {
313+ e.lambda
314+ };
315+ (lambda * bits).round() as i32
316+}
317+
279318 /// Code one macroblock: decide its mode, reconstruct it into `pic` and write
280319 /// its syntax into `w`.
281320 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
323362 let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y);
324363 let go_intra = match &inter {
325364 None => true,
326- Some(i) => intra_cost.best() + e.lambda * 8 < i.cost,
365+ Some(i) => intra_cost.best() + motion_rate(e, 8.0) < i.cost,
327366 };
328367
329368 if go_intra {
@@ -502,9 +541,11 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
502541 // which is what a search can afford; the winner is re-costed on SATD
503542 // because the intra candidates are SATD and the two scales differ.
504543 let mut cost_of = |mv: [i16; 2], satd: bool| -> i32 {
505- let bits = e.lambda
506- * (se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])))
507- / 2;
544+ let bits = motion_rate(
545+ e,
546+ f64::from(se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])))
547+ / 2.0,
548+ );
508549 if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 {
509550 let o = integer_origin(
510551 &plane,
@@ -592,7 +633,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
592633 let skip_cost = {
593634 let mut buf = [0u8; 256];
594635 mc_luma(&plane, sx as i32, sy as i32, skip_mv, 16, 16, 16, &mut buf);
595- satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - e.lambda * 4
636+ satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 4.0)
596637 };
597638
598639 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
607648 // time. That is a Balanced trade, not a Fast one.
608649 if e.preset == Preset::Balanced && cost16 > 16 * 16 {
609650 for shape in [PShape::Horizontal, PShape::Vertical] {
610- let mut total = e.lambda * 6; // the partition's own signalling
651+ let mut total = motion_rate(e, 6.0); // the partition's own signalling
611652 let mut mvs = [[0i16; 2]; 2];
612653 for part in 0..2 {
613654 let ((bx, by), (w, h)) = shape.geometry(part);
@@ -671,7 +712,14 @@ fn code_luma_4x4(
671712 // half of rate-distortion optimised quantisation, and the half that
672713 // pays. Intra blocks are left alone: their reconstruction is what the
673714 // next block in the macroblock predicts from.
674- if !intra && !worth_coding(&source, &resid, &lv.luma[blk], qp) {
715+ if !intra
716+ && !worth_coding(
717+ &source,
718+ &resid,
719+ &lv.luma[blk],
720+ zero_block_lambda(e, qp, e.t8x8_inter(mb_y)),
721+ )
722+ {
675723 lv.luma[blk] = [0; 16];
676724 lv.luma_nz[blk] = 0;
677725 continue;
@@ -691,9 +739,17 @@ fn code_luma_4x4(
691739 /// without costing camera content.
692740 const ZERO_BLOCK_LAMBDA: f64 = 0.4;
693741
742+fn zero_block_lambda(e: &MbEnc<'_>, qp: i32, transform_8x8: bool) -> f64 {
743+ if transform_8x8 {
744+ e.lambda
745+ } else {
746+ ZERO_BLOCK_LAMBDA * lambda_ssd(qp)
747+ }
748+}
749+
694750 /// The rate-distortion test behind the per-block zero decision: coding the
695751 /// block has to buy more squared error than its bits are worth.
696-fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], qp: i32) -> bool {
752+fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool {
697753 let mut ssd_zero = 0i64;
698754 let mut ssd_coded = 0i64;
699755 for i in 0..source.len() {
@@ -702,8 +758,7 @@ fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], qp: i32) -> bool
702758 ssd_zero += z * z;
703759 ssd_coded += c * c;
704760 }
705- ssd_coded as f64 + ZERO_BLOCK_LAMBDA * lambda_ssd(qp) * (block_bits(levels) as f64)
706- < ssd_zero as f64
761+ ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64
707762 }
708763
709764 /// Predict and code the luma of an Intra_16x16 macroblock.
@@ -847,7 +902,20 @@ fn code_chroma(
847902 dequant_4x4(&mut raster, &e.ls, qp_c, true);
848903 let mut resid = [0i32; 16];
849904 inverse_transform_4x4(&raster, &mut resid);
850- if !worth_coding(&source, &resid, &ac[comp][blk], qp_c) {
905+ if !worth_coding(
906+ &source,
907+ &resid,
908+ &ac[comp][blk],
909+ zero_block_lambda(
910+ e,
911+ qp_c,
912+ if intra {
913+ e.t8x8_intra(mb_y)
914+ } else {
915+ e.t8x8_inter(mb_y)
916+ },
917+ ),
918+ ) {
851919 ac[comp][blk] = [0; 16];
852920 nz = 0;
853921 }
@@ -1019,7 +1087,7 @@ fn code_intra_4x4(
10191087 }
10201088 pred_4x4(mode, &n, &mut p);
10211089 let bits = if mode == predicted { 1 } else { 4 };
1022- let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + e.lambda * bits;
1090+ let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits));
10231091 if c < best.0 {
10241092 best = (c, mode);
10251093 }
@@ -1101,7 +1169,14 @@ fn code_block_8x8(
11011169 dequant_8x8(&mut raster, &e.ls8, qp);
11021170 let mut resid = [0i32; 64];
11031171 inverse_transform_8x8(&raster, &mut resid);
1104- if !intra && !worth_coding(&d, &resid, out, qp) {
1172+ if !intra
1173+ && !worth_coding(
1174+ &d,
1175+ &resid,
1176+ out,
1177+ zero_block_lambda(e, qp, e.transform_8x8_inter),
1178+ )
1179+ {
11051180 *out = [0; 64];
11061181 return 0;
11071182 }
@@ -1140,7 +1215,7 @@ fn code_intra_8x8(
11401215 }
11411216 pred_8x8(mode, &n, &mut p);
11421217 let bits = if mode == predicted { 1 } else { 4 };
1143- let mut c = e.lambda * bits;
1218+ let mut c = motion_rate(e, f64::from(bits));
11441219 for q in 0..4 {
11451220 let (ox, oy) = ((q % 2) * 4, (q / 2) * 4);
11461221 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]) {
12201295 }
12211296 }
12221297
1223-/// Bits the luma residual and the mode signalling of an intra macroblock cost,
1224-/// to the accuracy the mode decision needs.
1225-fn intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 {
1298+fn rough_intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 {
12261299 let mut bits = estimate_luma_bits(lv);
12271300 match i4 {
1228- // Sixteen (or four) mode signals plus the coded_block_pattern the
1229- // 16x16 form derives from its macroblock type instead.
12301301 Some((modes, pred)) => {
12311302 bits += 6;
12321303 for blk in 0..modes.len() {
@@ -1238,6 +1309,256 @@ fn intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 {
12381309 bits
12391310 }
12401311
1312+fn entropy_bits(w: &EncEntropy, write: impl FnOnce(&mut EncEntropy)) -> i64 {
1313+ let mut probe = w.clone();
1314+ let before = probe.bit_len();
1315+ write(&mut probe);
1316+ (probe.bit_len() - before) as i64
1317+}
1318+
1319+fn cost_luma_nz_pair(
1320+ pic: &Picture,
1321+ nbr: &MbNeighbors,
1322+ local: &[u8; 16],
1323+ bx0: usize,
1324+ by0: usize,
1325+ bx: usize,
1326+ by: usize,
1327+) -> (Option<u8>, Option<u8>) {
1328+ let w4 = pic.mb_w * 4;
1329+ let left_avail = if bx.is_multiple_of(4) { nbr.a } else { true };
1330+ let top_avail = if by.is_multiple_of(4) { nbr.b } else { true };
1331+ let left = (left_avail && bx > 0).then(|| {
1332+ if bx > bx0 {
1333+ local[(by - by0) * 4 + (bx - bx0 - 1)]
1334+ } else {
1335+ pic.nz_y[by * w4 + bx - 1]
1336+ }
1337+ });
1338+ let top = (top_avail && by > 0).then(|| {
1339+ if by > by0 {
1340+ local[(by - by0 - 1) * 4 + (bx - bx0)]
1341+ } else {
1342+ pic.nz_y[(by - 1) * w4 + bx]
1343+ }
1344+ });
1345+ (left, top)
1346+}
1347+
1348+fn write_luma_for_cost(
1349+ pic: &Picture,
1350+ nbr: &MbNeighbors,
1351+ w: &mut EncEntropy,
1352+ mb_x: usize,
1353+ mb_y: usize,
1354+ lv: &Levels,
1355+ is_i16: bool,
1356+) {
1357+ let (bx0, by0) = (mb_x * 4, mb_y * 4);
1358+ let mut nz = [0u8; 16];
1359+ if is_i16 {
1360+ let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx0, by0);
1361+ nz[0] = w.residual_block(&lv.dc, BlockCat::LumaDc, na, nb);
1362+ }
1363+ if lv.trans8 {
1364+ for blk8 in 0..4 {
1365+ let (bx, by) = (bx0 + (blk8 % 2) * 2, by0 + (blk8 / 2) * 2);
1366+ if lv.cbp_luma & (1 << blk8) == 0 {
1367+ continue;
1368+ }
1369+ if w.is_cabac() {
1370+ let tc = w.residual_block(&lv.luma8[blk8], BlockCat::Luma8x8, None, None);
1371+ for dy in 0..2 {
1372+ let base = (by - by0 + dy) * 4 + bx - bx0;
1373+ nz[base..base + 2].fill(tc.min(16));
1374+ }
1375+ } else {
1376+ for i4 in 0..4 {
1377+ let (dx, dy) = BLK4_POS[blk8 * 4 + i4];
1378+ let (sx, sy) = (bx0 + dx as usize, by0 + dy as usize);
1379+ let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, sx, sy);
1380+ let sub = sub_block_4x4(&lv.luma8[blk8], i4);
1381+ nz[(sy - by0) * 4 + (sx - bx0)] =
1382+ w.residual_block(&sub, BlockCat::Luma4x4, na, nb);
1383+ }
1384+ }
1385+ }
1386+ return;
1387+ }
1388+ for blk in 0..16 {
1389+ let (dx, dy) = BLK4_POS[blk];
1390+ let (bx, by) = (bx0 + dx as usize, by0 + dy as usize);
1391+ let group = 1 << (blk >> 2);
1392+ let coded_block = if is_i16 {
1393+ lv.cbp_luma != 0
1394+ } else {
1395+ lv.cbp_luma & group != 0
1396+ };
1397+ if coded_block {
1398+ let (na, nb) = cost_luma_nz_pair(pic, nbr, &nz, bx0, by0, bx, by);
1399+ let (levels, cat) = if is_i16 {
1400+ (&lv.luma[blk][..15], BlockCat::LumaAc)
1401+ } else {
1402+ (&lv.luma[blk][..16], BlockCat::Luma4x4)
1403+ };
1404+ nz[(by - by0) * 4 + (bx - bx0)] = w.residual_block(levels, cat, na, nb);
1405+ }
1406+ }
1407+}
1408+fn cost_chroma_nz_pair(
1409+ pic: &Picture,
1410+ nbr: &MbNeighbors,
1411+ local: &[[u8; 4]; 2],
1412+ comp: usize,
1413+ cx0: usize,
1414+ cy0: usize,
1415+ cx: usize,
1416+ cy: usize,
1417+) -> (Option<u8>, Option<u8>) {
1418+ let w2 = pic.mb_w * 2;
1419+ let left_avail = if cx.is_multiple_of(2) { nbr.a } else { true };
1420+ let top_avail = if cy.is_multiple_of(2) { nbr.b } else { true };
1421+ let left = (left_avail && cx > 0).then(|| {
1422+ if cx > cx0 {
1423+ local[comp][(cy - cy0) * 2 + (cx - cx0 - 1)]
1424+ } else {
1425+ pic.nz_c[comp][cy * w2 + cx - 1]
1426+ }
1427+ });
1428+ let top = (top_avail && cy > 0).then(|| {
1429+ if cy > cy0 {
1430+ local[comp][(cy - cy0 - 1) * 2 + (cx - cx0)]
1431+ } else {
1432+ pic.nz_c[comp][(cy - 1) * w2 + cx]
1433+ }
1434+ });
1435+ (left, top)
1436+}
1437+
1438+fn write_chroma_for_cost(
1439+ pic: &Picture,
1440+ nbr: &MbNeighbors,
1441+ w: &mut EncEntropy,
1442+ mb_x: usize,
1443+ mb_y: usize,
1444+ lv: &Levels,
1445+) {
1446+ if lv.cbp_chroma != 0 {
1447+ for comp in 0..2 {
1448+ w.residual_block(
1449+ &lv.chroma_dc[comp][..4],
1450+ BlockCat::ChromaDc(comp as u8),
1451+ None,
1452+ None,
1453+ );
1454+ }
1455+ }
1456+ if lv.cbp_chroma != 2 {
1457+ return;
1458+ }
1459+ let (cx0, cy0) = (mb_x * 2, mb_y * 2);
1460+ let mut nz = [[0u8; 4]; 2];
1461+ for comp in 0..2 {
1462+ for blk in 0..4 {
1463+ let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
1464+ let (na, nb) = cost_chroma_nz_pair(pic, nbr, &nz, comp, cx0, cy0, cx, cy);
1465+ nz[comp][blk] =
1466+ w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb);
1467+ }
1468+ }
1469+}
1470+
1471+fn intra_mb_bits(
1472+ pic: &Picture,
1473+ e: &MbEnc<'_>,
1474+ w: &EncEntropy,
1475+ mb_addr: usize,
1476+ nbr: &MbNeighbors,
1477+ lv: &Levels,
1478+ i4: Option<(&[u8], &[u8])>,
1479+ i16_mode: u8,
1480+ chroma_mode: u8,
1481+) -> i64 {
1482+ let use_i4 = i4.is_some();
1483+ let p_slice = e.slice_type == SliceType::P;
1484+ let offset = if p_slice { 5 } else { 0 };
1485+ let intra_type = if use_i4 {
1486+ 0
1487+ } else {
1488+ 1 + u32::from(i16_mode)
1489+ + 4 * u32::from(lv.cbp_chroma)
1490+ + if lv.cbp_luma != 0 { 12 } else { 0 }
1491+ };
1492+ entropy_bits(w, |cw| {
1493+ cw.begin_mb(&e.mb_ctx);
1494+ cw.coded_mb(p_slice, e.skip_inc);
1495+ cw.set_intra(true);
1496+ cw.mb_type(p_slice, intra_type + offset);
1497+ if let Some((modes, pred)) = i4 {
1498+ if e.transform_8x8 {
1499+ cw.transform_size_8x8_flag(lv.trans8);
1500+ }
1501+ for blk in 0..modes.len() {
1502+ let rem = if modes[blk] == pred[blk] {
1503+ None
1504+ } else if modes[blk] > pred[blk] {
1505+ Some(modes[blk] - 1)
1506+ } else {
1507+ Some(modes[blk])
1508+ };
1509+ cw.intra4x4_pred_mode(rem);
1510+ }
1511+ }
1512+ cw.intra_chroma_pred_mode(chroma_mode);
1513+ if use_i4 {
1514+ cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true);
1515+ }
1516+ let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || !use_i4;
1517+ if coded {
1518+ cw.mb_qp_delta(e.target_qp - e.qp);
1519+ }
1520+ let mb_x = mb_addr % pic.mb_w;
1521+ let mb_y = mb_addr / pic.mb_w;
1522+ write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, !use_i4);
1523+ write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
1524+ })
1525+}
1526+
1527+fn inter_mb_bits(
1528+ pic: &Picture,
1529+ e: &MbEnc<'_>,
1530+ w: &EncEntropy,
1531+ mb_addr: usize,
1532+ nbr: &MbNeighbors,
1533+ shape: PShape,
1534+ mvd: &[[i16; 2]; 2],
1535+ inc: &[[usize; 2]; 2],
1536+ lv: &Levels,
1537+) -> i64 {
1538+ entropy_bits(w, |cw| {
1539+ cw.begin_mb(&e.mb_ctx);
1540+ cw.coded_mb(true, e.skip_inc);
1541+ cw.set_intra(false);
1542+ cw.mb_type(true, shape.mb_type());
1543+ for part in 0..shape.parts() {
1544+ for comp in 0..2 {
1545+ cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
1546+ }
1547+ }
1548+ cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false);
1549+ if lv.cbp_luma != 0 && e.transform_8x8 {
1550+ cw.transform_size_8x8_flag(lv.trans8);
1551+ }
1552+ if lv.cbp_luma != 0 || lv.cbp_chroma != 0 {
1553+ cw.mb_qp_delta(e.target_qp - e.qp);
1554+ let mb_x = mb_addr % pic.mb_w;
1555+ let mb_y = mb_addr / pic.mb_w;
1556+ write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, false);
1557+ write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
1558+ }
1559+ })
1560+}
1561+
12411562 /// Code an intra macroblock, choosing Intra_16x16 against Intra_4x4 on real
12421563 /// rate and real distortion.
12431564 ///
@@ -1260,19 +1581,37 @@ fn encode_intra_mb(
12601581 let (bx0, by0) = (mb_x * 4, mb_y * 4);
12611582 let qp = e.target_qp;
12621583 write_intra_mb(pic, mb_x, mb_y);
1263- let mut lv = Levels::default();
1584+ let mut lv: Levels;
12641585 let mut modes = [2u8; 16];
12651586 let mut pred_modes = [2u8; 16];
12661587 let mut modes8 = [2u8; 4];
12671588 let mut pred_modes8 = [2u8; 4];
12681589 let mut use_i4 = false;
1590+ let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y);
1591+ let mut chroma_lv = Levels::default();
1592+ code_chroma(pic, e, mb_x, mb_y, qp, true, &mut chroma_lv);
12691593 let mut use_i8 = false;
12701594
12711595 if cost.allow_i4 {
1272- let mut lv4 = Levels::default();
1596+ let mut lv4 = chroma_lv.clone();
12731597 let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4);
1274- let cost4 = ssd_luma(pic, e, mb_x, mb_y) as f64
1275- + lambda_ssd(qp) * intra_bits(&lv4, Some((&m4, &p4))) as f64;
1598+ let cost4 = if e.t8x8_intra(mb_y) {
1599+ let bits = intra_mb_bits(
1600+ pic,
1601+ e,
1602+ w,
1603+ mb_addr,
1604+ &nbr,
1605+ &lv4,
1606+ Some((&m4, &p4)),
1607+ cost.i16_mode,
1608+ chroma_mode,
1609+ );
1610+ ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64
1611+ } else {
1612+ ssd_luma(pic, e, mb_x, mb_y) as f64
1613+ + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64
1614+ };
12761615 let mut recon4 = [0u8; 256];
12771616 save_luma(pic, mb_x, mb_y, &mut recon4);
12781617 let mut modes4 = [2u8; 16];
@@ -1282,25 +1621,52 @@ fn encode_intra_mb(
12821621 }
12831622
12841623 // Intra_8x8 on the same terms, when the PPS allows it.
1285- let mut lv8 = Levels::default();
1624+ let mut lv8 = chroma_lv.clone();
12861625 let mut recon8 = [0u8; 256];
1287- let cost8 = if e.transform_8x8 {
1626+ let cost8 = if e.t8x8_intra(mb_y) {
12881627 let (m8, p8) = code_intra_8x8(pic, e, mb_x, mb_y, qp, &nbr, &mut lv8);
12891628 modes8 = m8;
12901629 pred_modes8 = p8;
12911630 save_luma(pic, mb_x, mb_y, &mut recon8);
1292- ssd_luma(pic, e, mb_x, mb_y) as f64
1293- + lambda_ssd(qp) * intra_bits(&lv8, Some((&m8, &p8))) as f64
1631+ let bits = intra_mb_bits(
1632+ pic,
1633+ e,
1634+ w,
1635+ mb_addr,
1636+ &nbr,
1637+ &lv8,
1638+ Some((&m8, &p8)),
1639+ cost.i16_mode,
1640+ chroma_mode,
1641+ );
1642+ ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64
12941643 } else {
12951644 f64::INFINITY
12961645 };
12971646
1298- let mut lv16 = Levels::default();
1647+ let mut lv16 = chroma_lv;
12991648 code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16);
1300- let cost16 =
1301- ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * intra_bits(&lv16, None) as f64;
1649+ let cost16 = if e.t8x8_intra(mb_y) {
1650+ let bits = intra_mb_bits(
1651+ pic,
1652+ e,
1653+ w,
1654+ mb_addr,
1655+ &nbr,
1656+ &lv16,
1657+ None,
1658+ cost.i16_mode,
1659+ chroma_mode,
1660+ );
1661+ ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64
1662+ } else {
1663+ ssd_luma(pic, e, mb_x, mb_y) as f64
1664+ + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64
1665+ };
13021666
1303- if cost8 <= cost4 && cost8 <= cost16 {
1667+ if cost8 + e.lambda * e.t8x8_margin_bits <= cost4
1668+ && cost8 + e.lambda * e.t8x8_margin_bits <= cost16
1669+ {
13041670 use_i4 = true;
13051671 use_i8 = true;
13061672 restore_luma(pic, mb_x, mb_y, &recon8);
@@ -1325,12 +1691,10 @@ fn encode_intra_mb(
13251691 lv = lv16;
13261692 }
13271693 } else {
1694+ lv = chroma_lv;
13281695 code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv);
13291696 }
13301697
1331- let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y);
1332- code_chroma(pic, e, mb_x, mb_y, qp, true, &mut lv);
1333-
13341698 // ---- syntax ----
13351699 w.begin_mb(&e.mb_ctx);
13361700 w.coded_mb(e.slice_type == SliceType::P, e.skip_inc);
@@ -1455,7 +1819,11 @@ fn block_bits(b: &[i32]) -> i64 {
14551819 n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1;
14561820 }
14571821 }
1458- if n > 0 { n + 6 } else { 2 }
1822+ if n > 0 {
1823+ n + 6
1824+ } else {
1825+ 2
1826+ }
14591827 }
14601828
14611829 /// Rough bit cost of a macroblock's residual, for the skip decision: a level
@@ -1475,12 +1843,6 @@ fn estimate_bits(lv: &Levels) -> i64 {
14751843 bits
14761844 }
14771845
1478-/// Lagrangian multiplier in the squared-error domain, paired with
1479-/// [`super::lambda_for`] in the SATD one.
1480-fn lambda_ssd(qp: i32) -> f64 {
1481- 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2()
1482-}
1483-
14841846 /// Motion-compensate one partition into the picture planes.
14851847 fn compensate_part(
14861848 pic: &mut Picture,
@@ -1613,38 +1975,45 @@ fn encode_inter_mb(
16131975 // quantisation churn costs bits every picture and improves nothing.
16141976 let may_skip = choice.prefer_skip;
16151977 let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y));
1616- let mut lv = Levels::default();
1617- if e.transform_8x8 {
1978+ let mut chroma_lv = Levels::default();
1979+ code_chroma(pic, e, mb_x, mb_y, qp, false, &mut chroma_lv);
1980+ let mut lv = chroma_lv.clone();
1981+ if e.t8x8_inter(mb_y) {
16181982 // Both transform sizes on the same prediction; the cheaper
16191983 // rate-distortion cost is coded.
16201984 let mut pred = [0u8; 256];
16211985 save_luma(pic, mb_x, mb_y, &mut pred);
1622- code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv);
1623- let cost4 =
1624- ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv) as f64;
1986+ let mut lv4 = chroma_lv.clone();
1987+ code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv4);
1988+ let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4);
1989+ let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits4 as f64;
16251990 let mut recon4 = [0u8; 256];
16261991 save_luma(pic, mb_x, mb_y, &mut recon4);
16271992 restore_luma(pic, mb_x, mb_y, &pred);
1628- let mut lv8 = Levels::default();
1993+ let mut lv8 = chroma_lv;
16291994 code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8);
1630- let cost8 =
1631- ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_luma_bits(&lv8) as f64;
1632- if cost8 < cost4 {
1995+ let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8);
1996+ let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits8 as f64;
1997+ if cost8 + e.lambda * e.t8x8_margin_bits < cost4 {
16331998 lv = lv8;
16341999 } else {
2000+ lv = lv4;
16352001 restore_luma(pic, mb_x, mb_y, &recon4);
16362002 }
16372003 } else {
16382004 code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv);
16392005 }
1640- code_chroma(pic, e, mb_x, mb_y, qp, false, &mut lv);
16412006 let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0;
16422007 let skip = match ssd_skip {
16432008 None => false,
16442009 Some(_) if empty => true,
16452010 Some(ssd_skip) => {
1646- let coded =
1647- ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64;
2011+ let coded = if e.t8x8_inter(mb_y) {
2012+ let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv);
2013+ ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64
2014+ } else {
2015+ ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64
2016+ };
16482017 if ssd_skip as f64 <= coded {
16492018 // Put the prediction back: the residual has been added to it.
16502019 compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv);
crates/ec-h264/src/enc/mod.rsmodified+228 -20
@@ -28,19 +28,21 @@ mod quant;
2828 mod rc;
2929 mod vlc;
3030
31-use ec_core::BitWriter;
3231 use ec_core::error::{Error, Result};
33-use ec_h264_syntax::nal::{NalUnitType, escape_rbsp};
32+use ec_core::BitWriter;
33+use ec_h264_syntax::nal::{escape_rbsp, NalUnitType};
3434 use ec_h264_syntax::{SliceType, Sps};
3535
3636 use crate::decoder::deblock_picture;
3737 use crate::dpb::{Picture, SliceParams as DeblockParams};
3838 use crate::entropy::{FLAG_INTER, FLAG_TRANS8X8};
39+#[cfg(feature = "rd-ablation")]
40+use crate::entropy::FLAG_SKIP;
3941 use crate::transform::{LevelScale4x4, LevelScale8x8};
4042
4143 use entropy::EncEntropy;
42-use headers::{SeqParams, SliceParams, write_pps, write_slice_header, write_sps};
43-use mb::{MbEnc, Source, encode_mb};
44+use headers::{write_pps, write_slice_header, write_sps, SeqParams, SliceParams};
45+use mb::{encode_mb, MbEnc, Source};
4446 use rc::RateControl;
4547
4648 pub use mb::Preset;
@@ -74,17 +76,21 @@ pub struct EncoderConfig {
7476 pub qp: i32,
7577 /// 8x8 transform (High profile). Off by default.
7678 ///
77- /// NOT SAFE TO SET YET: this only flips the SPS/PPS High-profile tail
78- /// (`profile_idc` 100, `transform_8x8_mode_flag`). Once the PPS carries
79- /// that flag, a conformant decoder unconditionally reads an extra
80- /// `transform_size_8x8_flag` per macroblock (7.3.5: every non-I16x16
81- /// intra macroblock, and every inter macroblock with a nonzero luma cbp —
82- /// see `decoder.rs:1151` and `:1789-1793`). Nothing in `enc::entropy` /
83- /// `enc::mb` writes that bit yet, so turning this on desyncs every real
84- /// stream (headers.rs's own tests only exercise the parameter sets, not a
85- /// full encode). Wiring that emission — and then the mode decision that
86- /// actually picks 8x8 blocks — is later work.
79+ /// When enabled, eligible intra and inter luma macroblocks write
80+ /// `transform_size_8x8_flag` and choose the 8x8 path with a squared-error
81+ /// rate-distortion cost. Leaving it off preserves the Baseline/Main-profile
82+ /// 4x4 path.
8783 pub transform_8x8: bool,
84+ #[cfg(feature = "rd-ablation")]
85+ rd_lambda_standard: bool,
86+ #[cfg(feature = "rd-ablation")]
87+ rd_transform_8x8_intra: bool,
88+ #[cfg(feature = "rd-ablation")]
89+ rd_transform_8x8_inter: bool,
90+ #[cfg(feature = "rd-ablation")]
91+ rd_transform_8x8_roweven: bool,
92+ #[cfg(feature = "rd-ablation")]
93+ rd_transform_8x8_margin_bits: f64,
8894 }
8995
9096 impl EncoderConfig {
@@ -102,6 +108,16 @@ impl EncoderConfig {
102108 threads: 0,
103109 qp: 26,
104110 transform_8x8: false,
111+ #[cfg(feature = "rd-ablation")]
112+ rd_lambda_standard: false,
113+ #[cfg(feature = "rd-ablation")]
114+ rd_transform_8x8_intra: false,
115+ #[cfg(feature = "rd-ablation")]
116+ rd_transform_8x8_inter: false,
117+ #[cfg(feature = "rd-ablation")]
118+ rd_transform_8x8_roweven: false,
119+ #[cfg(feature = "rd-ablation")]
120+ rd_transform_8x8_margin_bits: 0.0,
105121 }
106122 }
107123 }
@@ -176,6 +192,10 @@ impl<'a> PictureView<'a> {
176192 impl Encoder {
177193 /// Build an encoder for `cfg`, refusing what it cannot code.
178194 pub fn new(cfg: EncoderConfig) -> Result<Encoder> {
195+ #[cfg(feature = "rd-ablation")]
196+ let mut cfg = cfg;
197+ #[cfg(feature = "rd-ablation")]
198+ apply_rd_ablation(&mut cfg);
179199 if cfg.width < 16 || cfg.height < 16 {
180200 return Err(Error::unsupported(
181201 "picture smaller than one macroblock",
@@ -385,7 +405,16 @@ impl Encoder {
385405 }
386406 }
387407 }
408+ // H5 measurement hook: the chosen candidate's trial SSD is the
409+ // pre-deblock SSD of the macroblock in this picture (round 4 verified
410+ // trial bits and SSD against the final picture), so capturing the
411+ // per-macroblock SSD right before and right after the filter is the
412+ // exact pre/post comparison with no hooks inside the RD trials.
413+ #[cfg(feature = "rd-ablation")]
414+ let rd_pre = rd_trace_capture(master, &self.src);
388415 deblock_picture(master);
416+ #[cfg(feature = "rd-ablation")]
417+ rd_trace_write(master, &self.src, self.frames, rd_pre);
389418 master.extend_borders();
390419 master.complete = true;
391420 std::mem::swap(master, &mut self.reference);
@@ -516,9 +545,14 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
516545 slice_id: job.slice_id,
517546 qp: job.qp,
518547 target_qp: job.qp,
519- lambda: lambda_for(job.qp),
548+ lambda: lambda_for(job.qp, rd_lambda_standard(job.cfg)),
549+ t8x8_margin_bits: rd_transform_8x8_margin_bits(job.cfg),
520550 preset: job.cfg.preset,
551+ lambda_standard: rd_lambda_standard(job.cfg),
521552 transform_8x8: job.cfg.transform_8x8,
553+ transform_8x8_intra: rd_transform_8x8_intra(job.cfg),
554+ transform_8x8_inter: rd_transform_8x8_inter(job.cfg),
555+ transform_8x8_roweven: rd_transform_8x8_roweven(job.cfg),
522556 ls: LevelScale4x4::new(&[16; 16]),
523557 ls8: LevelScale8x8::new(&[16; 64]),
524558 mb_ctx: crate::entropy::MbCtx::default(),
@@ -534,7 +568,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
534568 let expected = job.band_target * n as f64 / rows as f64;
535569 let delta = job.rc.row_delta(spent, expected);
536570 e.target_qp = (job.qp + delta).clamp(10, 51);
537- e.lambda = lambda_for(e.target_qp);
571+ e.lambda = lambda_for(e.target_qp, rd_lambda_standard(job.cfg));
538572 }
539573 for mb_x in 0..mb_w {
540574 let addr = mb_y * mb_w + mb_x;
@@ -546,10 +580,174 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
546580 w.finish(job.slice_type == SliceType::P)
547581 }
548582
549-/// Lagrangian multiplier for mode decision in the SATD domain.
550-fn lambda_for(qp: i32) -> i32 {
551- // 2^((qp - 12) / 6), the usual ladder, floored at 1.
552- (((f64::from(qp) - 12.0) / 6.0).exp2().round() as i32).max(1)
583+/// Standard Lagrangian multiplier in the squared-error domain.
584+pub(crate) fn lambda_ssd(qp: i32) -> f64 {
585+ 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2()
586+}
587+
588+/// Lagrangian multiplier. Production uses the established byte-stable ladder;
589+/// the ablation feature can select the standard squared-error multiplier.
590+fn lambda_for(qp: i32, standard: bool) -> f64 {
591+ if standard {
592+ lambda_ssd(qp)
593+ } else {
594+ (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0)
595+ }
596+}
597+
598+#[cfg(feature = "rd-ablation")]
599+fn apply_rd_ablation(cfg: &mut EncoderConfig) {
600+ if let Ok(lambda) = std::env::var("EC_H264_RD_LAMBDA") {
601+ cfg.rd_lambda_standard = match lambda.as_str() {
602+ "ladder" => false,
603+ "standard" => true,
604+ _ => panic!("EC_H264_RD_LAMBDA must be ladder or standard"),
605+ };
606+ }
607+ if let Ok(transform) = std::env::var("EC_H264_RD_T8X8") {
608+ let (intra, inter, roweven) = match transform.as_str() {
609+ "off" => (false, false, false),
610+ "on" => (true, true, false),
611+ "roweven" => (true, true, true),
612+ "intra" => (true, false, false),
613+ "inter" => (false, true, false),
614+ _ => panic!("EC_H264_RD_T8X8 must be off, on, roweven, intra, or inter"),
615+ };
616+ cfg.rd_transform_8x8_intra = intra;
617+ cfg.rd_transform_8x8_inter = inter;
618+ cfg.rd_transform_8x8_roweven = roweven;
619+ cfg.transform_8x8 = intra || inter;
620+ } else if cfg.transform_8x8 {
621+ cfg.rd_transform_8x8_intra = true;
622+ cfg.rd_transform_8x8_inter = true;
623+ }
624+ if let Ok(margin) = std::env::var("EC_H264_RD_T8X8_MARGIN_BITS") {
625+ cfg.rd_transform_8x8_margin_bits = margin
626+ .parse()
627+ .expect("EC_H264_RD_T8X8_MARGIN_BITS must be a number");
628+ }
629+}
630+
631+/// Luma and chroma SSD of every macroblock against the source, before the
632+/// deblocking filter — the distortion the RD decision actually paid.
633+#[cfg(feature = "rd-ablation")]
634+fn rd_trace_capture(pic: &Picture, src: &Source) -> Option<Vec<(i64, i64)>> {
635+ if std::env::var_os("EC_H264_RD_TRACE").is_none() {
636+ return None;
637+ }
638+ let mut out = Vec::with_capacity(pic.mb_w * pic.mb_h);
639+ for mb_y in 0..pic.mb_h {
640+ for mb_x in 0..pic.mb_w {
641+ out.push(rd_trace_ssd(pic, src, mb_x, mb_y));
642+ }
643+ }
644+ Some(out)
645+}
646+
647+/// One line per macroblock: `frame addr intra trans8 skip qp pre_luma
648+/// pre_chroma post_luma post_chroma`, appended to `$EC_H264_RD_TRACE`.
649+#[cfg(feature = "rd-ablation")]
650+fn rd_trace_write(pic: &Picture, src: &Source, frame: u64, pre: Option<Vec<(i64, i64)>>) {
651+ use std::io::Write;
652+ let Some(pre) = pre else { return };
653+ let mut out = std::fs::OpenOptions::new()
654+ .create(true)
655+ .append(true)
656+ .open(std::env::var_os("EC_H264_RD_TRACE").expect("checked in capture"))
657+ .expect("open EC_H264_RD_TRACE");
658+ for (addr, &(pre_luma, pre_chroma)) in pre.iter().enumerate() {
659+ let (post_luma, post_chroma) = rd_trace_ssd(pic, src, addr % pic.mb_w, addr / pic.mb_w);
660+ let f = pic.mb_flags[addr];
661+ let _ = writeln!(
662+ out,
663+ "{frame} {addr} {} {} {} {} {pre_luma} {pre_chroma} {post_luma} {post_chroma}",
664+ u8::from(f & FLAG_INTER == 0),
665+ u8::from(f & FLAG_TRANS8X8 != 0),
666+ u8::from(f & FLAG_SKIP != 0),
667+ pic.mb_qp[addr]
668+ );
669+ }
670+}
671+
672+/// Luma and chroma SSD of one macroblock against the source planes.
673+#[cfg(feature = "rd-ablation")]
674+fn rd_trace_ssd(pic: &Picture, src: &Source, mb_x: usize, mb_y: usize) -> (i64, i64) {
675+ let mut luma = 0i64;
676+ let stride = pic.y.stride;
677+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
678+ for row in 0..16 {
679+ let s = (mb_y * 16 + row) * src.stride + mb_x * 16;
680+ for x in 0..16 {
681+ let d = i64::from(src.y[s + x]) - i64::from(pic.y.data[origin + row * stride + x]);
682+ luma += d * d;
683+ }
684+ }
685+ let mut chroma = 0i64;
686+ for (plane, source) in [(&pic.cb, &src.u), (&pic.cr, &src.v)] {
687+ let stride = plane.stride;
688+ let origin = plane.at(mb_x * 8, mb_y * 8);
689+ for row in 0..8 {
690+ let s = (mb_y * 8 + row) * src.c_stride + mb_x * 8;
691+ for x in 0..8 {
692+ let d = i64::from(source[s + x]) - i64::from(plane.data[origin + row * stride + x]);
693+ chroma += d * d;
694+ }
695+ }
696+ }
697+ (luma, chroma)
698+}
699+
700+#[cfg(feature = "rd-ablation")]
701+fn rd_lambda_standard(cfg: &EncoderConfig) -> bool {
702+ cfg.rd_lambda_standard
703+}
704+
705+#[cfg(not(feature = "rd-ablation"))]
706+fn rd_lambda_standard(cfg: &EncoderConfig) -> bool {
707+ cfg.transform_8x8
708+}
709+
710+#[cfg(feature = "rd-ablation")]
711+fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool {
712+ cfg.rd_transform_8x8_intra
713+}
714+
715+#[cfg(not(feature = "rd-ablation"))]
716+fn rd_transform_8x8_intra(cfg: &EncoderConfig) -> bool {
717+ cfg.transform_8x8
718+}
719+
720+#[cfg(feature = "rd-ablation")]
721+fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool {
722+ cfg.rd_transform_8x8_inter
723+}
724+
725+#[cfg(not(feature = "rd-ablation"))]
726+fn rd_transform_8x8_inter(cfg: &EncoderConfig) -> bool {
727+ cfg.transform_8x8
728+}
729+
730+#[cfg(feature = "rd-ablation")]
731+fn rd_transform_8x8_roweven(cfg: &EncoderConfig) -> bool {
732+ cfg.rd_transform_8x8_roweven
733+}
734+
735+#[cfg(not(feature = "rd-ablation"))]
736+fn rd_transform_8x8_roweven(_: &EncoderConfig) -> bool {
737+ false
738+}
739+
740+#[cfg(not(feature = "rd-ablation"))]
741+const TRANSFORM_8X8_MARGIN_BITS: f64 = 0.0;
742+
743+#[cfg(feature = "rd-ablation")]
744+fn rd_transform_8x8_margin_bits(cfg: &EncoderConfig) -> f64 {
745+ cfg.rd_transform_8x8_margin_bits
746+}
747+
748+#[cfg(not(feature = "rd-ablation"))]
749+fn rd_transform_8x8_margin_bits(_: &EncoderConfig) -> f64 {
750+ TRANSFORM_8X8_MARGIN_BITS
553751 }
554752
555753 /// Split `mb_h` macroblock rows into at most `n` contiguous bands.
@@ -707,4 +905,14 @@ mod tests {
707905 assert!(matches!(err, Error::Unsupported { .. }), "{err}");
708906 assert!(Encoder::new(EncoderConfig::new(640, 480)).is_ok());
709907 }
908+ #[test]
909+ fn production_lambda_tracks_transform_mode() {
910+ let mut cfg = EncoderConfig::new(640, 480);
911+ assert_eq!(
912+ lambda_for(26, rd_lambda_standard(&cfg)),
913+ lambda_for(26, false)
914+ );
915+ cfg.transform_8x8 = true;
916+ assert_eq!(lambda_for(26, rd_lambda_standard(&cfg)), lambda_ssd(26));
917+ }
710918 }
crates/ec-h264/tests/encode.rsmodified+76 -23
@@ -122,6 +122,66 @@ fn psnr(a: &[u8], b: &[u8]) -> f64 {
122122 }
123123 }
124124
125+fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] {
126+ let mut a = [[0.0; 5]; 4];
127+ for i in 0..4 {
128+ a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]];
129+ }
130+ for col in 0..4 {
131+ let mut pivot = col;
132+ for row in col + 1..4 {
133+ if a[row][col].abs() > a[pivot][col].abs() {
134+ pivot = row;
135+ }
136+ }
137+ a.swap(col, pivot);
138+ let div = a[col][col];
139+ assert!(div.abs() > 1e-12, "singular BD-PSNR fit");
140+ for j in col..5 {
141+ a[col][j] /= div;
142+ }
143+ for row in 0..4 {
144+ if row == col {
145+ continue;
146+ }
147+ let f = a[row][col];
148+ for j in col..5 {
149+ a[row][j] -= f * a[col][j];
150+ }
151+ }
152+ }
153+ [a[0][4], a[1][4], a[2][4], a[3][4]]
154+}
155+
156+fn cubic_integral(c: [f64; 4], x: f64) -> f64 {
157+ c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0
158+}
159+
160+fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> f64 {
161+ let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln());
162+ let ys_candidate = std::array::from_fn(|i| candidate[i].1);
163+ let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln());
164+ let ys_anchor = std::array::from_fn(|i| anchor[i].1);
165+ let lo = xs_candidate
166+ .iter()
167+ .copied()
168+ .fold(f64::INFINITY, f64::min)
169+ .max(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min));
170+ let hi = xs_candidate
171+ .iter()
172+ .copied()
173+ .fold(f64::NEG_INFINITY, f64::max)
174+ .min(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max));
175+ assert!(hi > lo, "BD-PSNR curves do not overlap in bitrate");
176+ let c_candidate = cubic_fit(xs_candidate, ys_candidate);
177+ let c_anchor = cubic_fit(xs_anchor, ys_anchor);
178+ (cubic_integral(c_candidate, hi)
179+ - cubic_integral(c_candidate, lo)
180+ - cubic_integral(c_anchor, hi)
181+ + cubic_integral(c_anchor, lo))
182+ / (hi - lo)
183+}
184+
125185 /// The encoder's reconstruction and a decode of its bitstream agree sample for
126186 /// sample, over a QP sweep, both presets, single and multi threaded.
127187 #[test]
@@ -350,8 +410,8 @@ fn encode_clip(
350410 }
351411
352412 /// Flat gradients and glyph-like rectangles: the content the 8x8 transform
353-/// exists for. A 10-frame clip with the flag on must beat the flag off by at
354-/// least 0.3 dB at equal bits, or by 5% fewer bits at equal PSNR.
413+/// exists for. A 10-frame clip with the flag on must keep a clear positive
414+/// gain at equal bits, or cut bits at equal PSNR.
355415 #[test]
356416 fn eight_by_eight_gains_on_flat_and_text() {
357417 let (w, h) = (320, 240);
@@ -382,11 +442,12 @@ fn eight_by_eight_gains_on_flat_and_text() {
382442 clip.u.fill(128);
383443 clip.v.fill(128);
384444 };
385- let run = |t8x8: bool, qp: i32| {
445+ let run = |t8x8: bool, qp: i32, cabac: bool| {
386446 let mut cfg = EncoderConfig::new(w as u32, h as u32);
387447 cfg.qp = qp;
388448 cfg.gop_size = 10;
389449 cfg.transform_8x8 = t8x8;
450+ cfg.cabac = cabac;
390451 let mut enc = Encoder::new(cfg).expect("encoder");
391452 let mut clip = Clip::new(w, h);
392453 let (mut bits, mut sum_psnr) = (0usize, 0.0);
@@ -404,31 +465,23 @@ fn eight_by_eight_gains_on_flat_and_text() {
404465 }
405466 (bits as f64, sum_psnr / 10.0, share)
406467 };
407- // Interpolate the off curve at the on point's bits / PSNR.
408- let qp = 26;
409- let (bits_on, psnr_on, share) = run(true, qp);
410- let off: Vec<_> = [qp - 2, qp, qp + 2]
411- .iter()
412- .map(|&q| run(false, q))
413- .collect();
414- let (bits_off, psnr_off, _) = off[1];
415- // Local slopes of the off curve, from the neighbouring QPs.
416- let dpsnr_dbits = (off[0].1 - off[2].1) / (off[0].0 - off[2].0);
417- let psnr_off_at_on_bits = psnr_off + (bits_on - bits_off) * dpsnr_dbits;
418- let bits_off_at_on_psnr = bits_off + (psnr_on - psnr_off) / dpsnr_dbits;
419- let gain_db = psnr_on - psnr_off_at_on_bits;
420- let saving = 1.0 - bits_on / bits_off_at_on_psnr;
468+ let qps = [22, 26, 30, 34];
469+ let on: Vec<_> = qps.iter().map(|&q| run(true, q, true)).collect();
470+ let off: Vec<_> = qps.iter().map(|&q| run(false, q, true)).collect();
471+ let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
472+ let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
473+ let bd = bd_psnr_delta(&on_curve, &off_curve);
474+ let share = on.iter().map(|&(_, _, share)| share).sum::<f64>() / on.len() as f64;
475+ const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.255_347;
421476 eprintln!(
422- "8x8 qp {qp}: on {bits_on:.0} bits {psnr_on:.2} dB, off {bits_off:.0} bits {psnr_off:.2} dB; \
423- gain at equal bits {gain_db:+.2} dB, saving at equal PSNR {:.1}%, 8x8 MB share {:.1}%",
424- saving * 100.0,
477+ "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%",
425478 share * 100.0
426479 );
427480 assert!(share > 0.0, "no 8x8 macroblocks were coded");
481+ assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off");
428482 assert!(
429- gain_db >= 0.3 || saving >= 0.05,
430- "8x8 gain {gain_db:+.2} dB / {:.1}% is below the bar",
431- saving * 100.0
483+ bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB,
484+ "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate"
432485 );
433486 }
434487