From 11904c0e2b1117f792dd54a027272fb3683a0c64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 01:22:59 +0300 Subject: [PATCH] feat(h265): residual quadtree, one split level, on by default A 2Nx2N intra coding unit may now split its luma transform once into four half-size children, chosen against the unsplit block by J = SSD + lambda*bits. Chroma splits with the tree while its own blocks stay 4x4 or larger; at an 8x8 luma tree chroma stays at the parent size and is coded with the last child (7.3.8.8). The parent luma cbf is the OR of the children's. Measured against x265 over the four-point ladder it is worth +0.010 dB BD-PSNR on film and +0.080 dB on screen capture, so it is on by default. Flipping the default surfaced a transform-skip desync: transform_skip_flag is read for every 4x4 residual block once the picture parameter set enables skip, and the encoder decided it from the coding unit's size, so the 4x4 chroma children of a 16x16 unit were coded with a real transform and no flag. The decision now travels by the transform block's own size. --- crates/ec-h265/src/ctu.rs | 320 ++++++++++++++++++++++++- crates/ec-h265/src/encoder.rs | 12 +- crates/ec-h265/tests/conformance.rs | 357 +++++++++++++++++++++++++++- crates/ec-h265/tests/encode.rs | 3 + lanes/h265-rqt-r1.report.md | 56 +++++ 5 files changed, 736 insertions(+), 12 deletions(-) create mode 100644 lanes/h265-rqt-r1.report.md diff --git a/crates/ec-h265/src/ctu.rs b/crates/ec-h265/src/ctu.rs index 71babbff..a52a43fe 100644 --- a/crates/ec-h265/src/ctu.rs +++ b/crates/ec-h265/src/ctu.rs @@ -172,6 +172,7 @@ pub struct CtuEncoder<'a> { /// Whether the levels get a rate-distortion search after quantisation. rdoq: bool, transform_skip: bool, + rqt: bool, /// The counting CABAC engine that search prices its trials with. rdoq_enc: CabacEncoder, /// `log2` of the smallest coding unit the search will produce. @@ -208,6 +209,7 @@ impl<'a> CtuEncoder<'a> { sign_hiding: bool, rdoq: bool, transform_skip: bool, + rqt: bool, min_cb_log2: u32, ) -> CtuEncoder<'a> { let band_rows = (height - band_y0).min(ctb_size); @@ -231,6 +233,7 @@ impl<'a> CtuEncoder<'a> { sign_hiding, rdoq, transform_skip, + rqt, rdoq_enc: CabacEncoder::counter(Contexts::new(qp)), min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5), modes: vec![255; (width / 4) * (ctb_size / 4)], @@ -662,7 +665,12 @@ impl<'a> CtuEncoder<'a> { enc: &mut CabacEncoder, ) -> f64 { let n = 1usize << log2; - let chroma_tskip = self.transform_skip && n == 8; + // Transform skip is a per-block flag the decoder reads for every 4x4 + // residual once the picture parameter set enables it, so the decision + // has to travel by the block's own size, not the coding unit's: a + // transform tree splits chroma down to 4x4 from a 16x16 unit too. + // `code_chroma` and `encode_residual` each apply it only at 4x4. + let chroma_tskip = self.transform_skip; let before = enc.bit_count(); if log2 == MIN_CB_LOG2 { // part_mode: PART_2Nx2N is the single bin 1. @@ -683,6 +691,205 @@ impl<'a> CtuEncoder<'a> { let cb_cbf = self.code_chroma(x, y, n, chroma_mode, 1, chroma_tskip).1; let cr_cbf = self.code_chroma(x, y, n, chroma_mode, 2, chroma_tskip).1; + if self.rqt && log2 > 2 { + // A child transform tree signals its own chroma as long as its + // chroma blocks are still 4x4 or larger; only the 8x8 luma tree, + // whose children are 4x4, leaves chroma at the parent size and + // codes it with the last child (7.3.8.8). + let chroma_split = log2 > 3; + let nosplit_rec = self.save_region(x, y, n); + let parent_cb = self.scratch.cb_levels[..n * n / 4].to_vec(); + let parent_cr = self.scratch.cr_levels[..n * n / 4].to_vec(); + let start = enc.snapshot(); + enc.set_counting(true); + + let nb = enc.bit_count(); + enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0); + self.write_single_tu( + enc, + n, + log2, + mode, + chroma_mode, + chroma_tskip, + luma_cbf, + cb_cbf, + cr_cbf, + ); + let nosplit_bits = enc.bit_count() - nb; + let nosplit_ssd = self.region_ssd(x, y, n); + + enc.restore(&start); + + let half = n / 2; + let offsets = [(0usize, 0usize), (half, 0), (0, half), (half, half)]; + let mut child_levels = [[0i32; 256]; 4]; + let mut child_cbf = [false; 4]; + let mut child_cb = [[0i32; 64]; 4]; + let mut child_cr = [[0i32; 64]; 4]; + let mut child_cb_cbf = [false; 4]; + let mut child_cr_cbf = [false; 4]; + for (part, &(dx, dy)) in offsets.iter().enumerate() { + let (cx, cy) = (x + dx, y + dy); + let refs = self.luma_refs(cx, cy, half); + let mut source = std::mem::take(&mut self.scratch.source); + for row in 0..half { + source[row * half..row * half + half].copy_from_slice( + &self.src.y + [(cy + row) * self.width + cx..(cy + row) * self.width + cx + half], + ); + } + let (_, cbf) = self.transform_luma(half, mode, &source, &refs); + child_levels[part][..half * half] + .copy_from_slice(&self.scratch.levels[..half * half]); + child_cbf[part] = cbf; + for row in 0..half { + for col in 0..half { + self.write_rec_y(cx + col, cy + row, self.scratch.recon[row * half + col]); + } + } + self.scratch.source = source; + // The next child predicts from this one, so its samples have + // to read as available now rather than when the whole coding + // unit is marked: a transform tree is walked in the same + // z-order by the decoder. + self.mark_coded(cx, cy, half, mode, depth); + if chroma_split { + let q = half * half / 4; + let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 1, chroma_tskip); + child_cb_cbf[part] = cbf; + child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]); + let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 2, chroma_tskip); + child_cr_cbf[part] = cbf; + child_cr[part][..q].copy_from_slice(&self.scratch.cr_levels[..q]); + } + } + // The parent's flag is the OR of the children's: a clear one at + // depth 0 tells the decoder to infer every child's as clear. + let split_cb_cbf = if chroma_split { + child_cb_cbf.iter().any(|&c| c) + } else { + cb_cbf + }; + let split_cr_cbf = if chroma_split { + child_cr_cbf.iter().any(|&c| c) + } else { + cr_cbf + }; + + let sb = enc.bit_count(); + enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 1); + self.write_split_tu( + enc, + n, + log2, + mode, + chroma_mode, + chroma_tskip, + chroma_split, + split_cb_cbf, + split_cr_cbf, + &child_cbf, + &child_levels, + &child_cb_cbf, + &child_cr_cbf, + &child_cb, + &child_cr, + &parent_cb, + &parent_cr, + ); + let split_bits = enc.bit_count() - sb; + let split_rec = self.save_region(x, y, n); + let split_ssd = self.region_ssd(x, y, n); + + enc.set_counting(false); + enc.restore(&start); + + let nosplit_cost = nosplit_ssd + self.lambda * nosplit_bits as f64; + let split_cost = split_ssd + self.lambda * split_bits as f64; + + if nosplit_cost <= split_cost { + self.load_region(x, y, n, &nosplit_rec); + // The children coded over the shared chroma scratch. + self.scratch.cb_levels[..n * n / 4].copy_from_slice(&parent_cb); + self.scratch.cr_levels[..n * n / 4].copy_from_slice(&parent_cr); + enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 0); + self.write_single_tu( + enc, + n, + log2, + mode, + chroma_mode, + chroma_tskip, + luma_cbf, + cb_cbf, + cr_cbf, + ); + self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf); + } else { + self.load_region(x, y, n, &split_rec); + enc.encode_bin(ctx::SPLIT_TRANSFORM + (5 - log2) as usize, 1); + self.write_split_tu( + enc, + n, + log2, + mode, + chroma_mode, + chroma_tskip, + chroma_split, + split_cb_cbf, + split_cr_cbf, + &child_cbf, + &child_levels, + &child_cb_cbf, + &child_cr_cbf, + &child_cb, + &child_cr, + &parent_cb, + &parent_cr, + ); + self.last_cu_empty = + !(child_cbf.iter().any(|&c| c) || split_cb_cbf || split_cr_cbf); + } + + self.mark_coded(x, y, n, mode, depth); + let bits = enc.bit_count() - before; + return self.region_ssd(x, y, n) + self.lambda * bits as f64; + } + + // No-RQT: single TU, no split_transform_flag written (inferred 0). + self.write_single_tu( + enc, + n, + log2, + mode, + chroma_mode, + chroma_tskip, + luma_cbf, + cb_cbf, + cr_cbf, + ); + self.mark_coded(x, y, n, mode, depth); + self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf); + let bits = enc.bit_count() - before; + self.region_ssd(x, y, n) + self.lambda * bits as f64 + } + + /// Write cbf flags + residual for one unsplit transform tree (no + /// `split_transform_flag`). + #[allow(clippy::too_many_arguments)] + fn write_single_tu( + &mut self, + enc: &mut CabacEncoder, + n: usize, + log2: u32, + mode: u8, + chroma_mode: u8, + chroma_tskip: bool, + luma_cbf: bool, + cb_cbf: bool, + cr_cbf: bool, + ) { enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf)); enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf)); enc.encode_bin(ctx::CBF_LUMA + 1, u32::from(luma_cbf)); @@ -727,11 +934,114 @@ impl<'a> CtuEncoder<'a> { ); self.scratch.cr_levels = levels; } + } - self.mark_coded(x, y, n, mode, depth); - self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf); - let bits = enc.bit_count() - before; - self.region_ssd(x, y, n) + self.lambda * bits as f64 + /// Write cbf flags + residual for a split transform tree: chroma cbf first, + /// then four half-size luma children (CBF_LUMA ctx 0 for depth 1), chroma + /// residual on the last child. + /// Write the syntax of a split transform tree: the parent's chroma flags, + /// then four half-size children. A child carries its own chroma when the + /// chroma blocks stay 4x4 or larger, and reads the depth-one contexts for + /// both flags; below that the parent's chroma rides on the last child. + #[allow(clippy::too_many_arguments)] + fn write_split_tu( + &mut self, + enc: &mut CabacEncoder, + n: usize, + log2: u32, + mode: u8, + chroma_mode: u8, + chroma_tskip: bool, + chroma_split: bool, + cb_cbf: bool, + cr_cbf: bool, + child_cbf: &[bool; 4], + child_levels: &[[i32; 256]; 4], + child_cb_cbf: &[bool; 4], + child_cr_cbf: &[bool; 4], + child_cb: &[[i32; 64]; 4], + child_cr: &[[i32; 64]; 4], + parent_cb: &[i32], + parent_cr: &[i32], + ) { + let half = n / 2; + enc.encode_bin(ctx::CBF_CHROMA, u32::from(cb_cbf)); + enc.encode_bin(ctx::CBF_CHROMA, u32::from(cr_cbf)); + let luma_scan = intra::scan_index(mode, log2 - 1, true); + for part in 0..4usize { + if chroma_split { + if cb_cbf { + enc.encode_bin(ctx::CBF_CHROMA + 1, u32::from(child_cb_cbf[part])); + } + if cr_cbf { + enc.encode_bin(ctx::CBF_CHROMA + 1, u32::from(child_cr_cbf[part])); + } + } + enc.encode_bin(ctx::CBF_LUMA, u32::from(child_cbf[part])); + if child_cbf[part] { + encode_residual( + enc, + &child_levels[part][..half * half], + log2 - 1, + 0, + luma_scan, + self.sign_hiding, + self.transform_skip, + ); + } + if chroma_split { + let (q, scan) = ( + half * half / 4, + intra::scan_index(chroma_mode, log2 - 2, false), + ); + if cb_cbf && child_cb_cbf[part] { + encode_residual( + enc, + &child_cb[part][..q], + log2 - 2, + 1, + scan, + self.sign_hiding, + chroma_tskip, + ); + } + if cr_cbf && child_cr_cbf[part] { + encode_residual( + enc, + &child_cr[part][..q], + log2 - 2, + 2, + scan, + self.sign_hiding, + chroma_tskip, + ); + } + } else if part == 3 { + let scan = intra::scan_index(chroma_mode, log2 - 1, false); + if cb_cbf { + encode_residual( + enc, + &parent_cb[..n * n / 4], + log2 - 1, + 1, + scan, + self.sign_hiding, + chroma_tskip, + ); + } + if cr_cbf { + encode_residual( + enc, + &parent_cr[..n * n / 4], + log2 - 1, + 2, + scan, + self.sign_hiding, + chroma_tskip, + ); + } + } + } } fn write_mode_syntax(&self, enc: &mut CabacEncoder, mode: u8, mpm: &[u8; 3]) { diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index a906781a..c5594011 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -167,6 +167,14 @@ pub struct EncoderConfig { pub rdoq: bool, /// Whether 4x4 TUs may skip the integer transform. pub transform_skip: TransformSkip, + /// Whether the transform tree may split once (rate-quantisation transform): + /// the luma TU of a 2Nx2N coding unit may be coded as four half-size + /// children when that costs less in `J = SSD + lambda * bits`. + /// + /// On by default: measured against x265 over the four-point ladder it is + /// worth +0.010 dB BD-PSNR on film and +0.080 dB on screen capture, which + /// is where our gap against x265 is (see `lanes/h265-rqt-r1.report.md`). + pub rqt: bool, /// What the samples mean, written into the VUI. pub video_signal_type: Option, /// Sample aspect ratio. @@ -199,6 +207,7 @@ impl EncoderConfig { sign_hiding: false, rdoq: true, transform_skip: TransformSkip::Off, + rqt: true, video_signal_type: None, sample_aspect_ratio: None, timing: None, @@ -295,7 +304,7 @@ impl Encoder { log2_min_tb_size_minus2: 0, log2_diff_max_min_tb_size: 3, max_transform_hierarchy_depth_inter: 0, - max_transform_hierarchy_depth_intra: 0, + max_transform_hierarchy_depth_intra: if cfg.rqt { 1 } else { 0 }, scaling_list_enabled: false, amp_enabled: false, // No in-loop filters: see `Encoder` docs and the PPS below. @@ -579,6 +588,7 @@ impl Encoder { self.cfg.sign_hiding, self.cfg.rdoq, self.cfg.transform_skip != TransformSkip::Off, + self.cfg.rqt, self.cfg.min_cu_size.max(8).trailing_zeros(), ); for col in 0..cols { diff --git a/crates/ec-h265/tests/conformance.rs b/crates/ec-h265/tests/conformance.rs index 358e064d..855aad6c 100644 --- a/crates/ec-h265/tests/conformance.rs +++ b/crates/ec-h265/tests/conformance.rs @@ -163,7 +163,50 @@ fn chroma_mode_search_decodes_bit_exactly() { let recon = planes_of(coded.recon.as_ref().expect("recon kept")); assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); + if mismatches != 0 { + // Which plane and where: a luma-only divergence is the transform + // tree, a chroma-only one is the flags that ride on it. + let luma = (w * h) as usize; + let chroma = luma / 4; + let first = decoded + .iter() + .zip(&recon) + .position(|(a, b)| a != b) + .unwrap(); + let count = |range: std::ops::Range| { + decoded[range.clone()] + .iter() + .zip(&recon[range]) + .filter(|(a, b)| a != b) + .count() + }; + let mut map = String::new(); + for by in (0..h as usize).step_by(16) { + for bx in (0..w as usize).step_by(16) { + let mut c = 0; + for row in by..by + 16 { + for col in bx..bx + 16 { + let i = row * w as usize + col; + if decoded[i] != recon[i] { + c += 1; + } + } + } + map.push_str(&format!("{c:4}")); + } + map.push('\n'); + } + eprintln!("luma 16x16 mismatch map:\n{map}"); + panic!( + "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ + ({}, {})", + count(0..luma), + count(luma..luma + chroma), + count(luma + chroma..luma + 2 * chroma), + first % w as usize, + first / w as usize, + ); + } let quality = psnr(&planes_of(&source), &recon); assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); } @@ -197,7 +240,50 @@ fn intra_nxn_decodes_bit_exactly() { let recon = planes_of(coded.recon.as_ref().expect("recon kept")); assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); + if mismatches != 0 { + // Which plane and where: a luma-only divergence is the transform + // tree, a chroma-only one is the flags that ride on it. + let luma = (w * h) as usize; + let chroma = luma / 4; + let first = decoded + .iter() + .zip(&recon) + .position(|(a, b)| a != b) + .unwrap(); + let count = |range: std::ops::Range| { + decoded[range.clone()] + .iter() + .zip(&recon[range]) + .filter(|(a, b)| a != b) + .count() + }; + let mut map = String::new(); + for by in (0..h as usize).step_by(16) { + for bx in (0..w as usize).step_by(16) { + let mut c = 0; + for row in by..by + 16 { + for col in bx..bx + 16 { + let i = row * w as usize + col; + if decoded[i] != recon[i] { + c += 1; + } + } + } + map.push_str(&format!("{c:4}")); + } + map.push('\n'); + } + eprintln!("luma 16x16 mismatch map:\n{map}"); + panic!( + "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ + ({}, {})", + count(0..luma), + count(luma..luma + chroma), + count(luma + chroma..luma + 2 * chroma), + first % w as usize, + first / w as usize, + ); + } let quality = psnr(&planes_of(&source), &recon); assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); } @@ -235,7 +321,50 @@ fn sign_hiding_decodes_bit_exactly() { let recon = planes_of(coded.recon.as_ref().expect("recon kept")); assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); + if mismatches != 0 { + // Which plane and where: a luma-only divergence is the transform + // tree, a chroma-only one is the flags that ride on it. + let luma = (w * h) as usize; + let chroma = luma / 4; + let first = decoded + .iter() + .zip(&recon) + .position(|(a, b)| a != b) + .unwrap(); + let count = |range: std::ops::Range| { + decoded[range.clone()] + .iter() + .zip(&recon[range]) + .filter(|(a, b)| a != b) + .count() + }; + let mut map = String::new(); + for by in (0..h as usize).step_by(16) { + for bx in (0..w as usize).step_by(16) { + let mut c = 0; + for row in by..by + 16 { + for col in bx..bx + 16 { + let i = row * w as usize + col; + if decoded[i] != recon[i] { + c += 1; + } + } + } + map.push_str(&format!("{c:4}")); + } + map.push('\n'); + } + eprintln!("luma 16x16 mismatch map:\n{map}"); + panic!( + "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ + ({}, {})", + count(0..luma), + count(luma..luma + chroma), + count(luma + chroma..luma + 2 * chroma), + first % w as usize, + first / w as usize, + ); + } let quality = psnr(&planes_of(&source), &recon); assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); } @@ -301,7 +430,50 @@ fn transform_skip_decodes_bit_exactly() { let recon = planes_of(coded.recon.as_ref().expect("recon kept")); assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); + if mismatches != 0 { + // Which plane and where: a luma-only divergence is the transform + // tree, a chroma-only one is the flags that ride on it. + let luma = (w * h) as usize; + let chroma = luma / 4; + let first = decoded + .iter() + .zip(&recon) + .position(|(a, b)| a != b) + .unwrap(); + let count = |range: std::ops::Range| { + decoded[range.clone()] + .iter() + .zip(&recon[range]) + .filter(|(a, b)| a != b) + .count() + }; + let mut map = String::new(); + for by in (0..h as usize).step_by(16) { + for bx in (0..w as usize).step_by(16) { + let mut c = 0; + for row in by..by + 16 { + for col in bx..bx + 16 { + let i = row * w as usize + col; + if decoded[i] != recon[i] { + c += 1; + } + } + } + map.push_str(&format!("{c:4}")); + } + map.push('\n'); + } + eprintln!("luma 16x16 mismatch map:\n{map}"); + panic!( + "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ + ({}, {})", + count(0..luma), + count(luma..luma + chroma), + count(luma + chroma..luma + 2 * chroma), + first % w as usize, + first / w as usize, + ); + } let quality = psnr(&planes_of(&source), &recon); assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); } @@ -343,7 +515,50 @@ fn ffmpeg_decodes_bit_exactly_at_every_shape() { recon.len() ); let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); + if mismatches != 0 { + // Which plane and where: a luma-only divergence is the transform + // tree, a chroma-only one is the flags that ride on it. + let luma = (w * h) as usize; + let chroma = luma / 4; + let first = decoded + .iter() + .zip(&recon) + .position(|(a, b)| a != b) + .unwrap(); + let count = |range: std::ops::Range| { + decoded[range.clone()] + .iter() + .zip(&recon[range]) + .filter(|(a, b)| a != b) + .count() + }; + let mut map = String::new(); + for by in (0..h as usize).step_by(16) { + for bx in (0..w as usize).step_by(16) { + let mut c = 0; + for row in by..by + 16 { + for col in bx..bx + 16 { + let i = row * w as usize + col; + if decoded[i] != recon[i] { + c += 1; + } + } + } + map.push_str(&format!("{c:4}")); + } + map.push('\n'); + } + eprintln!("luma 16x16 mismatch map:\n{map}"); + panic!( + "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ + ({}, {})", + count(0..luma), + count(luma..luma + chroma), + count(luma + chroma..luma + 2 * chroma), + first % w as usize, + first / w as usize, + ); + } // And the encode is worth something: PSNR against the source. let quality = psnr(&planes_of(&source), &recon); assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); @@ -568,7 +783,50 @@ fn rdoq_decodes_bit_exactly() { let recon = planes_of(coded.recon.as_ref().expect("recon kept")); assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - assert_eq!(mismatches, 0, "{name}: {mismatches} samples differ"); + if mismatches != 0 { + // Which plane and where: a luma-only divergence is the transform + // tree, a chroma-only one is the flags that ride on it. + let luma = (w * h) as usize; + let chroma = luma / 4; + let first = decoded + .iter() + .zip(&recon) + .position(|(a, b)| a != b) + .unwrap(); + let count = |range: std::ops::Range| { + decoded[range.clone()] + .iter() + .zip(&recon[range]) + .filter(|(a, b)| a != b) + .count() + }; + let mut map = String::new(); + for by in (0..h as usize).step_by(16) { + for bx in (0..w as usize).step_by(16) { + let mut c = 0; + for row in by..by + 16 { + for col in bx..bx + 16 { + let i = row * w as usize + col; + if decoded[i] != recon[i] { + c += 1; + } + } + } + map.push_str(&format!("{c:4}")); + } + map.push('\n'); + } + eprintln!("luma 16x16 mismatch map:\n{map}"); + panic!( + "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ + ({}, {})", + count(0..luma), + count(luma..luma + chroma), + count(luma + chroma..luma + 2 * chroma), + first % w as usize, + first / w as usize, + ); + } let quality = psnr(&planes_of(&source), &recon); assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); } @@ -587,3 +845,90 @@ fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, Enc let coded = encoder.encode_idr(&frame).expect("encode"); (frame, coded) } + +/// RQT must produce a bitstream a conformant decoder reads back to the exact +/// samples the encoder reconstructed. +#[test] +fn rqt_decodes_bit_exactly() { + if !have_ffmpeg() { + eprintln!("skipping: ffmpeg not installed"); + return; + } + for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { + let (source, coded) = encode_rqt(w, h, 27, true); + let (_, plain) = encode_rqt(w, h, 27, false); + let name = format!("rqt-{w}x{h}"); + assert_ne!( + coded.au, plain.au, + "{name}: RQT changed no byte, so the split path is not running" + ); + let path = write_au(&name, &coded); + let decoded = match ffmpeg_decode(&path) { + Ok(bytes) => bytes, + Err(e) => panic!("{name}: ffmpeg failed: {e}"), + }; + let recon = planes_of(coded.recon.as_ref().expect("recon kept")); + assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); + let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); + if mismatches != 0 { + // Which plane and where: a luma-only divergence is the transform + // tree, a chroma-only one is the flags that ride on it. + let luma = (w * h) as usize; + let chroma = luma / 4; + let first = decoded + .iter() + .zip(&recon) + .position(|(a, b)| a != b) + .unwrap(); + let count = |range: std::ops::Range| { + decoded[range.clone()] + .iter() + .zip(&recon[range]) + .filter(|(a, b)| a != b) + .count() + }; + let mut map = String::new(); + for by in (0..h as usize).step_by(16) { + for bx in (0..w as usize).step_by(16) { + let mut c = 0; + for row in by..by + 16 { + for col in bx..bx + 16 { + let i = row * w as usize + col; + if decoded[i] != recon[i] { + c += 1; + } + } + } + map.push_str(&format!("{c:4}")); + } + map.push('\n'); + } + eprintln!("luma 16x16 mismatch map:\n{map}"); + panic!( + "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ + ({}, {})", + count(0..luma), + count(luma..luma + chroma), + count(luma + chroma..luma + 2 * chroma), + first % w as usize, + first / w as usize, + ); + } + let quality = psnr(&planes_of(&source), &recon); + assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); + } +} + +/// The natural frame coded with RQT on or off, everything else left at its +/// default. +fn encode_rqt(width: u32, height: u32, qp: i32, rqt: bool) -> (VideoFrame, EncodedPicture) { + let mut cfg = EncoderConfig::new(width, height); + cfg.rqt = rqt; + cfg.rate_control = RateControl::ConstantQp(qp); + cfg.keep_recon = true; + cfg.picture_hash = true; + let encoder = Encoder::new(cfg).expect("encoder"); + let frame = natural_frame(width, height, 0); + let coded = encoder.encode_idr(&frame).expect("encode"); + (frame, coded) +} diff --git a/crates/ec-h265/tests/encode.rs b/crates/ec-h265/tests/encode.rs index 69130146..96469d5f 100644 --- a/crates/ec-h265/tests/encode.rs +++ b/crates/ec-h265/tests/encode.rs @@ -451,6 +451,9 @@ fn bd_psnr_vs_x265() { if let Ok(v) = std::env::var("EC_H265_NXN") { cfg.intra_nxn = v != "0"; } + if let Ok(v) = std::env::var("EC_H265_RQT") { + cfg.rqt = v != "0"; + } if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") { cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number"); } diff --git a/lanes/h265-rqt-r1.report.md b/lanes/h265-rqt-r1.report.md new file mode 100644 index 00000000..312fb620 --- /dev/null +++ b/lanes/h265-rqt-r1.report.md @@ -0,0 +1,56 @@ +# lane-h265-rqt r1 — residual quadtree, one split level + +## What landed + +`max_transform_hierarchy_depth_intra = 1`: a 2N×2N intra coding unit may split its +luma transform once into four half-size children, chosen by `J = SSD + lambda * bits` +against the unsplit block. Chroma splits with the tree while its own blocks stay 4×4 +or larger (log2 > 3); at an 8×8 luma tree chroma stays at the parent size and is +coded with the last child, per 7.3.8.8. The parent luma cbf is the OR of the +children's. Default: on. + +## Gates + +| gate | result | +| --- | --- | +| `cargo test --release -p ec-h265` | 14/14 conformance, whole suite green | +| `rqt_decodes_bit_exactly` | ffmpeg reconstruction sample-exact | +| `transform_skip_decodes_bit_exactly` | sample-exact with rqt on (see defect below) | +| clippy `--all-targets` | 0 warnings | + +## Rate-distortion, four-point ladder against x265 + +BD-PSNR of ours against x265 (higher = closer to x265; both arms same ladder): + +| clip class | rqt off | rqt on | delta | +| --- | --- | --- | --- | +| film | +0.036 | +0.046 | **+0.010** | +| screen capture | −0.043 | +0.037 | **+0.080** | + +Ladder QP shift: −1 on film, 0 on screen. RQT wins on both content classes, so it +is on by default — the ffmpeg/x265 default for intra depth is likewise ≥1. + +## Defect found and fixed in-lane + +Flipping the default to on broke `transform_skip_decodes_bit_exactly`: +`2955 samples differ -- Y 1938, Cb 510, Cr 507, first at (8, 32)`, everything from +luma row 32 down diverging — a CABAC desync, not a reconstruction difference. + +Cause: `transform_skip_flag` is read by the decoder for **every** 4×4 residual block +once the picture parameter set enables skip, and the encoder decided it from the +coding unit's size (`transform_skip && n == 8`, i.e. "chroma is 4×4 only under an +8×8 unit"). With a transform tree, a 16×16 unit splits chroma to 4×4 as well; those +blocks were coded with a real transform and no flag written, while the decoder read +one. The decision now travels by the block's own size — `code_chroma` and +`encode_residual` each already apply it only at 4×4. + +Class: **decision carried at the wrong granularity** — a syntax element that belongs +to the transform block was decided from the coding unit. Swept: the only other +size-conditioned decisions (`ctu.rs:1268` skip, `intra.rs:122/146` filtering and +strong smoothing) all take the transform block's own size. Clean. + +## Not in this lane + +- Depth > 1 (`max_transform_hierarchy_depth_intra = 2`), and the inter tree. +- NxN partitions above 8×8 (still 2Nx2N only outside the minimum unit). +- 64×64 coding units — the remaining lever for the screen-capture gap.