forge
Explore
Log in

Don't you dare go Hollow

Measure all three planes, and a chroma coded_block_pattern test

Browse files at this commit

49e08f56ad7eaf353738ff2e53314af9966e2cf2Ahmet Kaan GümüşParent: 835b128
  • feat
    • measure all three planes, and a chroma coded_block_pattern test
Show full message
feat(h264): measure all three planes, and a chroma coded_block_pattern test

The rate-quality gate measured PSNR on the luma plane alone, so any decision
that could trade chroma bits for luma bits read as a pure gain. It now also
reports an all-plane PSNR, pooled by sample count the way x264 reports it --
luma 6, each chroma plane 1 for 4:2:0 -- as BD-PSNR-YUV beside the luma number.

Chroma gets the group test luma already has: cbp_chroma is 0, 1 (DC) or 2 (DC
and AC), so one surviving AC block takes the pattern to 2 and makes the other
seven each spend a coded_block_flag saying they are empty. The eight AC blocks
are pooled, coding them is compared against zeroing them all, and the pattern
step is charged CBP_CHROMA_BIT.

Swept at 0, 4, 8, 16, 32 and 64 bits the charge reads -0.688/-0.681/-0.659/
-0.653/-0.670/-0.742 dB all-plane BD on a 3840x1608 film clip and -0.537/
-0.527/-0.530/-0.517/-0.524/-0.522 on a 2560x1440 screen capture; both turn
over at sixteen. Read on luma alone the same sweep climbs monotonically to
+0.079 dB at 64, which is the encoder buying luma by throwing chroma away.

