diff --git a/crates/ec-h264/src/enc/mb.rs b/crates/ec-h264/src/enc/mb.rs index b5162d1d..0f8c6918 100644 --- a/crates/ec-h264/src/enc/mb.rs +++ b/crates/ec-h264/src/enc/mb.rs @@ -15,6 +15,7 @@ use ec_h264_syntax::SliceType; use wide::i16x16; +use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line}; use crate::decoder::{ chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, MbNeighbors, }; @@ -1607,7 +1608,7 @@ fn encode_intra_mb( cost.i16_mode, chroma_mode, ); - ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 + ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false) 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 @@ -1639,7 +1640,7 @@ fn encode_intra_mb( cost.i16_mode, chroma_mode, ); - ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 + ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, true) as f64 + e.lambda * bits as f64 } else { f64::INFINITY }; @@ -1658,7 +1659,7 @@ fn encode_intra_mb( cost.i16_mode, chroma_mode, ); - ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f64 + ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false) 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 @@ -1783,6 +1784,95 @@ fn ssd_mb(pic: &Picture, e: &MbEnc<'_>, mb_x: usize, mb_y: usize) -> i64 { sum } +/// [`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. +/// +/// 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. +fn ssd_mb_deblocked( + pic: &Picture, + e: &MbEnc<'_>, + mb_x: usize, + mb_y: usize, + nbr: &MbNeighbors, + trans8: bool, +) -> 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. + const A: usize = 4; + const S: usize = A + 16; + let mut scratch = [0u8; S * S]; + let stride = pic.y.stride; + let origin = pic.y.at(mb_x * 16, mb_y * 16); + for row in 0..16 { + let src = origin + row * stride; + let dst = (A + row) * S + A; + scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]); + } + if nbr.a { + for row in 0..16 { + let src = origin + row * stride - A; + let dst = (A + row) * S; + scratch[dst..dst + A].copy_from_slice(&pic.y.data[src..src + A]); + } + } + if nbr.b { + for row in 0..A { + let src = origin - (A - row) * stride; + let dst = row * S + A; + scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]); + } + } + // 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. + 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 { + continue; + } + for row in 0..16 { + filter_luma_line(&mut scratch, (A + row) * S + A + x, 1, &e3); + } + } + if nbr.b { + filter_luma_h_edge16(&mut scratch, A * S + A, S, &e4); + } + for y in [4, 8, 12] { + if trans8 && y != 8 { + continue; + } + filter_luma_h_edge16(&mut scratch, (A + y) * S + A, S, &e3); + } + let mut sum = ssd_mb(pic, e, mb_x, mb_y) - ssd_luma(pic, e, mb_x, mb_y); + for row in 0..16 { + let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16; + for x in 0..16 { + let d = + i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]); + sum += d * d; + } + } + sum +} + /// Rough bit cost of a macroblock's luma residual. fn estimate_luma_bits(lv: &Levels) -> i64 { let mut bits = 0; diff --git a/crates/ec-h264/tests/encode.rs b/crates/ec-h264/tests/encode.rs index 50be5e2e..ea3fb4e8 100644 --- a/crates/ec-h264/tests/encode.rs +++ b/crates/ec-h264/tests/encode.rs @@ -699,3 +699,111 @@ fn real_library_frames_encode_and_decode_exactly() { ); assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s"); } + +/// BD-PSNR of the opt-in `transform_8x8` flag against flag-off on one real +/// clip from the library, full size, over a QP sweep: the number the synthetic +/// gate above cannot give, because the synthetic clip is content the flag wins +/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share; +/// asserts nothing, so a regressing clip fails a gate, not the test run. +/// +/// EC_H264_CLIP= cargo test --release -p ec-h264 --test encode \ +/// real_clip_t8x8_bd_psnr -- --ignored --nocapture +#[test] +#[ignore = "set EC_H264_CLIP to a media file of yours"] +fn real_clip_t8x8_bd_psnr() { + use ec_core::registry::{Decoder as _, Demuxer as _}; + + let Some(path) = std::env::var_os("EC_H264_CLIP") else { + panic!("EC_H264_CLIP must name a media file"); + }; + // The first 30 pictures a second apart, demuxed by ec-mp4 and decoded by + // this crate: every Nth frame, N the source frame rate. + let file = std::fs::File::open(&path).expect("source opens"); + let mut demux = + ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 opens the file"); + let (index, params) = demux + .streams() + .iter() + .find(|s| s.params.codec == ec_core::registry::CodecId::H264) + .map(|s| (s.index, s.params.clone())) + .expect("an H.264 track"); + let video = match ¶ms.media { + ec_core::registry::MediaParameters::Video(v) => v, + _ => panic!("the H.264 track carries no video parameters"), + }; + let (w, h) = (video.width as usize, video.height as usize); + let stride = video + .frame_rate + .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1)); + let mut dec = ec_h264::H264Decoder::new(params).expect("decoder"); + let mut sources: Vec = Vec::new(); + let mut seen = 0usize; + while sources.len() < 30 { + let Ok(packet) = demux.next_packet() else { + break; + }; + if packet.stream != index { + continue; + } + dec.send_packet(&packet).expect("decode"); + while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() { + if sources.len() < 30 && seen % stride == 0 { + sources.push(planes_of(&f)); + } + seen += 1; + } + } + assert!( + sources.len() >= 10, + "only {} pictures decoded from {}", + sources.len(), + path.to_string_lossy() + ); + eprintln!( + "{}: {}x{}, {} pictures 1 s apart (every {stride}th of {seen})", + path.to_string_lossy(), + w, + h, + sources.len() + ); + + let run = |t8x8: bool, qp: i32| { + let mut cfg = EncoderConfig::new(w as u32, h as u32); + cfg.qp = qp; + cfg.gop_size = 10; + cfg.cabac = true; + cfg.transform_8x8 = t8x8; + cfg.framerate = 1.0; // the kept pictures are a second apart + cfg.threads = 0; + let mut enc = Encoder::new(cfg).expect("encoder"); + let (mut bits, mut sum_psnr) = (0usize, 0.0); + for (y, u, v) in &sources { + let view = PictureView::i420(w as u32, h as u32, y, u, v); + bits += enc.encode(&view).expect("encode").au.len() * 8; + let rec = enc.reconstruction().expect("reconstruction"); + sum_psnr += psnr(y, &rec.0); + } + let (i8x8, p8x8) = enc.transform_8x8_mbs(); + let share = (i8x8 + p8x8) as f64 / (sources.len() * (w / 16) * (h / 16)) as f64; + (bits as f64, sum_psnr / sources.len() as f64, share) + }; + let qps = [22, 26, 30, 34]; + let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect(); + let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect(); + for (i, &qp) in qps.iter().enumerate() { + let (ob, op, _) = off[i]; + let (nb, np, share) = on[i]; + eprintln!( + "qp {qp}: flag-off {ob:.0} bits {op:.2} dB | flag-on {nb:.0} bits {np:.2} dB, 8x8 share {:.1}%", + share * 100.0 + ); + } + let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); + let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect(); + let bd = bd_psnr_delta(&on_curve, &off_curve); + let share = on.iter().map(|&(_, _, s)| s).sum::() / on.len() as f64; + eprintln!( + "BD-PSNR flag-on vs flag-off over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%", + share * 100.0 + ); +} diff --git a/lanes/h264rd-r2.report.md b/lanes/h264rd-r2.report.md new file mode 100644 index 00000000..fa3d5416 --- /dev/null +++ b/lanes/h264rd-r2.report.md @@ -0,0 +1,95 @@ +# h264rd r2 — deblock-aware intra trial distortion + +Lane `h264rd2`, worktree `ec-wt-h264rd2`. Goal inherited from r1: the opt-in +`transform_8x8` flag lost ~0.1 dB BD-PSNR on natural content (won on synthetic). +r1 (`3165e8c`) re-priced the 8x8 RD by exact syntax bit delta; r2 makes the +intra trial distortion itself deblock-aware. + +## Harness + +`real_clip_t8x8_bd_psnr` in `crates/ec-h264/tests/encode.rs` (`#[ignore]`d, +existing test binary). `EC_H264_CLIP` names a file; ec-mp4 + this crate's +decoder yield the first 30 pictures 1 s apart; a q22/26/30/34 sweep +(gop 10, CABAC, full size, framerate 1.0) prints per-qp points, BD-PSNR +flag-on vs flag-off, and the 8x8 MB share. Asserts nothing — the number +gates the lane, not the suite. + + EC_H264_CLIP= cargo test --release -p ec-h264 --test encode \ + real_clip_t8x8_bd_psnr -- --ignored --nocapture + +## Baselines (harness commit `d5b0525`, before the r2 change) + +**natural 720p film** (1280x720, 30 pictures, 8x8 share 13.5 % avg): + +| qp | off bits | off dB | on bits | on dB | 8x8 share | +|----|----------|--------|---------|-------|-----------| +| 22 | 9538320 | 50.06 | 9345832 | 50.87 | 14.6 % | +| 26 | 6220816 | 47.73 | 6105104 | 48.17 | 13.5 % | +| 30 | 3975904 | 44.14 | 3911680 | 45.21 | 14.7 % | +| 34 | 2474616 | 42.36 | 2442024 | 42.45 | 11.3 % | + +**BD-PSNR +0.796 dB.** The r1 loss on this class is already closed by the +exact-bits pricing — the r1-era -0.102 dB was measured under the old rough-bit +cost model. r2's job became: don't regress it, push it. + +**obs 1440p capture** (2560x1440, 19 pictures, 8x8 share 1.9 % avg): +q22 52.41/52.44, q26 49.01/49.00, q30 45.32/45.19, q34 41.28/41.43 dB — +**BD-PSNR -0.007 dB.** + +## Change (`da6a6bb`) + +`ssd_mb_deblocked` in `crates/ec-h264/src/enc/mb.rs`, swapped into the three +`t8x8_intra` trial costs (cost4/cost8/cost16) of `encode_intra_mb`: + +- Copy the candidate's 16x16 luma recon plus 4-px left/top aprons (gated on + `nbr.a`/`nbr.b`, the same availability intra prediction uses) into a 24x24 + scratch; the apron feeds the bS-4 p3 read / p2 rewrite. +- Filter exactly as `deblock_picture` will: bS 4 on the MB edges, bS 3 on + internal edges, verticals left-to-right then horizontals, `edge_params(qp, 0, 0, bs)`; + the 8x8 candidate skips luma edges 4/12 — the decoder's `internal()` gate — + so each candidate meets its own true edge set. +- Luma SSD on the filtered scratch vs source, composited with `ssd_mb - + ssd_luma` for the untouched chroma half (chroma never takes the 8x8 + transform; it cannot separate the candidates). +- Flag-off path untouched: default output stays byte-identical (structural; + only the three `e.t8x8_intra(mb_y)` branches changed). + +## After (feature commit `da6a6bb`) + +**natural 720p film** (8x8 share 13.5 % avg): + +| qp | off bits | off dB | on bits | on dB | 8x8 share | +|----|----------|--------|---------|-------|-----------| +| 22 | 9538320 | 50.06 | 9349104 | 50.87 | 14.7 % | +| 26 | 6220816 | 47.73 | 6098024 | 48.18 | 13.3 % | +| 30 | 3975904 | 44.14 | 3888736 | 45.25 | 14.7 % | +| 34 | 2474616 | 42.36 | 2426344 | 42.35 | 11.4 % | + +**BD-PSNR +0.827 dB** (was +0.796; +0.031). + +**obs 1440p capture** (8x8 share 1.8 % avg): +q22 52.41/52.44, q26 49.01/49.02, q30 45.32/45.20, q34 41.28/41.46 dB — +**BD-PSNR -0.000 dB** (was -0.007; +0.007). + +Mechanism visible in the points: same or better PSNR at fewer bits where 8x8 +competes (720p q30: 45.21 dB @ 3912 kb → 45.25 dB @ 3889 kb); the share is +stable, so the gain is truer candidate pricing, not mode flipping. + +## Variants measured / rejected + +- None needed: the primary design passed both clip gates on the first + measurement. Deliberate scope cuts (chroma half pre-filter; aprons + pre-filter; no right/bottom edges — those belong to MBs coded later; + neighbours at slice qp rather than tracked per-MB) stayed as designed. + +## Gates + +1. `cargo test --release -p ec-h264` — **75+23+9+1 passed, 0 failed** + (includes the synthetic gate `eight_by_eight_gains_on_flat_and_text` + pinning BD ≥ 0.255347 - 0.02 dB and the byte-identity determinism tests). +2. Harness both clips: 720p +0.827 ≥ -0.02; obs -0.000, not below its + -0.007 baseline — **pass**. +3. `cargo test --release -p ec-h264 --test conformance` — **23 passed, + 0 failed**. + +Out of scope by charter: the inter trial (`encode_inter_mb` cost4/cost8).