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] = [
259259 /// luma transform block that covers its whole plane block, which is context 0.
260260 pub const TXB_SKIP_LUMA_32: [u16; 3] = [30669, 32768, 0];
261261
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-
267262 /// `Default_Coeff_Base_Cdf[2][3][0]` (spec 9.4): the level of a coefficient
268263 /// of a 32x32 luma transform block, capped at three, for each of the
269264 /// 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] = [
371366 [6, 21, 21, 21, 21],
372367 [21, 21, 21, 21, 21],
373368 ];
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+432 -129
@@ -246,8 +246,8 @@ pub fn split_dc_key_frame_tile(
246246 &cdf::TXB_SKIP_LUMA_32,
247247 &cdf::COEFF_BASE_EOB_LUMA_32[0],
248248 );
249- enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16);
250- 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[0]);
251251
252252 above[c as usize] = Some(negative);
253253 left[r as usize] = Some(negative);
@@ -257,43 +257,128 @@ pub fn split_dc_key_frame_tile(
257257 Ok(enc.finish())
258258 }
259259
260-/// One quantised coefficient of a 32x32 luma transform block.
260+/// One quantised coefficient of a transform block.
261261 ///
262-/// `row` and `col` are its position in the transform, not in the picture: a
263-/// coefficient at row 0 varies along the picture's width and one at column 0
264-/// along its height, and the coefficient at the origin is the DC the block's
265-/// average sample value rides on.
262+/// `row` and `col` are its position in the transform it belongs to — 32x32 for
263+/// luma, 16x16 for each chroma plane — not in the picture: a coefficient at
264+/// row 0 varies along the picture's width and one at column 0 along its
265+/// height, and the coefficient at the origin is the DC the block's average
266+/// sample value rides on.
266267 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
267268 pub struct Coeff {
268- /// The coefficient's row in the transform, 0..32.
269+ /// The coefficient's row in the transform.
269270 pub row: u8,
270- /// The coefficient's column in the transform, 0..32.
271+ /// The coefficient's column in the transform.
271272 pub col: u8,
272273 /// Its quantised level, which the base and base-range syntax carry for
273274 /// magnitudes up to [`MAX_LEVEL`].
274275 pub level: i32,
275276 }
276277
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+
277300 /// Side of the luma transform the coefficient writer codes.
278301 const TX32: usize = 32;
279-/// How many coefficients that transform holds.
280-const TX32_AREA: usize = TX32 * TX32;
302+/// Side of the chroma transform beside it at 4:2:0.
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+}
281365
282366 /// 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 luma
284-/// coefficients `blocks` gives it and no chroma residual.
367+/// split into four 32x32 DC-predicted blocks, each carrying the coefficients
368+/// `blocks` gives it.
285369 ///
286-/// `blocks` gives one coefficient list per 32x32 block in raster order across
287-/// the frame, so it is twice as wide and twice as tall as the superblock grid.
288-/// An empty list writes an all-zero transform block. Unlike the DC writers,
289-/// the coefficients may sit anywhere in the transform, so a block here is a
290-/// picture rather than a flat grey: a single coefficient off the origin
291-/// decodes to the basis function it selects.
370+/// `blocks` gives one coefficient set per 32x32 block in raster order across
371+/// the frame, so the grid is twice as wide and twice as tall as the superblock
372+/// grid. Each set carries a 32x32 luma transform and the 16x16 transform of
373+/// each chroma plane; an empty list writes an all-zero transform block. Unlike
374+/// the DC writers, the coefficients may sit anywhere in their transform, so a
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.
292377 ///
293378 /// # Errors
294379 /// 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,
296-/// when a coefficient sits outside the transform, repeats a position, carries
380+/// superblocks, when `blocks` does not carry exactly one set per 32x32 block,
381+/// when a coefficient sits outside its transform, repeats a position, carries
297382 /// a zero level or one wider than the base and base-range syntax reach, or
298383 /// when `base_q_idx` is outside the q-context band whose default CDFs this
299384 /// crate carries.
@@ -301,7 +386,7 @@ pub fn split_coeff_key_frame_tile(
301386 mi_cols: u32,
302387 mi_rows: u32,
303388 base_q_idx: u8,
304- blocks: &[Vec<Coeff>],
389+ blocks: &[BlockCoeffs],
305390 ) -> Result<Vec<u8>> {
306391 check_superblocks(mi_cols, mi_rows)?;
307392 let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
@@ -309,7 +394,7 @@ pub fn split_coeff_key_frame_tile(
309394 if blocks.len() != (cols * rows) as usize {
310395 return Err(Error::unsupported(
311396 "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",
313398 ));
314399 }
315400 if !Q_CTX_2.contains(&base_q_idx) {
@@ -319,62 +404,89 @@ pub fn split_coeff_key_frame_tile(
319404 base_q_idx must be 61..=120",
320405 ));
321406 }
407+ // One level grid per plane of every block, in the plane order they are
408+ // coded in: luma, then U, then V.
322409 let grids = blocks
323410 .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+ })
325418 .collect::<Result<Vec<_>>>()?;
326419
327- let scan = default_scan_32();
328- // The sign of each coded block's DC, for the neighbours the DC sign
329- // context is read from. A block whose DC is zero casts no vote, however
330- // much its other coefficients carry.
331- let mut above: Vec<Option<bool>> = vec![None; cols as usize];
332- let mut left: Vec<Option<bool>> = vec![None; rows as usize];
420+ let planes = [&LUMA_32, &CHROMA_16, &CHROMA_16];
421+ let scans = [default_scan(TX32), default_scan(TX16)];
422+ // What the blocks above and to the left of the one being coded left
423+ // behind, per plane. The left column is reset at every superblock row
424+ // because a tile starts each row with no left neighbour.
425+ let mut above = vec![[Neighbour::default(); 3]; cols as usize];
426+ let mut left = vec![[Neighbour::default(); 3]; rows as usize];
333427
334428 let mut enc = SymbolEncoder::new();
335429 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());
337431 for sb_c in 0..sb_cols {
338432 let ctx = 2 * usize::from(sb_c > 0) + usize::from(sb_r > 0);
339433 enc.symbol_fixed(PARTITION_SPLIT, &cdf::PARTITION_W64[ctx]);
340434
341435 for quadrant in 0..4 {
342436 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];
344439
345440 enc.symbol_fixed(PARTITION_NONE, &cdf::PARTITION_W32[0]);
346441 enc.symbol_fixed(0, &cdf::SKIP[0]);
347442 enc.symbol_fixed(DC_PRED, &cdf::KF_Y_MODE[0][0]);
348443 enc.symbol_fixed(DC_PRED, &cdf::UV_MODE_CFL_DC);
349444
350- write_coeffs(
351- &mut enc,
352- grid,
353- &scan,
354- dc_sign_ctx(above[c as usize], left[r as usize]),
355- );
356- enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16);
357- enc.symbol_fixed(1, &cdf::TXB_SKIP_CHROMA_16);
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+ };
456+ write_coeffs(
457+ &mut enc,
458+ coding,
459+ grid,
460+ &scans[usize::from(plane > 0)],
461+ skip_ctx,
462+ dc_sign_ctx(above[c][plane].dc, left[r][plane].dc),
463+ );
464+ }
358465
359- let dc = grid[0];
360- let vote = (dc != 0).then_some(dc < 0);
361- above[c as usize] = vote;
362- left[r as usize] = vote;
466+ for plane in 0..3 {
467+ let grid = &block[plane];
468+ let state = Neighbour {
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+ }
363475 }
364476 }
365477 }
366478 Ok(enc.finish())
367479 }
368480
369-/// Lays one block's coefficient list out over the transform, rejecting the
481+/// Lays one plane's coefficient list out over its transform, rejecting the
370482 /// positions and levels the writer does not code.
371-fn level_grid(coeffs: &[Coeff]) -> Result<Vec<i32>> {
372- let mut grid = vec![0i32; TX32_AREA];
483+fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> {
484+ let mut grid = vec![0i32; side * side];
373485 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 {
375487 return Err(Error::unsupported(
376488 "AV1 tile",
377- "a coefficient sits outside the 32x32 transform the writer codes",
489+ "a coefficient sits outside the transform of its plane",
378490 ));
379491 }
380492 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {
@@ -384,7 +496,7 @@ fn level_grid(coeffs: &[Coeff]) -> Result<Vec<i32>> {
384496 wider levels need the Golomb tail",
385497 ));
386498 }
387- let pos = usize::from(coeff.row) * TX32 + usize::from(coeff.col);
499+ let pos = usize::from(coeff.row) * side + usize::from(coeff.col);
388500 if grid[pos] != 0 {
389501 return Err(Error::unsupported(
390502 "AV1 tile",
@@ -396,19 +508,19 @@ fn level_grid(coeffs: &[Coeff]) -> Result<Vec<i32>> {
396508 Ok(grid)
397509 }
398510
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`),
400512 /// as raster positions in the order they are coded.
401513 ///
402-/// The table is a rule rather than a thousand pinned numbers: the scan walks
514+/// The table is a rule rather than hundreds of pinned numbers: the scan walks
403515 /// the anti-diagonals of the transform outwards from the origin, each diagonal
404516 /// from its top-right end on odd diagonals and from its bottom-left end on
405517 /// even ones.
406-fn default_scan_32() -> Vec<u16> {
407- let mut scan = Vec::with_capacity(TX32_AREA);
408- for d in 0..(2 * TX32 - 1) {
409- let lo = d.saturating_sub(TX32 - 1);
410- let hi = d.min(TX32 - 1);
411- let diagonal = (lo..=hi).map(|row| (row * TX32 + (d - row)) as u16);
518+fn default_scan(side: usize) -> Vec<u16> {
519+ let mut scan = Vec::with_capacity(side * side);
520+ for d in 0..(2 * side - 1) {
521+ let lo = d.saturating_sub(side - 1);
522+ let hi = d.min(side - 1);
523+ let diagonal = (lo..=hi).map(|row| (row * side + (d - row)) as u16);
412524 if d % 2 == 0 {
413525 scan.extend(diagonal.rev());
414526 } else {
@@ -418,49 +530,54 @@ fn default_scan_32() -> Vec<u16> {
418530 scan
419531 }
420532
421-/// coeffs() for a luma transform block of any coefficients the base and
533+/// coeffs() for one plane's transform block of any coefficients the base and
422534 /// base-range syntax reach (spec 5.11.39).
423535 ///
424-/// The block is its own transform size, so the all-zero flag's context is 0;
425-/// a 32x32 transform is DCT-only, so no transform type is coded; and the
426-/// levels the contexts below are read from are the levels of coefficients
427-/// later in the scan, which a decoder walking the scan backwards already has.
428-fn write_coeffs(enc: &mut SymbolEncoder, grid: &[i32], scan: &[u16], sign_ctx: usize) {
536+/// A 32x32 or 16x16 transform is DCT-only here, so no transform type is coded;
537+/// and the levels the contexts below are read from are the levels of
538+/// coefficients later in the scan, which a decoder walking the scan backwards
539+/// already has.
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;
429549 let eob = scan
430550 .iter()
431551 .rposition(|&pos| grid[pos as usize] != 0)
432552 .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]);
434554 if eob == 0 {
435555 return;
436556 }
437557
438- write_eob(enc, eob);
558+ write_eob(enc, coding, eob);
439559
440560 for scan_idx in (0..eob).rev() {
441561 let pos = scan[scan_idx] as usize;
442- let (row, col) = (pos / TX32, pos % TX32);
562+ let (row, col) = (pos / side, pos % side);
443563 let level = grid[pos].abs();
444564 if scan_idx == eob - 1 {
445- let ctx = eob_coeff_ctx(scan_idx);
565+ let ctx = eob_coeff_ctx(scan_idx, side * side);
446566 enc.symbol_fixed(
447567 (level.min(NUM_BASE_LEVELS + 1) - 1) as usize,
448- &cdf::COEFF_BASE_EOB_LUMA_32[ctx],
568+ &coding.base_eob[ctx],
449569 );
450570 } else {
451- let ctx = base_ctx(grid, row, col);
452- enc.symbol_fixed(
453- level.min(NUM_BASE_LEVELS + 1) as usize,
454- &cdf::COEFF_BASE_LUMA_32[ctx],
455- );
571+ let ctx = base_ctx(grid, side, row, col);
572+ enc.symbol_fixed(level.min(NUM_BASE_LEVELS + 1) as usize, &coding.base[ctx]);
456573 }
457574 if level > NUM_BASE_LEVELS {
458- let ctx = br_ctx(grid, row, col);
575+ let ctx = br_ctx(grid, side, row, col);
459576 let mut remaining = level - (NUM_BASE_LEVELS + 1);
460577 let mut sent = 0;
461578 while sent < COEFF_BASE_RANGE {
462579 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]);
464581 if k < BR_STEP {
465582 break;
466583 }
@@ -478,7 +595,7 @@ fn write_coeffs(enc: &mut SymbolEncoder, grid: &[i32], scan: &[u16], sign_ctx: u
478595 continue;
479596 }
480597 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]);
482599 } else {
483600 enc.literal(u32::from(level < 0), 1);
484601 }
@@ -488,7 +605,7 @@ fn write_coeffs(enc: &mut SymbolEncoder, grid: &[i32], scan: &[u16], sign_ctx: u
488605 /// The end-of-block position (spec 5.11.39): which group of scan positions the
489606 /// last coded coefficient falls in, then its offset inside that group — the
490607 /// 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) {
492609 /// `Eob_Group_Start` (spec 5.11.39): the first scan position each group of
493610 /// end-of-block positions covers, indexed by the group's own number.
494611 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) {
499616 .iter()
500617 .rposition(|&start| start <= eob)
501618 .expect("the first group starts at zero");
502- // A 32x32 transform codes its end-of-block group out of the eleven the
503- // 1024-coefficient alphabet carries, numbered from one.
504- enc.symbol_fixed(group - 1, &cdf::EOB_PT_1024_LUMA);
619+ // The groups are numbered from one, and how many of them the transform
620+ // reaches is the size of its own end-of-block alphabet.
621+ enc.symbol_fixed(group - 1, coding.eob_pt);
505622
506623 let bits = OFFSET_BITS[group];
507624 if bits > 0 {
508625 let offset = (eob - GROUP_START[group]) as u32;
509626 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]);
511628 if bits > 1 {
512629 enc.literal(offset & ((1 << (bits - 1)) - 1), bits - 1);
513630 }
@@ -516,11 +633,11 @@ fn write_eob(enc: &mut SymbolEncoder, eob: usize) {
516633
517634 /// The context of the level of the last coded coefficient (spec 8.3.2): how
518635 /// 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 {
520637 match scan_idx {
521638 0 => 0,
522- i if i <= TX32_AREA / 8 => 1,
523- i if i <= TX32_AREA / 4 => 2,
639+ i if i <= area / 8 => 1,
640+ i if i <= area / 4 => 2,
524641 _ => 3,
525642 }
526643 }
@@ -529,13 +646,13 @@ fn eob_coeff_ctx(scan_idx: usize) -> usize {
529646 /// five neighbours below and to the right of it — the ones a decoder walking
530647 /// the scan backwards already has — plus a term for where in the transform it
531648 /// 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 {
533650 if row == 0 && col == 0 {
534651 return 0;
535652 }
536653 let mag: i32 = [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)]
537654 .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))
539656 .sum();
540657 let offset = cdf::NZ_MAP_CTX_OFFSET_32[row.min(4)][col.min(4)] as usize;
541658 (((mag + 1) >> 1).min(4) as usize) + offset
@@ -544,10 +661,10 @@ fn base_ctx(grid: &[i32], row: usize, col: usize) -> usize {
544661 /// The context of a coefficient's base-range tail (spec 8.3.2): the magnitudes
545662 /// of its three closest neighbours below and to the right, uncapped, and a
546663 /// 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 {
548665 let mag: i32 = [(1, 0), (0, 1), (1, 1)]
549666 .iter()
550- .map(|&(dr, dc)| neighbour(grid, row + dr, col + dc).abs())
667+ .map(|&(dr, dc)| neighbour(grid, side, row + dr, col + dc).abs())
551668 .sum();
552669 let mag = (((mag + 1) >> 1).min(6)) as usize;
553670 if row == 0 && col == 0 {
@@ -561,11 +678,11 @@ fn br_ctx(grid: &[i32], row: usize, col: usize) -> usize {
561678
562679 /// A level at a position that may fall off the transform, where the levels a
563680 /// context reads are zero.
564-fn neighbour(grid: &[i32], row: usize, col: usize) -> i32 {
565- if row >= TX32 || col >= TX32 {
681+fn neighbour(grid: &[i32], side: usize, row: usize, col: usize) -> i32 {
682+ if row >= side || col >= side {
566683 0
567684 } else {
568- grid[row * TX32 + col]
685+ grid[row * side + col]
569686 }
570687 }
571688
@@ -1126,6 +1243,26 @@ mod tests {
11261243 /// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
11271244 /// hands back the luma plane as rows of samples.
11281245 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] {
11291266 let (seq, header) = frame_of(64, 64);
11301267 let tile =
11311268 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
@@ -1134,14 +1271,12 @@ mod tests {
11341271 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
11351272 let planes = ffmpeg_decode(&stream, 64, 64);
11361273 let (luma, chroma) = planes.split_at(64 * 64);
1137- for (i, &s) in chroma.iter().enumerate() {
1138- assert_eq!(
1139- s, 128,
1140- "chroma sample {i}: no block codes a chroma coefficient, and a \
1141- DC prediction with no coded neighbour is mid-grey"
1142- );
1143- }
1144- luma.chunks_exact(64).map(<[u8]>::to_vec).collect()
1274+ let (u, v) = chroma.split_at(32 * 32);
1275+ [
1276+ luma.chunks_exact(64).map(<[u8]>::to_vec).collect(),
1277+ u.chunks_exact(32).map(<[u8]>::to_vec).collect(),
1278+ v.chunks_exact(32).map(<[u8]>::to_vec).collect(),
1279+ ]
11451280 }
11461281
11471282 /// The top-left 32x32 block of a decoded frame, which is the only one whose
@@ -1384,16 +1519,169 @@ mod tests {
13841519 }
13851520 }
13861521
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+
13871675 /// The coefficient writer refuses what it cannot code rather than writing a
13881676 /// stream a decoder walks off the end of.
13891677 #[test]
13901678 fn coefficients_the_writer_cannot_code_are_refused() {
1391- let empty = || vec![Vec::new(), Vec::new(), Vec::new(), Vec::new()];
1392- let cases: [(&str, Vec<Vec<Coeff>>); 5] = [
1393- ("one list short", vec![Vec::new(), Vec::new(), Vec::new()]),
1679+ let empty = || vec![BlockCoeffs::default(); 4];
1680+ let cases: [(&str, Vec<BlockCoeffs>); 6] = [
1681+ ("one set short", vec![BlockCoeffs::default(); 3]),
13941682 ("off the transform", {
13951683 let mut b = empty();
1396- b[0] = vec![Coeff {
1684+ b[0].luma = vec![Coeff {
13971685 row: 32,
13981686 col: 0,
13991687 level: 1,
@@ -1402,7 +1690,7 @@ mod tests {
14021690 }),
14031691 ("a zero level", {
14041692 let mut b = empty();
1405- b[1] = vec![Coeff {
1693+ b[1].luma = vec![Coeff {
14061694 row: 0,
14071695 col: 0,
14081696 level: 0,
@@ -1411,7 +1699,7 @@ mod tests {
14111699 }),
14121700 ("a level past the base-range tail", {
14131701 let mut b = empty();
1414- b[2] = vec![Coeff {
1702+ b[2].luma = vec![Coeff {
14151703 row: 0,
14161704 col: 0,
14171705 level: 15,
@@ -1420,7 +1708,7 @@ mod tests {
14201708 }),
14211709 ("two coefficients at one position", {
14221710 let mut b = empty();
1423- b[3] = vec![
1711+ b[3].luma = vec![
14241712 Coeff {
14251713 row: 4,
14261714 col: 4,
@@ -1434,6 +1722,15 @@ mod tests {
14341722 ];
14351723 b
14361724 }),
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+ }),
14371734 ];
14381735 for (name, blocks) in cases {
14391736 assert!(
@@ -1454,29 +1751,35 @@ mod tests {
14541751 /// a coefficient's context off the coefficients it has already decoded.
14551752 #[test]
14561753 fn the_default_scan_walks_every_position_outwards() {
1457- let scan = default_scan_32();
1458- assert_eq!(scan.len(), TX32_AREA);
1459- let mut seen = vec![false; TX32_AREA];
1460- for &pos in &scan {
1461- assert!(!seen[pos as usize], "position {pos} is scanned twice");
1462- seen[pos as usize] = true;
1463- }
1464- assert_eq!(scan[0], 0, "the scan starts at the DC");
1754+ for side in [TX16, TX32] {
1755+ let area = side * side;
1756+ let scan = default_scan(side);
1757+ assert_eq!(scan.len(), area);
1758+ let mut seen = vec![false; area];
1759+ for &pos in &scan {
1760+ assert!(
1761+ !seen[pos as usize],
1762+ "position {pos} is scanned twice in {side}x{side}"
1763+ );
1764+ seen[pos as usize] = true;
1765+ }
1766+ assert_eq!(scan[0], 0, "the scan starts at the DC");
14651767
1466- let mut order = vec![0usize; TX32_AREA];
1467- for (i, &pos) in scan.iter().enumerate() {
1468- order[pos as usize] = i;
1469- }
1470- for row in 0..TX32 {
1471- for col in 0..TX32 {
1472- for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
1473- let (nr, nc) = (row + dr, col + dc);
1474- if nr < TX32 && nc < TX32 {
1475- assert!(
1476- order[nr * TX32 + nc] > order[row * TX32 + col],
1477- "({nr},{nc}) is a context neighbour of ({row},{col}), so it must be \
1478- scanned after it"
1479- );
1768+ let mut order = vec![0usize; area];
1769+ for (i, &pos) in scan.iter().enumerate() {
1770+ order[pos as usize] = i;
1771+ }
1772+ for row in 0..side {
1773+ for col in 0..side {
1774+ for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
1775+ let (nr, nc) = (row + dr, col + dc);
1776+ if nr < side && nc < side {
1777+ assert!(
1778+ order[nr * side + nc] > order[row * side + col],
1779+ "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \
1780+ be scanned after it"
1781+ );
1782+ }
14801783 }
14811784 }
14821785 }