On the all-plane number the gap to x264 is -0.65 dB on the film clip against
-0.18 luma, and -0.52 against -0.23 on the screen capture: chroma is the larger
half of what is left, and nothing in this lane had been able to see it.
crates/ec-h264/src/enc/mb.rsmodified+60 -0
@@ -1141,6 +1141,19 @@ fn code_luma_4x4(
11411141 /// plausible six.
11421142 const CBP_BIT: f64 = 6.0;
11431143
1144+/// What chroma pays to take its coded_block_pattern from one to two, in bits,
1145+/// on top of the levels: the pattern bins themselves plus a coded_block_flag
1146+/// for every AC block that then has to say it is empty.
1147+///
1148+/// Swept at 0, 4, 8, 16, 32 and 64 bits, read on the all-plane PSNR because a
1149+/// luma-only one cannot see what this decision spends: -0.688/-0.681/-0.659/
1150+/// -0.653/-0.670/-0.742 dB BD on the film clip and -0.537/-0.527/-0.530/
1151+/// -0.517/-0.524/-0.522 on the screen capture. Both turn over at sixteen. The
1152+/// same sweep read on luma alone climbs all the way to +0.079 dB at 64,
1153+/// because past the turn the test is buying luma bits by throwing chroma
1154+/// away -- which is exactly the trade an all-plane metric exists to catch.
1155+const CBP_CHROMA_BIT: f64 = 16.0;
1156+
11441157 /// How much of the mode-decision lambda the group test uses.
11451158 ///
11461159 /// The 8x8 transform path was swept the same way and does not want this test
@@ -1442,6 +1455,7 @@ fn code_chroma(
14421455 let qp_c = chroma_qp(qp_y);
14431456 let mut dc_lists = [[0i32; 4]; 2];
14441457 let mut ac = [[[0i32; 16]; 4]; 2];
1458+ let mut srcs = [[[0i32; 16]; 4]; 2];
14451459 let mut any_ac = false;
14461460 for comp in 0..2 {
14471461 let (plane, src) = if comp == 0 {
@@ -1461,6 +1475,7 @@ fn code_chroma(
14611475 }
14621476 }
14631477 let source = d;
1478+ srcs[comp][blk] = d;
14641479 forward_4x4(&mut d);
14651480 dc_lists[comp][blk] = d[0];
14661481 let rdoq = !intra && w.is_cabac();
@@ -1512,6 +1527,51 @@ fn code_chroma(
15121527 }
15131528 }
15141529 }
1530+ // The chroma pattern is one decision for all eight AC blocks: a single
1531+ // surviving block takes coded_block_pattern from one to two, and every
1532+ // other block then has to code a coded_block_flag to say it is empty. So
1533+ // the same group test luma runs over four blocks runs here over all eight,
1534+ // against the same lambda.
1535+ if any_ac {
1536+ let (mut ssd_zero, mut ssd_coded, mut rate) = (0i64, 0i64, 0f64);
1537+ for comp in 0..2 {
1538+ for blk in 0..4 {
1539+ let source = &srcs[comp][blk];
1540+ let mut resid = [0i32; 16];
1541+ if lv.chroma_nz[comp][blk] > 0 {
1542+ let mut raster = [0i32; 16];
1543+ unzigzag_ac15(&ac[comp][blk], &mut raster);
1544+ dequant_4x4(&mut raster, &e.ls, qp_c, true);
1545+ inverse_transform_4x4(&raster, &mut resid);
1546+ rate += match w.residual_block_cost(
1547+ &ac[comp][blk],
1548+ BlockCat::ChromaAc,
1549+ Some(1),
1550+ Some(1),
1551+ ) {
1552+ Some(bits) => f64::from(bits) / 256.0,
1553+ None => block_bits(&ac[comp][blk]) as f64,
1554+ };
1555+ }
1556+ for i in 0..16 {
1557+ let z = i64::from(source[i]);
1558+ let c = i64::from(source[i] - resid[i]);
1559+ ssd_zero += z * z;
1560+ ssd_coded += c * c;
1561+ }
1562+ }
1563+ }
1564+ let lambda = if w.is_cabac() {
1565+ GROUP_LAMBDA * lambda_ssd(qp_c)
1566+ } else {
1567+ zero_block_lambda(e, qp_c, false)
1568+ };
1569+ if ssd_coded as f64 + lambda * (rate + CBP_CHROMA_BIT) >= ssd_zero as f64 {
1570+ ac = [[[0; 16]; 4]; 2];
1571+ lv.chroma_nz = [[0; 4]; 2];
1572+ any_ac = false;
1573+ }
1574+ }
15151575 let mut any_dc = false;
15161576 for comp in 0..2 {
15171577 forward_hadamard_2x2(&mut dc_lists[comp]);
crates/ec-h264/tests/encode.rsmodified+60 -8
@@ -147,6 +147,35 @@ fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes {
147147 (y, u, v)
148148 }
149149
150+/// Mean squared error between two equal-length planes.
151+fn plane_mse(a: &[u8], b: &[u8]) -> f64 {
152+ a.iter()
153+ .zip(b)
154+ .map(|(&x, &y)| {
155+ let d = f64::from(x) - f64::from(y);
156+ d * d
157+ })
158+ .sum::<f64>()
159+ / a.len() as f64
160+}
161+
162+/// PSNR over all three planes, pooled by sample count the way x264 reports it:
163+/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number
164+/// rewards an encoder for throwing chroma away — a chroma decision measured
165+/// against it will always say "code less" — so any decision that can move
166+/// chroma bits is read here instead.
167+fn psnr_yuv(a: &(Vec<u8>, Vec<u8>, Vec<u8>), b: &(Vec<u8>, Vec<u8>, Vec<u8>)) -> f64 {
168+ let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64);
169+ let sse =
170+ plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c;
171+ let mse = sse / (n_y + 2.0 * n_c);
172+ if mse == 0.0 {
173+ 99.0
174+ } else {
175+ 10.0 * (255.0 * 255.0 / mse).log10()
176+ }
177+}
178+
150179 fn psnr(a: &[u8], b: &[u8]) -> f64 {
151180 let mse: f64 = a
152181 .iter()
@@ -1054,6 +1083,11 @@ fn bd_psnr_vs_x264() {
10541083 .zip(&decoded)
10551084 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
10561085 .sum();
1086+ let sum_yuv: f64 = sources
1087+ .iter()
1088+ .zip(&decoded)
1089+ .map(|(s, d)| psnr_yuv(s, d))
1090+ .sum();
10571091 let (decoded_psnr, recon_psnr) =
10581092 (sum / sources.len() as f64, sum_recon / sources.len() as f64);
10591093 assert!(
@@ -1061,7 +1095,11 @@ fn bd_psnr_vs_x264() {
10611095 "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \
10621096 stream decodes to {decoded_psnr:.2} dB"
10631097 );
1064- ((stream.len() * 8) as f64, decoded_psnr)
1098+ (
1099+ (stream.len() * 8) as f64,
1100+ decoded_psnr,
1101+ sum_yuv / sources.len() as f64,
1102+ )
10651103 };
10661104 let x264 = |qp: i32| {
10671105 let stream = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes");
@@ -1078,24 +1116,38 @@ fn bd_psnr_vs_x264() {
10781116 .zip(&decoded)
10791117 .map(|((y, _, _), (dy, _, _))| psnr(y, dy))
10801118 .sum();
1081- ((stream.len() * 8) as f64, sum / sources.len() as f64)
1119+ let sum_yuv: f64 = sources
1120+ .iter()
1121+ .zip(&decoded)
1122+ .map(|(s, d)| psnr_yuv(s, d))
1123+ .sum();
1124+ let n = sources.len() as f64;
1125+ ((stream.len() * 8) as f64, sum / n, sum_yuv / n)
10821126 };
10831127
10841128 let qps = [22, 26, 30, 34];
10851129 let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect();
10861130 let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect();
10871131 for (i, &qp) in qps.iter().enumerate() {
1088- let (ob, op) = mine[i];
1089- let (xb, xp) = theirs[i];
1132+ let (ob, op, oy) = mine[i];
1133+ let (xb, xp, xy) = theirs[i];
10901134 eprintln!(
1091- "qp {qp}: ours {ob:.0} bits {op:.2} dB | x264 {xb:.0} bits {xp:.2} dB \
1092- ({:+.1}% bits, {:+.2} dB)",
1135+ "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x264 {xb:.0} bits {xp:.2} dB \
1136+ ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)",
10931137 (ob / xb - 1.0) * 100.0,
1094- op - xp
1138+ op - xp,
1139+ oy - xy
10951140 );
10961141 }
1097- let bd = bd_psnr_delta(&mine, &theirs);
1142+ let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> {
1143+ v.iter()
1144+ .map(|&(b, p, y)| (b, if luma { p } else { y }))
1145+ .collect()
1146+ };
1147+ let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true));
1148+ let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false));
10981149 eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB");
1150+ eprintln!("BD-PSNR-YUV ours vs x264 over q22/26/30/34: {bd_yuv:+.3} dB");
10991151
11001152 // The floor is calibrated on the synthetic clip; a clip of the user's is a
11011153 // measurement, not a gate, because its content is not pinned.
lanes/h264x264-r2.report.mdmodified+34 -0
@@ -665,3 +665,37 @@ arms move when the paths under them change: the flag-off arm is the 4x4 path
665665 that just improved, and the flag-on arm is not. Its delta drops from 0.255 to
666666 0.230 dB while the absolute synthetic comparison against x264 improves from
667667 -4.060 to -3.969 dB, and the gate is re-pinned with that written next to it.
668+
669+## The gate could not see chroma, so chroma decisions kept winning by starving it
670+
671+`cbp_chroma` has the same group structure the luma `coded_block_pattern` test
672+just fixed: it is 0 (nothing), 1 (DC only) or 2 (DC and AC), so a single
673+surviving AC block takes the pattern to 2 and makes every other AC block spend
674+a coded_block_flag saying it is empty. The same group RD test applies -- pool
675+the eight AC blocks, compare coding them against zeroing them all, and charge
676+the pattern step.
677+
678+Swept against the gate as it stood, the charge looked like free money: the film
679+clip went -0.310, -0.292, -0.247, -0.178, -0.069, +0.079 dB BD at 0, 4, 8, 16,
680+32 and 64 bits, crossing x264 and still climbing at the top of the grid. A
681+result that good from one constant is a reason to check the instrument, and the
682+instrument was wrong: `bd_psnr_vs_x264` measured PSNR on the luma plane alone.
683+Every bit the encoder stopped spending on chroma came back as luma quality, and
684+the metric counted only the second half of that trade. A chroma decision read
685+against a luma-only metric can only ever conclude "code less chroma".
686+
687+The gate now also reports an all-plane PSNR, pooled by sample count the way
688+x264 reports it -- for 4:2:0 that weights luma 6 and each chroma plane 1 -- and
689+prints it as `BD-PSNR-YUV` next to the luma number. On that metric the same
690+sweep reads -0.688, -0.681, -0.659, -0.653, -0.670, -0.742 dB on the film clip
691+and -0.537, -0.527, -0.530, -0.517, -0.524, -0.522 on the screen capture. Both
692+contents turn over at sixteen, and past the turn the luma number keeps rising
693+while the real one falls -- the shape the luma-only gate was blind to.
694+`CBP_CHROMA_BIT` is baked at 16.
695+
696+The larger finding is the metric itself. At the settings this lane has been
697+tuning, we are -0.18 dB luma on the film clip but -0.65 dB all-plane, and
698+-0.23 against -0.52 on the screen capture. Chroma is the bigger half of the
699+remaining gap to x264 and no measurement in this lane had ever seen it. Every
700+earlier constant in this report was chosen on the luma-only number; the ones
701+that can move chroma bits are owed a re-sweep.