diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index 2c1c1c0f..59a5603b 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -300,6 +300,26 @@ pub(crate) struct TxbTables<'a> { pub tx_type: Option<&'a mut [u16]>, } +impl TxbSet { + /// Whether this set codes a CHROMA plane's transform, which is what + /// picks the `txb_skip` context rule the writer uses: chroma reads + /// "did the above/left neighbour code anything" (`write_block_planes`), + /// luma reads context 0 for a transform covering its whole block and + /// `SKIP_CONTEXTS` for a smaller unit (`write_luma_tus`). + pub(crate) fn is_chroma(self) -> bool { + matches!( + self, + Self::Chroma4 + | Self::Chroma8 + | Self::Chroma16 + | Self::Chroma32 + | Self::ChromaRect8x4 + | Self::ChromaRect16x8 + | Self::ChromaRect32x16 + ) + } +} + /// Every table a key frame's tile writer adapts. #[derive(Clone)] pub(crate) struct Cdfs { diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index bc359a45..5cd72b5e 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1196,6 +1196,45 @@ fn too_large() -> Error { /// One plane of the picture being coded, and the reconstruction being built /// beside it. +/// What one committed 4x4 cell left behind for the coefficient contexts of +/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which +/// is the same state decode.rs records. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +struct CoefCtx { + /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7. + level: u8, + /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when + /// the DC itself was zero (tile.rs `dc_vote`). + dc: i8, +} + +/// One plane's coefficient contexts, committed in CODING ORDER: the search +/// prices partition TREES, so the neighbour state a candidate reads has to be +/// whatever the blocks coded before it left -- the parent's committed +/// neighbours for a tree's first child, the just-committed sibling for the +/// later ones. Keeping the map as a full per-4x4-cell grid rather than the +/// writer's two running bands is what makes that fall out: a trial commits +/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone +/// with the pixels ([`Plane::restore`]), so what a candidate reads above and +/// to its left is exactly what the tile writer's `Neighbours` bands will hold +/// when it gets there. +/// +/// Before this map the pricer took both contexts as zero, which is exact for +/// a luma transform covering its whole block and the largest remaining row of +/// the pricer census everywhere else (all-zero chroma under-priced 41-81%). +#[derive(Default)] +struct CoefCtxMap { + cells: Vec, + stride: usize, + /// Whether the transforms being priced right now are SMALLER than the + /// block they sit in -- a `TxMode::Select` depth split + /// ([`Plane::code_tx_depth`]) or an inter var-tx split + /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a + /// trial cannot tell, and it is what decides whether luma reads context 0 + /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`). + tu_split: bool, +} + struct Plane<'a> { source: &'a [u8], reconstruction: Vec, @@ -1223,6 +1262,11 @@ struct Plane<'a> { tile_y0: usize, tile_x1: usize, tile_y1: usize, + /// [`CoefCtxMap`]: what the blocks already committed left for the + /// coefficient contexts of the ones still being priced. Sized on the + /// first commit, so a plane literal does not have to know its own extent + /// twice. + ctx: CoefCtxMap, } impl Plane<'_> { @@ -1418,7 +1462,16 @@ impl Plane<'_> { .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) .sum() } else { - crate::tile::coeff_bits(&levels, at.set, crate::decode::q_ctx_of(base_q_idx)) + { + let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set); + crate::tile::coeff_bits( + &levels, + at.set, + crate::decode::q_ctx_of(base_q_idx), + skip_ctx, + sign_ctx, + ) + } }; #[cfg(test)] stage_add(3, t.elapsed()); @@ -1487,7 +1540,16 @@ impl Plane<'_> { .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) .sum() } else { - crate::tile::coeff_bits(&levels, set, crate::decode::q_ctx_of(base_q_idx)) + { + let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set); + crate::tile::coeff_bits( + &levels, + set, + crate::decode::q_ctx_of(base_q_idx), + skip_ctx, + sign_ctx, + ) + } }; #[cfg(test)] stage_add(3, t.elapsed()); @@ -1525,6 +1587,9 @@ impl Plane<'_> { }; let mut levels = vec![0i32; side * side]; census_add(4, n * n); + // A unit smaller than its block reads the neighbour magnitude table + // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]). + self.ctx.tu_split = n > 1; let (mut sse, mut bits) = (0.0, 0.0); for tu_row in 0..n { for tu_col in 0..n { @@ -1546,15 +1611,116 @@ impl Plane<'_> { } } } + self.ctx.tu_split = false; (levels, sse, bits) } - /// Writes a trial's reconstruction back into the plane. + /// Writes a trial's reconstruction back into the plane, and the + /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]). fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { for row in 0..side { self.reconstruction[(y + row) * self.width + x..][..side] .copy_from_slice(&trial.reconstruction[row * side..][..side]); } + self.commit_ctx(x, y, side, &trial.levels); + } + + /// Publishes one committed transform's own context over every 4x4 cell it + /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`, + /// which is what the writer will read when it reaches the next block. + fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) { + if self.ctx.cells.is_empty() { + self.ctx.stride = self.width.div_ceil(4); + self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)]; + } + let cul = levels.iter().map(|l| l.unsigned_abs()).sum::().min(7) as u8; + let state = CoefCtx { + level: cul, + dc: match levels[0].signum() { + 0 => 0, + -1 => -1, + _ => 1, + }, + }; + let n = (side / 4).max(1); + // Only up to the frame's TRUE extent: the writer's own + // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high` + // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`) + // and leaves the cells past it uncoded even mid-block, so a + // straddling block publishes context for its inside part only. + let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4)); + let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4)); + for row in 0..rows { + let start = (y / 4 + row) * self.ctx.stride + x / 4; + let end = (start + cols).min(self.ctx.cells.len()); + if start < end { + self.ctx.cells[start..end].fill(state); + } + } + } + + /// A block committed without any residual at all ([`ibc_commit`]): the + /// cells it covers coded nothing, and leaving an earlier trial's state + /// there would price its neighbours off a block that was never coded. + fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) { + self.commit_ctx(x, y, side, &[0i32]); + } + + /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this + /// plane reads, off what the blocks before it in coding order committed + /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether + /// the above/left neighbours coded anything (tile.rs + /// `write_block_planes`), luma reads context 0 when its transform covers + /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour + /// magnitude tiers when it does not (tile.rs `write_luma_tus` / + /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of + /// the same neighbours (tile.rs `dc_sign_ctx`). + /// + /// A neighbour outside this plane's own TILE does not exist, exactly as + /// the writer's per-tile `Neighbours` bands start blank. + /// + /// CLOSED (lane-av1straddle): the decisions this price changes used to + /// make `decode_stream_round_trips_an_odd_size_gop` and + /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction` + /// fail at 216x96. Never this map: the writer coded the phantom + /// transform units of a right-edge-straddling 32x32 (tile.rs + /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows` + /// like decode.rs and libaom), which libdav1d and libaom both refused + /// outright while a decision change was what first walked into it. + fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) { + if self.ctx.cells.is_empty() { + return (0, 0); + } + let n = (side / 4).max(1); + let (cx, cy) = (x / 4, y / 4); + let (mut top, mut left) = (0u8, 0u8); + let mut vote = 0i32; + if y > self.tile_y0 && cy > 0 { + for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] { + top |= cell.level; + vote += i32::from(cell.dc); + } + } + if x > self.tile_x0 && cx > 0 { + for row in 0..n { + let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1]; + left |= cell.level; + vote += i32::from(cell.dc); + } + } + let skip_ctx = if set.is_chroma() { + usize::from(top != 0) + usize::from(left != 0) + } else if self.ctx.tu_split { + crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)] + } else { + 0 + }; + let sign_ctx = match vote.signum() { + 0 => 0, + -1 => 1, + _ => 2, + }; + (skip_ctx, sign_ctx) } /// The source samples of one square, contiguous — what a motion search @@ -1567,15 +1733,46 @@ impl Plane<'_> { /// The reconstructed samples of one square, so that a partition trial can /// be undone. - fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec { - rows_of(&self.reconstruction, self.width, x, y, side) + /// The reconstructed samples of one square AND the coefficient contexts + /// its cells hold, so that a partition trial can be undone whole: a + /// losing trial that left its own nz/DC state behind would price the + /// blocks after it off a block the tile writer never codes. + fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec, Vec) { + ( + rows_of(&self.reconstruction, self.width, x, y, side), + self.ctx_rows(x, y, side), + ) + } + + fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec { + if self.ctx.cells.is_empty() { + return Vec::new(); + } + let n = (side / 4).max(1); + (0..n) + .flat_map(|row| { + let start = (y / 4 + row) * self.ctx.stride + x / 4; + self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec() + }) + .collect() } /// Puts a snapshot back. - fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) { + fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec, Vec)) { for row in 0..side { self.reconstruction[(y + row) * self.width + x..][..side] - .copy_from_slice(&samples[row * side..][..side]); + .copy_from_slice(&saved.0[row * side..][..side]); + } + if saved.1.is_empty() { + return; + } + let n = (side / 4).max(1); + for row in 0..n { + let start = (y / 4 + row) * self.ctx.stride + x / 4; + let end = (start + n).min(self.ctx.cells.len()); + if start < end { + self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]); + } } } @@ -2407,6 +2604,10 @@ fn commit_inter_luma( let mut levels = vec![0i32; side * side]; let (mut sse, mut bits) = (0.0, 0.0); let mut units = Vec::with_capacity(4); + // The split units are smaller than their block, so their `txb_skip` + // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and + // each unit's own commit publishes what the next one reads, coding order. + luma.ctx.tu_split = true; for tu_row in 0..2 { for tu_col in 0..2 { let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx); @@ -2423,6 +2624,7 @@ fn commit_inter_luma( units.push((tu_x, tu_y, trial)); } } + luma.ctx.tu_split = false; let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1)); let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0)); if split_cost < flat_cost { @@ -2900,7 +3102,9 @@ fn ibc_commit( let copied: Vec = plane.reconstruction[from..from + half].to_vec(); plane.reconstruction[to..to + half].copy_from_slice(&copied); } + plane.commit_ctx_zero(x / 2, y / 2, half); } + luma.commit_ctx_zero(x, y, side); } /// Searches this block's own DV: every hash-table position whose 16x16 luma @@ -4000,7 +4204,7 @@ fn snapshot( chroma: &[Plane; 2], (x, y): (usize, usize), side: usize, -) -> [Vec; 3] { +) -> [(Vec, Vec); 3] { [ luma.snapshot(x, y, side), chroma[0].snapshot(x / 2, y / 2, side / 2), @@ -4014,7 +4218,7 @@ fn restore( chroma: &mut [Plane; 2], (x, y): (usize, usize), side: usize, - saved: &[Vec; 3], + saved: &[(Vec, Vec); 3], ) { luma.restore(x, y, side, &saved[0]); chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]); @@ -4361,6 +4565,7 @@ fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, tr tile_y0: 0, tile_x1: width, tile_y1: height, + ctx: CoefCtxMap::default(), } } @@ -4632,6 +4837,7 @@ pub(crate) fn encode_key_frame_inner( tile_y0: 0, tile_x1: picture.width, tile_y1: picture.height, + ctx: CoefCtxMap::default(), }; let mut chroma = [ Plane { @@ -4645,6 +4851,7 @@ pub(crate) fn encode_key_frame_inner( tile_y0: 0, tile_x1: picture.width / 2, tile_y1: picture.height / 2, + ctx: CoefCtxMap::default(), }, Plane { source: &picture_v8, @@ -4657,6 +4864,7 @@ pub(crate) fn encode_key_frame_inner( tile_y0: 0, tile_x1: picture.width / 2, tile_y1: picture.height / 2, + ctx: CoefCtxMap::default(), }, ]; @@ -6630,6 +6838,7 @@ pub(crate) fn encode_inter_frame( tile_y0: 0, tile_x1: picture.width, tile_y1: picture.height, + ctx: CoefCtxMap::default(), }; let mut chroma = [ Plane { @@ -6643,6 +6852,7 @@ pub(crate) fn encode_inter_frame( tile_y0: 0, tile_x1: picture.width / 2, tile_y1: picture.height / 2, + ctx: CoefCtxMap::default(), }, Plane { source: &picture_v8, @@ -6655,6 +6865,7 @@ pub(crate) fn encode_inter_frame( tile_y0: 0, tile_x1: picture.width / 2, tile_y1: picture.height / 2, + ctx: CoefCtxMap::default(), }, ]; @@ -9943,7 +10154,7 @@ mod tests { }; let t = Instant::now(); for _ in 0..N { - std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2)); + std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0)); } let entropy_t = t.elapsed() / N; @@ -10730,7 +10941,10 @@ mod tests { /// above, not by this pin. Re-pinned on lane-av1price2: the search now /// prices coefficients against the tables the frame's writer really /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a - /// decision change the BD gate judges. + /// decision change the BD gate judges. Re-pinned again on + /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the + /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which + /// is the same kind of decision change. #[test] fn the_encoders_own_streams_are_byte_identical_to_their_pins() { if !have_ffmpeg() { @@ -10752,7 +10966,7 @@ mod tests { }) }; let pins: [(u8, usize, u64); 2] = - [(150, 7106, 0x1da4_9acd_a892_68e3), (60, 25963, 0x94df_8f46_174e_1a5e)]; + [(150, 7141, 0x3a6a_df46_9b16_d9a7), (60, 25906, 0xbf71_9320_9e50_d237)]; for (q, bytes, hash) in pins { let encoded = encode_sequence(&source, q, 0.5).unwrap(); assert_eq!( diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 4cc6869d..2ef0a4bb 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -3318,18 +3318,33 @@ pub(crate) mod tests { eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg"); return; } - let (width, height) = (128usize, 64usize); - let pictures: Vec<_> = (0..3) - .map(|i| panned_test_card(width, height, i * 3)) - .collect(); - let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); - let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); - let decoded = decode_stream(&encoded.stream).unwrap(); - assert_eq!(decoded.len(), 3); - for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { - assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg"); - assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg"); - assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg"); + // lane-av1straddle: 216x96 joins 128x64 because only a size whose + // 32x32 blocks straddle the right-hand frame edge can see the writer + // coding a transform unit that starts outside the frame -- libdav1d + // AND libaom both refused the whole key frame while it did, and this + // crate's own (lenient) decoder only differed in the last block's V. + for &(width, height) in &[(128usize, 64usize), (216usize, 96usize)] { + let pictures: Vec<_> = (0..3) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); + let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); + let decoded = decode_stream(&encoded.stream).unwrap(); + assert_eq!(decoded.len(), 3); + for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg"); + assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg"); + assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg"); + } + // ... and the encoder's own reconstruction is what ffmpeg sees, + // so the check fails on a writer-side desync too, not only on a + // decoder-side one. + for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() { + let rec = &frame.reconstruction; + assert_eq!(rec.y, want.y, "{width}x{height} frame {i} luma: reconstruction vs ffmpeg"); + assert_eq!(rec.u, want.u, "{width}x{height} frame {i} U: reconstruction vs ffmpeg"); + assert_eq!(rec.v, want.v, "{width}x{height} frame {i} V: reconstruction vs ffmpeg"); + } } } diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 079e0946..f22967bc 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -3630,7 +3630,14 @@ fn write_block_planes( Some(plane), ); #[cfg(test)] - census_record(planes[plane], q_ctx, grid, f64::from(enc.tell() - before)); + census_record( + planes[plane], + q_ctx, + grid, + f64::from(enc.tell() - before), + skip_ctx, + dc_sign_ctx(around[plane].dc_vote), + ); ec_rng_trace(|| { format!( "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}", @@ -3693,6 +3700,19 @@ fn write_luma_tus( for tu_row in 0..n { for tu_col in 0..n { let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI)); + // lane-av1straddle: libaom clips the transform loop to + // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`, + // off the frame's true `mi_cols`/`mi_rows`), and decode.rs does + // the same (`tu_px >= y.true_width` there): a unit whose TOP-LEFT + // sample is outside the frame is NEVER coded. Writing one -- as + // this loop did for the phantom right-hand column of a 32x32 at + // x=192 in a 216-wide frame -- desyncs the tile at the very next + // symbol, which is what made an odd-size GOP's last block + // reconstruct differently and both ffmpeg decoders (libdav1d and + // libaom) refuse the whole key frame. + if tu_mi.0 >= neighbours.mi_rows || tu_mi.1 >= neighbours.mi_cols { + continue; + } let unit = if n == 1 { grid.to_vec() } else { @@ -3725,7 +3745,14 @@ fn write_luma_tus( Some(0), ); #[cfg(test)] - census_record(set, q_ctx, &unit, f64::from(enc.tell() - before)); + census_record( + set, + q_ctx, + &unit, + f64::from(enc.tell() - before), + skip_ctx, + dc_sign_ctx(around.dc_vote), + ); if n > 1 { neighbours.record_mi_luma(tu_mi, tx, &unit); } @@ -4006,9 +4033,9 @@ pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8 // top-left 32x32 carries coefficients) and each chroma plane at // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here. Superblock::Whole(block) if !block.skip => { - coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx) - + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx) - + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx) + coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0) + + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0) + + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0) } Superblock::Whole(_) => 0.0, Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx), @@ -4035,9 +4062,9 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 { (_, false) => (TxbSet::Luma8, TxbSet::Chroma4), (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4), }; - coeff_bits(&dense(&block.luma, side), luma, q_ctx) - + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx) - + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx) + coeff_bits(&dense(&block.luma, side), luma, q_ctx, 0, 0) + + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx, 0, 0) + + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx, 0, 0) } blocks .iter() @@ -4053,7 +4080,7 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 { #[cfg(test)] pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { - coeff_bits(grid, TxbSet::Luma32, 2) + coeff_bits(grid, TxbSet::Luma32, 2, 0, 0) } /// What one transform block's levels cost through the CDFs of `set`, in bits. @@ -4067,21 +4094,41 @@ pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 { /// tables), and against the contexts a block whose neighbours coded nothing /// reads. /// -/// That last assumption -- `skip_ctx` 0, `sign_ctx` 0 -- is the largest -/// remaining row of the census and lane-av1price2 did NOT close it: every -/// all-zero block is priced at the `txb_skip` cost of a block whose -/// neighbours coded nothing, which is the most expensive context there is, so -/// an all-zero chroma block is UNDER-priced by 41-81% on film and 51-73% on -/// the screen capture (`pricer_error_census_on_clips`), and an all-zero -/// Luma4 is over-priced by 400%+. Arming the frame's real tables does not -/// touch those rows (Chroma8 nz=0 reads -73.0% in both modes). Pricing them -/// right needs the real neighbour context, which needs something the search -/// does not have: a per-plane non-zero context map committed in coding order. -/// The search ranks partition TREES, so it prices candidates whose neighbours -/// are not yet decided; the map would have to be built per trial, not per -/// block. Deferred with the numbers above rather than approximated by a -/// fitted constant. -pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { +/// lane-av1skipctx CLOSED that row: `skip_ctx`/`sign_ctx` are the caller's +/// now, and [`crate::encode::CoefCtxMap`] -- a per-plane, per-4x4-cell map +/// committed in coding order and undone with a losing partition trial's +/// pixels -- is the per-trial neighbour state the previous lane said the +/// search did not have. The census (6 frames of each clip at 640x384, q=100, +/// `pricer_error_census_on_clips`) moved: +/// +/// | row | before | after | +/// |---|---|---| +/// | screen total | +10.3% | +9.5% | +/// | screen Chroma8 nz=0 | -73.0% | -1.9% | +/// | screen Chroma16 nz=0 | -48% | -23.4% | +/// | screen Chroma4 nz=0 | -74% | -6.7% | +/// | screen Chroma8 nz=1 / nz=2 | +32.2% / +26.2% | +4.9% / +7.9% | +/// | screen Luma4 nz=0 | +464% | +89.5% | +/// | film total | +5.3% | +1.5% | +/// +/// What is left in the all-zero rows is table ADAPTATION, not context: the +/// price is taken against the frame's starting tables, and a frame whose +/// blocks mostly code nothing narrows `txb_skip` far below where it started. +/// A whole-block luma transform still reads context 0 -- that is what the +/// writer codes (`write_luma_tus`, `n == 1`), not an approximation. +pub(crate) fn coeff_bits( + grid: &[i32], + set: TxbSet, + q_ctx: usize, + // lane-av1skipctx: the two neighbour-derived contexts, mirrored from the + // writer's own (`write_block_planes`/`write_luma_tus`) off the search's + // coding-order-committed map ([`crate::encode::CoefCtxMap`]). `(0, 0)` is + // what every caller passed before the map existed -- exact for a luma + // transform covering its whole block, and the census row that was the + // largest remaining pricer error for every other block. + skip_ctx: usize, + sign_ctx: usize, +) -> f64 { /// Built once per size: the search prices thirteen modes for every block, /// and the scan is the same table every time. static SCANS: LazyLock<[Vec; 4]> = LazyLock::new(|| { @@ -4131,7 +4178,7 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 { _ => &SCANS[3], }; let mut enc = SymbolEncoder::pricer(); - write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None); + write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None); enc.bits() }; PRICING_BASE.with_borrow_mut(|base| { @@ -4207,8 +4254,10 @@ thread_local! { /// luma price accurate while leaving the bigger chroma and all-zero errors /// exactly where they were, which SKEWS the search's tradeoffs between them /// instead of correcting them -- and the bytes get worse. The fix for that -/// row is the neighbour skip context, not another table set (see -/// [`coeff_bits`]). +/// row was the neighbour skip context, not another table set, and +/// lane-av1skipctx landed it (see [`coeff_bits`]): with the real contexts +/// under every price the screen capture comes down +59.4 -> +58.3 vs libaom +/// at native, still with every one of its frames armed with the defaults. pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); let mode = *MODE.get_or_init(|| match std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() { @@ -4282,7 +4331,18 @@ pub(crate) fn census_bucket_label(bucket: usize) -> &'static str { } #[cfg(test)] -fn census_record(set: TxbSet, q_ctx: usize, grid: &[i32], written: f64) { +fn census_record( + set: TxbSet, + q_ctx: usize, + grid: &[i32], + written: f64, + // The writer's own neighbour contexts for this very transform block: the + // census prices the search's estimate the way the search now takes it + // (lane-av1skipctx), so a row's error is the table/adaptation drift that + // is left once the context is right. + skip_ctx: usize, + sign_ctx: usize, +) { if CENSUS.with_borrow(|c| c.is_none()) { return; } @@ -4296,7 +4356,7 @@ fn census_record(set: TxbSet, q_ctx: usize, grid: &[i32], written: f64) { 9..=16 => 5, _ => 6, }; - let priced = coeff_bits(grid, set, q_ctx); + let priced = coeff_bits(grid, set, q_ctx, skip_ctx, sign_ctx); CENSUS.with_borrow_mut(|rows| { let rows = rows.as_mut().expect("the census is on"); let row = rows.entry((format!("{set:?}"), bucket)).or_default();