forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h265-deblock': HEVC deblocking filter

Browse files at this commit

42d0bf6f3e6b0e54fd4334e66556c813c0f367a5Ahmet Kaan GümüşParent: d5332d296b7b12
crates/ec-h265/src/ctu.rsmodified+34 -2
@@ -184,6 +184,9 @@ pub struct CtuEncoder<'a> {
184 modes: Vec<u8>,184 modes: Vec<u8>,
185 /// Coding depth per 4x4 block of the band.185 /// Coding depth per 4x4 block of the band.
186 depths: Vec<u8>,186 depths: Vec<u8>,
187+ /// `log2` of the transform block covering each 4x4 block of the band,
188+ /// which is all the deblocking filter needs to find its edges.
189+ tu_log2: Vec<u8>,
187 /// Which 4x4 blocks of the *current* CTB are reconstructed.190 /// Which 4x4 blocks of the *current* CTB are reconstructed.
188 coded: [bool; 256],191 coded: [bool; 256],
189 ctu_x: usize,192 ctu_x: usize,
@@ -243,6 +246,7 @@ impl<'a> CtuEncoder<'a> {
243 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),246 min_cb_log2: min_cb_log2.clamp(MIN_CB_LOG2, 5),
244 modes: vec![255; (width / 4) * (ctb_size / 4)],247 modes: vec![255; (width / 4) * (ctb_size / 4)],
245 depths: vec![0; (width / 4) * (ctb_size / 4)],248 depths: vec![0; (width / 4) * (ctb_size / 4)],
249+ tu_log2: vec![2; (width / 4) * (ctb_size / 4)],
246 coded: [false; 256],250 coded: [false; 256],
247 ctu_x: 0,251 ctu_x: 0,
248 last_cu_empty: false,252 last_cu_empty: false,
@@ -250,6 +254,12 @@ impl<'a> CtuEncoder<'a> {
250 }254 }
251 }255 }
252 256
257+ /// `log2` of the transform block covering each 4x4 unit of this row's
258+ /// band, in raster order across the whole picture width.
259+ pub fn tu_log2_band(&self) -> &[u8] {
260+ &self.tu_log2
261+ }
262+
253 /// Code one coding tree unit at CTB column `ctu_x`.263 /// Code one coding tree unit at CTB column `ctu_x`.
254 pub fn encode_ctu(&mut self, ctu_x: usize, enc: &mut CabacEncoder) {264 pub fn encode_ctu(&mut self, ctu_x: usize, enc: &mut CabacEncoder) {
255 self.ctu_x = ctu_x;265 self.ctu_x = ctu_x;
@@ -482,12 +492,13 @@ impl<'a> CtuEncoder<'a> {
482 492
483 fn save_meta(&self, x: usize, y: usize, size: usize) -> Vec<u8> {493 fn save_meta(&self, x: usize, y: usize, size: usize) -> Vec<u8> {
484 let stride = self.width / 4;494 let stride = self.width / 4;
485- let mut out = Vec::with_capacity(2 * (size / 4) * (size / 4));495+ let mut out = Vec::with_capacity(3 * (size / 4) * (size / 4));
486 for by in (y..y + size).step_by(4) {496 for by in (y..y + size).step_by(4) {
487 for bx in (x..x + size).step_by(4) {497 for bx in (x..x + size).step_by(4) {
488 let idx = ((by - self.band_y0) / 4) * stride + bx / 4;498 let idx = ((by - self.band_y0) / 4) * stride + bx / 4;
489 out.push(self.modes[idx]);499 out.push(self.modes[idx]);
490 out.push(self.depths[idx]);500 out.push(self.depths[idx]);
501+ out.push(self.tu_log2[idx]);
491 }502 }
492 }503 }
493 out504 out
@@ -501,7 +512,8 @@ impl<'a> CtuEncoder<'a> {
501 let idx = ((by - self.band_y0) / 4) * stride + bx / 4;512 let idx = ((by - self.band_y0) / 4) * stride + bx / 4;
502 self.modes[idx] = data[i];513 self.modes[idx] = data[i];
503 self.depths[idx] = data[i + 1];514 self.depths[idx] = data[i + 1];
504- i += 2;515+ self.tu_log2[idx] = data[i + 2];
516+ i += 3;
505 }517 }
506 }518 }
507 }519 }
@@ -579,6 +591,7 @@ impl<'a> CtuEncoder<'a> {
579 modes[part] = mode;591 modes[part] = mode;
580 mpms[part] = mpm;592 mpms[part] = mpm;
581 self.mark_coded(px, py, 4, mode, depth);593 self.mark_coded(px, py, 4, mode, depth);
594+ self.mark_tu(px, py, 4);
582 }595 }
583 596
584 // part_mode: PART_NxN is the single bin 0.597 // part_mode: PART_NxN is the single bin 0.
@@ -733,6 +746,7 @@ impl<'a> CtuEncoder<'a> {
733 // The next quadrant predicts from this one, so its samples have to746 // The next quadrant predicts from this one, so its samples have to
734 // read as available now: the decoder walks the tree in z-order too.747 // read as available now: the decoder walks the tree in z-order too.
735 self.mark_coded(cx, cy, HALF, mode, depth);748 self.mark_coded(cx, cy, HALF, mode, depth);
749+ self.mark_tu(cx, cy, HALF);
736 let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 1, chroma_tskip);750 let (_, cbf) = self.code_chroma(cx, cy, HALF, chroma_mode, 1, chroma_tskip);
737 child_cb_cbf[part] = cbf;751 child_cb_cbf[part] = cbf;
738 child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]);752 child_cb[part][..q].copy_from_slice(&self.scratch.cb_levels[..q]);
@@ -870,6 +884,7 @@ impl<'a> CtuEncoder<'a> {
870 // unit is marked: a transform tree is walked in the same884 // unit is marked: a transform tree is walked in the same
871 // z-order by the decoder.885 // z-order by the decoder.
872 self.mark_coded(cx, cy, half, mode, depth);886 self.mark_coded(cx, cy, half, mode, depth);
887+ self.mark_tu(cx, cy, half);
873 if chroma_split {888 if chroma_split {
874 let q = half * half / 4;889 let q = half * half / 4;
875 let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 1, chroma_tskip);890 let (_, cbf) = self.code_chroma(cx, cy, half, chroma_mode, 1, chroma_tskip);
@@ -941,6 +956,9 @@ impl<'a> CtuEncoder<'a> {
941 cb_cbf,956 cb_cbf,
942 cr_cbf,957 cr_cbf,
943 );958 );
959+ // The split trial recorded four child transform blocks; this
960+ // unit keeps one, and the deblocking filter reads the map.
961+ self.mark_tu(x, y, n);
944 self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);962 self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);
945 } else {963 } else {
946 self.load_region(x, y, n, &split_rec);964 self.load_region(x, y, n, &split_rec);
@@ -986,6 +1004,7 @@ impl<'a> CtuEncoder<'a> {
986 cr_cbf,1004 cr_cbf,
987 );1005 );
988 self.mark_coded(x, y, n, mode, depth);1006 self.mark_coded(x, y, n, mode, depth);
1007+ self.mark_tu(x, y, n);
989 self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);1008 self.last_cu_empty = !(luma_cbf || cb_cbf || cr_cbf);
990 let bits = enc.bit_count() - before;1009 let bits = enc.bit_count() - before;
991 self.region_ssd(x, y, n) + self.lambda * bits as f641010 self.region_ssd(x, y, n) + self.lambda * bits as f64
@@ -1217,6 +1236,19 @@ impl<'a> CtuEncoder<'a> {
1217 intra::mpm_list(left, above)1236 intra::mpm_list(left, above)
1218 }1237 }
1219 1238
1239+ /// Record the transform block of side `n` at `(x, y)`, which is what the
1240+ /// deblocking filter reads its edges off. Marked at transform-tree *leaves*
1241+ /// only: a coding unit that split records four children, never itself.
1242+ fn mark_tu(&mut self, x: usize, y: usize, n: usize) {
1243+ let stride = self.width / 4;
1244+ let log2 = n.trailing_zeros() as u8;
1245+ for by in (y..y + n).step_by(4) {
1246+ for bx in (x..x + n).step_by(4) {
1247+ self.tu_log2[((by - self.band_y0) / 4) * stride + bx / 4] = log2;
1248+ }
1249+ }
1250+ }
1251+
1220 fn mark_coded(&mut self, x: usize, y: usize, n: usize, mode: u8, depth: u8) {1252 fn mark_coded(&mut self, x: usize, y: usize, n: usize, mode: u8, depth: u8) {
1221 let stride = self.width / 4;1253 let stride = self.width / 4;
1222 for by in (y..y + n).step_by(4) {1254 for by in (y..y + n).step_by(4) {
crates/ec-h265/src/deblock.rsadded+341 -0
@@ -0,0 +1,341 @@
1+//! The in-loop deblocking filter (8.7.2).
2+//!
3+//! An intra-only stream predicts from its own *unfiltered* reconstruction
4+//! (8.4.4.2.1 reads the samples prior to deblocking), so the filter changes
5+//! nothing the encoder predicts from: it runs once over the finished picture,
6+//! and what it produces is what a decoder shows. That keeps the reconstruction
7+//! bit-identical to a decoder's output -- and the picture-hash SEI that rides
8+//! on it honest -- while buying back the block edges the transform left.
9+//!
10+//! Every edge in an intra picture is a boundary between two intra blocks, so
11+//! `bS` is 2 wherever an edge exists at all (8.7.2.4); the whole derivation
12+//! reduces to *where* the transform-block boundaries are, which is what
13+//! [`TuMap`] carries.
14+
15+use crate::transform::chroma_qp;
16+
17+/// beta' by Q (table 8-12, first column).
18+const BETA: [i32; 52] = [
19+ 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+ 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64,
21+];
22+
23+/// tC' by Q (table 8-12, second column).
24+const TC: [i32; 54] = [
25+ 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,
26+ 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24,
27+];
28+
29+/// The size of the transform block covering each 4x4 luma position, as a
30+/// `log2`, over a whole picture.
31+///
32+/// A transform block of side `S` is aligned to a multiple of `S`, so an edge at
33+/// `x` is that block's own left edge -- and therefore a filtered boundary --
34+/// exactly when `x % S == 0`. One number per 4x4 unit answers the question for
35+/// every edge without recording edges at all.
36+pub struct TuMap {
37+ log2: Vec<u8>,
38+ stride: usize,
39+}
40+
41+impl TuMap {
42+ /// An empty map for a picture of `width` x `height` luma samples.
43+ pub fn new(width: usize, height: usize) -> TuMap {
44+ TuMap {
45+ log2: vec![2; (width / 4) * (height / 4)],
46+ stride: width / 4,
47+ }
48+ }
49+
50+ /// Record that the transform block of side `1 << log2` covers the square at
51+ /// `(x, y)`.
52+ pub fn mark(&mut self, x: usize, y: usize, log2: u8) {
53+ let side = 1usize << log2;
54+ for by in (y..y + side).step_by(4) {
55+ for bx in (x..x + side).step_by(4) {
56+ let idx = (by / 4) * self.stride + bx / 4;
57+ if idx < self.log2.len() {
58+ self.log2[idx] = log2;
59+ }
60+ }
61+ }
62+ }
63+
64+ /// Copy one wavefront worker's band, `rows` 4x4 rows of it, into place.
65+ pub fn absorb_band(&mut self, band_y0: usize, rows: usize, band: &[u8]) {
66+ for row in 0..rows {
67+ let dst = (band_y0 / 4 + row) * self.stride;
68+ let src = row * self.stride;
69+ if dst + self.stride <= self.log2.len() && src + self.stride <= band.len() {
70+ self.log2[dst..dst + self.stride].copy_from_slice(&band[src..src + self.stride]);
71+ }
72+ }
73+ }
74+
75+ /// Whether the vertical edge at luma column `x` is a transform-block
76+ /// boundary for the four rows starting at `y`.
77+ fn vertical_edge(&self, x: usize, y: usize) -> bool {
78+ x > 0 && x.is_multiple_of(1usize << self.log2[(y / 4) * self.stride + x / 4])
79+ }
80+
81+ /// Whether the horizontal edge at luma row `y` is a transform-block
82+ /// boundary for the four columns starting at `x`.
83+ fn horizontal_edge(&self, x: usize, y: usize) -> bool {
84+ y > 0 && y.is_multiple_of(1usize << self.log2[(y / 4) * self.stride + x / 4])
85+ }
86+}
87+
88+/// One line across an edge, as offsets from the boundary: `p3..p0` on one side,
89+/// `q0..q3` on the other. `step` is the distance between samples across the
90+/// edge, `at` the index of `q0`.
91+struct Line {
92+ at: usize,
93+ step: usize,
94+}
95+
96+impl Line {
97+ fn p(&self, plane: &[u8], i: usize) -> i32 {
98+ i32::from(plane[self.at - (i + 1) * self.step])
99+ }
100+
101+ fn q(&self, plane: &[u8], i: usize) -> i32 {
102+ i32::from(plane[self.at + i * self.step])
103+ }
104+
105+ fn set_p(&self, plane: &mut [u8], i: usize, value: i32) {
106+ plane[self.at - (i + 1) * self.step] = value.clamp(0, 255) as u8;
107+ }
108+
109+ fn set_q(&self, plane: &mut [u8], i: usize, value: i32) {
110+ plane[self.at + i * self.step] = value.clamp(0, 255) as u8;
111+ }
112+}
113+
114+fn clip3(lo: i32, hi: i32, v: i32) -> i32 {
115+ v.clamp(lo, hi)
116+}
117+
118+/// Filter one four-line luma edge segment (8.7.2.5.3).
119+fn luma_segment(plane: &mut [u8], lines: [Line; 4], beta: i32, tc: i32) {
120+ let d_of = |line: &Line, plane: &[u8]| {
121+ (
122+ (line.p(plane, 2) - 2 * line.p(plane, 1) + line.p(plane, 0)).abs(),
123+ (line.q(plane, 2) - 2 * line.q(plane, 1) + line.q(plane, 0)).abs(),
124+ )
125+ };
126+ let (dp0, dq0) = d_of(&lines[0], plane);
127+ let (dp3, dq3) = d_of(&lines[3], plane);
128+ let (dpq0, dpq3) = (dp0 + dq0, dp3 + dq3);
129+ let d = dpq0 + dpq3;
130+ if d >= beta {
131+ return;
132+ }
133+ let (dp, dq) = (dp0 + dp3, dq0 + dq3);
134+
135+ // 8.7.2.5.6: both outer lines have to want the strong filter.
136+ let strong_on = |line: &Line, dpq: i32, plane: &[u8]| {
137+ 2 * dpq < (beta >> 2)
138+ && (line.p(plane, 3) - line.p(plane, 0)).abs()
139+ + (line.q(plane, 0) - line.q(plane, 3)).abs()
140+ < (beta >> 3)
141+ && (line.p(plane, 0) - line.q(plane, 0)).abs() < ((5 * tc + 1) >> 1)
142+ };
143+ let strong = strong_on(&lines[0], dpq0, plane) && strong_on(&lines[3], dpq3, plane);
144+ let filter_p1 = dp < ((beta + (beta >> 1)) >> 3);
145+ let filter_q1 = dq < ((beta + (beta >> 1)) >> 3);
146+
147+ for line in &lines {
148+ let p: [i32; 4] = std::array::from_fn(|i| line.p(plane, i));
149+ let q: [i32; 4] = std::array::from_fn(|i| line.q(plane, i));
150+ if strong {
151+ let clip = |base: i32, v: i32| clip3(base - 2 * tc, base + 2 * tc, v);
152+ line.set_p(
153+ plane,
154+ 0,
155+ clip(
156+ p[0],
157+ (p[2] + 2 * p[1] + 2 * p[0] + 2 * q[0] + q[1] + 4) >> 3,
158+ ),
159+ );
160+ line.set_p(plane, 1, clip(p[1], (p[2] + p[1] + p[0] + q[0] + 2) >> 2));
161+ line.set_p(
162+ plane,
163+ 2,
164+ clip(p[2], (2 * p[3] + 3 * p[2] + p[1] + p[0] + q[0] + 4) >> 3),
165+ );
166+ line.set_q(
167+ plane,
168+ 0,
169+ clip(
170+ q[0],
171+ (p[1] + 2 * p[0] + 2 * q[0] + 2 * q[1] + q[2] + 4) >> 3,
172+ ),
173+ );
174+ line.set_q(plane, 1, clip(q[1], (p[0] + q[0] + q[1] + q[2] + 2) >> 2));
175+ line.set_q(
176+ plane,
177+ 2,
178+ clip(q[2], (p[0] + q[0] + q[1] + 3 * q[2] + 2 * q[3] + 4) >> 3),
179+ );
180+ } else {
181+ let delta = (9 * (q[0] - p[0]) - 3 * (q[1] - p[1]) + 8) >> 4;
182+ if delta.abs() >= tc * 10 {
183+ continue;
184+ }
185+ let delta = clip3(-tc, tc, delta);
186+ line.set_p(plane, 0, p[0] + delta);
187+ line.set_q(plane, 0, q[0] - delta);
188+ if filter_p1 {
189+ let dp = clip3(
190+ -(tc >> 1),
191+ tc >> 1,
192+ (((p[2] + p[0] + 1) >> 1) - p[1] + delta) >> 1,
193+ );
194+ line.set_p(plane, 1, p[1] + dp);
195+ }
196+ if filter_q1 {
197+ let dq = clip3(
198+ -(tc >> 1),
199+ tc >> 1,
200+ (((q[2] + q[0] + 1) >> 1) - q[1] - delta) >> 1,
201+ );
202+ line.set_q(plane, 1, q[1] + dq);
203+ }
204+ }
205+ }
206+}
207+
208+/// Filter one chroma line across an edge (8.7.2.5.5).
209+fn chroma_line(plane: &mut [u8], line: &Line, tc: i32) {
210+ let (p0, p1) = (line.p(plane, 0), line.p(plane, 1));
211+ let (q0, q1) = (line.q(plane, 0), line.q(plane, 1));
212+ let delta = clip3(-tc, tc, (((q0 - p0) << 2) + p1 - q1 + 4) >> 3);
213+ line.set_p(plane, 0, p0 + delta);
214+ line.set_q(plane, 0, q0 - delta);
215+}
216+
217+/// Run the filter over a whole picture: every vertical edge first, then every
218+/// horizontal one over what the vertical pass left (8.7.2).
219+///
220+/// `qp` is the picture's quantisation parameter, which is every block's here --
221+/// nothing in this encoder writes `cu_qp_delta`.
222+pub fn deblock(
223+ rec_y: &mut [u8],
224+ rec_cb: &mut [u8],
225+ rec_cr: &mut [u8],
226+ width: usize,
227+ height: usize,
228+ qp: i32,
229+ tus: &TuMap,
230+) {
231+ // bS is 2 on every edge of an intra picture, so both look-ups are constant.
232+ let beta = BETA[clip3(0, 51, qp) as usize];
233+ let tc_luma = TC[clip3(0, 53, qp + 2) as usize];
234+ let tc_chroma = TC[clip3(0, 53, chroma_qp(qp, 0) + 2) as usize];
235+ if beta == 0 && tc_luma == 0 && tc_chroma == 0 {
236+ return;
237+ }
238+ let (cw, ch) = (width / 2, height / 2);
239+
240+ for x in (8..width).step_by(8) {
241+ for y in (0..height).step_by(4) {
242+ if tus.vertical_edge(x, y) {
243+ let lines = std::array::from_fn(|i| Line {
244+ at: (y + i) * width + x,
245+ step: 1,
246+ });
247+ luma_segment(rec_y, lines, beta, tc_luma);
248+ }
249+ }
250+ }
251+ for x_c in (8..cw).step_by(8) {
252+ for y_c in (0..ch).step_by(2) {
253+ if tus.vertical_edge(2 * x_c, 2 * y_c) {
254+ for row in 0..2 {
255+ let line = Line {
256+ at: (y_c + row) * cw + x_c,
257+ step: 1,
258+ };
259+ chroma_line(rec_cb, &line, tc_chroma);
260+ chroma_line(rec_cr, &line, tc_chroma);
261+ }
262+ }
263+ }
264+ }
265+
266+ for y in (8..height).step_by(8) {
267+ for x in (0..width).step_by(4) {
268+ if tus.horizontal_edge(x, y) {
269+ let lines = std::array::from_fn(|i| Line {
270+ at: y * width + x + i,
271+ step: width,
272+ });
273+ luma_segment(rec_y, lines, beta, tc_luma);
274+ }
275+ }
276+ }
277+ for y_c in (8..ch).step_by(8) {
278+ for x_c in (0..cw).step_by(2) {
279+ if tus.horizontal_edge(2 * x_c, 2 * y_c) {
280+ for col in 0..2 {
281+ let line = Line {
282+ at: y_c * cw + x_c + col,
283+ step: cw,
284+ };
285+ chroma_line(rec_cb, &line, tc_chroma);
286+ chroma_line(rec_cr, &line, tc_chroma);
287+ }
288+ }
289+ }
290+ }
291+}
292+
293+#[cfg(test)]
294+mod tests {
295+ use super::*;
296+
297+ /// A step across an 8x8 transform boundary, the case the filter exists for.
298+ fn step_picture(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
299+ let mut y = vec![0u8; w * h];
300+ for row in 0..h {
301+ for col in 0..w {
302+ y[row * w + col] = if col < 8 { 100 } else { 130 };
303+ }
304+ }
305+ let c = vec![128u8; w / 2 * h / 2];
306+ (y, c.clone(), c)
307+ }
308+
309+ /// The filter has to actually reach the samples: a gate that only proves
310+ /// bit-exactness against a decoder stays green if the filter never fires,
311+ /// because a decoder told the same thing does nothing either.
312+ #[test]
313+ fn an_edge_between_two_transform_blocks_is_filtered() {
314+ let (w, h) = (16, 16);
315+ let (mut y, mut cb, mut cr) = step_picture(w, h);
316+ let before = y.clone();
317+ let mut tus = TuMap::new(w, h);
318+ for by in (0..h).step_by(8) {
319+ for bx in (0..w).step_by(8) {
320+ tus.mark(bx, by, 3);
321+ }
322+ }
323+ deblock(&mut y, &mut cb, &mut cr, w, h, 32, &tus);
324+ assert_ne!(y, before, "the edge at x=8 was left alone");
325+ assert!(y[7] > before[7], "p0 should be pulled up toward q0");
326+ assert!(y[8] < before[8], "q0 should be pulled down toward p0");
327+ }
328+
329+ /// The same picture inside one transform block has no interior boundary,
330+ /// so nothing may move — this is what keeps the map honest.
331+ #[test]
332+ fn no_transform_boundary_means_no_filtering() {
333+ let (w, h) = (16, 16);
334+ let (mut y, mut cb, mut cr) = step_picture(w, h);
335+ let before = y.clone();
336+ let mut tus = TuMap::new(w, h);
337+ tus.mark(0, 0, 4);
338+ deblock(&mut y, &mut cb, &mut cr, w, h, 32, &tus);
339+ assert_eq!(y, before);
340+ }
341+}
crates/ec-h265/src/encoder.rsmodified+41 -8
@@ -24,6 +24,7 @@
24 //! whose parameter sets are elsewhere is not one.24 //! whose parameter sets are elsewhere is not one.
25 25
26 use crate::ctu::{CtuEncoder, RowBoundary, RowState, SourcePlanes};26 use crate::ctu::{CtuEncoder, RowBoundary, RowState, SourcePlanes};
27+use crate::deblock::{TuMap, deblock};
27 use ec_core::color::ContentLight;28 use ec_core::color::ContentLight;
28 use ec_core::error::{Error, Result};29 use ec_core::error::{Error, Result};
29 use ec_core::frame::{PixelFormat, Plane, VideoFrame};30 use ec_core::frame::{PixelFormat, Plane, VideoFrame};
@@ -196,6 +197,12 @@ pub struct EncoderConfig {
196 pub timing: Option<(u32, u32)>,197 pub timing: Option<(u32, u32)>,
197 /// HDR mastering metadata, written as prefix SEI.198 /// HDR mastering metadata, written as prefix SEI.
198 pub content_light: ContentLight,199 pub content_light: ContentLight,
200+ /// Run the in-loop deblocking filter over the finished picture.
201+ ///
202+ /// An intra picture predicts from its unfiltered reconstruction, so this
203+ /// changes only what a decoder shows -- and what the reconstruction and its
204+ /// picture hash therefore have to say.
205+ pub deblock: bool,
199 /// Emit the decoded picture hash SEI (MD5 of the reconstruction).206 /// Emit the decoded picture hash SEI (MD5 of the reconstruction).
200 pub picture_hash: bool,207 pub picture_hash: bool,
201 /// Return the reconstruction alongside the bitstream.208 /// Return the reconstruction alongside the bitstream.
@@ -226,6 +233,7 @@ impl EncoderConfig {
226 sample_aspect_ratio: None,233 sample_aspect_ratio: None,
227 timing: None,234 timing: None,
228 content_light: ContentLight::default(),235 content_light: ContentLight::default(),
236+ deblock: true,
229 picture_hash: false,237 picture_hash: false,
230 keep_recon: false,238 keep_recon: false,
231 }239 }
@@ -343,17 +351,16 @@ impl Encoder {
343 id: 0,351 id: 0,
344 sps_id: 0,352 sps_id: 0,
345 entropy_coding_sync_enabled: true,353 entropy_coding_sync_enabled: true,
346- // Deblocking and SAO are both off, which is what makes the354+ // SAO is off; deblocking follows `EncoderConfig::deblock`. An
347- // encoder's reconstruction bit-identical to a decoder's output: an355+ // intra-only stream predicts from its own *unfiltered*
348- // intra-only stream predicts from its own reconstruction only, so356+ // reconstruction (8.4.4.2.1), so the deblocking filter changes
349- // an in-loop filter would change what a decoder shows without357+ // neither side's prediction: running it over the finished picture
350- // changing what either side predicts from. Turning them off buys358+ // here keeps the reconstruction bit-identical to a decoder's
351- // that identity (and the picture-hash check that rides on it)359+ // output, and the picture hash that rides on it honest.
352- // rather than a fraction of a dB.
353 sign_data_hiding_enabled: cfg.sign_hiding,360 sign_data_hiding_enabled: cfg.sign_hiding,
354 transform_skip_enabled: cfg.transform_skip != TransformSkip::Off,361 transform_skip_enabled: cfg.transform_skip != TransformSkip::Off,
355 deblocking_filter_control_present: true,362 deblocking_filter_control_present: true,
356- deblocking_filter_disabled: true,363+ deblocking_filter_disabled: !cfg.deblock,
357 loop_filter_across_slices_enabled: false,364 loop_filter_across_slices_enabled: false,
358 ..Pps::default()365 ..Pps::default()
359 };366 };
@@ -525,6 +532,9 @@ impl Encoder {
525 let wpp_contexts: Vec<Mutex<Option<Contexts>>> =532 let wpp_contexts: Vec<Mutex<Option<Contexts>>> =
526 (0..rows).map(|_| Mutex::new(None)).collect();533 (0..rows).map(|_| Mutex::new(None)).collect();
527 let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();534 let substreams: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
535+ // Each row publishes the transform-block sizes of its band, which the
536+ // deblocking filter reads its edges off once the picture is whole.
537+ let tu_bands: Vec<Mutex<Vec<u8>>> = (0..rows).map(|_| Mutex::new(Vec::new())).collect();
528 538
529 // One band of the reconstruction per CTB row, handed out by index.539 // One band of the reconstruction per CTB row, handed out by index.
530 let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect();540 let mut bands_y: Vec<&mut [u8]> = rec_y.chunks_mut(ctb * width).collect();
@@ -553,6 +563,7 @@ impl Encoder {
553 let progress = &progress;563 let progress = &progress;
554 let wpp_contexts = &wpp_contexts;564 let wpp_contexts = &wpp_contexts;
555 let substreams = &substreams;565 let substreams = &substreams;
566+ let tu_bands = &tu_bands;
556 let src = &src;567 let src = &src;
557 scope.spawn(move || {568 scope.spawn(move || {
558 for (row, band_y, band_cb, band_cr) in worker_rows {569 for (row, band_y, band_cb, band_cr) in worker_rows {
@@ -629,6 +640,9 @@ impl Encoder {
629 if let Ok(mut slot) = substreams[row].lock() {640 if let Ok(mut slot) = substreams[row].lock() {
630 *slot = enc.finish();641 *slot = enc.finish();
631 }642 }
643+ if let Ok(mut slot) = tu_bands[row].lock() {
644+ *slot = coder.tu_log2_band().to_vec();
645+ }
632 }646 }
633 });647 });
634 }648 }
@@ -638,6 +652,25 @@ impl Encoder {
638 .into_iter()652 .into_iter()
639 .map(|m| m.into_inner().unwrap_or_default())653 .map(|m| m.into_inner().unwrap_or_default())
640 .collect();654 .collect();
655+ if self.cfg.deblock {
656+ let mut tus = TuMap::new(width, height);
657+ for (row, band) in tu_bands.into_iter().enumerate() {
658+ let band = band.into_inner().unwrap_or_default();
659+ let band_y0 = row * ctb;
660+ let band_rows = (height - band_y0).min(ctb) / 4;
661+ tus.absorb_band(band_y0, band_rows, &band);
662+ }
663+ deblock(
664+ &mut rec_y,
665+ &mut rec_cb,
666+ &mut rec_cr,
667+ width,
668+ height,
669+ qp,
670+ &tus,
671+ );
672+ }
673+
641 let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr);674 let au = self.assemble_au(qp, &substreams, &rec_y, &rec_cb, &rec_cr);
642 let recon = self675 let recon = self
643 .cfg676 .cfg
crates/ec-h265/src/lib.rsmodified+1 -0
@@ -4,6 +4,7 @@
4 4
5 pub mod cabac;5 pub mod cabac;
6 pub mod ctu;6 pub mod ctu;
7+pub mod deblock;
7 pub mod encoder;8 pub mod encoder;
8 pub mod intra;9 pub mod intra;
9 pub mod residual;10 pub mod residual;
crates/ec-h265/tests/encode.rsmodified+13 -3
@@ -349,10 +349,17 @@ fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option<Vec
349 // EC_H265_X265_PARAMS appends to attribute a single feature the same way349 // EC_H265_X265_PARAMS appends to attribute a single feature the same way
350 // EC_H264_X264_PARAMS does.350 // EC_H264_X264_PARAMS does.
351 let params = format!(351 let params = format!(
352- "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:no-deblock:\352+ "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:{deblock}\
353 aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\353 aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\
354- pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{}",354+ pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{extra}",
355- match std::env::var("EC_H265_X265_PARAMS") {355+ // x265 deblocks by default; `no-deblock` matches an encoder that does
356+ // not, and EC_H265_X265_DEBLOCK=1 drops it so both sides filter.
357+ deblock = if std::env::var("EC_H265_X265_DEBLOCK").is_ok_and(|v| v != "0") {
358+ ""
359+ } else {
360+ "no-deblock:"
361+ },
362+ extra = match std::env::var("EC_H265_X265_PARAMS") {
356 Ok(extra) if !extra.trim().trim_matches(':').is_empty() =>363 Ok(extra) if !extra.trim().trim_matches(':').is_empty() =>
357 format!(":{}", extra.trim().trim_matches(':')),364 format!(":{}", extra.trim().trim_matches(':')),
358 _ => String::new(),365 _ => String::new(),
@@ -457,6 +464,9 @@ fn bd_psnr_vs_x265() {
457 if let Ok(v) = std::env::var("EC_H265_CU64") {464 if let Ok(v) = std::env::var("EC_H265_CU64") {
458 cfg.cu64 = v != "0";465 cfg.cu64 = v != "0";
459 }466 }
467+ if let Ok(v) = std::env::var("EC_H265_DEBLOCK") {
468+ cfg.deblock = v != "0";
469+ }
460 if let Ok(v) = std::env::var("EC_H265_RQT") {470 if let Ok(v) = std::env::var("EC_H265_RQT") {
461 cfg.rqt = v != "0";471 cfg.rqt = v != "0";
462 }472 }
lanes/h265-deblock-r1.report.mdadded+91 -0
@@ -0,0 +1,91 @@
1+# lane-h265-deblock r1 — HEVC deblocking filter, on by default
2+
3+## What landed
4+
5+`crates/ec-h265/src/deblock.rs`: the spec 8.7.2 in-loop deblocking filter,
6+written from the text, and the encoder wiring for it.
7+
8+An intra-only stream makes the filter unusually simple:
9+
10+* Intra prediction reads *unfiltered* reconstruction (8.4.4.2.1), so for a
11+ stream with no inter pictures the filter is a post-pass over the finished
12+ picture. Reconstruction stays bit-identical to a decoder's output, which is
13+ what the picture-hash SEI promises.
14+* Every edge of an intra picture has `bS = 2`, so the whole boundary-strength
15+ derivation collapses to one question: where are the transform-block
16+ boundaries?
17+
18+`TuMap` answers that with one byte per 4x4 unit — `log2` of the transform block
19+covering it. Transform blocks of side S are aligned to multiples of S, so an
20+edge at `x` is a boundary exactly when `x % S == 0`. No edge list is stored.
21+Each wavefront worker publishes its band's map; the encoder stitches the bands
22+and runs every vertical edge in the picture, then every horizontal one over the
23+vertically-filtered samples.
24+
25+Luma is the per-4-line-segment decision (`d < beta`), strong or weak filter,
26+with `filter_p1`/`filter_q1` gated on `dp`/`dq`. Chroma filters p0/q0
27+unconditionally with `delta = Clip3(-tC, tC, ((((q0-p0)<<2) + p1 - q1 + 4) >> 3))`
28+on the 8-chroma-sample edge grid. `beta` is indexed by `Clip3(0,51,qp)`, `tC`
29+by `Clip3(0,53,qp+2)`; chroma `tC` uses `chroma_qp(qp,0)+2`.
30+
31+## Conformance
32+
33+`ffmpeg_decodes_bit_exactly_at_every_shape` passes with the filter on: six
34+picture shapes, both CTB sizes, zero samples differ against ffmpeg's decode.
35+Bit-exactness against a reference decoder is the whole gate here — the filter
36+is normative, so "close" is a bug.
37+
38+## Bug this uncovered — class `trial-map-not-restored`
39+
40+First run: `shape-64x64-ctbdefault: 28 samples differ -- Y 0, Cb 16, Cr 12`.
41+Luma exact, chroma not, which pointed at a real edge disagreement rather than
42+at the filter arithmetic: chroma filters unconditionally, so a phantom edge
43+shows there while luma's `d < beta` test swallows it.
44+
45+Root cause was in the encoder, not the filter. The RQT split trial marks four
46+child transform blocks in the TU map; when the *nosplit* trial won, nothing
47+rewrote those cells, so the map reported a 16x16 boundary inside a 32x32
48+transform. Reconstruction and coefficients were snapshot/restored between
49+trials — the side map was not.
50+
51+Fixed by marking the accepted transform in the nosplit branch, and by adding
52+`tu_log2` to the third byte of `save_meta`/`load_meta` so the CU-depth trials
53+restore it too.
54+
55+Class swept across `ctu.rs`: every `mark_*` write inside a trial body was
56+checked against the winner path. `mark_coded` is rewritten by the parent after
57+the decision; `modes`/`depths`/`tu_log2` all ride the meta snapshot. No second
58+instance.
59+
60+## Measurement — his files
61+
62+BD-PSNR against x265 at matched features, **x265 deblocking in every row**, so
63+the two rows differ only in whether our filter runs. 24 pictures after 1500,
64+ladders auto-aligned, 0% extrapolation both sides.
65+
66+| clip | ours off | ours on | delta luma | delta YUV |
67+|---|---|---|---|---|
68+| synthetic 352x288 | +8.781 | +8.796 | +0.015 | +0.039 |
69+| film 3840x1608 | -0.197 | **+0.063** | **+0.260** | +0.244 |
70+| screen capture 2560x1440 | +0.606 | +0.693 | +0.087 | +0.104 |
71+| web clip 640x1138 | +0.567 | +0.686 | +0.119 | +0.140 |
72+| phone clip 1920x1080 | +0.113 | +0.162 | +0.049 | +0.074 |
73+
74+Every clip improves, luma and YUV, so the default is **on** (`EncoderConfig::
75+deblock: true`, `deblocking_filter_disabled = !deblock` in the PPS). The film
76+crosses from behind x265 to ahead of it.
77+
78+The absolute numbers in this table are not comparable to the ones in the gate's
79+doc comment: those were measured against an x265 with `no-deblock`, which is a
80+different anchor. `EC_H265_X265_DEBLOCK=1` selects the anchor used here.
81+
82+## Knobs
83+
84+* `EC_H265_DEBLOCK=0` — our filter off.
85+* `EC_H265_X265_DEBLOCK=1` — x265 deblocks (drops `no-deblock`), for the
86+ matched-feature anchor above.
87+
88+## Next
89+
90+SAO is the remaining in-loop tool (`sao_enabled: false`). Screen capture is
91+still the largest content gap.