forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1dec' (r2): decoder covers directional modes, skip, odd sizes

Browse files at this commit

468f12825131de5993f7bbacea45a2041e8050afAhmet Kaan GümüşParent: 2023929632319a
All 13 intra modes, skip=1 blocks, and non-superblock-aligned frames now
decode byte-exact against the encoder reconstruction (854x480, 216x96,
128x128, 192x128). Fixes a right-by-coincidence txb mode index from r1.
crates/ec-av1/src/decode.rsmodified+471 -174
@@ -25,7 +25,8 @@ use ec_core::{Error, Result};
2525
2626 use crate::cdf;
2727 use crate::cdf_state::{Cdfs, TxbSet, TxbTables};
28-use crate::encode::Picture;
28+use crate::encode::{Picture, Reach};
29+use crate::intra::predict;
2930 use crate::msac::SymbolDecoder;
3031 use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
3132 use crate::transform::dequant_and_inverse;
@@ -35,6 +36,7 @@ const PARTITION_SPLIT: usize = 3;
3536 const SB_MI: u32 = 16;
3637 const BLOCK_MI: u32 = 8;
3738 const SUB_MI: u32 = 4;
39+const MI: usize = 4;
3840 const SB: usize = 64;
3941 const BLOCK: usize = 32;
4042 const SUB: usize = 16;
@@ -42,11 +44,43 @@ const TX32: usize = 32;
4244 const TX16: usize = 16;
4345 const TX8: usize = 8;
4446 const DC_PRED: usize = 0;
47+/// `V_PRED` (spec 6.10.2): the first directional mode, and so the first that
48+/// carries an angle delta — [`crate::tile`]'s own private copy of the same
49+/// constant.
50+const V_PRED: usize = 1;
51+/// The last directional mode, `D67_PRED`.
52+const D67_PRED: usize = 8;
53+/// The symbol an angle delta of zero codes as (spec 9.3): the alphabet runs
54+/// from -3 to +3, so this is its middle — [`crate::tile`]'s writer never
55+/// codes anything else, so this decoder never reads anything else either.
56+const ANGLE_DELTA_ZERO: usize = 3;
4557 const NUM_BASE_LEVELS: i32 = 2;
4658 const COEFF_BASE_RANGE: i32 = 12;
4759 const BR_STEP: i32 = 3;
4860 const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
4961
62+/// `partition_gather_vert_alike`/`_horz_alike` (spec 9.3): the partition types
63+/// whose probability mass a superblock or block half outside the frame
64+/// gathers into its one remaining flag — [`crate::tile`]'s own private copy,
65+/// duplicated here (that module is another lane's territory this round) and
66+/// kept in step with it by the byte-exact round-trip tests below rather than
67+/// by sharing code.
68+const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
69+const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
70+
71+fn element_prob(cdf: &[u16], element: usize) -> u16 {
72+ cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
73+}
74+
75+/// The two-symbol CDF a partial superblock/block's forced-split flag is read
76+/// with: the mass of `elements` becomes the probability of the one partition
77+/// the frame edge still allows, mirroring [`crate::tile`]'s own `gather`
78+/// (the encoder's non-adapting counterpart to this read).
79+fn gather(cdf: &[u16], elements: [usize; 6]) -> [u16; 3] {
80+ let split: u16 = elements.iter().map(|&e| element_prob(cdf, e)).sum();
81+ [32768 - split, 32768, 0]
82+}
83+
5084 fn unsupported(what: impl Into<String>) -> Error {
5185 Error::unsupported("AV1 tile", what.into())
5286 }
@@ -257,32 +291,62 @@ fn read_coeffs(
257291 Ok(grid)
258292 }
259293
260-/// The neighbour state a block's contexts are read from — the decode-side
261-/// twin of [`crate::tile`]'s private `Neighbours`, keeping only what a
262-/// `DC_PRED`-only decoder needs: per-16x16-cell block size (partition
263-/// context) and per-plane coded/DC-sign state (coefficient contexts). Mode
264-/// tracking is not needed: every block is `DC_PRED`, so the mode context is
265-/// always `[0][0]`.
294+/// What one coded block leaves behind for the blocks that read it as a
295+/// neighbour: whether it coded anything at all, and the sign of its DC —
296+/// [`crate::tile`]'s own private `Neighbour`.
297+#[derive(Clone, Copy, Default)]
298+struct Neighbour {
299+ coded: bool,
300+ dc: Option<bool>,
301+}
302+
303+fn neighbour_state(grid: &[i32]) -> Neighbour {
304+ Neighbour {
305+ coded: grid.iter().any(|&l| l != 0),
306+ dc: (grid[0] != 0).then_some(grid[0] < 0),
307+ }
308+}
309+
310+/// The neighbour state a block's contexts are read from — a duplicate of
311+/// [`crate::tile`]'s own private `Neighbours` (that module is another lane's
312+/// territory this round), kept at the same two granularities the real writer
313+/// tracks: `above_mode`/`left_mode`/`above_side`/`left_side` on the 16x16
314+/// (`SUB`) grid the partition/mode symbols read, and `above`/`left`'s
315+/// per-plane coded/DC-sign state on the finer 4x4 (`MI`) grid the coefficient
316+/// contexts read (spec `av1_set_entropy_contexts`) — which is what lets a
317+/// chroma transform straddling the true, odd-sized frame edge see its
318+/// neighbour's state clamped at its own subsampled edge rather than luma's.
266319 struct Neighbours {
320+ above: Vec<[Neighbour; 3]>,
321+ left: Vec<[Neighbour; 3]>,
322+ above_mode: Vec<usize>,
323+ left_mode: Vec<usize>,
267324 above_side: Vec<usize>,
268325 left_side: Vec<usize>,
269- above: Vec<[(bool, Option<bool>); 3]>,
270- left: Vec<[(bool, Option<bool>); 3]>,
326+ mi_cols: usize,
327+ mi_rows: usize,
271328 }
272329
273330 impl Neighbours {
274- fn new(cols: usize, rows: usize) -> Self {
331+ /// `cols`/`rows` are in [`SUB`] units; `mi_cols`/`mi_rows` are the frame's
332+ /// true (unpadded) size in 4x4 mode-info units.
333+ fn new(cols: usize, rows: usize, mi_cols: usize, mi_rows: usize) -> Self {
275334 Self {
335+ above: vec![[Neighbour::default(); 3]; cols * (SUB / MI)],
336+ left: vec![[Neighbour::default(); 3]; rows * (SUB / MI)],
337+ above_mode: vec![DC_PRED; cols],
338+ left_mode: vec![DC_PRED; rows],
276339 above_side: vec![SB; cols],
277340 left_side: vec![SB; rows],
278- above: vec![[(false, None); 3]; cols],
279- left: vec![[(false, None); 3]; rows],
341+ mi_cols,
342+ mi_rows,
280343 }
281344 }
282345
283346 fn start_row(&mut self) {
284- self.left_side.iter_mut().for_each(|s| *s = SB);
285347 self.left.iter_mut().for_each(|l| *l = Default::default());
348+ self.left_mode.iter_mut().for_each(|m| *m = DC_PRED);
349+ self.left_side.iter_mut().for_each(|s| *s = SB);
286350 }
287351
288352 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
@@ -290,57 +354,100 @@ impl Neighbours {
290354 2 * usize::from(self.left_side[r] * 2 <= side) + usize::from(self.above_side[c] * 2 <= side)
291355 }
292356
293- /// Whether any transform block above/left of this one (spanning `side_sub`
294- /// `SUB`-sized cells) coded a coefficient, and the gathered DC-sign vote,
295- /// per plane.
296- fn around(&self, at: (usize, usize), side_sub: usize) -> [(bool, bool, i32); 3] {
297- let (r, c) = at;
357+ /// The gathered coded/DC-sign state of the blocks above and to the left
358+ /// of a block `side` samples across, per plane.
359+ fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
360+ let (mi_r, mi_c, side_mi) = (r * (SUB / MI), c * (SUB / MI), side / MI);
298361 std::array::from_fn(|plane| {
299362 let mut above_coded = false;
300363 let mut left_coded = false;
301364 let mut vote = 0;
302- for cell in 0..side_sub {
303- let (a_coded, a_dc) = self.above[c + cell][plane];
304- let (l_coded, l_dc) = self.left[r + cell][plane];
305- above_coded |= a_coded;
306- left_coded |= l_coded;
307- vote += dc_vote(a_dc) + dc_vote(l_dc);
365+ for cell in 0..side_mi {
366+ let above = &self.above[mi_c + cell][plane];
367+ let left = &self.left[mi_r + cell][plane];
368+ above_coded |= above.coded;
369+ left_coded |= left.coded;
370+ vote += dc_vote(above.dc) + dc_vote(left.dc);
308371 }
309372 (above_coded, left_coded, vote)
310373 })
311374 }
312375
313- fn record(&mut self, at: (usize, usize), side: usize, grids: &[Vec<i32>; 3]) {
376+ /// Writes one coded block into every cell it covers, on both grids: the
377+ /// mode/side arrays up to `side`'s own width, and the coefficient-context
378+ /// arrays up to the true frame edge — the units past it are left at their
379+ /// default (uncoded), even mid-cell, exactly as [`crate::tile`]'s own
380+ /// `record` leaves them (spec `av1_set_entropy_contexts`, which clamps to
381+ /// `blocks_wide`/`blocks_high` derived from the true `mi_cols`/`mi_rows`,
382+ /// not from this block's own side).
383+ fn record(&mut self, at: (usize, usize), side: usize, mode: usize, grids: &[Vec<i32>; 3]) {
314384 let (r, c) = at;
315- let states: [(bool, Option<bool>); 3] = std::array::from_fn(|plane| {
316- let grid = &grids[plane];
317- (
318- grid.iter().any(|&l| l != 0),
319- (grid[0] != 0).then_some(grid[0] < 0),
320- )
321- });
385+ let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[plane]));
322386 for cell in 0..side / SUB {
387+ self.above_mode[c + cell] = mode;
388+ self.left_mode[r + cell] = mode;
323389 self.above_side[c + cell] = side;
324390 self.left_side[r + cell] = side;
325391 }
326- for cell in 0..side / SUB {
327- self.above[c + cell] = states;
328- self.left[r + cell] = states;
392+ let (mi_r, mi_c, side_mi) = (r * (SUB / MI), c * (SUB / MI), side / MI);
393+ // A chroma 4x4 unit straddling the true luma edge is still whole in
394+ // chroma's own halved grid, so libaom rounds the luma bound up to the
395+ // plane's own 4x4 unit before clamping a subsampled plane
396+ // (`av1_write_intra_coeffs_mb`, encodetxb.c).
397+ let round_up_even = |n: usize| n.div_ceil(2) * 2;
398+ let bound_h = [
399+ self.mi_rows,
400+ round_up_even(self.mi_rows),
401+ round_up_even(self.mi_rows),
402+ ];
403+ let bound_w = [
404+ self.mi_cols,
405+ round_up_even(self.mi_cols),
406+ round_up_even(self.mi_cols),
407+ ];
408+ for cell in 0..side_mi {
409+ self.left[mi_r + cell] = std::array::from_fn(|plane| {
410+ if cell < side_mi.min(bound_h[plane].saturating_sub(mi_r)) {
411+ states[plane]
412+ } else {
413+ Default::default()
414+ }
415+ });
416+ self.above[mi_c + cell] = std::array::from_fn(|plane| {
417+ if cell < side_mi.min(bound_w[plane].saturating_sub(mi_c)) {
418+ states[plane]
419+ } else {
420+ Default::default()
421+ }
422+ });
329423 }
330424 }
331425 }
332426
333-/// Reads one coded block's mode and skip flag, refusing anything but
334-/// `DC_PRED`, unskipped — the only shape this round's decoder reconstructs.
335-fn read_intra_mode(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, cfl: bool) -> Result<()> {
336- if dec.symbol(&mut cdfs.skip[0]) != 0 {
337- return Err(unsupported("a skipped block (round 2)"));
338- }
339- let mode = dec.symbol(&mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]]);
340- if mode != DC_PRED {
341- return Err(unsupported(format!(
342- "intra mode {mode} (round 1 reconstructs DC_PRED only)"
343- )));
427+/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
428+/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
429+/// exactly — including its skip context, which the real key-frame writer
430+/// always writes at a fixed context of zero (it never tracks a neighbour-based
431+/// one for intra blocks; that is the inter-frame writer's rule instead).
432+/// Refuses a nonzero angle delta or a chroma-from-luma mode: this decoder
433+/// reconstructs the thirteen luma modes at their base angle, DC-only chroma.
434+fn read_intra_mode(
435+ dec: &mut SymbolDecoder,
436+ cdfs: &mut Cdfs,
437+ above_mode: usize,
438+ left_mode: usize,
439+ cfl: bool,
440+) -> Result<(bool, usize)> {
441+ let skip = dec.symbol(&mut cdfs.skip[0]) != 0;
442+ let mode =
443+ dec.symbol(&mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]]);
444+ if (V_PRED..=D67_PRED).contains(&mode) {
445+ let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
446+ if angle != ANGLE_DELTA_ZERO {
447+ return Err(unsupported(
448+ "a nonzero angle delta (this encoder never writes one)",
449+ ));
450+ }
344451 }
345452 let uv_mode = if cfl {
346453 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
@@ -350,14 +457,23 @@ fn read_intra_mode(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, cfl: bool) -> Resul
350457 if uv_mode != DC_PRED {
351458 return Err(unsupported("a chroma-from-luma mode (round 2)"));
352459 }
353- Ok(())
460+ Ok((skip, mode))
354461 }
355462
356463 /// One plane's reconstruction buffer, `width * height` samples, and the
357-/// prediction/residual reads and writes into it.
464+/// prediction/residual reads and writes into it — the decode-side twin of
465+/// [`crate::encode`]'s private `Plane`, whose `edges` this mirrors exactly
466+/// (own-edge and reach clamps both), passing what it gathers straight to
467+/// [`crate::intra::predict`] instead of hand-rolling `DC_PRED` alone.
358468 struct PlaneBuf {
359469 data: Vec<u8>,
360470 width: usize,
471+ height: usize,
472+ /// The frame's true, decodable extent in this plane's own units — past
473+ /// this, samples are the padded coding surface's invented tail, never a
474+ /// real decoder's edge or reach reads.
475+ true_width: usize,
476+ true_height: usize,
361477 }
362478
363479 impl PlaneBuf {
@@ -366,40 +482,58 @@ impl PlaneBuf {
366482 x: usize,
367483 y: usize,
368484 side: usize,
485+ reach: Reach,
369486 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
370- let above = (y > 0).then(|| self.data[(y - 1) * self.width + x..][..side].to_vec());
371- let left = (x > 0).then(|| {
372- (y..y + side)
487+ let own_across = x + side.min(self.true_width.saturating_sub(x));
488+ let across = if reach.above_right {
489+ own_across + side.min(self.true_width.saturating_sub(own_across))
490+ } else {
491+ own_across
492+ }
493+ .min(self.width);
494+ let own_down = y + side.min(self.true_height.saturating_sub(y));
495+ let down = if reach.below_left {
496+ own_down + side.min(self.true_height.saturating_sub(own_down))
497+ } else {
498+ own_down
499+ }
500+ .min(self.height);
501+ let above = (y > 0 && across > x)
502+ .then(|| self.data[(y - 1) * self.width + x..][..across - x].to_vec());
503+ let left = (x > 0 && down > y).then(|| {
504+ (y..down)
373505 .map(|row| self.data[row * self.width + x - 1])
374- .collect()
506+ .collect::<Vec<_>>()
375507 });
376508 let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]);
377509 (above, left, corner)
378510 }
379511
380- /// Predicts (`DC_PRED` only) then adds `residual` (side*side, raster),
512+ /// Predicts under `mode` then adds `residual` (side*side, raster),
381513 /// writing the clamped reconstruction back into the plane at `(x, y)`.
382- fn reconstruct(&mut self, x: usize, y: usize, side: usize, residual: &[i32]) {
383- let (above, left, _corner) = self.edges(x, y, side);
384- let dc = match (&above, &left) {
385- (None, None) => 128,
386- (Some(a), None) => {
387- let sum: u32 = a.iter().map(|&s| u32::from(s)).sum();
388- ((sum + (a.len() as u32 >> 1)) / a.len() as u32) as i32
389- }
390- (None, Some(l)) => {
391- let sum: u32 = l.iter().map(|&s| u32::from(s)).sum();
392- ((sum + (l.len() as u32 >> 1)) / l.len() as u32) as i32
393- }
394- (Some(a), Some(l)) => {
395- let sum: u32 = a.iter().chain(l).map(|&s| u32::from(s)).sum();
396- let count = (a.len() + l.len()) as u32;
397- ((sum + (count >> 1)) / count) as i32
398- }
399- };
514+ fn reconstruct(
515+ &mut self,
516+ x: usize,
517+ y: usize,
518+ side: usize,
519+ mode: usize,
520+ reach: Reach,
521+ residual: &[i32],
522+ ) {
523+ let (above, left, corner) = self.edges(x, y, side, reach);
524+ let mut prediction = vec![0u8; side * side];
525+ predict(
526+ mode as u8,
527+ above.as_deref(),
528+ left.as_deref(),
529+ corner,
530+ side,
531+ &mut prediction,
532+ );
400533 for row in 0..side {
401534 for col in 0..side {
402- let sample = (dc + residual[row * side + col]).clamp(0, 255) as u8;
535+ let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
536+ .clamp(0, 255) as u8;
403537 self.data[(y + row) * self.width + x + col] = sample;
404538 }
405539 }
@@ -416,6 +550,12 @@ fn read_plane(
416550 scan: &[u16],
417551 plane_idx: usize,
418552 around: (bool, bool, i32),
553+ // The block's own luma mode — [`crate::tile::write_block_planes`] passes
554+ // it for every plane's `txb` lookup (it is what an intra transform type's
555+ // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
556+ tx_mode: usize,
557+ predict_mode: usize,
558+ reach: Reach,
419559 plane: &mut PlaneBuf,
420560 x: usize,
421561 y: usize,
@@ -428,7 +568,7 @@ fn read_plane(
428568 } else {
429569 usize::from(around.0) + usize::from(around.1)
430570 };
431- let mut coding = cdfs.txb(set, DC_PRED);
571+ let mut coding = cdfs.txb(set, tx_mode);
432572 let grid = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?;
433573 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
434574 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
@@ -444,7 +584,7 @@ fn read_plane(
444584 full
445585 };
446586 let residual = dequant_and_inverse(&levels, tx_side, 8, i32::from(base_q_idx));
447- plane.reconstruct(x, y, tx_side, &residual);
587+ plane.reconstruct(x, y, tx_side, predict_mode, reach, &residual);
448588 Ok(if tx_side == side {
449589 residual_grid_placeholder(&levels, tx_side)
450590 } else {
@@ -481,44 +621,84 @@ fn decode_block(
481621 v: &mut PlaneBuf,
482622 base_q_idx: u8,
483623 ) -> Result<()> {
484- read_intra_mode(dec, cdfs, cfl)?;
485624 let (r, c) = at;
486- let around = neighbours.around(at, side / SUB);
487625 let (px, py) = (c * SUB, r * SUB);
488- let luma_grid = read_plane(
489- dec, cdfs, luma_set, scans.0, 0, around[0], y, px, py, side, luma_tx, base_q_idx,
490- )?;
491- let (cpx, cpy) = (px / 2, py / 2);
492- let chroma_side = side / 2;
493- let u_grid = read_plane(
626+ let (skip, mode) = read_intra_mode(
494627 dec,
495628 cdfs,
496- chroma_set,
497- scans.1,
498- 1,
499- around[1],
500- u,
501- cpx,
502- cpy,
503- chroma_side,
504- chroma_tx,
505- base_q_idx,
629+ neighbours.above_mode[c],
630+ neighbours.left_mode[r],
631+ cfl,
506632 )?;
507- let v_grid = read_plane(
508- dec,
509- cdfs,
510- chroma_set,
511- scans.1,
512- 2,
513- around[2],
514- v,
515- cpx,
516- cpy,
517- chroma_side,
518- chroma_tx,
519- base_q_idx,
520- )?;
521- neighbours.record(at, side, &[luma_grid, u_grid, v_grid]);
633+ let reach = Reach::of(side, px, py, y.width, y.height);
634+ let (luma_grid, u_grid, v_grid);
635+ let (cpx, cpy) = (px / 2, py / 2);
636+ let chroma_side = side / 2;
637+ if skip {
638+ // A skipped block codes no residual syntax at all (spec 5.11.34):
639+ // straight prediction, on every plane.
640+ y.reconstruct(px, py, side, mode, reach, &vec![0i32; side * side]);
641+ u.reconstruct(
642+ cpx,
643+ cpy,
644+ chroma_side,
645+ DC_PRED,
646+ Reach::none(),
647+ &vec![0i32; chroma_side * chroma_side],
648+ );
649+ v.reconstruct(
650+ cpx,
651+ cpy,
652+ chroma_side,
653+ DC_PRED,
654+ Reach::none(),
655+ &vec![0i32; chroma_side * chroma_side],
656+ );
657+ luma_grid = vec![0i32; side * side];
658+ u_grid = vec![0i32; chroma_side * chroma_side];
659+ v_grid = vec![0i32; chroma_side * chroma_side];
660+ } else {
661+ let around = neighbours.around(at, side);
662+ luma_grid = read_plane(
663+ dec, cdfs, luma_set, scans.0, 0, around[0], mode, mode, reach, y, px, py, side,
664+ luma_tx, base_q_idx,
665+ )?;
666+ u_grid = read_plane(
667+ dec,
668+ cdfs,
669+ chroma_set,
670+ scans.1,
671+ 1,
672+ around[1],
673+ mode,
674+ DC_PRED,
675+ Reach::none(),
676+ u,
677+ cpx,
678+ cpy,
679+ chroma_side,
680+ chroma_tx,
681+ base_q_idx,
682+ )?;
683+ v_grid = read_plane(
684+ dec,
685+ cdfs,
686+ chroma_set,
687+ scans.1,
688+ 2,
689+ around[2],
690+ mode,
691+ DC_PRED,
692+ Reach::none(),
693+ v,
694+ cpx,
695+ cpy,
696+ chroma_side,
697+ chroma_tx,
698+ base_q_idx,
699+ )?;
700+ }
701+ neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
522702 Ok(())
523703 }
524704
@@ -526,46 +706,56 @@ fn decode_block(
526706 /// returning the picture it reconstructs to.
527707 ///
528708 /// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by
529-/// [`ec_av1_syntax`].
709+/// [`ec_av1_syntax`]. `frame_width`/`frame_height` are the header's own true
710+/// (render) size — a separate field from `mi_cols`/`mi_rows` (spec
711+/// `compute_image_size` derives one from the other, but not losslessly: a
712+/// width that is not a multiple of 8 samples leaves `mi_cols * 4` past it) —
713+/// what the reconstruction is cropped to on the way out, mirroring
714+/// [`crate::encode::crop_encoded`].
530715 ///
531716 /// # Errors
532-/// Returns an error when the frame is not a whole number of 64x64
533-/// superblocks (round 2: the partial-superblock/gathered-CDF path), when a
534-/// block's partition, mode, skip flag or transform type is anything this
535-/// decoder does not reconstruct (round 2: non-`DC_PRED` intra, inter, tx
536-/// types other than `DCT_DCT`), or when the tile payload runs out of the
537-/// symbols this decode expects (a genuinely foreign stream).
717+/// Returns an error when a block's partition, mode, skip flag or transform
718+/// type is anything this decoder does not reconstruct (round 2: inter, tx
719+/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
720+/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
721+/// or when the tile payload runs out of the symbols this decode expects (a
722+/// genuinely foreign stream).
538723 pub fn decode_key_frame_tile(
539724 data: &[u8],
540725 mi_cols: u32,
541726 mi_rows: u32,
542727 base_q_idx: u8,
728+ frame_width: u32,
729+ frame_height: u32,
543730 ) -> Result<Picture> {
544- if mi_cols == 0
545- || mi_rows == 0
546- || !mi_cols.is_multiple_of(SB_MI)
547- || !mi_rows.is_multiple_of(SB_MI)
548- {
549- return Err(unsupported(
550- "a frame that is not a whole number of 64x64 superblocks (round 2)",
551- ));
552- }
553- let (sb_cols, sb_rows) = (mi_cols / SB_MI, mi_rows / SB_MI);
731+ if mi_cols == 0 || mi_rows == 0 {
732+ return Err(unsupported("a frame with no mode-info grid"));
733+ }
734+ let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(SB_MI));
554735 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
555- let width = (mi_cols * 4) as usize;
556- let height = (mi_rows * 4) as usize;
736+ let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
737+ let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
557738
558739 let mut y = PlaneBuf {
559740 data: vec![0u8; width * height],
560741 width,
742+ height,
743+ true_width,
744+ true_height,
561745 };
562746 let mut u = PlaneBuf {
563747 data: vec![0u8; width * height / 4],
564748 width: width / 2,
749+ height: height / 2,
750+ true_width: true_width / 2,
751+ true_height: true_height / 2,
565752 };
566753 let mut v = PlaneBuf {
567754 data: vec![0u8; width * height / 4],
568755 width: width / 2,
756+ height: height / 2,
757+ true_width: true_width / 2,
758+ true_height: true_height / 2,
569759 };
570760
571761 let scan32 = default_scan(TX32);
@@ -574,7 +764,12 @@ pub fn decode_key_frame_tile(
574764
575765 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
576766 let mut dec = SymbolDecoder::new(data);
577- let mut neighbours = Neighbours::new(cols32 as usize * 2, rows32 as usize * 2);
767+ let mut neighbours = Neighbours::new(
768+ cols32 as usize * 2,
769+ rows32 as usize * 2,
770+ mi_cols as usize,
771+ mi_rows as usize,
772+ );
578773
579774 for sb_r in 0..sb_rows {
580775 neighbours.start_row();
@@ -585,12 +780,27 @@ pub fn decode_key_frame_tile(
585780 sb_c * SB_MI + SB_MI / 2 < mi_cols,
586781 sb_r * SB_MI + SB_MI / 2 < mi_rows,
587782 );
588- if !has_cols || !has_rows {
589- return Err(unsupported(
590- "a superblock half outside the true frame (round 2)",
591- ));
592- }
593- let part = dec.symbol(&mut cdfs.partition_w64[ctx]);
783+ // Recomputed at this superblock's own half (spec
784+ // `decode_partition`): a full alphabet symbol when both halves are
785+ // inside the true frame, a single gathered bit when just one is
786+ // (the superblock cannot be left whole, so this is forced split),
787+ // and nothing at all (SPLIT inferred, no bits) when neither is —
788+ // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
789+ // three-way write exactly.
790+ let part = if has_cols && has_rows {
791+ dec.symbol(&mut cdfs.partition_w64[ctx])
792+ } else {
793+ match (has_cols, has_rows) {
794+ (true, false) => {
795+ dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
796+ }
797+ (false, true) => {
798+ dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
799+ }
800+ _ => {}
801+ }
802+ PARTITION_SPLIT
803+ };
594804 match part {
595805 PARTITION_NONE => {
596806 decode_block(
@@ -623,12 +833,26 @@ pub fn decode_key_frame_tile(
623833 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
624834 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
625835 );
626- if !has_cols32 || !has_rows32 {
627- return Err(unsupported(
628- "a 32x32 block half outside the true frame (round 2)",
629- ));
630- }
631- let part32 = dec.symbol(&mut cdfs.partition_w32[ctx32]);
836+ let part32 = if has_cols32 && has_rows32 {
837+ dec.symbol(&mut cdfs.partition_w32[ctx32])
838+ } else {
839+ match (has_cols32, has_rows32) {
840+ (true, false) => {
841+ dec.symbol_fixed(&gather(
842+ &cdfs.partition_w32[ctx32],
843+ VERT_ALIKE,
844+ ));
845+ }
846+ (false, true) => {
847+ dec.symbol_fixed(&gather(
848+ &cdfs.partition_w32[ctx32],
849+ HORZ_ALIKE,
850+ ));
851+ }
852+ _ => {}
853+ }
854+ PARTITION_SPLIT
855+ };
632856 match part32 {
633857 PARTITION_NONE => {
634858 decode_block(
@@ -709,12 +933,29 @@ pub fn decode_key_frame_tile(
709933 }
710934 }
711935
936+ let (fw, fh) = (frame_width as usize, frame_height as usize);
937+ if fw == width && fh == height {
938+ return Ok(Picture {
939+ width,
940+ height,
941+ y: y.data,
942+ u: u.data,
943+ v: v.data,
944+ });
945+ }
946+ let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
947+ let mut out = Vec::with_capacity(w * h);
948+ for row in 0..h {
949+ out.extend_from_slice(&plane.data[row * plane.width..][..w]);
950+ }
951+ out
952+ };
712953 Ok(Picture {
713- width,
714- height,
715- y: y.data,
716- u: u.data,
717- v: v.data,
954+ width: fw,
955+ height: fh,
956+ y: crop(&y, fw, fh),
957+ u: crop(&u, fw / 2, fh / 2),
958+ v: crop(&v, fw / 2, fh / 2),
718959 })
719960 }
720961
@@ -733,41 +974,97 @@ mod tests {
733974 // that path with real quantised residual, not a synthetic all-DC frame.
734975
735976 #[test]
736- fn a_frame_that_is_not_a_whole_number_of_superblocks_is_refused() {
737- assert!(decode_key_frame_tile(&[0u8; 4], 33, 32, 32).is_err());
977+ fn a_frame_with_no_mode_info_grid_is_refused() {
978+ assert!(decode_key_frame_tile(&[0u8; 4], 0, 32, 32, 0, 128).is_err());
979+ }
980+
981+ /// Encodes and decodes one picture with `modes`, asserting the decoder's
982+ /// planes are byte-exact against the encoder's own reconstruction.
983+ fn round_trips(w: usize, h: usize, modes: &[u8]) {
984+ use crate::encode::{Encoded, Picture as Pic};
985+ let mut source = vec![0u8; w * h];
986+ for row in 0..h {
987+ for col in 0..w {
988+ source[row * w + col] = ((row * 3 + col * 5) % 251) as u8;
989+ }
990+ }
991+ let picture = Pic {
992+ width: w,
993+ height: h,
994+ y: source,
995+ u: vec![128; w * h / 4],
996+ v: vec![128; w * h / 4],
997+ };
998+ let Encoded {
999+ tile,
1000+ reconstruction,
1001+ mi_cols,
1002+ mi_rows,
1003+ base_q_idx,
1004+ ..
1005+ }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
1006+ let decoded =
1007+ decode_key_frame_tile(&tile, mi_cols, mi_rows, base_q_idx, w as u32, h as u32).unwrap();
1008+ assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
1009+ assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
1010+ assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
1011+ assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
1012+ assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
7381013 }
7391014
7401015 #[test]
7411016 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
742- use crate::encode::{Encoded, Picture as Pic};
7431017 for (w, h) in [(128usize, 128usize), (192, 128)] {
744- let mut source = vec![0u8; w * h];
745- for row in 0..h {
746- for col in 0..w {
747- source[row * w + col] = ((row * 3 + col * 5) % 251) as u8;
748- }
749- }
750- let picture = Pic {
751- width: w,
752- height: h,
753- y: source,
754- u: vec![128; w * h / 4],
755- v: vec![128; w * h / 4],
756- };
757- let Encoded {
758- tile,
759- reconstruction,
760- mi_cols,
761- mi_rows,
762- base_q_idx,
763- ..
764- }: Encoded =
765- crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, &[DC_PRED as u8])
766- .unwrap();
767- let decoded = decode_key_frame_tile(&tile, mi_cols, mi_rows, base_q_idx).unwrap();
768- assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
769- assert_eq!(decoded.u, reconstruction.u, "{w}x{h} chroma U mismatch");
770- assert_eq!(decoded.v, reconstruction.v, "{w}x{h} chroma V mismatch");
1018+ round_trips(w, h, &[DC_PRED as u8]);
7711019 }
7721020 }
1021+
1022+ /// Every one of the thirteen key-frame intra modes, at their base angle,
1023+ /// on real (non-flat) content: the mode search picks whichever wins each
1024+ /// block, so this exercises the directional edge/reach plumbing this
1025+ /// decoder round adds, not just `DC_PRED`.
1026+ #[test]
1027+ fn every_intra_mode_round_trips_bit_exact_against_the_encoder_reconstruction() {
1028+ for (w, h) in [(128usize, 128usize), (192, 128)] {
1029+ round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
1030+ }
1031+ }
1032+
1033+ /// Sizes not a whole number of 64x64 superblocks (nor even of 32x32
1034+ /// blocks, for 854x480): the gathered-CDF partial-superblock/32x32 path
1035+ /// this decoder round adds.
1036+ #[test]
1037+ fn odd_sizes_round_trip_bit_exact_against_the_encoder_reconstruction() {
1038+ for (w, h) in [(854usize, 480usize), (216, 96)] {
1039+ round_trips(w, h, &crate::intra::KEY_FRAME_MODES);
1040+ }
1041+ }
1042+
1043+ /// A skipped block codes no residual syntax at all (spec 5.11.34):
1044+ /// straight prediction on every plane. The real key-frame writer never
1045+ /// emits `skip = 1` ([`crate::tile::write_intra_mode`] hardcodes it to
1046+ /// `0`), so this constructs the exact symbol sequence a writer that did
1047+ /// emit it would produce, by hand, and asserts the decoded reconstruction
1048+ /// is pure DC prediction (mid-grey, with no neighbours) rather than
1049+ /// refusing.
1050+ #[test]
1051+ fn a_skipped_block_decodes_to_pure_prediction() {
1052+ use crate::msac::SymbolEncoder;
1053+ let mut cdfs = Cdfs::new(q_ctx_of(40));
1054+ let mut enc = SymbolEncoder::new();
1055+ // One whole, unsplit 64x64 superblock, coded skip = true.
1056+ enc.symbol(PARTITION_NONE, &mut cdfs.partition_w64[0]);
1057+ enc.symbol(1, &mut cdfs.skip[0]);
1058+ enc.symbol(
1059+ DC_PRED,
1060+ &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
1061+ );
1062+ enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
1063+ let data = enc.finish();
1064+ let decoded = decode_key_frame_tile(&data, 16, 16, 40, 64, 64).unwrap();
1065+ assert!(
1066+ decoded.y.iter().all(|&s| s == 128),
1067+ "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
1068+ );
1069+ }
7731070 }
crates/ec-av1/src/encode.rsmodified+5 -5
@@ -935,9 +935,9 @@ struct At {
935935 /// (or below its left) are decoded depends only on where the block sits inside
936936 /// its 64x64 superblock, which is a pinned table per block size.
937937 #[derive(Clone, Copy)]
938-struct Reach {
939- above_right: bool,
940- below_left: bool,
938+pub(crate) struct Reach {
939+ pub(crate) above_right: bool,
940+ pub(crate) below_left: bool,
941941 }
942942
943943 /// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
@@ -955,7 +955,7 @@ const HAS_BOTTOM_LEFT: [&[u8]; 2] = [&[84, 16, 84, 0, 84, 16, 84, 0], &[4, 4]];
955955 impl Reach {
956956 /// What a block of `side` samples at `(x, y)` may read past its own edges,
957957 /// in a frame of `width` by `height`.
958- fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self {
958+ pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self {
959959 Self {
960960 above_right: y > 0 && x + side < width && Self::top_right(side, x, y),
961961 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y),
@@ -964,7 +964,7 @@ impl Reach {
964964
965965 /// Neither, which is all a mode that reads no further than its own edges
966966 /// needs.
967- fn none() -> Self {
967+ pub(crate) fn none() -> Self {
968968 Self {
969969 above_right: false,
970970 below_left: false,