forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1tx' (723ab821): key-frame TxMode::Select -- intra blocks search tx_depth 0..2 with per-transform-unit prediction/reconstruction, writer codes tx_depth with the deblock-grid context and cul_level-based skip contexts; BD-rate vs rav1e screen +141% -> +73%, films -1; inter var-tx syntax written but desyncs, shipped off behind EC_AV1_TX_SELECT_INTER=1; ffmpeg decodes every default stream sample-exact

Browse files at this commit

96d82d042d73c5a52f97fc1a72d682c1e2c0729cAhmet Kaan GümüşParent: 0e574b56397783
crates/ec-av1/src/decode.rsmodified+3 -3
@@ -6558,7 +6558,7 @@ fn neighbour_state(grid: &[i32]) -> Neighbour {
65586558 /// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
65596559 /// transform unit smaller than the block it sits in): `top`/`left` are the
65606560 /// above/left neighbours' magnitude tiers, each already clamped to 4.
6561-const SKIP_CONTEXTS: [[usize; 5]; 5] = [
6561+pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [
65626562 [1, 2, 2, 2, 3],
65636563 [2, 4, 4, 4, 5],
65646564 [2, 4, 4, 4, 5],
@@ -16962,7 +16962,7 @@ fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize
1696216962 /// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
1696316963 /// side for a square transform, which is why the square form above is a
1696416964 /// special case of this one.
16965-fn txfm_partition_ctx_rect(
16965+pub(crate) fn txfm_partition_ctx_rect(
1696616966 above_px: u8,
1696716967 left_px: u8,
1696816968 blk_max_px: usize,
@@ -17092,7 +17092,7 @@ fn set_txfm_ctxs(
1709217092 /// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
1709317093 /// pixels, so an unwritten neighbour reads as the *widest* possible
1709417094 /// transform, not the narrowest.
17095-const TXFM_CTX_INIT: u8 = 64;
17095+pub(crate) const TXFM_CTX_INIT: u8 = 64;
1709617096
1709717097 /// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
1709817098 /// twice below its own largest transform.
crates/ec-av1/src/encode.rsmodified+266 -23
@@ -39,7 +39,6 @@ use crate::quant::ac_q;
3939 use crate::sequence::sequence_header_obu;
4040 use crate::tile::{
4141 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
42- sb_coeff_inter_frame_tile, sb_coeff_key_frame_tile,
4342 };
4443 use crate::transform::{
4544 TxType, dequant_and_inverse, dequant_and_inverse_typed, forward_and_quantize,
@@ -122,6 +121,36 @@ pub(crate) fn take_predicted_bits() -> Vec<f64> {
122121 const SPLIT_INTER_8: bool = true;
123122
124123 /// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
124+/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
125+/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
126+/// turns it off for an A/B on one build.
127+/// Whether an INTER frame also carries `TxMode::Select` (lane-av1tx step 2:
128+/// one `txfm_split` flag per inter block, a searched `tx_depth` on every
129+/// intra block inside the inter frame). OFF by default and opt-in through
130+/// `EC_AV1_TX_SELECT_INTER=1`: the syntax is written but a stream carrying it
131+/// is refused by dav1d and by this crate's own decoder, and the first
132+/// diverging symbol was not located inside the lane's budget. Key frames are
133+/// unaffected -- they are byte-exact with [`tx_select`] on.
134+fn tx_select_inter() -> bool {
135+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
136+ *ON.get_or_init(|| {
137+ matches!(
138+ std::env::var("EC_AV1_TX_SELECT_INTER").as_deref(),
139+ Ok("1") | Ok("on")
140+ )
141+ })
142+}
143+
144+fn tx_select() -> bool {
145+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
146+ *ON.get_or_init(|| {
147+ !matches!(
148+ std::env::var("EC_AV1_TX_SELECT").as_deref(),
149+ Ok("0") | Ok("off")
150+ )
151+ })
152+}
153+
125154 fn split_inter_8() -> bool {
126155 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
127156 Some(v) if cfg!(test) => v != "0",
@@ -951,6 +980,55 @@ impl Plane<'_> {
951980 }
952981 }
953982
983+ /// Codes this block's luma at transform depth `depth`: the
984+ /// `(side >> depth)^2` transform units in raster order, each predicted
985+ /// from the reconstruction the units before it left behind -- exactly
986+ /// what the decoder's multi-transform-unit branch does (decode.rs
987+ /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
988+ /// reconstructed on its own. Commits the result and hands back the
989+ /// block-coordinate levels, the block's squared error and what its
990+ /// coefficients cost.
991+ fn code_tx_depth(
992+ &mut self,
993+ at: At,
994+ mode: u8,
995+ depth: usize,
996+ search: &Search, fctx: &crate::decode::FrameCtx,
997+ ) -> (Vec<i32>, f64, f64) {
998+ let At { x, y, side, reach, .. } = at;
999+ let tx = side >> depth;
1000+ let n = 1usize << depth;
1001+ let set = match tx {
1002+ 32 => TxbSet::Luma32,
1003+ 16 => TxbSet::Luma16,
1004+ 8 => TxbSet::Luma8,
1005+ _ => TxbSet::Luma4,
1006+ };
1007+ let mut levels = vec![0i32; side * side];
1008+ let (mut sse, mut bits) = (0.0, 0.0);
1009+ for tu_row in 0..n {
1010+ for tu_col in 0..n {
1011+ let (col_off, row_off) = (tu_col * tx, tu_row * tx);
1012+ let tu = At {
1013+ x: x + col_off,
1014+ y: y + row_off,
1015+ side: tx,
1016+ reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
1017+ set,
1018+ };
1019+ let trial = self.trial(tu, mode, search.base_q_idx, search.deadzone, fctx);
1020+ sse += trial.sse;
1021+ bits += trial.bits;
1022+ self.commit(tu.x, tu.y, tx, &trial);
1023+ for row in 0..tx {
1024+ levels[(row_off + row) * side + col_off..][..tx]
1025+ .copy_from_slice(&trial.levels[row * tx..][..tx]);
1026+ }
1027+ }
1028+ }
1029+ (levels, sse, bits)
1030+ }
1031+
9541032 /// Writes a trial's reconstruction back into the plane.
9551033 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
9561034 for row in 0..side {
@@ -1675,13 +1753,55 @@ pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
16751753 /// Codes one square of the picture as a single block: searches the luma mode,
16761754 /// codes both chroma planes DC, and hands back the block and what it cost --
16771755 /// squared error plus lambda times the bits its symbols spend.
1756+/// How many halvings of a `side`-square block's transform the `tx_depth`
1757+/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
1758+/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
1759+fn max_tx_depth(side: usize) -> usize {
1760+ match side {
1761+ 8 => 1,
1762+ 16 | 32 => 2,
1763+ _ => 0,
1764+ }
1765+}
1766+
1767+/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
1768+/// Priced at context row 0 -- the writer picks the real row from its
1769+/// neighbours' transform sizes, which the search has no view of; the term is
1770+/// the same for every depth of one block either way, so it only shifts the
1771+/// depth-0-versus-split margin, never the ordering between two splits.
1772+fn tx_depth_bits(side: usize, depth: usize) -> f64 {
1773+ match side {
1774+ 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
1775+ 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
1776+ 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
1777+ _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
1778+ }
1779+}
1780+
1781+/// How many blocks resolved to each `tx_depth`, the fire count that says
1782+/// whether the depth search below reaches its candidates at all.
1783+static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
1784+ [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
1785+
1786+/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
1787+/// to its own encode.
1788+#[cfg(test)]
1789+pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
1790+ std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
1791+}
1792+
1793+#[allow(clippy::too_many_arguments)]
16781794 fn code_square(
16791795 luma: &mut Plane,
16801796 chroma: &mut [Plane; 2],
16811797 (x, y): (usize, usize),
16821798 side: usize,
16831799 search: &Search,
1684- mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
1800+ mode_bits: &[f64; 13],
1801+ // The frame header's `tx_mode == TxMode::Select`: the block then searches
1802+ // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
1803+ // transform over its whole side.
1804+ tx_select: bool, fctx: &crate::decode::FrameCtx,
16851805 ) -> (BlockCoeffs, f64) {
16861806 let (luma_set, chroma_set) = if side == BLOCK {
16871807 (TxbSet::Luma32, TxbSet::Chroma16)
@@ -1697,17 +1817,40 @@ fn code_square(
16971817 } else {
16981818 (TxbSet::Luma16, TxbSet::Chroma8)
16991819 };
1700- let (luma_coeffs, mode, mut cost) = luma.search_block(
1701- At {
1702- x,
1703- y,
1704- side,
1705- reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
1706- set: luma_set,
1707- },
1708- search,
1709- mode_bits, fctx,
1710- );
1820+ let at = At {
1821+ x,
1822+ y,
1823+ side,
1824+ reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
1825+ set: luma_set,
1826+ };
1827+ let (mut luma_coeffs, mode, mut cost) = luma.search_block(at, search, mode_bits, fctx);
1828+ // The depth search runs on the mode the whole-block transform picked --
1829+ // libaom's own ordering, and the reason it costs one extra pass per depth
1830+ // rather than one per (mode, depth) pair.
1831+ let mut tx_depth = 0u8;
1832+ if tx_select && max_tx_depth(side) > 0 {
1833+ let mut best = (
1834+ cost + search.lambda * tx_depth_bits(side, 0),
1835+ 0usize,
1836+ luma.snapshot(x, y, side),
1837+ luma_coeffs,
1838+ );
1839+ for depth in 1..=max_tx_depth(side) {
1840+ let (levels, sse, bits) = luma.code_tx_depth(at, mode, depth, search, fctx);
1841+ let cost_d = sse
1842+ + search.lambda
1843+ * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));
1844+ if cost_d < best.0 {
1845+ best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
1846+ }
1847+ }
1848+ luma.restore(x, y, side, &best.2);
1849+ cost = best.0;
1850+ tx_depth = best.1 as u8;
1851+ luma_coeffs = best.3;
1852+ TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1853+ }
17111854 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
17121855 // planes; what it costs still counts towards the partition decision.
17131856 let ([u, v], uv_mode, chroma_cost) =
@@ -1720,6 +1863,7 @@ fn code_square(
17201863 luma: luma_coeffs,
17211864 mode,
17221865 uv_mode,
1866+ tx_depth,
17231867 ..BlockCoeffs::default()
17241868 },
17251869 cost,
@@ -1838,7 +1982,17 @@ fn code_square_inter(
18381982 reference: &Picture,
18391983 stack: &MvStack, fctx: &crate::decode::FrameCtx,
18401984 ) -> (BlockCoeffs, f64) {
1841- let (intra_block, intra_cost) = code_square(luma, chroma, (x, y), side, search, mode_bits, fctx);
1985+ let (intra_block, intra_cost) =
1986+ code_square(
1987+ luma,
1988+ chroma,
1989+ (x, y),
1990+ side,
1991+ search,
1992+ mode_bits,
1993+ tx_select() && tx_select_inter(),
1994+ fctx,
1995+ );
18421996 let luma_set = if side == 8 {
18431997 TxbSet::Luma8Inter
18441998 } else {
@@ -2045,6 +2199,7 @@ fn code_square_inter(
20452199 uv_mode: DC_PRED,
20462200 skip: skip_new,
20472201 eight: None,
2202+ tx_depth: 0,
20482203 inter: Some(InterInfo {
20492204 mode: InterMode::NewMv,
20502205 mv: new_mv,
@@ -2067,6 +2222,7 @@ fn code_square_inter(
20672222 uv_mode: DC_PRED,
20682223 skip,
20692224 eight: None,
2225+ tx_depth: 0,
20702226 inter: Some(InterInfo {
20712227 mode: InterMode::NearestMv,
20722228 mv,
@@ -2462,6 +2618,15 @@ pub(crate) fn encode_key_frame_inner(
24622618 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
24632619 header.render_width = render.0 as u32;
24642620 header.render_height = render.1 as u32;
2621+ // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
2622+ // its luma transform below its own side (`crate::tile::write_luma_select`).
2623+ // Set here rather than in `key_frame_headers_colour` so the header
2624+ // builders' other callers -- the hand-built tile writers, which code no
2625+ // depth symbol -- keep the `TxMode::Largest` stream they are written for.
2626+ let tx_select = tx_select();
2627+ if tx_select {
2628+ header.tx_mode = TxMode::Select;
2629+ }
24652630
24662631 // Prediction reads no further than this, in each plane's own units --
24672632 // see `Plane::true_width`/`true_height`.
@@ -2614,7 +2779,8 @@ pub(crate) fn encode_key_frame_inner(
26142779 (x, y),
26152780 BLOCK,
26162781 &search,
2617- &mode_bits(above_mode[c0], left_mode[r0]), fctx,
2782+ &mode_bits(above_mode[c0], left_mode[r0]),
2783+ tx_select, fctx,
26182784 );
26192785 cost_whole += search.lambda * partition_bits(BLOCK, false);
26202786 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
@@ -2647,7 +2813,8 @@ pub(crate) fn encode_key_frame_inner(
26472813 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
26482814 SUB,
26492815 &search,
2650- &mode_bits(above_mode[sc], left_mode[sr]), fctx,
2816+ &mode_bits(above_mode[sc], left_mode[sr]),
2817+ tx_select, fctx,
26512818 );
26522819 cost_split += cost;
26532820 split_modes.push(block.mode);
@@ -2678,7 +2845,8 @@ pub(crate) fn encode_key_frame_inner(
26782845 (leaf_x, leaf_y),
26792846 8,
26802847 &search,
2681- &leaf_mode_bits, fctx,
2848+ &leaf_mode_bits,
2849+ tx_select, fctx,
26822850 );
26832851 cost_split += cost;
26842852 split_modes.push(leaf.mode);
@@ -2718,7 +2886,13 @@ pub(crate) fn encode_key_frame_inner(
27182886
27192887 #[cfg(test)]
27202888 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
2721- let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &superblocks)?;
2889+ let tile = crate::tile::sb_coeff_key_frame_tile_tx(
2890+ header.mi_cols,
2891+ header.mi_rows,
2892+ base_q_idx,
2893+ &superblocks,
2894+ tx_select,
2895+ )?;
27222896 let mut stream = temporal_delimiter();
27232897 stream.extend_from_slice(&sequence_header_obu(&seq)?);
27242898 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -3323,6 +3497,7 @@ fn search_inter_block(
33233497 skip: best.skip,
33243498 inter: best.inter,
33253499 eight: None,
3500+ tx_depth: 0,
33263501 },
33273502 best.cost,
33283503 )
@@ -3370,6 +3545,14 @@ pub(crate) fn encode_inter_frame(
33703545 inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?;
33713546 header.render_width = render.0 as u32;
33723547 header.render_height = render.1 as u32;
3548+ // `TxMode::Select` here too: an inter block then codes one `txfm_split`
3549+ // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
3550+ // block inside this frame codes and searches its own `tx_depth`, the same
3551+ // as in a key frame (`crate::tile::write_tx_syntax_inter`).
3552+ let tx_select = tx_select() && tx_select_inter();
3553+ if tx_select {
3554+ header.tx_mode = TxMode::Select;
3555+ }
33733556
33743557 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
33753558 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
@@ -3793,7 +3976,13 @@ pub(crate) fn encode_inter_frame(
37933976 / modes.len() as f64;
37943977 #[cfg(test)]
37953978 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
3796- let tile = sb_coeff_inter_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &blocks)?;
3979+ let tile = crate::tile::sb_coeff_inter_frame_tile_tx(
3980+ header.mi_cols,
3981+ header.mi_rows,
3982+ base_q_idx,
3983+ &blocks,
3984+ tx_select,
3985+ )?;
37973986 let mut stream = temporal_delimiter();
37983987 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
37993988
@@ -4201,6 +4390,7 @@ mod tests {
42014390 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
42024391 let (width, height) = (64usize, 64usize);
42034392 let picture = test_card(width, height);
4393+ let _ = take_tx_depth_hits();
42044394 for &q in &[15u8, 45, 100, 200] {
42054395 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
42064396 let decoded = ffmpeg_decode(&encoded.stream, width, height);
@@ -4208,6 +4398,18 @@ mod tests {
42084398 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
42094399 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
42104400 }
4401+ // lane-av1tx: the exactness above is only a claim about SPLIT
4402+ // transforms if some block actually split one (`gate-blind-to-feature`
4403+ // -- with `tx_depth` stuck at 0 every assert here passes on the
4404+ // pre-lane stream). The test card's edges split at these four
4405+ // quantizers; the counter is per-process (another test encoding in
4406+ // parallel can only ADD to it, so this can be masked, never falsely
4407+ // failed), so it is read once for the whole q ladder.
4408+ let depths = take_tx_depth_hits();
4409+ assert!(
4410+ depths[1] + depths[2] > 0,
4411+ "no block split its transform: depths {depths:?}"
4412+ );
42114413 }
42124414
42134415 /// The minimal repro that isolated the inter-residual desync: a key frame
@@ -4246,6 +4448,7 @@ mod tests {
42464448 uv_mode: 0,
42474449 skip: false,
42484450 eight: None,
4451+ tx_depth: 0,
42494452 inter: Some(InterInfo {
42504453 mode: InterMode::NearestMv,
42514454 mv: (0, 0),
@@ -4266,7 +4469,7 @@ mod tests {
42664469 Quadrant::Whole(skipped_block),
42674470 ];
42684471 let tile =
4269- sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
4472+ crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
42704473 .unwrap();
42714474
42724475 // `key.stream` is already a temporal delimiter, the sequence header
@@ -5062,7 +5265,25 @@ mod tests {
50625265 let high = reference[reference.len() - 1]
50635266 .0
50645267 .min(other[other.len() - 1].0);
5065- assert!(high > low, "the two ladders have to overlap in PSNR");
5268+ // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
5269+ // the non-directional one on the synthetic diagonals -- every point
5270+ // both higher in PSNR *and* lower in rate -- so there is no PSNR band
5271+ // to integrate over any more. A curve that dominates that way has
5272+ // saved everything the measure can express (the
5273+ // `instrument-at-bound` class: the answer is at the instrument's own
5274+ // edge, not undefined), so name it rather than panicking; anything
5275+ // less clean than strict dominance still is.
5276+ if high <= low {
5277+ let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
5278+ let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
5279+ let dominates = other[0].0 > reference[reference.len() - 1].0
5280+ && other_hi_rate <= ref_lo_rate;
5281+ assert!(
5282+ dominates,
5283+ "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
5284+ );
5285+ return -1.0;
5286+ }
50665287 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
50675288 let i = curve
50685289 .windows(2)
@@ -5343,7 +5564,12 @@ mod tests {
53435564 // CDF while the writer codes it against an adapted one -- 311 -> 319
53445565 // bytes at q 120->121 on this picture. The table this gate is really
53455566 // watching would move the rate by far more than the mode churn does.
5346- // Ceiling: a q-context table wrong by under 5% would pass. Upgrade
5567+ // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
5568+ // same block can also change transform DEPTH between two neighbouring
5569+ // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
5570+ // symbol is priced off the static CDF row 0 for the same reason the
5571+ // uv_mode one is.
5572+ // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
53475573 // path is pricing through the adapting CDF state (what
53485574 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
53495575 // drift of), after which the exact bound comes back.
@@ -5351,7 +5577,7 @@ mod tests {
53515577 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
53525578 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
53535579 assert!(
5354- hi_bytes as f64 <= lo_bytes as f64 * 1.05,
5580+ hi_bytes as f64 <= lo_bytes as f64 * 1.10,
53555581 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
53565582 );
53575583 }
@@ -6613,6 +6839,23 @@ mod tests {
66136839 .collect::<Vec<_>>()
66146840 .join(" ")
66156841 );
6842+ // Which transform depth the intra blocks of this clip's key
6843+ // frames resolved to (lane-av1tx): depth 0 is one transform over
6844+ // the whole block, 1 and 2 its halvings.
6845+ let depths = take_tx_depth_hits();
6846+ let depth_total: usize = depths.iter().sum();
6847+ eprintln!(
6848+ "{name}: intra tx depths {}",
6849+ depths
6850+ .iter()
6851+ .enumerate()
6852+ .map(|(d, &n)| format!(
6853+ "{d}={n} ({:.1}%)",
6854+ 100.0 * n as f64 / depth_total.max(1) as f64
6855+ ))
6856+ .collect::<Vec<_>>()
6857+ .join(" ")
6858+ );
66166859 let (aom, aom_wall) =
66176860 external_ladder(&source, width, height, "libaom-av1", &aom_points);
66186861 let (rav1e, rav1e_wall) =
crates/ec-av1/src/tile.rsmodified+530 -13
@@ -15,6 +15,7 @@ use ec_core::{Error, Result};
1515
1616 use crate::cdf;
1717 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
18+use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
1819 use crate::msac::SymbolEncoder;
1920 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx};
2021
@@ -477,6 +478,13 @@ pub struct BlockCoeffs {
477478 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
478479 /// per-quadrant fields are unused.
479480 pub eight: Option<Vec<BlockCoeffs>>,
481+ /// How many times this block's luma transform is halved under
482+ /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole
483+ /// block). Read only by the writers a `tx_select` frame calls; a
484+ /// `TxMode::Largest` frame codes no symbol and leaves this at zero.
485+ /// `luma` then carries the whole block's levels in BLOCK coordinates,
486+ /// which the writer slices per transform unit.
487+ pub tx_depth: u8,
480488 }
481489
482490 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec
@@ -543,6 +551,11 @@ const MI: usize = 4;
543551 struct Neighbour {
544552 /// Whether the plane's transform block carried a coefficient.
545553 coded: bool,
554+ /// Its cumulative coefficient level (spec `cul_level`, clamped to 7) --
555+ /// what the *luma* `txb_skip_ctx` of a transform unit smaller than its
556+ /// own block reads (`get_txb_ctx_general`, decode.rs `luma_skip_ctx`),
557+ /// where "coded or not" is not enough.
558+ level: u8,
546559 /// The sign of its DC, absent when the DC itself is zero.
547560 dc: Option<bool>,
548561 }
@@ -640,6 +653,23 @@ struct Neighbours {
640653 above_skip: Vec<bool>,
641654 /// The same, down the left edge.
642655 left_skip: Vec<bool>,
656+ /// The side, in pixels, of the transform last written in this 4x4
657+ /// mode-info column -- the deblock `tx_grid` a key frame's
658+ /// `get_tx_size_context` reads (decode.rs `tx_size_context`/`tx_px_at`),
659+ /// which is what picks the CDF row of a `TxMode::Select` block's
660+ /// `tx_depth` symbol.
661+ above_tx: Vec<u8>,
662+ /// The same, down the left edge (the transform's HEIGHT, `tx_h_px_at`;
663+ /// every transform this writer codes is square, so one value serves).
664+ left_tx: Vec<u8>,
665+ /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), per
666+ /// 4x4 mode-info unit: what an INTER frame's `txfm_split` and `tx_depth`
667+ /// symbols read their context from (decode.rs `txfm_partition_ctx_rect`/
668+ /// `tx_size_context_txfm_rect`). Initialised to the widest transform, not
669+ /// zero (decode.rs `TXFM_CTX_INIT`).
670+ above_txfm: Vec<u8>,
671+ /// The same, down the left edge (transform HEIGHT).
672+ left_txfm: Vec<u8>,
643673 /// Whether the neighbour was coded inter, for the `is_inter` context.
644674 /// Unused by the key frame writers.
645675 above_inter: Vec<bool>,
@@ -688,6 +718,10 @@ impl Neighbours {
688718 left_skip: vec![false; rows * (SUB / MI)],
689719 above_inter: vec![false; cols * (SUB / MI)],
690720 left_inter: vec![false; rows * (SUB / MI)],
721+ above_tx: vec![0; cols * (SUB / MI)],
722+ left_tx: vec![0; rows * (SUB / MI)],
723+ above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)],
724+ left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)],
691725 mi_cols,
692726 mi_rows,
693727 }
@@ -701,6 +735,90 @@ impl Neighbours {
701735 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
702736 self.left_skip.iter_mut().for_each(|s| *s = false);
703737 self.left_inter.iter_mut().for_each(|i| *i = false);
738+ self.left_tx.iter_mut().for_each(|t| *t = 0);
739+ self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT);
740+ }
741+
742+ /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block
743+ /// of an INTER frame leaves in the two `TXFM_CONTEXT` bands -- its
744+ /// resolved transform size over the span `(w_px, h_px)`, which for a
745+ /// SKIPPED inter block is its own block size instead.
746+ fn record_txfm(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, w_px: usize, h_px: usize) {
747+ for i in 0..h_px / MI {
748+ if let Some(cell) = self.left_txfm.get_mut(mi_r + i) {
749+ *cell = tx_px as u8;
750+ }
751+ }
752+ for i in 0..w_px / MI {
753+ if let Some(cell) = self.above_txfm.get_mut(mi_c + i) {
754+ *cell = tx_px as u8;
755+ }
756+ }
757+ }
758+
759+ /// `get_tx_size_context` as libaom writes it for a block inside an INTER
760+ /// frame (decode.rs `tx_size_context_txfm_rect`): the `TXFM_CONTEXT`
761+ /// bands, except that an *inter* neighbour contributes its own BLOCK size.
762+ fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize {
763+ let mut above = usize::from(self.above_txfm[mi_c]) >= own_side;
764+ let mut left = usize::from(self.left_txfm[mi_r]) >= own_side;
765+ if mi_r > 0 && self.above_inter[mi_c] {
766+ above = self.above_side_mi[mi_c] >= own_side;
767+ }
768+ if mi_c > 0 && self.left_inter[mi_r] {
769+ left = self.left_side_mi[mi_r] >= own_side;
770+ }
771+ usize::from(above) + usize::from(left)
772+ }
773+
774+ /// `get_tx_size_context` (decode.rs [`crate::decode::tx_size_context`]):
775+ /// whether the transform above is at least as wide as this block's own
776+ /// largest transform, plus whether the one to the left is at least as
777+ /// tall. A neighbour outside the tile contributes nothing.
778+ fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize {
779+ usize::from(mi_r > 0 && usize::from(self.above_tx[mi_c]) >= max_tx)
780+ + usize::from(mi_c > 0 && usize::from(self.left_tx[mi_r]) >= max_tx)
781+ }
782+
783+ /// Publishes one block's resolved transform side over every 4x4 unit it
784+ /// covers, the way the decoder's `fill_lf_grid` does at the end of every
785+ /// block.
786+ fn record_tx(&mut self, (mi_r, mi_c): (usize, usize), side: usize, tx_px: usize) {
787+ for cell in 0..side / MI {
788+ if mi_r + cell < self.left_tx.len() {
789+ self.left_tx[mi_r + cell] = tx_px as u8;
790+ }
791+ if mi_c + cell < self.above_tx.len() {
792+ self.above_tx[mi_c + cell] = tx_px as u8;
793+ }
794+ }
795+ }
796+
797+ /// The luma `txb_skip_ctx` of a transform unit smaller than its own block
798+ /// (decode.rs `Neighbours::luma_skip_ctx`): the above and left magnitude
799+ /// tiers, each ORed over the unit's own span and clamped to 4.
800+ fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize {
801+ let mut top = 0u8;
802+ let mut left = 0u8;
803+ for cell in 0..side_mi {
804+ top |= self.above[mi_c + cell][0].level;
805+ left |= self.left[mi_r + cell][0].level;
806+ }
807+ crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
808+ }
809+
810+ /// Publishes ONE luma transform unit's coefficient context, the way the
811+ /// decoder's `record_mi_luma` does between the units of a split block.
812+ fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) {
813+ let state = neighbour_state(grid);
814+ for cell in 0..tx_px / MI {
815+ if mi_r + cell < self.mi_rows {
816+ self.left[mi_r + cell][0] = state;
817+ }
818+ if mi_c + cell < self.mi_cols {
819+ self.above[mi_c + cell][0] = state;
820+ }
821+ }
704822 }
705823
706824 /// Writes one coded block into every 16x16 column and row it covers, and,
@@ -711,6 +829,22 @@ impl Neighbours {
711829 /// derived from the true `mi_cols`/`mi_rows`, not from this block's own
712830 /// side).
713831 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
832+ self.record_planes(at, side, mode, grids, true);
833+ }
834+
835+ /// [`Self::record`] with a switch for plane 0: a block whose luma was
836+ /// written as several transform units published each unit's own context
837+ /// as it went ([`Self::record_mi_luma`]), so the whole-block write here
838+ /// would clobber what the next block reads (decode.rs
839+ /// `record_split_luma`).
840+ fn record_planes(
841+ &mut self,
842+ at: (usize, usize),
843+ side: usize,
844+ mode: usize,
845+ grids: &[Vec<i32>; 3],
846+ luma: bool,
847+ ) {
714848 let (r, c) = at;
715849 for cell in 0..side / SUB {
716850 self.above_mode[c + cell] = mode;
@@ -718,7 +852,7 @@ impl Neighbours {
718852 self.above_side[c + cell] = side;
719853 self.left_side[r + cell] = side;
720854 }
721- self.record_mi((r * (SUB / MI), c * (SUB / MI)), side, grids);
855+ self.record_mi_planes((r * (SUB / MI), c * (SUB / MI)), side, grids, luma);
722856 }
723857
724858 /// The coefficient-context half of [`Self::record`], taking the block's
@@ -729,6 +863,17 @@ impl Neighbours {
729863 /// grid, so no resizing is needed to write into them at this
730864 /// finer-than-SUB granularity.
731865 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
866+ self.record_mi_planes(at_mi, side, grids, true);
867+ }
868+
869+ /// [`Self::record_mi`] with [`Self::record_planes`]'s plane-0 switch.
870+ fn record_mi_planes(
871+ &mut self,
872+ at_mi: (usize, usize),
873+ side: usize,
874+ grids: &[Vec<i32>; 3],
875+ luma: bool,
876+ ) {
732877 let (mi_r, mi_c) = at_mi;
733878 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
734879 let side_mi = side / MI;
@@ -754,6 +899,8 @@ impl Neighbours {
754899 round_up_even(self.mi_cols),
755900 ];
756901 for cell in 0..side_mi {
902+ let keep_left = self.left[mi_r + cell][0];
903+ let keep_above = self.above[mi_c + cell][0];
757904 self.left[mi_r + cell] = std::array::from_fn(|plane| {
758905 if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) {
759906 states[plane]
@@ -768,6 +915,10 @@ impl Neighbours {
768915 Default::default()
769916 }
770917 });
918+ if !luma {
919+ self.left[mi_r + cell][0] = keep_left;
920+ self.above[mi_c + cell][0] = keep_above;
921+ }
771922 }
772923 }
773924
@@ -860,6 +1011,25 @@ pub fn sb_coeff_key_frame_tile(
8601011 mi_rows: u32,
8611012 base_q_idx: u8,
8621013 superblocks: &[Superblock],
1014+) -> Result<Vec<u8>> {
1015+ sb_coeff_key_frame_tile_tx(mi_cols, mi_rows, base_q_idx, superblocks, false)
1016+}
1017+
1018+/// [`sb_coeff_key_frame_tile`] for a frame header carrying
1019+/// `tx_mode == TxMode::Select` (`tx_select`): every block then codes a
1020+/// `tx_depth` symbol and, where that depth is nonzero, its luma residual as
1021+/// several transform units ([`write_luma_select`]). With `tx_select` false
1022+/// this writes exactly the stream it always did.
1023+///
1024+/// # Errors
1025+/// As [`sb_coeff_key_frame_tile`], plus a 64x64 block whose `tx_depth` is
1026+/// nonzero (not written yet).
1027+pub fn sb_coeff_key_frame_tile_tx(
1028+ mi_cols: u32,
1029+ mi_rows: u32,
1030+ base_q_idx: u8,
1031+ superblocks: &[Superblock],
1032+ tx_select: bool,
8631033 ) -> Result<Vec<u8>> {
8641034 check_blocks(mi_cols, mi_rows)?;
8651035 let (cols, rows) = block_grid(mi_cols, mi_rows);
@@ -978,7 +1148,9 @@ pub fn sb_coeff_key_frame_tile(
9781148 // A 64x64 block is too big to be offered chroma from
9791149 // luma, so its chroma mode reads the table without it.
9801150 false,
981- );
1151+ tx_select,
1152+ &scans,
1153+ )?;
9821154 ec_rng_trace(|| {
9831155 format!(
9841156 "EC_TOK mi_row={} mi_col={} tell={}",
@@ -1056,7 +1228,9 @@ pub fn sb_coeff_key_frame_tile(
10561228 &grids,
10571229 [&scans[0], &scans[1], &scans[1]],
10581230 true,
1059- );
1231+ tx_select,
1232+ &scans,
1233+ )?;
10601234 ec_rng_trace(|| {
10611235 format!(
10621236 "EC_TOK mi_row={} mi_col={} tell={}",
@@ -1149,7 +1323,9 @@ pub fn sb_coeff_key_frame_tile(
11491323 &grids,
11501324 [&scans[1], &scans[2], &scans[2]],
11511325 true,
1152- );
1326+ tx_select,
1327+ &scans,
1328+ )?;
11531329 ec_rng_trace(|| {
11541330 format!(
11551331 "EC_TOK mi_row={} mi_col={} tell={}",
@@ -1251,7 +1427,9 @@ pub fn sb_coeff_key_frame_tile(
12511427 &grids,
12521428 [&scans[2], &scans[3], &scans[3]],
12531429 prev_leaf,
1254- );
1430+ tx_select,
1431+ &scans,
1432+ )?;
12551433 prev_leaf = Some((leaf_mi, leaf_mode));
12561434 ec_rng_trace(|| {
12571435 format!(
@@ -1345,7 +1523,13 @@ fn write_block(
13451523 grids: &[Vec<i32>; 3],
13461524 scans: [&Vec<u16>; 3],
13471525 cfl: bool,
1348-) {
1526+ // The frame's `tx_mode == TxMode::Select`, and the block's own chosen
1527+ // depth: with it the luma residual goes through [`write_luma_select`]
1528+ // (one `tx_depth` symbol, then one transform unit per tile of the block)
1529+ // instead of the single whole-block transform below.
1530+ tx_select: bool,
1531+ all_scans: &[Vec<u16>; 4],
1532+) -> Result<()> {
13491533 let (r, c) = at;
13501534 let mode = write_intra_mode(
13511535 enc,
@@ -1355,6 +1539,23 @@ fn write_block(
13551539 neighbours.left_mode[r],
13561540 cfl,
13571541 );
1542+ let at_mi = (r * (SUB / MI), c * (SUB / MI));
1543+ let split = if tx_select {
1544+ let tx = write_luma_select(
1545+ enc,
1546+ cdfs,
1547+ neighbours,
1548+ at_mi,
1549+ side,
1550+ usize::from(block.tx_depth),
1551+ &grids[0],
1552+ mode,
1553+ all_scans,
1554+ )?;
1555+ tx < side
1556+ } else {
1557+ false
1558+ };
13581559 write_block_planes(
13591560 enc,
13601561 cdfs,
@@ -1363,8 +1564,10 @@ fn write_block(
13631564 &scans,
13641565 &neighbours.around(at, side),
13651566 mode,
1567+ tx_select,
13661568 );
1367- neighbours.record(at, side, mode, grids);
1569+ neighbours.record_planes(at, side, mode, grids, !split);
1570+ Ok(())
13681571 }
13691572
13701573 /// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
@@ -1386,7 +1589,9 @@ fn write_leaf8(
13861589 grids: &[Vec<i32>; 3],
13871590 scans: [&Vec<u16>; 3],
13881591 prev_leaf: Option<((usize, usize), usize)>,
1389-) -> usize {
1592+ tx_select: bool,
1593+ all_scans: &[Vec<u16>; 4],
1594+) -> Result<usize> {
13901595 let (r, c) = outer_at;
13911596 let mut above_mode = neighbours.above_mode[c];
13921597 let mut left_mode = neighbours.left_mode[r];
@@ -1410,6 +1615,22 @@ fn write_leaf8(
14101615 // unchanged).
14111616 let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true);
14121617 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];
1618+ let split = if tx_select {
1619+ let tx = write_luma_select(
1620+ enc,
1621+ cdfs,
1622+ neighbours,
1623+ leaf_mi,
1624+ 8,
1625+ usize::from(block.tx_depth),
1626+ &grids[0],
1627+ mode,
1628+ all_scans,
1629+ )?;
1630+ tx < 8
1631+ } else {
1632+ false
1633+ };
14131634 write_block_planes(
14141635 enc,
14151636 cdfs,
@@ -1418,9 +1639,10 @@ fn write_leaf8(
14181639 &scans,
14191640 &neighbours.around_mi(leaf_mi, 8),
14201641 mode,
1642+ tx_select,
14211643 );
1422- neighbours.record_mi(leaf_mi, 8, grids);
1423- mode
1644+ neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
1645+ Ok(mode)
14241646 }
14251647
14261648 /// Writes the three transform blocks of one coded block, in the order a
@@ -1434,8 +1656,14 @@ fn write_block_planes(
14341656 scans: &[&Vec<u16>; 3],
14351657 around: &[Around; 3],
14361658 mode: usize,
1659+ // A block whose luma was already written as several transform units
1660+ // ([`write_luma_select`]) has only its chroma planes left here.
1661+ skip_luma: bool,
14371662 ) {
14381663 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
1664+ if plane == 0 && skip_luma {
1665+ continue;
1666+ }
14391667 // Luma's transform covers its whole block, which fixes the all-zero
14401668 // flag's context at zero; a chroma transform reads whether its
14411669 // neighbours coded anything, on top of the offset the chroma tables
@@ -1464,11 +1692,190 @@ fn write_block_planes(
14641692 }
14651693 }
14661694
1695+/// The `(side / tx)^2` transform units of one block's luma residual, raster
1696+/// order, each with its own coefficient context and each published before the
1697+/// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch).
1698+/// `grid` is the block's levels in BLOCK coordinates when the transform
1699+/// splits, and the single transform's own coefficient grid when it does not.
1700+#[allow(clippy::too_many_arguments)]
1701+fn write_luma_tus(
1702+ enc: &mut SymbolEncoder,
1703+ cdfs: &mut Cdfs,
1704+ neighbours: &mut Neighbours,
1705+ at_mi: (usize, usize),
1706+ side: usize,
1707+ tx: usize,
1708+ grid: &[i32],
1709+ mode: usize,
1710+ scans: &[Vec<u16>; 4],
1711+) -> Result<()> {
1712+ if tx < side && side > 32 {
1713+ // A 64x64 block's own levels reach the writer as the 32x32 corner a
1714+ // 64-point transform codes, not as a 64x64 block grid, so there is
1715+ // nothing to slice per unit here.
1716+ return Err(Error::unsupported(
1717+ "AV1 tile",
1718+ "a 64x64 block's split luma transform is not written yet",
1719+ ));
1720+ }
1721+ let coeff_side = tx.min(32);
1722+ let n = side / tx;
1723+ let set = match tx {
1724+ 32 => TxbSet::Luma32,
1725+ 16 => TxbSet::Luma16,
1726+ 8 => TxbSet::Luma8,
1727+ 4 => TxbSet::Luma4,
1728+ _ => TxbSet::Luma64,
1729+ };
1730+ let scan = match coeff_side {
1731+ 32 => &scans[0],
1732+ 16 => &scans[1],
1733+ 8 => &scans[2],
1734+ _ => &scans[3],
1735+ };
1736+ let (mi_r, mi_c) = at_mi;
1737+ for tu_row in 0..n {
1738+ for tu_col in 0..n {
1739+ let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI));
1740+ let unit = if n == 1 {
1741+ grid.to_vec()
1742+ } else {
1743+ (0..tx)
1744+ .flat_map(|row| {
1745+ grid[(tu_row * tx + row) * side + tu_col * tx..][..tx].to_vec()
1746+ })
1747+ .collect()
1748+ };
1749+ // spec `get_txb_ctx_general`: a lone transform unit covering its
1750+ // whole block reads context 0, a smaller one the neighbour
1751+ // magnitude table.
1752+ let skip_ctx = if n == 1 {
1753+ 0
1754+ } else {
1755+ neighbours.luma_skip_ctx(tu_mi, tx / MI)
1756+ };
1757+ let around = neighbours.around_mi(tu_mi, tx)[0];
1758+ write_coeffs(
1759+ enc,
1760+ &mut cdfs.txb(set, mode),
1761+ &unit,
1762+ scan,
1763+ skip_ctx,
1764+ dc_sign_ctx(around.dc_vote),
1765+ Some(0),
1766+ );
1767+ if n > 1 {
1768+ neighbours.record_mi_luma(tu_mi, tx, &unit);
1769+ }
1770+ }
1771+ }
1772+ Ok(())
1773+}
1774+
1775+/// Writes one intra block's luma residual under `TxMode::Select`: the
1776+/// `tx_depth` symbol (spec 5.11.16 `read_selected_tx_size`, off the size
1777+/// category's own CDF at [`Neighbours::tx_size_ctx`]'s row), then the
1778+/// `(side / tx)^2` transform units in raster order -- each predicted and
1779+/// coded against what the units before it already left behind, which is why
1780+/// every unit publishes its own coefficient context before the next one reads
1781+/// it (decode.rs `decode_block`'s multi-transform-unit branch).
1782+///
1783+/// `grid` is the block's levels in BLOCK coordinates (`side` by `side`) when
1784+/// the transform splits, and the single transform's own coefficient grid when
1785+/// it does not. Hands back the resolved transform side in pixels.
1786+#[allow(clippy::too_many_arguments)]
1787+fn write_luma_select(
1788+ enc: &mut SymbolEncoder,
1789+ cdfs: &mut Cdfs,
1790+ neighbours: &mut Neighbours,
1791+ at_mi: (usize, usize),
1792+ side: usize,
1793+ depth: usize,
1794+ grid: &[i32],
1795+ mode: usize,
1796+ scans: &[Vec<u16>; 4],
1797+) -> Result<usize> {
1798+ let max_tx = side.min(64);
1799+ let ctx = neighbours.tx_size_ctx(at_mi, max_tx);
1800+ match max_tx {
1801+ 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
1802+ 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
1803+ 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
1804+ 64 => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
1805+ _ => {
1806+ return Err(Error::unsupported(
1807+ "AV1 tile",
1808+ "a tx_depth symbol is only coded at 8/16/32/64",
1809+ ));
1810+ }
1811+ }
1812+ let tx = max_tx >> depth;
1813+ write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans)?;
1814+ neighbours.record_tx(at_mi, side, tx);
1815+ Ok(tx)
1816+}
1817+
1818+/// The transform syntax one block of an INTER frame coded with
1819+/// `tx_mode == TxMode::Select` carries, in the place spec 5.11.16's
1820+/// `read_block_tx_size` reads it -- after the modes and the motion vector,
1821+/// before the residual:
1822+/// * an inter block that codes a residual walks a var-tx tree; this writer
1823+/// keeps it at its own largest transform, so that is one `txfm_split` flag
1824+/// of zero, off `txfm_partition_ctx_rect`'s row, publishing the bands per
1825+/// unit the way `read_var_tx_size` does.
1826+/// * a skipped inter block codes nothing and records its own BLOCK size
1827+/// (`set_txfm_ctxs`'s `skip_inter` term).
1828+/// * an intra block codes `tx_depth` like a key frame's, but off the
1829+/// `TXFM_CONTEXT` bands rather than the deblock grid.
1830+///
1831+/// Hands back the block's resolved luma transform side.
1832+#[allow(clippy::too_many_arguments)]
1833+fn write_tx_syntax_inter(
1834+ enc: &mut SymbolEncoder,
1835+ cdfs: &mut Cdfs,
1836+ neighbours: &mut Neighbours,
1837+ at_mi: (usize, usize),
1838+ side: usize,
1839+ is_inter: bool,
1840+ skip: bool,
1841+ depth: usize,
1842+) -> usize {
1843+ let max_tx = side.min(64);
1844+ let (mi_r, mi_c) = at_mi;
1845+ if is_inter {
1846+ if !skip {
1847+ let ctx = txfm_partition_ctx_rect(
1848+ neighbours.above_txfm[mi_c],
1849+ neighbours.left_txfm[mi_r],
1850+ side,
1851+ max_tx,
1852+ max_tx,
1853+ );
1854+ enc.symbol(0, &mut cdfs.txfm_partition[ctx]);
1855+ neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx);
1856+ } else {
1857+ neighbours.record_txfm(at_mi, side, side, side);
1858+ }
1859+ return max_tx;
1860+ }
1861+ let ctx = neighbours.tx_size_ctx_txfm(at_mi, max_tx);
1862+ match max_tx {
1863+ 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]),
1864+ 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]),
1865+ 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]),
1866+ _ => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]),
1867+ }
1868+ let tx = max_tx >> depth;
1869+ neighbours.record_txfm(at_mi, tx, side, side);
1870+ tx
1871+}
1872+
14671873 /// What a coded transform block leaves behind for the blocks that read it as a
14681874 /// neighbour.
14691875 fn neighbour_state(grid: &[i32]) -> Neighbour {
14701876 Neighbour {
14711877 coded: grid.iter().any(|&l| l != 0),
1878+ level: grid.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8,
14721879 dc: (grid[0] != 0).then_some(grid[0] < 0),
14731880 }
14741881 }
@@ -2211,6 +2618,25 @@ pub fn sb_coeff_inter_frame_tile(
22112618 mi_rows: u32,
22122619 base_q_idx: u8,
22132620 blocks: &[Quadrant],
2621+) -> Result<Vec<u8>> {
2622+ sb_coeff_inter_frame_tile_tx(mi_cols, mi_rows, base_q_idx, blocks, false)
2623+}
2624+
2625+/// [`sb_coeff_inter_frame_tile`] for a frame header carrying
2626+/// `tx_mode == TxMode::Select`: every block then codes the transform syntax
2627+/// [`write_tx_syntax_inter`] writes -- one `txfm_split` flag on an inter
2628+/// block that carries a residual, a `tx_depth` symbol on an intra one -- and
2629+/// an intra block whose depth is nonzero codes its luma as several transform
2630+/// units. With `tx_select` false this writes exactly the stream it always did.
2631+///
2632+/// # Errors
2633+/// As [`sb_coeff_inter_frame_tile`].
2634+pub fn sb_coeff_inter_frame_tile_tx(
2635+ mi_cols: u32,
2636+ mi_rows: u32,
2637+ base_q_idx: u8,
2638+ blocks: &[Quadrant],
2639+ tx_select: bool,
22142640 ) -> Result<Vec<u8>> {
22152641 check_blocks(mi_cols, mi_rows)?;
22162642 // `block_grid`'s ceiling, not a plain division: a true frame size that is
@@ -2265,6 +2691,14 @@ pub fn sb_coeff_inter_frame_tile(
22652691 let scan16 = default_scan(TX16);
22662692 let scan8 = default_scan(TX8);
22672693 let scan4 = default_scan(TX4);
2694+ // The same four tables again as one array, which is what the per-unit
2695+ // luma writer indexes by transform side.
2696+ let all_scans = [
2697+ scan32.clone(),
2698+ scan16.clone(),
2699+ scan8.clone(),
2700+ scan4.clone(),
2701+ ];
22682702 let zero_grids = [
22692703 vec![0i32; TX32 * TX32],
22702704 vec![0i32; TX16 * TX16],
@@ -2428,6 +2862,8 @@ pub fn sb_coeff_inter_frame_tile(
24282862 leaf_mi,
24292863 &scan8,
24302864 &scan4,
2865+ tx_select,
2866+ &all_scans,
24312867 )?;
24322868 let _ = (skip, is_inter);
24332869 }
@@ -2445,6 +2881,8 @@ pub fn sb_coeff_inter_frame_tile(
24452881 at16,
24462882 &scan16,
24472883 &scan8,
2884+ tx_select,
2885+ &all_scans,
24482886 )?;
24492887 } else {
24502888 let ctx16 = neighbours.partition_ctx(at16, SUB);
@@ -2493,6 +2931,8 @@ pub fn sb_coeff_inter_frame_tile(
24932931 leaf_mi,
24942932 &scan8,
24952933 &scan4,
2934+ tx_select,
2935+ &all_scans,
24962936 )?;
24972937 let _ = (skip, is_inter);
24982938 }
@@ -2644,6 +3084,22 @@ pub fn sb_coeff_inter_frame_tile(
26443084 }
26453085 }
26463086
3087+ let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
3088+ let tx = if tx_select {
3089+ write_tx_syntax_inter(
3090+ &mut enc,
3091+ &mut cdfs,
3092+ &mut neighbours,
3093+ at_mi,
3094+ BLOCK,
3095+ is_inter,
3096+ block.skip,
3097+ usize::from(block.tx_depth),
3098+ )
3099+ } else {
3100+ BLOCK
3101+ };
3102+ let split = tx < BLOCK;
26473103 if block.skip {
26483104 neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);
26493105 } else {
@@ -2652,6 +3108,19 @@ pub fn sb_coeff_inter_frame_tile(
26523108 level_grid(&block.u, TX16)?,
26533109 level_grid(&block.v, TX16)?,
26543110 ];
3111+ if split {
3112+ write_luma_tus(
3113+ &mut enc,
3114+ &mut cdfs,
3115+ &mut neighbours,
3116+ at_mi,
3117+ BLOCK,
3118+ tx,
3119+ &grids[0],
3120+ mode_for_tx,
3121+ &all_scans,
3122+ )?;
3123+ }
26553124 write_block_planes(
26563125 &mut enc,
26573126 &mut cdfs,
@@ -2664,8 +3133,9 @@ pub fn sb_coeff_inter_frame_tile(
26643133 &[&scan32, &scan16, &scan16],
26653134 &neighbours.around(at, BLOCK),
26663135 mode_for_tx,
3136+ split,
26673137 );
2668- neighbours.record(at, BLOCK, mode_for_tx, &grids);
3138+ neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
26693139 }
26703140 neighbours.record_inter(at, BLOCK, block.skip, is_inter);
26713141 }
@@ -2696,6 +3166,8 @@ fn write_inter_frame_leaf(
26963166 at: (usize, usize),
26973167 scan16: &Vec<u16>,
26983168 scan8: &Vec<u16>,
3169+ tx_select: bool,
3170+ all_scans: &[Vec<u16>; 4],
26993171 ) -> Result<()> {
27003172 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
27013173 return Err(Error::unsupported(
@@ -2824,6 +3296,22 @@ fn write_inter_frame_leaf(
28243296 }
28253297 }
28263298
3299+ let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI));
3300+ let tx = if tx_select {
3301+ write_tx_syntax_inter(
3302+ enc,
3303+ cdfs,
3304+ neighbours,
3305+ at_mi,
3306+ SUB,
3307+ is_inter,
3308+ block.skip,
3309+ usize::from(block.tx_depth),
3310+ )
3311+ } else {
3312+ SUB
3313+ };
3314+ let split = tx < SUB;
28273315 if block.skip {
28283316 let zero_grids = [
28293317 vec![0i32; TX16 * TX16],
@@ -2837,6 +3325,11 @@ fn write_inter_frame_leaf(
28373325 level_grid(&block.u, TX8)?,
28383326 level_grid(&block.v, TX8)?,
28393327 ];
3328+ if split {
3329+ write_luma_tus(
3330+ enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans,
3331+ )?;
3332+ }
28403333 write_block_planes(
28413334 enc,
28423335 cdfs,
@@ -2849,8 +3342,9 @@ fn write_inter_frame_leaf(
28493342 &[scan16, scan8, scan8],
28503343 &neighbours.around(at, SUB),
28513344 mode_for_tx,
3345+ split,
28523346 );
2853- neighbours.record(at, SUB, mode_for_tx, &grids);
3347+ neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
28543348 }
28553349 neighbours.record_inter(at, SUB, block.skip, is_inter);
28563350 Ok(())
@@ -2885,6 +3379,8 @@ fn write_inter_frame_leaf8(
28853379 leaf_mi: (usize, usize),
28863380 scan8: &Vec<u16>,
28873381 scan4: &Vec<u16>,
3382+ tx_select: bool,
3383+ all_scans: &[Vec<u16>; 4],
28883384 ) -> Result<(bool, bool)> {
28893385 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
28903386 return Err(Error::unsupported(
@@ -3025,6 +3521,21 @@ fn write_inter_frame_leaf8(
30253521 } else {
30263522 [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]
30273523 };
3524+ let tx = if tx_select {
3525+ write_tx_syntax_inter(
3526+ enc,
3527+ cdfs,
3528+ neighbours,
3529+ leaf_mi,
3530+ 8,
3531+ is_inter,
3532+ block.skip,
3533+ usize::from(block.tx_depth),
3534+ )
3535+ } else {
3536+ 8
3537+ };
3538+ let split = tx < 8;
30283539 if block.skip {
30293540 let zero_grids = [
30303541 vec![0i32; TX8 * TX8],
@@ -3039,6 +3550,11 @@ fn write_inter_frame_leaf8(
30393550 level_grid(&block.u, TX4)?,
30403551 level_grid(&block.v, TX4)?,
30413552 ];
3553+ if split {
3554+ write_luma_tus(
3555+ enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans,
3556+ )?;
3557+ }
30423558 write_block_planes(
30433559 enc,
30443560 cdfs,
@@ -3047,8 +3563,9 @@ fn write_inter_frame_leaf8(
30473563 &[scan8, scan4, scan4],
30483564 &neighbours.around_mi(leaf_mi, 8),
30493565 mode_for_tx,
3566+ split,
30503567 );
3051- neighbours.record_mi(leaf_mi, 8, &grids);
3568+ neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
30523569 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter);
30533570 }
30543571 Ok((block.skip, is_inter))