diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 62069434..2438521f 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -105,10 +105,7 @@ pub fn flat_key_frame_tile(mi_cols: u32, mi_rows: u32) -> Result> { /// picks the coefficient CDFs. /// /// # Errors -/// Returns an error when the frame is not a whole number of 64x64 superblocks, -/// when `dc_level` is outside the range the base and base-range syntax carry -/// (`-14..=14` without zero), or when `base_q_idx` is outside the q-context -/// band whose default CDFs this crate carries. +/// As [`dc_key_frame_tile_levels`], which this is the one-level case of. pub fn dc_key_frame_tile( mi_cols: u32, mi_rows: u32, @@ -116,7 +113,41 @@ pub fn dc_key_frame_tile( dc_level: i32, ) -> Result> { check_superblocks(mi_cols, mi_rows)?; - if dc_level == 0 || dc_level.abs() > MAX_LEVEL { + let blocks = ((mi_cols / SB_MI) * (mi_rows / SB_MI)) as usize; + dc_key_frame_tile_levels(mi_cols, mi_rows, base_q_idx, &vec![dc_level; blocks]) +} + +/// Writes the payload of a one-tile key frame carrying one luma DC coefficient +/// per superblock, `levels` giving them in the raster order the superblocks are +/// coded in. +/// +/// Each superblock decodes to a flat block of its own grey, so a frame written +/// here is a grid of greys the caller chooses — which is what makes the sign +/// context observable: a block's sign context is read off its coded neighbours, +/// and a frame whose levels differ in sign exercises the three-way split that a +/// single-sign frame cannot reach. +/// +/// # Errors +/// Returns an error when the frame is not a whole number of 64x64 superblocks, +/// when `levels` does not carry exactly one level per superblock, when a level +/// is outside the range the base and base-range syntax carry (`-14..=14` +/// without zero), or when `base_q_idx` is outside the q-context band whose +/// default CDFs this crate carries. +pub fn dc_key_frame_tile_levels( + mi_cols: u32, + mi_rows: u32, + base_q_idx: u8, + levels: &[i32], +) -> Result> { + check_superblocks(mi_cols, mi_rows)?; + let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI); + if levels.len() != (sb_cols * sb_rows) as usize { + return Err(Error::unsupported( + "AV1 tile", + "a DC-only key frame needs one level per 64x64 superblock", + )); + } + if levels.iter().any(|&l| l == 0 || l.abs() > MAX_LEVEL) { return Err(Error::unsupported( "AV1 tile", "a DC-only key frame is written for levels -14..=14 without zero; \ @@ -130,13 +161,20 @@ pub fn dc_key_frame_tile( base_q_idx must be 61..=120", )); } - let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI); - let level = dc_level.abs(); - let negative = dc_level < 0; + // The sign of the DC each coded block left behind, for the two neighbours + // the sign context is read from: one row of them above, and the block to + // the left, which is dropped at the start of every superblock row the way a + // decoder clears its left context there. + let mut above: Vec> = vec![None; sb_cols as usize]; let mut enc = SymbolEncoder::new(); for r in 0..sb_rows { + let mut left: Option = None; for c in 0..sb_cols { + let dc_level = levels[(r * sb_cols + c) as usize]; + let level = dc_level.abs(); + let negative = dc_level < 0; + enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W64[0]); // Nothing is skipped now, so every neighbour's skip flag is 0 and @@ -160,22 +198,22 @@ pub fn dc_key_frame_tile( // The base-range tail. Every neighbour of the DC is zero, so its // magnitude context is 0 throughout. if level > NUM_BASE_LEVELS { - let mut left = level - (NUM_BASE_LEVELS + 1); + let mut remaining = level - (NUM_BASE_LEVELS + 1); let mut sent = 0; while sent < COEFF_BASE_RANGE { - let k = left.min(BR_STEP); + let k = remaining.min(BR_STEP); enc.symbol_fixed(k as usize, &cdf::COEFF_BR_LUMA); if k < BR_STEP { break; } - left -= k; + remaining -= k; sent += BR_STEP; } } // The signs come after the levels, DC first (spec 5.11.39). enc.symbol_fixed( usize::from(negative), - &cdf::DC_SIGN_LUMA[dc_sign_ctx(r, c, negative)], + &cdf::DC_SIGN_LUMA[dc_sign_ctx(above[c as usize], left)], ); // Both chroma transform blocks are all-zero. Their planes carry no @@ -184,22 +222,31 @@ pub fn dc_key_frame_tile( // 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); + + above[c as usize] = Some(negative); + left = Some(negative); } } Ok(enc.finish()) } -/// `Dc_Sign_Contexts` (spec 8.3.2) for a frame every block of which carries a -/// DC of the same sign: each of the sixteen 4x4 units above and left of the -/// block votes its neighbour's sign, so the count is 0, +-16 or +-32 and the -/// table's three-way split reduces to "no coded neighbour, or which way they -/// lean". The left column is cleared at the start of every superblock row. -fn dc_sign_ctx(sb_row: u32, sb_col: u32, negative: bool) -> usize { - let neighbours = i32::from(sb_row > 0) + i32::from(sb_col > 0); - if neighbours == 0 { - return 0; +/// `Dc_Sign_Contexts` (spec 8.3.2): every 4x4 unit above and left of the block +/// votes the sign of the DC its own block carries — plus one for a positive +/// one, minus one for a negative one, nothing for a unit with no coded +/// coefficient — and the sum picks one of three contexts. Every block here is a +/// whole superblock carrying one DC, so all sixteen units of a neighbour vote +/// together and the sum can only lean up, lean down, or cancel. +fn dc_sign_ctx(above: Option, left: Option) -> usize { + let vote = |n: Option| match n { + None => 0i32, + Some(true) => -1, + Some(false) => 1, + }; + match (vote(above) + vote(left)).signum() { + 0 => 0, + -1 => 1, + _ => 2, } - if negative { 1 } else { 2 } } #[cfg(test)] @@ -449,6 +496,112 @@ mod tests { ); } + /// Encode a grid of 64x64 superblocks, each carrying its own DC level, and + /// hand back the decoded planes. + fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec { + let (w, h) = (64 * sb_cols, 64 * sb_rows); + let mut seq = sequence_64(); + seq.max_frame_width = w; + seq.max_frame_height = h; + let mut header = flat_key_frame(); + header.frame_width = w; + header.frame_height = h; + header.upscaled_width = w; + header.render_width = w; + header.render_height = h; + header.mi_cols = sb_cols * SB_MI; + header.mi_rows = sb_rows * SB_MI; + header.tile_info.mi_col_starts = vec![0, header.mi_cols]; + header.tile_info.mi_row_starts = vec![0, header.mi_rows]; + header.quantization.base_q_idx = Q_IDX; + let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).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()); + ffmpeg_decode(&stream, w as usize, h as usize) + } + + fn decoded_value(level: i32) -> u8 { + DECODED_AT_Q100 + .iter() + .find(|&&(l, _)| l == level) + .map(|&(_, v)| v) + .expect("the level is in the pinned table") + } + + /// `dc_predict` (spec 7.11.2) for the flat case: a block whose neighbours + /// are themselves flat predicts their average, and predicts mid-grey with + /// no neighbour at all. Every block here is a whole 64x64 superblock, so + /// the above row and the left column weigh the same. + fn dc_prediction(above: Option, left: Option) -> u8 { + match (above, left) { + (None, None) => 128, + (Some(a), None) => a, + (None, Some(l)) => l, + (Some(a), Some(l)) => ((u32::from(a) * 64 + u32::from(l) * 64 + 64) >> 7) as u8, + } + } + + /// What a DC level adds to the prediction: the pinned table is that sum + /// against a mid-grey prediction, and the residual does not depend on what + /// it is added to. + fn dc_residual(level: i32) -> i32 { + i32::from(decoded_value(level)) - 128 + } + + /// Every block reads its DC sign context off the coded blocks above and to + /// its left, and the three ways that can land — no coded neighbour, the + /// neighbours leaning one way, the neighbours cancelling — are only + /// reachable in a frame whose levels differ in sign. Getting the context + /// wrong desyncs the arithmetic decoder, so the check is that every block + /// still decodes to the grey its own level asks for. + #[test] + fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() { + if !have_ffmpeg() { + eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg"); + return; + } + // Read in raster order the two grids put a positive, a negative and a + // cancelling sign context in front of the bottom-right block, and a + // leaning-down one in front of the second grid's right and bottom + // blocks. + for levels in [[14, 3, -3, -14], [-14, -3, 3, 14]] { + let planes = decode_level_grid(&levels, 2, 2); + let (luma, chroma) = planes.split_at(128 * 128); + // The blocks are not independent: a DC prediction reads the + // reconstructed neighbours, so each block's grey is its + // neighbours' average plus its own residual. + let mut recon = [0u8; 4]; + for (block, level) in levels.iter().enumerate() { + let (br, bc) = (block / 2, block % 2); + let above = (br > 0).then(|| recon[block - 2]); + let left = (bc > 0).then(|| recon[block - 1]); + let want = (i32::from(dc_prediction(above, left)) + dc_residual(*level)) + .clamp(0, 255) as u8; + recon[block] = want; + for y in 0..64 { + for x in 0..64 { + let i = (br * 64 + y) * 128 + bc * 64 + x; + assert_eq!( + luma[i], want, + "luma at ({x}, {y}) of the block carrying level {level} in {levels:?}" + ); + } + } + } + for (i, &sample) in chroma.iter().enumerate() { + assert_eq!(sample, 128, "chroma sample {i} of {levels:?}"); + } + } + } + + #[test] + fn a_level_grid_that_does_not_cover_the_frame_is_refused() { + assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err()); + assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err()); + assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err()); + } + #[test] fn dc_levels_the_base_syntax_cannot_carry_are_refused() { assert!(dc_key_frame_tile(16, 16, 100, 0).is_err());