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 {
6558 /// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,6558 /// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0,
6559 /// transform unit smaller than the block it sits in): `top`/`left` are the6559 /// transform unit smaller than the block it sits in): `top`/`left` are the
6560 /// above/left neighbours' magnitude tiers, each already clamped to 4.6560 /// 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] = [
6562 [1, 2, 2, 2, 3],6562 [1, 2, 2, 2, 3],
6563 [2, 4, 4, 4, 5],6563 [2, 4, 4, 4, 5],
6564 [2, 4, 4, 4, 5],6564 [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
16962 /// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one16962 /// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one
16963 /// side for a square transform, which is why the square form above is a16963 /// side for a square transform, which is why the square form above is a
16964 /// special case of this one.16964 /// special case of this one.
16965-fn txfm_partition_ctx_rect(16965+pub(crate) fn txfm_partition_ctx_rect(
16966 above_px: u8,16966 above_px: u8,
16967 left_px: u8,16967 left_px: u8,
16968 blk_max_px: usize,16968 blk_max_px: usize,
@@ -17092,7 +17092,7 @@ fn set_txfm_ctxs(
17092 /// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 6417092 /// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64
17093 /// pixels, so an unwritten neighbour reads as the *widest* possible17093 /// pixels, so an unwritten neighbour reads as the *widest* possible
17094 /// transform, not the narrowest.17094 /// transform, not the narrowest.
17095-const TXFM_CTX_INIT: u8 = 64;17095+pub(crate) const TXFM_CTX_INIT: u8 = 64;
17096 17096
17097 /// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most17097 /// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most
17098 /// twice below its own largest transform.17098 /// twice below its own largest transform.
crates/ec-av1/src/encode.rsmodified+266 -23
@@ -39,7 +39,6 @@ use crate::quant::ac_q;
39 use crate::sequence::sequence_header_obu;39 use crate::sequence::sequence_header_obu;
40 use crate::tile::{40 use crate::tile::{
41 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,41 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
42- sb_coeff_inter_frame_tile, sb_coeff_key_frame_tile,
43 };42 };
44 use crate::transform::{43 use crate::transform::{
45 TxType, dequant_and_inverse, dequant_and_inverse_typed, forward_and_quantize,44 TxType, dequant_and_inverse, dequant_and_inverse_typed, forward_and_quantize,
@@ -122,6 +121,36 @@ pub(crate) fn take_predicted_bits() -> Vec<f64> {
122 const SPLIT_INTER_8: bool = true;121 const SPLIT_INTER_8: bool = true;
123 122
124 /// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.123 /// [`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+
125 fn split_inter_8() -> bool {154 fn split_inter_8() -> bool {
126 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {155 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
127 Some(v) if cfg!(test) => v != "0",156 Some(v) if cfg!(test) => v != "0",
@@ -951,6 +980,55 @@ impl Plane<'_> {
951 }980 }
952 }981 }
953 982
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+
954 /// Writes a trial's reconstruction back into the plane.1032 /// Writes a trial's reconstruction back into the plane.
955 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {1033 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
956 for row in 0..side {1034 for row in 0..side {
@@ -1675,13 +1753,55 @@ pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
1675 /// Codes one square of the picture as a single block: searches the luma mode,1753 /// Codes one square of the picture as a single block: searches the luma mode,
1676 /// codes both chroma planes DC, and hands back the block and what it cost --1754 /// codes both chroma planes DC, and hands back the block and what it cost --
1677 /// squared error plus lambda times the bits its symbols spend.1755 /// 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)]
1678 fn code_square(1794 fn code_square(
1679 luma: &mut Plane,1795 luma: &mut Plane,
1680 chroma: &mut [Plane; 2],1796 chroma: &mut [Plane; 2],
1681 (x, y): (usize, usize),1797 (x, y): (usize, usize),
1682 side: usize,1798 side: usize,
1683 search: &Search,1799 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,
1685 ) -> (BlockCoeffs, f64) {1805 ) -> (BlockCoeffs, f64) {
1686 let (luma_set, chroma_set) = if side == BLOCK {1806 let (luma_set, chroma_set) = if side == BLOCK {
1687 (TxbSet::Luma32, TxbSet::Chroma16)1807 (TxbSet::Luma32, TxbSet::Chroma16)
@@ -1697,17 +1817,40 @@ fn code_square(
1697 } else {1817 } else {
1698 (TxbSet::Luma16, TxbSet::Chroma8)1818 (TxbSet::Luma16, TxbSet::Chroma8)
1699 };1819 };
1700- let (luma_coeffs, mode, mut cost) = luma.search_block(1820+ let at = At {
1701- At {1821+ x,
1702- x,1822+ y,
1703- y,1823+ side,
1704- side,1824+ reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
1705- reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),1825+ set: luma_set,
1706- set: luma_set,1826+ };
1707- },1827+ let (mut luma_coeffs, mode, mut cost) = luma.search_block(at, search, mode_bits, fctx);
1708- search,1828+ // The depth search runs on the mode the whole-block transform picked --
1709- mode_bits, fctx,1829+ // libaom's own ordering, and the reason it costs one extra pass per depth
1710- );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+ }
1711 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both1854 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
1712 // planes; what it costs still counts towards the partition decision.1855 // planes; what it costs still counts towards the partition decision.
1713 let ([u, v], uv_mode, chroma_cost) =1856 let ([u, v], uv_mode, chroma_cost) =
@@ -1720,6 +1863,7 @@ fn code_square(
1720 luma: luma_coeffs,1863 luma: luma_coeffs,
1721 mode,1864 mode,
1722 uv_mode,1865 uv_mode,
1866+ tx_depth,
1723 ..BlockCoeffs::default()1867 ..BlockCoeffs::default()
1724 },1868 },
1725 cost,1869 cost,
@@ -1838,7 +1982,17 @@ fn code_square_inter(
1838 reference: &Picture,1982 reference: &Picture,
1839 stack: &MvStack, fctx: &crate::decode::FrameCtx,1983 stack: &MvStack, fctx: &crate::decode::FrameCtx,
1840 ) -> (BlockCoeffs, f64) {1984 ) -> (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+ );
1842 let luma_set = if side == 8 {1996 let luma_set = if side == 8 {
1843 TxbSet::Luma8Inter1997 TxbSet::Luma8Inter
1844 } else {1998 } else {
@@ -2045,6 +2199,7 @@ fn code_square_inter(
2045 uv_mode: DC_PRED,2199 uv_mode: DC_PRED,
2046 skip: skip_new,2200 skip: skip_new,
2047 eight: None,2201 eight: None,
2202+ tx_depth: 0,
2048 inter: Some(InterInfo {2203 inter: Some(InterInfo {
2049 mode: InterMode::NewMv,2204 mode: InterMode::NewMv,
2050 mv: new_mv,2205 mv: new_mv,
@@ -2067,6 +2222,7 @@ fn code_square_inter(
2067 uv_mode: DC_PRED,2222 uv_mode: DC_PRED,
2068 skip,2223 skip,
2069 eight: None,2224 eight: None,
2225+ tx_depth: 0,
2070 inter: Some(InterInfo {2226 inter: Some(InterInfo {
2071 mode: InterMode::NearestMv,2227 mode: InterMode::NearestMv,
2072 mv,2228 mv,
@@ -2462,6 +2618,15 @@ pub(crate) fn encode_key_frame_inner(
2462 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;2618 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
2463 header.render_width = render.0 as u32;2619 header.render_width = render.0 as u32;
2464 header.render_height = render.1 as u32;2620 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+ }
2465 2630
2466 // Prediction reads no further than this, in each plane's own units --2631 // Prediction reads no further than this, in each plane's own units --
2467 // see `Plane::true_width`/`true_height`.2632 // see `Plane::true_width`/`true_height`.
@@ -2614,7 +2779,8 @@ pub(crate) fn encode_key_frame_inner(
2614 (x, y),2779 (x, y),
2615 BLOCK,2780 BLOCK,
2616 &search,2781 &search,
2617- &mode_bits(above_mode[c0], left_mode[r0]), fctx,2782+ &mode_bits(above_mode[c0], left_mode[r0]),
2783+ tx_select, fctx,
2618 );2784 );
2619 cost_whole += search.lambda * partition_bits(BLOCK, false);2785 cost_whole += search.lambda * partition_bits(BLOCK, false);
2620 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);2786 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
@@ -2647,7 +2813,8 @@ pub(crate) fn encode_key_frame_inner(
2647 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),2813 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
2648 SUB,2814 SUB,
2649 &search,2815 &search,
2650- &mode_bits(above_mode[sc], left_mode[sr]), fctx,2816+ &mode_bits(above_mode[sc], left_mode[sr]),
2817+ tx_select, fctx,
2651 );2818 );
2652 cost_split += cost;2819 cost_split += cost;
2653 split_modes.push(block.mode);2820 split_modes.push(block.mode);
@@ -2678,7 +2845,8 @@ pub(crate) fn encode_key_frame_inner(
2678 (leaf_x, leaf_y),2845 (leaf_x, leaf_y),
2679 8,2846 8,
2680 &search,2847 &search,
2681- &leaf_mode_bits, fctx,2848+ &leaf_mode_bits,
2849+ tx_select, fctx,
2682 );2850 );
2683 cost_split += cost;2851 cost_split += cost;
2684 split_modes.push(leaf.mode);2852 split_modes.push(leaf.mode);
@@ -2718,7 +2886,13 @@ pub(crate) fn encode_key_frame_inner(
2718 2886
2719 #[cfg(test)]2887 #[cfg(test)]
2720 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));2888 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+ )?;
2722 let mut stream = temporal_delimiter();2896 let mut stream = temporal_delimiter();
2723 stream.extend_from_slice(&sequence_header_obu(&seq)?);2897 stream.extend_from_slice(&sequence_header_obu(&seq)?);
2724 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);2898 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
@@ -3323,6 +3497,7 @@ fn search_inter_block(
3323 skip: best.skip,3497 skip: best.skip,
3324 inter: best.inter,3498 inter: best.inter,
3325 eight: None,3499 eight: None,
3500+ tx_depth: 0,
3326 },3501 },
3327 best.cost,3502 best.cost,
3328 )3503 )
@@ -3370,6 +3545,14 @@ pub(crate) fn encode_inter_frame(
3370 inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?;3545 inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?;
3371 header.render_width = render.0 as u32;3546 header.render_width = render.0 as u32;
3372 header.render_height = render.1 as u32;3547 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+ }
3373 3556
3374 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);3557 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
3375 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once3558 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
@@ -3793,7 +3976,13 @@ pub(crate) fn encode_inter_frame(
3793 / modes.len() as f64;3976 / modes.len() as f64;
3794 #[cfg(test)]3977 #[cfg(test)]
3795 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));3978 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+ )?;
3797 let mut stream = temporal_delimiter();3986 let mut stream = temporal_delimiter();
3798 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);3987 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
3799 3988
@@ -4201,6 +4390,7 @@ mod tests {
4201 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.4390 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
4202 let (width, height) = (64usize, 64usize);4391 let (width, height) = (64usize, 64usize);
4203 let picture = test_card(width, height);4392 let picture = test_card(width, height);
4393+ let _ = take_tx_depth_hits();
4204 for &q in &[15u8, 45, 100, 200] {4394 for &q in &[15u8, 45, 100, 200] {
4205 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();4395 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
4206 let decoded = ffmpeg_decode(&encoded.stream, width, height);4396 let decoded = ffmpeg_decode(&encoded.stream, width, height);
@@ -4208,6 +4398,18 @@ mod tests {
4208 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");4398 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
4209 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");4399 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
4210 }4400 }
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+ );
4211 }4413 }
4212 4414
4213 /// The minimal repro that isolated the inter-residual desync: a key frame4415 /// The minimal repro that isolated the inter-residual desync: a key frame
@@ -4246,6 +4448,7 @@ mod tests {
4246 uv_mode: 0,4448 uv_mode: 0,
4247 skip: false,4449 skip: false,
4248 eight: None,4450 eight: None,
4451+ tx_depth: 0,
4249 inter: Some(InterInfo {4452 inter: Some(InterInfo {
4250 mode: InterMode::NearestMv,4453 mode: InterMode::NearestMv,
4251 mv: (0, 0),4454 mv: (0, 0),
@@ -4266,7 +4469,7 @@ mod tests {
4266 Quadrant::Whole(skipped_block),4469 Quadrant::Whole(skipped_block),
4267 ];4470 ];
4268 let tile =4471 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)
4270 .unwrap();4473 .unwrap();
4271 4474
4272 // `key.stream` is already a temporal delimiter, the sequence header4475 // `key.stream` is already a temporal delimiter, the sequence header
@@ -5062,7 +5265,25 @@ mod tests {
5062 let high = reference[reference.len() - 1]5265 let high = reference[reference.len() - 1]
5063 .05266 .0
5064 .min(other[other.len() - 1].0);5267 .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+ }
5066 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {5287 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
5067 let i = curve5288 let i = curve
5068 .windows(2)5289 .windows(2)
@@ -5343,7 +5564,12 @@ mod tests {
5343 // CDF while the writer codes it against an adapted one -- 311 -> 3195564 // CDF while the writer codes it against an adapted one -- 311 -> 319
5344 // bytes at q 120->121 on this picture. The table this gate is really5565 // bytes at q 120->121 on this picture. The table this gate is really
5345 // watching would move the rate by far more than the mode churn does.5566 // 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. Upgrade5567+ // 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
5347 // path is pricing through the adapting CDF state (what5573 // path is pricing through the adapting CDF state (what
5348 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the5574 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
5349 // drift of), after which the exact bound comes back.5575 // drift of), after which the exact bound comes back.
@@ -5351,7 +5577,7 @@ mod tests {
5351 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();5577 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
5352 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();5578 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
5353 assert!(5579 assert!(
5354- hi_bytes as f64 <= lo_bytes as f64 * 1.05,5580+ hi_bytes as f64 <= lo_bytes as f64 * 1.10,
5355 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"5581 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
5356 );5582 );
5357 }5583 }
@@ -6613,6 +6839,23 @@ mod tests {
6613 .collect::<Vec<_>>()6839 .collect::<Vec<_>>()
6614 .join(" ")6840 .join(" ")
6615 );6841 );
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+ );
6616 let (aom, aom_wall) =6859 let (aom, aom_wall) =
6617 external_ladder(&source, width, height, "libaom-av1", &aom_points);6860 external_ladder(&source, width, height, "libaom-av1", &aom_points);
6618 let (rav1e, rav1e_wall) =6861 let (rav1e, rav1e_wall) =
crates/ec-av1/src/tile.rsmodified+530 -13
@@ -15,6 +15,7 @@ use ec_core::{Error, Result};
15 15
16 use crate::cdf;16 use crate::cdf;
17 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};17 use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables};
18+use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect};
18 use crate::msac::SymbolEncoder;19 use crate::msac::SymbolEncoder;
19 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx};20 use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx};
20 21
@@ -477,6 +478,13 @@ pub struct BlockCoeffs {
477 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s478 /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s
478 /// per-quadrant fields are unused.479 /// per-quadrant fields are unused.
479 pub eight: Option<Vec<BlockCoeffs>>,480 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,
480 }488 }
481 489
482 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec490 /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec
@@ -543,6 +551,11 @@ const MI: usize = 4;
543 struct Neighbour {551 struct Neighbour {
544 /// Whether the plane's transform block carried a coefficient.552 /// Whether the plane's transform block carried a coefficient.
545 coded: bool,553 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,
546 /// The sign of its DC, absent when the DC itself is zero.559 /// The sign of its DC, absent when the DC itself is zero.
547 dc: Option<bool>,560 dc: Option<bool>,
548 }561 }
@@ -640,6 +653,23 @@ struct Neighbours {
640 above_skip: Vec<bool>,653 above_skip: Vec<bool>,
641 /// The same, down the left edge.654 /// The same, down the left edge.
642 left_skip: Vec<bool>,655 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>,
643 /// Whether the neighbour was coded inter, for the `is_inter` context.673 /// Whether the neighbour was coded inter, for the `is_inter` context.
644 /// Unused by the key frame writers.674 /// Unused by the key frame writers.
645 above_inter: Vec<bool>,675 above_inter: Vec<bool>,
@@ -688,6 +718,10 @@ impl Neighbours {
688 left_skip: vec![false; rows * (SUB / MI)],718 left_skip: vec![false; rows * (SUB / MI)],
689 above_inter: vec![false; cols * (SUB / MI)],719 above_inter: vec![false; cols * (SUB / MI)],
690 left_inter: vec![false; rows * (SUB / MI)],720 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)],
691 mi_cols,725 mi_cols,
692 mi_rows,726 mi_rows,
693 }727 }
@@ -701,6 +735,90 @@ impl Neighbours {
701 self.left_side_mi.iter_mut().for_each(|s| *s = SB);735 self.left_side_mi.iter_mut().for_each(|s| *s = SB);
702 self.left_skip.iter_mut().for_each(|s| *s = false);736 self.left_skip.iter_mut().for_each(|s| *s = false);
703 self.left_inter.iter_mut().for_each(|i| *i = false);737 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+ }
704 }822 }
705 823
706 /// Writes one coded block into every 16x16 column and row it covers, and,824 /// Writes one coded block into every 16x16 column and row it covers, and,
@@ -711,6 +829,22 @@ impl Neighbours {
711 /// derived from the true `mi_cols`/`mi_rows`, not from this block's own829 /// derived from the true `mi_cols`/`mi_rows`, not from this block's own
712 /// side).830 /// side).
713 fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {831 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+ ) {
714 let (r, c) = at;848 let (r, c) = at;
715 for cell in 0..side / SUB {849 for cell in 0..side / SUB {
716 self.above_mode[c + cell] = mode;850 self.above_mode[c + cell] = mode;
@@ -718,7 +852,7 @@ impl Neighbours {
718 self.above_side[c + cell] = side;852 self.above_side[c + cell] = side;
719 self.left_side[r + cell] = side;853 self.left_side[r + cell] = side;
720 }854 }
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);
722 }856 }
723 857
724 /// The coefficient-context half of [`Self::record`], taking the block's858 /// The coefficient-context half of [`Self::record`], taking the block's
@@ -729,6 +863,17 @@ impl Neighbours {
729 /// grid, so no resizing is needed to write into them at this863 /// grid, so no resizing is needed to write into them at this
730 /// finer-than-SUB granularity.864 /// finer-than-SUB granularity.
731 fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {865 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+ ) {
732 let (mi_r, mi_c) = at_mi;877 let (mi_r, mi_c) = at_mi;
733 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));878 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
734 let side_mi = side / MI;879 let side_mi = side / MI;
@@ -754,6 +899,8 @@ impl Neighbours {
754 round_up_even(self.mi_cols),899 round_up_even(self.mi_cols),
755 ];900 ];
756 for cell in 0..side_mi {901 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];
757 self.left[mi_r + cell] = std::array::from_fn(|plane| {904 self.left[mi_r + cell] = std::array::from_fn(|plane| {
758 if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) {905 if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) {
759 states[plane]906 states[plane]
@@ -768,6 +915,10 @@ impl Neighbours {
768 Default::default()915 Default::default()
769 }916 }
770 });917 });
918+ if !luma {
919+ self.left[mi_r + cell][0] = keep_left;
920+ self.above[mi_c + cell][0] = keep_above;
921+ }
771 }922 }
772 }923 }
773 924
@@ -860,6 +1011,25 @@ pub fn sb_coeff_key_frame_tile(
860 mi_rows: u32,1011 mi_rows: u32,
861 base_q_idx: u8,1012 base_q_idx: u8,
862 superblocks: &[Superblock],1013 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,
863 ) -> Result<Vec<u8>> {1033 ) -> Result<Vec<u8>> {
864 check_blocks(mi_cols, mi_rows)?;1034 check_blocks(mi_cols, mi_rows)?;
865 let (cols, rows) = block_grid(mi_cols, mi_rows);1035 let (cols, rows) = block_grid(mi_cols, mi_rows);
@@ -978,7 +1148,9 @@ pub fn sb_coeff_key_frame_tile(
978 // A 64x64 block is too big to be offered chroma from1148 // A 64x64 block is too big to be offered chroma from
979 // luma, so its chroma mode reads the table without it.1149 // luma, so its chroma mode reads the table without it.
980 false,1150 false,
981- );1151+ tx_select,
1152+ &scans,
1153+ )?;
982 ec_rng_trace(|| {1154 ec_rng_trace(|| {
983 format!(1155 format!(
984 "EC_TOK mi_row={} mi_col={} tell={}",1156 "EC_TOK mi_row={} mi_col={} tell={}",
@@ -1056,7 +1228,9 @@ pub fn sb_coeff_key_frame_tile(
1056 &grids,1228 &grids,
1057 [&scans[0], &scans[1], &scans[1]],1229 [&scans[0], &scans[1], &scans[1]],
1058 true,1230 true,
1059- );1231+ tx_select,
1232+ &scans,
1233+ )?;
1060 ec_rng_trace(|| {1234 ec_rng_trace(|| {
1061 format!(1235 format!(
1062 "EC_TOK mi_row={} mi_col={} tell={}",1236 "EC_TOK mi_row={} mi_col={} tell={}",
@@ -1149,7 +1323,9 @@ pub fn sb_coeff_key_frame_tile(
1149 &grids,1323 &grids,
1150 [&scans[1], &scans[2], &scans[2]],1324 [&scans[1], &scans[2], &scans[2]],
1151 true,1325 true,
1152- );1326+ tx_select,
1327+ &scans,
1328+ )?;
1153 ec_rng_trace(|| {1329 ec_rng_trace(|| {
1154 format!(1330 format!(
1155 "EC_TOK mi_row={} mi_col={} tell={}",1331 "EC_TOK mi_row={} mi_col={} tell={}",
@@ -1251,7 +1427,9 @@ pub fn sb_coeff_key_frame_tile(
1251 &grids,1427 &grids,
1252 [&scans[2], &scans[3], &scans[3]],1428 [&scans[2], &scans[3], &scans[3]],
1253 prev_leaf,1429 prev_leaf,
1254- );1430+ tx_select,
1431+ &scans,
1432+ )?;
1255 prev_leaf = Some((leaf_mi, leaf_mode));1433 prev_leaf = Some((leaf_mi, leaf_mode));
1256 ec_rng_trace(|| {1434 ec_rng_trace(|| {
1257 format!(1435 format!(
@@ -1345,7 +1523,13 @@ fn write_block(
1345 grids: &[Vec<i32>; 3],1523 grids: &[Vec<i32>; 3],
1346 scans: [&Vec<u16>; 3],1524 scans: [&Vec<u16>; 3],
1347 cfl: bool,1525 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<()> {
1349 let (r, c) = at;1533 let (r, c) = at;
1350 let mode = write_intra_mode(1534 let mode = write_intra_mode(
1351 enc,1535 enc,
@@ -1355,6 +1539,23 @@ fn write_block(
1355 neighbours.left_mode[r],1539 neighbours.left_mode[r],
1356 cfl,1540 cfl,
1357 );1541 );
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+ };
1358 write_block_planes(1559 write_block_planes(
1359 enc,1560 enc,
1360 cdfs,1561 cdfs,
@@ -1363,8 +1564,10 @@ fn write_block(
1363 &scans,1564 &scans,
1364 &neighbours.around(at, side),1565 &neighbours.around(at, side),
1365 mode,1566 mode,
1567+ tx_select,
1366 );1568 );
1367- neighbours.record(at, side, mode, grids);1569+ neighbours.record_planes(at, side, mode, grids, !split);
1570+ Ok(())
1368 }1571 }
1369 1572
1370 /// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own1573 /// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own
@@ -1386,7 +1589,9 @@ fn write_leaf8(
1386 grids: &[Vec<i32>; 3],1589 grids: &[Vec<i32>; 3],
1387 scans: [&Vec<u16>; 3],1590 scans: [&Vec<u16>; 3],
1388 prev_leaf: Option<((usize, usize), usize)>,1591 prev_leaf: Option<((usize, usize), usize)>,
1389-) -> usize {1592+ tx_select: bool,
1593+ all_scans: &[Vec<u16>; 4],
1594+) -> Result<usize> {
1390 let (r, c) = outer_at;1595 let (r, c) = outer_at;
1391 let mut above_mode = neighbours.above_mode[c];1596 let mut above_mode = neighbours.above_mode[c];
1392 let mut left_mode = neighbours.left_mode[r];1597 let mut left_mode = neighbours.left_mode[r];
@@ -1410,6 +1615,22 @@ fn write_leaf8(
1410 // unchanged).1615 // unchanged).
1411 let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true);1616 let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true);
1412 let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4];1617 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+ };
1413 write_block_planes(1634 write_block_planes(
1414 enc,1635 enc,
1415 cdfs,1636 cdfs,
@@ -1418,9 +1639,10 @@ fn write_leaf8(
1418 &scans,1639 &scans,
1419 &neighbours.around_mi(leaf_mi, 8),1640 &neighbours.around_mi(leaf_mi, 8),
1420 mode,1641 mode,
1642+ tx_select,
1421 );1643 );
1422- neighbours.record_mi(leaf_mi, 8, grids);1644+ neighbours.record_mi_planes(leaf_mi, 8, grids, !split);
1423- mode1645+ Ok(mode)
1424 }1646 }
1425 1647
1426 /// Writes the three transform blocks of one coded block, in the order a1648 /// Writes the three transform blocks of one coded block, in the order a
@@ -1434,8 +1656,14 @@ fn write_block_planes(
1434 scans: &[&Vec<u16>; 3],1656 scans: &[&Vec<u16>; 3],
1435 around: &[Around; 3],1657 around: &[Around; 3],
1436 mode: usize,1658 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,
1437 ) {1662 ) {
1438 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {1663 for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() {
1664+ if plane == 0 && skip_luma {
1665+ continue;
1666+ }
1439 // Luma's transform covers its whole block, which fixes the all-zero1667 // Luma's transform covers its whole block, which fixes the all-zero
1440 // flag's context at zero; a chroma transform reads whether its1668 // flag's context at zero; a chroma transform reads whether its
1441 // neighbours coded anything, on top of the offset the chroma tables1669 // neighbours coded anything, on top of the offset the chroma tables
@@ -1464,11 +1692,190 @@ fn write_block_planes(
1464 }1692 }
1465 }1693 }
1466 1694
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+
1467 /// What a coded transform block leaves behind for the blocks that read it as a1873 /// What a coded transform block leaves behind for the blocks that read it as a
1468 /// neighbour.1874 /// neighbour.
1469 fn neighbour_state(grid: &[i32]) -> Neighbour {1875 fn neighbour_state(grid: &[i32]) -> Neighbour {
1470 Neighbour {1876 Neighbour {
1471 coded: grid.iter().any(|&l| l != 0),1877 coded: grid.iter().any(|&l| l != 0),
1878+ level: grid.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8,
1472 dc: (grid[0] != 0).then_some(grid[0] < 0),1879 dc: (grid[0] != 0).then_some(grid[0] < 0),
1473 }1880 }
1474 }1881 }
@@ -2211,6 +2618,25 @@ pub fn sb_coeff_inter_frame_tile(
2211 mi_rows: u32,2618 mi_rows: u32,
2212 base_q_idx: u8,2619 base_q_idx: u8,
2213 blocks: &[Quadrant],2620 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,
2214 ) -> Result<Vec<u8>> {2640 ) -> Result<Vec<u8>> {
2215 check_blocks(mi_cols, mi_rows)?;2641 check_blocks(mi_cols, mi_rows)?;
2216 // `block_grid`'s ceiling, not a plain division: a true frame size that is2642 // `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(
2265 let scan16 = default_scan(TX16);2691 let scan16 = default_scan(TX16);
2266 let scan8 = default_scan(TX8);2692 let scan8 = default_scan(TX8);
2267 let scan4 = default_scan(TX4);2693 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+ ];
2268 let zero_grids = [2702 let zero_grids = [
2269 vec![0i32; TX32 * TX32],2703 vec![0i32; TX32 * TX32],
2270 vec![0i32; TX16 * TX16],2704 vec![0i32; TX16 * TX16],
@@ -2428,6 +2862,8 @@ pub fn sb_coeff_inter_frame_tile(
2428 leaf_mi,2862 leaf_mi,
2429 &scan8,2863 &scan8,
2430 &scan4,2864 &scan4,
2865+ tx_select,
2866+ &all_scans,
2431 )?;2867 )?;
2432 let _ = (skip, is_inter);2868 let _ = (skip, is_inter);
2433 }2869 }
@@ -2445,6 +2881,8 @@ pub fn sb_coeff_inter_frame_tile(
2445 at16,2881 at16,
2446 &scan16,2882 &scan16,
2447 &scan8,2883 &scan8,
2884+ tx_select,
2885+ &all_scans,
2448 )?;2886 )?;
2449 } else {2887 } else {
2450 let ctx16 = neighbours.partition_ctx(at16, SUB);2888 let ctx16 = neighbours.partition_ctx(at16, SUB);
@@ -2493,6 +2931,8 @@ pub fn sb_coeff_inter_frame_tile(
2493 leaf_mi,2931 leaf_mi,
2494 &scan8,2932 &scan8,
2495 &scan4,2933 &scan4,
2934+ tx_select,
2935+ &all_scans,
2496 )?;2936 )?;
2497 let _ = (skip, is_inter);2937 let _ = (skip, is_inter);
2498 }2938 }
@@ -2644,6 +3084,22 @@ pub fn sb_coeff_inter_frame_tile(
2644 }3084 }
2645 }3085 }
2646 3086
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;
2647 if block.skip {3103 if block.skip {
2648 neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);3104 neighbours.record(at, BLOCK, mode_for_tx, &zero_grids);
2649 } else {3105 } else {
@@ -2652,6 +3108,19 @@ pub fn sb_coeff_inter_frame_tile(
2652 level_grid(&block.u, TX16)?,3108 level_grid(&block.u, TX16)?,
2653 level_grid(&block.v, TX16)?,3109 level_grid(&block.v, TX16)?,
2654 ];3110 ];
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+ }
2655 write_block_planes(3124 write_block_planes(
2656 &mut enc,3125 &mut enc,
2657 &mut cdfs,3126 &mut cdfs,
@@ -2664,8 +3133,9 @@ pub fn sb_coeff_inter_frame_tile(
2664 &[&scan32, &scan16, &scan16],3133 &[&scan32, &scan16, &scan16],
2665 &neighbours.around(at, BLOCK),3134 &neighbours.around(at, BLOCK),
2666 mode_for_tx,3135 mode_for_tx,
3136+ split,
2667 );3137 );
2668- neighbours.record(at, BLOCK, mode_for_tx, &grids);3138+ neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split);
2669 }3139 }
2670 neighbours.record_inter(at, BLOCK, block.skip, is_inter);3140 neighbours.record_inter(at, BLOCK, block.skip, is_inter);
2671 }3141 }
@@ -2696,6 +3166,8 @@ fn write_inter_frame_leaf(
2696 at: (usize, usize),3166 at: (usize, usize),
2697 scan16: &Vec<u16>,3167 scan16: &Vec<u16>,
2698 scan8: &Vec<u16>,3168 scan8: &Vec<u16>,
3169+ tx_select: bool,
3170+ all_scans: &[Vec<u16>; 4],
2699 ) -> Result<()> {3171 ) -> Result<()> {
2700 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {3172 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
2701 return Err(Error::unsupported(3173 return Err(Error::unsupported(
@@ -2824,6 +3296,22 @@ fn write_inter_frame_leaf(
2824 }3296 }
2825 }3297 }
2826 3298
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;
2827 if block.skip {3315 if block.skip {
2828 let zero_grids = [3316 let zero_grids = [
2829 vec![0i32; TX16 * TX16],3317 vec![0i32; TX16 * TX16],
@@ -2837,6 +3325,11 @@ fn write_inter_frame_leaf(
2837 level_grid(&block.u, TX8)?,3325 level_grid(&block.u, TX8)?,
2838 level_grid(&block.v, TX8)?,3326 level_grid(&block.v, TX8)?,
2839 ];3327 ];
3328+ if split {
3329+ write_luma_tus(
3330+ enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans,
3331+ )?;
3332+ }
2840 write_block_planes(3333 write_block_planes(
2841 enc,3334 enc,
2842 cdfs,3335 cdfs,
@@ -2849,8 +3342,9 @@ fn write_inter_frame_leaf(
2849 &[scan16, scan8, scan8],3342 &[scan16, scan8, scan8],
2850 &neighbours.around(at, SUB),3343 &neighbours.around(at, SUB),
2851 mode_for_tx,3344 mode_for_tx,
3345+ split,
2852 );3346 );
2853- neighbours.record(at, SUB, mode_for_tx, &grids);3347+ neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split);
2854 }3348 }
2855 neighbours.record_inter(at, SUB, block.skip, is_inter);3349 neighbours.record_inter(at, SUB, block.skip, is_inter);
2856 Ok(())3350 Ok(())
@@ -2885,6 +3379,8 @@ fn write_inter_frame_leaf8(
2885 leaf_mi: (usize, usize),3379 leaf_mi: (usize, usize),
2886 scan8: &Vec<u16>,3380 scan8: &Vec<u16>,
2887 scan4: &Vec<u16>,3381 scan4: &Vec<u16>,
3382+ tx_select: bool,
3383+ all_scans: &[Vec<u16>; 4],
2888 ) -> Result<(bool, bool)> {3384 ) -> Result<(bool, bool)> {
2889 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {3385 if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES {
2890 return Err(Error::unsupported(3386 return Err(Error::unsupported(
@@ -3025,6 +3521,21 @@ fn write_inter_frame_leaf8(
3025 } else {3521 } else {
3026 [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]3522 [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]
3027 };3523 };
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;
3028 if block.skip {3539 if block.skip {
3029 let zero_grids = [3540 let zero_grids = [
3030 vec![0i32; TX8 * TX8],3541 vec![0i32; TX8 * TX8],
@@ -3039,6 +3550,11 @@ fn write_inter_frame_leaf8(
3039 level_grid(&block.u, TX4)?,3550 level_grid(&block.u, TX4)?,
3040 level_grid(&block.v, TX4)?,3551 level_grid(&block.v, TX4)?,
3041 ];3552 ];
3553+ if split {
3554+ write_luma_tus(
3555+ enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans,
3556+ )?;
3557+ }
3042 write_block_planes(3558 write_block_planes(
3043 enc,3559 enc,
3044 cdfs,3560 cdfs,
@@ -3047,8 +3563,9 @@ fn write_inter_frame_leaf8(
3047 &[scan8, scan4, scan4],3563 &[scan8, scan4, scan4],
3048 &neighbours.around_mi(leaf_mi, 8),3564 &neighbours.around_mi(leaf_mi, 8),
3049 mode_for_tx,3565 mode_for_tx,
3566+ split,
3050 );3567 );
3051- neighbours.record_mi(leaf_mi, 8, &grids);3568+ neighbours.record_mi_planes(leaf_mi, 8, &grids, !split);
3052 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter);3569 neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter);
3053 }3570 }
3054 Ok((block.skip, is_inter))3571 Ok((block.skip, is_inter))