forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

tests.rs2557 lines, 90.4 KiBHistoryRawDownload
1use super::*;
2use crate::frame::frame_obu;
3use crate::obu::temporal_delimiter;
4use crate::probe::run_with_stdin;
5use crate::sequence::sequence_header_obu;
6use ec_av1_syntax::sequence::SequenceHeader;
7use ec_av1_syntax::{
8 FrameHeader, FrameType, LoopFilterParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
9 TxMode,
10};
11use std::process::{Command, Stdio};
12
13/// A 64x64 sequence with every tool this writer does not code turned off:
14/// 64x64 superblocks, no CDEF, no loop restoration, no superres, no filter
15/// intra, and no screen content tools (which is what keeps intra block copy
16/// and palette out of the block syntax).
17fn sequence_64() -> SequenceHeader {
18 let mut seq = crate::sequence::tests::sample_1080p();
19 seq.frame_width_bits = 7;
20 seq.frame_height_bits = 7;
21 seq.max_frame_width = 64;
22 seq.max_frame_height = 64;
23 seq.use_128x128_superblock = false;
24 seq.enable_filter_intra = false;
25 seq.enable_cdef = false;
26 seq.enable_restoration = false;
27 seq.enable_superres = false;
28 seq.seq_force_screen_content_tools = 0;
29 seq.seq_force_integer_mv = 0;
30 seq
31}
32
33/// The key frame the tile above belongs to: one tile, quantised so nothing
34/// is lossless, one transform size per block, no in-loop filtering, and no
35/// CDF adaptation (the writer codes against the defaults).
36fn flat_key_frame() -> FrameHeader {
37 FrameHeader {
38 frame_type: FrameType::Key,
39 frame_is_intra: true,
40 show_frame: true,
41 error_resilient_mode: true,
42 disable_cdf_update: true,
43 allow_screen_content_tools: false,
44 force_integer_mv: true,
45 refresh_frame_flags: 0xFF,
46 primary_ref_frame: PRIMARY_REF_NONE,
47 frame_width: 64,
48 frame_height: 64,
49 upscaled_width: 64,
50 render_width: 64,
51 render_height: 64,
52 mi_cols: 16,
53 mi_rows: 16,
54 tile_info: TileInfo {
55 uniform_spacing: true,
56 cols: 1,
57 rows: 1,
58 cols_log2: 0,
59 rows_log2: 0,
60 mi_col_starts: vec![0, 16],
61 mi_row_starts: vec![0, 16],
62 context_update_tile_id: 0,
63 tile_size_bytes: 1,
64 },
65 quantization: QuantizationParams {
66 base_q_idx: 100,
67 ..QuantizationParams::default()
68 },
69 loop_filter: LoopFilterParams::default(),
70 tx_mode: TxMode::Largest,
71 reduced_tx_set: false,
72 ..FrameHeader::default()
73 }
74}
75
76/// Whether ffmpeg is on PATH. Absence normally SKIPs, but
77/// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
78/// aomenc gate decodes its stream through ffmpeg and is meaningless
79/// without it -- turns it into a hard failure. Without this the require
80/// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
81/// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
82/// printed SKIP and reported green (class gate-skips-on-its-own-failure).
83fn have_ffmpeg() -> bool {
84 let present = Command::new("ffmpeg")
85 .arg("-version")
86 .stdout(Stdio::null())
87 .stderr(Stdio::null())
88 .status()
89 .is_ok_and(|s| s.success());
90 assert!(
91 present
92 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
93 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
94 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
95 );
96 present
97}
98
99/// Decodes an AV1 OBU stream with ffmpeg and hands back the planes.
100fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Vec<u8> {
101 let out = run_with_stdin(
102 Command::new("ffmpeg").args([
103 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
104 ]),
105 stream,
106 );
107 assert!(
108 out.status.success(),
109 "ffmpeg refused the stream: {}",
110 String::from_utf8_lossy(&out.stderr)
111 );
112 assert_eq!(
113 out.stdout.len(),
114 w * h * 3 / 2,
115 "expected one 4:2:0 frame, ffmpeg said: {}",
116 String::from_utf8_lossy(&out.stderr)
117 );
118 out.stdout
119}
120
121#[test]
122fn flat_key_frame_decodes_to_mid_grey() {
123 if !have_ffmpeg() {
124 eprintln!("SKIP flat_key_frame_decodes_to_mid_grey: no ffmpeg on PATH");
125 return;
126 }
127 let seq = sequence_64();
128 let header = flat_key_frame();
129 let tile = flat_key_frame_tile(header.mi_cols, header.mi_rows).unwrap();
130
131 let mut stream = temporal_delimiter();
132 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
133 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
134
135 let planes = ffmpeg_decode(&stream, 64, 64);
136 // A DC prediction with no neighbour to average is the middle of the
137 // range, and a skipped block adds no residual, so every sample of every
138 // plane is 128 — one wrong symbol anywhere in the tile shows up here.
139 for (i, &s) in planes.iter().enumerate() {
140 assert_eq!(s, 128, "sample {i} of the decoded frame");
141 }
142}
143
144/// The one q-context whose CDFs this crate carries; the decoded table
145/// below is pinned at this quantiser and nowhere else.
146const Q_IDX: u8 = 100;
147
148/// Encode a 64x64 key frame carrying `dc_level` and hand back its planes.
149fn decode_dc_frame(dc_level: i32) -> Vec<u8> {
150 let seq = sequence_64();
151 let mut header = flat_key_frame();
152 header.quantization.base_q_idx = Q_IDX;
153 let tile = dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, dc_level).unwrap();
154 let mut stream = temporal_delimiter();
155 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
156 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
157 ffmpeg_decode(&stream, 64, 64)
158}
159
160/// What a reference decoder makes of each DC level at `base_q_idx` 100:
161/// the level times the DC quantiser, inverse-transformed over a whole
162/// 64x64 block — which spreads one coefficient over 4096 samples, so a
163/// level moves the picture by a sample or two, not by tens. These numbers
164/// are pinned from the decoder rather than derived: this crate has no
165/// inverse transform of its own yet to derive them with. What the test
166/// asserts around them — flat planes, untouched chroma, monotone in the
167/// level, and the sign going the right way — is derived, and it is what a
168/// desync in the coefficient syntax breaks first.
169const DECODED_AT_Q100: [(i32, u8); 28] = [
170 (1, 128),
171 (2, 128),
172 (3, 129),
173 (4, 129),
174 (5, 129),
175 (6, 129),
176 (7, 129),
177 (8, 129),
178 (9, 130),
179 (10, 130),
180 (11, 130),
181 (12, 130),
182 (13, 130),
183 (14, 131),
184 (-1, 128),
185 (-2, 128),
186 (-3, 128),
187 (-4, 127),
188 (-5, 127),
189 (-6, 127),
190 (-7, 127),
191 (-8, 127),
192 (-9, 126),
193 (-10, 126),
194 (-11, 126),
195 (-12, 126),
196 (-13, 126),
197 (-14, 126),
198];
199
200#[test]
201fn a_dc_coefficient_moves_the_whole_block_off_mid_grey() {
202 if !have_ffmpeg() {
203 eprintln!("SKIP a_dc_coefficient_moves_the_whole_block_off_mid_grey: no ffmpeg");
204 return;
205 }
206 let mut seen = Vec::new();
207 for (level, want) in DECODED_AT_Q100 {
208 let planes = decode_dc_frame(level);
209 let (luma, chroma) = planes.split_at(64 * 64);
210 for (i, &sample) in luma.iter().enumerate() {
211 assert_eq!(sample, want, "luma sample {i} at dc level {level}");
212 }
213 // The chroma transform blocks are all-zero, so both planes stay at
214 // the prediction. A desync in the luma coefficient syntax lands
215 // here first: the chroma flags are the next symbols after it.
216 for (i, &sample) in chroma.iter().enumerate() {
217 assert_eq!(sample, 128, "chroma sample {i} at dc level {level}");
218 }
219 seen.push((level, want));
220 }
221 // The picture moves off mid-grey the way the level says: up for a
222 // positive level, down for a negative one, and never back towards it
223 // as the level grows.
224 for w in seen.windows(2) {
225 let ((prev_level, prev), (level, value)) = (w[0], w[1]);
226 if prev_level.signum() != level.signum() {
227 continue;
228 }
229 if level > 0 {
230 assert!(
231 value >= prev,
232 "level {level} decoded below level {prev_level}"
233 );
234 assert!(value >= 128, "a positive level darkened the picture");
235 } else {
236 assert!(
237 value <= prev,
238 "level {level} decoded above level {prev_level}"
239 );
240 assert!(value <= 128, "a negative level brightened the picture");
241 }
242 }
243 assert!(
244 DECODED_AT_Q100.iter().any(|&(_, v)| v > 128)
245 && DECODED_AT_Q100.iter().any(|&(_, v)| v < 128),
246 "the pinned table has to move the picture both ways"
247 );
248}
249
250/// Encode a grid of 64x64 superblocks, each carrying its own DC level, and
251/// hand back the decoded planes.
252fn decode_level_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
253 let (w, h) = (64 * sb_cols, 64 * sb_rows);
254 let (seq, mut header) = frame_of(w, h);
255 // The DC fixture writers code against the default CDFs and never
256 // update them, so their frames say so.
257 header.disable_cdf_update = true;
258 let tile = dc_key_frame_tile_levels(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
259 let mut stream = temporal_delimiter();
260 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
261 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
262 ffmpeg_decode(&stream, w as usize, h as usize)
263}
264
265/// A sequence and key frame header for a `w` by `h` frame of whole
266/// superblocks.
267fn frame_of(w: u32, h: u32) -> (SequenceHeader, FrameHeader) {
268 let mut seq = sequence_64();
269 seq.max_frame_width = w;
270 seq.max_frame_height = h;
271 let mut header = flat_key_frame();
272 // Every tile these headers carry is written by the adapting writer.
273 header.disable_cdf_update = false;
274 header.frame_width = w;
275 header.frame_height = h;
276 header.upscaled_width = w;
277 header.render_width = w;
278 header.render_height = h;
279 header.mi_cols = w / 4;
280 header.mi_rows = h / 4;
281 header.tile_info.mi_col_starts = vec![0, header.mi_cols];
282 header.tile_info.mi_row_starts = vec![0, header.mi_rows];
283 header.quantization.base_q_idx = Q_IDX;
284 (seq, header)
285}
286
287fn decoded_value(level: i32) -> u8 {
288 DECODED_AT_Q100
289 .iter()
290 .find(|&&(l, _)| l == level)
291 .map(|&(_, v)| v)
292 .expect("the level is in the pinned table")
293}
294
295/// `dc_predict` (spec 7.11.2) for the flat case: a block whose neighbours
296/// are themselves flat predicts their average, and predicts mid-grey with
297/// no neighbour at all. Every block here is a whole 64x64 superblock, so
298/// the above row and the left column weigh the same.
299fn dc_prediction(above: Option<u8>, left: Option<u8>) -> u8 {
300 match (above, left) {
301 (None, None) => 128,
302 (Some(a), None) => a,
303 (None, Some(l)) => l,
304 (Some(a), Some(l)) => ((u32::from(a) * 64 + u32::from(l) * 64 + 64) >> 7) as u8,
305 }
306}
307
308/// What a DC level adds to the prediction: the pinned table is that sum
309/// against a mid-grey prediction, and the residual does not depend on what
310/// it is added to.
311fn dc_residual(level: i32) -> i32 {
312 i32::from(decoded_value(level)) - 128
313}
314
315/// Every block reads its DC sign context off the coded blocks above and to
316/// its left, and the three ways that can land — no coded neighbour, the
317/// neighbours leaning one way, the neighbours cancelling — are only
318/// reachable in a frame whose levels differ in sign. Getting the context
319/// wrong desyncs the arithmetic decoder, so the check is that every block
320/// still decodes to the grey its own level asks for.
321#[test]
322fn each_superblock_decodes_to_the_grey_its_own_level_asks_for() {
323 if !have_ffmpeg() {
324 eprintln!("SKIP each_superblock_decodes_to_the_grey_its_own_level_asks_for: no ffmpeg");
325 return;
326 }
327 // Read in raster order the two grids put a positive, a negative and a
328 // cancelling sign context in front of the bottom-right block, and a
329 // leaning-down one in front of the second grid's right and bottom
330 // blocks.
331 for levels in [[14, 3, -3, -14], [-14, -3, 3, 14]] {
332 let planes = decode_level_grid(&levels, 2, 2);
333 let (luma, chroma) = planes.split_at(128 * 128);
334 // The blocks are not independent: a DC prediction reads the
335 // reconstructed neighbours, so each block's grey is its
336 // neighbours' average plus its own residual.
337 let mut recon = [0u8; 4];
338 for (block, level) in levels.iter().enumerate() {
339 let (br, bc) = (block / 2, block % 2);
340 let above = (br > 0).then(|| recon[block - 2]);
341 let left = (bc > 0).then(|| recon[block - 1]);
342 let want = (i32::from(dc_prediction(above, left)) + dc_residual(*level))
343 .clamp(0, 255) as u8;
344 recon[block] = want;
345 for y in 0..64 {
346 for x in 0..64 {
347 let i = (br * 64 + y) * 128 + bc * 64 + x;
348 assert_eq!(
349 luma[i], want,
350 "luma at ({x}, {y}) of the block carrying level {level} in {levels:?}"
351 );
352 }
353 }
354 }
355 for (i, &sample) in chroma.iter().enumerate() {
356 assert_eq!(sample, 128, "chroma sample {i} of {levels:?}");
357 }
358 }
359}
360
361/// What a DC level adds to a 32x32 block's prediction at `base_q_idx` 100,
362/// pinned from the decoder the way [`DECODED_AT_Q100`] is. A 32x32
363/// transform spreads its DC over a quarter of the samples a 64x64 one
364/// does, so the same level moves the picture further: level 14 is five
365/// sample values here against three there.
366const SPLIT_RESIDUAL_AT_Q100: [(i32, i32); 28] = [
367 (1, 0),
368 (2, 1),
369 (3, 1),
370 (4, 1),
371 (5, 2),
372 (6, 2),
373 (7, 3),
374 (8, 3),
375 (9, 3),
376 (10, 4),
377 (11, 4),
378 (12, 4),
379 (13, 5),
380 (14, 5),
381 (-1, 0),
382 (-2, -1),
383 (-3, -1),
384 (-4, -1),
385 (-5, -2),
386 (-6, -2),
387 (-7, -2),
388 (-8, -3),
389 (-9, -3),
390 (-10, -4),
391 (-11, -4),
392 (-12, -4),
393 (-13, -5),
394 (-14, -5),
395];
396
397fn split_residual(level: i32) -> i32 {
398 SPLIT_RESIDUAL_AT_Q100
399 .iter()
400 .find(|&&(l, _)| l == level)
401 .map(|&(_, r)| r)
402 .expect("the level is in the pinned table")
403}
404
405/// Splitting a superblock puts three more syntax elements in front of every
406/// block — the split partition itself, the 32x32 partition below it and a
407/// chroma mode from the wider table CFL-capable blocks read — and moves the
408/// coefficients onto the 32x32 CDFs. Getting any of them wrong desyncs the
409/// arithmetic decoder, and the check is that all sixteen blocks still land
410/// on the grey their own level and their neighbours ask for.
411#[test]
412fn a_split_superblock_decodes_each_quadrant_on_its_own_level() {
413 if !have_ffmpeg() {
414 eprintln!("SKIP a_split_superblock_decodes_each_quadrant_on_its_own_level: no ffmpeg");
415 return;
416 }
417 // Four by four 32x32 blocks over two by two superblocks, so the walk
418 // crosses superblock boundaries in both directions, and signs that
419 // alternate so the DC sign context lands on all three of its values.
420 let levels: [i32; 16] = [14, -3, 5, -5, -7, 7, -14, 3, 2, -2, 9, -9, -11, 11, -1, 1];
421 let planes = decode_split_grid(&levels, 2, 2);
422 let (luma, chroma) = planes.split_at(128 * 128);
423
424 let mut recon = [0i32; 16];
425 for (block, level) in levels.iter().enumerate() {
426 let (br, bc) = (block / 4, block % 4);
427 let above = (br > 0).then(|| recon[block - 4] as u8);
428 let left = (bc > 0).then(|| recon[block - 1] as u8);
429 let want =
430 (i32::from(dc_prediction(above, left)) + split_residual(*level)).clamp(0, 255);
431 recon[block] = want;
432 for y in 0..32 {
433 for x in 0..32 {
434 let i = (br * 32 + y) * 128 + bc * 32 + x;
435 assert_eq!(
436 i32::from(luma[i]),
437 want,
438 "luma at ({x}, {y}) of the block carrying level {level} at row {br}, \
439 column {bc}"
440 );
441 }
442 }
443 }
444 for (i, &sample) in chroma.iter().enumerate() {
445 assert_eq!(sample, 128, "chroma sample {i}");
446 }
447}
448
449/// Encode a grid of 32x32 blocks, each carrying its own DC level.
450fn decode_split_grid(levels: &[i32], sb_cols: u32, sb_rows: u32) -> Vec<u8> {
451 let (w, h) = (64 * sb_cols, 64 * sb_rows);
452 let (seq, mut header) = frame_of(w, h);
453 // The DC fixture writers code against the default CDFs and never
454 // update them, so their frames say so.
455 header.disable_cdf_update = true;
456 let tile = split_dc_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, levels).unwrap();
457 let mut stream = temporal_delimiter();
458 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
459 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
460 ffmpeg_decode(&stream, w as usize, h as usize)
461}
462
463#[test]
464fn a_level_grid_that_does_not_cover_the_frame_is_refused() {
465 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3]).is_err());
466 assert!(split_dc_key_frame_tile(16, 16, 100, &[3, 3, 3, 0]).is_err());
467 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3]).is_err());
468 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 3, 3, 3]).is_err());
469 assert!(dc_key_frame_tile_levels(32, 32, 100, &[3, 3, 0, 3]).is_err());
470}
471
472#[test]
473fn dc_levels_the_base_syntax_cannot_carry_are_refused() {
474 assert!(dc_key_frame_tile(16, 16, 100, 0).is_err());
475 assert!(dc_key_frame_tile(16, 16, 100, 15).is_err());
476 assert!(dc_key_frame_tile(16, 16, 100, -15).is_err());
477}
478
479#[test]
480fn partial_superblocks_are_refused() {
481 assert!(flat_key_frame_tile(16, 20).is_err());
482 assert!(flat_key_frame_tile(0, 16).is_err());
483}
484
485/// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
486/// hands back the luma plane as rows of samples.
487fn decode_coeff_quadrants(blocks: &[Vec<Coeff>]) -> Vec<Vec<u8>> {
488 let blocks: Vec<BlockCoeffs> = blocks.iter().cloned().map(BlockCoeffs::from).collect();
489 let [luma, u, v] = decode_coeff_planes(&blocks);
490 for (name, plane) in [("U", &u), ("V", &v)] {
491 for (y, row) in plane.iter().enumerate() {
492 for (x, &s) in row.iter().enumerate() {
493 assert_eq!(
494 s, 128,
495 "{name} sample ({x},{y}): no block codes a chroma coefficient, and a \
496 DC prediction with no coded neighbour is mid-grey"
497 );
498 }
499 }
500 }
501 luma
502}
503
504/// Encodes a 64x64 key frame whose four 32x32 blocks carry `blocks` and
505/// hands back its three planes as rows of samples: 64 rows of luma and, at
506/// 4:2:0, 32 rows of each chroma plane.
507fn decode_coeff_planes(blocks: &[BlockCoeffs]) -> [Vec<Vec<u8>>; 3] {
508 let (seq, header) = frame_of(64, 64);
509 let tile =
510 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
511 let mut stream = temporal_delimiter();
512 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
513 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
514 let planes = ffmpeg_decode(&stream, 64, 64);
515 let (luma, chroma) = planes.split_at(64 * 64);
516 let (u, v) = chroma.split_at(32 * 32);
517 [
518 luma.as_chunks::<64>().0.iter().map(|c| c.to_vec()).collect(),
519 u.as_chunks::<32>().0.iter().map(|c| c.to_vec()).collect(),
520 v.as_chunks::<32>().0.iter().map(|c| c.to_vec()).collect(),
521 ]
522}
523
524/// The top-left 32x32 block of a decoded frame, which is the only one whose
525/// prediction has no neighbour to lean on.
526fn top_left_block(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
527 rows[..32].iter().map(|r| r[..32].to_vec()).collect()
528}
529
530/// A transform's basis functions all average to zero except the DC's, so a
531/// block carrying no DC decodes to samples that average to its prediction —
532/// mid-grey for the block with no neighbours. Rounding of the inverse
533/// transform moves the average by less than a sample.
534fn assert_mean_is_mid_grey(block: &[Vec<u8>]) {
535 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
536 let mean = f64::from(sum) / (32.0 * 32.0);
537 assert!(
538 (mean - 128.0).abs() <= 1.0,
539 "a block with no DC coefficient averages to its mid-grey prediction, got {mean}"
540 );
541}
542
543/// A coefficient at row 0, column 1 selects the basis function that is flat
544/// down the block and a half-cycle of a cosine across it. Nothing about
545/// that shape is pinned here: every row of the block must be the same row,
546/// the samples must fall from left to right and actually move, and the
547/// block must still average to its prediction. A desync in the scan, the
548/// end-of-block position or the level contexts breaks one of those.
549#[test]
550fn a_coefficient_off_the_origin_selects_its_own_basis_function() {
551 if !have_ffmpeg() {
552 eprintln!(
553 "SKIP a_coefficient_off_the_origin_selects_its_own_basis_function: no ffmpeg"
554 );
555 return;
556 }
557 let blocks = vec![
558 vec![Coeff {
559 row: 0,
560 col: 1,
561 level: 12,
562 }],
563 Vec::new(),
564 Vec::new(),
565 Vec::new(),
566 ];
567 let rows = decode_coeff_quadrants(&blocks);
568 let block = top_left_block(&rows);
569
570 for (y, row) in block.iter().enumerate() {
571 assert_eq!(row, &block[0], "row {y} of a horizontal basis function");
572 }
573 assert!(
574 block[0][0] > block[0][31],
575 "a positive coefficient leans the block towards its left edge: {:?}",
576 block[0]
577 );
578 for x in 1..32 {
579 assert!(
580 block[0][x] <= block[0][x - 1],
581 "the half-cycle falls from left to right, broke at column {x}: {:?}",
582 block[0]
583 );
584 }
585 assert_mean_is_mid_grey(&block);
586
587 // The same coefficient transposed selects the basis function that is
588 // flat across the block and a half-cycle down it.
589 let blocks = vec![
590 vec![Coeff {
591 row: 1,
592 col: 0,
593 level: 12,
594 }],
595 Vec::new(),
596 Vec::new(),
597 Vec::new(),
598 ];
599 let rows = decode_coeff_quadrants(&blocks);
600 let block = top_left_block(&rows);
601 for (y, row) in block.iter().enumerate() {
602 for (x, &s) in row.iter().enumerate() {
603 assert_eq!(s, row[0], "sample ({y},{x}) of a vertical basis function");
604 }
605 }
606 assert!(
607 block[0][0] > block[31][0],
608 "a positive coefficient leans the block up"
609 );
610 for y in 1..32 {
611 assert!(
612 block[y][0] <= block[y - 1][0],
613 "the half-cycle falls from top to bottom, broke at row {y}"
614 );
615 }
616 assert_mean_is_mid_grey(&block);
617}
618
619/// A coefficient late in the scan pushes the end-of-block position into a
620/// group that carries an offset — the far corner of a 32x32 transform is
621/// the last of the eleven groups, whose offset is nine bits wide, one of
622/// them from a CDF and the rest raw. Every coefficient before it is coded
623/// too, so this also walks the base and base-range contexts over a block
624/// with neighbours that carry levels rather than zeros.
625#[test]
626fn a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group() {
627 if !have_ffmpeg() {
628 eprintln!("SKIP a_coefficient_in_the_far_corner_reaches_the_last_end_of_block_group");
629 return;
630 }
631 let block = vec![
632 Coeff {
633 row: 31,
634 col: 31,
635 level: 5,
636 },
637 Coeff {
638 row: 5,
639 col: 7,
640 level: -9,
641 },
642 Coeff {
643 row: 1,
644 col: 1,
645 level: 14,
646 },
647 Coeff {
648 row: 0,
649 col: 2,
650 level: -3,
651 },
652 Coeff {
653 row: 2,
654 col: 0,
655 level: 2,
656 },
657 Coeff {
658 row: 1,
659 col: 2,
660 level: -1,
661 },
662 ];
663 let rows = decode_coeff_quadrants(&[block, Vec::new(), Vec::new(), Vec::new()]);
664 let block = top_left_block(&rows);
665 assert_mean_is_mid_grey(&block);
666 assert!(
667 block.iter().flatten().any(|&s| s != block[0][0]),
668 "six coefficients do not decode to a flat block"
669 );
670 // The blocks that carry nothing are flat: their prediction is whatever
671 // their neighbours left, and they add no residual to it.
672 for (name, ys, xs) in [("top right", 0..32, 32..64), ("bottom left", 32..64, 0..32)] {
673 let first = rows[ys.start][xs.start];
674 for y in ys {
675 for x in xs.clone() {
676 assert_eq!(rows[y][x], first, "the {name} block carries no coefficient");
677 }
678 }
679 }
680}
681
682/// The price the mode search pays for a block's levels has to be the price
683/// the writer charges for them, or the search is ranking modes by a
684/// fiction. Both halves are asked for the same grids under the same
685/// neutral contexts, and the priced bits are compared against the bytes
686/// the writer really spends.
687#[test]
688fn the_priced_coefficient_bits_match_the_bytes_written() {
689 let scan = default_scan(TX32);
690 // Three grids that reach different parts of the syntax: a lone DC, a
691 // sparse spread of small levels with both signs, and levels past the
692 // base-range alphabet so the Golomb tail runs.
693 let mut grids = vec![vec![0i32; TX32 * TX32]; 3];
694 grids[0][0] = -7;
695 for (i, &pos) in scan.iter().enumerate().take(400) {
696 if i % 7 == 0 {
697 grids[1][pos as usize] = if i % 2 == 0 { 2 } else { -1 };
698 }
699 }
700 grids[2][0] = 40;
701 for (i, &pos) in scan.iter().enumerate().take(64) {
702 grids[2][pos as usize] += i as i32 % 23 - 11;
703 }
704
705 // A single block is too short for the coder's own flush to average
706 // out, so all three go through one encoder and one flush.
707 let mut enc = SymbolEncoder::new();
708 let mut priced = 0.0;
709 for grid in &grids {
710 write_coeffs(
711 &mut enc,
712 &mut Cdfs::new(2).txb(TxbSet::Luma32, 0),
713 grid,
714 &scan,
715 0,
716 0,
717 None,
718 TxType::DctDct,
719 );
720 priced += luma_32_coeff_bits(grid);
721 }
722 let spent = enc.finish().len() as f64 * 8.0;
723 assert!(
724 (priced - spent).abs() / spent < 0.02,
725 "priced {priced} bits, wrote {spent}"
726 );
727}
728
729/// A rate term the search can read as constant is a rate term that ranks
730/// nothing, so the price is checked to move the way the levels move: an
731/// empty block is the cheapest thing there is, one coefficient costs more
732/// than none, and both spreading the coefficients and growing them costs
733/// more again.
734#[test]
735fn the_price_grows_with_the_levels() {
736 let grid = |f: &dyn Fn(&mut Vec<i32>)| {
737 let mut g = vec![0i32; TX32 * TX32];
738 f(&mut g);
739 luma_32_coeff_bits(&g)
740 };
741 let empty = grid(&|_| {});
742 let one = grid(&|g| g[0] = 1);
743 let bigger = grid(&|g| g[0] = 30);
744 let spread = grid(&|g| {
745 for i in 0..TX32 {
746 g[i * TX32 + i] = 1;
747 }
748 });
749 assert!(empty < one, "{empty} {one}");
750 assert!(one < bigger, "{one} {bigger}");
751 assert!(one < spread, "{one} {spread}");
752 // An empty block is one symbol -- an expensive one, because a block
753 // with no coefficients at all is the rarer of the two under the
754 // neutral context -- and nothing else.
755 assert!(
756 empty < 6.0,
757 "an empty block is one skip symbol, not {empty}"
758 );
759}
760
761/// Neighbouring blocks that each carry coefficients read their DC sign
762/// context, their prediction and their own contexts off each other, so a
763/// frame whose four blocks all carry mixed-sign coefficients exercises what
764/// a single coded block cannot. The check is that it decodes at all — a
765/// desync anywhere fails the decode or the frame size — and that the block
766/// with no neighbours still averages to mid-grey.
767#[test]
768fn every_quadrant_carries_its_own_coefficients() {
769 if !have_ffmpeg() {
770 eprintln!("SKIP every_quadrant_carries_its_own_coefficients: no ffmpeg");
771 return;
772 }
773 let blocks = vec![
774 vec![
775 Coeff {
776 row: 0,
777 col: 1,
778 level: 7,
779 },
780 Coeff {
781 row: 3,
782 col: 4,
783 level: -14,
784 },
785 ],
786 vec![
787 Coeff {
788 row: 0,
789 col: 0,
790 level: -6,
791 },
792 Coeff {
793 row: 2,
794 col: 2,
795 level: 9,
796 },
797 ],
798 vec![
799 Coeff {
800 row: 0,
801 col: 0,
802 level: 6,
803 },
804 Coeff {
805 row: 1,
806 col: 0,
807 level: -2,
808 },
809 Coeff {
810 row: 8,
811 col: 9,
812 level: 3,
813 },
814 ],
815 vec![
816 Coeff {
817 row: 0,
818 col: 0,
819 level: 11,
820 },
821 Coeff {
822 row: 16,
823 col: 1,
824 level: -4,
825 },
826 ],
827 ];
828 let rows = decode_coeff_quadrants(&blocks);
829 assert_mean_is_mid_grey(&top_left_block(&rows));
830 for (name, ys, xs) in [
831 ("top right", 0..32, 32..64),
832 ("bottom left", 32..64, 0..32),
833 ("bottom right", 32..64, 32..64),
834 ] {
835 let block: Vec<Vec<u8>> = rows[ys].iter().map(|r| r[xs.clone()].to_vec()).collect();
836 assert!(
837 block.iter().flatten().any(|&s| s != block[0][0]),
838 "the {name} block carries coefficients, so it is not flat"
839 );
840 }
841}
842
843/// The top-left 16x16 block of a decoded chroma plane, which is the only
844/// one whose prediction has no neighbour to lean on.
845fn top_left_chroma(rows: &[Vec<u8>]) -> Vec<Vec<u8>> {
846 rows[..16].iter().map(|r| r[..16].to_vec()).collect()
847}
848
849/// The mean of a decoded block, which every basis function but the DC's
850/// leaves at the block's prediction.
851fn mean(block: &[Vec<u8>]) -> f64 {
852 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
853 let count = block.iter().map(Vec::len).sum::<usize>() as f64;
854 f64::from(sum) / count
855}
856
857/// A chroma plane's coefficients ride their own transform, their own CDFs
858/// and their own end-of-block alphabet, so a chroma basis function is the
859/// gate on all three: U carries the coefficient that is flat down the block
860/// and a half-cycle across it, V the one turned a quarter turn, and neither
861/// may reach the other plane or luma.
862#[test]
863fn each_chroma_plane_codes_its_own_basis_function() {
864 if !have_ffmpeg() {
865 eprintln!("SKIP each_chroma_plane_codes_its_own_basis_function: no ffmpeg");
866 return;
867 }
868 let mut blocks = vec![BlockCoeffs::default(); 4];
869 blocks[0].u = vec![Coeff {
870 row: 0,
871 col: 1,
872 level: 12,
873 }];
874 blocks[0].v = vec![Coeff {
875 row: 1,
876 col: 0,
877 level: 12,
878 }];
879 let [luma, u, v] = decode_coeff_planes(&blocks);
880
881 for (y, row) in luma.iter().enumerate() {
882 for (x, &s) in row.iter().enumerate() {
883 assert_eq!(
884 s, 128,
885 "luma sample ({x},{y}): no block codes a luma coefficient, so the picture \
886 stays at its mid-grey prediction"
887 );
888 }
889 }
890
891 let u_block = top_left_chroma(&u);
892 for (y, row) in u_block.iter().enumerate() {
893 assert_eq!(
894 row, &u_block[0],
895 "row {y} of a horizontal chroma basis function"
896 );
897 }
898 assert!(
899 u_block[0][0] > u_block[0][15],
900 "a positive coefficient leans the U block towards its left edge: {:?}",
901 u_block[0]
902 );
903
904 let v_block = top_left_chroma(&v);
905 for (x, &top) in v_block[0].iter().enumerate() {
906 assert_eq!(
907 top, v_block[0][0],
908 "column {x} of a vertical chroma basis function"
909 );
910 let column: Vec<u8> = v_block.iter().map(|r| r[x]).collect();
911 assert!(
912 column[0] > column[15],
913 "a positive coefficient leans the V column towards its top edge: {column:?}"
914 );
915 }
916
917 for (name, block) in [("U", &u_block), ("V", &v_block)] {
918 let mean = mean(block);
919 assert!(
920 (mean - 128.0).abs() <= 1.0,
921 "the {name} block carries no DC, so it averages to its mid-grey prediction, \
922 got {mean}"
923 );
924 }
925}
926
927/// Every block coding chroma puts the chroma all-zero flag on the contexts
928/// a coded neighbour above and to the left select, and the DC sign on the
929/// contexts their signs select. A frame whose four blocks all carry chroma
930/// DCs of mixed sign walks those contexts; the picture that comes back must
931/// still lean the way each block's own DC asks.
932#[test]
933fn chroma_dc_signs_read_their_neighbours() {
934 if !have_ffmpeg() {
935 eprintln!("SKIP chroma_dc_signs_read_their_neighbours: no ffmpeg");
936 return;
937 }
938 let dc = |level| {
939 vec![Coeff {
940 row: 0,
941 col: 0,
942 level,
943 }]
944 };
945 let signs = [8, -8, -8, 8];
946 let blocks: Vec<BlockCoeffs> = signs
947 .iter()
948 .map(|&level| BlockCoeffs {
949 luma: Vec::new(),
950 u: dc(level),
951 v: dc(-level),
952 ..BlockCoeffs::default()
953 })
954 .collect();
955 let [luma, u, v] = decode_coeff_planes(&blocks);
956
957 for (y, row) in luma.iter().enumerate() {
958 for (x, &s) in row.iter().enumerate() {
959 assert_eq!(s, 128, "luma sample ({x},{y}) with no luma coefficient");
960 }
961 }
962
963 // A DC prediction leans on the neighbours a block has, so each block is
964 // measured against the prediction it was given rather than mid-grey:
965 // the only block with no neighbour is the first, and the rest are read
966 // as a step away from the block above them and to their left.
967 for (i, &level) in signs.iter().enumerate() {
968 let (r, c) = (i / 2, i % 2);
969 let block = |plane: &[Vec<u8>]| -> Vec<Vec<u8>> {
970 plane[r * 16..r * 16 + 16]
971 .iter()
972 .map(|row| row[c * 16..c * 16 + 16].to_vec())
973 .collect()
974 };
975 for (name, plane, want) in [("U", &u, level), ("V", &v, -level)] {
976 let block = block(plane);
977 let mean = mean(&block);
978 for (y, row) in block.iter().enumerate() {
979 assert_eq!(
980 row.iter().collect::<std::collections::HashSet<_>>().len(),
981 1,
982 "row {y} of a DC-only {name} block is flat"
983 );
984 }
985 if i == 0 {
986 assert!(
987 (want > 0) == (mean > 128.0),
988 "{name} block {i} carries a DC of {want}, so it must lean off its \
989 mid-grey prediction that way, got {mean}"
990 );
991 }
992 }
993 }
994 assert_ne!(u, v, "the two chroma planes carry opposite DCs");
995}
996
997/// The coefficient writer refuses what it cannot code rather than writing a
998/// stream a decoder walks off the end of.
999/// The 32x32 block at the given block row and column of a decoded plane.
1000fn block_at(rows: &[Vec<u8>], block_row: usize, block_col: usize) -> Vec<Vec<u8>> {
1001 rows[block_row * 32..block_row * 32 + 32]
1002 .iter()
1003 .map(|r| r[block_col * 32..block_col * 32 + 32].to_vec())
1004 .collect()
1005}
1006
1007/// Encodes a key frame of the given size, whose 32x32 blocks carry
1008/// `blocks` in raster order, and hands back its luma plane as rows of
1009/// The neighbour context a block reads is gathered across every cell it
1010/// spans, not taken from the first one: a 32x32 block whose left-hand
1011/// neighbour cells disagree still sees the coded one. Reading a single
1012/// cell agreed with the decoder only while every block was the same size,
1013/// and desynchronised the arithmetic decoder the moment a 16x16 one
1014/// appeared beside a 32x32 one.
1015#[test]
1016fn a_block_gathers_the_cells_its_neighbours_cover() {
1017 let mut neighbours = Neighbours::new(4, 4, 64, 64);
1018 let quiet = [
1019 vec![0i32; TX16 * TX16],
1020 vec![0; TX8 * TX8],
1021 vec![0; TX8 * TX8],
1022 ];
1023 let mut loud = quiet.clone();
1024 loud[1][0] = -3;
1025 // Two 16x16 blocks above the right-hand 32x32 block of the row, of
1026 // which only the second codes anything.
1027 neighbours.record((0, 2), SUB, DC_PRED, &quiet);
1028 neighbours.record((0, 3), SUB, DC_PRED, &loud);
1029 let around = neighbours.around((2, 2), BLOCK);
1030 assert!(
1031 around[1].above_coded,
1032 "the coded cell has to reach the block below it"
1033 );
1034 assert_eq!(
1035 dc_sign_ctx(around[1].dc_vote),
1036 1,
1037 "the one negative DC above the block is what it votes"
1038 );
1039 // The same read one cell at a time misses it, which is the bug this
1040 // gate is here for. `above[8]` is the first 4x4 unit the quiet block
1041 // at `(0, 2)` wrote (2 SUB units * 4 4x4-units-per-SUB).
1042 assert!(!neighbours.above[8][1].coded);
1043}
1044
1045/// samples.
1046fn decode_luma_at(width: usize, height: usize, blocks: &[BlockCoeffs]) -> Vec<Vec<u8>> {
1047 let (seq, header) = frame_of(width as u32, height as u32);
1048 let tile =
1049 split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, blocks).unwrap();
1050 let mut stream = temporal_delimiter();
1051 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
1052 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
1053 let planes = ffmpeg_decode(&stream, width, height);
1054 planes[..width * height]
1055 .chunks_exact(width)
1056 .map(<[u8]>::to_vec)
1057 .collect()
1058}
1059
1060/// Every row of a block is the same row, and that row falls from left to
1061/// right — the shape of a coefficient at row 0, column 1.
1062fn assert_falls_across(block: &[Vec<u8>], name: &str) {
1063 for row in block {
1064 assert_eq!(
1065 row, &block[0],
1066 "{name}: every row of the block is the same row"
1067 );
1068 }
1069 assert!(
1070 block[0][0] > block[0][31],
1071 "{name}: the row falls from left to right, got {} then {}",
1072 block[0][0],
1073 block[0][31]
1074 );
1075}
1076
1077/// Every column of a block is constant across it and falls down it — the
1078/// shape of a coefficient at row 1, column 0.
1079fn assert_falls_down(block: &[Vec<u8>], name: &str) {
1080 for (y, row) in block.iter().enumerate() {
1081 assert!(
1082 row.iter().all(|&s| s == row[0]),
1083 "{name}: row {y} of the block is one constant"
1084 );
1085 }
1086 assert!(
1087 block[0][0] > block[31][0],
1088 "{name}: the column falls down the block, got {} then {}",
1089 block[0][0],
1090 block[31][0]
1091 );
1092}
1093
1094/// The mean sample of a decoded block.
1095fn mean_of(block: &[Vec<u8>]) -> f64 {
1096 let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
1097 f64::from(sum) / (block.len() * block[0].len()) as f64
1098}
1099
1100/// The top-left block of a frame whose only coefficient is a luma DC of
1101/// `level`.
1102fn decode_dc_level_block(level: i32) -> Vec<Vec<u8>> {
1103 let blocks = vec![
1104 vec![Coeff {
1105 row: 0,
1106 col: 0,
1107 level,
1108 }],
1109 Vec::new(),
1110 Vec::new(),
1111 Vec::new(),
1112 ];
1113 top_left_block(&decode_coeff_quadrants(&blocks))
1114}
1115
1116/// `read_golomb` (spec 5.11.40), written from the specification's
1117/// pseudocode, and the level its caller builds from it: a level above the
1118/// base-range tail is fifteen plus what the tail carries.
1119fn read_golomb_level(dec: &mut crate::msac::tests::SymbolDecoder) -> u32 {
1120 let mut length = 0;
1121 while dec.literal(1) == 0 {
1122 length += 1;
1123 assert!(
1124 length < 20,
1125 "the tail's length prefix runs past twenty bits"
1126 );
1127 }
1128 let mut x = 1;
1129 for _ in 0..length {
1130 x = (x << 1) | dec.literal(1);
1131 }
1132 (MAX_BR_LEVEL + 1) as u32 + (x - 1)
1133}
1134
1135/// The tail says how much of the level the base and base-range syntax could
1136/// not carry, and the spec's own reader must hand back the level that was
1137/// asked for — not one either side of it. A tail written a bit long, a bit
1138/// short, or against the wrong base fails this at the first level it
1139/// reaches.
1140#[test]
1141fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() {
1142 for level in (MAX_BR_LEVEL + 1..=MAX_BR_LEVEL + 300)
1143 .chain([MAX_LEVEL - 1, MAX_LEVEL])
1144 .map(|l| l as u32)
1145 {
1146 let mut enc = SymbolEncoder::new();
1147 write_golomb(&mut enc, level - (MAX_BR_LEVEL + 1) as u32);
1148 // The tail is raw bits, so it needs no padding beyond what the
1149 // encoder's own flush writes.
1150 let data = enc.finish();
1151 let mut dec = crate::msac::tests::SymbolDecoder::new(&data);
1152 assert_eq!(
1153 read_golomb_level(&mut dec),
1154 level,
1155 "the tail of level {level}"
1156 );
1157 }
1158}
1159
1160/// The base and base-range syntax reach level fourteen between them;
1161/// anything above that carries the rest of itself as a Golomb tail, written
1162/// after its own sign. A DC level moves the whole block off its mid-grey
1163/// prediction by an amount that grows with the level, so a run of levels
1164/// either side of the tail's threshold — spaced wide enough that the
1165/// quantiser separates them — must decode to a run of steadily
1166/// brighter blocks — and the negatives of the same levels to steadily
1167/// darker ones. A tail written with the wrong length, in the wrong place in
1168/// the syntax, or off by one desyncs the decoder outright.
1169#[test]
1170fn levels_above_the_base_range_tail_carry_a_golomb_tail() {
1171 if !have_ffmpeg() {
1172 eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg");
1173 return;
1174 }
1175 let mut brighter = Vec::new();
1176 let mut darker = Vec::new();
1177 for level in [10, 14, 18, 31, 60, 400] {
1178 brighter.push((level, mean_of(&decode_dc_level_block(level))));
1179 darker.push((level, mean_of(&decode_dc_level_block(-level))));
1180 }
1181 for pair in brighter.windows(2) {
1182 let [(low, dim), (high, bright)] = [pair[0], pair[1]];
1183 assert!(
1184 bright > dim,
1185 "level {high} decodes brighter than level {low}, got {bright} against {dim}"
1186 );
1187 }
1188 for pair in darker.windows(2) {
1189 let [(low, bright), (high, dim)] = [pair[0], pair[1]];
1190 assert!(
1191 dim < bright,
1192 "level -{high} decodes darker than level -{low}, got {dim} against {bright}"
1193 );
1194 }
1195 let (_, mid) = brighter[0];
1196 assert!(
1197 mid > 128.0 && darker[0].1 < 128.0,
1198 "a positive level brightens its block and a negative one darkens it, got {mid} and {}",
1199 darker[0].1
1200 );
1201}
1202
1203/// A frame need not be a whole number of superblocks. A 96x64 frame is a
1204/// superblock and a half across: the second superblock has no right-hand
1205/// half, so its partition is a gathered flag rather than the full symbol,
1206/// and the two blocks that would sit in that half are never coded at all.
1207/// Each of the six blocks that do exist carries one of two basis functions,
1208/// alternating, so a block written into the wrong place or a flag the
1209/// decoder reads as a different number of bits shows up as a block with the
1210/// other block's shape — or as a decode failure.
1211fn decode_luma_sb(width: usize, height: usize, sbs: &[Superblock]) -> Vec<Vec<u8>> {
1212 let (seq, header) = frame_of(width as u32, height as u32);
1213 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, sbs).unwrap();
1214 let mut stream = temporal_delimiter();
1215 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
1216 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
1217 let planes = ffmpeg_decode(&stream, width, height);
1218 planes[..width * height]
1219 .chunks_exact(width)
1220 .map(<[u8]>::to_vec)
1221 .collect()
1222}
1223
1224/// A superblock left whole carries one 64x64 transform, whose lowest
1225/// horizontal basis function falls across the whole sixty-four samples in
1226/// one stroke. Were the same superblock split, each half would restart the
1227/// gradient at its own left edge and the picture would rise again in the
1228/// middle, so the walk across the row is what tells the two apart — and
1229/// the split superblock beside it proves the two partitions still agree on
1230/// where the next one begins.
1231#[test]
1232fn a_whole_superblock_covers_all_four_of_its_quadrants() {
1233 if !have_ffmpeg() {
1234 eprintln!("SKIP a_whole_superblock_covers_all_four_of_its_quadrants: no ffmpeg");
1235 return;
1236 }
1237 let across = BlockCoeffs::from(vec![Coeff {
1238 row: 0,
1239 col: 1,
1240 level: 20,
1241 }]);
1242 let down = BlockCoeffs::from(vec![Coeff {
1243 row: 1,
1244 col: 0,
1245 level: 20,
1246 }]);
1247 let sbs = [
1248 Superblock::Whole(across),
1249 Superblock::Split(vec![
1250 Quadrant::Whole(down.clone()),
1251 Quadrant::Whole(down.clone()),
1252 Quadrant::Whole(down.clone()),
1253 Quadrant::Whole(down),
1254 ]),
1255 ];
1256 let rows = decode_luma_sb(128, 64, &sbs);
1257
1258 for (y, row) in rows.iter().enumerate() {
1259 assert_eq!(
1260 &row[..64],
1261 &rows[0][..64],
1262 "row {y} of the whole superblock repeats its first row"
1263 );
1264 }
1265 let first = &rows[0][..64];
1266 assert!(
1267 first.windows(2).all(|w| w[0] >= w[1]),
1268 "the whole superblock falls across its sixty-four samples without \
1269 restarting: {first:?}"
1270 );
1271 assert!(
1272 first[0] > first[63],
1273 "the whole superblock falls from left to right, got {} then {}",
1274 first[0],
1275 first[63]
1276 );
1277 for block_row in 0..2 {
1278 for block_col in 2..4 {
1279 let block = block_at(&rows, block_row, block_col);
1280 assert_falls_down(&block, &format!("quadrant ({block_row},{block_col})"));
1281 }
1282 }
1283}
1284
1285/// A quadrant may be split again into four 16x16 blocks, each carrying its
1286/// own 16x16 luma transform and 8x8 chroma transforms. A DC level per block
1287/// makes each of the four a flat grey of its own, so the quadrant reads as
1288/// four squares rather than one — which is what tells the extra split from
1289/// a 32x32 block that merely carries the same coefficients.
1290#[test]
1291fn a_quadrant_splits_into_four_sixteens() {
1292 if !have_ffmpeg() {
1293 eprintln!("SKIP a_quadrant_splits_into_four_sixteens: no ffmpeg");
1294 return;
1295 }
1296 let dc = |level: i32| {
1297 BlockCoeffs::from(vec![Coeff {
1298 row: 0,
1299 col: 0,
1300 level,
1301 }])
1302 };
1303 let levels = [14, 8, -8, -14];
1304 let flat = BlockCoeffs::from(Vec::new());
1305 let sbs = [Superblock::Split(vec![
1306 Quadrant::Split(levels.iter().map(|&l| dc(l)).collect()),
1307 Quadrant::Whole(flat.clone()),
1308 Quadrant::Whole(flat.clone()),
1309 Quadrant::Whole(flat),
1310 ])];
1311 let rows = decode_luma_sb(64, 64, &sbs);
1312
1313 let mut greys = Vec::new();
1314 for i in 0..levels.len() {
1315 let (y0, x0) = ((i / 2) * 16, (i % 2) * 16);
1316 let grey = rows[y0][x0];
1317 for (y, row) in rows.iter().enumerate().skip(y0).take(16) {
1318 for (x, &sample) in row.iter().enumerate().skip(x0).take(16) {
1319 assert_eq!(
1320 sample, grey,
1321 "the 16x16 block at ({x0},{y0}) is flat, but ({x},{y}) is not"
1322 );
1323 }
1324 }
1325 greys.push(grey);
1326 }
1327
1328 // Each block is predicted DC from the blocks the decoder has already
1329 // rebuilt, so what its own level does is move it off that prediction,
1330 // in the level's own direction.
1331 let g = |i: usize| i32::from(greys[i]);
1332 let predictions = [128, g(0), g(0), (g(1) + g(2) + 1) / 2];
1333 for (i, (&level, prediction)) in levels.iter().zip(predictions).enumerate() {
1334 assert_eq!(
1335 (g(i) - prediction).signum(),
1336 level.signum(),
1337 "the 16x16 block {i} carries level {level}, so it sits on the \
1338 {} side of the {prediction} its neighbours predict, not at {}",
1339 if level > 0 { "bright" } else { "dark" },
1340 g(i)
1341 );
1342 }
1343 assert_eq!(
1344 greys.iter().collect::<std::collections::HashSet<_>>().len(),
1345 4,
1346 "the four blocks are four different greys, not one: {greys:?}"
1347 );
1348}
1349
1350/// A superblock half outside the frame has no partition that keeps a block
1351/// outside it, so it cannot be left whole.
1352#[test]
1353fn a_whole_superblock_at_the_frame_edge_is_refused() {
1354 let block = BlockCoeffs::from(vec![Coeff {
1355 row: 0,
1356 col: 0,
1357 level: 4,
1358 }]);
1359 let sbs = [
1360 Superblock::Split(vec![
1361 Quadrant::Whole(block.clone()),
1362 Quadrant::Whole(block.clone()),
1363 Quadrant::Whole(block.clone()),
1364 Quadrant::Whole(block.clone()),
1365 ]),
1366 Superblock::Whole(block.clone()),
1367 ];
1368 // Ninety-six samples across is three 32x32 blocks, so the second
1369 // superblock hangs half outside the frame.
1370 let err = sb_coeff_key_frame_tile(24, 16, Q_IDX, &sbs).unwrap_err();
1371 assert!(
1372 format!("{err}").contains("half outside the frame"),
1373 "got {err}"
1374 );
1375}
1376
1377#[test]
1378fn a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block() {
1379 if !have_ffmpeg() {
1380 eprintln!(
1381 "SKIP a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block: no \
1382 ffmpeg"
1383 );
1384 return;
1385 }
1386 let blocks: Vec<BlockCoeffs> = (0..6)
1387 .map(|i| {
1388 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
1389 BlockCoeffs::from(vec![Coeff {
1390 row,
1391 col,
1392 level: 12,
1393 }])
1394 })
1395 .collect();
1396 let rows = decode_luma_at(96, 64, &blocks);
1397 for block_row in 0..2 {
1398 for block_col in 0..3 {
1399 let name = format!("block ({block_row},{block_col})");
1400 let block = block_at(&rows, block_row, block_col);
1401 if (block_row * 3 + block_col) % 2 == 0 {
1402 assert_falls_across(&block, &name);
1403 } else {
1404 assert_falls_down(&block, &name);
1405 }
1406 }
1407 }
1408}
1409
1410/// The transpose of [`a_frame_that_is_not_a_whole_number_of_superblocks_codes_every_block`]:
1411/// an odd number of 32x32 block *rows* (superblock hangs off the
1412/// *bottom*, `has_cols=true, has_rows=false`) rather than an odd number of
1413/// columns (hangs off the *right*, `has_cols=false, has_rows=true`) --
1414/// the two halves of the `(has_cols, has_rows)` match in
1415/// `sb_coeff_key_frame_tile` gather from different tables
1416/// (`VERT_ALIKE`/`HORZ_ALIKE`), and only the right-hand-edge direction had
1417/// a real-decoder test before this one.
1418#[test]
1419fn a_frame_that_hangs_off_the_bottom_codes_every_block() {
1420 if !have_ffmpeg() {
1421 eprintln!("SKIP a_frame_that_hangs_off_the_bottom_codes_every_block: no ffmpeg");
1422 return;
1423 }
1424 let blocks: Vec<BlockCoeffs> = (0..6)
1425 .map(|i| {
1426 let (row, col) = if i % 2 == 0 { (0, 1) } else { (1, 0) };
1427 BlockCoeffs::from(vec![Coeff {
1428 row,
1429 col,
1430 level: 12,
1431 }])
1432 })
1433 .collect();
1434 let rows = decode_luma_at(64, 96, &blocks);
1435 for block_row in 0..3 {
1436 for block_col in 0..2 {
1437 let name = format!("block ({block_row},{block_col})");
1438 let block = block_at(&rows, block_row, block_col);
1439 if (block_row * 2 + block_col) % 2 == 0 {
1440 assert_falls_across(&block, &name);
1441 } else {
1442 assert_falls_down(&block, &name);
1443 }
1444 }
1445 }
1446}
1447
1448/// A frame whose blocks do not tile it is refused rather than written as a
1449/// stream a decoder walks off the end of.
1450#[test]
1451fn a_frame_that_is_not_a_whole_number_of_blocks_is_refused() {
1452 let (_, header) = frame_of(80, 64);
1453 let blocks = vec![BlockCoeffs::default(); 4];
1454 let err = split_coeff_key_frame_tile(header.mi_cols, header.mi_rows, Q_IDX, &blocks)
1455 .expect_err("80 is not a whole number of 32x32 blocks");
1456 assert!(
1457 format!("{err}").contains("32x32"),
1458 "the refusal names the block size, got {err}"
1459 );
1460}
1461
1462/// A directional intra mode says where its prediction comes from, and with
1463/// no residual of its own a block must be exactly that prediction. The
1464/// top-left block is given a basis function that is flat across it and
1465/// falls down it; the block to its right is coded `H_PRED`, so every one of
1466/// its rows must be the constant its left neighbour's rightmost column
1467/// hands it, and the block below is coded `V_PRED`, so every one of its
1468/// columns must be the constant the row above it ends on — a single flat
1469/// value for the whole block. Nothing here pins the transform's shape or
1470/// the mode's CDF: a mode written with the wrong context, an angle delta
1471/// left out or a mode index off by one desyncs the symbol decoder and the
1472/// two empty blocks stop mirroring their neighbours.
1473#[test]
1474fn directional_modes_predict_from_the_neighbours_they_name() {
1475 if !have_ffmpeg() {
1476 eprintln!("SKIP directional_modes_predict_from_the_neighbours_they_name: no ffmpeg");
1477 return;
1478 }
1479 let gradient = BlockCoeffs {
1480 luma: vec![Coeff {
1481 row: 1,
1482 col: 0,
1483 level: 12,
1484 }],
1485 ..BlockCoeffs::default()
1486 };
1487 let blocks = [
1488 gradient,
1489 BlockCoeffs {
1490 mode: H_PRED as u8,
1491 ..BlockCoeffs::default()
1492 },
1493 BlockCoeffs {
1494 mode: V_PRED as u8,
1495 ..BlockCoeffs::default()
1496 },
1497 BlockCoeffs::default(),
1498 ];
1499 let [luma, ..] = decode_coeff_planes(&blocks);
1500
1501 let source = block_at(&luma, 0, 0);
1502 for (r, row) in source.iter().enumerate() {
1503 assert!(
1504 row.iter().all(|&s| s == row[0]),
1505 "the basis function at row 1, column 0 is flat across the block, row {r} is not: {row:?}"
1506 );
1507 }
1508 let profile: Vec<u8> = source.iter().map(|r| r[0]).collect();
1509 assert!(
1510 profile.windows(2).all(|w| w[0] >= w[1]) && profile[0] > profile[31],
1511 "the block must fall from top to bottom, got {profile:?}"
1512 );
1513
1514 let horizontal = block_at(&luma, 0, 1);
1515 for (r, row) in horizontal.iter().enumerate() {
1516 assert!(
1517 row.iter().all(|&s| s == profile[r]),
1518 "an H_PRED block repeats the column to its left, row {r} should be all {} but is {row:?}",
1519 profile[r]
1520 );
1521 }
1522
1523 let vertical = block_at(&luma, 1, 0);
1524 let bottom = profile[31];
1525 assert!(
1526 vertical.iter().flatten().all(|&s| s == bottom),
1527 "a V_PRED block repeats the row above it, which is all {bottom} here, got rows \
1528 {:?} and {:?}",
1529 vertical[0],
1530 vertical[31]
1531 );
1532}
1533
1534/// The mode index is checked before anything is written.
1535#[test]
1536fn an_intra_mode_outside_the_key_frame_set_is_refused() {
1537 let mut blocks = vec![BlockCoeffs::default(); 4];
1538 blocks[2].mode = INTRA_MODES as u8;
1539 let message = split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks)
1540 .unwrap_err()
1541 .to_string();
1542 assert!(
1543 message.contains("intra mode 13"),
1544 "the refusal must name the mode, got {message}"
1545 );
1546}
1547
1548#[test]
1549fn coefficients_the_writer_cannot_code_are_refused() {
1550 let empty = || vec![BlockCoeffs::default(); 4];
1551 let cases: [(&str, Vec<BlockCoeffs>); 6] = [
1552 ("one set short", vec![BlockCoeffs::default(); 3]),
1553 ("off the transform", {
1554 let mut b = empty();
1555 b[0].luma = vec![Coeff {
1556 row: 32,
1557 col: 0,
1558 level: 1,
1559 }];
1560 b
1561 }),
1562 ("a zero level", {
1563 let mut b = empty();
1564 b[1].luma = vec![Coeff {
1565 row: 0,
1566 col: 0,
1567 level: 0,
1568 }];
1569 b
1570 }),
1571 ("a level past the Golomb tail's reach", {
1572 let mut b = empty();
1573 b[2].luma = vec![Coeff {
1574 row: 0,
1575 col: 0,
1576 level: MAX_LEVEL + 1,
1577 }];
1578 b
1579 }),
1580 ("two coefficients at one position", {
1581 let mut b = empty();
1582 b[3].luma = vec![
1583 Coeff {
1584 row: 4,
1585 col: 4,
1586 level: 1,
1587 },
1588 Coeff {
1589 row: 4,
1590 col: 4,
1591 level: 2,
1592 },
1593 ];
1594 b
1595 }),
1596 ("off the chroma transform", {
1597 let mut b = empty();
1598 b[0].u = vec![Coeff {
1599 row: 0,
1600 col: 16,
1601 level: 1,
1602 }];
1603 b
1604 }),
1605 ];
1606 for (name, blocks) in cases {
1607 assert!(
1608 split_coeff_key_frame_tile(16, 16, Q_IDX, &blocks).is_err(),
1609 "{name} must be refused"
1610 );
1611 }
1612}
1613
1614/// The default scan is written as the rule that generates it rather than a
1615/// thousand pinned numbers, so the rule is checked against what a scan must
1616/// be: every position exactly once, the origin first, and never a position
1617/// before one it sits diagonally behind — which is what lets a decoder read
1618/// a coefficient's context off the coefficients it has already decoded.
1619/// lane-rdoq's two contracts, on a block shaped like the ones the pass
1620/// exists for (a strong DC, two mid levels and a tail of barely-rounded
1621/// +-1s): it may only move a block to a LOWER `D + lambda * R`, and the
1622/// bits it hands back must be the price of the grid it leaves behind --
1623/// the search takes that number as the block's rate, so a stale one
1624/// would price a tile nobody writes.
1625#[test]
1626fn rdoq_only_lowers_the_cost_and_reports_its_own_grid() {
1627 let (side, set, q, lambda) = (16usize, TxbSet::Luma16, 150u8, 0.0275);
1628 let mut scaled = vec![0f32; side * side];
1629 for (i, v) in [
1630 (0usize, 7.4f32),
1631 (1, 2.6),
1632 (side, -1.55),
1633 // The tail the pass exists for: coefficients the deadzone only
1634 // just rounded up to +-1, which give a whole level back for a
1635 // fraction of one step of squared error.
1636 (2, 0.55),
1637 (2 * side + 1, -0.52),
1638 (3 * side + 3, 0.51),
1639 ] {
1640 scaled[i] = v;
1641 }
1642 // The deadzone quantiser this pass runs after, at the shipped 0.5.
1643 let mut levels: Vec<i32> = scaled
1644 .iter()
1645 .map(|&v| {
1646 let m = f64::from(v).abs() + 0.5;
1647 let l = if m < 1.0 { 0 } else { m.floor() as i32 };
1648 if v < 0.0 { -l } else { l }
1649 })
1650 .collect();
1651 let before = levels.clone();
1652 let dc = f64::from(crate::quant::dc_q(8, i32::from(q)));
1653 let ac = f64::from(crate::quant::ac_q(8, i32::from(q)));
1654 let dc_weight = (dc / ac) * (dc / ac);
1655 let cost = |grid: &[i32]| -> f64 {
1656 let d: f64 = grid
1657 .iter()
1658 .zip(&scaled)
1659 .enumerate()
1660 .map(|(i, (&l, &s))| {
1661 (if i == 0 { dc_weight } else { 1.0 }) * (f64::from(s) - f64::from(l)).powi(2)
1662 })
1663 .sum();
1664 d + lambda * coeff_bits(grid, set, crate::decode::q_ctx_of(q), 0, 0)
1665 };
1666 let bits = rdoq(
1667 &mut levels,
1668 &scaled,
1669 side,
1670 q,
1671 set,
1672 0,
1673 0,
1674 lambda,
1675 TxType::DctDct,
1676 );
1677 assert_eq!(
1678 bits,
1679 coeff_bits(&levels, set, crate::decode::q_ctx_of(q), 0, 0)
1680 );
1681 assert!(
1682 cost(&levels) <= cost(&before),
1683 "{:?} vs {:?}",
1684 cost(&levels),
1685 cost(&before)
1686 );
1687 // The tail is what it is for: the last coded position moves earlier.
1688 let last = |g: &[i32]| scan_of(side).iter().rposition(|&p| g[usize::from(p)] != 0);
1689 assert!(
1690 last(&levels) < last(&before),
1691 "eob {:?} -> {:?}",
1692 last(&before),
1693 last(&levels)
1694 );
1695 // A 64-point transform is priced on its top-left 32x32 corner, and
1696 // the pass has to hand back THAT price (the dense path).
1697 let (side, set) = (64usize, TxbSet::Luma64);
1698 let mut scaled = vec![0f32; side * side];
1699 for (i, v) in [(0usize, 6.1f32), (1, 0.55), (side + 1, -0.53)] {
1700 scaled[i] = v;
1701 }
1702 let mut levels: Vec<i32> = scaled
1703 .iter()
1704 .map(|&v| {
1705 let m = f64::from(v).abs() + 0.5;
1706 let l = if m < 1.0 { 0 } else { m.floor() as i32 };
1707 if v < 0.0 { -l } else { l }
1708 })
1709 .collect();
1710 let bits = rdoq(
1711 &mut levels,
1712 &scaled,
1713 side,
1714 q,
1715 set,
1716 0,
1717 0,
1718 lambda,
1719 TxType::DctDct,
1720 );
1721 let corner: Vec<i32> = (0..32)
1722 .flat_map(|row| levels[row * side..][..32].to_vec())
1723 .collect();
1724 assert_eq!(
1725 bits,
1726 coeff_bits(&corner, set, crate::decode::q_ctx_of(q), 0, 0)
1727 );
1728}
1729
1730#[test]
1731fn the_default_scan_walks_every_position_outwards() {
1732 for side in [TX16, TX32] {
1733 let area = side * side;
1734 let scan = default_scan(side);
1735 assert_eq!(scan.len(), area);
1736 let mut seen = vec![false; area];
1737 for &pos in &scan {
1738 assert!(
1739 !seen[pos as usize],
1740 "position {pos} is scanned twice in {side}x{side}"
1741 );
1742 seen[pos as usize] = true;
1743 }
1744 assert_eq!(scan[0], 0, "the scan starts at the DC");
1745
1746 let mut order = vec![0usize; area];
1747 for (i, &pos) in scan.iter().enumerate() {
1748 order[pos as usize] = i;
1749 }
1750 for row in 0..side {
1751 for col in 0..side {
1752 for (dr, dc) in [(1, 0), (0, 1), (1, 1), (2, 0), (0, 2)] {
1753 let (nr, nc) = (row + dr, col + dc);
1754 if nr < side && nc < side {
1755 assert!(
1756 order[nr * side + nc] > order[row * side + col],
1757 "({nr},{nc}) is a context neighbour of ({row},{col}), so it must \
1758 be scanned after it"
1759 );
1760 }
1761 }
1762 }
1763 }
1764 }
1765}
1766
1767/// The whole point of the inverse transform living in the encoder is that
1768/// it predicts the decoder without asking one. The residual a DC-only
1769/// 64x64 transform produces has already been pinned from a real decoder in
1770/// [`DECODED_AT_Q100`], so that table is the gate: every level in it, both
1771/// signs, has to come back out of `dequant_and_inverse` exactly.
1772#[test]
1773fn the_inverse_transform_reproduces_the_pinned_whole_superblock_residuals() {
1774 for (level, _) in DECODED_AT_Q100 {
1775 let mut levels = vec![0i32; 64 * 64];
1776 levels[0] = level;
1777 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
1778 let want = dc_residual(level);
1779 assert!(
1780 residual.iter().all(|&r| r == want),
1781 "level {level}: want a flat {want}, got {}..{} (first {})",
1782 residual.iter().min().unwrap(),
1783 residual.iter().max().unwrap(),
1784 residual[0]
1785 );
1786 }
1787}
1788
1789/// The same gate at the other transform size the encoder codes: a split
1790/// superblock's 32x32 blocks, whose residuals are pinned in
1791/// [`SPLIT_RESIDUAL_AT_Q100`]. The two sizes divide the dequantized
1792/// coefficient by different denominators, so a size-blind dequantizer
1793/// passes one table and fails the other.
1794#[test]
1795fn the_inverse_transform_reproduces_the_pinned_split_residuals() {
1796 for (level, want) in SPLIT_RESIDUAL_AT_Q100 {
1797 let mut levels = vec![0i32; 32 * 32];
1798 levels[0] = level;
1799 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
1800 assert!(
1801 residual.iter().all(|&r| r == want),
1802 "level {level}: want a flat {want}, got {}..{} (first {})",
1803 residual.iter().min().unwrap(),
1804 residual.iter().max().unwrap(),
1805 residual[0]
1806 );
1807 }
1808}
1809
1810/// A DC-only transform is flat, which is exactly the case that cannot tell
1811/// a transposed or mis-permuted butterfly network from a correct one. An AC
1812/// coefficient in the first row must vary along the row and stay constant
1813/// down each column, and the one in the first column the other way round;
1814/// a transposed network swaps the two.
1815#[test]
1816fn a_single_ac_coefficient_varies_along_its_own_axis() {
1817 for side in [4, 8, 16, 32, 64] {
1818 let mut horizontal = vec![0i32; side * side];
1819 horizontal[1] = 100;
1820 let h = crate::transform::dequant_and_inverse(&horizontal, side, 8, i32::from(Q_IDX));
1821 let mut vertical = vec![0i32; side * side];
1822 vertical[side] = 100;
1823 let v = crate::transform::dequant_and_inverse(&vertical, side, 8, i32::from(Q_IDX));
1824 for row in 0..side {
1825 for col in 0..side {
1826 assert_eq!(
1827 h[row * side + col],
1828 h[col],
1829 "{side}: a first-row coefficient is constant down column {col}"
1830 );
1831 assert_eq!(
1832 v[row * side + col],
1833 v[row * side],
1834 "{side}: a first-column coefficient is constant along row {row}"
1835 );
1836 }
1837 }
1838 // The two are each other's transpose. Only to within a rounding
1839 // step: the spec rounds halves up rather than away from zero, so a
1840 // basis function and its transpose can land a count apart where
1841 // the row and column passes round opposite ways.
1842 assert!(h[0] != h[side - 1], "{side}: the horizontal basis varies");
1843 for row in 0..side {
1844 for col in 0..side {
1845 let (a, b) = (h[row * side + col], v[col * side + row]);
1846 assert!(
1847 (a - b).abs() <= 1,
1848 "{side}: transpose at ({row},{col}): {a} vs {b}"
1849 );
1850 }
1851 }
1852 }
1853}
1854
1855/// Negating every level negates every residual, to within the one count
1856/// the spec's round-halves-up leaves behind. A dequantizer that rounded a
1857/// negative coefficient away from zero instead of toward it would shift a
1858/// whole basis function, not a count of it, so the bound is what makes
1859/// this a test rather than a restatement.
1860#[test]
1861fn negating_the_levels_negates_the_residual() {
1862 for side in [32, 64] {
1863 for level in [1, 2, 3, 5, 9, 14, 40, 100] {
1864 let mut levels = vec![0i32; side * side];
1865 levels[0] = level;
1866 levels[1] = -level;
1867 levels[side + 1] = level * 2;
1868 let pos = crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
1869 let negated: Vec<i32> = levels.iter().map(|&l| -l).collect();
1870 let neg =
1871 crate::transform::dequant_and_inverse(&negated, side, 8, i32::from(Q_IDX));
1872 let worst = pos
1873 .iter()
1874 .zip(&neg)
1875 .map(|(&p, &n)| (p + n).abs())
1876 .max()
1877 .expect("the block is not empty");
1878 assert!(worst <= 1, "side {side} level {level}: off by {worst}");
1879 }
1880 }
1881}
1882
1883/// The pinned tables above are DC-only, and a flat residual cannot tell a
1884/// correct butterfly network from one that is merely correct at DC. This
1885/// is the same claim against a real decoder and with real AC content: the
1886/// top-left block of a key frame predicts a flat mid-grey with no
1887/// neighbours to read, so what ffmpeg shows there is exactly 128 plus the
1888/// residual the encoder's own inverse transform computes. Every sample has
1889/// to agree, not most of them.
1890#[test]
1891fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block() {
1892 if !have_ffmpeg() {
1893 eprintln!(
1894 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_32x32_block: no ffmpeg"
1895 );
1896 return;
1897 }
1898 // A DC, two low-frequency terms of each orientation, a diagonal and a
1899 // far corner, with both signs among them.
1900 let coeffs = [
1901 (0u8, 0u8, 9i32),
1902 (0, 1, -14),
1903 (1, 0, 7),
1904 (0, 3, 5),
1905 (3, 0, -3),
1906 (2, 2, 11),
1907 (7, 5, -6),
1908 (31, 31, 4),
1909 ];
1910 let block: BlockCoeffs = coeffs
1911 .iter()
1912 .map(|&(row, col, level)| Coeff { row, col, level })
1913 .collect::<Vec<_>>()
1914 .into();
1915 let rows = decode_luma_at(
1916 64,
1917 64,
1918 &[
1919 block,
1920 BlockCoeffs::default(),
1921 BlockCoeffs::default(),
1922 BlockCoeffs::default(),
1923 ],
1924 );
1925
1926 let mut levels = vec![0i32; 32 * 32];
1927 for &(row, col, level) in &coeffs {
1928 levels[usize::from(row) * 32 + usize::from(col)] = level;
1929 }
1930 let residual = crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
1931 for row in 0..32 {
1932 for col in 0..32 {
1933 let want = (128 + residual[row * 32 + col]).clamp(0, 255);
1934 assert_eq!(
1935 i32::from(rows[row][col]),
1936 want,
1937 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
1938 rows[row][col]
1939 );
1940 }
1941 }
1942 // The block is not flat, so the agreement is about the transform and
1943 // not about a prediction both sides got trivially right.
1944 let (lo, hi) = (
1945 rows[..32].iter().flat_map(|r| &r[..32]).min().unwrap(),
1946 rows[..32].iter().flat_map(|r| &r[..32]).max().unwrap(),
1947 );
1948 assert!(hi - lo > 4, "the block carries real detail, got {lo}..{hi}");
1949}
1950
1951/// The same against the smallest transform the writer codes, the 16x16 one
1952/// a split quadrant carries. Its rounding is the one the split path rests
1953/// on, and nothing else in the crate exercises it against a decoder.
1954#[test]
1955fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block() {
1956 if !have_ffmpeg() {
1957 eprintln!(
1958 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_16x16_block: no ffmpeg"
1959 );
1960 return;
1961 }
1962 let coeffs = [
1963 (0u8, 0u8, 9i32),
1964 (0, 1, -14),
1965 (1, 0, 7),
1966 (0, 3, 5),
1967 (3, 0, -3),
1968 (2, 2, 11),
1969 (7, 5, -6),
1970 (15, 15, 4),
1971 ];
1972 let block: BlockCoeffs = coeffs
1973 .iter()
1974 .map(|&(row, col, level)| Coeff { row, col, level })
1975 .collect::<Vec<_>>()
1976 .into();
1977 let (seq, header) = frame_of(64, 64);
1978 let quadrants = vec![
1979 Quadrant::Split(vec![
1980 block,
1981 BlockCoeffs::default(),
1982 BlockCoeffs::default(),
1983 BlockCoeffs::default(),
1984 ]),
1985 Quadrant::Whole(BlockCoeffs::default()),
1986 Quadrant::Whole(BlockCoeffs::default()),
1987 Quadrant::Whole(BlockCoeffs::default()),
1988 ];
1989 let tile = sb_coeff_key_frame_tile(
1990 header.mi_cols,
1991 header.mi_rows,
1992 Q_IDX,
1993 &[Superblock::Split(quadrants)],
1994 )
1995 .unwrap();
1996 let mut stream = temporal_delimiter();
1997 stream.extend_from_slice(&sequence_header_obu(&seq).unwrap());
1998 stream.extend_from_slice(&frame_obu(&seq, &header, &tile).unwrap());
1999 let planes = ffmpeg_decode(&stream, 64, 64);
2000
2001 let mut levels = vec![0i32; TX16 * TX16];
2002 for &(row, col, level) in &coeffs {
2003 levels[usize::from(row) * TX16 + usize::from(col)] = level;
2004 }
2005 let residual = crate::transform::dequant_and_inverse(&levels, TX16, 8, i32::from(Q_IDX));
2006 for row in 0..TX16 {
2007 for col in 0..TX16 {
2008 let want = (128 + residual[row * TX16 + col]).clamp(0, 255);
2009 assert_eq!(
2010 i32::from(planes[row * 64 + col]),
2011 want,
2012 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
2013 planes[row * 64 + col]
2014 );
2015 }
2016 }
2017}
2018
2019/// The same against the other transform size, the 64x64 one a whole
2020/// superblock carries. Only its top-left 32x32 can hold coefficients, and
2021/// the spec zeroes the rest before the row transform — a 64-point network
2022/// that read the missing half as anything else would disagree here.
2023#[test]
2024fn the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block() {
2025 if !have_ffmpeg() {
2026 eprintln!(
2027 "SKIP the_inverse_transform_predicts_what_ffmpeg_decodes_for_a_64x64_block: no ffmpeg"
2028 );
2029 return;
2030 }
2031 let coeffs = [
2032 (0u8, 0u8, 12i32),
2033 (0, 2, -9),
2034 (2, 0, 6),
2035 (1, 1, -5),
2036 (5, 9, 8),
2037 (31, 0, -4),
2038 (0, 31, 3),
2039 ];
2040 let block: BlockCoeffs = coeffs
2041 .iter()
2042 .map(|&(row, col, level)| Coeff { row, col, level })
2043 .collect::<Vec<_>>()
2044 .into();
2045 let rows = decode_luma_sb(64, 64, &[Superblock::Whole(block)]);
2046
2047 let mut levels = vec![0i32; 64 * 64];
2048 for &(row, col, level) in &coeffs {
2049 levels[usize::from(row) * 64 + usize::from(col)] = level;
2050 }
2051 let residual = crate::transform::dequant_and_inverse(&levels, 64, 8, i32::from(Q_IDX));
2052 for row in 0..64 {
2053 for col in 0..64 {
2054 let want = (128 + residual[row * 64 + col]).clamp(0, 255);
2055 assert_eq!(
2056 i32::from(rows[row][col]),
2057 want,
2058 "({row},{col}): ffmpeg decoded {} where the encoder predicted {want}",
2059 rows[row][col]
2060 );
2061 }
2062 }
2063}
2064
2065/// The AV1 transforms are normalized so that a quantized level means the
2066/// same thing at every size: doubling the transform's side halves what a
2067/// DC level is worth, which is the job the per-size row shift and the
2068/// dequantizer's denominator split between them. The frame syntax only
2069/// codes 32x32 and 64x64 transforms, so this is what holds the four
2070/// smaller sizes' shifts to the spec's table — a shift wrong by one at any
2071/// size doubles or halves that size's step alone.
2072#[test]
2073fn a_dc_level_is_worth_half_as_much_each_time_the_transform_doubles() {
2074 let mut previous: Option<i32> = None;
2075 for side in [4usize, 8, 16, 32, 64] {
2076 let mut levels = vec![0i32; side * side];
2077 levels[0] = 100;
2078 let residual =
2079 crate::transform::dequant_and_inverse(&levels, side, 8, i32::from(Q_IDX));
2080 let dc = residual[0];
2081 assert!(
2082 residual.iter().all(|&r| r == dc),
2083 "side {side}: a DC coefficient reconstructs flat"
2084 );
2085 if let Some(previous) = previous {
2086 assert!(
2087 (dc * 2 - previous).abs() <= 1,
2088 "side {side}: {dc} is not half of the previous size's {previous}"
2089 );
2090 }
2091 previous = Some(dc);
2092 }
2093}
2094
2095/// The encoder's own round trip, through a real bitstream.
2096///
2097/// A picture is chosen, its residual against the DC prediction of 128 is
2098/// forward-transformed and quantized, the levels are written into a tile,
2099/// and ffmpeg decodes it. Two things have to hold: what comes back is
2100/// exactly what the encoder's own inverse said it would be — sample for
2101/// sample, which is what lets a rate-distortion loop trust its
2102/// reconstruction — and it is within a quantizer step of the picture that
2103/// was asked for, which is what makes the forward transform an encoder
2104/// rather than a scrambler.
2105#[test]
2106fn a_quantized_picture_decodes_to_what_the_encoder_reconstructed() {
2107 if !have_ffmpeg() {
2108 eprintln!(
2109 "SKIP a_quantized_picture_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
2110 );
2111 return;
2112 }
2113 // A gradient, a ripple and a corner patch: low frequencies, a mid one
2114 // and an edge, none of them a basis function of the transform.
2115 let mut residual = vec![0i32; 32 * 32];
2116 for row in 0..32usize {
2117 for col in 0..32usize {
2118 let gradient = row as f64 * 2.0 - 32.0;
2119 let ripple = 25.0
2120 * (col as f64 * std::f64::consts::PI / 6.0).sin()
2121 * (row as f64 * std::f64::consts::PI / 11.0).cos();
2122 let patch = if row >= 24 && col >= 20 { -40.0 } else { 0.0 };
2123 residual[row * 32 + col] = (gradient + ripple + patch).round() as i32;
2124 }
2125 }
2126
2127 let levels =
2128 crate::transform::forward_and_quantize(&residual, 32, 8, i32::from(Q_IDX), 0.5);
2129 assert!(
2130 levels.iter().any(|&l| l != 0),
2131 "the picture quantized away entirely"
2132 );
2133 let coded: Vec<Coeff> = levels
2134 .iter()
2135 .enumerate()
2136 .filter(|&(_, &level)| level != 0)
2137 .map(|(i, &level)| Coeff {
2138 row: (i / 32) as u8,
2139 col: (i % 32) as u8,
2140 level,
2141 })
2142 .collect();
2143
2144 let rows = decode_luma_at(
2145 64,
2146 64,
2147 &[
2148 coded.into(),
2149 BlockCoeffs::default(),
2150 BlockCoeffs::default(),
2151 BlockCoeffs::default(),
2152 ],
2153 );
2154 let reconstruction =
2155 crate::transform::dequant_and_inverse(&levels, 32, 8, i32::from(Q_IDX));
2156
2157 let mut squared = 0.0f64;
2158 for row in 0..32 {
2159 for col in 0..32 {
2160 let want = (128 + reconstruction[row * 32 + col]).clamp(0, 255);
2161 assert_eq!(
2162 i32::from(rows[row][col]),
2163 want,
2164 "sample ({row},{col}): the decoder and the encoder disagree"
2165 );
2166 let error = f64::from(rows[row][col]) - f64::from(128 + residual[row * 32 + col]);
2167 squared += error * error;
2168 }
2169 }
2170 let rmse = (squared / 1024.0).sqrt();
2171 // A quantizer step is q/8 in residual units. Rounding to nearest
2172 // spreads the error over a step, and a quarter of one is a bound this
2173 // picture clears with room to spare (2.2 of 14 as written) while a
2174 // forward transform that is merely energy-preserving does not: a
2175 // transposed column pass measures 13.3 here.
2176 let step = f64::from(crate::quant::ac_q(8, i32::from(Q_IDX))) / 8.0;
2177 assert!(
2178 rmse < step / 4.0,
2179 "the decoded picture is {rmse} off, a step being {step}"
2180 );
2181}
2182
2183/// The inverse of [`write_mv_component`], mirroring [`SymbolDecoder`]
2184/// against the spec's own `read_mv_component` pseudocode.
2185fn decode_mv_component(
2186 dec: &mut crate::msac::tests::SymbolDecoder,
2187 c: &mut MvComponentCdfs,
2188) -> i32 {
2189 let sign = dec.symbol(&mut c.sign);
2190 let class = dec.symbol(&mut c.class);
2191 let local = if class == 0 {
2192 let bit = dec.symbol(&mut c.class0_bit);
2193 let fr = dec.symbol(&mut c.class0_fr[bit]);
2194 (bit << 3) | (fr << 1) | 1
2195 } else {
2196 let mut d = 0;
2197 for i in 0..class {
2198 d |= dec.symbol(&mut c.bit[i]) << i;
2199 }
2200 let fr = dec.symbol(&mut c.fr);
2201 (d << 3) | (fr << 1) | 1
2202 };
2203 let mag = mv_class_base(class) + local as i32 + 1;
2204 if sign == 1 { -mag } else { mag }
2205}
2206
2207/// Decodes one superblock a [`sb_coeff_inter_frame_tile`] payload wrote,
2208/// mirroring the writer's own context tracking (partition, skip,
2209/// is_inter, and the MV stack) symbol for symbol against a fresh
2210/// [`Cdfs`], so a desync between the two shows up as a wrong decoded
2211/// value rather than a silent pass. Every block here is skipped, so no
2212/// coefficient symbols are read. `wrong_y_mode` swaps in `KF_Y_MODE`'s
2213/// (0, 0) row for an intra block's mode read, to show that reading the
2214/// wrong table decodes the wrong mode rather than the one that was
2215/// written.
2216///
2217/// One decoded block's `(skip, is_inter, mode, mv)` — `mode` is `None`
2218/// for an inter block, `mv` is `(0, 0)` for an intra one.
2219type DecodedBlock = (bool, bool, Option<usize>, (i32, i32));
2220
2221/// Returns the number of symbols and literals read, and each block's
2222/// decoded state.
2223fn decode_inter_sb(
2224 data: &[u8],
2225 mi_cols: u32,
2226 mi_rows: u32,
2227 wrong_y_mode: bool,
2228) -> (usize, Vec<DecodedBlock>) {
2229 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
2230 let mut cdfs = Cdfs::new(2);
2231 let mut grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
2232 let mut above_skip = [false; 2];
2233 let mut left_skip = [false; 2];
2234 let mut above_inter = [false; 2];
2235 let mut left_inter = [false; 2];
2236 let mut count = 0usize;
2237
2238 count += 1;
2239 dec.symbol(&mut cdfs.partition_w64[0]);
2240
2241 let mut results = Vec::new();
2242 for quadrant in 0..4usize {
2243 let (r32, c32) = (quadrant / 2, quadrant % 2);
2244 count += 1;
2245 dec.symbol(&mut cdfs.partition_w32[0]);
2246
2247 let (has_above, has_left) = (r32 > 0, c32 > 0);
2248 let skip_ctx = usize::from(above_skip[c32]) + usize::from(left_skip[r32]);
2249 count += 1;
2250 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
2251
2252 let ii_ctx = intra_inter_ctx(has_above, has_left, above_inter[c32], left_inter[r32]);
2253 count += 1;
2254 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
2255
2256 let (mode, mv) = if is_inter {
2257 let sr_ctx = crate::mvstack::single_ref_ctx(above_inter[c32] || left_inter[r32]);
2258 count += 3;
2259 assert_eq!(
2260 dec.symbol(&mut cdfs.single_ref[sr_ctx][0]),
2261 0,
2262 "single_ref p1"
2263 );
2264 assert_eq!(
2265 dec.symbol(&mut cdfs.single_ref[sr_ctx][2]),
2266 0,
2267 "single_ref p3"
2268 );
2269 assert_eq!(
2270 dec.symbol(&mut cdfs.single_ref[sr_ctx][3]),
2271 0,
2272 "single_ref p4"
2273 );
2274
2275 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
2276 let stack = find_mv_stack(
2277 &grid,
2278 mi_row,
2279 mi_col,
2280 8,
2281 8,
2282 1,
2283 mi_cols as usize,
2284 mi_rows as usize,
2285 );
2286
2287 count += 1;
2288 let new_mv = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 0;
2289 let (mv, is_new_mv) = if new_mv {
2290 if stack.entries.len() > 1 {
2291 count += 1;
2292 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
2293 }
2294 count += 1;
2295 let joint = dec.symbol(&mut cdfs.mv_joint);
2296 let mut diff = (0, 0);
2297 if joint == 2 || joint == 3 {
2298 // sign, class, class0_bit, class0_fr for this test's
2299 // small (class 0) components.
2300 count += 4;
2301 diff.0 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[0]);
2302 }
2303 if joint == 1 || joint == 3 {
2304 count += 4;
2305 diff.1 = decode_mv_component(&mut dec, &mut cdfs.mv_comp[1]);
2306 }
2307 ((stack.pred_mv.0 + diff.0, stack.pred_mv.1 + diff.1), true)
2308 } else {
2309 count += 2;
2310 assert_eq!(
2311 dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]),
2312 1,
2313 "zero_mv"
2314 );
2315 assert_eq!(dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]), 0, "ref_mv");
2316 (stack.nearest_mv, false)
2317 };
2318 for dr in 0..8 {
2319 for dc in 0..8 {
2320 grid.set(
2321 mi_row + dr,
2322 mi_col + dc,
2323 MiInfo {
2324 is_inter: true,
2325 ref_frame: 1,
2326 ref_frame1: NO_REF1,
2327 mv1: (0, 0),
2328 mv: mv16(mv),
2329 is_new_mv,
2330 size: 8,
2331 size_h: 8,
2332 is_global_mv0: false,
2333 is_global_mv1: false,
2334 },
2335 );
2336 }
2337 }
2338 (None, mv)
2339 } else {
2340 count += 1;
2341 let m = if wrong_y_mode {
2342 dec.symbol(&mut cdfs.kf_y_mode[0][0])
2343 } else {
2344 dec.symbol(&mut cdfs.y_mode[3])
2345 };
2346 if (V_PRED..=D67_PRED).contains(&m) {
2347 count += 1;
2348 dec.symbol(&mut cdfs.angle_delta[m - V_PRED]);
2349 }
2350 count += 1;
2351 dec.symbol(&mut cdfs.uv_mode_cfl[m]);
2352 (Some(m), (0, 0))
2353 };
2354
2355 above_skip[c32] = skip;
2356 left_skip[r32] = skip;
2357 above_inter[c32] = is_inter;
2358 left_inter[r32] = is_inter;
2359 results.push((skip, is_inter, mode, mv));
2360 }
2361 (count, results)
2362}
2363
2364/// Every superblock here skips: no residual, so the only symbols are the
2365/// mode chain, and the byte count and the symbol count both come out
2366/// small enough to hand-check.
2367#[test]
2368fn an_all_skip_inter_superblock_is_small_and_reads_back() {
2369 let block = BlockCoeffs {
2370 inter: Some(InterInfo {
2371 ref1: None,
2372 mv1: (0, 0),
2373 ref_frame: crate::mvstack::LAST_FRAME,
2374 mode: InterMode::NearestMv,
2375 mv: (0, 0),
2376 ref_mv_idx: 0,
2377 }),
2378 skip: true,
2379 ..BlockCoeffs::default()
2380 };
2381 let blocks = vec![
2382 Quadrant::Whole(block.clone()),
2383 Quadrant::Whole(block.clone()),
2384 Quadrant::Whole(block.clone()),
2385 Quadrant::Whole(block),
2386 ];
2387 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
2388 // Hand count: one partition_w64, then per block partition_w32 + skip +
2389 // is_inter + 3 single_ref + new_mv + zero_mv + ref_mv = 9, times four.
2390 assert!(
2391 data.len() <= 16,
2392 "an all-skip NEARESTMV superblock took {} bytes",
2393 data.len()
2394 );
2395
2396 let (count, results) = decode_inter_sb(&data, 16, 16, false);
2397 assert_eq!(count, 1 + 4 * 9, "symbol count against the hand count");
2398 for (skip, is_inter, mode, mv) in results {
2399 assert!(skip);
2400 assert!(is_inter);
2401 assert_eq!(mode, None);
2402 // Every block's only inter neighbours carry (0, 0), so the stack's
2403 // nearest candidate is (0, 0) throughout.
2404 assert_eq!(mv, (0, 0));
2405 }
2406}
2407
2408/// The fourth block codes NEWMV against a (0, 0) predictor with a coded
2409/// column component: the symbol sequence a decoder reads back has to be
2410/// exactly what [`write_mv`] wrote, not a residual that merely decodes
2411/// to *some* valid vector.
2412#[test]
2413fn a_newmv_block_reads_back_the_exact_symbol_sequence_it_was_written_with() {
2414 let nearest = BlockCoeffs {
2415 inter: Some(InterInfo {
2416 ref1: None,
2417 mv1: (0, 0),
2418 ref_frame: crate::mvstack::LAST_FRAME,
2419 mode: InterMode::NearestMv,
2420 mv: (0, 0),
2421 ref_mv_idx: 0,
2422 }),
2423 skip: true,
2424 ..BlockCoeffs::default()
2425 };
2426 let newmv = BlockCoeffs {
2427 inter: Some(InterInfo {
2428 ref1: None,
2429 mv1: (0, 0),
2430 ref_frame: crate::mvstack::LAST_FRAME,
2431 mode: InterMode::NewMv,
2432 mv: (0, 2),
2433 ref_mv_idx: 0,
2434 }),
2435 skip: true,
2436 ..BlockCoeffs::default()
2437 };
2438 let blocks = vec![
2439 Quadrant::Whole(nearest.clone()),
2440 Quadrant::Whole(nearest.clone()),
2441 Quadrant::Whole(nearest),
2442 Quadrant::Whole(newmv),
2443 ];
2444 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
2445
2446 let (count, results) = decode_inter_sb(&data, 16, 16, false);
2447 // Three NEARESTMV blocks at 9 symbols each, one NEWMV block at
2448 // partition + skip + is_inter + 3 single_ref + new_mv + mv_joint +
2449 // (sign, class, class0_bit, class0_fr for the one nonzero component)
2450 // = 12, plus the superblock's partition_w64.
2451 assert_eq!(count, 1 + 3 * 9 + 12, "symbol count against the hand count");
2452 let (skip, is_inter, mode, mv) = results[3];
2453 assert!(skip);
2454 assert!(is_inter);
2455 assert_eq!(mode, None);
2456 assert_eq!(
2457 mv,
2458 (0, 2),
2459 "the decoded motion vector must be exactly what was written"
2460 );
2461}
2462
2463/// Decodes only the first 32x32 block's mode symbol of a superblock: the
2464/// tile's own first block always reads partition, skip and is_inter at
2465/// context zero, so this needs none of [`decode_inter_sb`]'s neighbour
2466/// bookkeeping — which matters here because the mutation this feeds
2467/// desyncs everything after the one symbol it is testing, and a decoder
2468/// that kept reading past it would be asserting on garbage.
2469fn decode_first_block_mode(data: &[u8], wrong_y_mode: bool) -> usize {
2470 let mut dec = crate::msac::tests::SymbolDecoder::new(data);
2471 let mut cdfs = Cdfs::new(2);
2472 dec.symbol(&mut cdfs.partition_w64[0]);
2473 dec.symbol(&mut cdfs.partition_w32[0]);
2474 dec.symbol(&mut cdfs.skip[0]);
2475 dec.symbol(&mut cdfs.intra_inter[0]);
2476 if wrong_y_mode {
2477 dec.symbol(&mut cdfs.kf_y_mode[0][0])
2478 } else {
2479 dec.symbol(&mut cdfs.y_mode[3])
2480 }
2481}
2482
2483/// An inter frame's intra block reads its mode against `Y_MODE`'s size
2484/// group, not `KF_Y_MODE`'s neighbour-context table a key frame's block
2485/// reads. Reading the wrong table back — `KF_Y_MODE`'s `(0, 0)` row —
2486/// decodes a different mode than the one [`sb_coeff_inter_frame_tile`]
2487/// wrote, because the two tables carry different default probabilities
2488/// even though a row of each is the same fourteen-entry width. (The swap
2489/// this test's name warns of does not typecheck as a one-line
2490/// substitution at the write site either — `cdfs.kf_y_mode[3]` is a
2491/// `[[u16; 14]; 5]` row, not the single `[u16; 14]` `Y_MODE` indexing
2492/// needs — so a mutation that got the *outer* shape wrong would be
2493/// caught by `cargo check` before it ever reached a test; this test is
2494/// what catches getting the *right* leaf shape from the *wrong* table.)
2495#[test]
2496fn an_intra_block_in_an_inter_frame_is_caught_reading_kf_y_mode() {
2497 let block = BlockCoeffs {
2498 mode: H_PRED as u8,
2499 skip: true,
2500 ..BlockCoeffs::default()
2501 };
2502 let blocks = vec![Quadrant::Whole(block); 4];
2503 let data = sb_coeff_inter_frame_tile(16, 16, 90, &blocks).unwrap();
2504
2505 assert_eq!(
2506 decode_first_block_mode(&data, false),
2507 H_PRED,
2508 "the right table reads the mode back exactly"
2509 );
2510 assert_ne!(
2511 decode_first_block_mode(&data, true),
2512 H_PRED,
2513 "KF_Y_MODE's different probabilities must decode a different mode"
2514 );
2515}
2516
2517/// lane-rectdq witness: [`crate::encode::delta_q_bits`] prices exactly
2518/// what [`write_delta_q`] writes, over the whole `delta_q_abs` domain
2519/// (0..=20 steps, both signs -- the escape literal pair starts at 3 and
2520/// its `rem_bits` widens at 4, 5, 9 and 17). The writer is run into a
2521/// PRICING coder whose account (`SymbolEncoder::bits`) is the same
2522/// arithmetic-coder cost the pricer's `symbol_bits` sums, so the two
2523/// agree to floating-point noise, not to a tolerance band.
2524///
2525/// Both sides read the DEFAULT `delta_q` row: the writer's `cdfs` is
2526/// rebuilt per case, exactly as every tile's is armed before its first
2527/// superblock.
2528#[test]
2529fn the_delta_q_pricer_matches_the_writer_over_the_whole_domain() {
2530 const RES: i32 = 4;
2531 const CUR: i32 = 128;
2532 for steps in -20i32..=20 {
2533 let target = CUR + steps * RES;
2534 arm_delta_q(RES, 1, vec![u8::try_from(target).expect("in range")], 128);
2535 let mut cdfs = Cdfs::new(2);
2536 let mut enc = SymbolEncoder::pricer();
2537 enc.reset_bits();
2538 // `is_whole_sb = false`: the rect half / 64-superblock shape,
2539 // the one whose pricer this witnesses.
2540 write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
2541 let written = enc.bits();
2542 let priced = crate::encode::delta_q_bits(target, CUR, RES);
2543 assert!(
2544 (written - priced).abs() < 1e-9,
2545 "steps {steps}: writer {written} bits, pricer {priced}"
2546 );
2547 }
2548 // Disarmed plan: the writer codes nothing and the pricer charges
2549 // nothing.
2550 arm_delta_q(0, 1, Vec::new(), 128);
2551 let mut cdfs = Cdfs::new(2);
2552 let mut enc = SymbolEncoder::pricer();
2553 enc.reset_bits();
2554 write_delta_q(&mut enc, &mut cdfs, (0, 0), false, true);
2555 assert!(enc.bits().abs() < 1e-9, "a disarmed plan writes no symbol");
2556 assert!((crate::encode::delta_q_bits(200, 128, 0)).abs() < 1e-9);
2557}