From 96b7b126c451c4c823259896f01ae943a92254b8 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 04:47:39 +0300 Subject: [PATCH] feat(h265): in-loop deblocking filter, on by default Spec 8.7.2, written from the text. An intra-only stream simplifies it twice over: intra prediction reads unfiltered reconstruction, so the filter is a post-pass over the finished picture and the picture-hash SEI stays honest; and every edge has bS = 2, so the whole strength derivation reduces to finding the transform-block boundaries. TuMap carries one byte per 4x4 unit -- log2 of the transform covering it. Transform blocks of side S are aligned to multiples of S, so an edge at x is a boundary exactly when x % S == 0, and no edge list is needed. Each wavefront worker publishes its band; the encoder stitches them, filters every vertical edge, then every horizontal one over the result. Writing the filter exposed an encoder bug: the RQT split trial marks four child transform blocks, and when the nosplit trial won nothing rewrote those cells, so the map reported a boundary inside a 32x32 transform. Reconstruction and coefficients were restored between trials; the side map was not. The nosplit branch now marks its own transform, and tu_log2 rides the CU-depth meta snapshot. ffmpeg decodes every shape bit-exactly with the filter on. BD-PSNR against a deblocking x265, our filter off then on: film -0.197 -> +0.063 dB, screen capture +0.606 -> +0.693, web clip +0.567 -> +0.686, phone clip +0.113 -> +0.162, synthetic +8.781 -> +8.796. Every clip improves, so it defaults on. --- crates/ec-h265/src/ctu.rs | 36 +++- crates/ec-h265/src/deblock.rs | 341 ++++++++++++++++++++++++++++++++ crates/ec-h265/src/encoder.rs | 49 ++++- crates/ec-h265/src/lib.rs | 1 + crates/ec-h265/tests/encode.rs | 16 +- lanes/h265-deblock-r1.report.md | 91 +++++++++ 6 files changed, 521 insertions(+), 13 deletions(-) create mode 100644 crates/ec-h265/src/deblock.rs create mode 100644 lanes/h265-deblock-r1.report.md diff --git a/crates/ec-h265/src/ctu.rs b/crates/ec-h265/src/ctu.rs index 9edb58ed..27f991ef 100644 --- a/crates/ec-h265/src/ctu.rs +++ b/crates/ec-h265/src/ctu.rs @@ -184,6 +184,9 @@ pub struct CtuEncoder<'a> { modes: Vec, /// Coding depth per 4x4 block of the band. depths: Vec, + /// `log2` of the transform block covering each 4x4 block of the band, + /// which is all the deblocking filter needs to find its edges. + tu_log2: Vec, /// Which 4x4 blocks of the *current* CTB are reconstructed. coded: [bool; 256], ctu_x: usize, @@ -243,6 +246,7 @@ impl<'a> CtuEncoder<'a> { min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5), modes: vec![255; (width / 4) * (ctb_size / 4)], depths: vec![0; (width / 4) * (ctb_size / 4)], + tu_log2: vec![2; (width / 4) * (ctb_size / 4)], coded: [false; 256], ctu_x: 0, last_cu_empty: false, @@ -250,6 +254,12 @@ impl<'a> CtuEncoder<'a> { } } + /// `log2` of the transform block covering each 4x4 unit of this row's + /// band, in raster order across the whole picture width. + pub fn tu_log2_band(&self) -> &[u8] { + &self.tu_log2 + } + /// Code one coding tree unit at CTB column `ctu_x`. pub fn encode_ctu(&mut self, ctu_x: usize, enc: &mut CabacEncoder) { self.ctu_x = ctu_x; @@ -482,12 +492,13 @@ impl<'a> CtuEncoder<'a> { fn save_meta(&self, x: usize, y: usize, size: usize) -> Vec { let stride = self.width / 4; - let mut out = Vec::with_capacity(2 * (size / 4) * (size / 4)); + let mut out = Vec::with_capacity(3 * (size / 4) * (size / 4)); for by in (y..y + size).step_by(4) { for bx in (x..x + size).step_by(4) { let idx = ((by - self.band_y0) / 4) * stride + bx / 4; out.push(self.modes[idx]); out.push(self.depths[idx]); + out.push(self.tu_log2[idx]); } } out @@ -501,7 +512,8 @@ impl<'a> CtuEncoder<'a> { let idx = ((by - self.band_y0) / 4) * stride + bx / 4; self.modes[idx] = data[i]; self.depths[idx] = data[i + 1]; - i += 2; + self.tu_log2[idx] = data[i + 2]; + i += 3; } } } @@ -579,6 +591,7 @@ impl<'a> CtuEncoder<'a> { modes[part] = mode; mpms[part] = mpm; self.mark_coded(px, py, 4, mode, depth); + self.mark_tu(px, py, 4); } // part_mode: PART_NxN is the single bin 0. @@ -733,6 +746,7 @@ impl<'a> CtuEncoder<'a> { // The next quadrant predicts from this one, so its samples have to // read as available now: the decoder walks the tree in z-order too. self.mark_coded(cx, cy, HALF, mode, depth); + self.mark_tu(cx, cy, HALF); 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]); @@ -870,6 +884,7 @@ impl<'a> CtuEncoder<'a> { // unit is marked: a transform tree is walked in the same // z-order by the decoder. self.mark_coded(cx, cy, half, mode, depth); + self.mark_tu(cx, cy, half); if chroma_split { let q = half * half / 4; let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 1, chroma_tskip); @@ -941,6 +956,9 @@ impl<'a> CtuEncoder<'a> { cb_cbf, cr_cbf, ); + // The split trial recorded four child transform blocks; this + // unit keeps one, and the deblocking filter reads the map. + self.mark_tu(x, y, n); self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf); } else { self.load_region(x, y, n, &split_rec); @@ -986,6 +1004,7 @@ impl<'a> CtuEncoder<'a> { cr_cbf, ); self.mark_coded(x, y, n, mode, depth); + self.mark_tu(x, y, n); 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 @@ -1217,6 +1236,19 @@ impl<'a> CtuEncoder<'a> { intra::mpm_list(left, above) } + /// Record the transform block of side `n` at `(x, y)`, which is what the + /// deblocking filter reads its edges off. Marked at transform-tree *leaves* + /// only: a coding unit that split records four children, never itself. + fn mark_tu(&mut self, x: usize, y: usize, n: usize) { + let stride = self.width / 4; + let log2 = n.trailing_zeros() as u8; + for by in (y..y + n).step_by(4) { + for bx in (x..x + n).step_by(4) { + self.tu_log2[((by - self.band_y0) / 4) * stride + bx / 4] = log2; + } + } + } + fn mark_coded(&mut self, x: usize, y: usize, n: usize, mode: u8, depth: u8) { let stride = self.width / 4; for by in (y..y + n).step_by(4) { diff --git a/crates/ec-h265/src/deblock.rs b/crates/ec-h265/src/deblock.rs new file mode 100644 index 00000000..033df5f2 --- /dev/null +++ b/crates/ec-h265/src/deblock.rs @@ -0,0 +1,341 @@ +//! The in-loop deblocking filter (8.7.2). +//! +//! An intra-only stream predicts from its own *unfiltered* reconstruction +//! (8.4.4.2.1 reads the samples prior to deblocking), so the filter changes +//! nothing the encoder predicts from: it runs once over the finished picture, +//! and what it produces is what a decoder shows. That keeps the reconstruction +//! bit-identical to a decoder's output -- and the picture-hash SEI that rides +//! on it honest -- while buying back the block edges the transform left. +//! +//! Every edge in an intra picture is a boundary between two intra blocks, so +//! `bS` is 2 wherever an edge exists at all (8.7.2.4); the whole derivation +//! reduces to *where* the transform-block boundaries are, which is what +//! [`TuMap`] carries. + +use crate::transform::chroma_qp; + +/// beta' by Q (table 8-12, first column). +const BETA: [i32; 52] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, + 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, +]; + +/// tC' by Q (table 8-12, second column). +const TC: [i32; 54] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, + 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, +]; + +/// The size of the transform block covering each 4x4 luma position, as a +/// `log2`, over a whole picture. +/// +/// A transform block of side `S` is aligned to a multiple of `S`, so an edge at +/// `x` is that block's own left edge -- and therefore a filtered boundary -- +/// exactly when `x % S == 0`. One number per 4x4 unit answers the question for +/// every edge without recording edges at all. +pub struct TuMap { + log2: Vec, + stride: usize, +} + +impl TuMap { + /// An empty map for a picture of `width` x `height` luma samples. + pub fn new(width: usize, height: usize) -> TuMap { + TuMap { + log2: vec![2; (width / 4) * (height / 4)], + stride: width / 4, + } + } + + /// Record that the transform block of side `1 << log2` covers the square at + /// `(x, y)`. + pub fn mark(&mut self, x: usize, y: usize, log2: u8) { + let side = 1usize << log2; + for by in (y..y + side).step_by(4) { + for bx in (x..x + side).step_by(4) { + let idx = (by / 4) * self.stride + bx / 4; + if idx < self.log2.len() { + self.log2[idx] = log2; + } + } + } + } + + /// Copy one wavefront worker's band, `rows` 4x4 rows of it, into place. + pub fn absorb_band(&mut self, band_y0: usize, rows: usize, band: &[u8]) { + for row in 0..rows { + let dst = (band_y0 / 4 + row) * self.stride; + let src = row * self.stride; + if dst + self.stride <= self.log2.len() && src + self.stride <= band.len() { + self.log2[dst..dst + self.stride].copy_from_slice(&band[src..src + self.stride]); + } + } + } + + /// Whether the vertical edge at luma column `x` is a transform-block + /// boundary for the four rows starting at `y`. + fn vertical_edge(&self, x: usize, y: usize) -> bool { + x > 0 && x.is_multiple_of(1usize << self.log2[(y / 4) * self.stride + x / 4]) + } + + /// Whether the horizontal edge at luma row `y` is a transform-block + /// boundary for the four columns starting at `x`. + fn horizontal_edge(&self, x: usize, y: usize) -> bool { + y > 0 && y.is_multiple_of(1usize << self.log2[(y / 4) * self.stride + x / 4]) + } +} + +/// One line across an edge, as offsets from the boundary: `p3..p0` on one side, +/// `q0..q3` on the other. `step` is the distance between samples across the +/// edge, `at` the index of `q0`. +struct Line { + at: usize, + step: usize, +} + +impl Line { + fn p(&self, plane: &[u8], i: usize) -> i32 { + i32::from(plane[self.at - (i + 1) * self.step]) + } + + fn q(&self, plane: &[u8], i: usize) -> i32 { + i32::from(plane[self.at + i * self.step]) + } + + fn set_p(&self, plane: &mut [u8], i: usize, value: i32) { + plane[self.at - (i + 1) * self.step] = value.clamp(0, 255) as u8; + } + + fn set_q(&self, plane: &mut [u8], i: usize, value: i32) { + plane[self.at + i * self.step] = value.clamp(0, 255) as u8; + } +} + +fn clip3(lo: i32, hi: i32, v: i32) -> i32 { + v.clamp(lo, hi) +} + +/// Filter one four-line luma edge segment (8.7.2.5.3). +fn luma_segment(plane: &mut [u8], lines: [Line; 4], beta: i32, tc: i32) { + let d_of = |line: &Line, plane: &[u8]| { + ( + (line.p(plane, 2) - 2 * line.p(plane, 1) + line.p(plane, 0)).abs(), + (line.q(plane, 2) - 2 * line.q(plane, 1) + line.q(plane, 0)).abs(), + ) + }; + let (dp0, dq0) = d_of(&lines[0], plane); + let (dp3, dq3) = d_of(&lines[3], plane); + let (dpq0, dpq3) = (dp0 + dq0, dp3 + dq3); + let d = dpq0 + dpq3; + if d >= beta { + return; + } + let (dp, dq) = (dp0 + dp3, dq0 + dq3); + + // 8.7.2.5.6: both outer lines have to want the strong filter. + let strong_on = |line: &Line, dpq: i32, plane: &[u8]| { + 2 * dpq < (beta >> 2) + && (line.p(plane, 3) - line.p(plane, 0)).abs() + + (line.q(plane, 0) - line.q(plane, 3)).abs() + < (beta >> 3) + && (line.p(plane, 0) - line.q(plane, 0)).abs() < ((5 * tc + 1) >> 1) + }; + let strong = strong_on(&lines[0], dpq0, plane) && strong_on(&lines[3], dpq3, plane); + let filter_p1 = dp < ((beta + (beta >> 1)) >> 3); + let filter_q1 = dq < ((beta + (beta >> 1)) >> 3); + + for line in &lines { + let p: [i32; 4] = std::array::from_fn(|i| line.p(plane, i)); + let q: [i32; 4] = std::array::from_fn(|i| line.q(plane, i)); + if strong { + let clip = |base: i32, v: i32| clip3(base - 2 * tc, base + 2 * tc, v); + line.set_p( + plane, + 0, + clip( + p[0], + (p[2] + 2 * p[1] + 2 * p[0] + 2 * q[0] + q[1] + 4) >> 3, + ), + ); + line.set_p(plane, 1, clip(p[1], (p[2] + p[1] + p[0] + q[0] + 2) >> 2)); + line.set_p( + plane, + 2, + clip(p[2], (2 * p[3] + 3 * p[2] + p[1] + p[0] + q[0] + 4) >> 3), + ); + line.set_q( + plane, + 0, + clip( + q[0], + (p[1] + 2 * p[0] + 2 * q[0] + 2 * q[1] + q[2] + 4) >> 3, + ), + ); + line.set_q(plane, 1, clip(q[1], (p[0] + q[0] + q[1] + q[2] + 2) >> 2)); + line.set_q( + plane, + 2, + clip(q[2], (p[0] + q[0] + q[1] + 3 * q[2] + 2 * q[3] + 4) >> 3), + ); + } else { + let delta = (9 * (q[0] - p[0]) - 3 * (q[1] - p[1]) + 8) >> 4; + if delta.abs() >= tc * 10 { + continue; + } + let delta = clip3(-tc, tc, delta); + line.set_p(plane, 0, p[0] + delta); + line.set_q(plane, 0, q[0] - delta); + if filter_p1 { + let dp = clip3( + -(tc >> 1), + tc >> 1, + (((p[2] + p[0] + 1) >> 1) - p[1] + delta) >> 1, + ); + line.set_p(plane, 1, p[1] + dp); + } + if filter_q1 { + let dq = clip3( + -(tc >> 1), + tc >> 1, + (((q[2] + q[0] + 1) >> 1) - q[1] - delta) >> 1, + ); + line.set_q(plane, 1, q[1] + dq); + } + } + } +} + +/// Filter one chroma line across an edge (8.7.2.5.5). +fn chroma_line(plane: &mut [u8], line: &Line, tc: i32) { + let (p0, p1) = (line.p(plane, 0), line.p(plane, 1)); + let (q0, q1) = (line.q(plane, 0), line.q(plane, 1)); + let delta = clip3(-tc, tc, (((q0 - p0) << 2) + p1 - q1 + 4) >> 3); + line.set_p(plane, 0, p0 + delta); + line.set_q(plane, 0, q0 - delta); +} + +/// Run the filter over a whole picture: every vertical edge first, then every +/// horizontal one over what the vertical pass left (8.7.2). +/// +/// `qp` is the picture's quantisation parameter, which is every block's here -- +/// nothing in this encoder writes `cu_qp_delta`. +pub fn deblock( + rec_y: &mut [u8], + rec_cb: &mut [u8], + rec_cr: &mut [u8], + width: usize, + height: usize, + qp: i32, + tus: &TuMap, +) { + // bS is 2 on every edge of an intra picture, so both look-ups are constant. + let beta = BETA[clip3(0, 51, qp) as usize]; + let tc_luma = TC[clip3(0, 53, qp + 2) as usize]; + let tc_chroma = TC[clip3(0, 53, chroma_qp(qp, 0) + 2) as usize]; + if beta == 0 && tc_luma == 0 && tc_chroma == 0 { + return; + } + let (cw, ch) = (width / 2, height / 2); + + for x in (8..width).step_by(8) { + for y in (0..height).step_by(4) { + if tus.vertical_edge(x, y) { + let lines = std::array::from_fn(|i| Line { + at: (y + i) * width + x, + step: 1, + }); + luma_segment(rec_y, lines, beta, tc_luma); + } + } + } + for x_c in (8..cw).step_by(8) { + for y_c in (0..ch).step_by(2) { + if tus.vertical_edge(2 * x_c, 2 * y_c) { + for row in 0..2 { + let line = Line { + at: (y_c + row) * cw + x_c, + step: 1, + }; + chroma_line(rec_cb, &line, tc_chroma); + chroma_line(rec_cr, &line, tc_chroma); + } + } + } + } + + for y in (8..height).step_by(8) { + for x in (0..width).step_by(4) { + if tus.horizontal_edge(x, y) { + let lines = std::array::from_fn(|i| Line { + at: y * width + x + i, + step: width, + }); + luma_segment(rec_y, lines, beta, tc_luma); + } + } + } + for y_c in (8..ch).step_by(8) { + for x_c in (0..cw).step_by(2) { + if tus.horizontal_edge(2 * x_c, 2 * y_c) { + for col in 0..2 { + let line = Line { + at: y_c * cw + x_c + col, + step: cw, + }; + chroma_line(rec_cb, &line, tc_chroma); + chroma_line(rec_cr, &line, tc_chroma); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A step across an 8x8 transform boundary, the case the filter exists for. + fn step_picture(w: usize, h: usize) -> (Vec, Vec, Vec) { + let mut y = vec![0u8; w * h]; + for row in 0..h { + for col in 0..w { + y[row * w + col] = if col < 8 { 100 } else { 130 }; + } + } + let c = vec![128u8; w / 2 * h / 2]; + (y, c.clone(), c) + } + + /// The filter has to actually reach the samples: a gate that only proves + /// bit-exactness against a decoder stays green if the filter never fires, + /// because a decoder told the same thing does nothing either. + #[test] + fn an_edge_between_two_transform_blocks_is_filtered() { + let (w, h) = (16, 16); + let (mut y, mut cb, mut cr) = step_picture(w, h); + let before = y.clone(); + let mut tus = TuMap::new(w, h); + for by in (0..h).step_by(8) { + for bx in (0..w).step_by(8) { + tus.mark(bx, by, 3); + } + } + deblock(&mut y, &mut cb, &mut cr, w, h, 32, &tus); + assert_ne!(y, before, "the edge at x=8 was left alone"); + assert!(y[7] > before[7], "p0 should be pulled up toward q0"); + assert!(y[8] < before[8], "q0 should be pulled down toward p0"); + } + + /// The same picture inside one transform block has no interior boundary, + /// so nothing may move — this is what keeps the map honest. + #[test] + fn no_transform_boundary_means_no_filtering() { + let (w, h) = (16, 16); + let (mut y, mut cb, mut cr) = step_picture(w, h); + let before = y.clone(); + let mut tus = TuMap::new(w, h); + tus.mark(0, 0, 4); + deblock(&mut y, &mut cb, &mut cr, w, h, 32, &tus); + assert_eq!(y, before); + } +} diff --git a/crates/ec-h265/src/encoder.rs b/crates/ec-h265/src/encoder.rs index 6dc3e32d..0b9e050f 100644 --- a/crates/ec-h265/src/encoder.rs +++ b/crates/ec-h265/src/encoder.rs @@ -24,6 +24,7 @@ //! whose parameter sets are elsewhere is not one. use crate::ctu::{CtuEncoder, RowBoundary, RowState, SourcePlanes}; +use crate::deblock::{TuMap, deblock}; use ec_core::color::ContentLight; use ec_core::error::{Error, Result}; use ec_core::frame::{PixelFormat, Plane, VideoFrame}; @@ -196,6 +197,12 @@ pub struct EncoderConfig { pub timing: Option<(u32, u32)>, /// HDR mastering metadata, written as prefix SEI. pub content_light: ContentLight, + /// Run the in-loop deblocking filter over the finished picture. + /// + /// An intra picture predicts from its unfiltered reconstruction, so this + /// changes only what a decoder shows -- and what the reconstruction and its + /// picture hash therefore have to say. + pub deblock: bool, /// Emit the decoded picture hash SEI (MD5 of the reconstruction). pub picture_hash: bool, /// Return the reconstruction alongside the bitstream. @@ -226,6 +233,7 @@ impl EncoderConfig { sample_aspect_ratio: None, timing: None, content_light: ContentLight::default(), + deblock: true, picture_hash: false, keep_recon: false, } @@ -343,17 +351,16 @@ impl Encoder { id: 0, sps_id: 0, entropy_coding_sync_enabled: true, - // Deblocking and SAO are both off, which is what makes the - // encoder's reconstruction bit-identical to a decoder's output: an - // intra-only stream predicts from its own reconstruction only, so - // an in-loop filter would change what a decoder shows without - // changing what either side predicts from. Turning them off buys - // that identity (and the picture-hash check that rides on it) - // rather than a fraction of a dB. + // SAO is off; deblocking follows `EncoderConfig::deblock`. An + // intra-only stream predicts from its own *unfiltered* + // reconstruction (8.4.4.2.1), so the deblocking filter changes + // neither side's prediction: running it over the finished picture + // here keeps the reconstruction bit-identical to a decoder's + // output, and the picture hash that rides on it honest. sign_data_hiding_enabled: cfg.sign_hiding, transform_skip_enabled: cfg.transform_skip != TransformSkip::Off, deblocking_filter_control_present: true, - deblocking_filter_disabled: true, + deblocking_filter_disabled: !cfg.deblock, loop_filter_across_slices_enabled: false, ..Pps::default() }; @@ -525,6 +532,9 @@ impl Encoder { let wpp_contexts: Vec>> = (0..rows).map(|_| Mutex::new(None)).collect(); let substreams: Vec>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect(); + // Each row publishes the transform-block sizes of its band, which the + // deblocking filter reads its edges off once the picture is whole. + let tu_bands: Vec>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect(); // One band of the reconstruction per CTB row, handed out by index. let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect(); @@ -553,6 +563,7 @@ impl Encoder { let progress = &progress; let wpp_contexts = &wpp_contexts; let substreams = &substreams; + let tu_bands = &tu_bands; let src = &src; scope.spawn(move || { for (row, band_y, band_cb, band_cr) in worker_rows { @@ -629,6 +640,9 @@ impl Encoder { if let Ok(mut slot) = substreams[row].lock() { *slot = enc.finish(); } + if let Ok(mut slot) = tu_bands[row].lock() { + *slot = coder.tu_log2_band().to_vec(); + } } }); } @@ -638,6 +652,25 @@ impl Encoder { .into_iter() .map(|m| m.into_inner().unwrap_or_default()) .collect(); + if self.cfg.deblock { + let mut tus = TuMap::new(width, height); + for (row, band) in tu_bands.into_iter().enumerate() { + let band = band.into_inner().unwrap_or_default(); + let band_y0 = row * ctb; + let band_rows = (height - band_y0).min(ctb) / 4; + tus.absorb_band(band_y0, band_rows, &band); + } + deblock( + &mut rec_y, + &mut rec_cb, + &mut rec_cr, + width, + height, + qp, + &tus, + ); + } + let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr); let recon = self .cfg diff --git a/crates/ec-h265/src/lib.rs b/crates/ec-h265/src/lib.rs index 3e1830f2..46cd5211 100644 --- a/crates/ec-h265/src/lib.rs +++ b/crates/ec-h265/src/lib.rs @@ -4,6 +4,7 @@ pub mod cabac; pub mod ctu; +pub mod deblock; pub mod encoder; pub mod intra; pub mod residual; diff --git a/crates/ec-h265/tests/encode.rs b/crates/ec-h265/tests/encode.rs index 71876971..9827ac75 100644 --- a/crates/ec-h265/tests/encode.rs +++ b/crates/ec-h265/tests/encode.rs @@ -349,10 +349,17 @@ fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option format!(":{}", extra.trim().trim_matches(':')), _ => String::new(), @@ -457,6 +464,9 @@ fn bd_psnr_vs_x265() { if let Ok(v) = std::env::var("EC_H265_CU64") { cfg.cu64 = v != "0"; } + if let Ok(v) = std::env::var("EC_H265_DEBLOCK") { + cfg.deblock = v != "0"; + } if let Ok(v) = std::env::var("EC_H265_RQT") { cfg.rqt = v != "0"; } diff --git a/lanes/h265-deblock-r1.report.md b/lanes/h265-deblock-r1.report.md new file mode 100644 index 00000000..27c2ab23 --- /dev/null +++ b/lanes/h265-deblock-r1.report.md @@ -0,0 +1,91 @@ +# lane-h265-deblock r1 — HEVC deblocking filter, on by default + +## What landed + +`crates/ec-h265/src/deblock.rs`: the spec 8.7.2 in-loop deblocking filter, +written from the text, and the encoder wiring for it. + +An intra-only stream makes the filter unusually simple: + +* Intra prediction reads *unfiltered* reconstruction (8.4.4.2.1), so for a + stream with no inter pictures the filter is a post-pass over the finished + picture. Reconstruction stays bit-identical to a decoder's output, which is + what the picture-hash SEI promises. +* Every edge of an intra picture has `bS = 2`, so the whole boundary-strength + derivation collapses to one question: where are the transform-block + boundaries? + +`TuMap` answers that with one byte per 4x4 unit — `log2` of the transform block +covering it. Transform blocks of side S are aligned to multiples of S, so an +edge at `x` is a boundary exactly when `x % S == 0`. No edge list is stored. +Each wavefront worker publishes its band's map; the encoder stitches the bands +and runs every vertical edge in the picture, then every horizontal one over the +vertically-filtered samples. + +Luma is the per-4-line-segment decision (`d < beta`), strong or weak filter, +with `filter_p1`/`filter_q1` gated on `dp`/`dq`. Chroma filters p0/q0 +unconditionally with `delta = Clip3(-tC, tC, ((((q0-p0)<<2) + p1 - q1 + 4) >> 3))` +on the 8-chroma-sample edge grid. `beta` is indexed by `Clip3(0,51,qp)`, `tC` +by `Clip3(0,53,qp+2)`; chroma `tC` uses `chroma_qp(qp,0)+2`. + +## Conformance + +`ffmpeg_decodes_bit_exactly_at_every_shape` passes with the filter on: six +picture shapes, both CTB sizes, zero samples differ against ffmpeg's decode. +Bit-exactness against a reference decoder is the whole gate here — the filter +is normative, so "close" is a bug. + +## Bug this uncovered — class `trial-map-not-restored` + +First run: `shape-64x64-ctbdefault: 28 samples differ -- Y 0, Cb 16, Cr 12`. +Luma exact, chroma not, which pointed at a real edge disagreement rather than +at the filter arithmetic: chroma filters unconditionally, so a phantom edge +shows there while luma's `d < beta` test swallows it. + +Root cause was in the encoder, not the filter. The RQT split trial marks four +child transform blocks in the TU map; when the *nosplit* trial won, nothing +rewrote those cells, so the map reported a 16x16 boundary inside a 32x32 +transform. Reconstruction and coefficients were snapshot/restored between +trials — the side map was not. + +Fixed by marking the accepted transform in the nosplit branch, and by adding +`tu_log2` to the third byte of `save_meta`/`load_meta` so the CU-depth trials +restore it too. + +Class swept across `ctu.rs`: every `mark_*` write inside a trial body was +checked against the winner path. `mark_coded` is rewritten by the parent after +the decision; `modes`/`depths`/`tu_log2` all ride the meta snapshot. No second +instance. + +## Measurement — his files + +BD-PSNR against x265 at matched features, **x265 deblocking in every row**, so +the two rows differ only in whether our filter runs. 24 pictures after 1500, +ladders auto-aligned, 0% extrapolation both sides. + +| clip | ours off | ours on | delta luma | delta YUV | +|---|---|---|---|---| +| synthetic 352x288 | +8.781 | +8.796 | +0.015 | +0.039 | +| film 3840x1608 | -0.197 | **+0.063** | **+0.260** | +0.244 | +| screen capture 2560x1440 | +0.606 | +0.693 | +0.087 | +0.104 | +| web clip 640x1138 | +0.567 | +0.686 | +0.119 | +0.140 | +| phone clip 1920x1080 | +0.113 | +0.162 | +0.049 | +0.074 | + +Every clip improves, luma and YUV, so the default is **on** (`EncoderConfig:: +deblock: true`, `deblocking_filter_disabled = !deblock` in the PPS). The film +crosses from behind x265 to ahead of it. + +The absolute numbers in this table are not comparable to the ones in the gate's +doc comment: those were measured against an x265 with `no-deblock`, which is a +different anchor. `EC_H265_X265_DEBLOCK=1` selects the anchor used here. + +## Knobs + +* `EC_H265_DEBLOCK=0` — our filter off. +* `EC_H265_X265_DEBLOCK=1` — x265 deblocks (drops `no-deblock`), for the + matched-feature anchor above. + +## Next + +SAO is the remaining in-loop tool (`sao_enabled: false`). Screen capture is +still the largest content gap.