diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 1ab16bbb..e52fb2ea 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -1141,6 +1141,19 @@ fn code_luma_4x4( /// plausible six. const CBP_BIT: f64 = 6.0; +/// What chroma pays to take its coded_block_pattern from one to two, in bits, +/// on top of the levels: the pattern bins themselves plus a coded_block_flag +/// for every AC block that then has to say it is empty. +/// +/// Swept at 0, 4, 8, 16, 32 and 64 bits, read on the all-plane PSNR because a +/// luma-only one cannot see what this decision spends: -0.688/-0.681/-0.659/ +/// -0.653/-0.670/-0.742 dB BD on the film clip and -0.537/-0.527/-0.530/ +/// -0.517/-0.524/-0.522 on the screen capture. Both turn over at sixteen. The +/// same sweep read on luma alone climbs all the way to +0.079 dB at 64, +/// because past the turn the test is buying luma bits by throwing chroma +/// away -- which is exactly the trade an all-plane metric exists to catch. +const CBP_CHROMA_BIT: f64 = 16.0; + /// How much of the mode-decision lambda the group test uses. /// /// The 8x8 transform path was swept the same way and does not want this test @@ -1442,6 +1455,7 @@ fn code_chroma( let qp_c = chroma_qp(qp_y); let mut dc_lists = [[0i32; 4]; 2]; let mut ac = [[[0i32; 16]; 4]; 2]; + let mut srcs = [[[0i32; 16]; 4]; 2]; let mut any_ac = false; for comp in 0..2 { let (plane, src) = if comp == 0 { @@ -1461,6 +1475,7 @@ fn code_chroma( } } let source = d; + srcs[comp][blk] = d; forward_4x4(&mut d); dc_lists[comp][blk] = d[0]; let rdoq = !intra && w.is_cabac(); @@ -1512,6 +1527,51 @@ fn code_chroma( } } } + // The chroma pattern is one decision for all eight AC blocks: a single + // surviving block takes coded_block_pattern from one to two, and every + // other block then has to code a coded_block_flag to say it is empty. So + // the same group test luma runs over four blocks runs here over all eight, + // against the same lambda. + if any_ac { + let (mut ssd_zero, mut ssd_coded, mut rate) = (0i64, 0i64, 0f64); + for comp in 0..2 { + for blk in 0..4 { + let source = &srcs[comp][blk]; + let mut resid = [0i32; 16]; + if lv.chroma_nz[comp][blk] > 0 { + let mut raster = [0i32; 16]; + unzigzag_ac15(&ac[comp][blk], &mut raster); + dequant_4x4(&mut raster, &e.ls, qp_c, true); + inverse_transform_4x4(&raster, &mut resid); + rate += match w.residual_block_cost( + &ac[comp][blk], + BlockCat::ChromaAc, + Some(1), + Some(1), + ) { + Some(bits) => f64::from(bits) / 256.0, + None => block_bits(&ac[comp][blk]) as f64, + }; + } + for i in 0..16 { + let z = i64::from(source[i]); + let c = i64::from(source[i] - resid[i]); + ssd_zero += z * z; + ssd_coded += c * c; + } + } + } + let lambda = if w.is_cabac() { + GROUP_LAMBDA * lambda_ssd(qp_c) + } else { + zero_block_lambda(e, qp_c, false) + }; + if ssd_coded as f64 + lambda * (rate + CBP_CHROMA_BIT) >= ssd_zero as f64 { + ac = [[[0; 16]; 4]; 2]; + lv.chroma_nz = [[0; 4]; 2]; + any_ac = false; + } + } let mut any_dc = false; for comp in 0..2 { forward_hadamard_2x2(&mut dc_lists[comp]); diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index 47cf81f1..85a58884 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -147,6 +147,35 @@ fn planes_of(frame: &ec_core::frame::VideoFrame) -> Planes { (y, u, v) } +/// Mean squared error between two equal-length planes. +fn plane_mse(a: &[u8], b: &[u8]) -> f64 { + a.iter() + .zip(b) + .map(|(&x, &y)| { + let d = f64::from(x) - f64::from(y); + d * d + }) + .sum::() + / a.len() as f64 +} + +/// PSNR over all three planes, pooled by sample count the way x264 reports it: +/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number +/// rewards an encoder for throwing chroma away — a chroma decision measured +/// against it will always say "code less" — so any decision that can move +/// chroma bits is read here instead. +fn psnr_yuv(a: &(Vec, Vec, Vec), b: &(Vec, Vec, Vec)) -> f64 { + let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); + let sse = + plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; + let mse = sse / (n_y + 2.0 * n_c); + if mse == 0.0 { + 99.0 + } else { + 10.0 * (255.0 * 255.0 / mse).log10() + } +} + fn psnr(a: &[u8], b: &[u8]) -> f64 { let mse: f64 = a .iter() @@ -1054,6 +1083,11 @@ fn bd_psnr_vs_x264() { .zip(&decoded) .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) .sum(); + let sum_yuv: f64 = sources + .iter() + .zip(&decoded) + .map(|(s, d)| psnr_yuv(s, d)) + .sum(); let (decoded_psnr, recon_psnr) = (sum / sources.len() as f64, sum_recon / sources.len() as f64); assert!( @@ -1061,7 +1095,11 @@ fn bd_psnr_vs_x264() { "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ stream decodes to {decoded_psnr:.2} dB" ); - ((stream.len() * 8) as f64, decoded_psnr) + ( + (stream.len() * 8) as f64, + decoded_psnr, + sum_yuv / sources.len() as f64, + ) }; let x264 = |qp: i32| { let stream = x264_encode_qp(&sources, w, h, qp, gop).expect("x264 encodes"); @@ -1078,24 +1116,38 @@ fn bd_psnr_vs_x264() { .zip(&decoded) .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) .sum(); - ((stream.len() * 8) as f64, sum / sources.len() as f64) + let sum_yuv: f64 = sources + .iter() + .zip(&decoded) + .map(|(s, d)| psnr_yuv(s, d)) + .sum(); + let n = sources.len() as f64; + ((stream.len() * 8) as f64, sum / n, sum_yuv / n) }; let qps = [22, 26, 30, 34]; let mine: Vec<_> = qps.iter().map(|&q| ours(q)).collect(); let theirs: Vec<_> = qps.iter().map(|&q| x264(q)).collect(); for (i, &qp) in qps.iter().enumerate() { - let (ob, op) = mine[i]; - let (xb, xp) = theirs[i]; + let (ob, op, oy) = mine[i]; + let (xb, xp, xy) = theirs[i]; eprintln!( - "qp {qp}: ours {ob:.0} bits {op:.2} dB | x264 {xb:.0} bits {xp:.2} dB \ - ({:+.1}% bits, {:+.2} dB)", + "qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv) | x264 {xb:.0} bits {xp:.2} dB \ + ({xy:.2} yuv) ({:+.1}% bits, {:+.2} dB, {:+.2} yuv)", (ob / xb - 1.0) * 100.0, - op - xp + op - xp, + oy - xy ); } - let bd = bd_psnr_delta(&mine, &theirs); + let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { + v.iter() + .map(|&(b, p, y)| (b, if luma { p } else { y })) + .collect() + }; + let bd = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); + let bd_yuv = bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); eprintln!("BD-PSNR ours vs x264 over q22/26/30/34: {bd:+.3} dB"); + eprintln!("BD-PSNR-YUV ours vs x264 over q22/26/30/34: {bd_yuv:+.3} dB"); // The floor is calibrated on the synthetic clip; a clip of the user's is a // measurement, not a gate, because its content is not pinned. diff --git a/lanes/h264x264-r2.report.md b/lanes/h264x264-r2.report.md index 310e37ab..324ab53a 100644 --- a/lanes/h264x264-r2.report.md +++ b/lanes/h264x264-r2.report.md @@ -665,3 +665,37 @@ arms move when the paths under them change: the flag-off arm is the 4x4 path that just improved, and the flag-on arm is not. Its delta drops from 0.255 to 0.230 dB while the absolute synthetic comparison against x264 improves from -4.060 to -3.969 dB, and the gate is re-pinned with that written next to it. + +## The gate could not see chroma, so chroma decisions kept winning by starving it + +`cbp_chroma` has the same group structure the luma `coded_block_pattern` test +just fixed: it is 0 (nothing), 1 (DC only) or 2 (DC and AC), so a single +surviving AC block takes the pattern to 2 and makes every other AC block spend +a coded_block_flag saying it is empty. The same group RD test applies -- pool +the eight AC blocks, compare coding them against zeroing them all, and charge +the pattern step. + +Swept against the gate as it stood, the charge looked like free money: the film +clip went -0.310, -0.292, -0.247, -0.178, -0.069, +0.079 dB BD at 0, 4, 8, 16, +32 and 64 bits, crossing x264 and still climbing at the top of the grid. A +result that good from one constant is a reason to check the instrument, and the +instrument was wrong: `bd_psnr_vs_x264` measured PSNR on the luma plane alone. +Every bit the encoder stopped spending on chroma came back as luma quality, and +the metric counted only the second half of that trade. A chroma decision read +against a luma-only metric can only ever conclude "code less chroma". + +The gate now also reports an all-plane PSNR, pooled by sample count the way +x264 reports it -- for 4:2:0 that weights luma 6 and each chroma plane 1 -- and +prints it as `BD-PSNR-YUV` next to the luma number. On that metric the same +sweep reads -0.688, -0.681, -0.659, -0.653, -0.670, -0.742 dB on the film clip +and -0.537, -0.527, -0.530, -0.517, -0.524, -0.522 on the screen capture. Both +contents turn over at sixteen, and past the turn the luma number keeps rising +while the real one falls -- the shape the luma-only gate was blind to. +`CBP_CHROMA_BIT` is baked at 16. + +The larger finding is the metric itself. At the settings this lane has been +tuning, we are -0.18 dB luma on the film clip but -0.65 dB all-plane, and +-0.23 against -0.52 on the screen capture. Chroma is the bigger half of the +remaining gap to x264 and no measurement in this lane had ever seen it. Every +earlier constant in this report was chosen on the luma-only number; the ones +that can move chroma bits are owed a re-sweep.