forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h264rd2': deblock-aware intra 4x4 trial distortion + real-clip BD harness

Browse files at this commit

5208ad883d8dc14629843fed23535c8bf25b1dbdAhmet Kaan GümüşParent: de1d6879fc5978
crates/ec-h264/src/enc/mb.rsmodified+93 -3
@@ -15,6 +15,7 @@
15 use ec_h264_syntax::SliceType;15 use ec_h264_syntax::SliceType;
16 use wide::i16x16;16 use wide::i16x16;
17 17
18+use crate::deblock::{edge_params, filter_luma_h_edge16, filter_luma_line};
18 use crate::decoder::{19 use crate::decoder::{
19 chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, MbNeighbors,20 chroma_nz_pair, gather_nbr4, gather_nbr8, luma_nz_pair, mb_neighbors, MbNeighbors,
20 };21 };
@@ -1607,7 +1608,7 @@ fn encode_intra_mb(
1607 cost.i16_mode,1608 cost.i16_mode,
1608 chroma_mode,1609 chroma_mode,
1609 );1610 );
1610- ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f641611+ ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false) as f64 + e.lambda * bits as f64
1611 } else {1612 } else {
1612 ssd_luma(pic, e, mb_x, mb_y) as f641613 ssd_luma(pic, e, mb_x, mb_y) as f64
1613 + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f641614 + lambda_ssd(qp) * rough_intra_bits(&lv4, Some((&m4, &p4))) as f64
@@ -1639,7 +1640,7 @@ fn encode_intra_mb(
1639 cost.i16_mode,1640 cost.i16_mode,
1640 chroma_mode,1641 chroma_mode,
1641 );1642 );
1642- ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f641643+ ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, true) as f64 + e.lambda * bits as f64
1643 } else {1644 } else {
1644 f64::INFINITY1645 f64::INFINITY
1645 };1646 };
@@ -1658,7 +1659,7 @@ fn encode_intra_mb(
1658 cost.i16_mode,1659 cost.i16_mode,
1659 chroma_mode,1660 chroma_mode,
1660 );1661 );
1661- ssd_mb(pic, e, mb_x, mb_y) as f64 + e.lambda * bits as f641662+ ssd_mb_deblocked(pic, e, mb_x, mb_y, &nbr, false) as f64 + e.lambda * bits as f64
1662 } else {1663 } else {
1663 ssd_luma(pic, e, mb_x, mb_y) as f641664 ssd_luma(pic, e, mb_x, mb_y) as f64
1664 + lambda_ssd(qp) * rough_intra_bits(&lv16, None) as f641665 + 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 {
1783 sum1784 sum
1784 }1785 }
1785 1786
1787+/// [`ssd_mb`] with the luma half measured after the loop filter this
1788+/// macroblock's reconstruction will get. An intra macroblock forces bS 4 on
1789+/// its left and top macroblock edges (8.7.2.1) and bS 3 on the internal luma
1790+/// edges; a transform-8x8 macroblock has no transform edge at luma offsets 4
1791+/// and 12, so those stay unfiltered, exactly as the decoder's `internal`
1792+/// gate decides it. Neighbours share this slice's qp with the zero offsets
1793+/// the encoder writes, so every edge is parameterised by the trial qp alone.
1794+/// The right and bottom edges belong to macroblocks coded later and cannot
1795+/// be known here; the aprons are the pre-filter neighbour samples, which is
1796+/// everything that exists at decision time. The chroma half is left
1797+/// pre-filter: chroma never takes the 8x8 transform, so it cannot separate
1798+/// the candidates.
1799+///
1800+/// The 8x8-vs-4x4 intra trial is judged by this and not by [`ssd_mb`]
1801+/// because the two candidates meet different edge sets under the same loop
1802+/// filter: a pre-filter SSD prices the 4x4 candidate as if its extra
1803+/// filtered edges cost nothing.
1804+fn ssd_mb_deblocked(
1805+ pic: &Picture,
1806+ e: &MbEnc<'_>,
1807+ mb_x: usize,
1808+ mb_y: usize,
1809+ nbr: &MbNeighbors,
1810+ trans8: bool,
1811+) -> i64 {
1812+ // The macroblock at (A, A) plus 4-sample left and top aprons: a bS-4
1813+ // edge reads p3 and rewrites p2 on its far side.
1814+ const A: usize = 4;
1815+ const S: usize = A + 16;
1816+ let mut scratch = [0u8; S * S];
1817+ let stride = pic.y.stride;
1818+ let origin = pic.y.at(mb_x * 16, mb_y * 16);
1819+ for row in 0..16 {
1820+ let src = origin + row * stride;
1821+ let dst = (A + row) * S + A;
1822+ scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]);
1823+ }
1824+ if nbr.a {
1825+ for row in 0..16 {
1826+ let src = origin + row * stride - A;
1827+ let dst = (A + row) * S;
1828+ scratch[dst..dst + A].copy_from_slice(&pic.y.data[src..src + A]);
1829+ }
1830+ }
1831+ if nbr.b {
1832+ for row in 0..A {
1833+ let src = origin - (A - row) * stride;
1834+ let dst = row * S + A;
1835+ scratch[dst..dst + 16].copy_from_slice(&pic.y.data[src..src + 16]);
1836+ }
1837+ }
1838+ // Vertical edges left to right, then horizontal top to bottom, the order
1839+ // of 8.7.1: each edge filters what the earlier edges left behind.
1840+ let qp = e.target_qp;
1841+ let (e4, e3) = (edge_params(qp, 0, 0, 4), edge_params(qp, 0, 0, 3));
1842+ if nbr.a {
1843+ for row in 0..16 {
1844+ filter_luma_line(&mut scratch, (A + row) * S + A, 1, &e4);
1845+ }
1846+ }
1847+ for x in [4, 8, 12] {
1848+ if trans8 && x != 8 {
1849+ continue;
1850+ }
1851+ for row in 0..16 {
1852+ filter_luma_line(&mut scratch, (A + row) * S + A + x, 1, &e3);
1853+ }
1854+ }
1855+ if nbr.b {
1856+ filter_luma_h_edge16(&mut scratch, A * S + A, S, &e4);
1857+ }
1858+ for y in [4, 8, 12] {
1859+ if trans8 && y != 8 {
1860+ continue;
1861+ }
1862+ filter_luma_h_edge16(&mut scratch, (A + y) * S + A, S, &e3);
1863+ }
1864+ let mut sum = ssd_mb(pic, e, mb_x, mb_y) - ssd_luma(pic, e, mb_x, mb_y);
1865+ for row in 0..16 {
1866+ let src = (mb_y * 16 + row) * e.src.stride + mb_x * 16;
1867+ for x in 0..16 {
1868+ let d =
1869+ i64::from(e.src.y[src + x]) - i64::from(scratch[(A + row) * S + A + x]);
1870+ sum += d * d;
1871+ }
1872+ }
1873+ sum
1874+}
1875+
1786 /// Rough bit cost of a macroblock's luma residual.1876 /// Rough bit cost of a macroblock's luma residual.
1787 fn estimate_luma_bits(lv: &Levels) -> i64 {1877 fn estimate_luma_bits(lv: &Levels) -> i64 {
1788 let mut bits = 0;1878 let mut bits = 0;
crates/ec-h264/tests/encode.rsmodified+108 -0
@@ -699,3 +699,111 @@ fn real_library_frames_encode_and_decode_exactly() {
699 );699 );
700 assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s");700 assert!(quality > 30.0, "luma PSNR {quality:.2} dB at 8 Mbit/s");
701 }701 }
702+
703+/// BD-PSNR of the opt-in `transform_8x8` flag against flag-off on one real
704+/// clip from the library, full size, over a QP sweep: the number the synthetic
705+/// gate above cannot give, because the synthetic clip is content the flag wins
706+/// on. Prints the per-QP points, the BD-PSNR and the 8x8 macroblock share;
707+/// asserts nothing, so a regressing clip fails a gate, not the test run.
708+///
709+/// EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
710+/// real_clip_t8x8_bd_psnr -- --ignored --nocapture
711+#[test]
712+#[ignore = "set EC_H264_CLIP to a media file of yours"]
713+fn real_clip_t8x8_bd_psnr() {
714+ use ec_core::registry::{Decoder as _, Demuxer as _};
715+
716+ let Some(path) = std::env::var_os("EC_H264_CLIP") else {
717+ panic!("EC_H264_CLIP must name a media file");
718+ };
719+ // The first 30 pictures a second apart, demuxed by ec-mp4 and decoded by
720+ // this crate: every Nth frame, N the source frame rate.
721+ let file = std::fs::File::open(&path).expect("source opens");
722+ let mut demux =
723+ ec_mp4::Mp4Demuxer::new(std::io::BufReader::new(file)).expect("ec-mp4 opens the file");
724+ let (index, params) = demux
725+ .streams()
726+ .iter()
727+ .find(|s| s.params.codec == ec_core::registry::CodecId::H264)
728+ .map(|s| (s.index, s.params.clone()))
729+ .expect("an H.264 track");
730+ let video = match &params.media {
731+ ec_core::registry::MediaParameters::Video(v) => v,
732+ _ => panic!("the H.264 track carries no video parameters"),
733+ };
734+ let (w, h) = (video.width as usize, video.height as usize);
735+ let stride = video
736+ .frame_rate
737+ .map_or(25, |r| (r.as_secs_f64().round() as usize).max(1));
738+ let mut dec = ec_h264::H264Decoder::new(params).expect("decoder");
739+ let mut sources: Vec<Planes> = Vec::new();
740+ let mut seen = 0usize;
741+ while sources.len() < 30 {
742+ let Ok(packet) = demux.next_packet() else {
743+ break;
744+ };
745+ if packet.stream != index {
746+ continue;
747+ }
748+ dec.send_packet(&packet).expect("decode");
749+ while let Ok(ec_core::frame::Frame::Video(f)) = dec.receive_frame() {
750+ if sources.len() < 30 && seen % stride == 0 {
751+ sources.push(planes_of(&f));
752+ }
753+ seen += 1;
754+ }
755+ }
756+ assert!(
757+ sources.len() >= 10,
758+ "only {} pictures decoded from {}",
759+ sources.len(),
760+ path.to_string_lossy()
761+ );
762+ eprintln!(
763+ "{}: {}x{}, {} pictures 1 s apart (every {stride}th of {seen})",
764+ path.to_string_lossy(),
765+ w,
766+ h,
767+ sources.len()
768+ );
769+
770+ let run = |t8x8: bool, qp: i32| {
771+ let mut cfg = EncoderConfig::new(w as u32, h as u32);
772+ cfg.qp = qp;
773+ cfg.gop_size = 10;
774+ cfg.cabac = true;
775+ cfg.transform_8x8 = t8x8;
776+ cfg.framerate = 1.0; // the kept pictures are a second apart
777+ cfg.threads = 0;
778+ let mut enc = Encoder::new(cfg).expect("encoder");
779+ let (mut bits, mut sum_psnr) = (0usize, 0.0);
780+ for (y, u, v) in &sources {
781+ let view = PictureView::i420(w as u32, h as u32, y, u, v);
782+ bits += enc.encode(&view).expect("encode").au.len() * 8;
783+ let rec = enc.reconstruction().expect("reconstruction");
784+ sum_psnr += psnr(y, &rec.0);
785+ }
786+ let (i8x8, p8x8) = enc.transform_8x8_mbs();
787+ let share = (i8x8 + p8x8) as f64 / (sources.len() * (w / 16) * (h / 16)) as f64;
788+ (bits as f64, sum_psnr / sources.len() as f64, share)
789+ };
790+ let qps = [22, 26, 30, 34];
791+ let off: Vec<_> = qps.iter().map(|&q| run(false, q)).collect();
792+ let on: Vec<_> = qps.iter().map(|&q| run(true, q)).collect();
793+ for (i, &qp) in qps.iter().enumerate() {
794+ let (ob, op, _) = off[i];
795+ let (nb, np, share) = on[i];
796+ eprintln!(
797+ "qp {qp}: flag-off {ob:.0} bits {op:.2} dB | flag-on {nb:.0} bits {np:.2} dB, 8x8 share {:.1}%",
798+ share * 100.0
799+ );
800+ }
801+ let on_curve: Vec<_> = on.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
802+ let off_curve: Vec<_> = off.iter().map(|&(bits, psnr, _)| (bits, psnr)).collect();
803+ let bd = bd_psnr_delta(&on_curve, &off_curve);
804+ let share = on.iter().map(|&(_, _, s)| s).sum::<f64>() / on.len() as f64;
805+ eprintln!(
806+ "BD-PSNR flag-on vs flag-off over q22/26/30/34: {bd:+.3} dB, average 8x8 MB share {:.1}%",
807+ share * 100.0
808+ );
809+}
lanes/h264rd-r2.report.mdadded+95 -0
@@ -0,0 +1,95 @@
1+# h264rd r2 — deblock-aware intra trial distortion
2+
3+Lane `h264rd2`, worktree `ec-wt-h264rd2`. Goal inherited from r1: the opt-in
4+`transform_8x8` flag lost ~0.1 dB BD-PSNR on natural content (won on synthetic).
5+r1 (`3165e8c`) re-priced the 8x8 RD by exact syntax bit delta; r2 makes the
6+intra trial distortion itself deblock-aware.
7+
8+## Harness
9+
10+`real_clip_t8x8_bd_psnr` in `crates/ec-h264/tests/encode.rs` (`#[ignore]`d,
11+existing test binary). `EC_H264_CLIP` names a file; ec-mp4 + this crate's
12+decoder yield the first 30 pictures 1 s apart; a q22/26/30/34 sweep
13+(gop 10, CABAC, full size, framerate 1.0) prints per-qp points, BD-PSNR
14+flag-on vs flag-off, and the 8x8 MB share. Asserts nothing — the number
15+gates the lane, not the suite.
16+
17+ EC_H264_CLIP=<file> cargo test --release -p ec-h264 --test encode \
18+ real_clip_t8x8_bd_psnr -- --ignored --nocapture
19+
20+## Baselines (harness commit `d5b0525`, before the r2 change)
21+
22+**natural 720p film** (1280x720, 30 pictures, 8x8 share 13.5 % avg):
23+
24+| qp | off bits | off dB | on bits | on dB | 8x8 share |
25+|----|----------|--------|---------|-------|-----------|
26+| 22 | 9538320 | 50.06 | 9345832 | 50.87 | 14.6 % |
27+| 26 | 6220816 | 47.73 | 6105104 | 48.17 | 13.5 % |
28+| 30 | 3975904 | 44.14 | 3911680 | 45.21 | 14.7 % |
29+| 34 | 2474616 | 42.36 | 2442024 | 42.45 | 11.3 % |
30+
31+**BD-PSNR +0.796 dB.** The r1 loss on this class is already closed by the
32+exact-bits pricing — the r1-era -0.102 dB was measured under the old rough-bit
33+cost model. r2's job became: don't regress it, push it.
34+
35+**obs 1440p capture** (2560x1440, 19 pictures, 8x8 share 1.9 % avg):
36+q22 52.41/52.44, q26 49.01/49.00, q30 45.32/45.19, q34 41.28/41.43 dB —
37+**BD-PSNR -0.007 dB.**
38+
39+## Change (`da6a6bb`)
40+
41+`ssd_mb_deblocked` in `crates/ec-h264/src/enc/mb.rs`, swapped into the three
42+`t8x8_intra` trial costs (cost4/cost8/cost16) of `encode_intra_mb`:
43+
44+- Copy the candidate's 16x16 luma recon plus 4-px left/top aprons (gated on
45+ `nbr.a`/`nbr.b`, the same availability intra prediction uses) into a 24x24
46+ scratch; the apron feeds the bS-4 p3 read / p2 rewrite.
47+- Filter exactly as `deblock_picture` will: bS 4 on the MB edges, bS 3 on
48+ internal edges, verticals left-to-right then horizontals, `edge_params(qp, 0, 0, bs)`;
49+ the 8x8 candidate skips luma edges 4/12 — the decoder's `internal()` gate —
50+ so each candidate meets its own true edge set.
51+- Luma SSD on the filtered scratch vs source, composited with `ssd_mb -
52+ ssd_luma` for the untouched chroma half (chroma never takes the 8x8
53+ transform; it cannot separate the candidates).
54+- Flag-off path untouched: default output stays byte-identical (structural;
55+ only the three `e.t8x8_intra(mb_y)` branches changed).
56+
57+## After (feature commit `da6a6bb`)
58+
59+**natural 720p film** (8x8 share 13.5 % avg):
60+
61+| qp | off bits | off dB | on bits | on dB | 8x8 share |
62+|----|----------|--------|---------|-------|-----------|
63+| 22 | 9538320 | 50.06 | 9349104 | 50.87 | 14.7 % |
64+| 26 | 6220816 | 47.73 | 6098024 | 48.18 | 13.3 % |
65+| 30 | 3975904 | 44.14 | 3888736 | 45.25 | 14.7 % |
66+| 34 | 2474616 | 42.36 | 2426344 | 42.35 | 11.4 % |
67+
68+**BD-PSNR +0.827 dB** (was +0.796; +0.031).
69+
70+**obs 1440p capture** (8x8 share 1.8 % avg):
71+q22 52.41/52.44, q26 49.01/49.02, q30 45.32/45.20, q34 41.28/41.46 dB —
72+**BD-PSNR -0.000 dB** (was -0.007; +0.007).
73+
74+Mechanism visible in the points: same or better PSNR at fewer bits where 8x8
75+competes (720p q30: 45.21 dB @ 3912 kb → 45.25 dB @ 3889 kb); the share is
76+stable, so the gain is truer candidate pricing, not mode flipping.
77+
78+## Variants measured / rejected
79+
80+- None needed: the primary design passed both clip gates on the first
81+ measurement. Deliberate scope cuts (chroma half pre-filter; aprons
82+ pre-filter; no right/bottom edges — those belong to MBs coded later;
83+ neighbours at slice qp rather than tracked per-MB) stayed as designed.
84+
85+## Gates
86+
87+1. `cargo test --release -p ec-h264` — **75+23+9+1 passed, 0 failed**
88+ (includes the synthetic gate `eight_by_eight_gains_on_flat_and_text`
89+ pinning BD ≥ 0.255347 - 0.02 dB and the byte-identity determinism tests).
90+2. Harness both clips: 720p +0.827 ≥ -0.02; obs -0.000, not below its
91+ -0.007 baseline — **pass**.
92+3. `cargo test --release -p ec-h264 --test conformance` — **23 passed,
93+ 0 failed**.
94+
95+Out of scope by charter: the inter trial (`encode_inter_mb` cost4/cost8).