diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index d9906c7a..b9a01006 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -8303,6 +8303,17 @@ fn mv_component_bits(diff: i32) -> Option { Some(bits) } +/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the +/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch, +/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's +/// value without the second motion search's wall. +fn last2_new_mv() -> bool { + match std::env::var("EC_AV1_LAST2_NEW").ok() { + Some(v) => v != "0", + None => true, + } +} + /// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its /// own -- a second motion search per block against that reference's picture, /// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it @@ -9111,14 +9122,22 @@ fn search_inter_block( let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); // `write_single_ref`'s own tree, at the fixed context this pricer uses - // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN - // p1=0,p3=1,p5=1. + // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0, LAST2 + // p1=0,p3=0,p4=1 and GOLDEN p1=0,p3=1,p5=1. A BACKWARD reference + // (`ALTREF`, p1=1,p2=1) is priced as LAST here and always has been -- + // wrong by two symbols, but fixing it moves every shipped stream, so it + // is a lever of its own and not this lane's (lanes/last2.report.md). let single_ref_bits = |ref_frame: i8| { + use crate::mvstack::{GOLDEN_FRAME, LAST2_FRAME}; symbol_bits(&cdf::SINGLE_REF[0][0], 0) - + if ref_frame == crate::mvstack::GOLDEN_FRAME { + + if ref_frame == GOLDEN_FRAME { symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1) } else { - symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0) + symbol_bits(&cdf::SINGLE_REF[0][2], 0) + + symbol_bits( + &cdf::SINGLE_REF[0][3], + usize::from(ref_frame == LAST2_FRAME), + ) } }; @@ -9406,8 +9425,15 @@ fn search_inter_block( // prices out `margin` times better than LAST's best vector does -- // one candidate evaluation (`motion::cost_at`) standing in for a // whole search of ~50. + // lane-last2: the SEARCH-FREE arm for the second past leaf picture + // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some + // neighbour already found, which is how GOLDEN/ALTREF were offered + // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's + // own value from the second motion search's wall. + let searched = extra_ref_new_mv() + && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv()); let margin = extra_new_skip_margin(); - let skip_search = extra_ref_new_mv() + let skip_search = searched && margin > 0.0 && motion::cost_at( &g.y, @@ -9425,7 +9451,7 @@ fn search_inter_block( fctx, ) * margin <= found.cost; - if extra_ref_new_mv() && !skip_search { + if searched && !skip_search { let (gseeds, gn) = mv_seeds(gstack); #[cfg(test)] let t = stage_start(); @@ -10567,6 +10593,12 @@ pub(crate) struct PyramidFrame { /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a /// pyramid, which is what makes `sign_bias`'s last entry true. pub altref_slot: u8, + /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past + /// picture (the leaf chain alternates its refresh between two slots, so + /// the frame before `LAST` is still intact). `None` leaves + /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder + /// wrote before, and the caller then passes no `last2` picture either. + pub last2_slot: Option, /// `show_frame`: false for a hidden frame, output later by a /// `show_existing_frame` header. pub show_frame: bool, @@ -10602,7 +10634,14 @@ pub(crate) fn encode_inter_frame( // The frame two back, held in the slot this frame is about to refresh // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two // inter frames of a GOP, where the frame two back IS the key frame. - altref: Option<&Picture>, fctx: &crate::decode::FrameCtx, + altref: Option<&Picture>, + // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown + // frame BEFORE `reference` on the leaf chain, offered to the 32x32 + // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF` + // take. `None` (every caller but the pyramid leaves) codes the frame + // with the reference set unchanged. + last2: Option<&Picture>, + fctx: &crate::decode::FrameCtx, // Where this frame sits in the coding-order pyramid; `None` is the flat // one-shown-frame-per-picture stream this encoder wrote before. pyramid: Option, @@ -10683,6 +10722,14 @@ pub(crate) fn encode_inter_frame( // `GOLDEN_FRAME` is the key frame, order hint 0. Only // `frame::write_frame_header`'s `skipModeAllowed` reads this. header.order_hints = order_hints; + // lane-last2: `inter_frame_headers_slots` points every un-named + // reference at `last_slot`; the pyramid's leaf chain retains a second, + // older picture and names it here. The caller's `sign_bias` / + // `order_hints` entry 1 is derived from this same slot, so the stack + // scans and `skipModeAllowed` read what the decoder will. + if let Some(slot) = pyramid.and_then(|p| p.last2_slot) { + header.ref_frame_idx[1] = slot; + } header.reference_select = reference_select(); // Armed HERE, not only beside the tile write below: `ref_distance`'s own // per-reference order-hint distance is read by the block SEARCH, which @@ -10918,6 +10965,7 @@ pub(crate) fn encode_inter_frame( // built once per tile job (`obmc_prediction`). let mut obmc_refs: [Option<&Picture>; 8] = [None; 8]; obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference); + obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2; obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden; obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref; grid.set_tile_bounds( @@ -11109,6 +11157,7 @@ pub(crate) fn encode_inter_frame( let stack = find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); let extra_stacks: Vec<(i8, &Picture, MvStack)> = [ + (crate::mvstack::LAST2_FRAME, last2), (crate::mvstack::GOLDEN_FRAME, golden), (crate::mvstack::ALTREF_FRAME, altref), ] @@ -11664,8 +11713,22 @@ pub(crate) fn encode_inter_frame( } } }); + let trial_last2 = last2.map(|l| { + if (l.width, l.height) == (fw, fh) { + l.clone() + } else { + Picture { + width: fw, + height: fh, + y: crop_plane(&l.y, l.width, fw, fh), + u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2), + v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2), + } + } + }); let mut refs: [Option<&Picture>; 8] = [None; 8]; refs[1] = Some(&trial_ref); + refs[2] = trial_last2.as_ref(); refs[4] = trial_golden.as_ref(); refs[7] = trial_altref.as_ref(); let refpix = crate::decode::RefPix::ready(refs); @@ -11941,7 +12004,9 @@ pub(crate) fn encode_sequence_with_ctx( render, Some(&carried.0), Some(&golden), - prev2.as_ref(), fctx, + prev2.as_ref(), + None, + fctx, None, &lookahead, )?; @@ -14644,7 +14709,7 @@ mod tests { let padded_pic = picture.padded_to(SUPERBLOCK); let t = Instant::now(); let inter = - encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, &[]).unwrap(); + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[]).unwrap(); let inter_t = t.elapsed(); eprintln!( "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ @@ -14743,7 +14808,7 @@ mod tests { stage_reset(); let t = Instant::now(); let inter = - encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None, &[]).unwrap(); + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, None, fctx, None, &[]).unwrap(); let total_t = t.elapsed(); let [motion_search, interpolation, transform_quant, entropy] = stage_read(); let accounted = motion_search + transform_quant + entropy; @@ -14923,7 +14988,7 @@ mod tests { 0.5, 1, flat_order_hints(1, 0, false), - (width, height), None, None, None, fctx, None, &[], + (width, height), None, None, None, None, fctx, None, &[], ) .unwrap(); let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); @@ -14941,7 +15006,7 @@ mod tests { 0.5, 1, flat_order_hints(1, 0, false), - (width, height), None, None, None, fctx, None, &[], + (width, height), None, None, None, None, fctx, None, &[], ) .unwrap(); let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); @@ -15557,7 +15622,12 @@ mod tests { /// (`EC_AV1_ANGLE=0` restores that half). #[test] fn the_encoders_own_streams_are_byte_identical_to_their_pins() { - let _knobs = crate::speed::knob_read(); + // These are DEFAULT-PRESET pins: a speed preset switches search levers + // off, so it legitimately moves every byte. Encode at speed 0 whatever + // `EC_AV1_SPEED` says (write guard: the preset is process-global). + let _knobs = crate::speed::knob_write(); + let was = crate::speed::speed(); + crate::speed::set_speed(0); if !have_ffmpeg() { eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg"); return; @@ -15620,13 +15690,16 @@ mod tests { // now. `EC_AV1_I64=0` restores 8557 / 33345. let pins: [(u8, usize, u64); 2] = [(150, 8562, 0x66f5_4ffc_aacf_964f), (60, 33357, 0x1d61_9ca4_e960_b044)]; - for (q, bytes, hash) in pins { - let encoded = encode_sequence(&source, q, 0.5).unwrap(); - assert_eq!( - (encoded.stream.len(), fnv(&encoded.stream)), - (bytes, hash), - "q={q}: the encoder's stream moved" - ); + let coded: Vec<(u8, usize, u64)> = pins + .iter() + .map(|&(q, _, _)| { + let e = encode_sequence(&source, q, 0.5).unwrap(); + (q, e.stream.len(), fnv(&e.stream)) + }) + .collect(); + crate::speed::set_speed(was); + for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) { + assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved"); } } @@ -16934,6 +17007,19 @@ mod tests { mm.iter().sum::(), ); print_inter_tx_census(name); + // lane-last2 (class `gate-blind-to-feature`): which reference the + // 32x32-and-below inter blocks of this clip's four encodes chose. + // The native table is the standing keep table, so a second past + // reference that never won a block has to be visible HERE and not + // only in a synthetic witness. + let rh = crate::encode::take_ref_frame_hits(); + let rtot: usize = rh.iter().sum(); + eprintln!( + "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \ + (LAST2 {:.1}%)", + rh[1], rh[2], rh[4], rh[7], rtot, + 100.0 * rh[2] as f64 / rtot.max(1) as f64, + ); let palette = crate::tile::take_palette_hits(); let palette_uv = crate::tile::take_palette_uv_hits(); let ibc = crate::tile::take_intrabc_hits(); diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index 50063c97..7c9fccf5 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -961,6 +961,50 @@ const ANCHOR_SLOTS: [u8; 2] = [3, 4]; /// The slot the leaf chain refreshes and reads as `LAST_FRAME`. const LEAF_SLOT: u8 = 0; +/// lane-last2: the two slots the leaf chain alternates its refresh between +/// once [`last2`] is on, so that the shown frame BEFORE `LAST_FRAME` is still +/// in the DPB and can be named `LAST2_FRAME`. Slot 7 is the one the key frame +/// writes and nothing has ever read back, so this costs no other level a slot; +/// leaf `k` refreshes `LEAF_SLOTS[k % 2]`, which is the slot leaf `k - 2` +/// wrote -- read before write, spec 7.20's decode order. +const LEAF_SLOTS: [u8; 2] = [LEAF_SLOT, 7]; + +/// Whether the leaf chain retains that second past picture and offers it to +/// the block search as `LAST2_FRAME` (`EC_AV1_LAST2=0` / `=1`). The census +/// that priced the lever is `lanes/refs.report.md` §1; what it buys on the +/// gate is `lanes/last2.report.md`. +fn last2() -> bool { + match LAST2_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { + 0 => return false, + 1 => return true, + _ => {} + } + match std::env::var("EC_AV1_LAST2").ok() { + Some(v) => v != "0", + None => LAST2, + } +} + +/// A PROCESS-GLOBAL [`last2`] override that wins over the environment +/// (`u8::MAX` = unset), the shape `crate::encode::set_frame_interp` has -- +/// this crate's tests never call `set_var` (`crate::envflags`), so the +/// witness turns the lever on through this while holding +/// [`crate::speed::knob_write`]. +static LAST2_OVERRIDE: std::sync::atomic::AtomicU8 = + std::sync::atomic::AtomicU8::new(u8::MAX); + +/// Sets [`LAST2_OVERRIDE`]; `None` clears it. +#[allow(dead_code)] // set only from the `#[cfg(test)]` witness +pub(crate) fn set_last2(on: Option) { + LAST2_OVERRIDE.store( + on.map_or(u8::MAX, u8::from), + std::sync::atomic::Ordering::Relaxed, + ); +} + +/// [`last2`]'s default. +const LAST2: bool = false; + /// The slot the mid-level hidden frame of a three-level group refreshes /// ([`Pyramid::mid_q_offset`]): free of the two anchors (3, 4), of the leaf /// chain (0) and of `GOLDEN_SLOT` (1), so all four levels are live at once. @@ -1108,6 +1152,11 @@ pub struct Av1Encoder { /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its /// anchor. anchor: usize, + /// lane-last2: the [`LEAF_SLOTS`] the last two SHOWN leaves refreshed, + /// most recent first, across mini-GOP boundaries (the first leaf of a + /// group reads the anchor as `LAST_FRAME`, so its `LAST2_FRAME` is the + /// previous group's last leaf). Cleared by every key frame. + leaf_hist: Vec, /// Coding-order position of the next packet — a packet's `dts`. next_dts: u64, /// Set by [`Av1Encoder::encode_sequence_pyramid`]: every coded frame's @@ -1197,6 +1246,7 @@ impl Av1Encoder { pending: Vec::new(), held: std::collections::VecDeque::new(), anchor: 0, + leaf_hist: Vec::new(), next_dts: 0, collected: None, }) @@ -1468,6 +1518,7 @@ impl Av1Encoder { self.carried_cdfs.as_ref().map(|c| &c.0), self.golden.as_ref(), self.prev2.as_ref(), + None, &self.fctx, None, &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::>(), @@ -1607,6 +1658,9 @@ impl Av1Encoder { )?; self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0); self.anchor = 0; + // Every leaf slot now holds the key frame, which `GOLDEN_FRAME` + // already names: the chain starts empty again. + self.leaf_hist.clear(); let cropped = crop_encoded(&encoded, render.0, render.1); if let Some(rate_loop) = self.rate_loop.as_mut() { rate_loop.update(Level::Key, 0, cropped.stream.len()); @@ -1626,6 +1680,10 @@ impl Av1Encoder { last_slot: u8, self_slot: u8, altref_slot: u8, + // lane-last2: the slot read as `LAST2_FRAME`. `None` -- and any slot + // holding no picture, or the same one `LAST_FRAME` reads -- leaves + // the reference set exactly as it was before this lane. + last2_slot: Option, show_frame: bool, level: Level, // The quantizer offset comes from the CALLER, not from `level`: a @@ -1659,8 +1717,19 @@ impl Av1Encoder { .as_ref() .is_some_and(|s| s.order_hint > order_hint) }; + // A LAST2 slot only counts when it holds a picture that is not the + // one `LAST_FRAME` already names; otherwise the frame codes the + // reference set it always did. + let last2_slot = last2_slot + .filter(|&s| s != last_slot && self.dpb[s as usize].is_some()); let slots = [ - last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot, + last_slot, + last2_slot.unwrap_or(last_slot), + last_slot, + GOLDEN_SLOT, + last_slot, + last_slot, + altref_slot, ]; for (i, slot) in slots.into_iter().enumerate() { sign_bias[i] = ahead(slot, &self.dpb); @@ -1678,6 +1747,7 @@ impl Av1Encoder { .ok_or_else(|| { Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction") })?; + let last2 = last2_slot.and_then(|s| self.dpb[s as usize].as_ref().map(|d| d.picture.clone())); let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone()); let altref = (altref_slot != GOLDEN_SLOT) .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) @@ -1694,11 +1764,13 @@ impl Av1Encoder { start_cdfs.as_ref(), golden.as_ref(), altref.as_ref(), + last2.as_ref(), &self.fctx, Some(crate::encode::PyramidFrame { last_slot, self_slot, altref_slot, + last2_slot, show_frame, sign_bias, }), @@ -1715,7 +1787,8 @@ impl Av1Encoder { "AV1 encode", format!( "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \ - altref {altref_slot}, shown {show_frame}, golden {}, altref pic {}): {e}", + altref {altref_slot}, last2 {last2_slot:?}, shown {show_frame}, golden {}, \ + altref pic {}): {e}", golden.is_some(), altref.is_some(), ), @@ -1758,6 +1831,13 @@ impl Av1Encoder { }; window.into_iter().take(depth - 1).map(|p| p.padded_to(SUPERBLOCK)).collect() }; + // lane-last2: the slot a frame reading `last_slot` as `LAST_FRAME` + // names as `LAST2_FRAME` -- the most recent shown leaf that is not + // the one it already reads. `None` with the lever off, or before two + // distinct past pictures exist. + let last2_of = |hist: &[u8], last_slot: u8| -> Option { + last2().then(|| hist.iter().copied().find(|&s| s != last_slot)).flatten() + }; let anchor_slot = ANCHOR_SLOTS[self.anchor]; let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor]; let (arf_order, arf_picture) = group.last().cloned().expect("non-empty"); @@ -1771,6 +1851,7 @@ impl Av1Encoder { anchor_slot, next_anchor_slot, GOLDEN_SLOT, + last2_of(&self.leaf_hist, anchor_slot), true, Level::Leaf, pyramid.leaf_q_offset, @@ -1793,6 +1874,10 @@ impl Av1Encoder { true => next_anchor_slot, false => GOLDEN_SLOT, }, + // The ARF levels take no LAST2: the anchor pair already gives a + // top ARF two distinct past anchors (`arf_altref`), and the mid + // and quarter frames have only the one past anchor in the DPB. + None, false, Level::Arf, pyramid.arf_q_offset, @@ -1826,6 +1911,7 @@ impl Av1Encoder { anchor_slot, MID_SLOT, next_anchor_slot, + None, false, Level::Arf, offset, @@ -1862,6 +1948,7 @@ impl Av1Encoder { last_slot, QUARTER_SLOTS[i], altref_slot, + None, false, Level::Arf, offset, @@ -1902,23 +1989,42 @@ impl Av1Encoder { packets.push(packet); continue; } + // The previous shown leaf's own slot: `LEAF_SLOT` with the + // lever off, and with it on whichever of [`LEAF_SLOTS`] that leaf + // refreshed. + let prev_leaf = self.leaf_hist.first().copied().unwrap_or(LEAF_SLOT); let last_slot = match i { 0 => anchor_slot, i => inner .iter() .find(|(at, _)| at + 1 == i) - .map_or(LEAF_SLOT, |&(_, slot)| slot), + .map_or(prev_leaf, |&(_, slot)| slot), + }; + // Alternate the refresh: this leaf takes the leaf slot the + // PREVIOUS leaf did not, which is the one the leaf before that + // wrote and which this frame may still read as `LAST2_FRAME` + // (read before write). + let self_slot = match last2() { + true => LEAF_SLOTS + .into_iter() + .find(|&s| Some(s) != self.leaf_hist.first().copied()) + .unwrap_or(LEAF_SLOT), + false => LEAF_SLOT, }; + let last2_slot = last2_of(&self.leaf_hist, last_slot); let altref_slot = inner .iter() .find(|(at, _)| *at > i) .map_or(next_anchor_slot, |&(_, slot)| slot); + self.leaf_hist.insert(0, self_slot); + self.leaf_hist.truncate(2); packets.push(self.encode_pyramid_inter( *order, picture, last_slot, - LEAF_SLOT, + self_slot, altref_slot, + last2_slot, true, Level::Leaf, pyramid.leaf_q_offset, @@ -2917,6 +3023,91 @@ mod tests { assert!(finer > base, "key_q_offset -48 did not reach the key frame ({finer} <= {base})"); } + /// lane-last2's witness: a clip whose pictures ALTERNATE between two + /// textures, so for every leaf the picture two back is an exact match and + /// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf + /// chain alternates its refresh over [`LEAF_SLOTS`] and names the older + /// slot `LAST2_FRAME`; blocks must actually be CODED off it + /// ([[gate-blind-to-feature]]: a slot that is retained but never chosen + /// proves only that the bookkeeping compiles), the stream must decode + /// sample-exact through OUR decoder and through ffmpeg, and the hidden + /// frames must still come out in display order. With the lever OFF the + /// same clip codes ZERO `LAST2` blocks, which is what makes the counter a + /// measurement of this lane and not of the reference set we already had. + #[test] + fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() { + let _knobs = crate::speed::knob_write(); + crate::encode::force_screen(Some(false)); + let (width, height) = (128usize, 128usize); + let sources: Vec = + (0..9).map(|t| test_card(width, height, (t % 2) * 24)).collect(); + let run = |on: bool| -> ([usize; 8], Vec, Vec) { + set_last2(Some(on)); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 32, + colour: Colour::Bt709Limited, + tile_cols_log2: 0, + tile_rows_log2: 0, + }; + let pyramid = Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() }; + let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); + let _ = crate::encode::take_ref_frame_hits(); + let mut packets = Vec::new(); + for picture in &sources { + packets.extend(enc.encode_frames(picture).unwrap()); + } + packets.extend(enc.flush().unwrap()); + let hits = crate::encode::take_ref_frame_hits(); + (hits, concat(&packets), packets) + }; + let (off_hits, off_stream, _) = run(false); + let (on_hits, stream, packets) = run(true); + set_last2(None); + eprintln!( + "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \ + on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)", + off_hits[1], off_hits[2], off_hits[4], off_hits[7], off_stream.len(), + on_hits[1], on_hits[2], on_hits[4], on_hits[7], stream.len(), + ); + assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF"); + assert!( + on_hits[2] >= 8, + "the picture two back matches exactly and only {} blocks were coded off LAST2", + on_hits[2], + ); + + // Display order and sample-exactness, both decoders (the same shape + // `pyramid_round_trip` gates the hidden frames with). + let ours = crate::stream::decode_stream(&stream).expect("our decoder"); + assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); + if !have_ffmpeg() { + eprintln!("SKIP the ffmpeg half of the LAST2 witness: no ffmpeg"); + return; + } + let theirs = ffmpeg_decode_luma(&stream, width, height); + assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); + for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { + let got: Vec = a.y.iter().map(|&v| v as u8).collect(); + assert_eq!(got.len(), b.len(), "frame {i}: luma size"); + if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { + panic!( + "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", + at % width, + at / width, + got[at], + b[at], + ); + } + } + // The reordering itself is unchanged by the second leaf slot. + let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); + let arfs = packets.iter().filter(|p| p.level == Level::Arf).count(); + assert_eq!(shown, arfs, "one show_existing_frame per hidden frame"); + } + fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { let (width, height) = (128usize, 128usize); let config = EncoderConfig { diff --git a/lanes/last2.report.md b/lanes/last2.report.md new file mode 100644 index 00000000..9ad2b42e --- /dev/null +++ b/lanes/last2.report.md @@ -0,0 +1,180 @@ +# lane-last2 — a second past reference (LAST2) on the pyramid + +> **HANDOVER (session closed mid-lane).** What is DONE: the DPB/slot +> bookkeeping, the search offer at 32x32, the witness, and both 12-frame +> arms on both films — the lever is REFUTED on the gate and ships OFF +> (`LAST2 = false`, `EC_AV1_LAST2=1` turns it on). What is STILL OWED: +> (a) the three suite split arms (`--skip stream::` / `stream:: --skip 10bit` +> / `10bit`) were never run on this branch; (b) `cargo check --workspace +> --all-targets` was green BEFORE the last two commits (the `EC_AV1_LAST2_NEW` +> knob and the gate's reference census) — re-run it; (c) the preset-6 +> invariant arm failed ONLY on +> `the_encoders_own_streams_are_byte_identical_to_their_pins` (q=150: 9846 vs +> the 8562 pin) with `EC_AV1_LAST2=0`, i.e. with every one of this lane's +> paths switched off — the pins are DEFAULT-preset pins and `EC_AV1_SPEED=6` +> moves the stream, so this is believed pre-existing and NOT this lane's, but +> it was not confirmed against main; confirm it there first. Preset 0 with +> `EC_COMP_MISMATCH=1` passed all six invariants including the pins. +> (d) the compound `LAST_LAST2` step (charter step 4) was not built: with +> LAST2 winning only 1.3–1.7% of inter blocks as a single reference and both +> single-ref arms losing, its ceiling is too small to spend the wall on. +> No long-GOP arm was run because nothing ships (same reasoning as lane-refs). + +Worktree `edith_codecs-last2`, branch `lane-last2` off main e6df5196. +Charter: `lanes/refs.report.md` §6. 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), one film per arm +(`EC_AV1_NATIVE_FILM` / `EC_AV1_NATIVE_FILM4K` / `EC_AV1_NATIVE_SCREEN`); every +row is read off that log's own header line. + +## 0. The charter's ARF step is a stale premise (read this first) + +The charter orders "ARF level first". At the ARF level there is nothing to +build: a group's top ARF ALREADY names two distinct past anchors -- +`last_slot` = `ANCHOR_SLOTS[anchor]` (the previous group's top ARF, lag +`mini_gop`) and, since lane-arfcen's `arf_altref` shipped ON, +`altref_slot` = `ANCHOR_SLOTS[1 - anchor]`, which still holds the top ARF from +TWO groups back (lag 2 * `mini_gop`) when the frame is coded. Those are +exactly the census's (4, 8) ARF lags, and that reference is offered to the +32x32 search through the `extra` path WITH its own `NEWMV` search +(`EXTRA_REF_NEW_MV` = true, margin `EXTRA_NEW_SKIP_MARGIN` = 0.35). So the +census's ARF row (film A 10.31%, film B 8.38% of prediction SAD) is a lever +already banked by `arf_altref`, not an open one; naming the same slot again as +`LAST2_FRAME` would offer the same picture twice. + +The open half of the census is the LEAF chain (film A 6.99%, film B 7.25%): +a leaf has exactly one past picture in the DPB (`LEAF_SLOT`, or the mid / +quarter hidden frame behind it) plus the key as `GOLDEN`. That is what this +lane builds. + +## 1. The slot map + +| slot | holds | written by | read as | +|---|---|---|---| +| 0, 7 (`LEAF_SLOTS`) | the last two shown leaves | every leaf, alternating | `LAST_FRAME` and `LAST2_FRAME` of the next leaf | +| 1 (`GOLDEN_SLOT`) | the key frame | the key | `GOLDEN_FRAME` everywhere | +| 2 (`MID_SLOT`) | the mid ARF | the mid ARF | `LAST`/`ALTREF` of the leaves and quarters around it | +| 3, 4 (`ANCHOR_SLOTS`) | this group's anchor and the next | the key, each top ARF | anchor = `LAST`, next = `ALTREF` | +| 5, 6 (`QUARTER_SLOTS`) | the two quarter ARFs (off by default) | the quarter ARFs | `LAST`/`ALTREF` of the leaves beside them | + +Leaf `k` refreshes `LEAF_SLOTS[k % 2]`, i.e. the slot leaf `k - 2` wrote -- +read before write. `Av1Encoder::leaf_hist` carries the last two leaf slots +ACROSS mini-GOP boundaries (the first leaf of a group reads the anchor as +`LAST`, so its `LAST2` is the previous group's last leaf) and is cleared by +every key frame (which writes all eight slots with one picture `GOLDEN` +already names). A leaf whose `LAST` is a hidden frame reads the previous leaf +as `LAST2`. The hidden levels pass `None`: see §0. + +## 2. What changed + +`crates/ec-av1/src/encoder.rs` +* `LEAF_SLOTS = [0, 7]`, `Av1Encoder::leaf_hist` (the last two leaf slots, + cleared by every key frame), the leaf loop alternates `self_slot` and names + the older slot; `encode_pyramid_inter` takes `last2_slot: Option`, + drops it when it holds no picture or the same one `LAST` names, and derives + `sign_bias[1]` / `order_hints[1]` from it through the existing `slots` array + (so the writer and the decoder scan the same stacks). +* `last2()` / `set_last2` — `EC_AV1_LAST2`, default OFF this lane, plus the + process-global override the witness uses (this crate's tests never call + `set_var`). + +`crates/ec-av1/src/encode.rs` +* `PyramidFrame::last2_slot`; `encode_inter_frame` takes `last2: + Option<&Picture>` and, when the slot is named, sets + `header.ref_frame_idx[1]`. +* The picture reaches: the 32x32 `extra` search list (`NEAREST`/`NEAR`/ + `GLOBAL` plus the existing `EXTRA_REF_NEW_MV` search under + `EXTRA_NEW_SKIP_MARGIN` — the charter's "free arm" and its seeded arm are + the SAME code path here, since extra references already get a NEWMV), the + OBMC neighbour picture table, and the trial decode's `RefPix` slot 2. +* The RD pricer's `single_ref_bits` gained LAST2's `p4 = 1` leaf. +* The native gate prints a per-clip reference census (`LAST / LAST2 / GOLDEN / + ALTREF`), so the keep table can see whether the tool fires at all. + +The 16x16/8x8 leaves are NOT offered LAST2 as a single reference: that path +(`code_square_inter`) takes no `extra` list at all, only compound pairs. The +64x64 root goes through `search_skip_64`, likewise no `extra`. So this arm is +the 32x32 level, which is where the existing extra references live too. + +## 3. The witness + +`encoder::tests::a_leaf_predicts_off_last2_when_the_picture_two_back_matches` +(not ignored, 3.6 s): nine 128x128 pictures ALTERNATING between two textures, +`mini_gop` 4, so every leaf's picture two back is an exact match. + +| lever | LAST | LAST2 | GOLDEN | ALTREF | stream | +|---|---|---|---|---|---| +| off | 67 | **0** | 18 | 8 | 2969 B | +| on | 25 | **36** | 15 | 8 | 2300 B | + +36 blocks coded off LAST2 (0 with the lever off — the counter measures this +lane and not the reference set we already had), −22.5% bytes on the clip the +lever is built for, `decode_stream` and ffmpeg both reconstruct all nine +display positions sample-exact, and one `show_existing_frame` per hidden frame +survives. + +## 4. The 12-frame native gate + +Controls reproduce to the digit: film A +21.7 / −4.4, film B +26.9 / −0.6. + +| arm | film A (vs libaom / rav1e) | film B | wall ours, film A / film B | +|---|---|---|---| +| control (`EC_AV1_LAST2=0`) | +21.7 / −4.4 | +26.9 / −0.6 | 208.2 s / 165.0 s | +| LAST2 at the 32x32 search, with its own NEWMV | +21.4 / −4.5 | **+27.3 / −0.1** | 242.0 s / 202.5 s | + +Film A moves 0.3 down on the libaom column and 0.1 UP on rav1e's; film B moves +0.4 and 0.5 the WRONG way on both. The keep rule ("both film rows improve on +both columns, or one ≥0.5 down and the other flat ±0.3") is not met — and the +arm costs +16% / +23% encoder wall, on the stage the user's speed order is +about. So the searched arm is refuted. + +| LAST2 search-FREE (`EC_AV1_LAST2_NEW=0`) | +21.5 / −4.5 | **+27.3 / −0.0** | 194.3 s / 171.3 s | + +The charter's "free arm" does not rescue it: film A is 0.2 down on libaom and +0.1 up on rav1e, film B is 0.4 / 0.6 the wrong way on both columns. The wall +comes back (194 s / 171 s against the control's 208 s / 165 s, i.e. inside the +gate's own wall noise), so the cost of the searched arm was indeed the second +motion search — but the reference itself does not pay for its own syntax. + +**The screen row** (`EC_AV1_NATIVE_SCREEN=1`, the keep rule's third column): +control and the search-free arm are BYTE-IDENTICAL at all four quantizers +(+19.8% / -30.5%, 143.6 s vs 144.1 s), and the census prints `LAST2 0 of 23942 +inter blocks` — the screen clip's leaves never take the older picture, so the +screen half of the keep rule is neutral either way and the decision rests on +the two film rows. + +**Fire share, on the real film rows** (the census the gate now prints): + +| clip | LAST | LAST2 | GOLDEN | ALTREF | LAST2 share | +|---|---|---|---|---|---| +| film A | 41871 | 780 | 1349 | 916 | 1.7% | +| film B | 39412 | 566 | 1894 | 1807 | 1.3% | +| bars 1080p | 22626 | 58 | 4067 | 206 | 0.2% | + +So the tool DOES fire on real film (it is not a dead knob — the witness and +these counters are the [[gate-blind-to-feature]] proof), it is simply chosen +by 1 block in 60 and those blocks do not pay back the `single_ref` symbol they +spend. Read against `refs.report.md` §1's census (38% of blocks preferring the +older picture by SAD): a pure-SAD best-of-two over-counts the lever by more +than an order of magnitude once the block also has NEAR/NEAREST/DRL off LAST, +a backward `ALTREF` at every leaf, and a rate term. + +## 5. Decision + +`LAST2` ships **OFF** (`const LAST2: bool = false`). The machinery stays: it +is the only way the census's remaining claim can ever be re-measured, it is +witnessed end to end, and it costs the default path nothing (a `None` picture +is filtered out of the `extra` list and the header is untouched — the pins are +byte-identical with the lever off). + +## 6. Deferred / dropped + +* **The compound `LAST_LAST2` pair (charter step 4) — dropped, not deferred.** + Its input is the single-reference arm, which loses on both films with a + 1.5% fire share. +* **The ARF-level LAST2 (charter step 1) — dropped as a stale premise**, §0. +* **The RD pricer charges `ALTREF` as if it were `LAST`** (`single_ref_bits`, + `encode.rs`): a backward reference codes `p1=1,p2=1`, two different symbols + from LAST's `p1=0,p3=0,p4=0`. Left alone here because fixing it moves every + shipped stream, so it needs its own gate arm — deferred, unblocked by a lane + that can re-pin. Found while adding LAST2's own leaf to that same tree.