forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1straddle' (862db122): the writer no longer codes phantom transform units past the right frame edge; the RD pricer reads the real txb_skip/dc_sign contexts

Browse files at this commit

16ecf0666e0f7605be9768f99fcd4a8015c0538aAhmet Kaan GümüşParent: c9bed9a683eca4
A right-edge-straddling 32x32 wrote 16 luma units where the decoder and
libaom code 12; libdav1d and libaom refused the whole 216x96 stream. One
clip in write_luma_tus fixes it, byte pins unmoved (gate clips are
block-aligned). On top: the per-trial neighbour context map for the
pricer (lane-av1skipctx): screen all-zero chroma error -73% -> -1.9%,
native screen +58.3/-9.8, 2160p +47.1/+19.0, 1080p +18.1/+0.9.
crates/ec-av1/src/cdf_state.rsmodified+20 -0
@@ -300,6 +300,26 @@ pub(crate) struct TxbTables<'a> {
300 pub tx_type: Option<&'a mut [u16]>,300 pub tx_type: Option<&'a mut [u16]>,
301 }301 }
302 302
303+impl TxbSet {
304+ /// Whether this set codes a CHROMA plane's transform, which is what
305+ /// picks the `txb_skip` context rule the writer uses: chroma reads
306+ /// "did the above/left neighbour code anything" (`write_block_planes`),
307+ /// luma reads context 0 for a transform covering its whole block and
308+ /// `SKIP_CONTEXTS` for a smaller unit (`write_luma_tus`).
309+ pub(crate) fn is_chroma(self) -> bool {
310+ matches!(
311+ self,
312+ Self::Chroma4
313+ | Self::Chroma8
314+ | Self::Chroma16
315+ | Self::Chroma32
316+ | Self::ChromaRect8x4
317+ | Self::ChromaRect16x8
318+ | Self::ChromaRect32x16
319+ )
320+ }
321+}
322+
303 /// Every table a key frame's tile writer adapts.323 /// Every table a key frame's tile writer adapts.
304 #[derive(Clone)]324 #[derive(Clone)]
305 pub(crate) struct Cdfs {325 pub(crate) struct Cdfs {
crates/ec-av1/src/encode.rsmodified+226 -12
@@ -1196,6 +1196,45 @@ fn too_large() -> Error {
1196 1196
1197 /// One plane of the picture being coded, and the reconstruction being built1197 /// One plane of the picture being coded, and the reconstruction being built
1198 /// beside it.1198 /// beside it.
1199+/// What one committed 4x4 cell left behind for the coefficient contexts of
1200+/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
1201+/// is the same state decode.rs records.
1202+#[derive(Clone, Copy, Default, PartialEq, Eq)]
1203+struct CoefCtx {
1204+ /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
1205+ level: u8,
1206+ /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
1207+ /// the DC itself was zero (tile.rs `dc_vote`).
1208+ dc: i8,
1209+}
1210+
1211+/// One plane's coefficient contexts, committed in CODING ORDER: the search
1212+/// prices partition TREES, so the neighbour state a candidate reads has to be
1213+/// whatever the blocks coded before it left -- the parent's committed
1214+/// neighbours for a tree's first child, the just-committed sibling for the
1215+/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
1216+/// writer's two running bands is what makes that fall out: a trial commits
1217+/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
1218+/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
1219+/// to its left is exactly what the tile writer's `Neighbours` bands will hold
1220+/// when it gets there.
1221+///
1222+/// Before this map the pricer took both contexts as zero, which is exact for
1223+/// a luma transform covering its whole block and the largest remaining row of
1224+/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
1225+#[derive(Default)]
1226+struct CoefCtxMap {
1227+ cells: Vec<CoefCtx>,
1228+ stride: usize,
1229+ /// Whether the transforms being priced right now are SMALLER than the
1230+ /// block they sit in -- a `TxMode::Select` depth split
1231+ /// ([`Plane::code_tx_depth`]) or an inter var-tx split
1232+ /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
1233+ /// trial cannot tell, and it is what decides whether luma reads context 0
1234+ /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
1235+ tu_split: bool,
1236+}
1237+
1199 struct Plane<'a> {1238 struct Plane<'a> {
1200 source: &'a [u8],1239 source: &'a [u8],
1201 reconstruction: Vec<u8>,1240 reconstruction: Vec<u8>,
@@ -1223,6 +1262,11 @@ struct Plane<'a> {
1223 tile_y0: usize,1262 tile_y0: usize,
1224 tile_x1: usize,1263 tile_x1: usize,
1225 tile_y1: usize,1264 tile_y1: usize,
1265+ /// [`CoefCtxMap`]: what the blocks already committed left for the
1266+ /// coefficient contexts of the ones still being priced. Sized on the
1267+ /// first commit, so a plane literal does not have to know its own extent
1268+ /// twice.
1269+ ctx: CoefCtxMap,
1226 }1270 }
1227 1271
1228 impl Plane<'_> {1272 impl Plane<'_> {
@@ -1418,7 +1462,16 @@ impl Plane<'_> {
1418 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())1462 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1419 .sum()1463 .sum()
1420 } else {1464 } else {
1421- crate::tile::coeff_bits(&levels, at.set, crate::decode::q_ctx_of(base_q_idx))1465+ {
1466+ let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
1467+ crate::tile::coeff_bits(
1468+ &levels,
1469+ at.set,
1470+ crate::decode::q_ctx_of(base_q_idx),
1471+ skip_ctx,
1472+ sign_ctx,
1473+ )
1474+ }
1422 };1475 };
1423 #[cfg(test)]1476 #[cfg(test)]
1424 stage_add(3, t.elapsed());1477 stage_add(3, t.elapsed());
@@ -1487,7 +1540,16 @@ impl Plane<'_> {
1487 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())1540 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1488 .sum()1541 .sum()
1489 } else {1542 } else {
1490- crate::tile::coeff_bits(&levels, set, crate::decode::q_ctx_of(base_q_idx))1543+ {
1544+ let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
1545+ crate::tile::coeff_bits(
1546+ &levels,
1547+ set,
1548+ crate::decode::q_ctx_of(base_q_idx),
1549+ skip_ctx,
1550+ sign_ctx,
1551+ )
1552+ }
1491 };1553 };
1492 #[cfg(test)]1554 #[cfg(test)]
1493 stage_add(3, t.elapsed());1555 stage_add(3, t.elapsed());
@@ -1525,6 +1587,9 @@ impl Plane<'_> {
1525 };1587 };
1526 let mut levels = vec![0i32; side * side];1588 let mut levels = vec![0i32; side * side];
1527 census_add(4, n * n);1589 census_add(4, n * n);
1590+ // A unit smaller than its block reads the neighbour magnitude table
1591+ // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
1592+ self.ctx.tu_split = n > 1;
1528 let (mut sse, mut bits) = (0.0, 0.0);1593 let (mut sse, mut bits) = (0.0, 0.0);
1529 for tu_row in 0..n {1594 for tu_row in 0..n {
1530 for tu_col in 0..n {1595 for tu_col in 0..n {
@@ -1546,15 +1611,116 @@ impl Plane<'_> {
1546 }1611 }
1547 }1612 }
1548 }1613 }
1614+ self.ctx.tu_split = false;
1549 (levels, sse, bits)1615 (levels, sse, bits)
1550 }1616 }
1551 1617
1552- /// Writes a trial's reconstruction back into the plane.1618+ /// Writes a trial's reconstruction back into the plane, and the
1619+ /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
1553 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {1620 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
1554 for row in 0..side {1621 for row in 0..side {
1555 self.reconstruction[(y + row) * self.width + x..][..side]1622 self.reconstruction[(y + row) * self.width + x..][..side]
1556 .copy_from_slice(&trial.reconstruction[row * side..][..side]);1623 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
1557 }1624 }
1625+ self.commit_ctx(x, y, side, &trial.levels);
1626+ }
1627+
1628+ /// Publishes one committed transform's own context over every 4x4 cell it
1629+ /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
1630+ /// which is what the writer will read when it reaches the next block.
1631+ fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
1632+ if self.ctx.cells.is_empty() {
1633+ self.ctx.stride = self.width.div_ceil(4);
1634+ self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
1635+ }
1636+ let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
1637+ let state = CoefCtx {
1638+ level: cul,
1639+ dc: match levels[0].signum() {
1640+ 0 => 0,
1641+ -1 => -1,
1642+ _ => 1,
1643+ },
1644+ };
1645+ let n = (side / 4).max(1);
1646+ // Only up to the frame's TRUE extent: the writer's own
1647+ // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
1648+ // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
1649+ // and leaves the cells past it uncoded even mid-block, so a
1650+ // straddling block publishes context for its inside part only.
1651+ let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
1652+ let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
1653+ for row in 0..rows {
1654+ let start = (y / 4 + row) * self.ctx.stride + x / 4;
1655+ let end = (start + cols).min(self.ctx.cells.len());
1656+ if start < end {
1657+ self.ctx.cells[start..end].fill(state);
1658+ }
1659+ }
1660+ }
1661+
1662+ /// A block committed without any residual at all ([`ibc_commit`]): the
1663+ /// cells it covers coded nothing, and leaving an earlier trial's state
1664+ /// there would price its neighbours off a block that was never coded.
1665+ fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
1666+ self.commit_ctx(x, y, side, &[0i32]);
1667+ }
1668+
1669+ /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
1670+ /// plane reads, off what the blocks before it in coding order committed
1671+ /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
1672+ /// the above/left neighbours coded anything (tile.rs
1673+ /// `write_block_planes`), luma reads context 0 when its transform covers
1674+ /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
1675+ /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
1676+ /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
1677+ /// the same neighbours (tile.rs `dc_sign_ctx`).
1678+ ///
1679+ /// A neighbour outside this plane's own TILE does not exist, exactly as
1680+ /// the writer's per-tile `Neighbours` bands start blank.
1681+ ///
1682+ /// CLOSED (lane-av1straddle): the decisions this price changes used to
1683+ /// make `decode_stream_round_trips_an_odd_size_gop` and
1684+ /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
1685+ /// fail at 216x96. Never this map: the writer coded the phantom
1686+ /// transform units of a right-edge-straddling 32x32 (tile.rs
1687+ /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
1688+ /// like decode.rs and libaom), which libdav1d and libaom both refused
1689+ /// outright while a decision change was what first walked into it.
1690+ fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
1691+ if self.ctx.cells.is_empty() {
1692+ return (0, 0);
1693+ }
1694+ let n = (side / 4).max(1);
1695+ let (cx, cy) = (x / 4, y / 4);
1696+ let (mut top, mut left) = (0u8, 0u8);
1697+ let mut vote = 0i32;
1698+ if y > self.tile_y0 && cy > 0 {
1699+ for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
1700+ top |= cell.level;
1701+ vote += i32::from(cell.dc);
1702+ }
1703+ }
1704+ if x > self.tile_x0 && cx > 0 {
1705+ for row in 0..n {
1706+ let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
1707+ left |= cell.level;
1708+ vote += i32::from(cell.dc);
1709+ }
1710+ }
1711+ let skip_ctx = if set.is_chroma() {
1712+ usize::from(top != 0) + usize::from(left != 0)
1713+ } else if self.ctx.tu_split {
1714+ crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
1715+ } else {
1716+ 0
1717+ };
1718+ let sign_ctx = match vote.signum() {
1719+ 0 => 0,
1720+ -1 => 1,
1721+ _ => 2,
1722+ };
1723+ (skip_ctx, sign_ctx)
1558 }1724 }
1559 1725
1560 /// The source samples of one square, contiguous — what a motion search1726 /// The source samples of one square, contiguous — what a motion search
@@ -1567,15 +1733,46 @@ impl Plane<'_> {
1567 1733
1568 /// The reconstructed samples of one square, so that a partition trial can1734 /// The reconstructed samples of one square, so that a partition trial can
1569 /// be undone.1735 /// be undone.
1570- fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> {1736+ /// The reconstructed samples of one square AND the coefficient contexts
1571- rows_of(&self.reconstruction, self.width, x, y, side)1737+ /// its cells hold, so that a partition trial can be undone whole: a
1738+ /// losing trial that left its own nz/DC state behind would price the
1739+ /// blocks after it off a block the tile writer never codes.
1740+ fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
1741+ (
1742+ rows_of(&self.reconstruction, self.width, x, y, side),
1743+ self.ctx_rows(x, y, side),
1744+ )
1745+ }
1746+
1747+ fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
1748+ if self.ctx.cells.is_empty() {
1749+ return Vec::new();
1750+ }
1751+ let n = (side / 4).max(1);
1752+ (0..n)
1753+ .flat_map(|row| {
1754+ let start = (y / 4 + row) * self.ctx.stride + x / 4;
1755+ self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
1756+ })
1757+ .collect()
1572 }1758 }
1573 1759
1574 /// Puts a snapshot back.1760 /// Puts a snapshot back.
1575- fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) {1761+ fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
1576 for row in 0..side {1762 for row in 0..side {
1577 self.reconstruction[(y + row) * self.width + x..][..side]1763 self.reconstruction[(y + row) * self.width + x..][..side]
1578- .copy_from_slice(&samples[row * side..][..side]);1764+ .copy_from_slice(&saved.0[row * side..][..side]);
1765+ }
1766+ if saved.1.is_empty() {
1767+ return;
1768+ }
1769+ let n = (side / 4).max(1);
1770+ for row in 0..n {
1771+ let start = (y / 4 + row) * self.ctx.stride + x / 4;
1772+ let end = (start + n).min(self.ctx.cells.len());
1773+ if start < end {
1774+ self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
1775+ }
1579 }1776 }
1580 }1777 }
1581 1778
@@ -2407,6 +2604,10 @@ fn commit_inter_luma(
2407 let mut levels = vec![0i32; side * side];2604 let mut levels = vec![0i32; side * side];
2408 let (mut sse, mut bits) = (0.0, 0.0);2605 let (mut sse, mut bits) = (0.0, 0.0);
2409 let mut units = Vec::with_capacity(4);2606 let mut units = Vec::with_capacity(4);
2607+ // The split units are smaller than their block, so their `txb_skip`
2608+ // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
2609+ // each unit's own commit publishes what the next one reads, coding order.
2610+ luma.ctx.tu_split = true;
2410 for tu_row in 0..2 {2611 for tu_row in 0..2 {
2411 for tu_col in 0..2 {2612 for tu_col in 0..2 {
2412 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);2613 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
@@ -2423,6 +2624,7 @@ fn commit_inter_luma(
2423 units.push((tu_x, tu_y, trial));2624 units.push((tu_x, tu_y, trial));
2424 }2625 }
2425 }2626 }
2627+ luma.ctx.tu_split = false;
2426 let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));2628 let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));
2427 let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0));2629 let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0));
2428 if split_cost < flat_cost {2630 if split_cost < flat_cost {
@@ -2900,7 +3102,9 @@ fn ibc_commit(
2900 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();3102 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
2901 plane.reconstruction[to..to + half].copy_from_slice(&copied);3103 plane.reconstruction[to..to + half].copy_from_slice(&copied);
2902 }3104 }
3105+ plane.commit_ctx_zero(x / 2, y / 2, half);
2903 }3106 }
3107+ luma.commit_ctx_zero(x, y, side);
2904 }3108 }
2905 3109
2906 /// Searches this block's own DV: every hash-table position whose 16x16 luma3110 /// Searches this block's own DV: every hash-table position whose 16x16 luma
@@ -4000,7 +4204,7 @@ fn snapshot(
4000 chroma: &[Plane; 2],4204 chroma: &[Plane; 2],
4001 (x, y): (usize, usize),4205 (x, y): (usize, usize),
4002 side: usize,4206 side: usize,
4003-) -> [Vec<u8>; 3] {4207+) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
4004 [4208 [
4005 luma.snapshot(x, y, side),4209 luma.snapshot(x, y, side),
4006 chroma[0].snapshot(x / 2, y / 2, side / 2),4210 chroma[0].snapshot(x / 2, y / 2, side / 2),
@@ -4014,7 +4218,7 @@ fn restore(
4014 chroma: &mut [Plane; 2],4218 chroma: &mut [Plane; 2],
4015 (x, y): (usize, usize),4219 (x, y): (usize, usize),
4016 side: usize,4220 side: usize,
4017- saved: &[Vec<u8>; 3],4221+ saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
4018 ) {4222 ) {
4019 luma.restore(x, y, side, &saved[0]);4223 luma.restore(x, y, side, &saved[0]);
4020 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);4224 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
4361 tile_y0: 0,4565 tile_y0: 0,
4362 tile_x1: width,4566 tile_x1: width,
4363 tile_y1: height,4567 tile_y1: height,
4568+ ctx: CoefCtxMap::default(),
4364 }4569 }
4365 }4570 }
4366 4571
@@ -4632,6 +4837,7 @@ pub(crate) fn encode_key_frame_inner(
4632 tile_y0: 0,4837 tile_y0: 0,
4633 tile_x1: picture.width,4838 tile_x1: picture.width,
4634 tile_y1: picture.height,4839 tile_y1: picture.height,
4840+ ctx: CoefCtxMap::default(),
4635 };4841 };
4636 let mut chroma = [4842 let mut chroma = [
4637 Plane {4843 Plane {
@@ -4645,6 +4851,7 @@ pub(crate) fn encode_key_frame_inner(
4645 tile_y0: 0,4851 tile_y0: 0,
4646 tile_x1: picture.width / 2,4852 tile_x1: picture.width / 2,
4647 tile_y1: picture.height / 2,4853 tile_y1: picture.height / 2,
4854+ ctx: CoefCtxMap::default(),
4648 },4855 },
4649 Plane {4856 Plane {
4650 source: &picture_v8,4857 source: &picture_v8,
@@ -4657,6 +4864,7 @@ pub(crate) fn encode_key_frame_inner(
4657 tile_y0: 0,4864 tile_y0: 0,
4658 tile_x1: picture.width / 2,4865 tile_x1: picture.width / 2,
4659 tile_y1: picture.height / 2,4866 tile_y1: picture.height / 2,
4867+ ctx: CoefCtxMap::default(),
4660 },4868 },
4661 ];4869 ];
4662 4870
@@ -6630,6 +6838,7 @@ pub(crate) fn encode_inter_frame(
6630 tile_y0: 0,6838 tile_y0: 0,
6631 tile_x1: picture.width,6839 tile_x1: picture.width,
6632 tile_y1: picture.height,6840 tile_y1: picture.height,
6841+ ctx: CoefCtxMap::default(),
6633 };6842 };
6634 let mut chroma = [6843 let mut chroma = [
6635 Plane {6844 Plane {
@@ -6643,6 +6852,7 @@ pub(crate) fn encode_inter_frame(
6643 tile_y0: 0,6852 tile_y0: 0,
6644 tile_x1: picture.width / 2,6853 tile_x1: picture.width / 2,
6645 tile_y1: picture.height / 2,6854 tile_y1: picture.height / 2,
6855+ ctx: CoefCtxMap::default(),
6646 },6856 },
6647 Plane {6857 Plane {
6648 source: &picture_v8,6858 source: &picture_v8,
@@ -6655,6 +6865,7 @@ pub(crate) fn encode_inter_frame(
6655 tile_y0: 0,6865 tile_y0: 0,
6656 tile_x1: picture.width / 2,6866 tile_x1: picture.width / 2,
6657 tile_y1: picture.height / 2,6867 tile_y1: picture.height / 2,
6868+ ctx: CoefCtxMap::default(),
6658 },6869 },
6659 ];6870 ];
6660 6871
@@ -9943,7 +10154,7 @@ mod tests {
9943 };10154 };
9944 let t = Instant::now();10155 let t = Instant::now();
9945 for _ in 0..N {10156 for _ in 0..N {
9946- std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2));10157+ std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
9947 }10158 }
9948 let entropy_t = t.elapsed() / N;10159 let entropy_t = t.elapsed() / N;
9949 10160
@@ -10730,7 +10941,10 @@ mod tests {
10730 /// above, not by this pin. Re-pinned on lane-av1price2: the search now10941 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
10731 /// prices coefficients against the tables the frame's writer really10942 /// prices coefficients against the tables the frame's writer really
10732 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a10943 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
10733- /// decision change the BD gate judges.10944+ /// decision change the BD gate judges. Re-pinned again on
10945+ /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
10946+ /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
10947+ /// is the same kind of decision change.
10734 #[test]10948 #[test]
10735 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {10949 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
10736 if !have_ffmpeg() {10950 if !have_ffmpeg() {
@@ -10752,7 +10966,7 @@ mod tests {
10752 })10966 })
10753 };10967 };
10754 let pins: [(u8, usize, u64); 2] =10968 let pins: [(u8, usize, u64); 2] =
10755- [(150, 7106, 0x1da4_9acd_a892_68e3), (60, 25963, 0x94df_8f46_174e_1a5e)];10969+ [(150, 7141, 0x3a6a_df46_9b16_d9a7), (60, 25906, 0xbf71_9320_9e50_d237)];
10756 for (q, bytes, hash) in pins {10970 for (q, bytes, hash) in pins {
10757 let encoded = encode_sequence(&source, q, 0.5).unwrap();10971 let encoded = encode_sequence(&source, q, 0.5).unwrap();
10758 assert_eq!(10972 assert_eq!(
crates/ec-av1/src/stream.rsmodified+27 -12
@@ -3318,18 +3318,33 @@ pub(crate) mod tests {
3318 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");3318 eprintln!("SKIP decode_stream_agrees_with_ffmpeg_on_a_gop: no ffmpeg");
3319 return;3319 return;
3320 }3320 }
3321- let (width, height) = (128usize, 64usize);3321+ // lane-av1straddle: 216x96 joins 128x64 because only a size whose
3322- let pictures: Vec<_> = (0..3)3322+ // 32x32 blocks straddle the right-hand frame edge can see the writer
3323- .map(|i| panned_test_card(width, height, i * 3))3323+ // coding a transform unit that starts outside the frame -- libdav1d
3324- .collect();3324+ // AND libaom both refused the whole key frame while it did, and this
3325- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();3325+ // crate's own (lenient) decoder only differed in the last block's V.
3326- let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);3326+ for &(width, height) in &[(128usize, 64usize), (216usize, 96usize)] {
3327- let decoded = decode_stream(&encoded.stream).unwrap();3327+ let pictures: Vec<_> = (0..3)
3328- assert_eq!(decoded.len(), 3);3328+ .map(|i| panned_test_card(width, height, i * 3))
3329- for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {3329+ .collect();
3330- assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg");3330+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
3331- assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg");3331+ let ffmpeg_frames = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
3332- assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg");3332+ let decoded = decode_stream(&encoded.stream).unwrap();
3333+ assert_eq!(decoded.len(), 3);
3334+ for (i, (got, want)) in decoded.iter().zip(&ffmpeg_frames).enumerate() {
3335+ assert_eq!(got.y, want.y, "{width}x{height} frame {i} luma vs ffmpeg");
3336+ assert_eq!(got.u, want.u, "{width}x{height} frame {i} U vs ffmpeg");
3337+ assert_eq!(got.v, want.v, "{width}x{height} frame {i} V vs ffmpeg");
3338+ }
3339+ // ... and the encoder's own reconstruction is what ffmpeg sees,
3340+ // so the check fails on a writer-side desync too, not only on a
3341+ // decoder-side one.
3342+ for (i, (frame, want)) in encoded.frames.iter().zip(&ffmpeg_frames).enumerate() {
3343+ let rec = &frame.reconstruction;
3344+ assert_eq!(rec.y, want.y, "{width}x{height} frame {i} luma: reconstruction vs ffmpeg");
3345+ assert_eq!(rec.u, want.u, "{width}x{height} frame {i} U: reconstruction vs ffmpeg");
3346+ assert_eq!(rec.v, want.v, "{width}x{height} frame {i} V: reconstruction vs ffmpeg");
3347+ }
3333 }3348 }
3334 }3349 }
3335 3350
crates/ec-av1/src/tile.rsmodified+89 -29
@@ -3630,7 +3630,14 @@ fn write_block_planes(
3630 Some(plane),3630 Some(plane),
3631 );3631 );
3632 #[cfg(test)]3632 #[cfg(test)]
3633- census_record(planes[plane], q_ctx, grid, f64::from(enc.tell() - before));3633+ census_record(
3634+ planes[plane],
3635+ q_ctx,
3636+ grid,
3637+ f64::from(enc.tell() - before),
3638+ skip_ctx,
3639+ dc_sign_ctx(around[plane].dc_vote),
3640+ );
3634 ec_rng_trace(|| {3641 ec_rng_trace(|| {
3635 format!(3642 format!(
3636 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",3643 "EC_PLANE plane={plane} nz={} skip_ctx={skip_ctx} tell={}",
@@ -3693,6 +3700,19 @@ fn write_luma_tus(
3693 for tu_row in 0..n {3700 for tu_row in 0..n {
3694 for tu_col in 0..n {3701 for tu_col in 0..n {
3695 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));3702 let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
3703+ // lane-av1straddle: libaom clips the transform loop to
3704+ // `max_blocks_wide/high` (`mb_to_right_edge`/`mb_to_bottom_edge`,
3705+ // off the frame's true `mi_cols`/`mi_rows`), and decode.rs does
3706+ // the same (`tu_px >= y.true_width` there): a unit whose TOP-LEFT
3707+ // sample is outside the frame is NEVER coded. Writing one -- as
3708+ // this loop did for the phantom right-hand column of a 32x32 at
3709+ // x=192 in a 216-wide frame -- desyncs the tile at the very next
3710+ // symbol, which is what made an odd-size GOP's last block
3711+ // reconstruct differently and both ffmpeg decoders (libdav1d and
3712+ // libaom) refuse the whole key frame.
3713+ if tu_mi.0 >= neighbours.mi_rows || tu_mi.1 >= neighbours.mi_cols {
3714+ continue;
3715+ }
3696 let unit = if n == 1 {3716 let unit = if n == 1 {
3697 grid.to_vec()3717 grid.to_vec()
3698 } else {3718 } else {
@@ -3725,7 +3745,14 @@ fn write_luma_tus(
3725 Some(0),3745 Some(0),
3726 );3746 );
3727 #[cfg(test)]3747 #[cfg(test)]
3728- census_record(set, q_ctx, &unit, f64::from(enc.tell() - before));3748+ census_record(
3749+ set,
3750+ q_ctx,
3751+ &unit,
3752+ f64::from(enc.tell() - before),
3753+ skip_ctx,
3754+ dc_sign_ctx(around.dc_vote),
3755+ );
3729 if n > 1 {3756 if n > 1 {
3730 neighbours.record_mi_luma(tu_mi, tx, &unit);3757 neighbours.record_mi_luma(tu_mi, tx, &unit);
3731 }3758 }
@@ -4006,9 +4033,9 @@ pub(crate) fn predicted_coeff_bits_sb(superblocks: &[Superblock], base_q_idx: u8
4006 // top-left 32x32 carries coefficients) and each chroma plane at4033 // top-left 32x32 carries coefficients) and each chroma plane at
4007 // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here.4034 // 32x32; `predicted_coeff_bits` has no 64 arm, so price it here.
4008 Superblock::Whole(block) if !block.skip => {4035 Superblock::Whole(block) if !block.skip => {
4009- coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx)4036+ coeff_bits(&dense(&block.luma, 32), TxbSet::Luma64, q_ctx, 0, 0)
4010- + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx)4037+ + coeff_bits(&dense(&block.u, 32), TxbSet::Chroma32, q_ctx, 0, 0)
4011- + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx)4038+ + coeff_bits(&dense(&block.v, 32), TxbSet::Chroma32, q_ctx, 0, 0)
4012 }4039 }
4013 Superblock::Whole(_) => 0.0,4040 Superblock::Whole(_) => 0.0,
4014 Superblock::Split(quadrants) => predicted_coeff_bits(quadrants, base_q_idx),4041 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 {
4035 (_, false) => (TxbSet::Luma8, TxbSet::Chroma4),4062 (_, false) => (TxbSet::Luma8, TxbSet::Chroma4),
4036 (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4),4063 (_, true) => (TxbSet::Luma8Inter, TxbSet::Chroma4),
4037 };4064 };
4038- coeff_bits(&dense(&block.luma, side), luma, q_ctx)4065+ coeff_bits(&dense(&block.luma, side), luma, q_ctx, 0, 0)
4039- + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx)4066+ + coeff_bits(&dense(&block.u, side / 2), chroma, q_ctx, 0, 0)
4040- + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx)4067+ + coeff_bits(&dense(&block.v, side / 2), chroma, q_ctx, 0, 0)
4041 }4068 }
4042 blocks4069 blocks
4043 .iter()4070 .iter()
@@ -4053,7 +4080,7 @@ pub(crate) fn predicted_coeff_bits(blocks: &[Quadrant], base_q_idx: u8) -> f64 {
4053 4080
4054 #[cfg(test)]4081 #[cfg(test)]
4055 pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {4082 pub(crate) fn luma_32_coeff_bits(grid: &[i32]) -> f64 {
4056- coeff_bits(grid, TxbSet::Luma32, 2)4083+ coeff_bits(grid, TxbSet::Luma32, 2, 0, 0)
4057 }4084 }
4058 4085
4059 /// What one transform block's levels cost through the CDFs of `set`, in bits.4086 /// 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 {
4067 /// tables), and against the contexts a block whose neighbours coded nothing4094 /// tables), and against the contexts a block whose neighbours coded nothing
4068 /// reads.4095 /// reads.
4069 ///4096 ///
4070-/// That last assumption -- `skip_ctx` 0, `sign_ctx` 0 -- is the largest4097+/// lane-av1skipctx CLOSED that row: `skip_ctx`/`sign_ctx` are the caller's
4071-/// remaining row of the census and lane-av1price2 did NOT close it: every4098+/// now, and [`crate::encode::CoefCtxMap`] -- a per-plane, per-4x4-cell map
4072-/// all-zero block is priced at the `txb_skip` cost of a block whose4099+/// committed in coding order and undone with a losing partition trial's
4073-/// neighbours coded nothing, which is the most expensive context there is, so4100+/// pixels -- is the per-trial neighbour state the previous lane said the
4074-/// an all-zero chroma block is UNDER-priced by 41-81% on film and 51-73% on4101+/// search did not have. The census (6 frames of each clip at 640x384, q=100,
4075-/// the screen capture (`pricer_error_census_on_clips`), and an all-zero4102+/// `pricer_error_census_on_clips`) moved:
4076-/// Luma4 is over-priced by 400%+. Arming the frame's real tables does not4103+///
4077-/// touch those rows (Chroma8 nz=0 reads -73.0% in both modes). Pricing them4104+/// | row | before | after |
4078-/// right needs the real neighbour context, which needs something the search4105+/// |---|---|---|
4079-/// does not have: a per-plane non-zero context map committed in coding order.4106+/// | screen total | +10.3% | +9.5% |
4080-/// The search ranks partition TREES, so it prices candidates whose neighbours4107+/// | screen Chroma8 nz=0 | -73.0% | -1.9% |
4081-/// are not yet decided; the map would have to be built per trial, not per4108+/// | screen Chroma16 nz=0 | -48% | -23.4% |
4082-/// block. Deferred with the numbers above rather than approximated by a4109+/// | screen Chroma4 nz=0 | -74% | -6.7% |
4083-/// fitted constant.4110+/// | screen Chroma8 nz=1 / nz=2 | +32.2% / +26.2% | +4.9% / +7.9% |
4084-pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {4111+/// | screen Luma4 nz=0 | +464% | +89.5% |
4112+/// | film total | +5.3% | +1.5% |
4113+///
4114+/// What is left in the all-zero rows is table ADAPTATION, not context: the
4115+/// price is taken against the frame's starting tables, and a frame whose
4116+/// blocks mostly code nothing narrows `txb_skip` far below where it started.
4117+/// A whole-block luma transform still reads context 0 -- that is what the
4118+/// writer codes (`write_luma_tus`, `n == 1`), not an approximation.
4119+pub(crate) fn coeff_bits(
4120+ grid: &[i32],
4121+ set: TxbSet,
4122+ q_ctx: usize,
4123+ // lane-av1skipctx: the two neighbour-derived contexts, mirrored from the
4124+ // writer's own (`write_block_planes`/`write_luma_tus`) off the search's
4125+ // coding-order-committed map ([`crate::encode::CoefCtxMap`]). `(0, 0)` is
4126+ // what every caller passed before the map existed -- exact for a luma
4127+ // transform covering its whole block, and the census row that was the
4128+ // largest remaining pricer error for every other block.
4129+ skip_ctx: usize,
4130+ sign_ctx: usize,
4131+) -> f64 {
4085 /// Built once per size: the search prices thirteen modes for every block,4132 /// Built once per size: the search prices thirteen modes for every block,
4086 /// and the scan is the same table every time.4133 /// and the scan is the same table every time.
4087 static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {4134 static SCANS: LazyLock<[Vec<u16>; 4]> = LazyLock::new(|| {
@@ -4131,7 +4178,7 @@ pub(crate) fn coeff_bits(grid: &[i32], set: TxbSet, q_ctx: usize) -> f64 {
4131 _ => &SCANS[3],4178 _ => &SCANS[3],
4132 };4179 };
4133 let mut enc = SymbolEncoder::pricer();4180 let mut enc = SymbolEncoder::pricer();
4134- write_coeffs(&mut enc, &mut coding, grid, scan, 0, 0, None);4181+ write_coeffs(&mut enc, &mut coding, grid, scan, skip_ctx, sign_ctx, None);
4135 enc.bits()4182 enc.bits()
4136 };4183 };
4137 PRICING_BASE.with_borrow_mut(|base| {4184 PRICING_BASE.with_borrow_mut(|base| {
@@ -4207,8 +4254,10 @@ thread_local! {
4207 /// luma price accurate while leaving the bigger chroma and all-zero errors4254 /// luma price accurate while leaving the bigger chroma and all-zero errors
4208 /// exactly where they were, which SKEWS the search's tradeoffs between them4255 /// exactly where they were, which SKEWS the search's tradeoffs between them
4209 /// instead of correcting them -- and the bytes get worse. The fix for that4256 /// instead of correcting them -- and the bytes get worse. The fix for that
4210-/// row is the neighbour skip context, not another table set (see4257+/// row was the neighbour skip context, not another table set, and
4211-/// [`coeff_bits`]).4258+/// lane-av1skipctx landed it (see [`coeff_bits`]): with the real contexts
4259+/// under every price the screen capture comes down +59.4 -> +58.3 vs libaom
4260+/// at native, still with every one of its frames armed with the defaults.
4212 pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) {4261 pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) {
4213 static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();4262 static MODE: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
4214 let mode = *MODE.get_or_init(|| match std::env::var("EC_AV1_PRICE_FRAME_CDFS").as_deref() {4263 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 {
4282 }4331 }
4283 4332
4284 #[cfg(test)]4333 #[cfg(test)]
4285-fn census_record(set: TxbSet, q_ctx: usize, grid: &[i32], written: f64) {4334+fn census_record(
4335+ set: TxbSet,
4336+ q_ctx: usize,
4337+ grid: &[i32],
4338+ written: f64,
4339+ // The writer's own neighbour contexts for this very transform block: the
4340+ // census prices the search's estimate the way the search now takes it
4341+ // (lane-av1skipctx), so a row's error is the table/adaptation drift that
4342+ // is left once the context is right.
4343+ skip_ctx: usize,
4344+ sign_ctx: usize,
4345+) {
4286 if CENSUS.with_borrow(|c| c.is_none()) {4346 if CENSUS.with_borrow(|c| c.is_none()) {
4287 return;4347 return;
4288 }4348 }
@@ -4296,7 +4356,7 @@ fn census_record(set: TxbSet, q_ctx: usize, grid: &[i32], written: f64) {
4296 9..=16 => 5,4356 9..=16 => 5,
4297 _ => 6,4357 _ => 6,
4298 };4358 };
4299- let priced = coeff_bits(grid, set, q_ctx);4359+ let priced = coeff_bits(grid, set, q_ctx, skip_ctx, sign_ctx);
4300 CENSUS.with_borrow_mut(|rows| {4360 CENSUS.with_borrow_mut(|rows| {
4301 let rows = rows.as_mut().expect("the census is on");4361 let rows = rows.as_mut().expect("the census is on");
4302 let row = rows.entry((format!("{set:?}"), bucket)).or_default();4362 let row = rows.entry((format!("{set:?}"), bucket)).or_default();