diff --git a/crates/ec-av1/src/cdf.rs b/crates/ec-av1/src/cdf.rs index d4e5958d..4c9d5c58 100644 --- a/crates/ec-av1/src/cdf.rs +++ b/crates/ec-av1/src/cdf.rs @@ -210,7 +210,7 @@ pub const TXB_SKIP_LUMA_64: [u16; 3] = [28573, 32768, 0]; /// `Default_Txb_Skip_Cdf[2][3][7]` (spec 9.4): the all-zero flag of a 32x32 /// chroma transform block that covers its whole plane block with no coded /// neighbour, which is context 7. -pub const TXB_SKIP_CHROMA_32: [u16; 3] = [5124, 32768, 0]; +pub const TXB_SKIP_CHROMA_32_NONE: [u16; 3] = [5124, 32768, 0]; /// `Default_Eob_Pt_1024_Cdf[2][0][0]` (spec 9.4): the end-of-block position /// token of a luma transform block with 1024 coded coefficient positions — @@ -222,7 +222,7 @@ pub const EOB_PT_1024_LUMA: [u16; 12] = [ /// `Default_Coeff_Base_Eob_Cdf[2][4][0][0]` (spec 9.4): the level of the last /// coefficient of a 64x64 luma transform block, less one, when that /// coefficient is the DC. -pub const COEFF_BASE_EOB_LUMA_64: [u16; 4] = [935, 3382, 32768, 0]; +pub const COEFF_BASE_EOB_LUMA_64_DC: [u16; 4] = [935, 3382, 32768, 0]; /// `Default_Dc_Sign_Cdf[2][0]` (spec 9.4): the sign of a luma DC coefficient, /// indexed by whether the neighbouring blocks' DC signs lean negative (1), @@ -544,3 +544,181 @@ pub const ANGLE_DELTA: [[u16; 8]; 8] = [ [2240, 11096, 15453, 20341, 22561, 28917, 32768, 0], [3605, 10428, 12459, 17676, 21244, 30655, 32768, 0], ]; +/// `Default_Coeff_Base_Cdf[2][4][0]` (spec 9.4): the level of a coefficient of a 64x64 luma +/// transform block, capped at three, for each of the forty-two contexts its neighbours and its +/// position give. +pub const COEFF_BASE_LUMA_64: [[u16; 5]; 42] = [ + [2575, 7281, 11077, 32768, 0], + [14002, 20866, 25402, 32768, 0], + [6343, 15056, 19658, 32768, 0], + [4474, 11858, 17041, 32768, 0], + [2865, 8299, 12534, 32768, 0], + [1344, 3949, 6391, 32768, 0], + [24720, 31239, 32459, 32768, 0], + [12585, 25356, 29968, 32768, 0], + [7181, 18246, 24444, 32768, 0], + [5025, 13667, 19885, 32768, 0], + [2521, 7304, 11605, 32768, 0], + [29908, 32252, 32584, 32768, 0], + [17421, 29156, 31575, 32768, 0], + [9889, 22188, 27782, 32768, 0], + [5878, 15647, 22123, 32768, 0], + [2814, 8665, 13323, 32768, 0], + [30183, 32568, 32713, 32768, 0], + [18528, 30195, 32049, 32768, 0], + [10982, 24606, 29657, 32768, 0], + [6957, 18165, 25231, 32768, 0], + [3508, 10118, 15468, 32768, 0], + [31761, 32736, 32748, 32768, 0], + [21041, 31328, 32546, 32768, 0], + [12568, 26732, 31166, 32768, 0], + [8052, 20720, 27733, 32768, 0], + [4336, 12192, 18396, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], +]; + +/// `Default_Coeff_Base_Eob_Cdf[2][4][0]` (spec 9.4): the level of the last coefficient of a +/// 64x64 luma transform block, less one, for each of the four contexts its position gives. +pub const COEFF_BASE_EOB_LUMA_64: [[u16; 4]; 4] = [ + [935, 3382, 32768, 0], + [30789, 31909, 32768, 0], + [32466, 32756, 32768, 0], + [30860, 32513, 32768, 0], +]; + +/// `Default_Eob_Extra_Cdf[2][4][0]` (spec 9.4): the top bit of the end-of-block position of a +/// 64x64 luma transform block, one context per end-of-block group. +pub const EOB_EXTRA_LUMA_64: [[u16; 3]; 9] = [ + [26998, 32768, 0], + [16737, 32768, 0], + [17838, 32768, 0], + [18922, 32768, 0], + [19515, 32768, 0], + [18636, 32768, 0], + [17333, 32768, 0], + [15776, 32768, 0], + [22658, 32768, 0], +]; + +/// `Default_Coeff_Base_Cdf[2][3][1]` (spec 9.4): the level of a coefficient of a 32x32 chroma +/// transform block, capped at three, for each of the forty-two contexts its neighbours and its +/// position give. +pub const COEFF_BASE_CHROMA_32: [[u16; 5]; 42] = [ + [10202, 20633, 25484, 32768, 0], + [27336, 31445, 32352, 32768, 0], + [12420, 24384, 28552, 32768, 0], + [7648, 18115, 23856, 32768, 0], + [5662, 14341, 19902, 32768, 0], + [3611, 10328, 15390, 32768, 0], + [30945, 32616, 32736, 32768, 0], + [18682, 30505, 32253, 32768, 0], + [11513, 25336, 30203, 32768, 0], + [7449, 19452, 26148, 32768, 0], + [4482, 13051, 18886, 32768, 0], + [32022, 32690, 32747, 32768, 0], + [18578, 30501, 32146, 32768, 0], + [11249, 23368, 28631, 32768, 0], + [5645, 16958, 22158, 32768, 0], + [5009, 11444, 16637, 32768, 0], + [31357, 32710, 32748, 32768, 0], + [21552, 31494, 32504, 32768, 0], + [13891, 27677, 31340, 32768, 0], + [9051, 22098, 28172, 32768, 0], + [5190, 13377, 19486, 32768, 0], + [32364, 32740, 32748, 32768, 0], + [24839, 31907, 32551, 32768, 0], + [17160, 28779, 31696, 32768, 0], + [12452, 24137, 29602, 32768, 0], + [6165, 15389, 22477, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], + [8192, 16384, 24576, 32768, 0], +]; + +/// `Default_Coeff_Br_Cdf[2][3][1]` (spec 9.4): the base-range tail of a 32x32 chroma transform +/// block, for each of the twenty-one contexts its neighbours and its position give. +pub const COEFF_BR_CHROMA_32: [[u16; 5]; 21] = [ + [12339, 17329, 20140, 32768, 0], + [13505, 19895, 23225, 32768, 0], + [9847, 16944, 21564, 32768, 0], + [7280, 13256, 18348, 32768, 0], + [4712, 10009, 14454, 32768, 0], + [4361, 7914, 12477, 32768, 0], + [2870, 5628, 7995, 32768, 0], + [20061, 25504, 28526, 32768, 0], + [15235, 22878, 26145, 32768, 0], + [12985, 19958, 24155, 32768, 0], + [9782, 16641, 21403, 32768, 0], + [9456, 16360, 20760, 32768, 0], + [6855, 12940, 18557, 32768, 0], + [5661, 10564, 15002, 32768, 0], + [25656, 30602, 31894, 32768, 0], + [22570, 29107, 31092, 32768, 0], + [18917, 26423, 29541, 32768, 0], + [15940, 23649, 27754, 32768, 0], + [12803, 20581, 25219, 32768, 0], + [11082, 18695, 23376, 32768, 0], + [7939, 14373, 19005, 32768, 0], +]; + +/// `Default_Coeff_Base_Eob_Cdf[2][3][1]` (spec 9.4): the level of the last coefficient of a +/// 32x32 chroma transform block, less one, for each of the four contexts its position gives. +pub const COEFF_BASE_EOB_CHROMA_32: [[u16; 4]; 4] = [ + [22737, 29105, 32768, 0], + [30810, 32362, 32768, 0], + [30014, 32627, 32768, 0], + [30528, 32574, 32768, 0], +]; + +/// `Default_Eob_Extra_Cdf[2][3][1]` (spec 9.4): the top bit of the end-of-block position of a +/// 32x32 chroma transform block, one context per end-of-block group. +pub const EOB_EXTRA_CHROMA_32: [[u16; 3]; 9] = [ + [26579, 32768, 0], + [24910, 32768, 0], + [18637, 32768, 0], + [19800, 32768, 0], + [20388, 32768, 0], + [9887, 32768, 0], + [15642, 32768, 0], + [30198, 32768, 0], + [24721, 32768, 0], +]; + +/// `Default_Txb_Skip_Cdf[2][3][7..10]` (spec 9.4): the all-zero flag of a 32x32 chroma transform +/// block that covers its whole plane block, for the three contexts its coded neighbours give. +pub const TXB_SKIP_CHROMA_32: [[u16; 3]; 3] = + [[5124, 32768, 0], [18719, 32768, 0], [28468, 32768, 0]]; + +/// `Default_Eob_Pt_1024_Cdf[2][1][0]` (spec 9.4): the end-of-block group of a +/// 1024-coefficient chroma transform block with a two-dimensional transform. +pub const EOB_PT_1024_CHROMA: [u16; 12] = [ + 9577, 12466, 17739, 20750, 22061, 23215, 24601, 25483, 25843, 32056, 32768, 0, +]; diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 4c81d646..efbd0010 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -224,15 +224,15 @@ pub fn dc_key_frame_tile_levels( dc_level, dc_sign_ctx(above[c as usize], left), &cdf::TXB_SKIP_LUMA_64, - &cdf::COEFF_BASE_EOB_LUMA_64, + &cdf::COEFF_BASE_EOB_LUMA_64_DC, ); // Both chroma transform blocks are all-zero. Their planes carry no // coded coefficient anywhere in the frame, so the neighbour halves // of their context stay 0 and only the offset for a transform block // that covers its whole plane block is left: context 7. - enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32); - enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32); + enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32_NONE); + enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_32_NONE); above[c as usize] = Some(negative); left = Some(negative); @@ -278,6 +278,8 @@ pub fn split_dc_key_frame_tile( // it, and an uncoded one leaves it clear, so the context is just // which neighbours exist. The 32x32 blocks below read a bit their // own size leaves clear, so their context is 0 throughout. + // Every superblock here is split, so an existing neighbour always + // sets that bit. let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0); enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]); @@ -412,6 +414,39 @@ const CHROMA_16: TxbCoding = TxbCoding { dc_sign: &cdf::DC_SIGN_CHROMA, }; +/// The luma all-zero flag of a 64x64 transform, whose one context is fixed the +/// way [`TXB_SKIP_LUMA_32_CTX`] is. +const TXB_SKIP_LUMA_64_CTX: [[u16; 3]; 1] = [cdf::TXB_SKIP_LUMA_64]; + +/// The 64x64 luma transform of a whole superblock. Only its top-left 32x32 +/// carries coefficients, so it is scanned and its end-of-block position read +/// as a 32x32 transform is; what it does not share with [`LUMA_32`] is every +/// coefficient CDF, which is indexed by the transform size. +const LUMA_64: TxbCoding = TxbCoding { + side: TX32, + txb_skip: &TXB_SKIP_LUMA_64_CTX, + eob_pt: &cdf::EOB_PT_1024_LUMA, + eob_extra: &cdf::EOB_EXTRA_LUMA_64, + base: &cdf::COEFF_BASE_LUMA_64, + base_eob: &cdf::COEFF_BASE_EOB_LUMA_64, + // The base-range tail is the one table a 64x64 transform does not have of + // its own: the index is clamped at the 32x32 size, so it reads that row. + br: &cdf::COEFF_BR_LUMA_32, + dc_sign: &cdf::DC_SIGN_LUMA, +}; + +/// The 32x32 transform of either chroma plane of that superblock at 4:2:0. +const CHROMA_32: TxbCoding = TxbCoding { + side: TX32, + txb_skip: &cdf::TXB_SKIP_CHROMA_32, + eob_pt: &cdf::EOB_PT_1024_CHROMA, + eob_extra: &cdf::EOB_EXTRA_CHROMA_32, + base: &cdf::COEFF_BASE_CHROMA_32, + base_eob: &cdf::COEFF_BASE_EOB_CHROMA_32, + br: &cdf::COEFF_BR_CHROMA_32, + dc_sign: &cdf::DC_SIGN_CHROMA, +}; + /// What one coded block leaves behind for the blocks that read it as a /// neighbour: whether it coded anything at all, and the sign of its DC. #[derive(Clone, Copy, Default)] @@ -443,42 +478,66 @@ fn check_blocks(mi_cols: u32, mi_rows: u32) -> Result<()> { Ok(()) } -/// Writes the payload of a one-tile key frame in which every superblock is -/// split into 32x32 DC-predicted blocks, each carrying the coefficients -/// `blocks` gives it. +/// The coefficients of one superblock: either one 64x64 block covering it, or +/// the four 32x32 blocks it is split into. /// -/// `blocks` gives one coefficient set per 32x32 block in raster order across -/// the frame. The frame need not be a whole number of superblocks: a -/// superblock at the right-hand or bottom edge may be half outside it, and the -/// blocks that would sit in the half outside are not coded. Each set carries a 32x32 luma transform and the 16x16 transform of -/// each chroma plane; an empty list writes an all-zero transform block. Unlike -/// the DC writers, the coefficients may sit anywhere in their transform, so a -/// block here is a picture rather than a flat grey: a single coefficient off -/// the origin decodes to the basis function it selects. +/// A superblock at the right-hand or bottom edge of the frame may be half +/// outside it, and such a superblock cannot be left whole — the spec has no +/// partition that keeps a block outside the frame — so it must be +/// [`Split`](Superblock::Split), and carries only the quadrants that are +/// inside, in raster order among themselves. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Superblock { + /// One 64x64 block, whose luma transform is 64x64 — of which only the + /// top-left 32x32 carries coefficients — and whose chroma transforms are + /// 32x32 each at 4:2:0. + Whole(BlockCoeffs), + /// The 32x32 blocks the superblock is split into, each with a 32x32 luma + /// transform and a 16x16 transform per chroma plane. + Split(Vec), +} + +/// Writes the payload of a one-tile key frame built from `superblocks`, each +/// either one 64x64 block or the 32x32 blocks it splits into. +/// +/// `superblocks` gives one entry per superblock in raster order across the +/// frame. Every block is DC-predicted unless its [`BlockCoeffs::mode`] says +/// otherwise, and carries the coefficients its lists give; the coefficients +/// may sit anywhere in their transform, so a block is a picture rather than a +/// flat grey. /// /// # Errors -/// Returns an error when the frame is not a whole number of 32x32 blocks, -/// when `blocks` does not carry exactly one set per 32x32 block, -/// when a coefficient sits outside its transform, repeats a position, carries -/// a zero level or one wider than the base and base-range syntax reach, or -/// when `base_q_idx` is outside the q-context band whose default CDFs this -/// crate carries. -pub fn split_coeff_key_frame_tile( +/// Returns an error when the frame is not a whole number of 32x32 blocks, when +/// `superblocks` does not carry exactly one entry per superblock or an entry +/// does not carry one block per quadrant inside the frame, when a superblock +/// that is half outside the frame is left whole, when a block names an intra +/// mode a key frame does not code, when a coefficient sits outside its +/// transform, repeats a position, carries a zero level or one wider than the +/// Golomb tail reaches, or when `base_q_idx` is outside the q-context band +/// whose default CDFs this crate carries. +pub fn sb_coeff_key_frame_tile( mi_cols: u32, mi_rows: u32, base_q_idx: u8, - blocks: &[BlockCoeffs], + superblocks: &[Superblock], ) -> Result> { check_blocks(mi_cols, mi_rows)?; let (cols, rows) = (mi_cols / BLOCK_MI, mi_rows / BLOCK_MI); let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); - if blocks.len() != (cols * rows) as usize { + if superblocks.len() != (sb_cols * sb_rows) as usize { return Err(Error::unsupported( "AV1 tile", - "a coefficient key frame needs one coefficient set per 32x32 block", + "a coefficient key frame needs one entry per superblock", )); } - if let Some(bad) = blocks.iter().find(|b| usize::from(b.mode) >= INTRA_MODES) { + let bad_mode = superblocks + .iter() + .flat_map(|sb| match sb { + Superblock::Whole(b) => std::slice::from_ref(b), + Superblock::Split(b) => b.as_slice(), + }) + .find(|b| usize::from(b.mode) >= INTRA_MODES); + if let Some(bad) = bad_mode { return Err(Error::unsupported( "AV1 tile", format!( @@ -494,24 +553,14 @@ pub fn split_coeff_key_frame_tile( base_q_idx must be 61..=120", )); } - // One level grid per plane of every block, in the plane order they are - // coded in: luma, then U, then V. - let grids = blocks - .iter() - .map(|b| { - Ok([ - level_grid(&b.luma, TX32)?, - level_grid(&b.u, TX16)?, - level_grid(&b.v, TX16)?, - ]) - }) - .collect::>>()?; - let planes = [&LUMA_32, &CHROMA_16, &CHROMA_16]; + let split_planes = [&LUMA_32, &CHROMA_16, &CHROMA_16]; + let whole_planes = [&LUMA_64, &CHROMA_32, &CHROMA_32]; let scans = [default_scan(TX32), default_scan(TX16)]; // What the blocks above and to the left of the one being coded left - // behind, per plane. The left column is reset at every superblock row - // because a tile starts each row with no left neighbour. + // behind, per plane, one entry per 32x32 column and row. The left column + // is reset at every superblock row because a tile starts each row with no + // left neighbour. let mut above = vec![[Neighbour::default(); 3]; cols as usize]; let mut left = vec![[Neighbour::default(); 3]; rows as usize]; // The luma intra mode of those same neighbours, which picks the CDF the @@ -519,13 +568,23 @@ pub fn split_coeff_key_frame_tile( // `DC_PRED`, which is what these start and are reset to. let mut above_mode = vec![DC_PRED; cols as usize]; let mut left_mode = vec![DC_PRED; rows as usize]; + // Whether those neighbours were split, which is what the superblock's + // partition symbol reads: the context is bit three of the neighbour's + // entry in the spec's partition-context table, and of the sizes a + // superblock can leave behind only a 32x32 block sets it. A neighbour + // outside the tile reads as an unsplit one, which is what these start and + // are reset to. + let mut above_split = vec![false; cols as usize]; + let mut left_split = vec![false; rows as usize]; let mut enc = SymbolEncoder::new(); for sb_r in 0..sb_rows { left.iter_mut().for_each(|l| *l = Default::default()); left_mode.iter_mut().for_each(|m| *m = DC_PRED); + left_split.iter_mut().for_each(|l| *l = false); for sb_c in 0..sb_cols { - let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0); + let (r0, c0) = (sb_r as usize * 2, sb_c as usize * 2); + let ctx = 2 * usize::from(left_split[r0]) + usize::from(above_split[c0]); // A superblock whose bottom or right half is outside the frame // cannot be left unsplit, so the decoder reads a flag instead of // the partition symbol — and reads nothing at all when both halves @@ -534,66 +593,108 @@ pub fn split_coeff_key_frame_tile( sb_c * SB_MI + SB_MI / 2 < mi_cols, sb_r * SB_MI + SB_MI / 2 < mi_rows, ); - match (has_cols, has_rows) { - (true, true) => enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]), - (true, false) => enc.symbol_fixed(1, &gather(&cdf::PARTITION_W64[ctx], VERT_ALIKE)), - (false, true) => enc.symbol_fixed(1, &gather(&cdf::PARTITION_W64[ctx], HORZ_ALIKE)), - (false, false) => {} - } - - for quadrant in 0..4 { - let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); - if r >= rows || c >= cols { - // The quadrant is outside the frame: the decoder never - // walks into it. - continue; - } - let (r, c) = (r as usize, c as usize); - let block = &grids[r * cols as usize + c]; - let mode = usize::from(blocks[r * cols as usize + c].mode); - - enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]); - enc.symbol_fixed(0, &cdf::SKIP[0]); - enc.symbol_fixed( - mode, - &cdf::KF_Y_MODE[INTRA_MODE_CTX[above_mode[c]]][INTRA_MODE_CTX[left_mode[r]]], - ); - if (V_PRED..=D67_PRED).contains(&mode) { - enc.symbol_fixed(ANGLE_DELTA_ZERO, &cdf::ANGLE_DELTA[mode - V_PRED]); - } - enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL[mode]); - above_mode[c] = mode; - left_mode[r] = mode; - - for (plane, grid) in block.iter().enumerate() { - let coding = planes[plane]; - // 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 start at. - let skip_ctx = if plane == 0 { - 0 - } else { - usize::from(above[c][plane].coded) + usize::from(left[r][plane].coded) - }; - write_coeffs( + // The quadrants of this superblock that are inside the frame, as + // positions in the 32x32 block grid. + let quadrants: Vec<(usize, usize)> = (0..4) + .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2)) + .filter(|&(r, c)| r < rows && c < cols) + .map(|(r, c)| (r as usize, c as usize)) + .collect(); + + match &superblocks[(sb_r * sb_cols + sb_c) as usize] { + Superblock::Whole(block) => { + if !has_cols || !has_rows { + return Err(Error::unsupported( + "AV1 tile", + "a superblock that is half outside the frame cannot be left whole", + )); + } + enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[ctx]); + let mode = write_intra_mode( &mut enc, - coding, - grid, - &scans[usize::from(plane > 0)], - skip_ctx, - dc_sign_ctx(above[c][plane].dc, left[r][plane].dc), + block, + above_mode[c0], + left_mode[r0], + // A 64x64 block is too big to be offered chroma from + // luma, so its chroma mode reads the table without it. + &cdf::UV_MODE_NO_CFL[usize::from(block.mode)], ); + let grids = [ + level_grid(&block.luma, TX32)?, + level_grid(&block.u, TX32)?, + level_grid(&block.v, TX32)?, + ]; + write_block_planes( + &mut enc, + &whole_planes, + &grids, + &[&scans[0], &scans[0], &scans[0]], + &above[c0], + &left[r0], + ); + // The block covers two columns and two rows of the 32x32 + // grid, so both of each read it as their neighbour. + for (r, c) in quadrants { + for plane in 0..3 { + let state = neighbour_state(&grids[plane]); + above[c][plane] = state; + left[r][plane] = state; + } + above_mode[c] = mode; + left_mode[r] = mode; + above_split[c] = false; + left_split[r] = false; + } } - - for plane in 0..3 { - let grid = &block[plane]; - let state = Neighbour { - coded: grid.iter().any(|&l| l != 0), - dc: (grid[0] != 0).then_some(grid[0] < 0), - }; - above[c][plane] = state; - left[r][plane] = state; + Superblock::Split(blocks) => { + match (has_cols, has_rows) { + (true, true) => enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]), + (true, false) => { + enc.symbol_fixed(1, &gather(&cdf::PARTITION_W64[ctx], VERT_ALIKE)); + } + (false, true) => { + enc.symbol_fixed(1, &gather(&cdf::PARTITION_W64[ctx], HORZ_ALIKE)); + } + (false, false) => {} + } + if blocks.len() != quadrants.len() { + return Err(Error::unsupported( + "AV1 tile", + "a split superblock needs one block per quadrant inside the frame", + )); + } + for (block, (r, c)) in blocks.iter().zip(quadrants) { + enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]); + let mode = write_intra_mode( + &mut enc, + block, + above_mode[c], + left_mode[r], + &cdf::UV_MODE_CFL[usize::from(block.mode)], + ); + let grids = [ + level_grid(&block.luma, TX32)?, + level_grid(&block.u, TX16)?, + level_grid(&block.v, TX16)?, + ]; + write_block_planes( + &mut enc, + &split_planes, + &grids, + &[&scans[0], &scans[1], &scans[1]], + &above[c], + &left[r], + ); + for plane in 0..3 { + let state = neighbour_state(&grids[plane]); + above[c][plane] = state; + left[r][plane] = state; + } + above_mode[c] = mode; + left_mode[r] = mode; + above_split[c] = true; + left_split[r] = true; + } } } } @@ -601,6 +702,108 @@ pub fn split_coeff_key_frame_tile( Ok(enc.finish()) } +/// Writes everything a key frame's block carries before its coefficients: the +/// skip flag, its luma intra mode against the CDF its neighbours' modes pick, +/// the angle a directional mode is steered by, and its chroma mode. Hands back +/// the luma mode, which is what the blocks beside it read. +fn write_intra_mode( + enc: &mut SymbolEncoder, + block: &BlockCoeffs, + above_mode: usize, + left_mode: usize, + uv_cdf: &[u16], +) -> usize { + let mode = usize::from(block.mode); + enc.symbol_fixed(0, &cdf::SKIP[0]); + enc.symbol_fixed( + mode, + &cdf::KF_Y_MODE[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]], + ); + if (V_PRED..=D67_PRED).contains(&mode) { + enc.symbol_fixed(ANGLE_DELTA_ZERO, &cdf::ANGLE_DELTA[mode - V_PRED]); + } + enc.symbol_fixed(DC_PRED, uv_cdf); + mode +} + +/// Writes the three transform blocks of one coded block, in the order a +/// decoder reads them. +fn write_block_planes( + enc: &mut SymbolEncoder, + planes: &[&TxbCoding; 3], + grids: &[Vec; 3], + scans: &[&Vec; 3], + above: &[Neighbour; 3], + left: &[Neighbour; 3], +) { + for (plane, grid) in grids.iter().enumerate() { + // 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 + // start at. + let skip_ctx = if plane == 0 { + 0 + } else { + usize::from(above[plane].coded) + usize::from(left[plane].coded) + }; + write_coeffs( + enc, + planes[plane], + grid, + scans[plane], + skip_ctx, + dc_sign_ctx(above[plane].dc, left[plane].dc), + ); + } +} + +/// 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), + dc: (grid[0] != 0).then_some(grid[0] < 0), + } +} + +/// Writes the payload of a one-tile key frame in which every superblock is +/// split into 32x32 blocks, each carrying the coefficients `blocks` gives it. +/// +/// `blocks` gives one coefficient set per 32x32 block in raster order across +/// the frame. This is [`sb_coeff_key_frame_tile`] with every superblock split. +/// +/// # Errors +/// As [`sb_coeff_key_frame_tile`], with `blocks` sized for the 32x32 grid. +pub fn split_coeff_key_frame_tile( + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + blocks: &[BlockCoeffs], +) -> Result> { + check_blocks(mi_cols, mi_rows)?; + let (cols, rows) = (mi_cols / BLOCK_MI, mi_rows / BLOCK_MI); + if blocks.len() != (cols * rows) as usize { + return Err(Error::unsupported( + "AV1 tile", + "a coefficient key frame needs one coefficient set per 32x32 block", + )); + } + let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); + let superblocks: Vec = (0..sb_rows) + .flat_map(|sb_r| (0..sb_cols).map(move |sb_c| (sb_r, sb_c))) + .map(|(sb_r, sb_c)| { + Superblock::Split( + (0..4) + .map(|q| (sb_r * 2 + q / 2, sb_c * 2 + q % 2)) + .filter(|&(r, c)| r < rows && c < cols) + .map(|(r, c)| blocks[(r * cols + c) as usize].clone()) + .collect(), + ) + }) + .collect(); + sb_coeff_key_frame_tile(mi_cols, mi_rows, base_q_idx, &superblocks) +} + /// Lays one plane's coefficient list out over its transform, rejecting the /// positions and levels the writer does not code. fn level_grid(coeffs: &[Coeff], side: usize) -> Result> { @@ -1994,6 +2197,102 @@ mod tests { /// alternating, so a block written into the wrong place or a flag the /// decoder reads as a different number of bits shows up as a block with the /// other block's shape — or as a decode failure. + fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec> { + let (seq, header) = frame_of(width as u32, height as u32); + let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, sbs).unwrap(); + let mut stream = temporal_delimiter(); + stream.extend_from_slice(&sequence_header_obu(&seq).unwrap()); + stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap()); + let planes = ffmpeg_decode(&stream, width, height); + planes[..width * height] + .chunks_exact(width) + .map(<[u8]>::to_vec) + .collect() + } + + /// A superblock left whole carries one 64x64 transform, whose lowest + /// horizontal basis function falls across the whole sixty-four samples in + /// one stroke. Were the same superblock split, each half would restart the + /// gradient at its own left edge and the picture would rise again in the + /// middle, so the walk across the row is what tells the two apart — and + /// the split superblock beside it proves the two partitions still agree on + /// where the next one begins. + #[test] + fn a_whole_superblock_covers_all_four_of_its_quadrants() { + if !have_ffmpeg() { + eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg"); + return; + } + let across = BlockCoeffs::from(vec![Coeff { + row: 0, + col: 1, + level: 20, + }]); + let down = BlockCoeffs::from(vec![Coeff { + row: 1, + col: 0, + level: 20, + }]); + let sbs = [ + Superblock::Whole(across), + Superblock::Split(vec![down.clone(), down.clone(), down.clone(), down]), + ]; + let rows = decode_luma_sb(128, 64, &sbs); + + for (y, row) in rows.iter().enumerate() { + assert_eq!( + &row[..64], + &rows[0][..64], + "row {y} of the whole superblock repeats its first row" + ); + } + let first = &rows[0][..64]; + assert!( + first.windows(2).all(|w| w[0] >= w[1]), + "the whole superblock falls across its sixty-four samples without \ + restarting: {first:?}" + ); + assert!( + first[0] > first[63], + "the whole superblock falls from left to right, got {} then {}", + first[0], + first[63] + ); + for block_row in 0..2 { + for block_col in 2..4 { + let block = block_at(&rows, block_row, block_col); + assert_falls_down(&block, &format!("quadrant ({block_row},{block_col})")); + } + } + } + + /// A superblock half outside the frame has no partition that keeps a block + /// outside it, so it cannot be left whole. + #[test] + fn a_whole_superblock_at_the_frame_edge_is_refused() { + let block = BlockCoeffs::from(vec![Coeff { + row: 0, + col: 0, + level: 4, + }]); + let sbs = [ + Superblock::Split(vec![ + block.clone(), + block.clone(), + block.clone(), + block.clone(), + ]), + Superblock::Whole(block.clone()), + ]; + // Ninety-six samples across is three 32x32 blocks, so the second + // superblock hangs half outside the frame. + let err = sb_coeff_key_frame_tile(24, 16, Q_IDX, &sbs).unwrap_err(); + assert!( + format!("{err}").contains("half outside the frame"), + "got {err}" + ); + } + #[test] fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() { if !have_ffmpeg() {