diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 73df97da..45db5e06 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -32863,13 +32863,18 @@ pub(crate) fn decode_inter_frame_tile( // inter frames coded Select by default (class: test asserts against a // stale header, second instance). tx_select: bool, + // The CDF state this frame's tile was WRITTEN from (`Encoded::start_cdfs`): + // an inter frame whose header leaves `disable_frame_end_update_cdf` off + // starts from what the previous frame stored, not from the defaults. Same + // class as `tx_select` above, third instance. + initial_cdfs: Option, fctx: &crate::decode::FrameCtx, ) -> Result { decode_inter_frame_tile_lr( data, mi_cols, mi_rows, base_q_idx, frame_width, frame_height, refpix, cdef, loop_filter, allow_high_precision_mv, force_integer_mv, interp_fixed, enable_dual_filter, reference_select, tx_select, - &LoopRestorationParams::default(), fctx, + &LoopRestorationParams::default(), initial_cdfs, fctx, ) } @@ -32893,6 +32898,7 @@ pub(crate) fn decode_inter_frame_tile_lr( reference_select: bool, tx_select: bool, lr: &LoopRestorationParams, + initial_cdfs: Option, fctx: &crate::decode::FrameCtx, ) -> Result { let single_tile = TileInfo { @@ -32913,7 +32919,7 @@ pub(crate) fn decode_inter_frame_tile_lr( cdef, loop_filter, lr, - None, + initial_cdfs, allow_high_precision_mv, force_integer_mv, NO_SIGN_BIAS, @@ -35909,6 +35915,22 @@ mod tests { RefPix::ready(refs) } + /// [`last_only`] plus `GOLDEN_FRAME` (index 4 of the name-keyed array) + /// and `ALTREF_FRAME` (index 7, the frame two back, which the encoder + /// keeps in the slot the current frame refreshes): what a frame this + /// encoder writes needs, since its blocks may name any of the three. + fn last_golden_altref<'a>( + last: &'a Picture, + golden: &'a Picture, + altref: Option<&'a Picture>, + ) -> RefPix<'a> { + let mut refs: [Option<&Picture>; 8] = [None; 8]; + refs[1] = Some(last); + refs[4] = Some(golden); + refs[7] = altref; + RefPix::ready(refs) + } + /// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and /// a pre-resolved damping shift instead of a bounds-testing closure and a @@ -37050,6 +37072,7 @@ mod tests { false, false, false, + None, fctx, ) .unwrap_err(); @@ -37440,7 +37463,11 @@ mod tests { frame.base_q_idx, width as u32, height as u32, - &last_only(&reference), + &last_golden_altref( + &reference, + &encoded.frames[0].reconstruction, + (i >= 2).then(|| &encoded.frames[i - 2].reconstruction), + ), &frame.cdef, &frame.loop_filter, false, @@ -37450,6 +37477,7 @@ mod tests { false, frame.tx_select, &frame.loop_restoration, + Some(frame.start_cdfs.0.clone()), fctx, ) .unwrap(); @@ -37753,7 +37781,11 @@ mod tests { frame.base_q_idx, coded_w, coded_h, - &last_only(&reference), + &last_golden_altref( + &reference, + &encoded.frames[0].reconstruction, + (i >= 2).then(|| &encoded.frames[i - 2].reconstruction), + ), &frame.cdef, &frame.loop_filter, false, @@ -37763,6 +37795,7 @@ mod tests { false, frame.tx_select, &frame.loop_restoration, + Some(frame.start_cdfs.0.clone()), fctx, ) .unwrap(); diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 07e7147a..921bdd0f 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -491,12 +491,25 @@ pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> En mi_rows: encoded.mi_rows, base_q_idx: encoded.base_q_idx, tx_select: encoded.tx_select, + start_cdfs: encoded.start_cdfs.clone(), + next_cdfs: encoded.next_cdfs.clone(), loop_filter: encoded.loop_filter, loop_restoration: encoded.loop_restoration, cdef: encoded.cdef, } } +/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of +/// numbers nobody wants printed, and [`Encoded`] derives `Debug`. +#[derive(Clone)] +pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs); + +impl std::fmt::Debug for CdfSnapshot { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("CdfSnapshot") + } +} + /// What one call to [`encode_key_frame`] produced. #[derive(Clone, Debug)] pub struct Encoded { @@ -530,6 +543,18 @@ pub struct Encoded { /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first /// block. pub(crate) tx_select: bool, + /// The CDF state this frame's tile writer started from -- the defaults + /// for a key frame and for the first inter frame, and the previous + /// frame's stored tables after that. A test that decodes `tile` directly + /// must feed the decoder this, exactly as `decode_stream` feeds it what + /// the frame's `primary_ref_frame` slot holds (same class as + /// `tx_select`: a header bit a raw tile decode cannot guess). + pub(crate) start_cdfs: CdfSnapshot, + /// What this frame stores into the slots it refreshes (spec 7.20, + /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the + /// counts reset when `disable_frame_end_update_cdf` is off, and what it + /// started from when it is on. + pub(crate) next_cdfs: CdfSnapshot, /// This frame header's chosen deblocking parameters /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the /// picture the decoder produces UNDER them, so a test that decodes @@ -708,6 +733,11 @@ pub(crate) fn key_frame_headers_colour( Ok((seq, header)) } +/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the +/// key frame refreshes all eight slots, each inter frame only slot 0, so slot +/// 1 still holds the key frame however long the GOP runs. +pub const GOLDEN_SLOT: u8 = 1; + /// 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, @@ -721,6 +751,26 @@ pub fn inter_frame_headers( base_q_idx: u8, order_hint: u32, last_slot: u8, +) -> Result<(SequenceHeader, FrameHeader)> { + inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot) +} + +/// [`inter_frame_headers`] with the three slots named apart: the one read as +/// `LAST_FRAME`, the one this frame refreshes, and the one read as +/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2 +/// so that the frame two back is still intact in the slot this one is about +/// to overwrite -- read before write, spec 7.20's decode order. +/// +/// # Errors +/// As [`inter_frame_headers`]. +pub fn inter_frame_headers_slots( + width: usize, + height: usize, + base_q_idx: u8, + order_hint: u32, + last_slot: u8, + self_slot: u8, + altref_slot: u8, ) -> Result<(SequenceHeader, FrameHeader)> { let (seq, key) = key_frame_headers(width, height, base_q_idx)?; let header = FrameHeader { @@ -729,12 +779,25 @@ pub fn inter_frame_headers( show_frame: true, error_resilient_mode: false, disable_cdf_update: false, - disable_frame_end_update_cdf: true, + // The tile writer hands its end-of-tile tables to the next frame + // (`encode_sequence_with_ctx`), so the frame stores them the way the + // decoder will load them (spec 7.20). + disable_frame_end_update_cdf: false, force_integer_mv: false, order_hint, primary_ref_frame: 0, - refresh_frame_flags: 1 << last_slot, - ref_frame_idx: [last_slot; ec_av1_syntax::REFS_PER_FRAME], + refresh_frame_flags: 1 << self_slot, + // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`) + // names the slot this frame both predicts from and refreshes; + // GOLDEN names slot 1, which the key frame wrote when it refreshed + // all eight and which no inter frame ever overwrites, so it holds + // the key frame's own picture for the whole GOP. + ref_frame_idx: { + let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME]; + idx[3] = GOLDEN_SLOT; + idx[6] = altref_slot; + idx + }, allow_high_precision_mv: false, interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, is_motion_mode_switchable: false, @@ -2357,8 +2420,10 @@ fn code_square_inter( eight: None, tx_depth, inter: Some(InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewMv, mv: new_mv, + ref_mv_idx: 0, }), }, cost + dcost, @@ -2382,8 +2447,10 @@ fn code_square_inter( eight: None, tx_depth, inter: Some(InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv, + ref_mv_idx: 0, }), }, inter_cost + dcost) } else { @@ -2399,7 +2466,7 @@ fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: O let info = match inter { Some(info) => MiInfo { is_inter: true, - ref_frame: LAST_FRAME, + ref_frame: info.ref_frame, ref_frame1: NO_REF1, mv1: (0, 0), mv: mv16(info.mv), @@ -3044,13 +3111,21 @@ pub(crate) fn encode_key_frame_inner( #[cfg(test)] record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); + // A key frame always starts from the defaults (`primary_ref_frame` is + // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf` + // set, so what it stores into the slots it refreshes is exactly those + // defaults again (spec 7.20's `started_from` arm) -- the first inter + // frame after it therefore starts from the defaults too. let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); - let mut tile = crate::tile::sb_coeff_key_frame_tile_tx( + let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); + let start_cdfs = CdfSnapshot(cdfs.clone()); + let mut tile = crate::tile::sb_coeff_key_frame_tile_cdfs( mi_cols, mi_rows, base_q_idx, &superblocks, tx_select, + &mut cdfs, )?; // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing // the tile just coded back to the decoder under each candidate (see @@ -3072,15 +3147,21 @@ pub(crate) fn encode_key_frame_inner( &mut tile, search.lambda, fctx, + // Every re-code starts from this frame's OWN starting tables, never + // from where the first write left them: the second tile is the same + // symbol sequence plus new ones, so it must adapt from the same + // point the decoder will. |bits, sb_cols, grid, units| { crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); - crate::tile::sb_coeff_key_frame_tile_tx( + let mut cdfs = start_cdfs.0.clone(); + crate::tile::sb_coeff_key_frame_tile_cdfs( mi_cols, mi_rows, base_q_idx, &superblocks, tx_select, + &mut cdfs, ) }, |lf, cdef, h, tile, lr| { @@ -3124,6 +3205,8 @@ pub(crate) fn encode_key_frame_inner( mi_rows: header.mi_rows, base_q_idx, tx_select, + next_cdfs: start_cdfs.clone(), + start_cdfs, loop_filter: header.loop_filter, cdef: header.cdef, loop_restoration: header.loop_restoration, @@ -3483,7 +3566,13 @@ fn search_inter_block( search: &Search, mode_bits: &[f64; 13], reference: &Picture, - stack: &MvStack, fctx: &crate::decode::FrameCtx, + stack: &MvStack, + // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1 + // for the whole GOP, with the stack this block derives against it. Only + // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a + // second motion search would double the wall of the stage that already + // owns most of it. + extra: &[(i8, &Picture, &MvStack)], fctx: &crate::decode::FrameCtx, ) -> (BlockCoeffs, f64) { // `luma_set` is the INTRA candidates' table; the two inter candidates // below price their coefficients through `TxbSet::Luma32Inter`, which is @@ -3496,9 +3585,17 @@ fn search_inter_block( // function's doc comment. 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)); - let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) - + symbol_bits(&cdf::SINGLE_REF[0][2], 0) - + symbol_bits(&cdf::SINGLE_REF[0][3], 0); + // `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. + let single_ref_bits = |ref_frame: i8| { + symbol_bits(&cdf::SINGLE_REF[0][0], 0) + + if ref_frame == crate::mvstack::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) + } + }; struct Candidate { cost: f64, @@ -3631,100 +3728,72 @@ fn search_inter_block( chroma[1].true_width, chroma[1].true_height, ); - let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV - + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero - + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV - - // The NEARESTMV candidate: `skip` is decided below from whether its - // trial actually found a nonzero level, once its residual is priced - // against the same CDFs the tile writer codes it with. - // - // lane-av1speed: its three trials are kept (rather than moved straight - // into the candidate) so that a NEWMV landing on the very same vector -- - // common on static content, where the stack's nearest vector is also - // what the search finds -- reuses them instead of running the same - // motion compensation, transform, quantize and reconstruct again. The - // reused trials are the same values, so the choice is bit-identical. - let nearest_trials; - { - let mv = stack.nearest_mv; - let luma_trial = mc_trial( - luma, - x, - y, - BLOCK, - mv, - true, - ref_luma.0, - ref_luma.1, - ref_luma.2, - ref_luma.3, - false, - search.base_q_idx, - search.deadzone, - TxbSet::Luma32Inter, fctx, - ); - let u = mc_trial( - &chroma[0], - x / 2, - y / 2, - BLOCK / 2, - mv, - false, - ref_u.0, - ref_u.1, - ref_u.2, - ref_u.3, - false, - search.base_q_idx, - search.deadzone, - chroma_set, fctx, - ); - let v = mc_trial( - &chroma[1], - x / 2, - y / 2, - BLOCK / 2, - mv, - false, - ref_v.0, - ref_v.1, - ref_v.2, - ref_v.3, - false, - search.base_q_idx, - search.deadzone, - chroma_set, fctx, - ); - let skip = luma_trial.levels.iter().all(|&l| l == 0) - && u.levels.iter().all(|&l| l == 0) - && v.levels.iter().all(|&l| l == 0); - let cost = luma_trial.sse - + u.sse - + v.sse - + search.lambda - * (skip_bits(skip) - + intra_inter_bits(true) - + single_ref_bits - + mode_bits_inter - + if skip { - 0.0 - } else { - luma_trial.bits + u.bits + v.bits - }); - nearest_trials = (luma_trial.clone(), u.clone(), v.clone()); - consider(Candidate { - cost, - luma: luma_trial, - u, - v, - mode: DC_PRED, - skip, - inter: Some(InterInfo { + // Every single-reference mode the writer can code (spec 5.11.24's symbol + // chain, mirrored by `tile::write_inter_mode`), priced with the static + // CDFs at this block's own stack contexts. A candidate is a motion + // vector plus the cheapest syntax that reaches it, so two modes landing + // on the same vector share one set of trials: the added modes cost + // mode-bit arithmetic, not another motion compensation. + let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); + let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); + // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry + // past `start`, `1` to advance and `0` to stop, at most two. A `target` + // the loop cannot reach is never offered below -- every candidate's + // index is one this same loop walks to. + let drl_bits = |start: usize, target: usize| { + let mut bits = 0.0; + let mut idx = start; + while idx < start + 2 && stack.entries.len() > idx + 1 { + let advance = idx < target; + bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); + if !advance { + break; + } + idx += 1; + } + bits + }; + let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME); + let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ + ( + stack.nearest_mv, + last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), + InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, - mv, - }), - }); + mv: stack.nearest_mv, + ref_mv_idx: 0, + }, + ), + // GLOBALMV is the identity model's zero vector -- this encoder writes + // no `gm_params` -- and the cheapest syntax of the four on the static + // content where that vector is also the right one. + ( + (0, 0), + last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), + InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, + mode: InterMode::GlobalMv, + mv: (0, 0), + ref_mv_idx: 0, + }, + ), + ]; + let near_bits = + last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); + for idx in 1..=2usize { + if let Some(e) = stack.entries.get(idx) { + cands.push(( + e.mv, + near_bits + drl_bits(1, idx), + InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, + mode: InterMode::NearMv, + mv: e.mv, + ref_mv_idx: idx as u8, + }, + )); + } } let source_block = luma.source_block(x, y, BLOCK); @@ -3746,96 +3815,157 @@ fn search_inter_block( #[cfg(test)] stage_add(0, t.elapsed()); let mv = round_to_valid_mv(found.mv, stack.pred_mv); - if let Some(mv_bits) = mv_residual_bits(mv, stack.pred_mv) { - let (luma_trial, u, v) = if mv == stack.nearest_mv { - nearest_trials - } else { - ( - mc_trial( - luma, - x, - y, - BLOCK, - mv, - true, - ref_luma.0, - ref_luma.1, - ref_luma.2, - ref_luma.3, - false, - search.base_q_idx, - search.deadzone, - TxbSet::Luma32Inter, fctx, - ), - mc_trial( - &chroma[0], - x / 2, - y / 2, - BLOCK / 2, - mv, - false, - ref_u.0, - ref_u.1, - ref_u.2, - ref_u.3, - false, - search.base_q_idx, - search.deadzone, - chroma_set, fctx, - ), - mc_trial( - &chroma[1], - x / 2, - y / 2, - BLOCK / 2, - mv, - false, - ref_v.0, - ref_v.1, - ref_v.2, - ref_v.3, - false, - search.base_q_idx, - search.deadzone, - chroma_set, fctx, - ), - ) - }; - let drl_bits = if stack.entries.len() > 1 { - symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0) - } else { - 0.0 - }; - let skip = luma_trial.levels.iter().all(|&l| l == 0) - && u.levels.iter().all(|&l| l == 0) - && v.levels.iter().all(|&l| l == 0); - let cost = luma_trial.sse - + u.sse - + v.sse - + search.lambda - * (skip_bits(skip) - + intra_inter_bits(true) - + single_ref_bits - + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) - + drl_bits - + mv_bits - + if skip { - 0.0 - } else { - luma_trial.bits + u.bits + v.bits - }); - consider(Candidate { - cost, - luma: luma_trial, - u, - v, - mode: DC_PRED, - skip, - inter: Some(InterInfo { + // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so + // the same vector costs a different residual from each: take the index + // whose residual plus DRL bits is cheapest, not entry 0 by default. + let mut best_new: Option<(f64, u8)> = None; + for idx in 0..3usize { + if idx > 0 && stack.entries.len() <= idx { + break; + } + let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); + if let Some(b) = mv_residual_bits(mv, base) { + let total = b + drl_bits(0, idx); + if best_new.is_none_or(|(t, _)| total < t) { + best_new = Some((total, idx as u8)); + } + } + } + if let Some((bits, ref_mv_idx)) = best_new { + cands.push(( + mv, + last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, + InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewMv, mv, - }), - }); + ref_mv_idx, + }, + )); + } + + for &(ref_frame, _, gstack) in extra { + let g_ref_bits = single_ref_bits(ref_frame); + let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); + cands.push(( + gstack.nearest_mv, + g_ref_bits + + g_not_new + + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1) + + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0), + InterInfo { + ref_frame, + mode: InterMode::NearestMv, + mv: gstack.nearest_mv, + ref_mv_idx: 0, + }, + )); + cands.push(( + (0, 0), + g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0), + InterInfo { + ref_frame, + mode: InterMode::GlobalMv, + mv: (0, 0), + ref_mv_idx: 0, + }, + )); + } + + // One trial set per distinct (reference, vector) pair: sort, cheapest + // syntax first, and drop the rest of each pair's run. + cands.sort_by(|a, b| { + (a.2.ref_frame, a.0) + .cmp(&(b.2.ref_frame, b.0)) + .then(a.1.total_cmp(&b.1)) + }); + cands.dedup_by_key(|c| (c.2.ref_frame, c.0)); + { + for (mv, mode_bits_inter, info) in cands { + let (ref_luma, ref_u, ref_v) = match extra + .iter() + .find(|(r, _, _)| *r == info.ref_frame) + { + Some(&(_, g, _)) => ( + (&g.y, g.width, luma.true_width, luma.true_height), + (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height), + (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height), + ), + None => (ref_luma, ref_u, ref_v), + }; + let luma_trial = mc_trial( + luma, + x, + y, + BLOCK, + mv, + true, + ref_luma.0, + ref_luma.1, + ref_luma.2, + ref_luma.3, + false, + search.base_q_idx, + search.deadzone, + TxbSet::Luma32Inter, fctx, + ); + let u = mc_trial( + &chroma[0], + x / 2, + y / 2, + BLOCK / 2, + mv, + false, + ref_u.0, + ref_u.1, + ref_u.2, + ref_u.3, + false, + search.base_q_idx, + search.deadzone, + chroma_set, fctx, + ); + let v = mc_trial( + &chroma[1], + x / 2, + y / 2, + BLOCK / 2, + mv, + false, + ref_v.0, + ref_v.1, + ref_v.2, + ref_v.3, + false, + search.base_q_idx, + search.deadzone, + chroma_set, fctx, + ); + let skip = luma_trial.levels.iter().all(|&l| l == 0) + && u.levels.iter().all(|&l| l == 0) + && v.levels.iter().all(|&l| l == 0); + let cost = luma_trial.sse + + u.sse + + v.sse + + search.lambda + * (skip_bits(skip) + + intra_inter_bits(true) + + mode_bits_inter + + if skip { + 0.0 + } else { + luma_trial.bits + u.bits + v.bits + }); + consider(Candidate { + cost, + luma: luma_trial, + u, + v, + mode: DC_PRED, + skip, + inter: Some(info), + }); + } } let best = best.expect("the search offers at least the intra modes"); @@ -3867,7 +3997,20 @@ pub(crate) fn encode_inter_frame( base_q_idx: u8, deadzone: f64, order_hint: u32, - render: (usize, usize), fctx: &crate::decode::FrameCtx, + render: (usize, usize), + // The tables this frame's writer starts from: what the previous frame + // stored into the slot this one's `primary_ref_frame` names. `None` + // starts from the defaults, which is right only for the frame straight + // after a key frame. + start_cdfs: Option<&crate::cdf_state::Cdfs>, + // The key frame's own (padded) reconstruction, which every frame of the + // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame + // with `LAST_FRAME` alone, exactly as before. + golden: Option<&Picture>, + // 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, ) -> Result { picture.check()?; if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { @@ -3890,14 +4033,33 @@ pub(crate) fn encode_inter_frame( // overwrites slot 0, so the frame just coded is always what the next one // predicts against. const LAST_SLOT: u8 = 0; + // Slot 0 and slot 2 alternate so the frame two back survives one more + // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2) + // and the picture this frame names as `ALTREF_FRAME` is the one sitting + // in the very slot it will overwrite. + let self_slot = if order_hint % 2 == 1 { 0 } else { 2 }; + let last_slot = if order_hint <= 1 { + LAST_SLOT + } else if (order_hint - 1) % 2 == 1 { + 0 + } else { + 2 + }; // `render`, not `picture.width`/`picture.height`: `picture` here is // already padded to a whole number of superblocks (`encode_sequence`'s // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so // every true-edge clamp downstream) must come from the frame's real, // unpadded size, same as `key_frame_headers_colour` takes `render` and // not the padded picture in `encode_key_frame_inner`. - let (seq, mut header) = - inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?; + let (seq, mut header) = inter_frame_headers_slots( + render.0, + render.1, + base_q_idx, + order_hint, + last_slot, + self_slot, + if altref.is_some() { self_slot } else { GOLDEN_SLOT }, + )?; header.render_width = render.0 as u32; header.render_height = render.1 as u32; // `TxMode::Select` here too: an inter block then codes one `txfm_split` @@ -4002,6 +4164,25 @@ pub(crate) fn encode_inter_frame( let (mi_row, mi_col) = (r32 * 8, c32 * 8); 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::GOLDEN_FRAME, golden), + (crate::mvstack::ALTREF_FRAME, altref), + ] + .into_iter() + .filter_map(|(r, pic)| { + pic.map(|p| { + ( + r, + p, + find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows), + ) + }) + }) + .collect(); + let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks + .iter() + .map(|(r, p, st)| (*r, *p, st)) + .collect(); let base = snapshot(&luma, &chroma, (x, y), BLOCK); let (block, mut cost_whole) = search_inter_block( @@ -4011,7 +4192,8 @@ pub(crate) fn encode_inter_frame( &search, &mode_bits_table, reference, - &stack, fctx, + &stack, + &extra, fctx, ); cost_whole += search.lambda * partition_bits(BLOCK, false); let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); @@ -4331,13 +4513,22 @@ pub(crate) fn encode_inter_frame( / modes.len() as f64; #[cfg(test)] record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); + // This frame's header leaves `disable_frame_end_update_cdf` off, so it + // stores its end-of-tile tables with the counts reset (spec 7.20) and the + // next frame's writer starts from them -- exactly what + // `crate::stream::stored_cdfs_for` hands the decoder. let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); - let mut tile = crate::tile::sb_coeff_inter_frame_tile_tx( + let mut cdfs = start_cdfs + .cloned() + .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); + let start_cdfs = CdfSnapshot(cdfs.clone()); + let mut tile = crate::tile::sb_coeff_inter_frame_tile_cdfs( mi_cols, mi_rows, base_q_idx, &blocks, tx_select, + &mut cdfs, )?; // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs // this tile against the same single-slot reference this encoder predicted @@ -4347,6 +4538,7 @@ pub(crate) fn encode_inter_frame( // reference whose height is not the header's own `frame_height` (spec // 7.9's compatible-size rule), and the chained-decode round trips prove // the two predict identically. + let end_cdfs = std::cell::RefCell::new(cdfs); let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); let trial_ref = if (reference.width, reference.height) == (fw, fh) { reference.clone() @@ -4359,8 +4551,39 @@ pub(crate) fn encode_inter_frame( v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), } }; + // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1, + // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose + // blocks may name GOLDEN needs that plane too, cropped the same way. + let trial_golden = golden.map(|g| { + if (g.width, g.height) == (fw, fh) { + g.clone() + } else { + Picture { + width: fw, + height: fh, + y: crop_plane(&g.y, g.width, fw, fh), + u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2), + v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2), + } + } + }); + let trial_altref = altref.map(|a| { + if (a.width, a.height) == (fw, fh) { + a.clone() + } else { + Picture { + width: fw, + height: fh, + y: crop_plane(&a.y, a.width, fw, fh), + u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2), + v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2), + } + } + }); let mut refs: [Option<&Picture>; 8] = [None; 8]; refs[1] = Some(&trial_ref); + refs[4] = trial_golden.as_ref(); + refs[7] = trial_altref.as_ref(); let refpix = crate::decode::RefPix::ready(refs); // The luma restoration-unit grid this frame's `lr_params` implies // (`av1_lr_count_units` rounds to nearest, so a short last unit is @@ -4381,16 +4604,26 @@ pub(crate) fn encode_inter_frame( &mut tile, search.lambda, fctx, + // As in `encode_key_frame_inner`, but this frame's end-of-tile tables + // are what the NEXT frame writes from, so the winning re-code + // publishes its own into `end_cdfs` -- the first write's are stale + // the moment a second tile is coded. |bits, sb_cols, grid, units| { crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); - crate::tile::sb_coeff_inter_frame_tile_tx( + let mut cdfs = start_cdfs.0.clone(); + let coded = crate::tile::sb_coeff_inter_frame_tile_cdfs( mi_cols, mi_rows, base_q_idx, &blocks, tx_select, - ) + &mut cdfs, + ); + if coded.is_ok() { + *end_cdfs.borrow_mut() = cdfs; + } + coded }, |lf, cdef, h, tile, lr| { crate::decode::decode_inter_frame_tile_lr( @@ -4410,10 +4643,17 @@ pub(crate) fn encode_inter_frame( h.reference_select, tx_select, lr, + // The trial decode re-reads the tile the writer just wrote, + // so it starts from the same tables the writer did (this + // frame's `start_cdfs`), not from the defaults. + Some(start_cdfs.0.clone()), fctx, ) }, )?; + let mut cdfs = end_cdfs.into_inner(); + cdfs.reset_counts(); + let next_cdfs = CdfSnapshot(cdfs); let mut stream = temporal_delimiter(); stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); @@ -4434,6 +4674,8 @@ pub(crate) fn encode_inter_frame( mi_rows: header.mi_rows, base_q_idx, tx_select, + start_cdfs, + next_cdfs, loop_filter: header.loop_filter, cdef: header.cdef, loop_restoration: header.loop_restoration, @@ -4495,6 +4737,14 @@ pub(crate) fn encode_sequence_with_ctx( unspecified_color_config(), fctx, )?; let mut stream = key.stream.clone(); + // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the + // key frame refreshes every slot, each inter frame only slot 0), which is + // what `GOLDEN_FRAME` names. + let golden = key.reconstruction.clone(); + // The frame two back, once there is one that is not the key frame + // itself (which `GOLDEN_FRAME` already names). + let mut prev2: Option = None; + let mut carried = key.next_cdfs.clone(); let mut reference = key.reconstruction.clone(); let mut frames = vec![crop_encoded(&key, render.0, render.1)]; for (i, picture) in rest.iter().enumerate() { @@ -4512,10 +4762,17 @@ pub(crate) fn encode_sequence_with_ctx( base_q_idx, deadzone, order_hint, - render, fctx, + render, + Some(&carried.0), + Some(&golden), + prev2.as_ref(), fctx, )?; stream.extend_from_slice(&inter.stream); - reference = inter.reconstruction.clone(); + carried = inter.next_cdfs.clone(); + prev2 = Some(std::mem::replace( + &mut reference, + inter.reconstruction.clone(), + )); frames.push(crop_encoded(&inter, render.0, render.1)); } Ok(EncodedSequence { stream, frames }) @@ -4925,15 +5182,19 @@ mod tests { eight: None, tx_depth: 0, inter: Some(InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), + ref_mv_idx: 0, }), }; let skipped_block = BlockCoeffs { skip: true, inter: Some(InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), + ref_mv_idx: 0, }), ..BlockCoeffs::default() }; @@ -6544,7 +6805,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, (width, height), fctx).unwrap(); + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap(); let inter_t = t.elapsed(); eprintln!( "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ @@ -6642,7 +6903,7 @@ mod tests { stage_reset(); let t = Instant::now(); let inter = - encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), fctx).unwrap(); + encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height), None, None, None, fctx).unwrap(); let total_t = t.elapsed(); let [motion_search, interpolation, transform_quant, entropy] = stage_read(); let accounted = motion_search + transform_quant + entropy; @@ -6819,7 +7080,7 @@ mod tests { q, 0.5, 1, - (width, height), fctx, + (width, height), None, None, None, fctx, ) .unwrap(); let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); @@ -6836,7 +7097,7 @@ mod tests { q, 0.5, 1, - (width, height), fctx, + (width, height), None, None, None, fctx, ) .unwrap(); let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); @@ -7221,6 +7482,12 @@ mod tests { /// /// The BD gate above measures quality, which a speed lane can move by a /// hair without failing anything; this pins the streams themselves. + /// Re-measured on the lane-av1lr merge with main d5fc99e0: the per-64x64 + /// `cdef_idx` literals and the per-unit loop restoration syntax are new + /// bits in the tile, so the streams move (q=150 7416 -> 7458 bytes, + /// q=60 27927 -> 27807 -- the low-rate frame pays for the syntax, the + /// high-rate one more than earns it back). + /// /// Every number below was measured 2026-09-06: first on lane-av1fwd /// (whose three speed steps left them identical to `a6649c4e`'s), then /// re-measured on the lane-av1lr merge, which legitimately moves them -- @@ -7248,7 +7515,7 @@ mod tests { }) }; let pins: [(u8, usize, u64); 2] = - [(150, 7796, 0x70db_e81d_606b_034c), (60, 28182, 0xb23d_005b_1f2e_e008)]; + [(150, 7458, 0x7eb2_33c6_bd96_3baf), (60, 27807, 0xeee0_f1e5_e099_46bd)]; for (q, bytes, hash) in pins { let encoded = encode_sequence(&source, q, 0.5).unwrap(); assert_eq!( @@ -7409,11 +7676,34 @@ mod tests { let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); let _ = take_partition_hits(); let _ = take_uv_mode_hits(); + let _ = crate::tile::take_inter_mode_hits(); + let _ = crate::tile::take_drl_hits(); + let _ = crate::tile::take_ref_hits(); let (ours, ours_wall) = our_ladder(&source, width, height, fctx); // How often the inter split actually fired over this clip's four // encodes, against the whole 32x32 that was the only outcome // before (gate-blind-to-feature). let [whole32, split32, whole16, split16] = take_partition_hits(); + // Which inter modes actually fired over this clip's four encodes, + // and at which DRL index -- a mode nobody picks is a mode the BD + // number cannot be crediting (gate-blind-to-feature). + let [nearest, near, global, new] = crate::tile::take_inter_mode_hits(); + let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits(); + let refs = crate::tile::take_ref_hits(); + let modes_total = (nearest + near + global + new).max(1); + eprintln!( + "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \ + GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \ + {drl0}/{drl1}/{drl2}/{drl3}", + 100.0 * nearest as f64 / modes_total as f64, + 100.0 * near as f64 / modes_total as f64, + 100.0 * global as f64 / modes_total as f64, + 100.0 * new as f64 / modes_total as f64, + ); + eprintln!( + "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})", + refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6] + ); eprintln!( "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \ 16x16 leaves split into 8s {split16} of {} ({:.1}%)", diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs index bd8943d6..300f6d53 100644 --- a/crates/ec-av1/src/encoder.rs +++ b/crates/ec-av1/src/encoder.rs @@ -226,6 +226,17 @@ pub struct Av1Encoder { /// thread-local. One per encoder, never per frame: several of its fields /// (the inter-frame inheritance guards) carry state ACROSS frames. fctx: crate::decode::FrameCtx, + /// What the last coded frame stored into the reference slot the next + /// inter frame reads (spec 7.20): the tables that frame's tile writer + /// must start from, since the header leaves + /// `disable_frame_end_update_cdf` off. `None` before the first frame. + carried_cdfs: Option, + /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`, + /// which stays in DPB slot 1 until the next key frame refreshes it. + golden: Option, + /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is + /// about to refresh (`encode_inter_frame`'s 0/2 alternation). + prev2: Option, } /// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are @@ -251,6 +262,9 @@ impl Av1Encoder { // then. Picture::grey(config.width, config.height).check_even()?; Ok(Self { + carried_cdfs: None, + golden: None, + prev2: None, color_config: config.colour.color_config(), config, reference: None, @@ -355,10 +369,20 @@ impl Av1Encoder { DEADZONE, order as u32, render, + self.carried_cdfs.as_ref().map(|c| &c.0), + self.golden.as_ref(), + self.prev2.as_ref(), &self.fctx, )? }; + self.carried_cdfs = Some(encoded.next_cdfs.clone()); + if is_key { + self.golden = Some(encoded.reconstruction.clone()); + self.prev2 = None; + } else { + self.prev2 = self.reference.take(); + } self.reference = Some(encoded.reconstruction.clone()); self.next_index += 1; let cropped = crop_encoded(&encoded, render.0, render.1); diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index a8f9aede..6d9ccb21 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -2399,6 +2399,7 @@ pub struct CompoundTplArgs<'a> { /// two-valued test: "is there an inter neighbour at all". `has_inter` /// gathers that over the block's whole span, the way spec 5.11.39 reads any /// neighbour-derived context. +#[cfg(test)] pub(crate) fn single_ref_ctx(has_inter_neighbour: bool) -> usize { if has_inter_neighbour { 2 } else { 1 } } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index da25c40c..381638d7 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3396,7 +3396,13 @@ mod tests { // Frame 1: hand-coded, intra-only, refreshes slot 0 with a flat // 128 block (no neighbours to predict `DC_PRED` from). - let (_, header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap(); + let (_, mut header1) = inter_frame_headers(width, height, base_q_idx, 1, 0).unwrap(); + // These two tiles are hand-coded from a FRESH `Cdfs`, so the + // frames must not carry CDF state the way the encoder's own inter + // frames now do (spec 7.20): with the bit set, what each frame + // stores is what it started from -- the defaults -- which is + // exactly what the next hand-coded tile assumes. + header1.disable_frame_end_update_cdf = true; let tile1 = { let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); let mut enc = SymbolEncoder::new(); @@ -3414,6 +3420,7 @@ mod tests { // Frame 2: hand-coded, single_ref all the way to GOLDEN_FRAME, // skip zero-MV NEARESTMV -- a direct copy of slot 3 (frame 0). let (_, mut header2) = inter_frame_headers(width, height, base_q_idx, 2, 0).unwrap(); + header2.disable_frame_end_update_cdf = true; header2.ref_frame_idx[3] = 3; // GOLDEN_FRAME's own slot: frame 0's, untouched by frame 1 let tile2 = { let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 1f4a3ea4..8d5613fe 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -18,7 +18,7 @@ use crate::cdf; use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect}; use crate::msac::SymbolEncoder; -use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx}; +use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16}; // --------------------------------------------------------------------------- // lane-av1lr: per-64x64 `cdef_idx` (spec 5.11.56, `read_cdef`). The decoder @@ -293,7 +293,7 @@ const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19); /// The coefficient q-context (spec 8.3.2's `Get_Qctx`, `Default_..._Cdf`'s /// leading index) a frame's `base_q_idx` picks its default CDFs from. /// [`crate::cdf`] carries all four, one constant set per context. -fn q_ctx_of(base_q_idx: u8) -> usize { +pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize { match base_q_idx { 0..=20 => 0, 21..=60 => 1, @@ -645,16 +645,21 @@ pub struct BlockCoeffs { pub tx_depth: u8, } -/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec -/// 5.11.24 `read_inter_mode`), reduced to the two branches its symbol chain -/// needs to prove out: the stack's own top candidate outright, or a coded -/// residual against it. `NEARMV`/`GLOBALMV` are never written. +/// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take: the whole +/// single-reference set of spec 5.11.24 `read_inter_mode`, each written by +/// [`write_inter_mode`] with the decoder's own contexts. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum InterMode { /// `NEARESTMV`: takes `MvStack::nearest_mv` outright, no residual, no DRL. NearestMv, - /// `NEWMV`: codes `mv` as a residual against `MvStack::pred_mv`, through - /// a DRL index this writer always leaves at zero. + /// `NEARMV`: takes the stack entry [`InterInfo::ref_mv_idx`] names + /// (clamped to at least 1, the spec's own `RefMvIdx` base for this mode). + NearMv, + /// `GLOBALMV`: the identity global model's zero vector, two symbols and + /// no MV at all. + GlobalMv, + /// `NEWMV`: codes `mv` as a residual against the stack entry + /// [`InterInfo::ref_mv_idx`] names. NewMv, } @@ -668,6 +673,14 @@ pub struct InterInfo { pub mode: InterMode, /// The motion vector a [`InterMode::NewMv`] block's residual targets. pub mv: (i32, i32), + /// The reference this block predicts from (`LAST_FRAME`..=`ALTREF_FRAME`, + /// spec 6.10.24's alphabet), written by [`write_single_ref`]. + pub ref_frame: i8, + /// The block's `RefMvIdx` (spec 5.11.24 `read_drl_idx`): which + /// `MvStack::entries` slot `NEWMV` codes its residual against, or + /// `NEARMV` takes outright. Ignored by the two modes that code no DRL + /// index (`NEARESTMV`, `GLOBALMV`). + pub ref_mv_idx: u8, } impl From> for BlockCoeffs { @@ -833,6 +846,12 @@ struct Neighbours { above_inter: Vec, /// The same, down the left edge. left_inter: Vec, + /// The reference each neighbour named, `-1` for an intra or unavailable + /// one -- what the decoder keeps in its own `Neighbours::above_ref` + /// (decode.rs) and feeds `read_single_ref`'s context functions. + above_ref: Vec, + /// The same, down the left edge. + left_ref: Vec, /// The frame's true (unpadded) width and height, in 4x4 mode-info units, /// which is what clamps [`Self::above`]/[`Self::left`] at the edge (spec /// `av1_set_entropy_contexts`): a block whose row or column run spills @@ -876,6 +895,8 @@ impl Neighbours { left_skip: vec![false; rows * (SUB / MI)], above_inter: vec![false; cols * (SUB / MI)], left_inter: vec![false; rows * (SUB / MI)], + above_ref: vec![-1; cols * (SUB / MI)], + left_ref: vec![-1; rows * (SUB / MI)], above_tx: vec![0; cols * (SUB / MI)], left_tx: vec![0; rows * (SUB / MI)], above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], @@ -893,6 +914,7 @@ impl Neighbours { self.left_side_mi.iter_mut().for_each(|s| *s = SB); self.left_skip.iter_mut().for_each(|s| *s = false); self.left_inter.iter_mut().for_each(|i| *i = false); + self.left_ref.iter_mut().for_each(|r| *r = -1); self.left_tx.iter_mut().for_each(|t| *t = 0); self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); } @@ -1092,19 +1114,21 @@ impl Neighbours { /// Writes one inter-frame block's skip flag and inter/intra state into /// every 16x16 column and row it covers, the same span [`Self::record`] /// fills for the coefficient and mode state. - fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool) { + fn record_inter(&mut self, at: (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) { let (r, c) = at; - self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter); + self.record_inter_mi((r * (SUB / MI), c * (SUB / MI)), side, skip, is_inter, ref_frame); } /// [`Self::record_inter`] taking the block's position directly in 4x4 /// mode-info units, for a block finer than one [`SUB`] slot. - fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool) { + fn record_inter_mi(&mut self, (mi_r, mi_c): (usize, usize), side: usize, skip: bool, is_inter: bool, ref_frame: i8) { for cell in 0..side / MI { self.above_skip[mi_c + cell] = skip; self.left_skip[mi_r + cell] = skip; self.above_inter[mi_c + cell] = is_inter; self.left_inter[mi_r + cell] = is_inter; + self.above_ref[mi_c + cell] = ref_frame; + self.left_ref[mi_r + cell] = ref_frame; } } @@ -1198,7 +1222,27 @@ pub fn sb_coeff_key_frame_tile_tx( superblocks: &[Superblock], tx_select: bool, ) -> Result> { - // Consumes whatever `arm_cdef_idx` armed, on every exit path. + let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); + sb_coeff_key_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, superblocks, tx_select, &mut cdfs) +} + +/// [`sb_coeff_key_frame_tile_tx`] starting from -- and leaving behind -- the +/// caller's own CDF state, which is what a frame whose +/// `disable_frame_end_update_cdf` is off needs: the next frame's writer must +/// start where this tile ended (spec 7.20, mirrored by +/// `crate::stream::stored_cdfs_for`). +/// +/// # Errors +/// As [`sb_coeff_key_frame_tile_tx`]. +pub(crate) fn sb_coeff_key_frame_tile_cdfs( + mi_cols: u32, + mi_rows: u32, + _base_q_idx: u8, + superblocks: &[Superblock], + tx_select: bool, + cdfs: &mut Cdfs, +) -> Result> { + // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. let _cdef_idx = CdefIdxGuard; check_blocks(mi_cols, mi_rows)?; let (cols, rows) = block_grid(mi_cols, mi_rows); @@ -1258,7 +1302,7 @@ pub fn sb_coeff_key_frame_tile_tx( // The tile adapts every non-literal CDF it writes, exactly as the decoder // adapts the ones it reads, so the frame header leaves `disable_cdf_update` // off. - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); + let mut cdfs = cdfs; let mut enc = SymbolEncoder::new(); for sb_r in 0..sb_rows { neighbours.start_row(); @@ -2831,6 +2875,205 @@ fn write_mv( Ok(()) } +/// What a block leaves in the neighbour reference bands: its own reference, +/// or `-1` when it is intra (decode.rs `Neighbours::above_ref`'s convention). +fn block_ref(block: &BlockCoeffs) -> i8 { + block.inter.map_or(-1, |i| i.ref_frame) +} + +/// Writer-side counterpart of decode.rs `read_single_ref` (spec 5.11.25's +/// `single_ref_p1`..`p6` tree): codes `ref_frame` bit by bit, each symbol at +/// the context its own `single_ref_p*_ctx` derives from the immediate +/// above/left neighbours' references -- the same functions the decoder calls, +/// with `-1` standing for an intra or unavailable neighbour and no second +/// reference (this writer codes no compound block). +fn write_single_ref( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + ref_frame: i8, + above_ref: i8, + left_ref: i8, +) { + REF_HITS[(ref_frame.max(1) - 1) as usize % 7].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + use crate::mvstack::{ + ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME, + single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, + single_ref_p5_ctx, single_ref_p6_ctx, + }; + let above = (above_ref > 0).then_some(above_ref); + let left = (left_ref > 0).then_some(left_ref); + let backward = ref_frame >= BWDREF_FRAME; + enc.symbol( + usize::from(backward), + &mut cdfs.single_ref[single_ref_p1_ctx(above, None, left, None)][0], + ); + if backward { + let is_altref = ref_frame == ALTREF_FRAME; + enc.symbol( + usize::from(is_altref), + &mut cdfs.single_ref[single_ref_p2_ctx(above, None, left, None)][1], + ); + if !is_altref { + enc.symbol( + usize::from(ref_frame == ALTREF2_FRAME), + &mut cdfs.single_ref[single_ref_p6_ctx(above, None, left, None)][5], + ); + } + return; + } + let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME; + enc.symbol( + usize::from(far), + &mut cdfs.single_ref[single_ref_p3_ctx(above, None, left, None)][2], + ); + if far { + enc.symbol( + usize::from(ref_frame == GOLDEN_FRAME), + &mut cdfs.single_ref[single_ref_p5_ctx(above, None, left, None)][4], + ); + } else { + enc.symbol( + usize::from(ref_frame == LAST2_FRAME), + &mut cdfs.single_ref[single_ref_p4_ctx(above, None, left, None)][3], + ); + } +} + +/// Per-mode fire counts of [`write_inter_mode`], indexed +/// `NEARESTMV`/`NEARMV`/`GLOBALMV`/`NEWMV`, and the DRL index each block +/// coded (bucket 3 collects any index past 2). Read by the BD gate, which +/// is the only thing that proves a newly added mode ever fires +/// (gate-blind-to-feature). +static INTER_MODE_HITS: [std::sync::atomic::AtomicUsize; 4] = [ + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), +]; +static DRL_HITS: [std::sync::atomic::AtomicUsize; 4] = [ + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), +]; + +/// One counter per reference name (`LAST`..`ALTREF`), for the gate's own +/// census of what the encoder actually picks. +static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [ + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), + std::sync::atomic::AtomicUsize::new(0), +]; + +/// Takes and clears the per-reference histogram. +#[cfg(test)] +pub(crate) fn take_ref_hits() -> [usize; 7] { + std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// Bumps the two histograms for one coded inter block. +fn note_inter_mode(mode: usize, drl: usize) { + INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); +} + +/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW). +#[cfg(test)] +pub(crate) fn take_inter_mode_hits() -> [usize; 4] { + [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// Takes and clears the DRL-index histogram (0, 1, 2, 3+). +#[cfg(test)] +pub(crate) fn take_drl_hits() -> [usize; 4] { + [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +/// Writes the DRL index of one block: the loop the decoder runs (spec +/// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one +/// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to +/// stop, at most two bits. `drl_ctx[idx]` is the context between +/// `entries[idx]` and `entries[idx + 1]`, exactly the pair the bit chooses +/// between. +fn write_drl_idx( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + stack: &crate::mvstack::MvStack, + start: usize, + target: usize, +) { + let mut idx = start; + while idx < start + 2 && stack.entries.len() > idx + 1 { + let advance = idx < target; + enc.symbol(usize::from(advance), &mut cdfs.drl_mode[stack.drl_ctx[idx]]); + if !advance { + return; + } + idx += 1; + } +} + +/// Writer-side counterpart of the decoder's single-reference +/// `read_inter_mode`/`assign_mv` chain (decode.rs ~26645): writes `info`'s +/// mode symbols against `stack`'s own contexts and, for `NEWMV`, the MV +/// residual against the DRL-selected predictor. Returns the motion vector +/// the decoder will derive for the block (what the MI grid must record) and +/// whether it is `NEWMV`. +/// +/// `GLOBALMV` resolves to `(0, 0)` because this encoder writes no global +/// motion parameters at all, so every `gm_get_motion_vector` the decoder +/// runs is the identity model's zero vector; a lane that starts writing +/// real `gm_params` has to feed the same vector in here. +/// +/// # Errors +/// As [`write_mv`]: a `NEWMV` residual needing eighth-pel precision. +fn write_inter_mode( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + info: InterInfo, + stack: &crate::mvstack::MvStack, +) -> Result<((i32, i32), bool)> { + let idx = usize::from(info.ref_mv_idx); + match info.mode { + InterMode::NewMv => { + enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); + write_drl_idx(enc, cdfs, stack, 0, idx); + let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); + write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?; + note_inter_mode(3, idx); + Ok((info.mv, true)) + } + InterMode::GlobalMv => { + enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV + enc.symbol(0, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // GLOBALMV + note_inter_mode(2, 0); + Ok(((0, 0), false)) + } + InterMode::NearestMv => { + enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV + enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV + enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV + note_inter_mode(0, 0); + Ok((stack.nearest_mv, false)) + } + InterMode::NearMv => { + enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not NEWMV + enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not GLOBALMV + enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV + // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24). + let idx = idx.max(1); + write_drl_idx(enc, cdfs, stack, 1, idx); + let mv = stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv); + note_inter_mode(1, idx); + Ok((mv, false)) + } + } +} + /// Writes the payload of a one-tile inter frame built from `blocks`, one /// 32x32 block per entry in raster order across the frame — every superblock /// is split into its four quadrants the way [`split_coeff_key_frame_tile`] @@ -2884,7 +3127,24 @@ pub fn sb_coeff_inter_frame_tile_tx( blocks: &[Quadrant], tx_select: bool, ) -> Result> { - // Consumes whatever `arm_cdef_idx` armed, on every exit path. + let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); + sb_coeff_inter_frame_tile_cdfs(mi_cols, mi_rows, base_q_idx, blocks, tx_select, &mut cdfs) +} + +/// [`sb_coeff_inter_frame_tile_tx`] starting from -- and leaving behind -- +/// the caller's own CDF state; see [`sb_coeff_key_frame_tile_cdfs`]. +/// +/// # Errors +/// As [`sb_coeff_inter_frame_tile_tx`]. +pub(crate) fn sb_coeff_inter_frame_tile_cdfs( + mi_cols: u32, + mi_rows: u32, + _base_q_idx: u8, + blocks: &[Quadrant], + tx_select: bool, + cdfs: &mut Cdfs, +) -> Result> { + // Consumes whatever `arm_cdef_idx`/`arm_lr` armed, on every exit path. let _cdef_idx = CdefIdxGuard; check_blocks(mi_cols, mi_rows)?; // `block_grid`'s ceiling, not a plain division: a true frame size that is @@ -2915,9 +3175,6 @@ pub fn sb_coeff_inter_frame_tile_tx( /// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block, the only /// size this writer's inter branch codes. const SIZE_GROUP_32: usize = 3; - /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference this - /// writer's single-reference chain ever names. - const LAST_FRAME: i8 = 1; let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); let mut neighbours = Neighbours::new( @@ -2927,7 +3184,7 @@ pub fn sb_coeff_inter_frame_tile_tx( mi_rows as usize, ); let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize); - let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx)); + let mut cdfs = cdfs; let mut enc = SymbolEncoder::new(); // An `is_inter` block's 32x32 luma transform reads a different // `tx_type` set than an intra block's (`get_tx_set`, spec 5.11.48; see @@ -3214,10 +3471,7 @@ pub fn sb_coeff_inter_frame_tile_tx( let mode_for_tx; if let Some(info) = block.inter { - let sr_ctx = single_ref_ctx(above_inter || left_inter); - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2 - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST + write_single_ref(&mut enc, &mut cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]); let (mi_row, mi_col) = (r32 as usize * 8, c32 as usize * 8); let stack = find_mv_stack( @@ -3226,43 +3480,18 @@ pub fn sb_coeff_inter_frame_tile_tx( mi_col, 8, 8, - LAST_FRAME, + info.ref_frame, mi_cols as usize, mi_rows as usize, ); - let is_new_mv = matches!(info.mode, InterMode::NewMv); - if is_new_mv { - enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV - } else { - enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new - enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero - enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV - } - // This writer always keeps the first DRL candidate, so the - // loop (spec 5.11.24 `read_drl_idx`) only ever runs its - // first, breaking iteration. - if is_new_mv && stack.entries.len() > 1 { - enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]); - } - let mv = if is_new_mv { - write_mv( - &mut enc, - &mut cdfs.mv_comp, - &mut cdfs.mv_joint, - info.mv, - stack.pred_mv, - )?; - info.mv - } else { - stack.nearest_mv - }; + let (mv, is_new_mv) = write_inter_mode(&mut enc, &mut cdfs, info, &stack)?; grid.set( mi_row, mi_col, MiInfo { is_inter: true, - ref_frame: LAST_FRAME, + ref_frame: info.ref_frame, ref_frame1: NO_REF1, mv1: (0, 0), mv: mv16(mv), @@ -3283,7 +3512,7 @@ pub fn sb_coeff_inter_frame_tile_tx( mi_col + dc, MiInfo { is_inter: true, - ref_frame: LAST_FRAME, + ref_frame: info.ref_frame, ref_frame1: NO_REF1, mv1: (0, 0), mv: mv16(mv), @@ -3388,7 +3617,7 @@ pub fn sb_coeff_inter_frame_tile_tx( ); neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split); } - neighbours.record_inter(at, BLOCK, block.skip, is_inter); + neighbours.record_inter(at, BLOCK, block.skip, is_inter, block_ref(block)); } } } @@ -3432,9 +3661,6 @@ fn write_inter_frame_leaf( /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s /// `size_group_lookup[BLOCK_16X16]`) for this leaf's own size. const SIZE_GROUP_16: usize = 2; - /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference this - /// writer's single-reference chain ever names, same as the 32x32 branch. - const LAST_FRAME: i8 = 1; let (r, c) = at; let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); @@ -3450,10 +3676,7 @@ fn write_inter_frame_leaf( let mode_for_tx; if let Some(info) = block.inter { - let sr_ctx = single_ref_ctx(above_inter || left_inter); - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2 - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST + write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[mi_c], neighbours.left_ref[mi_r]); let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize); let stack = find_mv_stack( @@ -3462,34 +3685,12 @@ fn write_inter_frame_leaf( mi_col, SUB_MI as usize, SUB_MI as usize, - LAST_FRAME, + info.ref_frame, mi_cols as usize, mi_rows as usize, ); - let is_new_mv = matches!(info.mode, InterMode::NewMv); - if is_new_mv { - enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV - } else { - enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new - enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero - enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV - } - if is_new_mv && stack.entries.len() > 1 { - enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]); - } - let mv = if is_new_mv { - write_mv( - enc, - &mut cdfs.mv_comp, - &mut cdfs.mv_joint, - info.mv, - stack.pred_mv, - )?; - info.mv - } else { - stack.nearest_mv - }; + let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?; for dr in 0..SUB_MI as usize { for dc in 0..SUB_MI as usize { grid.set( @@ -3497,7 +3698,7 @@ fn write_inter_frame_leaf( mi_col + dc, MiInfo { is_inter: true, - ref_frame: LAST_FRAME, + ref_frame: info.ref_frame, ref_frame1: NO_REF1, mv1: (0, 0), mv: mv16(mv), @@ -3598,7 +3799,7 @@ fn write_inter_frame_leaf( ); neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split); } - neighbours.record_inter(at, SUB, block.skip, is_inter); + neighbours.record_inter(at, SUB, block.skip, is_inter, block_ref(block)); Ok(()) } @@ -3646,9 +3847,6 @@ fn write_inter_frame_leaf8( /// `Y_MODE`'s size group (spec `Size_Group`, `common_data.h`'s /// `size_group_lookup[BLOCK_8X8]`) for this leaf's own size. const SIZE_GROUP_8: usize = 1; - /// `Ref_Frame_List`'s `LAST_FRAME` (spec 3), same as the 16x16/32x32 - /// branches. - const LAST_FRAME: i8 = 1; // This leaf's own 4x4 mode-info cells, not the enclosing 16x16 slot's: // under a real PARTITION_SPLIT all four leaves are coded, so the @@ -3671,10 +3869,7 @@ fn write_inter_frame_leaf8( let mode_for_tx; if let Some(info) = block.inter { - let sr_ctx = single_ref_ctx(above_inter || left_inter); - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][0]); // p1: forward - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][2]); // p3: LAST/LAST2 - enc.symbol(0, &mut cdfs.single_ref[sr_ctx][3]); // p4: LAST + write_single_ref(enc, cdfs, info.ref_frame, neighbours.above_ref[leaf_mi.1], neighbours.left_ref[leaf_mi.0]); let (mi_row, mi_col) = leaf_mi; let stack = find_mv_stack( @@ -3683,34 +3878,12 @@ fn write_inter_frame_leaf8( mi_col, 2, 2, - LAST_FRAME, + info.ref_frame, mi_cols as usize, mi_rows as usize, ); - let is_new_mv = matches!(info.mode, InterMode::NewMv); - if is_new_mv { - enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); // NEWMV - } else { - enc.symbol(1, &mut cdfs.new_mv[stack.new_mv_ctx]); // not new - enc.symbol(1, &mut cdfs.zero_mv[stack.zero_mv_ctx]); // not zero - enc.symbol(0, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARESTMV - } - if is_new_mv && stack.entries.len() > 1 { - enc.symbol(0, &mut cdfs.drl_mode[stack.drl_ctx[0]]); - } - let mv = if is_new_mv { - write_mv( - enc, - &mut cdfs.mv_comp, - &mut cdfs.mv_joint, - info.mv, - stack.pred_mv, - )?; - info.mv - } else { - stack.nearest_mv - }; + let (mv, is_new_mv) = write_inter_mode(enc, cdfs, info, &stack)?; for dr in 0..2 { for dc in 0..2 { grid.set( @@ -3718,7 +3891,7 @@ fn write_inter_frame_leaf8( mi_col + dc, MiInfo { is_inter: true, - ref_frame: LAST_FRAME, + ref_frame: info.ref_frame, ref_frame1: NO_REF1, mv1: (0, 0), mv: mv16(mv), @@ -3796,7 +3969,7 @@ fn write_inter_frame_leaf8( vec![0i32; TX4 * TX4], ]; neighbours.record_mi(leaf_mi, 8, &zero_grids); - neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some()); + neighbours.record_inter_mi(leaf_mi, 8, block.skip, block.inter.is_some(), block_ref(block)); } else { let grids = [ level_grid(&block.luma, TX8)?, @@ -3819,7 +3992,7 @@ fn write_inter_frame_leaf8( split, ); neighbours.record_mi_planes(leaf_mi, 8, &grids, !split); - neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter); + neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter, block_ref(block)); } Ok((block.skip, is_inter)) } @@ -5987,7 +6160,7 @@ mod tests { let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1; let (mode, mv) = if is_inter { - let sr_ctx = single_ref_ctx(above_inter[c32] || left_inter[r32]); + let sr_ctx = crate::mvstack::single_ref_ctx(above_inter[c32] || left_inter[r32]); count += 3; assert_eq!( dec.symbol(&mut cdfs.single_ref[sr_ctx][0]), @@ -6101,8 +6274,10 @@ mod tests { fn an_all_skip_inter_superblock_is_small_and_reads_back() { let block = BlockCoeffs { inter: Some(InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), + ref_mv_idx: 0, }), skip: true, ..BlockCoeffs::default() @@ -6142,16 +6317,20 @@ mod tests { fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() { let nearest = BlockCoeffs { inter: Some(InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NearestMv, mv: (0, 0), + ref_mv_idx: 0, }), skip: true, ..BlockCoeffs::default() }; let newmv = BlockCoeffs { inter: Some(InterInfo { + ref_frame: crate::mvstack::LAST_FRAME, mode: InterMode::NewMv, mv: (0, 2), + ref_mv_idx: 0, }), skip: true, ..BlockCoeffs::default()