From ec4f10e671ffcc0a2ed0bc4b59f9e682e47788fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 8 Sep 2026 05:25:06 +0300 Subject: [PATCH] feat(av1): retain a second past leaf picture and offer it as LAST2 (off by default) --- crates/ec-av1/src/encode.rs | 67 ++++++++++++++++++++++---- crates/ec-av1/src/encoder.rs | 92 ++++++++++++++++++++++++++++++++++-- lanes/last2.report.md | 47 ++++++++++++++++++ 3 files changed, 192 insertions(+), 14 deletions(-) create mode 100644 lanes/last2.report.md diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 73e67b89..3389d281 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -9107,14 +9107,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), + ) } }; @@ -10563,6 +10571,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, @@ -10598,7 +10612,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, @@ -10679,6 +10700,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 @@ -10914,6 +10943,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( @@ -11105,6 +11135,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), ] @@ -11660,8 +11691,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); @@ -11937,7 +11982,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, )?; @@ -14640,7 +14687,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 \ @@ -14739,7 +14786,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; @@ -14919,7 +14966,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); @@ -14937,7 +14984,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); diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index b3962a8a..d503eae4 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -961,6 +961,28 @@ 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 std::env::var("EC_AV1_LAST2").ok() { + Some(v) => v != "0", + None => LAST2, + } +} + +/// [`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 +1130,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 +1224,7 @@ impl Av1Encoder { pending: Vec::new(), held: std::collections::VecDeque::new(), anchor: 0, + leaf_hist: Vec::new(), next_dts: 0, collected: None, }) @@ -1468,6 +1496,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 +1636,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 +1658,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 +1695,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 +1725,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 +1742,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 +1765,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 +1809,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 +1829,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 +1852,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 +1889,7 @@ impl Av1Encoder { anchor_slot, MID_SLOT, next_anchor_slot, + None, false, Level::Arf, offset, @@ -1862,6 +1926,7 @@ impl Av1Encoder { last_slot, QUARTER_SLOTS[i], altref_slot, + None, false, Level::Arf, offset, @@ -1902,23 +1967,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, diff --git a/lanes/last2.report.md b/lanes/last2.report.md new file mode 100644 index 00000000..2053a34f --- /dev/null +++ b/lanes/last2.report.md @@ -0,0 +1,47 @@ +# lane-last2 — a second past reference (LAST2) on the pyramid + +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. +