diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 31d62b41..7a3f576d 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -69,6 +69,14 @@ pub(crate) struct FrameCtx { pub(crate) capture_stages: std::cell::Cell, pub(crate) stages: std::cell::RefCell>, pub(crate) sb128_flag: std::cell::Cell, + /// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every + /// motion compensation of THIS frame runs, already resolved to a kernel. + /// `mc::predict` used to hardwire `Regular`, so the encoder's search, + /// trial and recon could only ever build a REGULAR prediction whatever + /// the frame header said; it lives here (and is copied by + /// [`filter_ctx_copy`]) so a tile-search worker thread reads the same + /// kernel the frame header wrote instead of the default. + pub(crate) interp_filter: std::cell::Cell, /// lane-lossless: this frame's `CodedLossless` (spec 5.9.12) -- every /// segment at `qindex == 0` with zero plane deltas. It forces TX_4X4 with /// the Walsh-Hadamard transform on every plane, drops the `tx_type` @@ -163,6 +171,7 @@ impl FrameCtx { // (`set_sb128`, stream.rs). The encoder's own contexts start at // the size this process encodes -- see [`FrameCtx::for_encoder`]. sb128_flag: std::cell::Cell::new(false), + interp_filter: std::cell::Cell::new(crate::mc::InterpFilterKind::Regular), lossless_flag: std::cell::Cell::new(false), cdef_bits: std::cell::Cell::new(0), bit_depth: std::cell::Cell::new(8), @@ -260,6 +269,7 @@ impl WithRef for T {} pub(crate) fn filter_ctx_copy(fctx: &FrameCtx) -> FrameCtx { let out = FrameCtx::new(); out.bit_depth.set(fctx.bit_depth.get()); + out.interp_filter.set(fctx.interp_filter.get()); out.grain_bit_depth.set(fctx.grain_bit_depth.get()); out.superres.set(fctx.superres.get()); out.seg_mi_dims.set(fctx.seg_mi_dims.get()); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 1f7912e1..73e67b89 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1967,6 +1967,49 @@ pub(crate) fn key_frame_headers_colour( /// 1 still holds the key frame however long the GOP runs. pub const GOLDEN_SLOT: u8 = 1; +/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter +/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the +/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR -- +/// one filter for the whole frame, which is what libaom does on this content +/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own +/// stream, so a per-BLOCK filter search has no bits to win). The kernel +/// reaches the search, the trials and the recon through +/// `FrameCtx::interp_filter`, so the stream a decoder reads and the +/// prediction the search priced are the same one. +/// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the +/// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has: +/// the witness that has to see a non-REGULAR kernel coded and decoded turns +/// it on through this while holding [`crate::speed::knob_write`]. +static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(u8::MAX); + +/// Sets [`INTERP_OVERRIDE`]; `None` clears it. +#[allow(dead_code)] // set only from the `#[cfg(test)]` gates +pub(crate) fn set_frame_interp(filter: Option) { + INTERP_OVERRIDE.store( + filter.map_or(u8::MAX, |f| f as u8), + std::sync::atomic::Ordering::Relaxed, + ); +} + +fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter { + use ec_av1_syntax::InterpolationFilter as F; + match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + 0 => return F::Eighttap, + 1 => return F::EighttapSmooth, + 2 => return F::EighttapSharp, + _ => {} + } + static ENV: std::sync::LazyLock> = std::sync::LazyLock::new(|| { + crate::envflags::var("EC_AV1_INTERP").ok().map(|v| match v.as_str() { + "smooth" => F::EighttapSmooth, + "sharp" => F::EighttapSharp, + _ => F::Eighttap, + }) + }); + ENV.unwrap_or(F::Eighttap) +} + /// The frame header for a shown inter frame that predicts from the single /// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that /// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s, @@ -5819,7 +5862,7 @@ fn obmc_prediction( x / 2, y / 2, &refpix, - Some(mc::InterpFilterKind::Regular), + Some(fctx.interp_filter.get()), frame_width, ) .ok()?; @@ -7251,6 +7294,10 @@ pub(crate) fn encode_key_frame_inner( render: (usize, usize), color_config: ColorConfig, fctx: &crate::decode::FrameCtx, ) -> Result { + // lane-refs: an intra frame runs no motion compensation, and the + // context is shared across the sequence -- put the kernel back to the + // default so nothing reads the previous inter frame's. + fctx.interp_filter.set(mc::InterpFilterKind::Regular); picture.check()?; if modes.is_empty() { return Err(Error::unsupported( @@ -8542,8 +8589,8 @@ fn mc_trial_compound_typed( mc::REF_NO_SCALE, side, side, - mc::InterpFilterKind::Regular, - mc::InterpFilterKind::Regular, + fctx.interp_filter.get(), + fctx.interp_filter.get(), dst, ); } @@ -8635,8 +8682,8 @@ fn predict_compound_u8( mc::REF_NO_SCALE, side, side, - mc::InterpFilterKind::Regular, - mc::InterpFilterKind::Regular, + fctx.interp_filter.get(), + fctx.interp_filter.get(), dst, ); } @@ -10618,6 +10665,12 @@ pub(crate) fn encode_inter_frame( )?; header.render_width = render.0 as u32; header.render_height = render.1 as u32; + // lane-refs: this frame's motion-compensation kernel, written into the + // header AND armed on the context every prediction reads, in one place so + // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched + // tile decodes to different pixels than the encoder scored). + header.interpolation_filter = frame_interp_filter(); + fctx.interp_filter.set(mc::InterpFilterKind::from_header(header.interpolation_filter)); let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias); // The order hint behind each `ref_frame_idx` entry. The flat path's own // slot plan (`inter_frame_headers_slots`) is: every reference but @@ -11680,7 +11733,7 @@ pub(crate) fn encode_inter_frame( lf, h.allow_high_precision_mv, h.force_integer_mv, - Some(mc::InterpFilterKind::Regular), + Some(fctx.interp_filter.get()), seq.enable_dual_filter, h.reference_select, // lane-txi: this frame's own bit, not the hardcoded `true` @@ -17083,4 +17136,160 @@ mod tests { eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}", e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid()); } + /// lane-refs: IS A SECOND PAST REFERENCE WORTH RETAINING? `encoder.rs`'s + /// `ref_frame_idx` maps `LAST2`/`LAST3` onto `LAST`'s own DPB slot, so no + /// block can predict from the picture before `LAST` -- while rav1e's ARFs + /// read LAST@-4 plus LAST2@-8 and libaom holds up to seven distinct + /// pictures. Building that (a second retained slot, the search offering + /// it, a witness, a second motion search per block) is a week of wall on + /// the stage that already owns most of the encode, so this census prices + /// the lever FIRST (class `gate-blind-to-feature`, "count how often the + /// feature would fire before building the machine"). + /// + /// The measurement is on the gate's own window and loader (`gate_crop`, + /// 12 pictures) of the two real films: every 16x16 luma block of every + /// picture gets one full-pel diamond search against the NEAR reference + /// and the same search against the FAR one, at the two lags the pyramid + /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF + /// level, rav1e's own pair. Reported per lag: the share of blocks the far + /// reference wins at all and by more than 10%, and -- the number the + /// decision is taken on -- the total SAD of best-of-{near, far} against + /// the total SAD of near alone, which is the prediction energy a second + /// reference could remove before any rate is paid for naming it. + /// + /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture + #[test] + #[ignore = "reads the real films"] + fn last2_census() { + if !have_ffmpeg() { + eprintln!("SKIP last2_census: no ffmpeg"); + return; + } + const SIDE: usize = 16; + // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or + // `None` when the displaced block leaves the picture. + let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| { + let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1); + if sy < 0 || sx < 0 { + return None; + } + let (sy, sx) = (sy as usize, sx as usize); + if sy + SIDE > r.height || sx + SIDE > r.width { + return None; + } + let mut acc = 0u64; + for row in 0..SIDE { + let c = &cur.y[(by + row) * cur.width + bx..][..SIDE]; + let p = &r.y[(sy + row) * r.width + sx..][..SIDE]; + acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::(); + } + Some(acc) + }; + // A log-step diamond from the zero motion vector: the cheapest search + // that still finds real pans. Both references get exactly this one, + // so the comparison is search-fair. + let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 { + let mut best = (sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX), (0isize, 0isize)); + let mut step = 16isize; + while step >= 1 { + let centre = best.1; + for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] { + let mv = (centre.0 + dy * step, centre.1 + dx * step); + if let Some(s) = sad(cur, r, bx, by, mv) { + if s < best.0 { + best = (s, mv); + } + } + } + step /= 2; + } + best.0 + }; + println!("| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |"); + println!("|---|---|---|---|---|---|---|---|"); + for (name, path, seek) in native_gate_clips() { + if !name.starts_with("film ") { + continue; + } + let (vf, cw, ch) = crate::probe::gate_crop(&path); + let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12); + for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] { + let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64); + let (mut near_sad, mut best_sad) = (0u64, 0u64); + for i in far..pictures.len() { + let cur = &pictures[i]; + let (rn, rf) = (&pictures[i - near], &pictures[i - far]); + for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) { + for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) { + let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by)); + blocks += 1; + wins += u64::from(f < n); + big += u64::from(f as f64 * 1.1 < n as f64); + near_sad += n; + best_sad += n.min(f); + } + } + } + let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64; + println!( + "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |", + pct(wins), + pct(big), + 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64, + ); + } + } + } + + /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to + /// hardwire the REGULAR kernel, so the encoder could not have coded a + /// SMOOTH or SHARP frame even if the header had said so -- the search, + /// the trials, the recon and the frame header now all read + /// `FrameCtx::interp_filter`. Each of the three kernels codes its own + /// distinct stream (a filter that never reached the prediction would code + /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg + /// reconstructs every frame of each of them exactly, which is what proves + /// the header and the prediction agree. + #[test] + fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() { + let _knobs = crate::speed::knob_write(); + if !have_ffmpeg() { + eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg"); + return; + } + let (width, height) = (256usize, 128usize); + // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so + // all three kernels would code the same bytes and the test would pass + // on a wiring that does nothing (class `fixture proves the symbol, not + // the signal`). `panned_test_card` shifts by whole pixels, so the + // search finds the sub-pel positions off the reconstruction instead: + // three frames of a slow diagonal pan. + let pictures: Vec = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect(); + let mut streams = Vec::new(); + for filter in [ + ec_av1_syntax::InterpolationFilter::Eighttap, + ec_av1_syntax::InterpolationFilter::EighttapSmooth, + ec_av1_syntax::InterpolationFilter::EighttapSharp, + ] { + set_frame_interp(Some(filter)); + let fctx = &crate::decode::FrameCtx::for_encoder(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) + .unwrap_or_else(|e| panic!("{filter:?}: {e}")); + let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); + assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count"); + for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { + assert_eq!(decoded.y, frame.reconstruction.y, "{filter:?} frame {i}: luma"); + assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U"); + assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V"); + } + streams.push((filter, encoded.stream)); + } + set_frame_interp(None); + for (i, (fa, a)) in streams.iter().enumerate() { + for (fb, b) in &streams[i + 1..] { + assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes"); + } + } + } + } diff --git a/crates/ec-av1/src/mc.rs b/crates/ec-av1/src/mc.rs index 485fd8d3..52b55a76 100644 --- a/crates/ec-av1/src/mc.rs +++ b/crates/ec-av1/src/mc.rs @@ -1048,7 +1048,12 @@ pub(crate) fn predict( y_q4, block_w, block_h, - InterpFilterKind::Regular, + // lane-refs: the FRAME's kernel (spec 6.8.9), not a hardwired + // `Regular` -- `FrameCtx::interp_filter` is what the encoder set from + // the header it is about to write, and every decode leaves it at + // `Regular` (the decoder's own inter path calls + // `predict_with_filters` with the kernels it parsed). + fctx.interp_filter.get(), dst, fctx, ); } diff --git a/lanes/refs.report.md b/lanes/refs.report.md new file mode 100644 index 00000000..c80c4a40 --- /dev/null +++ b/lanes/refs.report.md @@ -0,0 +1,142 @@ +# lane-refs — the reference set (LAST2) and the frame interpolation filter + +Worktree `edith_codecs-refs`, branch `lane-refs` off main 68e96c56. Every gate +arm is the prebuilt release lib-test binary running `bd_rate_screen_native` +(12 pictures, `gop 12`, four quantizers, native `gate_crop` window); every row +is read off that log's own header line, never off the argument order. + +## 0. The controls reproduce + +| clip | control (vs libaom / vs rav1e) | charter | +|---|---|---| +| film A, 12 frames | +21.7 / -4.4 | +21.7 / -4.4 | +| film B, 12 frames | +26.9 / -0.6 | +26.9 / -0.6 | +| screen capture, 12 frames | +20.1 / -30.4 | +20.1 / -30.4 | + +All three land to the digit. + +## 1. LAST2 — the census, before the machinery + +`encoder.rs`'s `ref_frame_idx` maps LAST2/LAST3 onto LAST's own DPB slot, so +the picture before LAST is not merely unoffered to the search, it is not +retained at all. Building it out is not a small diff (a second retained slot +per level, `ref_frame_idx` / `refresh_frame_flags` / `ref_frame_sign_bias` / +order hints for it, a per-reference mv stack, the writer's `single_ref` tree, +`record_mi`, and — the expensive part — a SECOND motion search per block, on +the stage that already owns most of the encode wall: `search_inter_block`'s +existing extra references are priced search-FREE for exactly that reason). +So the lever was PRICED first (`last2_census`, `--ignored`, 3.3 s): + +every 16x16 luma block of the gate's own 12-picture window of both real films +gets one full-pel diamond search against the NEAR reference and the same +search against the FAR one, at the two lags the pyramid offers — (1, 2) for +the leaf chain, (4, 8) for the ARF level, which is rav1e's own pair. + +| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | prediction energy removed | +|---|---|---|---|---|---|---|---| +| film A | leaf (1/2) | 57600 | 38.7% | 19.0% | 20974762 | 19509622 | **6.99%** | +| film A | ARF (4/8) | 23040 | 37.8% | 21.0% | 12015492 | 10776319 | **10.31%** | +| film B | leaf (1/2) | 76800 | 38.1% | 21.2% | 18946199 | 17572121 | **7.25%** | +| film B | ARF (4/8) | 30720 | 44.3% | 22.5% | 8539904 | 7824079 | **8.38%** | + +READ IT AS: a second past reference is chosen by ~4 blocks in 10 and by more +than 10% of SAD by ~1 in 5; best-of-two removes 7-10% of the total residual +ENERGY before any rate is paid for naming the reference or for the second +search. That is the largest un-taken prediction lever measured on this content +so far (the anchors' non-skip area is the standing film B gap), and the ARF +level — where the census is strongest — is exactly the level libaom and rav1e +spend their extra slots on. + +**Decision: the lever is worth building, and it does not fit this lane.** The +census is the charter's own first step ("before wiring the full search"), and +the build is chartered as its own lane below. + +## 2. The frame interpolation filter — WIRED, MEASURED, REJECTED as a default + +The premise held: `mc::predict` hardwired `InterpFilterKind::Regular`, so the +encoder could not have coded a SMOOTH or SHARP frame whatever the header said. +The kernel now travels on `FrameCtx::interp_filter` (copied into every +tile-search worker by `filter_ctx_copy`, so a threaded search reads the same +kernel), and `encode_inter_frame` writes that one kernel into the header — +one place, so header and prediction cannot disagree. `EC_AV1_INTERP= +smooth|sharp` (or `set_frame_interp`) selects it; the default is unchanged +REGULAR and byte-identical. + +| arm | film A | film B | keep rule | +|---|---|---|---| +| REGULAR (control) | +21.7 / -4.4 | +26.9 / -0.6 | — | +| SMOOTH | **+40.9 / +10.2** | +26.3 / -0.4 | film A loses 19.2 / 14.6 | +| SHARP | +24.0 / -2.9 | +28.4 / +0.6 | both rows worse on both columns | + +SMOOTH is a catastrophe on film A (19 BD points) for 0.6 of a point on film B's +libaom column while its rav1e column goes 0.2 the wrong way; SHARP is worse +everywhere. The keep rule (both films down on both columns) is nowhere near +met, so **REGULAR stays the default at every preset** and the per-frame +CHOOSER was not built: its ceiling is film B's +0.6/-0.2 mixed-sign move, and +its downside when a proxy mispicks is film A's 19 points (ladder rung 1 — it +does not need to exist). The wiring stays because it is what makes the +measurement possible at all and because it removes the hardwired-kernel +ceiling; it is proved by a witness rather than left as a claim. + +## 3. Invariants + +* `each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly` + (new, NOT ignored): each of the three kernels codes a DISTINCT stream (a + kernel that never reached the prediction would code REGULAR's bytes — class + `symbol consumption gap`) and ffmpeg reconstructs every frame of each of them + exactly against our own reconstruction. Green. +* `cargo test -p ec-av1 --release --lib`: see §4. +* `cargo check --workspace --all-targets`: see §4. + +## 4. Suite and check + +`timeout 900 cargo check --workspace --all-targets -j4`: **0 errors, 0 ec-av1 +warnings** (the 22 warnings are ec-opus' missing struct-field docs and +ec-vorbis' unused `decode_capture`, both pre-existing on main). + +THE LIB SUITE DOES NOT FIT A 900 s CAP ON THIS BOX. Two whole-suite arms died +`RC=124` -- the second one alone on the prebuilt binary, 168 of 253 +`stream::` tests in, no failure anywhere -- so the suite was SPLIT into three +disjoint-by-filter arms, each under the cap: + +| arm | filter | result | +|---|---|---| +| A | `--skip stream::` | 333 passed, 0 failed, 30 ignored (661 s) | +| B | `stream:: --skip 10bit` | 197 passed, 0 failed, 15 ignored (822 s) | +| C | `10bit` | 42 passed, 0 failed, 1 ignored (99 s) | + +Arms A and C overlap on exactly 2 tests (the two `10bit` names outside +`stream::`, counted from `--list`), and the binary holds 616 tests, so the +UNION is **570 passed / 46 ignored / 0 failed**, which accounts for every test +in the binary (570 + 46 = 616) and includes this lane's two: the filter +witness (passed) and `last2_census` (ignored). + +Invariants, all green, all on the prebuilt release binary: + +| invariant | run | result | +|---|---|---| +| every preset decodes sample-exact through both decoders | `--include-ignored`, `EC_COMP_MISMATCH=1` | 1 passed | +| tile / filter-stage bytes do not depend on the thread count | `--include-ignored` | 2 passed | +| facade identity + `predicted_coeff_bits_track_the_tile_the_writer_wrote` | default | 2 passed | +| pins 8562 / 33357 | `the_encoders_own_streams_are_byte_identical_to_their_pins`, in arm A | passed, UNCHANGED -- every lever ships off, so nothing was re-pinned | +| the filter witness | `each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly` | passed (landed in f6a107ff) | + +## 5. Deferred + +* **LAST2 / a real second past reference — deferred, chartered.** What it + needs: DPB slot 7 is free (the key's copy, never read back), so the leaf + chain can alternate its refresh between slots 0 and 7 and name the older of + the two as LAST2 while the ARF levels take theirs from the anchor pair; + `ref_frame_idx[1]`, `refresh_frame_flags`, `ref_frame_sign_bias`, the order + hints and a per-reference mv stack follow; the cheapest first arm offers + LAST2 through the EXISTING search-free `extra` path (NEARESTMV/GLOBALMV + only, as GOLDEN is offered today) so the second motion search — and its wall, + which is the user's stated priority — is a second arm, not a prerequisite. + Witness: a clip where the picture before LAST is the better reference, N + blocks coded off LAST2, exact through ffmpeg and `decode_stream`, hidden + frame display order intact. Unblocked by: a lane of its own with the wall + budget for the desync hunt. +* **The per-frame interpolation-filter chooser — dropped, not deferred**: §2's + table is its refutation, not a gap. +* The long-GOP gate was not run: nothing from this lane changes a default, so + there is nothing for it to confirm.