diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 12bf028f..2aaa66e8 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -2624,61 +2624,36 @@ fn uniform_motion(pic: &Picture, mb_x: usize, mb_y: usize) -> bool { }) } -/// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1). -/// -/// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the -/// macroblock, `seg` the 4-sample run along it. Edge 0 is the macroblock edge. -fn boundary_strength( - pic: &Picture, - mb_x: usize, - mb_y: usize, - edge: usize, - seg: usize, - vertical: bool, -) -> u8 { - let w4 = pic.mb_w * 4; - let (qbx, qby) = if vertical { - (mb_x * 4 + edge, mb_y * 4 + seg) - } else { - (mb_x * 4 + seg, mb_y * 4 + edge) - }; - let (pbx, pby) = if vertical { - (qbx - 1, qby) - } else { - (qbx, qby - 1) - }; - let q = qby * w4 + qbx; - let p = pby * w4 + pbx; - let mb_edge = edge == 0; - let q_mb = (qby / 4) * pic.mb_w + qbx / 4; - let p_mb = (pby / 4) * pic.mb_w + pbx / 4; - let intra = pic.mb_flags[q_mb] & FLAG_INTER == 0 || pic.mb_flags[p_mb] & FLAG_INTER == 0; - if intra { +/// What clause 8.7.2.1 needs from the 4x4 block on one side of a luma edge. +#[derive(Clone, Copy)] +pub(crate) struct BsSide { + /// The containing macroblock is intra: strength 4 on macroblock edges and + /// 3 on internal ones, regardless of motion or levels. + pub(crate) intra: bool, + /// The transform block containing this sample has non-zero levels. + pub(crate) coded: bool, + /// MvLX of the block, `[list][component]`. + pub(crate) mv: [[i16; 2]; 2], + /// RefIdxLX of the block as list identities (`Picture::id`), -1 unused. + pub(crate) refs: [i32; 2], +} + +/// Boundary strength between the 4x4 blocks on the two sides of a luma edge +/// (clause 8.7.2.1). `mb_edge` selects the macroblock-edge strengths 4/3. +pub(crate) fn bs_between(p: &BsSide, q: &BsSide, mb_edge: bool) -> u8 { + if p.intra || q.intra { return if mb_edge { 4 } else { 3 }; } - // "the transform block containing the sample has non-zero levels": for an - // 8x8-transform macroblock that is the whole 8x8, whose four 4x4 slots - // carry per-slot counts under CAVLC (7.3.5.3.1 splits it into four blocks). - let coded = |mb: usize, bx: usize, by: usize| -> bool { - if pic.mb_flags[mb] & FLAG_TRANS8X8 == 0 { - return pic.nz_y[by * w4 + bx] != 0; - } - let (ox, oy) = (bx & !1, by & !1); - pic.nz_y[oy * w4 + ox] != 0 - || pic.nz_y[oy * w4 + ox + 1] != 0 - || pic.nz_y[(oy + 1) * w4 + ox] != 0 - || pic.nz_y[(oy + 1) * w4 + ox + 1] != 0 - }; - if coded(p_mb, pbx, pby) || coded(q_mb, qbx, qby) { + if p.coded || q.coded { return 2; } - let (pr, qr) = (pic.ref_id[p], pic.ref_id[q]); + let (pr, qr) = (p.refs, q.refs); let pn = u8::from(pr[0] >= 0) + u8::from(pr[1] >= 0); let qn = u8::from(qr[0] >= 0) + u8::from(qr[1] >= 0); if pn != qn { return 1; } - let (pm, qm) = (pic.mv[p], pic.mv[q]); + let (pm, qm) = (p.mv, q.mv); let differs = |a: [i16; 2], b: [i16; 2]| { (i32::from(a[0]) - i32::from(b[0])).abs() >= 4 || (i32::from(a[1]) - i32::from(b[1])).abs() >= 4 @@ -2712,3 +2687,53 @@ fn boundary_strength( let crossed = !differs(pm[0], qm[1]) && !differs(pm[1], qm[0]); u8::from(!(straight || crossed)) } + +/// One side of a luma edge from picture state: the decoder path, both sides +/// final macroblocks. The encoder's inter trial uses this for the +/// already-coded neighbour and builds its candidate side itself. +pub(crate) fn bs_side(pic: &Picture, bx: usize, by: usize) -> BsSide { + let w4 = pic.mb_w * 4; + let mb = (by / 4) * pic.mb_w + bx / 4; + BsSide { + intra: pic.mb_flags[mb] & FLAG_INTER == 0, + coded: bs_coded(pic, mb, bx, by), + mv: pic.mv[by * w4 + bx], + refs: pic.ref_id[by * w4 + bx], + } +} + +/// "The transform block containing the sample has non-zero levels": for an +/// 8x8-transform macroblock that is the whole 8x8, whose four 4x4 slots +/// carry per-slot counts under CAVLC (7.3.5.3.1 splits it into four blocks). +fn bs_coded(pic: &Picture, mb: usize, bx: usize, by: usize) -> bool { + let w4 = pic.mb_w * 4; + if pic.mb_flags[mb] & FLAG_TRANS8X8 == 0 { + return pic.nz_y[by * w4 + bx] != 0; + } + let (ox, oy) = (bx & !1, by & !1); + pic.nz_y[oy * w4 + ox] != 0 + || pic.nz_y[oy * w4 + ox + 1] != 0 + || pic.nz_y[(oy + 1) * w4 + ox] != 0 + || pic.nz_y[(oy + 1) * w4 + ox + 1] != 0 +} + +/// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1). +/// +/// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the +/// macroblock, `seg` the 4-sample run along it. Edge 0 is the macroblock edge. +fn boundary_strength( + pic: &Picture, + mb_x: usize, + mb_y: usize, + edge: usize, + seg: usize, + vertical: bool, +) -> u8 { + let (qbx, qby) = if vertical { + (mb_x * 4 + edge, mb_y * 4 + seg) + } else { + (mb_x * 4 + seg, mb_y * 4 + edge) + }; + let (pbx, pby) = if vertical { (qbx - 1, qby) } else { (qbx, qby - 1) }; + bs_between(&bs_side(pic, pbx, pby), &bs_side(pic, qbx, qby), edge == 0) +} diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index 0f8c6918..724168be 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -1608,7 +1608,8 @@ fn encode_intra_mb( cost.i16_mode, chroma_mode, ); - ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false) as f64 + e.lambda * bits as f64 + ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64 + + e.lambda * bits as f64 } else { ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64 @@ -1640,7 +1641,8 @@ fn encode_intra_mb( cost.i16_mode, chroma_mode, ); - ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, true) as f64 + e.lambda * bits as f64 + ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, true, intra_bs) as f64 + + e.lambda * bits as f64 } else { f64::INFINITY }; @@ -1659,7 +1661,8 @@ fn encode_intra_mb( cost.i16_mode, chroma_mode, ); - ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false) as f64 + e.lambda * bits as f64 + ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false, intra_bs) as f64 + + e.lambda * bits as f64 } else { ssd_luma(pic, e, mb_x, mb_y) as f64 + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f64 @@ -1785,22 +1788,24 @@ fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { } /// [`ssd_mb`] with the luma half measured after the loop filter this -/// macroblock's reconstruction will get. An intra macroblock forces bS 4 on -/// its left and top macroblock edges (8.7.2.1) and bS 3 on the internal luma -/// edges; a transform-8x8 macroblock has no transform edge at luma offsets 4 -/// and 12, so those stay unfiltered, exactly as the decoder's `internal` -/// gate decides it. Neighbours share this slice's qp with the zero offsets -/// the encoder writes, so every edge is parameterised by the trial qp alone. -/// The right and bottom edges belong to macroblocks coded later and cannot -/// be known here; the aprons are the pre-filter neighbour samples, which is -/// everything that exists at decision time. The chroma half is left -/// pre-filter: chroma never takes the 8x8 transform, so it cannot separate -/// the candidates. +/// macroblock's reconstruction will get. `bs(edge, seg, vertical)` is the +/// boundary strength of one 4-sample edge segment — edge 0 the macroblock +/// edge, edges 1..3 the internal edges at offsets 4/8/12 — as the decoder +/// will derive it, so an intra candidate passes its forced 4/3 and an inter +/// candidate its own coded/motion strengths. A transform-8x8 macroblock has +/// no transform edge at luma offsets 4 and 12, so those stay unfiltered, +/// exactly as the decoder's `internal` gate decides it. Neighbours share +/// this slice's qp with the zero offsets the encoder writes, so every edge +/// is parameterised by the trial qp alone. The right and bottom edges +/// belong to macroblocks coded later and cannot be known here; the aprons +/// are the pre-filter neighbour samples, which is everything that exists at +/// decision time. The chroma half is left pre-filter: chroma never takes +/// the 8x8 transform, so it cannot separate the candidates. /// -/// The 8x8-vs-4x4 intra trial is judged by this and not by [`ssd_mb`] -/// because the two candidates meet different edge sets under the same loop -/// filter: a pre-filter SSD prices the 4x4 candidate as if its extra -/// filtered edges cost nothing. +/// The 8x8-vs-4x4 trials are judged by this and not by [`ssd_mb`] because the +/// two candidates meet different edge sets under the same loop filter: a +/// pre-filter SSD prices the 4x4 candidate as if its extra filtered edges +/// cost nothing. fn ssd_mb_deblocked( pic: &Picture, e: &MbEnc<'_>, @@ -1808,6 +1813,7 @@ fn ssd_mb_deblocked( mb_y: usize, nbr: &MbNeighbors, trans8: bool, + bs: impl Fn(usize, usize, bool) -> u8, ) -> i64 { // The macroblock at (A, A) plus 4-sample left and top aprons: a bS-4 // edge reads p3 and rewrites p2 on its far side. @@ -1836,30 +1842,52 @@ fn ssd_mb_deblocked( } } // Vertical edges left to right, then horizontal top to bottom, the order - // of 8.7.1: each edge filters what the earlier edges left behind. + // of 8.7.1: each edge filters what the earlier edges left behind. Each + // 4-sample segment carries its own strength, as in the decoder. let qp = e.target_qp; - let (e4, e3) = (edge_params(qp, 0, 0, 4), edge_params(qp, 0, 0, 3)); - if nbr.a { - for row in 0..16 { - filter_luma_line(&mut scratch, (A + row) * S + A, 1, &e4); - } - } - for x in [4, 8, 12] { - if trans8 && x != 8 { + for edge in 0..4 { + let x = edge * 4; + if (edge == 0 && !nbr.a) || (trans8 && x != 0 && x != 8) { continue; } - for row in 0..16 { - filter_luma_line(&mut scratch, (A + row) * S + A + x, 1, &e3); + for seg in 0..4 { + let s = bs(edge, seg, true); + if s == 0 { + continue; + } + let ep = edge_params(qp, 0, 0, s); + for row in seg * 4..seg * 4 + 4 { + filter_luma_line(&mut scratch, (A + row) * S + A + x, 1, &ep); + } } } - if nbr.b { - filter_luma_h_edge16(&mut scratch, A * S + A, S, &e4); - } - for y in [4, 8, 12] { - if trans8 && y != 8 { + for edge in 0..4 { + let y = edge * 4; + if (edge == 0 && !nbr.b) || (trans8 && y != 0 && y != 8) { + continue; + } + let seg_bs = [ + bs(edge, 0, false), + bs(edge, 1, false), + bs(edge, 2, false), + bs(edge, 3, false), + ]; + if seg_bs[0] == seg_bs[1] && seg_bs[1] == seg_bs[2] && seg_bs[2] == seg_bs[3] { + if seg_bs[0] != 0 { + let ep = edge_params(qp, 0, 0, seg_bs[0]); + filter_luma_h_edge16(&mut scratch, (A + y) * S + A, S, &ep); + } continue; } - filter_luma_h_edge16(&mut scratch, (A + y) * S + A, S, &e3); + for seg in 0..4 { + if seg_bs[seg] == 0 { + continue; + } + let ep = edge_params(qp, 0, 0, seg_bs[seg]); + for col in seg * 4..seg * 4 + 4 { + filter_luma_line(&mut scratch, (A + y) * S + A + col, S, &ep); + } + } } let mut sum = ssd_mb(pic, e, mb_x, mb_y) - ssd_luma(pic, e, mb_x, mb_y); for row in 0..16 { @@ -1873,6 +1901,16 @@ fn ssd_mb_deblocked( sum } +/// Boundary strengths an intra candidate forces (8.7.2.1): 4 on its +/// macroblock edges, 3 on the internal luma edges. +fn intra_bs(edge: usize, _seg: usize, _vertical: bool) -> u8 { + if edge == 0 { + 4 + } else { + 3 + } +} + /// Rough bit cost of a macroblock's luma residual. fn estimate_luma_bits(lv: &Levels) -> i64 { let mut bits = 0; diff --git a/lanes/h264rd-r3.report.md b/lanes/h264rd-r3.report.md new file mode 100644 index 00000000..6d1e81be --- /dev/null +++ b/lanes/h264rd-r3.report.md @@ -0,0 +1,91 @@ +# h264rd r3 — deblock-aware inter trial distortion: rejected + +Lane `h264rd3`, worktree `ec-wt-h264rd3`. Charter: mirror r2's intra change +on the inter trial — price `encode_inter_mb`'s cost4/cost8 pair with a +deblocked SSD whose per-edge boundary strength is derived per 8.7.2.1 +(coded → 2, mv/ref difference → 1, intra MB → 4/3), reusing the decoder's +own bS derivation rather than a second rule. + +**Verdict: every variant regressed the 720p clip; the encoder change is +reverted.** What ships is the behaviour-preserving extraction of the bS +derivation in `decoder.rs` (`BsSide`/`bs_side`/`bs_between`, `boundary_strength` +now composed from them) and the intra trial's `ssd_mb_deblocked` parametrised +by a `bs` closure (`intra_bs`) — output byte-identical to r2, confirmed by the +suite's byte-identity determinism tests and by the harness reproducing r2's +numbers exactly. + +## Variants measured (720p film / obs 1440p BD-PSNR, flag-on vs flag-off) + +Baseline = r2 (`da6a6bb`): **+0.827 dB** / **-0.000 dB**. Tolerance: no clip +below its baseline by > 0.005 dB; rise on 720p. + +| variant | 720p BD | Δ vs r2 | obs BD | verdict | +|---------|---------|---------|--------|---------| +| r2 baseline | +0.827 | — | -0.000 | — | +| V1 derived bS on cost4/cost8 | +0.818 | -0.009 | +0.001 | fail | +| V2 = V1 + deblocked skip re-check | +0.794 | -0.033 | +0.000 | fail | +| V3 = V1, weak edge-0 bS dropped | +0.821 | -0.006 | +0.000 | fail | +| reverted (shipped) | +0.827 | 0 | -0.000 | pass (=r2) | + +**V1 per-qp, 720p flag-on** (off rows identical to r2's, elided): +q22 9347720 bits 50.86 dB, q26 6095880 48.16, q30 3893464 45.24, +q34 2428872 42.36; 8x8 share 14.7/13.3/14.6/11.3 %. +**V2**: 9345712/50.86, 6087104/48.07, 3892752/45.24, 2429568/42.39. +**V3**: 9348064/50.86, 6097064/48.16, 3894768/45.24, 2428080/42.40. +obs per-qp rows moved by ≤ 0.01 dB in every variant; its BD stayed +within ±0.001 of flat the whole time. + +The four points are monotone: the more inter-edge filtering the trial +metric applies, the worse 720p gets. The deblocked-metric gain r2 found on +intra candidates does not transfer to inter candidates on this content. + +## Mechanism (what was built, why it loses) + +`inter_trial_bs(pic, mb_addr, mb_x, mb_y, lv)` answered `bs(edge, seg, +vertical)` with the decoder's own rule: the q side is always the candidate — +`BsSide { intra: false, coded: , mv/ref from pic (write_block already ran) }` — the p side is the +candidate again on internal edges, `bs_side(pic, …)` on macroblock edges. +`ssd_mb_deblocked` filtered its 24x24 scratch per (edge, seg) at that +strength. + +Why it loses: the trial's aprons are the neighbours' **pre-filter** samples — +the one state the encoder cannot know at decision time (the decoder filters +after the whole frame is coded, cascaded). For intra candidates (r2) the +forced bS 4/3 filtering dominates that staleness. For inter candidates the +derived strengths are mostly 1/2 — weak filters whose benefit is the same +order as the apron error — so pricing them adds model noise, not signal. +The variant ladder confirms the split: V3 (which dropped exactly the weak +macroblock-edge strengths against stale aprons, keeping the self-consistent +internal edges) recovered 0.003 of V1's 0.009 loss, and V2 (more deblocking +of the skip re-check, same stale aprons) lost a further 0.024. The +remaining -0.006 in V3 is the honest price of the internal bS-2 modelling: +on this film content even the self-consistent part does not pay for the inter +trial. + +## What ships + +- `crates/ec-h264/src/decoder.rs`: `bs_side`/`bs_between` extracted from + `boundary_strength` (the 8.7.2.1 rule in one place, `pub(crate)` so the + encoder can reach it); `boundary_strength` is now coords → + `bs_between(&bs_side(p), &bs_side(q), mb_edge)`. No behaviour change. +- `crates/ec-h264/src/enc/mb.rs`: `ssd_mb_deblocked` takes a + `bs(edge, seg, vertical)` closure instead of hard-coded 4/3; the three + intra trial costs pass `intra_bs` (edge 0 → 4, else 3 — the same values). + Per-segment strengths are now plumbed (uniform-segment fast path kept). + Inter cost4/cost8 and the skip re-check stay pre-filter, exactly r2. + +## Gates (reverted state) + +1. `cargo test --release -p ec-h264` — **75+23+9+1 passed, 0 failed** + (byte-identity determinism tests confirm flag-off/flag-on output matches + r2 bit-for-bit). +2. Harness both clips: 720p **+0.827 dB**, obs **-0.000 dB** — identical to + the r2 baselines (pass, no regression, no gain). +3. `cargo test --release -p ec-h264 --test conformance` — **23 passed, + 0 failed**. + +Scope cuts (moot after the revert, but measured as V2): the skip re-check was +chartered as the fallback variant and made things worse, so it stays +pre-filter permanently on this evidence. Chroma half and right/bottom edges +remain r2's scope cuts.