forge
Explore
Log in

Don't you dare go Hollow

ALTREF as the frame two back, on an alternating slot

Browse files at this commit

931098164d723070530a397176eddb5ff3e1a290Ahmet Kaan GümüşParent: 2f069ae
  • feat
    • ALTREF as the frame two back, on an alternating slot
Show full message
feat(av1): ALTREF as the frame two back, on an alternating slot

Frame n refreshes slot 0 for odd n and slot 2 for even n, so the frame
two back is still intact in the very slot this one is about to overwrite
(read before write): ref_frame_idx names it as ALTREF_FRAME, LAST names
the other slot, GOLDEN stays on slot 1. inter_frame_headers_slots is the
header builder that takes the three slots apart; the five-argument
inter_frame_headers keeps its old read-and-write-one-slot meaning for the
hand-built fixtures. The RD prices each extra reference's two
search-free modes from a slice, so LAST/GOLDEN/ALTREF share one code path.

ALTREF is picked for 337/405/1793 blocks per ladder. BD-rate vs libaom
127.3/153.4/83.0 -> 126.5/152.9/80.9, vs rav1e 78.6/105.7/18.3 ->
77.9/105.5/17.6; wall 7.8/7.1/7.8 -> 8.0/7.2/7.7 s. ffmpeg decodes every
stream sample-exact.
crates/ec-av1/src/decode.rsmodified+21 -2
@@ -35642,9 +35642,20 @@ mod tests {
3564235642 /// `ref_frame_idx[3]` names the slot the key frame left behind and its
3564335643 /// blocks may code `single_ref` out to it.
3564435644 fn last_and_golden<'a>(last: &'a Picture, golden: &'a Picture) -> RefPix<'a> {
35645+ last_golden_altref(last, golden, None)
35646+ }
35647+
35648+ /// [`last_and_golden`] plus `ALTREF_FRAME` (index 7): the frame two back,
35649+ /// which the encoder keeps in the slot the current frame refreshes.
35650+ fn last_golden_altref<'a>(
35651+ last: &'a Picture,
35652+ golden: &'a Picture,
35653+ altref: Option<&'a Picture>,
35654+ ) -> RefPix<'a> {
3564535655 let mut refs: [Option<&Picture>; 8] = [None; 8];
3564635656 refs[1] = Some(last);
3564735657 refs[4] = Some(golden);
35658+ refs[7] = altref;
3564835659 RefPix::ready(refs)
3564935660 }
3565035661
@@ -37175,7 +37186,11 @@ mod tests {
3717537186 frame.base_q_idx,
3717637187 width as u32,
3717737188 height as u32,
37178- &last_and_golden(&reference, &encoded.frames[0].reconstruction),
37189+ &last_golden_altref(
37190+ &reference,
37191+ &encoded.frames[0].reconstruction,
37192+ (i >= 2).then(|| &encoded.frames[i - 2].reconstruction),
37193+ ),
3717937194 &frame.cdef,
3718037195 &frame.loop_filter,
3718137196 false,
@@ -37487,7 +37502,11 @@ mod tests {
3748737502 frame.base_q_idx,
3748837503 coded_w,
3748937504 coded_h,
37490- &last_and_golden(&reference, &encoded.frames[0].reconstruction),
37505+ &last_golden_altref(
37506+ &reference,
37507+ &encoded.frames[0].reconstruction,
37508+ (i >= 2).then(|| &encoded.frames[i - 2].reconstruction),
37509+ ),
3749137510 &frame.cdef,
3749237511 &frame.loop_filter,
3749337512 false,
crates/ec-av1/src/encode.rsmodified+106 -31
@@ -731,6 +731,26 @@ pub fn inter_frame_headers(
731731 base_q_idx: u8,
732732 order_hint: u32,
733733 last_slot: u8,
734+) -> Result<(SequenceHeader, FrameHeader)> {
735+ inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
736+}
737+
738+/// [`inter_frame_headers`] with the three slots named apart: the one read as
739+/// `LAST_FRAME`, the one this frame refreshes, and the one read as
740+/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
741+/// so that the frame two back is still intact in the slot this one is about
742+/// to overwrite -- read before write, spec 7.20's decode order.
743+///
744+/// # Errors
745+/// As [`inter_frame_headers`].
746+pub fn inter_frame_headers_slots(
747+ width: usize,
748+ height: usize,
749+ base_q_idx: u8,
750+ order_hint: u32,
751+ last_slot: u8,
752+ self_slot: u8,
753+ altref_slot: u8,
734754 ) -> Result<(SequenceHeader, FrameHeader)> {
735755 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
736756 let header = FrameHeader {
@@ -746,7 +766,7 @@ pub fn inter_frame_headers(
746766 force_integer_mv: false,
747767 order_hint,
748768 primary_ref_frame: 0,
749- refresh_frame_flags: 1 << last_slot,
769+ refresh_frame_flags: 1 << self_slot,
750770 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
751771 // names the slot this frame both predicts from and refreshes;
752772 // GOLDEN names slot 1, which the key frame wrote when it refreshed
@@ -755,6 +775,7 @@ pub fn inter_frame_headers(
755775 ref_frame_idx: {
756776 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
757777 idx[3] = GOLDEN_SLOT;
778+ idx[6] = altref_slot;
758779 idx
759780 },
760781 allow_high_precision_mv: false,
@@ -3408,7 +3429,7 @@ fn search_inter_block(
34083429 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
34093430 // second motion search would double the wall of the stage that already
34103431 // owns most of it.
3411- golden: Option<(&Picture, &MvStack)>, fctx: &crate::decode::FrameCtx,
3432+ extra: &[(i8, &Picture, &MvStack)], fctx: &crate::decode::FrameCtx,
34123433 ) -> (BlockCoeffs, f64) {
34133434 // `luma_set` is the INTRA candidates' table; the two inter candidates
34143435 // below price their coefficients through `TxbSet::Luma32Inter`, which is
@@ -3680,8 +3701,8 @@ fn search_inter_block(
36803701 ));
36813702 }
36823703
3683- if let Some((_, gstack)) = golden {
3684- let g_ref_bits = single_ref_bits(crate::mvstack::GOLDEN_FRAME);
3704+ for &(ref_frame, _, gstack) in extra {
3705+ let g_ref_bits = single_ref_bits(ref_frame);
36853706 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
36863707 cands.push((
36873708 gstack.nearest_mv,
@@ -3690,7 +3711,7 @@ fn search_inter_block(
36903711 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
36913712 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
36923713 InterInfo {
3693- ref_frame: crate::mvstack::GOLDEN_FRAME,
3714+ ref_frame,
36943715 mode: InterMode::NearestMv,
36953716 mv: gstack.nearest_mv,
36963717 ref_mv_idx: 0,
@@ -3700,7 +3721,7 @@ fn search_inter_block(
37003721 (0, 0),
37013722 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
37023723 InterInfo {
3703- ref_frame: crate::mvstack::GOLDEN_FRAME,
3724+ ref_frame,
37043725 mode: InterMode::GlobalMv,
37053726 mv: (0, 0),
37063727 ref_mv_idx: 0,
@@ -3718,13 +3739,16 @@ fn search_inter_block(
37183739 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
37193740 {
37203741 for (mv, mode_bits_inter, info) in cands {
3721- let (ref_luma, ref_u, ref_v) = match golden {
3722- Some((g, _)) if info.ref_frame == crate::mvstack::GOLDEN_FRAME => (
3742+ let (ref_luma, ref_u, ref_v) = match extra
3743+ .iter()
3744+ .find(|(r, _, _)| *r == info.ref_frame)
3745+ {
3746+ Some(&(_, g, _)) => (
37233747 (&g.y, g.width, luma.true_width, luma.true_height),
37243748 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
37253749 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
37263750 ),
3727- _ => (ref_luma, ref_u, ref_v),
3751+ None => (ref_luma, ref_u, ref_v),
37283752 };
37293753 let luma_trial = mc_trial(
37303754 luma,
@@ -3839,7 +3863,11 @@ pub(crate) fn encode_inter_frame(
38393863 // The key frame's own (padded) reconstruction, which every frame of the
38403864 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
38413865 // with `LAST_FRAME` alone, exactly as before.
3842- golden: Option<&Picture>, fctx: &crate::decode::FrameCtx,
3866+ golden: Option<&Picture>,
3867+ // The frame two back, held in the slot this frame is about to refresh
3868+ // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
3869+ // inter frames of a GOP, where the frame two back IS the key frame.
3870+ altref: Option<&Picture>, fctx: &crate::decode::FrameCtx,
38433871 ) -> Result<Encoded> {
38443872 picture.check()?;
38453873 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
@@ -3862,14 +3890,33 @@ pub(crate) fn encode_inter_frame(
38623890 // overwrites slot 0, so the frame just coded is always what the next one
38633891 // predicts against.
38643892 const LAST_SLOT: u8 = 0;
3893+ // Slot 0 and slot 2 alternate so the frame two back survives one more
3894+ // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
3895+ // and the picture this frame names as `ALTREF_FRAME` is the one sitting
3896+ // in the very slot it will overwrite.
3897+ let self_slot = if order_hint % 2 == 1 { 0 } else { 2 };
3898+ let last_slot = if order_hint <= 1 {
3899+ LAST_SLOT
3900+ } else if (order_hint - 1) % 2 == 1 {
3901+ 0
3902+ } else {
3903+ 2
3904+ };
38653905 // `render`, not `picture.width`/`picture.height`: `picture` here is
38663906 // already padded to a whole number of superblocks (`encode_sequence`'s
38673907 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
38683908 // every true-edge clamp downstream) must come from the frame's real,
38693909 // unpadded size, same as `key_frame_headers_colour` takes `render` and
38703910 // not the padded picture in `encode_key_frame_inner`.
3871- let (seq, mut header) =
3872- inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?;
3911+ let (seq, mut header) = inter_frame_headers_slots(
3912+ render.0,
3913+ render.1,
3914+ base_q_idx,
3915+ order_hint,
3916+ last_slot,
3917+ self_slot,
3918+ if altref.is_some() { self_slot } else { GOLDEN_SLOT },
3919+ )?;
38733920 header.render_width = render.0 as u32;
38743921 header.render_height = render.1 as u32;
38753922 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
@@ -3974,18 +4021,25 @@ pub(crate) fn encode_inter_frame(
39744021 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
39754022 let stack =
39764023 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
3977- let golden_stack = golden.map(|_| {
3978- find_mv_stack(
3979- &grid,
3980- mi_row,
3981- mi_col,
3982- 8,
3983- 8,
3984- crate::mvstack::GOLDEN_FRAME,
3985- mi_cols,
3986- mi_rows,
3987- )
3988- });
4024+ let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
4025+ (crate::mvstack::GOLDEN_FRAME, golden),
4026+ (crate::mvstack::ALTREF_FRAME, altref),
4027+ ]
4028+ .into_iter()
4029+ .filter_map(|(r, pic)| {
4030+ pic.map(|p| {
4031+ (
4032+ r,
4033+ p,
4034+ find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
4035+ )
4036+ })
4037+ })
4038+ .collect();
4039+ let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
4040+ .iter()
4041+ .map(|(r, p, st)| (*r, *p, st))
4042+ .collect();
39894043
39904044 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
39914045 let (block, mut cost_whole) = search_inter_block(
@@ -3996,7 +4050,7 @@ pub(crate) fn encode_inter_frame(
39964050 &mode_bits_table,
39974051 reference,
39984052 &stack,
3999- golden.zip(golden_stack.as_ref()), fctx,
4053+ &extra, fctx,
40004054 );
40014055 cost_whole += search.lambda * partition_bits(BLOCK, false);
40024056 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
@@ -4368,9 +4422,23 @@ pub(crate) fn encode_inter_frame(
43684422 }
43694423 }
43704424 });
4425+ let trial_altref = altref.map(|a| {
4426+ if (a.width, a.height) == (fw, fh) {
4427+ a.clone()
4428+ } else {
4429+ Picture {
4430+ width: fw,
4431+ height: fh,
4432+ y: crop_plane(&a.y, a.width, fw, fh),
4433+ u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
4434+ v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
4435+ }
4436+ }
4437+ });
43714438 let mut refs: [Option<&Picture>; 8] = [None; 8];
43724439 refs[1] = Some(&trial_ref);
43734440 refs[4] = trial_golden.as_ref();
4441+ refs[7] = trial_altref.as_ref();
43744442 let refpix = crate::decode::RefPix::ready(refs);
43754443 pick_and_apply_filters(
43764444 &mut header,
@@ -4495,6 +4563,9 @@ pub(crate) fn encode_sequence_with_ctx(
44954563 // key frame refreshes every slot, each inter frame only slot 0), which is
44964564 // what `GOLDEN_FRAME` names.
44974565 let golden = key.reconstruction.clone();
4566+ // The frame two back, once there is one that is not the key frame
4567+ // itself (which `GOLDEN_FRAME` already names).
4568+ let mut prev2: Option<Picture> = None;
44984569 let mut carried = key.next_cdfs.clone();
44994570 let mut reference = key.reconstruction.clone();
45004571 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
@@ -4515,11 +4586,15 @@ pub(crate) fn encode_sequence_with_ctx(
45154586 order_hint,
45164587 render,
45174588 Some(&carried.0),
4518- Some(&golden), fctx,
4589+ Some(&golden),
4590+ prev2.as_ref(), fctx,
45194591 )?;
45204592 stream.extend_from_slice(&inter.stream);
45214593 carried = inter.next_cdfs.clone();
4522- reference = inter.reconstruction.clone();
4594+ prev2 = Some(std::mem::replace(
4595+ &mut reference,
4596+ inter.reconstruction.clone(),
4597+ ));
45234598 frames.push(crop_encoded(&inter, render.0, render.1));
45244599 }
45254600 Ok(EncodedSequence { stream, frames })
@@ -6552,7 +6627,7 @@ mod tests {
65526627 let padded_pic = picture.padded_to(SUPERBLOCK);
65536628 let t = Instant::now();
65546629 let inter =
6555- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, fctx).unwrap();
6630+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap();
65566631 let inter_t = t.elapsed();
65576632 eprintln!(
65586633 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
@@ -6650,7 +6725,7 @@ mod tests {
66506725 stage_reset();
66516726 let t = Instant::now();
66526727 let inter =
6653- encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, fctx).unwrap();
6728+ encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap();
66546729 let total_t = t.elapsed();
66556730 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
66566731 let accounted = motion_search + transform_quant + entropy;
@@ -6827,7 +6902,7 @@ mod tests {
68276902 q,
68286903 0.5,
68296904 1,
6830- (width, height), None, None, fctx,
6905+ (width, height), None, None, None, fctx,
68316906 )
68326907 .unwrap();
68336908 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
@@ -6844,7 +6919,7 @@ mod tests {
68446919 q,
68456920 0.5,
68466921 1,
6847- (width, height), None, None, fctx,
6922+ (width, height), None, None, None, fctx,
68486923 )
68496924 .unwrap();
68506925 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
crates/ec-av1/src/encoder.rsmodified+8 -0
@@ -234,6 +234,9 @@ pub struct Av1Encoder {
234234 /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`,
235235 /// which stays in DPB slot 1 until the next key frame refreshes it.
236236 golden: Option<Picture>,
237+ /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is
238+ /// about to refresh (`encode_inter_frame`'s 0/2 alternation).
239+ prev2: Option<Picture>,
237240 }
238241
239242 /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
@@ -261,6 +264,7 @@ impl Av1Encoder {
261264 Ok(Self {
262265 carried_cdfs: None,
263266 golden: None,
267+ prev2: None,
264268 color_config: config.colour.color_config(),
265269 config,
266270 reference: None,
@@ -367,6 +371,7 @@ impl Av1Encoder {
367371 render,
368372 self.carried_cdfs.as_ref().map(|c| &c.0),
369373 self.golden.as_ref(),
374+ self.prev2.as_ref(),
370375 &self.fctx,
371376 )?
372377 };
@@ -374,6 +379,9 @@ impl Av1Encoder {
374379 self.carried_cdfs = Some(encoded.next_cdfs.clone());
375380 if is_key {
376381 self.golden = Some(encoded.reconstruction.clone());
382+ self.prev2 = None;
383+ } else {
384+ self.prev2 = self.reference.take();
377385 }
378386 self.reference = Some(encoded.reconstruction.clone());
379387 self.next_index += 1;