diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index e8bbd8ab..62dd16ba 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -6558,7 +6558,7 @@ fn neighbour_state(grid: &[i32]) -> Neighbour { /// spec `get_txb_ctx_general`'s `skip_contexts[top][left]` table (plane 0, /// transform unit smaller than the block it sits in): `top`/`left` are the /// above/left neighbours' magnitude tiers, each already clamped to 4. -const SKIP_CONTEXTS: [[usize; 5]; 5] = [ +pub(crate) const SKIP_CONTEXTS: [[usize; 5]; 5] = [ [1, 2, 2, 2, 3], [2, 4, 4, 4, 5], [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 /// category from `txsize_sqr_up_map[tx_size]` -- all three collapse to one /// side for a square transform, which is why the square form above is a /// special case of this one. -fn txfm_partition_ctx_rect( +pub(crate) fn txfm_partition_ctx_rect( above_px: u8, left_px: u8, blk_max_px: usize, @@ -17092,7 +17092,7 @@ fn set_txfm_ctxs( /// with `tx_size_high[TX_SIZES_LARGEST]` (`av1_common_int.h`), i.e. 64 /// pixels, so an unwritten neighbour reads as the *widest* possible /// transform, not the narrowest. -const TXFM_CTX_INIT: u8 = 64; +pub(crate) const TXFM_CTX_INIT: u8 = 64; /// libaom's `MAX_VARTX_DEPTH`: an inter block's transform tree halves at most /// twice below its own largest transform. diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 6678a189..fed75396 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -39,7 +39,6 @@ use crate::quant::ac_q; use crate::sequence::sequence_header_obu; use crate::tile::{ BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits, - sb_coeff_inter_frame_tile, sb_coeff_key_frame_tile, }; use crate::transform::{ TxType, dequant_and_inverse, dequant_and_inverse_typed, forward_and_quantize, @@ -122,6 +121,36 @@ pub(crate) fn take_predicted_bits() -> Vec { const SPLIT_INTER_8: bool = true; /// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build. +/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each +/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0` +/// turns it off for an A/B on one build. +/// Whether an INTER frame also carries `TxMode::Select` (lane-av1tx step 2: +/// one `txfm_split` flag per inter block, a searched `tx_depth` on every +/// intra block inside the inter frame). OFF by default and opt-in through +/// `EC_AV1_TX_SELECT_INTER=1`: the syntax is written but a stream carrying it +/// is refused by dav1d and by this crate's own decoder, and the first +/// diverging symbol was not located inside the lane's budget. Key frames are +/// unaffected -- they are byte-exact with [`tx_select`] on. +fn tx_select_inter() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + matches!( + std::env::var("EC_AV1_TX_SELECT_INTER").as_deref(), + Ok("1") | Ok("on") + ) + }) +} + +fn tx_select() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + !matches!( + std::env::var("EC_AV1_TX_SELECT").as_deref(), + Ok("0") | Ok("off") + ) + }) +} + fn split_inter_8() -> bool { match std::env::var("EC_AV1_SPLIT_INTER8").ok() { Some(v) if cfg!(test) => v != "0", @@ -951,6 +980,55 @@ impl Plane<'_> { } } + /// Codes this block's luma at transform depth `depth`: the + /// `(side >> depth)^2` transform units in raster order, each predicted + /// from the reconstruction the units before it left behind -- exactly + /// what the decoder's multi-transform-unit branch does (decode.rs + /// `decode_block`, `tu_reach`) -- and each transformed, quantised and + /// reconstructed on its own. Commits the result and hands back the + /// block-coordinate levels, the block's squared error and what its + /// coefficients cost. + fn code_tx_depth( + &mut self, + at: At, + mode: u8, + depth: usize, + search: &Search, fctx: &crate::decode::FrameCtx, + ) -> (Vec, f64, f64) { + let At { x, y, side, reach, .. } = at; + let tx = side >> depth; + let n = 1usize << depth; + let set = match tx { + 32 => TxbSet::Luma32, + 16 => TxbSet::Luma16, + 8 => TxbSet::Luma8, + _ => TxbSet::Luma4, + }; + let mut levels = vec![0i32; side * side]; + let (mut sse, mut bits) = (0.0, 0.0); + for tu_row in 0..n { + for tu_col in 0..n { + let (col_off, row_off) = (tu_col * tx, tu_row * tx); + let tu = At { + x: x + col_off, + y: y + row_off, + side: tx, + reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach), + set, + }; + let trial = self.trial(tu, mode, search.base_q_idx, search.deadzone, fctx); + sse += trial.sse; + bits += trial.bits; + self.commit(tu.x, tu.y, tx, &trial); + for row in 0..tx { + levels[(row_off + row) * side + col_off..][..tx] + .copy_from_slice(&trial.levels[row * tx..][..tx]); + } + } + } + (levels, sse, bits) + } + /// Writes a trial's reconstruction back into the plane. fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { for row in 0..side { @@ -1675,13 +1753,55 @@ pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { /// Codes one square of the picture as a single block: searches the luma mode, /// codes both chroma planes DC, and hands back the block and what it cost -- /// squared error plus lambda times the bits its symbols spend. +/// How many halvings of a `side`-square block's transform the `tx_depth` +/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two +/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform. +fn max_tx_depth(side: usize) -> usize { + match side { + 8 => 1, + 16 | 32 => 2, + _ => 0, + } +} + +/// What the `tx_depth` symbol itself costs, off the size category's own CDF. +/// Priced at context row 0 -- the writer picks the real row from its +/// neighbours' transform sizes, which the search has no view of; the term is +/// the same for every depth of one block either way, so it only shifts the +/// depth-0-versus-split margin, never the ordering between two splits. +fn tx_depth_bits(side: usize, depth: usize) -> f64 { + match side { + 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth), + 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth), + 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth), + _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth), + } +} + +/// How many blocks resolved to each `tx_depth`, the fire count that says +/// whether the depth search below reaches its candidates at all. +static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; + +/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts +/// to its own encode. +#[cfg(test)] +pub(crate) fn take_tx_depth_hits() -> [usize; 3] { + std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) +} + +#[allow(clippy::too_many_arguments)] fn code_square( luma: &mut Plane, chroma: &mut [Plane; 2], (x, y): (usize, usize), side: usize, search: &Search, - mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx, + mode_bits: &[f64; 13], + // The frame header's `tx_mode == TxMode::Select`: the block then searches + // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one + // transform over its whole side. + tx_select: bool, fctx: &crate::decode::FrameCtx, ) -> (BlockCoeffs, f64) { let (luma_set, chroma_set) = if side == BLOCK { (TxbSet::Luma32, TxbSet::Chroma16) @@ -1697,17 +1817,40 @@ fn code_square( } else { (TxbSet::Luma16, TxbSet::Chroma8) }; - let (luma_coeffs, mode, mut cost) = luma.search_block( - At { - x, - y, - side, - reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx), - set: luma_set, - }, - search, - mode_bits, fctx, - ); + let at = At { + x, + y, + side, + reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx), + set: luma_set, + }; + let (mut luma_coeffs, mode, mut cost) = luma.search_block(at, search, mode_bits, fctx); + // The depth search runs on the mode the whole-block transform picked -- + // libaom's own ordering, and the reason it costs one extra pass per depth + // rather than one per (mode, depth) pair. + let mut tx_depth = 0u8; + if tx_select && max_tx_depth(side) > 0 { + let mut best = ( + cost + search.lambda * tx_depth_bits(side, 0), + 0usize, + luma.snapshot(x, y, side), + luma_coeffs, + ); + for depth in 1..=max_tx_depth(side) { + let (levels, sse, bits) = luma.code_tx_depth(at, mode, depth, search, fctx); + let cost_d = sse + + search.lambda + * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth)); + if cost_d < best.0 { + best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side)); + } + } + luma.restore(x, y, side, &best.2); + cost = best.0; + tx_depth = best.1 as u8; + luma_coeffs = best.3; + TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both // planes; what it costs still counts towards the partition decision. let ([u, v], uv_mode, chroma_cost) = @@ -1720,6 +1863,7 @@ fn code_square( luma: luma_coeffs, mode, uv_mode, + tx_depth, ..BlockCoeffs::default() }, cost, @@ -1838,7 +1982,17 @@ fn code_square_inter( reference: &Picture, stack: &MvStack, fctx: &crate::decode::FrameCtx, ) -> (BlockCoeffs, f64) { - let (intra_block, intra_cost) = code_square(luma, chroma, (x, y), side, search, mode_bits, fctx); + let (intra_block, intra_cost) = + code_square( + luma, + chroma, + (x, y), + side, + search, + mode_bits, + tx_select() && tx_select_inter(), + fctx, + ); let luma_set = if side == 8 { TxbSet::Luma8Inter } else { @@ -2045,6 +2199,7 @@ fn code_square_inter( uv_mode: DC_PRED, skip: skip_new, eight: None, + tx_depth: 0, inter: Some(InterInfo { mode: InterMode::NewMv, mv: new_mv, @@ -2067,6 +2222,7 @@ fn code_square_inter( uv_mode: DC_PRED, skip, eight: None, + tx_depth: 0, inter: Some(InterInfo { mode: InterMode::NearestMv, mv, @@ -2462,6 +2618,15 @@ pub(crate) fn encode_key_frame_inner( let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; header.render_width = render.0 as u32; header.render_height = render.1 as u32; + // `TxMode::Select`: every block codes a `tx_depth` symbol and may split + // its luma transform below its own side (`crate::tile::write_luma_select`). + // Set here rather than in `key_frame_headers_colour` so the header + // builders' other callers -- the hand-built tile writers, which code no + // depth symbol -- keep the `TxMode::Largest` stream they are written for. + let tx_select = tx_select(); + if tx_select { + header.tx_mode = TxMode::Select; + } // Prediction reads no further than this, in each plane's own units -- // see `Plane::true_width`/`true_height`. @@ -2614,7 +2779,8 @@ pub(crate) fn encode_key_frame_inner( (x, y), BLOCK, &search, - &mode_bits(above_mode[c0], left_mode[r0]), fctx, + &mode_bits(above_mode[c0], left_mode[r0]), + tx_select, fctx, ); cost_whole += search.lambda * partition_bits(BLOCK, false); let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); @@ -2647,7 +2813,8 @@ pub(crate) fn encode_key_frame_inner( (x + (sub % 2) * SUB, y + (sub / 2) * SUB), SUB, &search, - &mode_bits(above_mode[sc], left_mode[sr]), fctx, + &mode_bits(above_mode[sc], left_mode[sr]), + tx_select, fctx, ); cost_split += cost; split_modes.push(block.mode); @@ -2678,7 +2845,8 @@ pub(crate) fn encode_key_frame_inner( (leaf_x, leaf_y), 8, &search, - &leaf_mode_bits, fctx, + &leaf_mode_bits, + tx_select, fctx, ); cost_split += cost; split_modes.push(leaf.mode); @@ -2718,7 +2886,13 @@ pub(crate) fn encode_key_frame_inner( #[cfg(test)] record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); - let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &superblocks)?; + let tile = crate::tile::sb_coeff_key_frame_tile_tx( + header.mi_cols, + header.mi_rows, + base_q_idx, + &superblocks, + tx_select, + )?; let mut stream = temporal_delimiter(); stream.extend_from_slice(&sequence_header_obu(&seq)?); stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); @@ -3323,6 +3497,7 @@ fn search_inter_block( skip: best.skip, inter: best.inter, eight: None, + tx_depth: 0, }, best.cost, ) @@ -3370,6 +3545,14 @@ pub(crate) fn encode_inter_frame( inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?; header.render_width = render.0 as u32; header.render_height = render.1 as u32; + // `TxMode::Select` here too: an inter block then codes one `txfm_split` + // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA + // block inside this frame codes and searches its own `tx_depth`, the same + // as in a key frame (`crate::tile::write_tx_syntax_inter`). + let tx_select = tx_select() && tx_select_inter(); + if tx_select { + header.tx_mode = TxMode::Select; + } let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); // lane-hbd r4: encoder stays 8-bit by design; narrow the source once @@ -3793,7 +3976,13 @@ pub(crate) fn encode_inter_frame( / modes.len() as f64; #[cfg(test)] record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); - let tile = sb_coeff_inter_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &blocks)?; + let tile = crate::tile::sb_coeff_inter_frame_tile_tx( + header.mi_cols, + header.mi_rows, + base_q_idx, + &blocks, + tx_select, + )?; let mut stream = temporal_delimiter(); stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); @@ -4201,6 +4390,7 @@ mod tests { // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size. let (width, height) = (64usize, 64usize); let picture = test_card(width, height); + let _ = take_tx_depth_hits(); for &q in &[15u8, 45, 100, 200] { let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); let decoded = ffmpeg_decode(&encoded.stream, width, height); @@ -4208,6 +4398,18 @@ mod tests { assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); } + // lane-av1tx: the exactness above is only a claim about SPLIT + // transforms if some block actually split one (`gate-blind-to-feature` + // -- with `tx_depth` stuck at 0 every assert here passes on the + // pre-lane stream). The test card's edges split at these four + // quantizers; the counter is per-process (another test encoding in + // parallel can only ADD to it, so this can be masked, never falsely + // failed), so it is read once for the whole q ladder. + let depths = take_tx_depth_hits(); + assert!( + depths[1] + depths[2] > 0, + "no block split its transform: depths {depths:?}" + ); } /// The minimal repro that isolated the inter-residual desync: a key frame @@ -4246,6 +4448,7 @@ mod tests { uv_mode: 0, skip: false, eight: None, + tx_depth: 0, inter: Some(InterInfo { mode: InterMode::NearestMv, mv: (0, 0), @@ -4266,7 +4469,7 @@ mod tests { Quadrant::Whole(skipped_block), ]; let tile = - sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks) + crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks) .unwrap(); // `key.stream` is already a temporal delimiter, the sequence header @@ -5062,7 +5265,25 @@ mod tests { let high = reference[reference.len() - 1] .0 .min(other[other.len() - 1].0); - assert!(high > low, "the two ladders have to overlap in PSNR"); + // lane-av1tx: `TxMode::Select` moved the directional ladder clear of + // the non-directional one on the synthetic diagonals -- every point + // both higher in PSNR *and* lower in rate -- so there is no PSNR band + // to integrate over any more. A curve that dominates that way has + // saved everything the measure can express (the + // `instrument-at-bound` class: the answer is at the instrument's own + // edge, not undefined), so name it rather than panicking; anything + // less clean than strict dominance still is. + if high <= low { + let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min); + let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max); + let dominates = other[0].0 > reference[reference.len() - 1].0 + && other_hi_rate <= ref_lo_rate; + assert!( + dominates, + "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}" + ); + return -1.0; + } let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { let i = curve .windows(2) @@ -5343,7 +5564,12 @@ mod tests { // CDF while the writer codes it against an adapted one -- 311 -> 319 // bytes at q 120->121 on this picture. The table this gate is really // watching would move the rate by far more than the mode churn does. - // Ceiling: a q-context table wrong by under 5% would pass. Upgrade + // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the + // same block can also change transform DEPTH between two neighbouring + // quantizers (297 -> 315 bytes at q 120->121 here), and the depth + // symbol is priced off the static CDF row 0 for the same reason the + // uv_mode one is. + // Ceiling: a q-context table wrong by under 10% would pass. Upgrade // path is pricing through the adapting CDF state (what // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the // drift of), after which the exact bound comes back. @@ -5351,7 +5577,7 @@ mod tests { let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len(); let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len(); assert!( - hi_bytes as f64 <= lo_bytes as f64 * 1.05, + hi_bytes as f64 <= lo_bytes as f64 * 1.10, "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" ); } @@ -6613,6 +6839,23 @@ mod tests { .collect::>() .join(" ") ); + // Which transform depth the intra blocks of this clip's key + // frames resolved to (lane-av1tx): depth 0 is one transform over + // the whole block, 1 and 2 its halvings. + let depths = take_tx_depth_hits(); + let depth_total: usize = depths.iter().sum(); + eprintln!( + "{name}: intra tx depths {}", + depths + .iter() + .enumerate() + .map(|(d, &n)| format!( + "{d}={n} ({:.1}%)", + 100.0 * n as f64 / depth_total.max(1) as f64 + )) + .collect::>() + .join(" ") + ); let (aom, aom_wall) = external_ladder(&source, width, height, "libaom-av1", &aom_points); let (rav1e, rav1e_wall) = diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 8eab07af..6e0dbd15 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -15,6 +15,7 @@ use ec_core::{Error, Result}; use crate::cdf; use crate::cdf_state::{Cdfs, MvComponentCdfs, TxbSet, TxbTables}; +use crate::decode::{TXFM_CTX_INIT, txfm_partition_ctx_rect}; use crate::msac::SymbolEncoder; use crate::mvstack::{MiGrid, MiInfo, NO_REF1, find_mv_stack, mv16, single_ref_ctx}; @@ -477,6 +478,13 @@ pub struct BlockCoeffs { /// at their defaults and unused, the same way a `Whole` [`Superblock`]'s /// per-quadrant fields are unused. pub eight: Option>, + /// How many times this block's luma transform is halved under + /// `TxMode::Select` (spec `tx_depth`, 0 = one transform over the whole + /// block). Read only by the writers a `tx_select` frame calls; a + /// `TxMode::Largest` frame codes no symbol and leaves this at zero. + /// `luma` then carries the whole block's levels in BLOCK coordinates, + /// which the writer slices per transform unit. + pub tx_depth: u8, } /// One inter mode [`sb_coeff_inter_frame_tile`]'s blocks may take (spec @@ -543,6 +551,11 @@ const MI: usize = 4; struct Neighbour { /// Whether the plane's transform block carried a coefficient. coded: bool, + /// Its cumulative coefficient level (spec `cul_level`, clamped to 7) -- + /// what the *luma* `txb_skip_ctx` of a transform unit smaller than its + /// own block reads (`get_txb_ctx_general`, decode.rs `luma_skip_ctx`), + /// where "coded or not" is not enough. + level: u8, /// The sign of its DC, absent when the DC itself is zero. dc: Option, } @@ -640,6 +653,23 @@ struct Neighbours { above_skip: Vec, /// The same, down the left edge. left_skip: Vec, + /// The side, in pixels, of the transform last written in this 4x4 + /// mode-info column -- the deblock `tx_grid` a key frame's + /// `get_tx_size_context` reads (decode.rs `tx_size_context`/`tx_px_at`), + /// which is what picks the CDF row of a `TxMode::Select` block's + /// `tx_depth` symbol. + above_tx: Vec, + /// The same, down the left edge (the transform's HEIGHT, `tx_h_px_at`; + /// every transform this writer codes is square, so one value serves). + left_tx: Vec, + /// libaom's `above_txfm_context`/`left_txfm_context` (`TXFM_CONTEXT`), per + /// 4x4 mode-info unit: what an INTER frame's `txfm_split` and `tx_depth` + /// symbols read their context from (decode.rs `txfm_partition_ctx_rect`/ + /// `tx_size_context_txfm_rect`). Initialised to the widest transform, not + /// zero (decode.rs `TXFM_CTX_INIT`). + above_txfm: Vec, + /// The same, down the left edge (transform HEIGHT). + left_txfm: Vec, /// Whether the neighbour was coded inter, for the `is_inter` context. /// Unused by the key frame writers. above_inter: Vec, @@ -688,6 +718,10 @@ impl Neighbours { left_skip: vec![false; rows * (SUB / MI)], above_inter: vec![false; cols * (SUB / MI)], left_inter: vec![false; rows * (SUB / MI)], + above_tx: vec![0; cols * (SUB / MI)], + left_tx: vec![0; rows * (SUB / MI)], + above_txfm: vec![TXFM_CTX_INIT; cols * (SUB / MI)], + left_txfm: vec![TXFM_CTX_INIT; rows * (SUB / MI)], mi_cols, mi_rows, } @@ -701,6 +735,90 @@ impl Neighbours { self.left_side_mi.iter_mut().for_each(|s| *s = SB); self.left_skip.iter_mut().for_each(|s| *s = false); self.left_inter.iter_mut().for_each(|i| *i = false); + self.left_tx.iter_mut().for_each(|t| *t = 0); + self.left_txfm.iter_mut().for_each(|t| *t = TXFM_CTX_INIT); + } + + /// `txfm_partition_update`/`set_txfm_ctxs` (decode.rs): what every block + /// of an INTER frame leaves in the two `TXFM_CONTEXT` bands -- its + /// resolved transform size over the span `(w_px, h_px)`, which for a + /// SKIPPED inter block is its own block size instead. + fn record_txfm(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, w_px: usize, h_px: usize) { + for i in 0..h_px / MI { + if let Some(cell) = self.left_txfm.get_mut(mi_r + i) { + *cell = tx_px as u8; + } + } + for i in 0..w_px / MI { + if let Some(cell) = self.above_txfm.get_mut(mi_c + i) { + *cell = tx_px as u8; + } + } + } + + /// `get_tx_size_context` as libaom writes it for a block inside an INTER + /// frame (decode.rs `tx_size_context_txfm_rect`): the `TXFM_CONTEXT` + /// bands, except that an *inter* neighbour contributes its own BLOCK size. + fn tx_size_ctx_txfm(&self, (mi_r, mi_c): (usize, usize), own_side: usize) -> usize { + let mut above = usize::from(self.above_txfm[mi_c]) >= own_side; + let mut left = usize::from(self.left_txfm[mi_r]) >= own_side; + if mi_r > 0 && self.above_inter[mi_c] { + above = self.above_side_mi[mi_c] >= own_side; + } + if mi_c > 0 && self.left_inter[mi_r] { + left = self.left_side_mi[mi_r] >= own_side; + } + usize::from(above) + usize::from(left) + } + + /// `get_tx_size_context` (decode.rs [`crate::decode::tx_size_context`]): + /// whether the transform above is at least as wide as this block's own + /// largest transform, plus whether the one to the left is at least as + /// tall. A neighbour outside the tile contributes nothing. + fn tx_size_ctx(&self, (mi_r, mi_c): (usize, usize), max_tx: usize) -> usize { + usize::from(mi_r > 0 && usize::from(self.above_tx[mi_c]) >= max_tx) + + usize::from(mi_c > 0 && usize::from(self.left_tx[mi_r]) >= max_tx) + } + + /// Publishes one block's resolved transform side over every 4x4 unit it + /// covers, the way the decoder's `fill_lf_grid` does at the end of every + /// block. + fn record_tx(&mut self, (mi_r, mi_c): (usize, usize), side: usize, tx_px: usize) { + for cell in 0..side / MI { + if mi_r + cell < self.left_tx.len() { + self.left_tx[mi_r + cell] = tx_px as u8; + } + if mi_c + cell < self.above_tx.len() { + self.above_tx[mi_c + cell] = tx_px as u8; + } + } + } + + /// The luma `txb_skip_ctx` of a transform unit smaller than its own block + /// (decode.rs `Neighbours::luma_skip_ctx`): the above and left magnitude + /// tiers, each ORed over the unit's own span and clamped to 4. + fn luma_skip_ctx(&self, (mi_r, mi_c): (usize, usize), side_mi: usize) -> usize { + let mut top = 0u8; + let mut left = 0u8; + for cell in 0..side_mi { + top |= self.above[mi_c + cell][0].level; + left |= self.left[mi_r + cell][0].level; + } + crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)] + } + + /// Publishes ONE luma transform unit's coefficient context, the way the + /// decoder's `record_mi_luma` does between the units of a split block. + fn record_mi_luma(&mut self, (mi_r, mi_c): (usize, usize), tx_px: usize, grid: &[i32]) { + let state = neighbour_state(grid); + for cell in 0..tx_px / MI { + if mi_r + cell < self.mi_rows { + self.left[mi_r + cell][0] = state; + } + if mi_c + cell < self.mi_cols { + self.above[mi_c + cell][0] = state; + } + } } /// Writes one coded block into every 16x16 column and row it covers, and, @@ -711,6 +829,22 @@ impl Neighbours { /// derived from the true `mi_cols`/`mi_rows`, not from this block's own /// side). fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec; 3]) { + self.record_planes(at, side, mode, grids, true); + } + + /// [`Self::record`] with a switch for plane 0: a block whose luma was + /// written as several transform units published each unit's own context + /// as it went ([`Self::record_mi_luma`]), so the whole-block write here + /// would clobber what the next block reads (decode.rs + /// `record_split_luma`). + fn record_planes( + &mut self, + at: (usize, usize), + side: usize, + mode: usize, + grids: &[Vec; 3], + luma: bool, + ) { let (r, c) = at; for cell in 0..side / SUB { self.above_mode[c + cell] = mode; @@ -718,7 +852,7 @@ impl Neighbours { self.above_side[c + cell] = side; self.left_side[r + cell] = side; } - self.record_mi((r * (SUB / MI), c * (SUB / MI)), side, grids); + self.record_mi_planes((r * (SUB / MI), c * (SUB / MI)), side, grids, luma); } /// The coefficient-context half of [`Self::record`], taking the block's @@ -729,6 +863,17 @@ impl Neighbours { /// grid, so no resizing is needed to write into them at this /// finer-than-SUB granularity. fn record_mi(&mut self, at_mi: (usize, usize), side: usize, grids: &[Vec; 3]) { + self.record_mi_planes(at_mi, side, grids, true); + } + + /// [`Self::record_mi`] with [`Self::record_planes`]'s plane-0 switch. + fn record_mi_planes( + &mut self, + at_mi: (usize, usize), + side: usize, + grids: &[Vec; 3], + luma: bool, + ) { let (mi_r, mi_c) = at_mi; let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane])); let side_mi = side / MI; @@ -754,6 +899,8 @@ impl Neighbours { round_up_even(self.mi_cols), ]; for cell in 0..side_mi { + let keep_left = self.left[mi_r + cell][0]; + let keep_above = self.above[mi_c + cell][0]; self.left[mi_r + cell] = std::array::from_fn(|plane| { if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) { states[plane] @@ -768,6 +915,10 @@ impl Neighbours { Default::default() } }); + if !luma { + self.left[mi_r + cell][0] = keep_left; + self.above[mi_c + cell][0] = keep_above; + } } } @@ -860,6 +1011,25 @@ pub fn sb_coeff_key_frame_tile( mi_rows: u32, base_q_idx: u8, superblocks: &[Superblock], +) -> Result> { + sb_coeff_key_frame_tile_tx(mi_cols, mi_rows, base_q_idx, superblocks, false) +} + +/// [`sb_coeff_key_frame_tile`] for a frame header carrying +/// `tx_mode == TxMode::Select` (`tx_select`): every block then codes a +/// `tx_depth` symbol and, where that depth is nonzero, its luma residual as +/// several transform units ([`write_luma_select`]). With `tx_select` false +/// this writes exactly the stream it always did. +/// +/// # Errors +/// As [`sb_coeff_key_frame_tile`], plus a 64x64 block whose `tx_depth` is +/// nonzero (not written yet). +pub fn sb_coeff_key_frame_tile_tx( + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + superblocks: &[Superblock], + tx_select: bool, ) -> Result> { check_blocks(mi_cols, mi_rows)?; let (cols, rows) = block_grid(mi_cols, mi_rows); @@ -978,7 +1148,9 @@ pub fn sb_coeff_key_frame_tile( // A 64x64 block is too big to be offered chroma from // luma, so its chroma mode reads the table without it. false, - ); + tx_select, + &scans, + )?; ec_rng_trace(|| { format!( "EC_TOK mi_row={} mi_col={} tell={}", @@ -1056,7 +1228,9 @@ pub fn sb_coeff_key_frame_tile( &grids, [&scans[0], &scans[1], &scans[1]], true, - ); + tx_select, + &scans, + )?; ec_rng_trace(|| { format!( "EC_TOK mi_row={} mi_col={} tell={}", @@ -1149,7 +1323,9 @@ pub fn sb_coeff_key_frame_tile( &grids, [&scans[1], &scans[2], &scans[2]], true, - ); + tx_select, + &scans, + )?; ec_rng_trace(|| { format!( "EC_TOK mi_row={} mi_col={} tell={}", @@ -1251,7 +1427,9 @@ pub fn sb_coeff_key_frame_tile( &grids, [&scans[2], &scans[3], &scans[3]], prev_leaf, - ); + tx_select, + &scans, + )?; prev_leaf = Some((leaf_mi, leaf_mode)); ec_rng_trace(|| { format!( @@ -1345,7 +1523,13 @@ fn write_block( grids: &[Vec; 3], scans: [&Vec; 3], cfl: bool, -) { + // The frame's `tx_mode == TxMode::Select`, and the block's own chosen + // depth: with it the luma residual goes through [`write_luma_select`] + // (one `tx_depth` symbol, then one transform unit per tile of the block) + // instead of the single whole-block transform below. + tx_select: bool, + all_scans: &[Vec; 4], +) -> Result<()> { let (r, c) = at; let mode = write_intra_mode( enc, @@ -1355,6 +1539,23 @@ fn write_block( neighbours.left_mode[r], cfl, ); + let at_mi = (r * (SUB / MI), c * (SUB / MI)); + let split = if tx_select { + let tx = write_luma_select( + enc, + cdfs, + neighbours, + at_mi, + side, + usize::from(block.tx_depth), + &grids[0], + mode, + all_scans, + )?; + tx < side + } else { + false + }; write_block_planes( enc, cdfs, @@ -1363,8 +1564,10 @@ fn write_block( &scans, &neighbours.around(at, side), mode, + tx_select, ); - neighbours.record(at, side, mode, grids); + neighbours.record_planes(at, side, mode, grids, !split); + Ok(()) } /// Writes one 8x8 leaf of a straddling 16x16 block (lane-av1-rect): its own @@ -1386,7 +1589,9 @@ fn write_leaf8( grids: &[Vec; 3], scans: [&Vec; 3], prev_leaf: Option<((usize, usize), usize)>, -) -> usize { + tx_select: bool, + all_scans: &[Vec; 4], +) -> Result { let (r, c) = outer_at; let mut above_mode = neighbours.above_mode[c]; let mut left_mode = neighbours.left_mode[r]; @@ -1410,6 +1615,22 @@ fn write_leaf8( // unchanged). let mode = write_intra_mode(enc, cdfs, block, above_mode, left_mode, true); let planes = [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4]; + let split = if tx_select { + let tx = write_luma_select( + enc, + cdfs, + neighbours, + leaf_mi, + 8, + usize::from(block.tx_depth), + &grids[0], + mode, + all_scans, + )?; + tx < 8 + } else { + false + }; write_block_planes( enc, cdfs, @@ -1418,9 +1639,10 @@ fn write_leaf8( &scans, &neighbours.around_mi(leaf_mi, 8), mode, + tx_select, ); - neighbours.record_mi(leaf_mi, 8, grids); - mode + neighbours.record_mi_planes(leaf_mi, 8, grids, !split); + Ok(mode) } /// Writes the three transform blocks of one coded block, in the order a @@ -1434,8 +1656,14 @@ fn write_block_planes( scans: &[&Vec; 3], around: &[Around; 3], mode: usize, + // A block whose luma was already written as several transform units + // ([`write_luma_select`]) has only its chroma planes left here. + skip_luma: bool, ) { for (plane, (grid, scan)) in grids.iter().zip(scans.iter()).enumerate() { + if plane == 0 && skip_luma { + continue; + } // Luma's transform covers its whole block, which fixes the all-zero // flag's context at zero; a chroma transform reads whether its // neighbours coded anything, on top of the offset the chroma tables @@ -1464,11 +1692,190 @@ fn write_block_planes( } } +/// The `(side / tx)^2` transform units of one block's luma residual, raster +/// order, each with its own coefficient context and each published before the +/// next one reads it (decode.rs `decode_block`'s multi-transform-unit branch). +/// `grid` is the block's levels in BLOCK coordinates when the transform +/// splits, and the single transform's own coefficient grid when it does not. +#[allow(clippy::too_many_arguments)] +fn write_luma_tus( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + at_mi: (usize, usize), + side: usize, + tx: usize, + grid: &[i32], + mode: usize, + scans: &[Vec; 4], +) -> Result<()> { + if tx < side && side > 32 { + // A 64x64 block's own levels reach the writer as the 32x32 corner a + // 64-point transform codes, not as a 64x64 block grid, so there is + // nothing to slice per unit here. + return Err(Error::unsupported( + "AV1 tile", + "a 64x64 block's split luma transform is not written yet", + )); + } + let coeff_side = tx.min(32); + let n = side / tx; + let set = match tx { + 32 => TxbSet::Luma32, + 16 => TxbSet::Luma16, + 8 => TxbSet::Luma8, + 4 => TxbSet::Luma4, + _ => TxbSet::Luma64, + }; + let scan = match coeff_side { + 32 => &scans[0], + 16 => &scans[1], + 8 => &scans[2], + _ => &scans[3], + }; + let (mi_r, mi_c) = at_mi; + for tu_row in 0..n { + for tu_col in 0..n { + let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI)); + let unit = if n == 1 { + grid.to_vec() + } else { + (0..tx) + .flat_map(|row| { + grid[(tu_row * tx + row) * side + tu_col * tx..][..tx].to_vec() + }) + .collect() + }; + // spec `get_txb_ctx_general`: a lone transform unit covering its + // whole block reads context 0, a smaller one the neighbour + // magnitude table. + let skip_ctx = if n == 1 { + 0 + } else { + neighbours.luma_skip_ctx(tu_mi, tx / MI) + }; + let around = neighbours.around_mi(tu_mi, tx)[0]; + write_coeffs( + enc, + &mut cdfs.txb(set, mode), + &unit, + scan, + skip_ctx, + dc_sign_ctx(around.dc_vote), + Some(0), + ); + if n > 1 { + neighbours.record_mi_luma(tu_mi, tx, &unit); + } + } + } + Ok(()) +} + +/// Writes one intra block's luma residual under `TxMode::Select`: the +/// `tx_depth` symbol (spec 5.11.16 `read_selected_tx_size`, off the size +/// category's own CDF at [`Neighbours::tx_size_ctx`]'s row), then the +/// `(side / tx)^2` transform units in raster order -- each predicted and +/// coded against what the units before it already left behind, which is why +/// every unit publishes its own coefficient context before the next one reads +/// it (decode.rs `decode_block`'s multi-transform-unit branch). +/// +/// `grid` is the block's levels in BLOCK coordinates (`side` by `side`) when +/// the transform splits, and the single transform's own coefficient grid when +/// it does not. Hands back the resolved transform side in pixels. +#[allow(clippy::too_many_arguments)] +fn write_luma_select( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + at_mi: (usize, usize), + side: usize, + depth: usize, + grid: &[i32], + mode: usize, + scans: &[Vec; 4], +) -> Result { + let max_tx = side.min(64); + let ctx = neighbours.tx_size_ctx(at_mi, max_tx); + match max_tx { + 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]), + 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]), + 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]), + 64 => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]), + _ => { + return Err(Error::unsupported( + "AV1 tile", + "a tx_depth symbol is only coded at 8/16/32/64", + )); + } + } + let tx = max_tx >> depth; + write_luma_tus(enc, cdfs, neighbours, at_mi, side, tx, grid, mode, scans)?; + neighbours.record_tx(at_mi, side, tx); + Ok(tx) +} + +/// The transform syntax one block of an INTER frame coded with +/// `tx_mode == TxMode::Select` carries, in the place spec 5.11.16's +/// `read_block_tx_size` reads it -- after the modes and the motion vector, +/// before the residual: +/// * an inter block that codes a residual walks a var-tx tree; this writer +/// keeps it at its own largest transform, so that is one `txfm_split` flag +/// of zero, off `txfm_partition_ctx_rect`'s row, publishing the bands per +/// unit the way `read_var_tx_size` does. +/// * a skipped inter block codes nothing and records its own BLOCK size +/// (`set_txfm_ctxs`'s `skip_inter` term). +/// * an intra block codes `tx_depth` like a key frame's, but off the +/// `TXFM_CONTEXT` bands rather than the deblock grid. +/// +/// Hands back the block's resolved luma transform side. +#[allow(clippy::too_many_arguments)] +fn write_tx_syntax_inter( + enc: &mut SymbolEncoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + at_mi: (usize, usize), + side: usize, + is_inter: bool, + skip: bool, + depth: usize, +) -> usize { + let max_tx = side.min(64); + let (mi_r, mi_c) = at_mi; + if is_inter { + if !skip { + let ctx = txfm_partition_ctx_rect( + neighbours.above_txfm[mi_c], + neighbours.left_txfm[mi_r], + side, + max_tx, + max_tx, + ); + enc.symbol(0, &mut cdfs.txfm_partition[ctx]); + neighbours.record_txfm(at_mi, max_tx, max_tx, max_tx); + } else { + neighbours.record_txfm(at_mi, side, side, side); + } + return max_tx; + } + let ctx = neighbours.tx_size_ctx_txfm(at_mi, max_tx); + match max_tx { + 8 => enc.symbol(depth, &mut cdfs.tx_size_cat0[ctx]), + 16 => enc.symbol(depth, &mut cdfs.tx_size_cat1[ctx]), + 32 => enc.symbol(depth, &mut cdfs.tx_size_cat2[ctx]), + _ => enc.symbol(depth, &mut cdfs.tx_size_cat3[ctx]), + } + let tx = max_tx >> depth; + neighbours.record_txfm(at_mi, tx, side, side); + tx +} + /// What a coded transform block leaves behind for the blocks that read it as a /// neighbour. fn neighbour_state(grid: &[i32]) -> Neighbour { Neighbour { coded: grid.iter().any(|&l| l != 0), + level: grid.iter().map(|l| l.unsigned_abs()).sum::().min(7) as u8, dc: (grid[0] != 0).then_some(grid[0] < 0), } } @@ -2211,6 +2618,25 @@ pub fn sb_coeff_inter_frame_tile( mi_rows: u32, base_q_idx: u8, blocks: &[Quadrant], +) -> Result> { + sb_coeff_inter_frame_tile_tx(mi_cols, mi_rows, base_q_idx, blocks, false) +} + +/// [`sb_coeff_inter_frame_tile`] for a frame header carrying +/// `tx_mode == TxMode::Select`: every block then codes the transform syntax +/// [`write_tx_syntax_inter`] writes -- one `txfm_split` flag on an inter +/// block that carries a residual, a `tx_depth` symbol on an intra one -- and +/// an intra block whose depth is nonzero codes its luma as several transform +/// units. With `tx_select` false this writes exactly the stream it always did. +/// +/// # Errors +/// As [`sb_coeff_inter_frame_tile`]. +pub fn sb_coeff_inter_frame_tile_tx( + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + blocks: &[Quadrant], + tx_select: bool, ) -> Result> { check_blocks(mi_cols, mi_rows)?; // `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( let scan16 = default_scan(TX16); let scan8 = default_scan(TX8); let scan4 = default_scan(TX4); + // The same four tables again as one array, which is what the per-unit + // luma writer indexes by transform side. + let all_scans = [ + scan32.clone(), + scan16.clone(), + scan8.clone(), + scan4.clone(), + ]; let zero_grids = [ vec![0i32; TX32 * TX32], vec![0i32; TX16 * TX16], @@ -2428,6 +2862,8 @@ pub fn sb_coeff_inter_frame_tile( leaf_mi, &scan8, &scan4, + tx_select, + &all_scans, )?; let _ = (skip, is_inter); } @@ -2445,6 +2881,8 @@ pub fn sb_coeff_inter_frame_tile( at16, &scan16, &scan8, + tx_select, + &all_scans, )?; } else { let ctx16 = neighbours.partition_ctx(at16, SUB); @@ -2493,6 +2931,8 @@ pub fn sb_coeff_inter_frame_tile( leaf_mi, &scan8, &scan4, + tx_select, + &all_scans, )?; let _ = (skip, is_inter); } @@ -2644,6 +3084,22 @@ pub fn sb_coeff_inter_frame_tile( } } + let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI)); + let tx = if tx_select { + write_tx_syntax_inter( + &mut enc, + &mut cdfs, + &mut neighbours, + at_mi, + BLOCK, + is_inter, + block.skip, + usize::from(block.tx_depth), + ) + } else { + BLOCK + }; + let split = tx < BLOCK; if block.skip { neighbours.record(at, BLOCK, mode_for_tx, &zero_grids); } else { @@ -2652,6 +3108,19 @@ pub fn sb_coeff_inter_frame_tile( level_grid(&block.u, TX16)?, level_grid(&block.v, TX16)?, ]; + if split { + write_luma_tus( + &mut enc, + &mut cdfs, + &mut neighbours, + at_mi, + BLOCK, + tx, + &grids[0], + mode_for_tx, + &all_scans, + )?; + } write_block_planes( &mut enc, &mut cdfs, @@ -2664,8 +3133,9 @@ pub fn sb_coeff_inter_frame_tile( &[&scan32, &scan16, &scan16], &neighbours.around(at, BLOCK), mode_for_tx, + split, ); - neighbours.record(at, BLOCK, mode_for_tx, &grids); + neighbours.record_planes(at, BLOCK, mode_for_tx, &grids, !split); } neighbours.record_inter(at, BLOCK, block.skip, is_inter); } @@ -2696,6 +3166,8 @@ fn write_inter_frame_leaf( at: (usize, usize), scan16: &Vec, scan8: &Vec, + tx_select: bool, + all_scans: &[Vec; 4], ) -> Result<()> { if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES { return Err(Error::unsupported( @@ -2824,6 +3296,22 @@ fn write_inter_frame_leaf( } } + let at_mi = (at.0 * (SUB / MI), at.1 * (SUB / MI)); + let tx = if tx_select { + write_tx_syntax_inter( + enc, + cdfs, + neighbours, + at_mi, + SUB, + is_inter, + block.skip, + usize::from(block.tx_depth), + ) + } else { + SUB + }; + let split = tx < SUB; if block.skip { let zero_grids = [ vec![0i32; TX16 * TX16], @@ -2837,6 +3325,11 @@ fn write_inter_frame_leaf( level_grid(&block.u, TX8)?, level_grid(&block.v, TX8)?, ]; + if split { + write_luma_tus( + enc, cdfs, neighbours, at_mi, SUB, tx, &grids[0], mode_for_tx, all_scans, + )?; + } write_block_planes( enc, cdfs, @@ -2849,8 +3342,9 @@ fn write_inter_frame_leaf( &[scan16, scan8, scan8], &neighbours.around(at, SUB), mode_for_tx, + split, ); - neighbours.record(at, SUB, mode_for_tx, &grids); + neighbours.record_planes(at, SUB, mode_for_tx, &grids, !split); } neighbours.record_inter(at, SUB, block.skip, is_inter); Ok(()) @@ -2885,6 +3379,8 @@ fn write_inter_frame_leaf8( leaf_mi: (usize, usize), scan8: &Vec, scan4: &Vec, + tx_select: bool, + all_scans: &[Vec; 4], ) -> Result<(bool, bool)> { if block.inter.is_none() && usize::from(block.mode) >= INTRA_MODES { return Err(Error::unsupported( @@ -3025,6 +3521,21 @@ fn write_inter_frame_leaf8( } else { [TxbSet::Luma8, TxbSet::Chroma4, TxbSet::Chroma4] }; + let tx = if tx_select { + write_tx_syntax_inter( + enc, + cdfs, + neighbours, + leaf_mi, + 8, + is_inter, + block.skip, + usize::from(block.tx_depth), + ) + } else { + 8 + }; + let split = tx < 8; if block.skip { let zero_grids = [ vec![0i32; TX8 * TX8], @@ -3039,6 +3550,11 @@ fn write_inter_frame_leaf8( level_grid(&block.u, TX4)?, level_grid(&block.v, TX4)?, ]; + if split { + write_luma_tus( + enc, cdfs, neighbours, leaf_mi, 8, tx, &grids[0], mode_for_tx, all_scans, + )?; + } write_block_planes( enc, cdfs, @@ -3047,8 +3563,9 @@ fn write_inter_frame_leaf8( &[scan8, scan4, scan4], &neighbours.around_mi(leaf_mi, 8), mode_for_tx, + split, ); - neighbours.record_mi(leaf_mi, 8, &grids); + neighbours.record_mi_planes(leaf_mi, 8, &grids, !split); neighbours.record_inter_mi(leaf_mi, 8, block.skip, is_inter); } Ok((block.skip, is_inter))