forge
Explore
Log in

Don't you dare go Hollow

Code chroma coefficients beside the luma ones

Browse files at this commit

b99ade139d4f9399a17e4a39b47ddc09b47b39e1Ahmet Kaan GümüşParent: 0dac984
  • feat
    • code chroma coefficients beside the luma ones
Show full message
feat(av1): code chroma coefficients beside the luma ones

The coefficient writer took a luma coefficient list per 32x32 block and
wrote both chroma transform blocks as all-zero. It now takes a
BlockCoeffs per block — luma, U and V — and codes each plane's own
16x16 chroma transform.

The coefficient layer is generalised over the plane rather than
duplicated: a TxbCoding carries the transform's side and the six default
CDF sets that are indexed by plane type and transform size, plus the
end-of-block alphabet, which is a quarter the size at 16x16. The chroma
all-zero flag reads the context its coded neighbours above and to the
left select, so the writer now tracks per plane what each block left
behind rather than only the sign of its luma DC.

Gated by dav1d decodes of derived structure, not pinned bytes: a chroma
basis function must be flat down the block and fall across it, the plane
turned a quarter turn must do the reverse, neither may reach the other
plane or luma, and a block with no DC must average to its prediction.
Three mutations were checked to fail those tests: chroma reading the
luma base table, the chroma all-zero context pinned at 7, and the chroma
end-of-block alphabet taken from luma.
crates/ec-av1/src/cdf.rsmodified+114 -5
@@ -259,11 +259,6 @@ pub const UV_MODE_CFL_DC: [u16; 15] = [
259 /// luma transform block that covers its whole plane block, which is context 0.259 /// luma transform block that covers its whole plane block, which is context 0.
260 pub const TXB_SKIP_LUMA_32: [u16; 3] = [30669, 32768, 0];260 pub const TXB_SKIP_LUMA_32: [u16; 3] = [30669, 32768, 0];
261 261
262-/// `Default_Txb_Skip_Cdf[2][2][7]` (spec 9.4): the all-zero flag of a 16x16
263-/// chroma transform block that covers its whole plane block with no coded
264-/// neighbour, which is context 7.
265-pub const TXB_SKIP_CHROMA_16: [u16; 3] = [3648, 32768, 0];
266-
267 /// `Default_Coeff_Base_Cdf[2][3][0]` (spec 9.4): the level of a coefficient262 /// `Default_Coeff_Base_Cdf[2][3][0]` (spec 9.4): the level of a coefficient
268 /// of a 32x32 luma transform block, capped at three, for each of the263 /// of a 32x32 luma transform block, capped at three, for each of the
269 /// forty-two contexts its neighbours' magnitudes and its own position give.264 /// forty-two contexts its neighbours' magnitudes and its own position give.
@@ -371,3 +366,117 @@ pub const NZ_MAP_CTX_OFFSET_32: [[u8; 5]; 5] = [
371 [6, 21, 21, 21, 21],366 [6, 21, 21, 21, 21],
372 [21, 21, 21, 21, 21],367 [21, 21, 21, 21, 21],
373 ];368 ];
369+
370+/// `Default_Txb_Skip_Cdf[2][2][7..10]` (spec 9.4): the all-zero flag of a
371+/// 16x16 chroma transform block that covers its whole plane block, for the
372+/// three contexts its coded neighbours give.
373+pub const TXB_SKIP_CHROMA_16: [[u16; 3]; 3] =
374+ [[3648, 32768, 0], [15690, 32768, 0], [26815, 32768, 0]];
375+
376+/// `Default_Coeff_Base_Cdf[2][2][1]` (spec 9.4): the level of a coefficient
377+/// of a 16x16 chroma transform block, capped at three, for each of the
378+/// forty-two contexts its neighbours and its position give.
379+pub const COEFF_BASE_CHROMA_16: [[u16; 5]; 42] = [
380+ [9185, 19694, 24688, 32768, 0],
381+ [26081, 31985, 32621, 32768, 0],
382+ [16015, 29000, 31787, 32768, 0],
383+ [10542, 23690, 29206, 32768, 0],
384+ [6732, 17945, 24677, 32768, 0],
385+ [3916, 11039, 16722, 32768, 0],
386+ [28224, 32566, 32744, 32768, 0],
387+ [19100, 31138, 32485, 32768, 0],
388+ [12528, 26620, 30879, 32768, 0],
389+ [7741, 20277, 26885, 32768, 0],
390+ [4566, 12845, 18990, 32768, 0],
391+ [29933, 32593, 32718, 32768, 0],
392+ [17670, 30333, 32155, 32768, 0],
393+ [10385, 23600, 28909, 32768, 0],
394+ [6243, 16236, 22407, 32768, 0],
395+ [3976, 10389, 16017, 32768, 0],
396+ [28377, 32561, 32738, 32768, 0],
397+ [19366, 31175, 32482, 32768, 0],
398+ [13327, 27175, 31094, 32768, 0],
399+ [8258, 20769, 27143, 32768, 0],
400+ [4703, 13198, 19527, 32768, 0],
401+ [31086, 32706, 32748, 32768, 0],
402+ [22853, 31902, 32583, 32768, 0],
403+ [14759, 28186, 31419, 32768, 0],
404+ [9284, 22382, 28348, 32768, 0],
405+ [5585, 15192, 21868, 32768, 0],
406+ [28291, 32652, 32746, 32768, 0],
407+ [19849, 32107, 32571, 32768, 0],
408+ [14834, 26818, 29214, 32768, 0],
409+ [10306, 22594, 28672, 32768, 0],
410+ [6615, 17384, 23384, 32768, 0],
411+ [28947, 32604, 32745, 32768, 0],
412+ [25625, 32289, 32646, 32768, 0],
413+ [18758, 28672, 31403, 32768, 0],
414+ [10017, 23430, 28523, 32768, 0],
415+ [6862, 15269, 22131, 32768, 0],
416+ [23933, 32509, 32739, 32768, 0],
417+ [19927, 31495, 32631, 32768, 0],
418+ [11903, 26023, 30621, 32768, 0],
419+ [7026, 20094, 27252, 32768, 0],
420+ [5998, 18106, 24437, 32768, 0],
421+ [8192, 16384, 24576, 32768, 0],
422+];
423+
424+/// `Default_Coeff_Br_Cdf[2][2][1]` (spec 9.4): a base-range increment in a
425+/// 16x16 chroma transform block, for each of its twenty-one contexts.
426+pub const COEFF_BR_CHROMA_16: [[u16; 5]; 21] = [
427+ [13569, 19800, 23206, 32768, 0],
428+ [13128, 19924, 23869, 32768, 0],
429+ [8329, 14841, 19403, 32768, 0],
430+ [6130, 10976, 15057, 32768, 0],
431+ [4682, 8839, 12518, 32768, 0],
432+ [3656, 7409, 10588, 32768, 0],
433+ [2577, 5099, 7412, 32768, 0],
434+ [22427, 28684, 30585, 32768, 0],
435+ [20913, 27750, 30139, 32768, 0],
436+ [15840, 24109, 27834, 32768, 0],
437+ [12308, 20029, 24569, 32768, 0],
438+ [10216, 16785, 21458, 32768, 0],
439+ [8309, 14203, 19113, 32768, 0],
440+ [6043, 11168, 15307, 32768, 0],
441+ [23166, 28901, 30998, 32768, 0],
442+ [21899, 28405, 30751, 32768, 0],
443+ [18413, 26091, 29443, 32768, 0],
444+ [15233, 23114, 27352, 32768, 0],
445+ [12683, 20472, 25288, 32768, 0],
446+ [10702, 18259, 23409, 32768, 0],
447+ [8125, 14464, 19226, 32768, 0],
448+];
449+
450+/// `Default_Coeff_Base_Eob_Cdf[2][2][1]` (spec 9.4): the level of the last
451+/// coefficient of a 16x16 chroma transform block, less one, for each of the
452+/// four contexts its position in the scan gives.
453+pub const COEFF_BASE_EOB_CHROMA_16: [[u16; 4]; 4] = [
454+ [25476, 30366, 32768, 0],
455+ [32169, 32687, 32768, 0],
456+ [32479, 32689, 32768, 0],
457+ [31673, 32634, 32768, 0],
458+];
459+
460+/// `Default_Eob_Extra_Cdf[2][2][1]` (spec 9.4): the top bit of the offset
461+/// into an end-of-block position group of a 16x16 chroma transform block.
462+pub const EOB_EXTRA_CHROMA_16: [[u16; 3]; 9] = [
463+ [22041, 32768, 0],
464+ [23434, 32768, 0],
465+ [20001, 32768, 0],
466+ [20554, 32768, 0],
467+ [20951, 32768, 0],
468+ [20145, 32768, 0],
469+ [15562, 32768, 0],
470+ [16384, 32768, 0],
471+ [16384, 32768, 0],
472+];
473+
474+/// `Default_Eob_Pt_256_Cdf[2][1][0]` (spec 9.4): the end-of-block group of a
475+/// 256-coefficient chroma transform block with a two-dimensional transform.
476+pub const EOB_PT_256_CHROMA: [u16; 10] = [
477+ 11514, 13794, 17480, 20754, 24361, 27378, 29492, 31277, 32768, 0,
478+];
479+
480+/// `Default_Dc_Sign_Cdf[2][1]` (spec 9.4): the sign of a chroma DC
481+/// coefficient, indexed the way [`DC_SIGN_LUMA`] is.
482+pub const DC_SIGN_CHROMA: [[u16; 3]; 3] = [[15232, 32768, 0], [12928, 32768, 0], [17280, 32768, 0]];
crates/ec-av1/src/tile.rsmodified+417 -114
@@ -246,8 +246,8 @@ pub fn split_dc_key_frame_tile(
246 &cdf::TXB_SKIP_LUMA_32,246 &cdf::TXB_SKIP_LUMA_32,
247 &cdf::COEFF_BASE_EOB_LUMA_32[0],247 &cdf::COEFF_BASE_EOB_LUMA_32[0],
248 );248 );
249- enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16);249+ enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16[0]);
250- enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16);250+ enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16[0]);
251 251
252 above[c as usize] = Some(negative);252 above[c as usize] = Some(negative);
253 left[r as usize] = Some(negative);253 left[r as usize] = Some(negative);
@@ -257,43 +257,128 @@ pub fn split_dc_key_frame_tile(
257 Ok(enc.finish())257 Ok(enc.finish())
258 }258 }
259 259
260-/// One quantised coefficient of a 32x32 luma transform block.260+/// One quantised coefficient of a transform block.
261 ///261 ///
262-/// `row` and `col` are its position in the transform, not in the picture: a262+/// `row` and `col` are its position in the transform it belongs to — 32x32 for
263-/// coefficient at row 0 varies along the picture's width and one at column 0263+/// luma, 16x16 for each chroma plane — not in the picture: a coefficient at
264-/// along its height, and the coefficient at the origin is the DC the block's264+/// row 0 varies along the picture's width and one at column 0 along its
265-/// average sample value rides on.265+/// height, and the coefficient at the origin is the DC the block's average
266+/// sample value rides on.
266 #[derive(Clone, Copy, Debug, PartialEq, Eq)]267 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
267 pub struct Coeff {268 pub struct Coeff {
268- /// The coefficient's row in the transform, 0..32.269+ /// The coefficient's row in the transform.
269 pub row: u8,270 pub row: u8,
270- /// The coefficient's column in the transform, 0..32.271+ /// The coefficient's column in the transform.
271 pub col: u8,272 pub col: u8,
272 /// Its quantised level, which the base and base-range syntax carry for273 /// Its quantised level, which the base and base-range syntax carry for
273 /// magnitudes up to [`MAX_LEVEL`].274 /// magnitudes up to [`MAX_LEVEL`].
274 pub level: i32,275 pub level: i32,
275 }276 }
276 277
278+/// The coefficients of one coded block: a 32x32 luma transform and, at 4:2:0,
279+/// the 16x16 transform each chroma plane covers the same area with.
280+#[derive(Clone, Debug, Default, PartialEq, Eq)]
281+pub struct BlockCoeffs {
282+ /// The luma transform's coefficients.
283+ pub luma: Vec<Coeff>,
284+ /// The U plane's.
285+ pub u: Vec<Coeff>,
286+ /// The V plane's.
287+ pub v: Vec<Coeff>,
288+}
289+
290+impl From<Vec<Coeff>> for BlockCoeffs {
291+ /// A block that codes luma only.
292+ fn from(luma: Vec<Coeff>) -> Self {
293+ Self {
294+ luma,
295+ ..Self::default()
296+ }
297+ }
298+}
299+
277 /// Side of the luma transform the coefficient writer codes.300 /// Side of the luma transform the coefficient writer codes.
278 const TX32: usize = 32;301 const TX32: usize = 32;
279-/// How many coefficients that transform holds.302+/// Side of the chroma transform beside it at 4:2:0.
280-const TX32_AREA: usize = TX32 * TX32;303+const TX16: usize = 16;
304+
305+/// The shapes and default CDFs one plane's transform blocks are coded with.
306+/// The two differ in every coefficient table because the CDFs are indexed by
307+/// plane type and transform size, and in the end-of-block alphabet because a
308+/// 16x16 transform has a quarter of the positions to point at.
309+struct TxbCoding {
310+ /// Side of the transform, in coefficients.
311+ side: usize,
312+ /// The all-zero flag, indexed by its own context.
313+ txb_skip: &'static [[u16; 3]],
314+ /// The end-of-block group, whose alphabet the transform size sets.
315+ eob_pt: &'static [u16],
316+ /// The top bit of the offset inside that group.
317+ eob_extra: &'static [[u16; 3]; 9],
318+ /// A coefficient's base level.
319+ base: &'static [[u16; 5]; 42],
320+ /// The base level of the last coefficient in the scan.
321+ base_eob: &'static [[u16; 4]; 4],
322+ /// The base-range tail above level two.
323+ br: &'static [[u16; 5]; 21],
324+ /// The sign of the DC.
325+ dc_sign: &'static [[u16; 3]; 3],
326+}
327+
328+/// The luma all-zero flag has one context here: the transform covers its whole
329+/// block, which fixes it at zero.
330+const TXB_SKIP_LUMA_32_CTX: [[u16; 3]; 1] = [cdf::TXB_SKIP_LUMA_32];
331+
332+/// The 32x32 luma transform of a 32x32 block.
333+const LUMA_32: TxbCoding = TxbCoding {
334+ side: TX32,
335+ txb_skip: &TXB_SKIP_LUMA_32_CTX,
336+ eob_pt: &cdf::EOB_PT_1024_LUMA,
337+ eob_extra: &cdf::EOB_EXTRA_LUMA_32,
338+ base: &cdf::COEFF_BASE_LUMA_32,
339+ base_eob: &cdf::COEFF_BASE_EOB_LUMA_32,
340+ br: &cdf::COEFF_BR_LUMA_32,
341+ dc_sign: &cdf::DC_SIGN_LUMA,
342+};
343+
344+/// The 16x16 transform of either chroma plane of that block at 4:2:0.
345+const CHROMA_16: TxbCoding = TxbCoding {
346+ side: TX16,
347+ txb_skip: &cdf::TXB_SKIP_CHROMA_16,
348+ eob_pt: &cdf::EOB_PT_256_CHROMA,
349+ eob_extra: &cdf::EOB_EXTRA_CHROMA_16,
350+ base: &cdf::COEFF_BASE_CHROMA_16,
351+ base_eob: &cdf::COEFF_BASE_EOB_CHROMA_16,
352+ br: &cdf::COEFF_BR_CHROMA_16,
353+ dc_sign: &cdf::DC_SIGN_CHROMA,
354+};
355+
356+/// What one coded block leaves behind for the blocks that read it as a
357+/// neighbour: whether it coded anything at all, and the sign of its DC.
358+#[derive(Clone, Copy, Default)]
359+struct Neighbour {
360+ /// Whether the plane's transform block carried a coefficient.
361+ coded: bool,
362+ /// The sign of its DC, absent when the DC itself is zero.
363+ dc: Option<bool>,
364+}
281 365
282 /// Writes the payload of a one-tile key frame in which every superblock is366 /// Writes the payload of a one-tile key frame in which every superblock is
283-/// split into four 32x32 DC-predicted blocks, each carrying the luma367+/// split into four 32x32 DC-predicted blocks, each carrying the coefficients
284-/// coefficients `blocks` gives it and no chroma residual.368+/// `blocks` gives it.
285 ///369 ///
286-/// `blocks` gives one coefficient list per 32x32 block in raster order across370+/// `blocks` gives one coefficient set per 32x32 block in raster order across
287-/// the frame, so it is twice as wide and twice as tall as the superblock grid.371+/// the frame, so the grid is twice as wide and twice as tall as the superblock
288-/// An empty list writes an all-zero transform block. Unlike the DC writers,372+/// grid. Each set carries a 32x32 luma transform and the 16x16 transform of
289-/// the coefficients may sit anywhere in the transform, so a block here is a373+/// each chroma plane; an empty list writes an all-zero transform block. Unlike
290-/// picture rather than a flat grey: a single coefficient off the origin374+/// the DC writers, the coefficients may sit anywhere in their transform, so a
291-/// decodes to the basis function it selects.375+/// block here is a picture rather than a flat grey: a single coefficient off
376+/// the origin decodes to the basis function it selects.
292 ///377 ///
293 /// # Errors378 /// # Errors
294 /// Returns an error when the frame is not a whole number of 64x64379 /// Returns an error when the frame is not a whole number of 64x64
295-/// superblocks, when `blocks` does not carry exactly one list per 32x32 block,380+/// superblocks, when `blocks` does not carry exactly one set per 32x32 block,
296-/// when a coefficient sits outside the transform, repeats a position, carries381+/// when a coefficient sits outside its transform, repeats a position, carries
297 /// a zero level or one wider than the base and base-range syntax reach, or382 /// a zero level or one wider than the base and base-range syntax reach, or
298 /// when `base_q_idx` is outside the q-context band whose default CDFs this383 /// when `base_q_idx` is outside the q-context band whose default CDFs this
299 /// crate carries.384 /// crate carries.
@@ -301,7 +386,7 @@ pub fn split_coeff_key_frame_tile(
301 mi_cols: u32,386 mi_cols: u32,
302 mi_rows: u32,387 mi_rows: u32,
303 base_q_idx: u8,388 base_q_idx: u8,
304- blocks: &[Vec<Coeff>],389+ blocks: &[BlockCoeffs],
305 ) -> Result<Vec<u8>> {390 ) -> Result<Vec<u8>> {
306 check_superblocks(mi_cols, mi_rows)?;391 check_superblocks(mi_cols, mi_rows)?;
307 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);392 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
@@ -309,7 +394,7 @@ pub fn split_coeff_key_frame_tile(
309 if blocks.len() != (cols * rows) as usize {394 if blocks.len() != (cols * rows) as usize {
310 return Err(Error::unsupported(395 return Err(Error::unsupported(
311 "AV1 tile",396 "AV1 tile",
312- "a coefficient key frame needs one coefficient list per 32x32 block",397+ "a coefficient key frame needs one coefficient set per 32x32 block",
313 ));398 ));
314 }399 }
315 if !Q_CTX_2.contains(&base_q_idx) {400 if !Q_CTX_2.contains(&base_q_idx) {
@@ -319,62 +404,89 @@ pub fn split_coeff_key_frame_tile(
319 base_q_idx must be 61..=120",404 base_q_idx must be 61..=120",
320 ));405 ));
321 }406 }
407+ // One level grid per plane of every block, in the plane order they are
408+ // coded in: luma, then U, then V.
322 let grids = blocks409 let grids = blocks
323 .iter()410 .iter()
324- .map(|b| level_grid(b))411+ .map(|b| {
412+ Ok([
413+ level_grid(&b.luma, TX32)?,
414+ level_grid(&b.u, TX16)?,
415+ level_grid(&b.v, TX16)?,
416+ ])
417+ })
325 .collect::<Result<Vec<_>>>()?;418 .collect::<Result<Vec<_>>>()?;
326 419
327- let scan = default_scan_32();420+ let planes = [&LUMA_32, &CHROMA_16, &CHROMA_16];
328- // The sign of each coded block's DC, for the neighbours the DC sign421+ let scans = [default_scan(TX32), default_scan(TX16)];
329- // context is read from. A block whose DC is zero casts no vote, however422+ // What the blocks above and to the left of the one being coded left
330- // much its other coefficients carry.423+ // behind, per plane. The left column is reset at every superblock row
331- let mut above: Vec<Option<bool>> = vec![None; cols as usize];424+ // because a tile starts each row with no left neighbour.
332- let mut left: Vec<Option<bool>> = vec![None; rows as usize];425+ let mut above = vec![[Neighbour::default(); 3]; cols as usize];
426+ let mut left = vec![[Neighbour::default(); 3]; rows as usize];
333 427
334 let mut enc = SymbolEncoder::new();428 let mut enc = SymbolEncoder::new();
335 for sb_r in 0..sb_rows {429 for sb_r in 0..sb_rows {
336- left.iter_mut().for_each(|l| *l = None);430+ left.iter_mut().for_each(|l| *l = Default::default());
337 for sb_c in 0..sb_cols {431 for sb_c in 0..sb_cols {
338 let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);432 let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);
339 enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);433 enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);
340 434
341 for quadrant in 0..4 {435 for quadrant in 0..4 {
342 let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);436 let (r, c) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
343- let grid = &grids[(r * cols + c) as usize];437+ let (r, c) = (r as usize, c as usize);
438+ let block = &grids[r * cols as usize + c];
344 439
345 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);440 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
346 enc.symbol_fixed(0, &cdf::SKIP[0]);441 enc.symbol_fixed(0, &cdf::SKIP[0]);
347 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);442 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
348 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL_DC);443 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL_DC);
349 444
445+ for (plane, grid) in block.iter().enumerate() {
446+ let coding = planes[plane];
447+ // Luma's transform covers its whole block, which fixes the
448+ // all-zero flag's context at zero; a chroma transform reads
449+ // whether its neighbours coded anything, on top of the
450+ // offset the chroma tables start at.
451+ let skip_ctx = if plane == 0 {
452+ 0
453+ } else {
454+ usize::from(above[c][plane].coded) + usize::from(left[r][plane].coded)
455+ };
350 write_coeffs(456 write_coeffs(
351 &mut enc,457 &mut enc,
458+ coding,
352 grid,459 grid,
353- &scan,460+ &scans[usize::from(plane > 0)],
354- dc_sign_ctx(above[c as usize], left[r as usize]),461+ skip_ctx,
462+ dc_sign_ctx(above[c][plane].dc, left[r][plane].dc),
355 );463 );
356- enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16);464+ }
357- enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16);
358 465
359- let dc = grid[0];466+ for plane in 0..3 {
360- let vote = (dc != 0).then_some(dc < 0);467+ let grid = &block[plane];
361- above[c as usize] = vote;468+ let state = Neighbour {
362- left[r as usize] = vote;469+ coded: grid.iter().any(|&l| l != 0),
470+ dc: (grid[0] != 0).then_some(grid[0] < 0),
471+ };
472+ above[c][plane] = state;
473+ left[r][plane] = state;
474+ }
363 }475 }
364 }476 }
365 }477 }
366 Ok(enc.finish())478 Ok(enc.finish())
367 }479 }
368 480
369-/// Lays one block's coefficient list out over the transform, rejecting the481+/// Lays one plane's coefficient list out over its transform, rejecting the
370 /// positions and levels the writer does not code.482 /// positions and levels the writer does not code.
371-fn level_grid(coeffs: &[Coeff]) -> Result<Vec<i32>> {483+fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> {
372- let mut grid = vec![0i32; TX32_AREA];484+ let mut grid = vec![0i32; side * side];
373 for coeff in coeffs {485 for coeff in coeffs {
374- if usize::from(coeff.row) >= TX32 || usize::from(coeff.col) >= TX32 {486+ if usize::from(coeff.row) >= side || usize::from(coeff.col) >= side {
375 return Err(Error::unsupported(487 return Err(Error::unsupported(
376 "AV1 tile",488 "AV1 tile",
377- "a coefficient sits outside the 32x32 transform the writer codes",489+ "a coefficient sits outside the transform of its plane",
378 ));490 ));
379 }491 }
380 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {492 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {
@@ -384,7 +496,7 @@ fn level_grid(coeffs: &[Coeff]) -> Result<Vec<i32>> {
384 wider levels need the Golomb tail",496 wider levels need the Golomb tail",
385 ));497 ));
386 }498 }
387- let pos = usize::from(coeff.row) * TX32 + usize::from(coeff.col);499+ let pos = usize::from(coeff.row) * side + usize::from(coeff.col);
388 if grid[pos] != 0 {500 if grid[pos] != 0 {
389 return Err(Error::unsupported(501 return Err(Error::unsupported(
390 "AV1 tile",502 "AV1 tile",
@@ -396,19 +508,19 @@ fn level_grid(coeffs: &[Coeff]) -> Result<Vec<i32>> {
396 Ok(grid)508 Ok(grid)
397 }509 }
398 510
399-/// The default scan of a 32x32 transform (spec 8.4.2's `Default_Scan_32x32`),511+/// The default scan of a square transform (spec 8.4.2's `Default_Scan_NxN`),
400 /// as raster positions in the order they are coded.512 /// as raster positions in the order they are coded.
401 ///513 ///
402-/// The table is a rule rather than a thousand pinned numbers: the scan walks514+/// The table is a rule rather than hundreds of pinned numbers: the scan walks
403 /// the anti-diagonals of the transform outwards from the origin, each diagonal515 /// the anti-diagonals of the transform outwards from the origin, each diagonal
404 /// from its top-right end on odd diagonals and from its bottom-left end on516 /// from its top-right end on odd diagonals and from its bottom-left end on
405 /// even ones.517 /// even ones.
406-fn default_scan_32() -> Vec<u16> {518+fn default_scan(side: usize) -> Vec<u16> {
407- let mut scan = Vec::with_capacity(TX32_AREA);519+ let mut scan = Vec::with_capacity(side * side);
408- for d in 0..(2 * TX32 - 1) {520+ for d in 0..(2 * side - 1) {
409- let lo = d.saturating_sub(TX32 - 1);521+ let lo = d.saturating_sub(side - 1);
410- let hi = d.min(TX32 - 1);522+ let hi = d.min(side - 1);
411- let diagonal = (lo..=hi).map(|row| (row * TX32 + (d - row)) as u16);523+ let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
412 if d % 2 == 0 {524 if d % 2 == 0 {
413 scan.extend(diagonal.rev());525 scan.extend(diagonal.rev());
414 } else {526 } else {
@@ -418,49 +530,54 @@ fn default_scan_32() -> Vec<u16> {
418 scan530 scan
419 }531 }
420 532
421-/// coeffs() for a luma transform block of any coefficients the base and533+/// coeffs() for one plane's transform block of any coefficients the base and
422 /// base-range syntax reach (spec 5.11.39).534 /// base-range syntax reach (spec 5.11.39).
423 ///535 ///
424-/// The block is its own transform size, so the all-zero flag's context is 0;536+/// A 32x32 or 16x16 transform is DCT-only here, so no transform type is coded;
425-/// a 32x32 transform is DCT-only, so no transform type is coded; and the537+/// and the levels the contexts below are read from are the levels of
426-/// levels the contexts below are read from are the levels of coefficients538+/// coefficients later in the scan, which a decoder walking the scan backwards
427-/// later in the scan, which a decoder walking the scan backwards already has.539+/// already has.
428-fn write_coeffs(enc: &mut SymbolEncoder, grid: &[i32], scan: &[u16], sign_ctx: usize) {540+fn write_coeffs(
541+ enc: &mut SymbolEncoder,
542+ coding: &TxbCoding,
543+ grid: &[i32],
544+ scan: &[u16],
545+ skip_ctx: usize,
546+ sign_ctx: usize,
547+) {
548+ let side = coding.side;
429 let eob = scan549 let eob = scan
430 .iter()550 .iter()
431 .rposition(|&pos| grid[pos as usize] != 0)551 .rposition(|&pos| grid[pos as usize] != 0)
432 .map_or(0, |i| i + 1);552 .map_or(0, |i| i + 1);
433- enc.symbol_fixed(usize::from(eob == 0), &cdf::TXB_SKIP_LUMA_32);553+ enc.symbol_fixed(usize::from(eob == 0), &coding.txb_skip[skip_ctx]);
434 if eob == 0 {554 if eob == 0 {
435 return;555 return;
436 }556 }
437 557
438- write_eob(enc, eob);558+ write_eob(enc, coding, eob);
439 559
440 for scan_idx in (0..eob).rev() {560 for scan_idx in (0..eob).rev() {
441 let pos = scan[scan_idx] as usize;561 let pos = scan[scan_idx] as usize;
442- let (row, col) = (pos / TX32, pos % TX32);562+ let (row, col) = (pos / side, pos % side);
443 let level = grid[pos].abs();563 let level = grid[pos].abs();
444 if scan_idx == eob - 1 {564 if scan_idx == eob - 1 {
445- let ctx = eob_coeff_ctx(scan_idx);565+ let ctx = eob_coeff_ctx(scan_idx, side * side);
446 enc.symbol_fixed(566 enc.symbol_fixed(
447 (level.min(NUM_BASE_LEVELS + 1) - 1) as usize,567 (level.min(NUM_BASE_LEVELS + 1) - 1) as usize,
448- &cdf::COEFF_BASE_EOB_LUMA_32[ctx],568+ &coding.base_eob[ctx],
449 );569 );
450 } else {570 } else {
451- let ctx = base_ctx(grid, row, col);571+ let ctx = base_ctx(grid, side, row, col);
452- enc.symbol_fixed(572+ enc.symbol_fixed(level.min(NUM_BASE_LEVELS + 1) as usize, &coding.base[ctx]);
453- level.min(NUM_BASE_LEVELS + 1) as usize,
454- &cdf::COEFF_BASE_LUMA_32[ctx],
455- );
456 }573 }
457 if level > NUM_BASE_LEVELS {574 if level > NUM_BASE_LEVELS {
458- let ctx = br_ctx(grid, row, col);575+ let ctx = br_ctx(grid, side, row, col);
459 let mut remaining = level - (NUM_BASE_LEVELS + 1);576 let mut remaining = level - (NUM_BASE_LEVELS + 1);
460 let mut sent = 0;577 let mut sent = 0;
461 while sent < COEFF_BASE_RANGE {578 while sent < COEFF_BASE_RANGE {
462 let k = remaining.min(BR_STEP);579 let k = remaining.min(BR_STEP);
463- enc.symbol_fixed(k as usize, &cdf::COEFF_BR_LUMA_32[ctx]);580+ enc.symbol_fixed(k as usize, &coding.br[ctx]);
464 if k < BR_STEP {581 if k < BR_STEP {
465 break;582 break;
466 }583 }
@@ -478,7 +595,7 @@ fn write_coeffs(enc: &mut SymbolEncoder, grid: &[i32], scan: &[u16], sign_ctx: u
478 continue;595 continue;
479 }596 }
480 if pos == 0 {597 if pos == 0 {
481- enc.symbol_fixed(usize::from(level < 0), &cdf::DC_SIGN_LUMA[sign_ctx]);598+ enc.symbol_fixed(usize::from(level < 0), &coding.dc_sign[sign_ctx]);
482 } else {599 } else {
483 enc.literal(u32::from(level < 0), 1);600 enc.literal(u32::from(level < 0), 1);
484 }601 }
@@ -488,7 +605,7 @@ fn write_coeffs(enc: &mut SymbolEncoder, grid: &[i32], scan: &[u16], sign_ctx: u
488 /// The end-of-block position (spec 5.11.39): which group of scan positions the605 /// The end-of-block position (spec 5.11.39): which group of scan positions the
489 /// last coded coefficient falls in, then its offset inside that group — the606 /// last coded coefficient falls in, then its offset inside that group — the
490 /// offset's top bit from a CDF and the rest as raw bits.607 /// offset's top bit from a CDF and the rest as raw bits.
491-fn write_eob(enc: &mut SymbolEncoder, eob: usize) {608+fn write_eob(enc: &mut SymbolEncoder, coding: &TxbCoding, eob: usize) {
492 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of609 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
493 /// end-of-block positions covers, indexed by the group's own number.610 /// end-of-block positions covers, indexed by the group's own number.
494 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];611 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
@@ -499,15 +616,15 @@ fn write_eob(enc: &mut SymbolEncoder, eob: usize) {
499 .iter()616 .iter()
500 .rposition(|&start| start <= eob)617 .rposition(|&start| start <= eob)
501 .expect("the first group starts at zero");618 .expect("the first group starts at zero");
502- // A 32x32 transform codes its end-of-block group out of the eleven the619+ // The groups are numbered from one, and how many of them the transform
503- // 1024-coefficient alphabet carries, numbered from one.620+ // reaches is the size of its own end-of-block alphabet.
504- enc.symbol_fixed(group - 1, &cdf::EOB_PT_1024_LUMA);621+ enc.symbol_fixed(group - 1, coding.eob_pt);
505 622
506 let bits = OFFSET_BITS[group];623 let bits = OFFSET_BITS[group];
507 if bits > 0 {624 if bits > 0 {
508 let offset = (eob - GROUP_START[group]) as u32;625 let offset = (eob - GROUP_START[group]) as u32;
509 let top = (offset >> (bits - 1)) & 1;626 let top = (offset >> (bits - 1)) & 1;
510- enc.symbol_fixed(top as usize, &cdf::EOB_EXTRA_LUMA_32[group - 3]);627+ enc.symbol_fixed(top as usize, &coding.eob_extra[group - 3]);
511 if bits > 1 {628 if bits > 1 {
512 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);629 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
513 }630 }
@@ -516,11 +633,11 @@ fn write_eob(enc: &mut SymbolEncoder, eob: usize) {
516 633
517 /// The context of the level of the last coded coefficient (spec 8.3.2): how634 /// The context of the level of the last coded coefficient (spec 8.3.2): how
518 /// far into the scan it sits, in quarters and eighths of the transform.635 /// far into the scan it sits, in quarters and eighths of the transform.
519-fn eob_coeff_ctx(scan_idx: usize) -> usize {636+fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
520 match scan_idx {637 match scan_idx {
521 0 => 0,638 0 => 0,
522- i if i <= TX32_AREA / 8 => 1,639+ i if i <= area / 8 => 1,
523- i if i <= TX32_AREA / 4 => 2,640+ i if i <= area / 4 => 2,
524 _ => 3,641 _ => 3,
525 }642 }
526 }643 }
@@ -529,13 +646,13 @@ fn eob_coeff_ctx(scan_idx: usize) -> usize {
529 /// five neighbours below and to the right of it — the ones a decoder walking646 /// five neighbours below and to the right of it — the ones a decoder walking
530 /// the scan backwards already has — plus a term for where in the transform it647 /// the scan backwards already has — plus a term for where in the transform it
531 /// sits. The DC reads context 0 whatever its neighbours carry.648 /// sits. The DC reads context 0 whatever its neighbours carry.
532-fn base_ctx(grid: &[i32], row: usize, col: usize) -> usize {649+fn base_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
533 if row == 0 && col == 0 {650 if row == 0 && col == 0 {
534 return 0;651 return 0;
535 }652 }
536 let mag: i32 = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]653 let mag: i32 = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
537 .iter()654 .iter()
538- .map(|&(dr, dc)| neighbour(grid, row + dr, col + dc).abs().min(3))655+ .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs().min(3))
539 .sum();656 .sum();
540 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;657 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
541 (((mag + 1) >> 1).min(4) as usize) + offset658 (((mag + 1) >> 1).min(4) as usize) + offset
@@ -544,10 +661,10 @@ fn base_ctx(grid: &[i32], row: usize, col: usize) -> usize {
544 /// The context of a coefficient's base-range tail (spec 8.3.2): the magnitudes661 /// The context of a coefficient's base-range tail (spec 8.3.2): the magnitudes
545 /// of its three closest neighbours below and to the right, uncapped, and a662 /// of its three closest neighbours below and to the right, uncapped, and a
546 /// term separating the DC, the corner of the transform, and the rest.663 /// term separating the DC, the corner of the transform, and the rest.
547-fn br_ctx(grid: &[i32], row: usize, col: usize) -> usize {664+fn br_ctx(grid: &[i32], side: usize, row: usize, col: usize) -> usize {
548 let mag: i32 = [(1, 0), (0, 1), (1, 1)]665 let mag: i32 = [(1, 0), (0, 1), (1, 1)]
549 .iter()666 .iter()
550- .map(|&(dr, dc)| neighbour(grid, row + dr, col + dc).abs())667+ .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
551 .sum();668 .sum();
552 let mag = (((mag + 1) >> 1).min(6)) as usize;669 let mag = (((mag + 1) >> 1).min(6)) as usize;
553 if row == 0 && col == 0 {670 if row == 0 && col == 0 {
@@ -561,11 +678,11 @@ fn br_ctx(grid: &[i32], row: usize, col: usize) -> usize {
561 678
562 /// A level at a position that may fall off the transform, where the levels a679 /// A level at a position that may fall off the transform, where the levels a
563 /// context reads are zero.680 /// context reads are zero.
564-fn neighbour(grid: &[i32], row: usize, col: usize) -> i32 {681+fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
565- if row >= TX32 || col >= TX32 {682+ if row >= side || col >= side {
566 0683 0
567 } else {684 } else {
568- grid[row * TX32 + col]685+ grid[row * side + col]
569 }686 }
570 }687 }
571 688
@@ -1126,6 +1243,26 @@ mod tests {
1126 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and1243 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
1127 /// hands back the luma plane as rows of samples.1244 /// hands back the luma plane as rows of samples.
1128 fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> {1245 fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> {
1246+ let blocks: Vec<BlockCoeffs> = blocks.iter().cloned().map(BlockCoeffs::from).collect();
1247+ let [luma, u, v] = decode_coeff_planes(&blocks);
1248+ for (name, plane) in [("U", &u), ("V", &v)] {
1249+ for (y, row) in plane.iter().enumerate() {
1250+ for (x, &s) in row.iter().enumerate() {
1251+ assert_eq!(
1252+ s, 128,
1253+ "{name} sample ({x},{y}): no block codes a chroma coefficient, and a \
1254+ DC prediction with no coded neighbour is mid-grey"
1255+ );
1256+ }
1257+ }
1258+ }
1259+ luma
1260+ }
1261+
1262+ /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
1263+ /// hands back its three planes as rows of samples: 64 rows of luma and, at
1264+ /// 4:2:0, 32 rows of each chroma plane.
1265+ fn decode_coeff_planes(blocks: &[BlockCoeffs]) -> [Vec<Vec<u8>>; 3] {
1129 let (seq, header) = frame_of(64, 64);1266 let (seq, header) = frame_of(64, 64);
1130 let tile =1267 let tile =
1131 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();1268 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
@@ -1134,14 +1271,12 @@ mod tests {
1134 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());1271 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
1135 let planes = ffmpeg_decode(&stream, 64, 64);1272 let planes = ffmpeg_decode(&stream, 64, 64);
1136 let (luma, chroma) = planes.split_at(64 * 64);1273 let (luma, chroma) = planes.split_at(64 * 64);
1137- for (i, &s) in chroma.iter().enumerate() {1274+ let (u, v) = chroma.split_at(32 * 32);
1138- assert_eq!(1275+ [
1139- s, 128,1276+ luma.chunks_exact(64).map(<[u8]>::to_vec).collect(),
1140- "chroma sample {i}: no block codes a chroma coefficient, and a \1277+ u.chunks_exact(32).map(<[u8]>::to_vec).collect(),
1141- DC prediction with no coded neighbour is mid-grey"1278+ v.chunks_exact(32).map(<[u8]>::to_vec).collect(),
1142- );1279+ ]
1143- }
1144- luma.chunks_exact(64).map(<[u8]>::to_vec).collect()
1145 }1280 }
1146 1281
1147 /// The top-left 32x32 block of a decoded frame, which is the only one whose1282 /// The top-left 32x32 block of a decoded frame, which is the only one whose
@@ -1384,16 +1519,169 @@ mod tests {
1384 }1519 }
1385 }1520 }
1386 1521
1522+ /// The top-left 16x16 block of a decoded chroma plane, which is the only
1523+ /// one whose prediction has no neighbour to lean on.
1524+ fn top_left_chroma(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
1525+ rows[..16].iter().map(|r| r[..16].to_vec()).collect()
1526+ }
1527+
1528+ /// The mean of a decoded block, which every basis function but the DC's
1529+ /// leaves at the block's prediction.
1530+ fn mean(block: &[Vec<u8>]) -> f64 {
1531+ let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
1532+ let count = block.iter().map(Vec::len).sum::<usize>() as f64;
1533+ f64::from(sum) / count
1534+ }
1535+
1536+ /// A chroma plane's coefficients ride their own transform, their own CDFs
1537+ /// and their own end-of-block alphabet, so a chroma basis function is the
1538+ /// gate on all three: U carries the coefficient that is flat down the block
1539+ /// and a half-cycle across it, V the one turned a quarter turn, and neither
1540+ /// may reach the other plane or luma.
1541+ #[test]
1542+ fn each_chroma_plane_codes_its_own_basis_function() {
1543+ if !have_ffmpeg() {
1544+ eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg");
1545+ return;
1546+ }
1547+ let mut blocks = vec![BlockCoeffs::default(); 4];
1548+ blocks[0].u = vec![Coeff {
1549+ row: 0,
1550+ col: 1,
1551+ level: 12,
1552+ }];
1553+ blocks[0].v = vec![Coeff {
1554+ row: 1,
1555+ col: 0,
1556+ level: 12,
1557+ }];
1558+ let [luma, u, v] = decode_coeff_planes(&blocks);
1559+
1560+ for (y, row) in luma.iter().enumerate() {
1561+ for (x, &s) in row.iter().enumerate() {
1562+ assert_eq!(
1563+ s, 128,
1564+ "luma sample ({x},{y}): no block codes a luma coefficient, so the picture \
1565+ stays at its mid-grey prediction"
1566+ );
1567+ }
1568+ }
1569+
1570+ let u_block = top_left_chroma(&u);
1571+ for (y, row) in u_block.iter().enumerate() {
1572+ assert_eq!(
1573+ row, &u_block[0],
1574+ "row {y} of a horizontal chroma basis function"
1575+ );
1576+ }
1577+ assert!(
1578+ u_block[0][0] > u_block[0][15],
1579+ "a positive coefficient leans the U block towards its left edge: {:?}",
1580+ u_block[0]
1581+ );
1582+
1583+ let v_block = top_left_chroma(&v);
1584+ for (x, &top) in v_block[0].iter().enumerate() {
1585+ assert_eq!(
1586+ top, v_block[0][0],
1587+ "column {x} of a vertical chroma basis function"
1588+ );
1589+ let column: Vec<u8> = v_block.iter().map(|r| r[x]).collect();
1590+ assert!(
1591+ column[0] > column[15],
1592+ "a positive coefficient leans the V column towards its top edge: {column:?}"
1593+ );
1594+ }
1595+
1596+ for (name, block) in [("U", &u_block), ("V", &v_block)] {
1597+ let mean = mean(block);
1598+ assert!(
1599+ (mean - 128.0).abs() <= 1.0,
1600+ "the {name} block carries no DC, so it averages to its mid-grey prediction, \
1601+ got {mean}"
1602+ );
1603+ }
1604+ }
1605+
1606+ /// Every block coding chroma puts the chroma all-zero flag on the contexts
1607+ /// a coded neighbour above and to the left select, and the DC sign on the
1608+ /// contexts their signs select. A frame whose four blocks all carry chroma
1609+ /// DCs of mixed sign walks those contexts; the picture that comes back must
1610+ /// still lean the way each block's own DC asks.
1611+ #[test]
1612+ fn chroma_dc_signs_read_their_neighbours() {
1613+ if !have_ffmpeg() {
1614+ eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg");
1615+ return;
1616+ }
1617+ let dc = |level| {
1618+ vec![Coeff {
1619+ row: 0,
1620+ col: 0,
1621+ level,
1622+ }]
1623+ };
1624+ let signs = [8, -8, -8, 8];
1625+ let blocks: Vec<BlockCoeffs> = signs
1626+ .iter()
1627+ .map(|&level| BlockCoeffs {
1628+ luma: Vec::new(),
1629+ u: dc(level),
1630+ v: dc(-level),
1631+ })
1632+ .collect();
1633+ let [luma, u, v] = decode_coeff_planes(&blocks);
1634+
1635+ for (y, row) in luma.iter().enumerate() {
1636+ for (x, &s) in row.iter().enumerate() {
1637+ assert_eq!(s, 128, "luma sample ({x},{y}) with no luma coefficient");
1638+ }
1639+ }
1640+
1641+ // A DC prediction leans on the neighbours a block has, so each block is
1642+ // measured against the prediction it was given rather than mid-grey:
1643+ // the only block with no neighbour is the first, and the rest are read
1644+ // as a step away from the block above them and to their left.
1645+ for (i, &level) in signs.iter().enumerate() {
1646+ let (r, c) = (i / 2, i % 2);
1647+ let block = |plane: &[Vec<u8>]| -> Vec<Vec<u8>> {
1648+ plane[r * 16..r * 16 + 16]
1649+ .iter()
1650+ .map(|row| row[c * 16..c * 16 + 16].to_vec())
1651+ .collect()
1652+ };
1653+ for (name, plane, want) in [("U", &u, level), ("V", &v, -level)] {
1654+ let block = block(plane);
1655+ let mean = mean(&block);
1656+ for (y, row) in block.iter().enumerate() {
1657+ assert_eq!(
1658+ row.iter().collect::<std::collections::HashSet<_>>().len(),
1659+ 1,
1660+ "row {y} of a DC-only {name} block is flat"
1661+ );
1662+ }
1663+ if i == 0 {
1664+ assert!(
1665+ (want > 0) == (mean > 128.0),
1666+ "{name} block {i} carries a DC of {want}, so it must lean off its \
1667+ mid-grey prediction that way, got {mean}"
1668+ );
1669+ }
1670+ }
1671+ }
1672+ assert_ne!(u, v, "the two chroma planes carry opposite DCs");
1673+ }
1674+
1387 /// The coefficient writer refuses what it cannot code rather than writing a1675 /// The coefficient writer refuses what it cannot code rather than writing a
1388 /// stream a decoder walks off the end of.1676 /// stream a decoder walks off the end of.
1389 #[test]1677 #[test]
1390 fn coefficients_the_writer_cannot_code_are_refused() {1678 fn coefficients_the_writer_cannot_code_are_refused() {
1391- let empty = || vec![Vec::new(), Vec::new(), Vec::new(), Vec::new()];1679+ let empty = || vec![BlockCoeffs::default(); 4];
1392- let cases: [(&str, Vec<Vec<Coeff>>); 5] = [1680+ let cases: [(&str, Vec<BlockCoeffs>); 6] = [
1393- ("one list short", vec![Vec::new(), Vec::new(), Vec::new()]),1681+ ("one set short", vec![BlockCoeffs::default(); 3]),
1394 ("off the transform", {1682 ("off the transform", {
1395 let mut b = empty();1683 let mut b = empty();
1396- b[0] = vec![Coeff {1684+ b[0].luma = vec![Coeff {
1397 row: 32,1685 row: 32,
1398 col: 0,1686 col: 0,
1399 level: 1,1687 level: 1,
@@ -1402,7 +1690,7 @@ mod tests {
1402 }),1690 }),
1403 ("a zero level", {1691 ("a zero level", {
1404 let mut b = empty();1692 let mut b = empty();
1405- b[1] = vec![Coeff {1693+ b[1].luma = vec![Coeff {
1406 row: 0,1694 row: 0,
1407 col: 0,1695 col: 0,
1408 level: 0,1696 level: 0,
@@ -1411,7 +1699,7 @@ mod tests {
1411 }),1699 }),
1412 ("a level past the base-range tail", {1700 ("a level past the base-range tail", {
1413 let mut b = empty();1701 let mut b = empty();
1414- b[2] = vec![Coeff {1702+ b[2].luma = vec![Coeff {
1415 row: 0,1703 row: 0,
1416 col: 0,1704 col: 0,
1417 level: 15,1705 level: 15,
@@ -1420,7 +1708,7 @@ mod tests {
1420 }),1708 }),
1421 ("two coefficients at one position", {1709 ("two coefficients at one position", {
1422 let mut b = empty();1710 let mut b = empty();
1423- b[3] = vec![1711+ b[3].luma = vec![
1424 Coeff {1712 Coeff {
1425 row: 4,1713 row: 4,
1426 col: 4,1714 col: 4,
@@ -1434,6 +1722,15 @@ mod tests {
1434 ];1722 ];
1435 b1723 b
1436 }),1724 }),
1725+ ("off the chroma transform", {
1726+ let mut b = empty();
1727+ b[0].u = vec![Coeff {
1728+ row: 0,
1729+ col: 16,
1730+ level: 1,
1731+ }];
1732+ b
1733+ }),
1437 ];1734 ];
1438 for (name, blocks) in cases {1735 for (name, blocks) in cases {
1439 assert!(1736 assert!(
@@ -1454,28 +1751,33 @@ mod tests {
1454 /// a coefficient's context off the coefficients it has already decoded.1751 /// a coefficient's context off the coefficients it has already decoded.
1455 #[test]1752 #[test]
1456 fn the_default_scan_walks_every_position_outwards() {1753 fn the_default_scan_walks_every_position_outwards() {
1457- let scan = default_scan_32();1754+ for side in [TX16, TX32] {
1458- assert_eq!(scan.len(), TX32_AREA);1755+ let area = side * side;
1459- let mut seen = vec![false; TX32_AREA];1756+ let scan = default_scan(side);
1757+ assert_eq!(scan.len(), area);
1758+ let mut seen = vec![false; area];
1460 for &pos in &scan {1759 for &pos in &scan {
1461- assert!(!seen[pos as usize], "position {pos} is scanned twice");1760+ assert!(
1761+ !seen[pos as usize],
1762+ "position {pos} is scanned twice in {side}x{side}"
1763+ );
1462 seen[pos as usize] = true;1764 seen[pos as usize] = true;
1463 }1765 }
1464 assert_eq!(scan[0], 0, "the scan starts at the DC");1766 assert_eq!(scan[0], 0, "the scan starts at the DC");
1465 1767
1466- let mut order = vec![0usize; TX32_AREA];1768+ let mut order = vec![0usize; area];
1467 for (i, &pos) in scan.iter().enumerate() {1769 for (i, &pos) in scan.iter().enumerate() {
1468 order[pos as usize] = i;1770 order[pos as usize] = i;
1469 }1771 }
1470- for row in 0..TX32 {1772+ for row in 0..side {
1471- for col in 0..TX32 {1773+ for col in 0..side {
1472 for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {1774 for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
1473 let (nr, nc) = (row + dr, col + dc);1775 let (nr, nc) = (row + dr, col + dc);
1474- if nr < TX32 && nc < TX32 {1776+ if nr < side && nc < side {
1475 assert!(1777 assert!(
1476- order[nr * TX32 + nc] > order[row * TX32 + col],1778+ order[nr * side + nc] > order[row * side + col],
1477- "({nr},{nc}) is a context neighbour of ({row},{col}), so it must be \1779+ "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \
1478- scanned after it"1780+ be scanned after it"
1479 );1781 );
1480 }1782 }
1481 }1783 }
@@ -1483,3 +1785,4 @@ mod tests {
1483 }1785 }
1484 }1786 }
1485 }1787 }
1788+}