forge
Explore
Log in

Don't you dare go Hollow

Correct transform RD accounting

Browse files at this commit

b6c957803b10902689ec6b6bd7252f73671ce058Ahmet Kaan GümüşParent: fa65f3e
  • fix
    • correct transform RD accounting
Show full message
fix(h264): correct transform RD accounting
crates/ec-h264/src/enc/mb.rsmodified+170 -72
@@ -31,16 +31,19 @@ use crate::pred::{
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,8 +78,8 @@ 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 for SATD and motion-vector costs.
82+ pub lambda_motion: f64,
8083 pub preset: Preset,
8184 /// The PPS carries transform_8x8_mode_flag: transform_size_8x8_flag must
8285 /// be written for every eligible macroblock (7.3.5).
@@ -93,6 +96,7 @@ pub(crate) struct MbEnc<'a> {
9396 }
9497
9598 /// Quantised levels of one macroblock, scan order per block.
99+#[derive(Clone)]
96100 struct Levels {
97101 /// Luma AC/4x4 blocks in Z-order; only `[..15]` is used under Intra_16x16.
98102 luma: [[i32; 16]; 16],
@@ -276,6 +280,11 @@ fn modes_allowed(have_top: bool, have_left: bool, have_tl: bool) -> [bool; 9] {
276280 ]
277281 }
278282
283+#[inline]
284+fn motion_rate(e: &MbEnc<'_>, bits: f64) -> i32 {
285+ (e.lambda_motion * bits).round() as i32
286+}
287+
279288 /// Code one macroblock: decide its mode, reconstruct it into `pic` and write
280289 /// its syntax into `w`.
281290 pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy, mb_addr: usize) {
@@ -323,7 +332,7 @@ pub(crate) fn encode_mb(pic: &mut Picture, e: &mut MbEnc<'_>, w: &mut EncEntropy
323332 let intra_cost = intra_pre_cost(pic, e, &nbr, mb_x, mb_y);
324333 let go_intra = match &inter {
325334 None => true,
326- Some(i) => intra_cost.best() + e.lambda * 8 < i.cost,
335+ Some(i) => intra_cost.best() + motion_rate(e, 8.0) < i.cost,
327336 };
328337
329338 if go_intra {
@@ -502,9 +511,11 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
502511 // which is what a search can afford; the winner is re-costed on SATD
503512 // because the intra candidates are SATD and the two scales differ.
504513 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;
514+ let bits = motion_rate(
515+ e,
516+ f64::from(se_bits(i32::from(mv[0] - mvp[0])) + se_bits(i32::from(mv[1] - mvp[1])))
517+ / 2.0,
518+ );
508519 if !satd && mv[0] & 3 == 0 && mv[1] & 3 == 0 {
509520 let o = integer_origin(
510521 &plane,
@@ -592,7 +603,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
592603 let skip_cost = {
593604 let mut buf = [0u8; 256];
594605 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
606+ satd_block(&e.src.y, sw, sx, sy, &buf, 16, 0, 16, 16) - motion_rate(e, 4.0)
596607 };
597608
598609 let mut best = (PShape::Whole, [mv16, mv16], cost16);
@@ -607,7 +618,7 @@ fn choose_inter(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> Inter
607618 // time. That is a Balanced trade, not a Fast one.
608619 if e.preset == Preset::Balanced && cost16 > 16 * 16 {
609620 for shape in [PShape::Horizontal, PShape::Vertical] {
610- let mut total = e.lambda * 6; // the partition's own signalling
621+ let mut total = motion_rate(e, 6.0); // the partition's own signalling
611622 let mut mvs = [[0i16; 2]; 2];
612623 for part in 0..2 {
613624 let ((bx, by), (w, h)) = shape.geometry(part);
@@ -671,7 +682,7 @@ fn code_luma_4x4(
671682 // half of rate-distortion optimised quantisation, and the half that
672683 // pays. Intra blocks are left alone: their reconstruction is what the
673684 // next block in the macroblock predicts from.
674- if !intra && !worth_coding(&source, &resid, &lv.luma[blk], qp) {
685+ if !intra && !worth_coding(&source, &resid, &lv.luma[blk], zero_block_lambda(e, qp)) {
675686 lv.luma[blk] = [0; 16];
676687 lv.luma_nz[blk] = 0;
677688 continue;
@@ -691,9 +702,17 @@ fn code_luma_4x4(
691702 /// without costing camera content.
692703 const ZERO_BLOCK_LAMBDA: f64 = 0.4;
693704
705+fn zero_block_lambda(e: &MbEnc<'_>, qp: i32) -> f64 {
706+ if e.transform_8x8 {
707+ lambda_ssd(qp)
708+ } else {
709+ ZERO_BLOCK_LAMBDA * lambda_ssd(qp)
710+ }
711+}
712+
694713 /// The rate-distortion test behind the per-block zero decision: coding the
695714 /// 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 {
715+fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], lambda: f64) -> bool {
697716 let mut ssd_zero = 0i64;
698717 let mut ssd_coded = 0i64;
699718 for i in 0..source.len() {
@@ -702,8 +721,7 @@ fn worth_coding(source: &[i32], resid: &[i32], levels: &[i32], qp: i32) -> bool
702721 ssd_zero += z * z;
703722 ssd_coded += c * c;
704723 }
705- ssd_coded as f64 + ZERO_BLOCK_LAMBDA * lambda_ssd(qp) * (block_bits(levels) as f64)
706- < ssd_zero as f64
724+ ssd_coded as f64 + lambda * (block_bits(levels) as f64) < ssd_zero as f64
707725 }
708726
709727 /// Predict and code the luma of an Intra_16x16 macroblock.
@@ -847,7 +865,7 @@ fn code_chroma(
847865 dequant_4x4(&mut raster, &e.ls, qp_c, true);
848866 let mut resid = [0i32; 16];
849867 inverse_transform_4x4(&raster, &mut resid);
850- if !worth_coding(&source, &resid, &ac[comp][blk], qp_c) {
868+ if !worth_coding(&source, &resid, &ac[comp][blk], zero_block_lambda(e, qp_c)) {
851869 ac[comp][blk] = [0; 16];
852870 nz = 0;
853871 }
@@ -1019,7 +1037,7 @@ fn code_intra_4x4(
10191037 }
10201038 pred_4x4(mode, &n, &mut p);
10211039 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;
1040+ let c = satd4(&e.src.y, e.src.stride, x, y, &p, 4) + motion_rate(e, f64::from(bits));
10231041 if c < best.0 {
10241042 best = (c, mode);
10251043 }
@@ -1101,7 +1119,7 @@ fn code_block_8x8(
11011119 dequant_8x8(&mut raster, &e.ls8, qp);
11021120 let mut resid = [0i32; 64];
11031121 inverse_transform_8x8(&raster, &mut resid);
1104- if !intra && !worth_coding(&d, &resid, out, qp) {
1122+ if !intra && !worth_coding(&d, &resid, out, zero_block_lambda(e, qp)) {
11051123 *out = [0; 64];
11061124 return 0;
11071125 }
@@ -1140,7 +1158,7 @@ fn code_intra_8x8(
11401158 }
11411159 pred_8x8(mode, &n, &mut p);
11421160 let bits = if mode == predicted { 1 } else { 4 };
1143- let mut c = e.lambda * bits;
1161+ let mut c = motion_rate(e, f64::from(bits));
11441162 for q in 0..4 {
11451163 let (ox, oy) = ((q % 2) * 4, (q / 2) * 4);
11461164 c += satd4(&e.src.y, e.src.stride, x + ox, y + oy, &p[oy * 8 + ox..], 8);
@@ -1220,13 +1238,9 @@ fn restore_luma(pic: &mut Picture, mb_x: usize, mb_y: usize, src: &[u8; 256]) {
12201238 }
12211239 }
12221240
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 {
1241+fn rough_intra_bits(lv: &Levels, i4: Option<(&[u8], &[u8])>) -> i64 {
12261242 let mut bits = estimate_luma_bits(lv);
12271243 match i4 {
1228- // Sixteen (or four) mode signals plus the coded_block_pattern the
1229- // 16x16 form derives from its macroblock type instead.
12301244 Some((modes, pred)) => {
12311245 bits += 6;
12321246 for blk in 0..modes.len() {
@@ -1334,8 +1348,70 @@ fn write_luma_for_cost(
13341348 }
13351349 }
13361350 }
1351+fn cost_chroma_nz_pair(
1352+ pic: &Picture,
1353+ nbr: &MbNeighbors,
1354+ local: &[[u8; 4]; 2],
1355+ comp: usize,
1356+ cx0: usize,
1357+ cy0: usize,
1358+ cx: usize,
1359+ cy: usize,
1360+) -> (Option<u8>, Option<u8>) {
1361+ let w2 = pic.mb_w * 2;
1362+ let left_avail = if cx.is_multiple_of(2) { nbr.a } else { true };
1363+ let top_avail = if cy.is_multiple_of(2) { nbr.b } else { true };
1364+ let left = (left_avail && cx > 0).then(|| {
1365+ if cx > cx0 {
1366+ local[comp][(cy - cy0) * 2 + (cx - cx0 - 1)]
1367+ } else {
1368+ pic.nz_c[comp][cy * w2 + cx - 1]
1369+ }
1370+ });
1371+ let top = (top_avail && cy > 0).then(|| {
1372+ if cy > cy0 {
1373+ local[comp][(cy - cy0 - 1) * 2 + (cx - cx0)]
1374+ } else {
1375+ pic.nz_c[comp][(cy - 1) * w2 + cx]
1376+ }
1377+ });
1378+ (left, top)
1379+}
13371380
1338-fn intra_luma_bits(
1381+fn write_chroma_for_cost(
1382+ pic: &Picture,
1383+ nbr: &MbNeighbors,
1384+ w: &mut EncEntropy,
1385+ mb_x: usize,
1386+ mb_y: usize,
1387+ lv: &Levels,
1388+) {
1389+ if lv.cbp_chroma != 0 {
1390+ for comp in 0..2 {
1391+ w.residual_block(
1392+ &lv.chroma_dc[comp][..4],
1393+ BlockCat::ChromaDc(comp as u8),
1394+ None,
1395+ None,
1396+ );
1397+ }
1398+ }
1399+ if lv.cbp_chroma != 2 {
1400+ return;
1401+ }
1402+ let (cx0, cy0) = (mb_x * 2, mb_y * 2);
1403+ let mut nz = [[0u8; 4]; 2];
1404+ for comp in 0..2 {
1405+ for blk in 0..4 {
1406+ let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1));
1407+ let (na, nb) = cost_chroma_nz_pair(pic, nbr, &nz, comp, cx0, cy0, cx, cy);
1408+ nz[comp][blk] =
1409+ w.residual_block(&lv.chroma[comp][blk][..15], BlockCat::ChromaAc, na, nb);
1410+ }
1411+ }
1412+}
1413+
1414+fn intra_mb_bits(
13391415 pic: &Picture,
13401416 e: &MbEnc<'_>,
13411417 w: &EncEntropy,
@@ -1344,6 +1420,7 @@ fn intra_luma_bits(
13441420 lv: &Levels,
13451421 i4: Option<(&[u8], &[u8])>,
13461422 i16_mode: u8,
1423+ chroma_mode: u8,
13471424 ) -> i64 {
13481425 let use_i4 = i4.is_some();
13491426 let p_slice = e.slice_type == SliceType::P;
@@ -1351,7 +1428,9 @@ fn intra_luma_bits(
13511428 let intra_type = if use_i4 {
13521429 0
13531430 } else {
1354- 1 + u32::from(i16_mode) + if lv.cbp_luma != 0 { 12 } else { 0 }
1431+ 1 + u32::from(i16_mode)
1432+ + 4 * u32::from(lv.cbp_chroma)
1433+ + if lv.cbp_luma != 0 { 12 } else { 0 }
13551434 };
13561435 entropy_bits(w, |cw| {
13571436 cw.begin_mb(&e.mb_ctx);
@@ -1372,18 +1451,23 @@ fn intra_luma_bits(
13721451 };
13731452 cw.intra4x4_pred_mode(rem);
13741453 }
1375- cw.coded_block_pattern(lv.cbp_luma, 0, true);
13761454 }
1377- if !use_i4 || lv.cbp_luma != 0 {
1455+ cw.intra_chroma_pred_mode(chroma_mode);
1456+ if use_i4 {
1457+ cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, true);
1458+ }
1459+ let coded = lv.cbp_luma != 0 || lv.cbp_chroma != 0 || !use_i4;
1460+ if coded {
13781461 cw.mb_qp_delta(e.target_qp - e.qp);
13791462 }
13801463 let mb_x = mb_addr % pic.mb_w;
13811464 let mb_y = mb_addr / pic.mb_w;
13821465 write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, !use_i4);
1466+ write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
13831467 })
13841468 }
13851469
1386-fn inter_luma_bits(
1470+fn inter_mb_bits(
13871471 pic: &Picture,
13881472 e: &MbEnc<'_>,
13891473 w: &EncEntropy,
@@ -1404,15 +1488,16 @@ fn inter_luma_bits(
14041488 cw.mvd(comp, inc[part][comp], i32::from(mvd[part][comp]));
14051489 }
14061490 }
1407- cw.coded_block_pattern(lv.cbp_luma, 0, false);
1491+ cw.coded_block_pattern(lv.cbp_luma, lv.cbp_chroma, false);
14081492 if lv.cbp_luma != 0 && e.transform_8x8 {
14091493 cw.transform_size_8x8_flag(lv.trans8);
14101494 }
1411- if lv.cbp_luma != 0 {
1495+ if lv.cbp_luma != 0 || lv.cbp_chroma != 0 {
14121496 cw.mb_qp_delta(e.target_qp - e.qp);
14131497 let mb_x = mb_addr % pic.mb_w;
14141498 let mb_y = mb_addr / pic.mb_w;
14151499 write_luma_for_cost(pic, nbr, cw, mb_x, mb_y, lv, false);
1500+ write_chroma_for_cost(pic, nbr, cw, mb_x, mb_y, lv);
14161501 }
14171502 })
14181503 }
@@ -1439,20 +1524,22 @@ fn encode_intra_mb(
14391524 let (bx0, by0) = (mb_x * 4, mb_y * 4);
14401525 let qp = e.target_qp;
14411526 write_intra_mb(pic, mb_x, mb_y);
1442- let mut lv = Levels::default();
1527+ let mut lv: Levels;
14431528 let mut modes = [2u8; 16];
14441529 let mut pred_modes = [2u8; 16];
14451530 let mut modes8 = [2u8; 4];
14461531 let mut pred_modes8 = [2u8; 4];
14471532 let mut use_i4 = false;
1533+ let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y);
1534+ let mut chroma_lv = Levels::default();
1535+ code_chroma(pic, e, mb_x, mb_y, qp, true, &mut chroma_lv);
14481536 let mut use_i8 = false;
14491537
14501538 if cost.allow_i4 {
1451- let mut lv4 = Levels::default();
1539+ let mut lv4 = chroma_lv.clone();
14521540 let (m4, p4) = code_intra_4x4(pic, e, mb_x, mb_y, qp, &nbr, &mut lv4);
1453- let allow_t8 = e.transform_8x8 && qp < 30;
14541541 let cost4 = if e.transform_8x8 {
1455- let bits = intra_luma_bits(
1542+ let bits = intra_mb_bits(
14561543 pic,
14571544 e,
14581545 w,
@@ -1461,11 +1548,12 @@ fn encode_intra_mb(
14611548 &lv4,
14621549 Some((&m4, &p4)),
14631550 cost.i16_mode,
1551+ chroma_mode,
14641552 );
1465- ssd_luma(pic, e, mb_x, mb_y) as f64 + rd_lambda(qp) * bits as f64
1553+ ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * bits as f64
14661554 } else {
14671555 ssd_luma(pic, e, mb_x, mb_y) as f64
1468- + lambda_ssd(qp) * intra_bits(&lv4, Some((&m4, &p4))) as f64
1556+ + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64
14691557 };
14701558 let mut recon4 = [0u8; 256];
14711559 save_luma(pic, mb_x, mb_y, &mut recon4);
@@ -1476,14 +1564,14 @@ fn encode_intra_mb(
14761564 }
14771565
14781566 // Intra_8x8 on the same terms, when the PPS allows it.
1479- let mut lv8 = Levels::default();
1567+ let mut lv8 = chroma_lv.clone();
14801568 let mut recon8 = [0u8; 256];
1481- let cost8 = if allow_t8 {
1569+ let cost8 = if e.transform_8x8 {
14821570 let (m8, p8) = code_intra_8x8(pic, e, mb_x, mb_y, qp, &nbr, &mut lv8);
14831571 modes8 = m8;
14841572 pred_modes8 = p8;
14851573 save_luma(pic, mb_x, mb_y, &mut recon8);
1486- let bits = intra_luma_bits(
1574+ let bits = intra_mb_bits(
14871575 pic,
14881576 e,
14891577 w,
@@ -1492,19 +1580,31 @@ fn encode_intra_mb(
14921580 &lv8,
14931581 Some((&m8, &p8)),
14941582 cost.i16_mode,
1583+ chroma_mode,
14951584 );
1496- ssd_luma(pic, e, mb_x, mb_y) as f64 + rd_lambda(qp) * bits as f64
1585+ ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * bits as f64
14971586 } else {
14981587 f64::INFINITY
14991588 };
15001589
1501- let mut lv16 = Levels::default();
1590+ let mut lv16 = chroma_lv;
15021591 code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv16);
15031592 let cost16 = if e.transform_8x8 {
1504- let bits = intra_luma_bits(pic, e, w, mb_addr, &nbr, &lv16, None, cost.i16_mode);
1505- ssd_luma(pic, e, mb_x, mb_y) as f64 + rd_lambda(qp) * bits as f64
1593+ let bits = intra_mb_bits(
1594+ pic,
1595+ e,
1596+ w,
1597+ mb_addr,
1598+ &nbr,
1599+ &lv16,
1600+ None,
1601+ cost.i16_mode,
1602+ chroma_mode,
1603+ );
1604+ ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * bits as f64
15061605 } else {
1507- ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * intra_bits(&lv16, None) as f64
1606+ ssd_luma(pic, e, mb_x, mb_y) as f64
1607+ + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64
15081608 };
15091609
15101610 if cost8 <= cost4 && cost8 <= cost16 {
@@ -1532,12 +1632,10 @@ fn encode_intra_mb(
15321632 lv = lv16;
15331633 }
15341634 } else {
1635+ lv = chroma_lv;
15351636 code_i16_luma(pic, e, mb_x, mb_y, qp, cost.i16_mode, &nbr, &mut lv);
15361637 }
15371638
1538- let chroma_mode = choose_chroma_mode(pic, e, &nbr, mb_x, mb_y);
1539- code_chroma(pic, e, mb_x, mb_y, qp, true, &mut lv);
1540-
15411639 // ---- syntax ----
15421640 w.begin_mb(&e.mb_ctx);
15431641 w.coded_mb(e.slice_type == SliceType::P, e.skip_inc);
@@ -1662,7 +1760,11 @@ fn block_bits(b: &[i32]) -> i64 {
16621760 n += 2 * (64 - u64::from(l.unsigned_abs()).leading_zeros() as i64) + 1;
16631761 }
16641762 }
1665- if n > 0 { n + 6 } else { 2 }
1763+ if n > 0 {
1764+ n + 6
1765+ } else {
1766+ 2
1767+ }
16661768 }
16671769
16681770 /// Rough bit cost of a macroblock's residual, for the skip decision: a level
@@ -1682,17 +1784,6 @@ fn estimate_bits(lv: &Levels) -> i64 {
16821784 bits
16831785 }
16841786
1685-/// Lagrangian multiplier in the squared-error domain, paired with
1686-/// [`super::lambda_for`] in the SATD one.
1687-fn lambda_ssd(qp: i32) -> f64 {
1688- 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2()
1689-}
1690-
1691-fn rd_lambda(qp: i32) -> f64 {
1692- let scale = if qp <= 22 { 1.0 } else { 0.25 };
1693- lambda_ssd(qp) * scale
1694-}
1695-
16961787 /// Motion-compensate one partition into the picture planes.
16971788 fn compensate_part(
16981789 pic: &mut Picture,
@@ -1825,38 +1916,45 @@ fn encode_inter_mb(
18251916 // quantisation churn costs bits every picture and improves nothing.
18261917 let may_skip = choice.prefer_skip;
18271918 let ssd_skip = may_skip.then(|| ssd_mb(pic, e, mb_x, mb_y));
1828- let mut lv = Levels::default();
1829- if e.transform_8x8 && qp < 30 {
1919+ let mut chroma_lv = Levels::default();
1920+ code_chroma(pic, e, mb_x, mb_y, qp, false, &mut chroma_lv);
1921+ let mut lv = chroma_lv.clone();
1922+ if e.transform_8x8 {
18301923 // Both transform sizes on the same prediction; the cheaper
18311924 // rate-distortion cost is coded.
18321925 let mut pred = [0u8; 256];
18331926 save_luma(pic, mb_x, mb_y, &mut pred);
1834- code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv);
1835- let bits4 = inter_luma_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv);
1836- let cost4 = ssd_luma(pic, e, mb_x, mb_y) as f64 + rd_lambda(qp) * bits4 as f64;
1927+ let mut lv4 = chroma_lv.clone();
1928+ code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv4);
1929+ let bits4 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv4);
1930+ let cost4 = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * bits4 as f64;
18371931 let mut recon4 = [0u8; 256];
18381932 save_luma(pic, mb_x, mb_y, &mut recon4);
18391933 restore_luma(pic, mb_x, mb_y, &pred);
1840- let mut lv8 = Levels::default();
1934+ let mut lv8 = chroma_lv;
18411935 code_luma_8x8(pic, e, mb_x, mb_y, qp, &mut lv8);
1842- let bits8 = inter_luma_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8);
1843- let cost8 = ssd_luma(pic, e, mb_x, mb_y) as f64 + rd_lambda(qp) * bits8 as f64;
1936+ let bits8 = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv8);
1937+ let cost8 = ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * bits8 as f64;
18441938 if cost8 < cost4 {
18451939 lv = lv8;
18461940 } else {
1941+ lv = lv4;
18471942 restore_luma(pic, mb_x, mb_y, &recon4);
18481943 }
18491944 } else {
18501945 code_luma_4x4(pic, e, mb_x, mb_y, qp, false, &mut lv);
18511946 }
1852- code_chroma(pic, e, mb_x, mb_y, qp, false, &mut lv);
18531947 let empty = lv.cbp_luma == 0 && lv.cbp_chroma == 0;
18541948 let skip = match ssd_skip {
18551949 None => false,
18561950 Some(_) if empty => true,
18571951 Some(ssd_skip) => {
1858- let coded =
1859- ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64;
1952+ let coded = if e.transform_8x8 {
1953+ let bits = inter_mb_bits(pic, e, w, mb_addr, &nbr, shape, &mvd, &inc, &lv);
1954+ ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * bits as f64
1955+ } else {
1956+ ssd_mb(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * estimate_bits(&lv) as f64
1957+ };
18601958 if ssd_skip as f64 <= coded {
18611959 // Put the prediction back: the residual has been added to it.
18621960 compensate_part(pic, reference, mb_x, mb_y, (0, 0), (16, 16), choice.skip_mv);
crates/ec-h264/src/enc/mod.rsmodified+16 -14
@@ -28,8 +28,8 @@ mod quant;
2828 mod rc;
2929 mod vlc;
3030
31-use ec_core::BitWriter;
3231 use ec_core::error::{Error, Result};
32+use ec_core::BitWriter;
3333 use ec_h264_syntax::nal::{NalUnitType, escape_rbsp};
3434 use ec_h264_syntax::{SliceType, Sps};
3535
@@ -190,13 +190,6 @@ impl Encoder {
190190 "no level defines a picture this large for this profile",
191191 ));
192192 }
193- // corner-cut: high-QP 8x8 trials bought header/syntax cost without a
194- // matched-bit quality win on the harness clips; revisit with a
195- // picture-level RD curve instead of a macroblock-only decision.
196- let mut cfg = cfg;
197- if cfg.transform_8x8 && cfg.bitrate == 0 && cfg.qp >= 30 {
198- cfg.transform_8x8 = false;
199- }
200193 let mb_w = cfg.width.div_ceil(16);
201194 let mb_h = cfg.height.div_ceil(16);
202195 let fps = f64::from(cfg.framerate.max(1.0));
@@ -517,7 +510,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
517510 slice_id: job.slice_id,
518511 qp: job.qp,
519512 target_qp: job.qp,
520- lambda: lambda_for(job.qp),
513+ lambda_motion: lambda_for(job.qp, job.cfg.transform_8x8),
521514 preset: job.cfg.preset,
522515 transform_8x8: job.cfg.transform_8x8,
523516 ls: LevelScale4x4::new(&[16; 16]),
@@ -535,7 +528,7 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
535528 let expected = job.band_target * n as f64 / rows as f64;
536529 let delta = job.rc.row_delta(spent, expected);
537530 e.target_qp = (job.qp + delta).clamp(10, 51);
538- e.lambda = lambda_for(e.target_qp);
531+ e.lambda_motion = lambda_for(e.target_qp, job.cfg.transform_8x8);
539532 }
540533 for mb_x in 0..mb_w {
541534 let addr = mb_y * mb_w + mb_x;
@@ -547,10 +540,19 @@ fn code_band(pic: &mut Picture, job: BandJob<'_>) -> Vec<u8> {
547540 w.finish(job.slice_type == SliceType::P)
548541 }
549542
550-/// Lagrangian multiplier for mode decision in the SATD domain.
551-fn lambda_for(qp: i32) -> i32 {
552- // 2^((qp - 12) / 6), the usual ladder, floored at 1.
553- (((f64::from(qp) - 12.0) / 6.0).exp2().round() as i32).max(1)
543+/// Standard Lagrangian multiplier in the squared-error domain.
544+pub(crate) fn lambda_ssd(qp: i32) -> f64 {
545+ 0.85 * ((f64::from(qp) - 12.0) / 3.0).exp2()
546+}
547+
548+/// Lagrangian multiplier for SATD and motion-vector costs.
549+fn lambda_for(qp: i32, transform_8x8: bool) -> f64 {
550+ if transform_8x8 {
551+ lambda_ssd(qp).sqrt()
552+ } else {
553+ // The established 4x4 path stays byte-stable when the feature is off.
554+ (((f64::from(qp) - 12.0) / 6.0).exp2().round()).max(1.0)
555+ }
554556 }
555557
556558 /// Split `mb_h` macroblock rows into at most `n` contiguous bands.
crates/ec-h264/tests/encode.rsmodified+72 -20
@@ -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]
@@ -404,31 +464,23 @@ fn eight_by_eight_gains_on_flat_and_text() {
404464 }
405465 (bits as f64, sum_psnr / 10.0, share)
406466 };
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;
467+ let qps = [22, 26, 30, 34];
468+ let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect();
469+ let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect();
470+ let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
471+ let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
472+ let bd = bd_psnr_delta(&on_curve, &off_curve);
473+ let share = on.iter().map(|&(_, _, share)| share).sum::<f64>() / on.len() as f64;
474+ const OLD_FLAG_ON_BD_PSNR_DB: f64 = 0.255_347;
421475 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,
476+ "8x8 BD-PSNR over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%",
425477 share * 100.0
426478 );
427479 assert!(share > 0.0, "no 8x8 macroblocks were coded");
480+ assert!(bd >= 0.0, "8x8 BD-PSNR {bd:+.3} dB is below flag-off");
428481 assert!(
429- gain_db >= 0.05 || saving >= 0.05,
430- "8x8 gain {gain_db:+.2} dB / {:.1}% is below the bar",
431- saving * 100.0
482+ bd + 0.02 >= OLD_FLAG_ON_BD_PSNR_DB,
483+ "8x8 BD-PSNR {bd:+.3} dB regressed more than 0.02 dB from the old flag-on gate"
432484 );
433485 }
434486