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};
25 25
26 use crate::cdf;26 use crate::cdf;
27 use crate::cdf_state::{Cdfs, TxbSet, TxbTables};27 use crate::cdf_state::{Cdfs, TxbSet, TxbTables};
28-use crate::encode::Picture;28+use crate::encode::{Picture, Reach};
29+use crate::intra::predict;
29 use crate::msac::SymbolDecoder;30 use crate::msac::SymbolDecoder;
30 use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};31 use crate::tile::{INTRA_MODE_CTX, block_grid, has_half};
31 use crate::transform::dequant_and_inverse;32 use crate::transform::dequant_and_inverse;
@@ -35,6 +36,7 @@ const PARTITION_SPLIT: usize = 3;
35 const SB_MI: u32 = 16;36 const SB_MI: u32 = 16;
36 const BLOCK_MI: u32 = 8;37 const BLOCK_MI: u32 = 8;
37 const SUB_MI: u32 = 4;38 const SUB_MI: u32 = 4;
39+const MI: usize = 4;
38 const SB: usize = 64;40 const SB: usize = 64;
39 const BLOCK: usize = 32;41 const BLOCK: usize = 32;
40 const SUB: usize = 16;42 const SUB: usize = 16;
@@ -42,11 +44,43 @@ const TX32: usize = 32;
42 const TX16: usize = 16;44 const TX16: usize = 16;
43 const TX8: usize = 8;45 const TX8: usize = 8;
44 const DC_PRED: usize = 0;46 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;
45 const NUM_BASE_LEVELS: i32 = 2;57 const NUM_BASE_LEVELS: i32 = 2;
46 const COEFF_BASE_RANGE: i32 = 12;58 const COEFF_BASE_RANGE: i32 = 12;
47 const BR_STEP: i32 = 3;59 const BR_STEP: i32 = 3;
48 const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;60 const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
49 61
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+
50 fn unsupported(what: impl Into<String>) -> Error {84 fn unsupported(what: impl Into<String>) -> Error {
51 Error::unsupported("AV1 tile", what.into())85 Error::unsupported("AV1 tile", what.into())
52 }86 }
@@ -257,32 +291,62 @@ fn read_coeffs(
257 Ok(grid)291 Ok(grid)
258 }292 }
259 293
260-/// The neighbour state a block's contexts are read from — the decode-side294+/// What one coded block leaves behind for the blocks that read it as a
261-/// twin of [`crate::tile`]'s private `Neighbours`, keeping only what a295+/// neighbour: whether it coded anything at all, and the sign of its DC —
262-/// `DC_PRED`-only decoder needs: per-16x16-cell block size (partition296+/// [`crate::tile`]'s own private `Neighbour`.
263-/// context) and per-plane coded/DC-sign state (coefficient contexts). Mode297+#[derive(Clone, Copy, Default)]
264-/// tracking is not needed: every block is `DC_PRED`, so the mode context is298+struct Neighbour {
265-/// always `[0][0]`.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.
266 struct Neighbours {319 struct Neighbours {
320+ above: Vec<[Neighbour; 3]>,
321+ left: Vec<[Neighbour; 3]>,
322+ above_mode: Vec<usize>,
323+ left_mode: Vec<usize>,
267 above_side: Vec<usize>,324 above_side: Vec<usize>,
268 left_side: Vec<usize>,325 left_side: Vec<usize>,
269- above: Vec<[(bool, Option<bool>); 3]>,326+ mi_cols: usize,
270- left: Vec<[(bool, Option<bool>); 3]>,327+ mi_rows: usize,
271 }328 }
272 329
273 impl Neighbours {330 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 {
275 Self {334 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],
276 above_side: vec![SB; cols],339 above_side: vec![SB; cols],
277 left_side: vec![SB; rows],340 left_side: vec![SB; rows],
278- above: vec![[(false, None); 3]; cols],341+ mi_cols,
279- left: vec![[(false, None); 3]; rows],342+ mi_rows,
280 }343 }
281 }344 }
282 345
283 fn start_row(&mut self) {346 fn start_row(&mut self) {
284- self.left_side.iter_mut().for_each(|s| *s = SB);
285 self.left.iter_mut().for_each(|l| *l = Default::default());347 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);
286 }350 }
287 351
288 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {352 fn partition_ctx(&self, at: (usize, usize), side: usize) -> usize {
@@ -290,57 +354,100 @@ impl Neighbours {
290 2 * usize::from(self.left_side[r] * 2 <= side) + usize::from(self.above_side[c] * 2 <= side)354 2 * usize::from(self.left_side[r] * 2 <= side) + usize::from(self.above_side[c] * 2 <= side)
291 }355 }
292 356
293- /// Whether any transform block above/left of this one (spanning `side_sub`357+ /// The gathered coded/DC-sign state of the blocks above and to the left
294- /// `SUB`-sized cells) coded a coefficient, and the gathered DC-sign vote,358+ /// of a block `side` samples across, per plane.
295- /// per plane.359+ fn around(&self, (r, c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
296- fn around(&self, at: (usize, usize), side_sub: usize) -> [(bool, bool, i32); 3] {360+ let (mi_r, mi_c, side_mi) = (r * (SUB / MI), c * (SUB / MI), side / MI);
297- let (r, c) = at;
298 std::array::from_fn(|plane| {361 std::array::from_fn(|plane| {
299 let mut above_coded = false;362 let mut above_coded = false;
300 let mut left_coded = false;363 let mut left_coded = false;
301 let mut vote = 0;364 let mut vote = 0;
302- for cell in 0..side_sub {365+ for cell in 0..side_mi {
303- let (a_coded, a_dc) = self.above[c + cell][plane];366+ let above = &self.above[mi_c + cell][plane];
304- let (l_coded, l_dc) = self.left[r + cell][plane];367+ let left = &self.left[mi_r + cell][plane];
305- above_coded |= a_coded;368+ above_coded |= above.coded;
306- left_coded |= l_coded;369+ left_coded |= left.coded;
307- vote += dc_vote(a_dc) + dc_vote(l_dc);370+ vote += dc_vote(above.dc) + dc_vote(left.dc);
308 }371 }
309 (above_coded, left_coded, vote)372 (above_coded, left_coded, vote)
310 })373 })
311 }374 }
312 375
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]) {
314 let (r, c) = at;384 let (r, c) = at;
315- let states: [(bool, Option<bool>); 3] = std::array::from_fn(|plane| {385+ let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(&grids[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- });
322 for cell in 0..side / SUB {386 for cell in 0..side / SUB {
387+ self.above_mode[c + cell] = mode;
388+ self.left_mode[r + cell] = mode;
323 self.above_side[c + cell] = side;389 self.above_side[c + cell] = side;
324 self.left_side[r + cell] = side;390 self.left_side[r + cell] = side;
325 }391 }
326- for cell in 0..side / SUB {392+ let (mi_r, mi_c, side_mi) = (r * (SUB / MI), c * (SUB / MI), side / MI);
327- self.above[c + cell] = states;393+ // A chroma 4x4 unit straddling the true luma edge is still whole in
328- self.left[r + cell] = states;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+ });
329 }423 }
330 }424 }
331 }425 }
332 426
333-/// Reads one coded block's mode and skip flag, refusing anything but427+/// Reads one coded block's skip flag, luma mode, angle delta (if the mode
334-/// `DC_PRED`, unskipped — the only shape this round's decoder reconstructs.428+/// carries one) and chroma mode, mirroring [`crate::tile`]'s `write_intra_mode`
335-fn read_intra_mode(dec: &mut SymbolDecoder, cdfs: &mut Cdfs, cfl: bool) -> Result<()> {429+/// exactly — including its skip context, which the real key-frame writer
336- if dec.symbol(&mut cdfs.skip[0]) != 0 {430+/// always writes at a fixed context of zero (it never tracks a neighbour-based
337- return Err(unsupported("a skipped block (round 2)"));431+/// one for intra blocks; that is the inter-frame writer's rule instead).
338- }432+/// Refuses a nonzero angle delta or a chroma-from-luma mode: this decoder
339- let mode = dec.symbol(&mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]]);433+/// reconstructs the thirteen luma modes at their base angle, DC-only chroma.
340- if mode != DC_PRED {434+fn read_intra_mode(
341- return Err(unsupported(format!(435+ dec: &mut SymbolDecoder,
342- "intra mode {mode} (round 1 reconstructs DC_PRED only)"436+ cdfs: &mut Cdfs,
343- )));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+ }
344 }451 }
345 let uv_mode = if cfl {452 let uv_mode = if cfl {
346 dec.symbol(&mut cdfs.uv_mode_cfl[mode])453 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
350 if uv_mode != DC_PRED {457 if uv_mode != DC_PRED {
351 return Err(unsupported("a chroma-from-luma mode (round 2)"));458 return Err(unsupported("a chroma-from-luma mode (round 2)"));
352 }459 }
353- Ok(())460+ Ok((skip, mode))
354 }461 }
355 462
356 /// One plane's reconstruction buffer, `width * height` samples, and the463 /// 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.
358 struct PlaneBuf {468 struct PlaneBuf {
359 data: Vec<u8>,469 data: Vec<u8>,
360 width: usize,470 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,
361 }477 }
362 478
363 impl PlaneBuf {479 impl PlaneBuf {
@@ -366,40 +482,58 @@ impl PlaneBuf {
366 x: usize,482 x: usize,
367 y: usize,483 y: usize,
368 side: usize,484 side: usize,
485+ reach: Reach,
369 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {486 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
370- let above = (y > 0).then(|| self.data[(y - 1) * self.width + x..][..side].to_vec());487+ let own_across = x + side.min(self.true_width.saturating_sub(x));
371- let left = (x > 0).then(|| {488+ let across = if reach.above_right {
372- (y..y + side)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)
373 .map(|row| self.data[row * self.width + x - 1])505 .map(|row| self.data[row * self.width + x - 1])
374- .collect()506+ .collect::<Vec<_>>()
375 });507 });
376 let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]);508 let corner = (x > 0 && y > 0).then(|| self.data[(y - 1) * self.width + x - 1]);
377 (above, left, corner)509 (above, left, corner)
378 }510 }
379 511
380- /// Predicts (`DC_PRED` only) then adds `residual` (side*side, raster),512+ /// Predicts under `mode` then adds `residual` (side*side, raster),
381 /// writing the clamped reconstruction back into the plane at `(x, y)`.513 /// writing the clamped reconstruction back into the plane at `(x, y)`.
382- fn reconstruct(&mut self, x: usize, y: usize, side: usize, residual: &[i32]) {514+ fn reconstruct(
383- let (above, left, _corner) = self.edges(x, y, side);515+ &mut self,
384- let dc = match (&above, &left) {516+ x: usize,
385- (None, None) => 128,517+ y: usize,
386- (Some(a), None) => {518+ side: usize,
387- let sum: u32 = a.iter().map(|&s| u32::from(s)).sum();519+ mode: usize,
388- ((sum + (a.len() as u32 >> 1)) / a.len() as u32) as i32520+ reach: Reach,
389- }521+ residual: &[i32],
390- (None, Some(l)) => {522+ ) {
391- let sum: u32 = l.iter().map(|&s| u32::from(s)).sum();523+ let (above, left, corner) = self.edges(x, y, side, reach);
392- ((sum + (l.len() as u32 >> 1)) / l.len() as u32) as i32524+ let mut prediction = vec![0u8; side * side];
393- }525+ predict(
394- (Some(a), Some(l)) => {526+ mode as u8,
395- let sum: u32 = a.iter().chain(l).map(|&s| u32::from(s)).sum();527+ above.as_deref(),
396- let count = (a.len() + l.len()) as u32;528+ left.as_deref(),
397- ((sum + (count >> 1)) / count) as i32529+ corner,
398- }530+ side,
399- };531+ &mut prediction,
532+ );
400 for row in 0..side {533 for row in 0..side {
401 for col in 0..side {534 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;
403 self.data[(y + row) * self.width + x + col] = sample;537 self.data[(y + row) * self.width + x + col] = sample;
404 }538 }
405 }539 }
@@ -416,6 +550,12 @@ fn read_plane(
416 scan: &[u16],550 scan: &[u16],
417 plane_idx: usize,551 plane_idx: usize,
418 around: (bool, bool, i32),552 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,
419 plane: &mut PlaneBuf,559 plane: &mut PlaneBuf,
420 x: usize,560 x: usize,
421 y: usize,561 y: usize,
@@ -428,7 +568,7 @@ fn read_plane(
428 } else {568 } else {
429 usize::from(around.0) + usize::from(around.1)569 usize::from(around.0) + usize::from(around.1)
430 };570 };
431- let mut coding = cdfs.txb(set, DC_PRED);571+ let mut coding = cdfs.txb(set, tx_mode);
432 let grid = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?;572 let grid = read_coeffs(dec, &mut coding, scan, skip_ctx, dc_sign_ctx(around.2))?;
433 // A 64x64 luma block's transform covers the whole 64x64 area, but only its573 // A 64x64 luma block's transform covers the whole 64x64 area, but only its
434 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the574 // top-left 32x32 of frequencies are coded (spec 5.11.40); the rest of the
@@ -444,7 +584,7 @@ fn read_plane(
444 full584 full
445 };585 };
446 let residual = dequant_and_inverse(&levels, tx_side, 8, i32::from(base_q_idx));586 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);
448 Ok(if tx_side == side {588 Ok(if tx_side == side {
449 residual_grid_placeholder(&levels, tx_side)589 residual_grid_placeholder(&levels, tx_side)
450 } else {590 } else {
@@ -481,44 +621,84 @@ fn decode_block(
481 v: &mut PlaneBuf,621 v: &mut PlaneBuf,
482 base_q_idx: u8,622 base_q_idx: u8,
483 ) -> Result<()> {623 ) -> Result<()> {
484- read_intra_mode(dec, cdfs, cfl)?;
485 let (r, c) = at;624 let (r, c) = at;
486- let around = neighbours.around(at, side / SUB);
487 let (px, py) = (c * SUB, r * SUB);625 let (px, py) = (c * SUB, r * SUB);
488- let luma_grid = read_plane(626+ let (skip, mode) = read_intra_mode(
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(
494 dec,627 dec,
495 cdfs,628 cdfs,
496- chroma_set,629+ neighbours.above_mode[c],
497- scans.1,630+ neighbours.left_mode[r],
498- 1,631+ cfl,
499- around[1],
500- u,
501- cpx,
502- cpy,
503- chroma_side,
504- chroma_tx,
505- base_q_idx,
506 )?;632 )?;
507- let v_grid = read_plane(633+ let reach = Reach::of(side, px, py, y.width, y.height);
508- dec,634+ let (luma_grid, u_grid, v_grid);
509- cdfs,635+ let (cpx, cpy) = (px / 2, py / 2);
510- chroma_set,636+ let chroma_side = side / 2;
511- scans.1,637+ if skip {
512- 2,638+ // A skipped block codes no residual syntax at all (spec 5.11.34):
513- around[2],639+ // straight prediction, on every plane.
514- v,640+ y.reconstruct(px, py, side, mode, reach, &vec![0i32; side * side]);
515- cpx,641+ u.reconstruct(
516- cpy,642+ cpx,
517- chroma_side,643+ cpy,
518- chroma_tx,644+ chroma_side,
519- base_q_idx,645+ DC_PRED,
520- )?;646+ Reach::none(),
521- neighbours.record(at, side, &[luma_grid, u_grid, v_grid]);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]);
522 Ok(())702 Ok(())
523 }703 }
524 704
@@ -526,46 +706,56 @@ fn decode_block(
526 /// returning the picture it reconstructs to.706 /// returning the picture it reconstructs to.
527 ///707 ///
528 /// `mi_cols`/`mi_rows` and `base_q_idx` are the frame header's, as parsed by708 /// `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`].
530 ///715 ///
531 /// # Errors716 /// # Errors
532-/// Returns an error when the frame is not a whole number of 64x64717+/// Returns an error when a block's partition, mode, skip flag or transform
533-/// superblocks (round 2: the partial-superblock/gathered-CDF path), when a718+/// type is anything this decoder does not reconstruct (round 2: inter, tx
534-/// block's partition, mode, skip flag or transform type is anything this719+/// types other than `DCT_DCT`, non-CDF-gathered rectangular splits below
535-/// decoder does not reconstruct (round 2: non-`DC_PRED` intra, inter, tx720+/// 16x16, a directional mode's angle delta other than zero, chroma-from-luma),
536-/// types other than `DCT_DCT`), or when the tile payload runs out of the721+/// or when the tile payload runs out of the symbols this decode expects (a
537-/// symbols this decode expects (a genuinely foreign stream).722+/// genuinely foreign stream).
538 pub fn decode_key_frame_tile(723 pub fn decode_key_frame_tile(
539 data: &[u8],724 data: &[u8],
540 mi_cols: u32,725 mi_cols: u32,
541 mi_rows: u32,726 mi_rows: u32,
542 base_q_idx: u8,727 base_q_idx: u8,
728+ frame_width: u32,
729+ frame_height: u32,
543 ) -> Result<Picture> {730 ) -> Result<Picture> {
544- if mi_cols == 0731+ if mi_cols == 0 || mi_rows == 0 {
545- || mi_rows == 0732+ return Err(unsupported("a frame with no mode-info grid"));
546- || !mi_cols.is_multiple_of(SB_MI)733+ }
547- || !mi_rows.is_multiple_of(SB_MI)734+ let (sb_cols, sb_rows) = (mi_cols.div_ceil(SB_MI), mi_rows.div_ceil(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);
554 let (cols32, rows32) = block_grid(mi_cols, mi_rows);735 let (cols32, rows32) = block_grid(mi_cols, mi_rows);
555- let width = (mi_cols * 4) as usize;736+ let (true_width, true_height) = ((mi_cols * 4) as usize, (mi_rows * 4) as usize);
556- let height = (mi_rows * 4) as usize;737+ let (width, height) = (cols32 as usize * BLOCK, rows32 as usize * BLOCK);
557 738
558 let mut y = PlaneBuf {739 let mut y = PlaneBuf {
559 data: vec![0u8; width * height],740 data: vec![0u8; width * height],
560 width,741 width,
742+ height,
743+ true_width,
744+ true_height,
561 };745 };
562 let mut u = PlaneBuf {746 let mut u = PlaneBuf {
563 data: vec![0u8; width * height / 4],747 data: vec![0u8; width * height / 4],
564 width: width / 2,748 width: width / 2,
749+ height: height / 2,
750+ true_width: true_width / 2,
751+ true_height: true_height / 2,
565 };752 };
566 let mut v = PlaneBuf {753 let mut v = PlaneBuf {
567 data: vec![0u8; width * height / 4],754 data: vec![0u8; width * height / 4],
568 width: width / 2,755 width: width / 2,
756+ height: height / 2,
757+ true_width: true_width / 2,
758+ true_height: true_height / 2,
569 };759 };
570 760
571 let scan32 = default_scan(TX32);761 let scan32 = default_scan(TX32);
@@ -574,7 +764,12 @@ pub fn decode_key_frame_tile(
574 764
575 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));765 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
576 let mut dec = SymbolDecoder::new(data);766 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+ );
578 773
579 for sb_r in 0..sb_rows {774 for sb_r in 0..sb_rows {
580 neighbours.start_row();775 neighbours.start_row();
@@ -585,12 +780,27 @@ pub fn decode_key_frame_tile(
585 sb_c * SB_MI + SB_MI / 2 < mi_cols,780 sb_c * SB_MI + SB_MI / 2 < mi_cols,
586 sb_r * SB_MI + SB_MI / 2 < mi_rows,781 sb_r * SB_MI + SB_MI / 2 < mi_rows,
587 );782 );
588- if !has_cols || !has_rows {783+ // Recomputed at this superblock's own half (spec
589- return Err(unsupported(784+ // `decode_partition`): a full alphabet symbol when both halves are
590- "a superblock half outside the true frame (round 2)",785+ // inside the true frame, a single gathered bit when just one is
591- ));786+ // (the superblock cannot be left whole, so this is forced split),
592- }787+ // and nothing at all (SPLIT inferred, no bits) when neither is —
593- let part = dec.symbol(&mut cdfs.partition_w64[ctx]);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+ };
594 match part {804 match part {
595 PARTITION_NONE => {805 PARTITION_NONE => {
596 decode_block(806 decode_block(
@@ -623,12 +833,26 @@ pub fn decode_key_frame_tile(
623 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),833 has_half(c32 * BLOCK_MI, BLOCK_MI, mi_cols),
624 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),834 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
625 );835 );
626- if !has_cols32 || !has_rows32 {836+ let part32 = if has_cols32 && has_rows32 {
627- return Err(unsupported(837+ dec.symbol(&mut cdfs.partition_w32[ctx32])
628- "a 32x32 block half outside the true frame (round 2)",838+ } else {
629- ));839+ match (has_cols32, has_rows32) {
630- }840+ (true, false) => {
631- let part32 = dec.symbol(&mut cdfs.partition_w32[ctx32]);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+ };
632 match part32 {856 match part32 {
633 PARTITION_NONE => {857 PARTITION_NONE => {
634 decode_block(858 decode_block(
@@ -709,12 +933,29 @@ pub fn decode_key_frame_tile(
709 }933 }
710 }934 }
711 935
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+ };
712 Ok(Picture {953 Ok(Picture {
713- width,954+ width: fw,
714- height,955+ height: fh,
715- y: y.data,956+ y: crop(&y, fw, fh),
716- u: u.data,957+ u: crop(&u, fw / 2, fh / 2),
717- v: v.data,958+ v: crop(&v, fw / 2, fh / 2),
718 })959 })
719 }960 }
720 961
@@ -733,41 +974,97 @@ mod tests {
733 // that path with real quantised residual, not a synthetic all-DC frame.974 // that path with real quantised residual, not a synthetic all-DC frame.
734 975
735 #[test]976 #[test]
736- fn a_frame_that_is_not_a_whole_number_of_superblocks_is_refused() {977+ fn a_frame_with_no_mode_info_grid_is_refused() {
737- assert!(decode_key_frame_tile(&[0u8; 4], 33, 32, 32).is_err());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");
738 }1013 }
739 1014
740 #[test]1015 #[test]
741 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {1016 fn real_yuv_round_trips_bit_exact_against_the_encoder_reconstruction() {
742- use crate::encode::{Encoded, Picture as Pic};
743 for (w, h) in [(128usize, 128usize), (192, 128)] {1017 for (w, h) in [(128usize, 128usize), (192, 128)] {
744- let mut source = vec![0u8; w * h];1018+ round_trips(w, h, &[DC_PRED as u8]);
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");
771 }1019 }
772 }1020 }
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+ }
773 }1070 }
crates/ec-av1/src/encode.rsmodified+5 -5
@@ -935,9 +935,9 @@ struct At {
935 /// (or below its left) are decoded depends only on where the block sits inside935 /// (or below its left) are decoded depends only on where the block sits inside
936 /// its 64x64 superblock, which is a pinned table per block size.936 /// its 64x64 superblock, which is a pinned table per block size.
937 #[derive(Clone, Copy)]937 #[derive(Clone, Copy)]
938-struct Reach {938+pub(crate) struct Reach {
939- above_right: bool,939+ pub(crate) above_right: bool,
940- below_left: bool,940+ pub(crate) below_left: bool,
941 }941 }
942 942
943 /// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in943 /// `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]];
955 impl Reach {955 impl Reach {
956 /// What a block of `side` samples at `(x, y)` may read past its own edges,956 /// What a block of `side` samples at `(x, y)` may read past its own edges,
957 /// in a frame of `width` by `height`.957 /// 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 {
959 Self {959 Self {
960 above_right: y > 0 && x + side < width && Self::top_right(side, x, y),960 above_right: y > 0 && x + side < width && Self::top_right(side, x, y),
961 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y),961 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y),
@@ -964,7 +964,7 @@ impl Reach {
964 964
965 /// Neither, which is all a mode that reads no further than its own edges965 /// Neither, which is all a mode that reads no further than its own edges
966 /// needs.966 /// needs.
967- fn none() -> Self {967+ pub(crate) fn none() -> Self {
968 Self {968 Self {
969 above_right: false,969 above_right: false,
970 below_left: false,970 below_left: false,