forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1real': the unread use_filter_intra bit, CfL, real-stream exactness

Browse files at this commit

588c3e4e4b1939aa55e9406b844ea6346bc80935Ahmet Kaan GümüşParent: b5e06f8beeeec5
Eleven rounds: CDEF/TxMode::Select/screen-content/delta/segmentation are
named refusals instead of silent miscodes; CfL prediction landed; the
pinned real libaom stream decodes pixel-exact on all planes. The root
cause was one unread flag bit that every same-transcription oracle
validated — only a foreign implementation (debug aomdec) could see it.
crates/ec-av1/src/cdf.rsmodified+52 -0
@@ -305,6 +305,58 @@ pub const UV_MODE_CFL: [[u16; 15]; 13] = [
305305 ],
306306 ];
307307
308+/// `Default_Cfl_Sign_Cdf` (spec 9.4): the joint sign of a `UV_CFL_PRED`
309+/// block's U/V alpha (spec 5.11.45's `cfl_alpha_signs`) — libaom's
310+/// `default_cfl_sign_cdf` (entropymode.c), whose `AOM_CDF8(a0..a6)` arguments
311+/// are this convention's cumulative points verbatim (only the *storage*, not
312+/// the spec's own table, is `AOM_ICDF`-inverted).
313+pub const CFL_SIGN: [u16; 9] = [1418, 2123, 13340, 18405, 26972, 28343, 32294, 32768, 0];
314+
315+/// `default_filter_intra_cdfs` (entropymode.c), the `use_filter_intra` flag's
316+/// prior, indexed by block-size class: `[0]`=4x4, `[1]`=8x8, `[2]`=16x16,
317+/// `[3]`=32x32 -- the only square sizes `av1_filter_intra_allowed_bsize`
318+/// (width and height both <=32) ever offers this decoder's square blocks.
319+pub const FILTER_INTRA: [[u16; 3]; 4] = [
320+ [4621, 32768, 0],
321+ [7866, 32768, 0],
322+ [12408, 32768, 0],
323+ [22343, 32768, 0],
324+];
325+/// `default_filter_intra_mode_cdf` (entropymode.c): which of the five
326+/// `FILTER_INTRA_MODES` a `use_filter_intra` block picks.
327+pub const FILTER_INTRA_MODE: [u16; 6] = [8949, 12776, 17211, 29558, 32768, 0];
328+
329+/// `Default_Cfl_Alpha_Cdf` (spec 9.4): a `UV_CFL_PRED` block's per-plane
330+/// alpha magnitude (spec 5.11.45's `cfl_alpha_u`/`cfl_alpha_v`), indexed by
331+/// the joint sign's context (`CFL_CONTEXT_U`/`CFL_CONTEXT_V`,
332+/// libaom's cfl.h) — libaom's `default_cfl_alpha_cdf`.
333+pub const CFL_ALPHA: [[u16; 17]; 6] = [
334+ [
335+ 7637, 20719, 31401, 32481, 32657, 32688, 32692, 32696, 32700, 32704, 32708, 32712, 32716,
336+ 32720, 32724, 32768, 0,
337+ ],
338+ [
339+ 14365, 23603, 28135, 31168, 32167, 32395, 32487, 32573, 32620, 32647, 32668, 32672, 32676,
340+ 32680, 32684, 32768, 0,
341+ ],
342+ [
343+ 11532, 22380, 28445, 31360, 32349, 32523, 32584, 32649, 32673, 32677, 32681, 32685, 32689,
344+ 32693, 32697, 32768, 0,
345+ ],
346+ [
347+ 26990, 31402, 32282, 32571, 32692, 32696, 32700, 32704, 32708, 32712, 32716, 32720, 32724,
348+ 32728, 32732, 32768, 0,
349+ ],
350+ [
351+ 17248, 26058, 28904, 30608, 31305, 31877, 32126, 32321, 32394, 32464, 32516, 32560, 32576,
352+ 32593, 32622, 32768, 0,
353+ ],
354+ [
355+ 14738, 21678, 25779, 27901, 29024, 30302, 30980, 31843, 32144, 32413, 32520, 32594, 32622,
356+ 32656, 32660, 32768, 0,
357+ ],
358+];
359+
308360 /// `Default_Txb_Skip_Cdf[2][3][0]` (spec 9.4): the all-zero flag of a 32x32
309361 /// luma transform block that covers its whole plane block, which is context 0.
310362 pub const TXB_SKIP_LUMA_32: [u16; 3] = [30669, 32768, 0];
crates/ec-av1/src/cdf_state.rsmodified+13 -0
@@ -98,6 +98,10 @@ pub(crate) struct Cdfs {
9898 pub uv_mode_no_cfl: [[u16; 14]; 13],
9999 /// The chroma mode of a block that is offered it.
100100 pub uv_mode_cfl: [[u16; 15]; 13],
101+ /// The joint sign of a `UV_CFL_PRED` block's U/V alpha.
102+ pub cfl_sign: [u16; 9],
103+ /// A `UV_CFL_PRED` block's per-plane alpha magnitude, by joint-sign context.
104+ pub cfl_alpha: [[u16; 17]; 6],
101105 /// The angle a directional mode is nudged by.
102106 pub angle_delta: [[u16; 8]; 8],
103107 /// The one-context all-zero flag of a 16x16 luma transform.
@@ -235,6 +239,11 @@ pub(crate) struct Cdfs {
235239 /// The two motion vector components' own tables: separate owned state,
236240 /// since spec 8.3.2 adapts one component without touching the other.
237241 pub mv_comp: [MvComponentCdfs; 2],
242+ /// The `use_filter_intra` flag, indexed by block-size class (`[0]`=4x4,
243+ /// `[1]`=8x8, `[2]`=16x16, `[3]`=32x32) -- see [`cdf::FILTER_INTRA`].
244+ pub filter_intra: [[u16; 3]; 4],
245+ /// Which `FILTER_INTRA_MODES` entry a `use_filter_intra` block picks.
246+ pub filter_intra_mode: [u16; 6],
238247 }
239248
240249 /// One motion vector component's adapting state (spec 9.4's `Default_Mv_*`,
@@ -297,6 +306,8 @@ impl Cdfs {
297306 kf_y_mode: cdf::KF_Y_MODE,
298307 uv_mode_no_cfl: cdf::UV_MODE_NO_CFL,
299308 uv_mode_cfl: cdf::UV_MODE_CFL,
309+ cfl_sign: cdf::CFL_SIGN,
310+ cfl_alpha: cdf::CFL_ALPHA,
300311 angle_delta: cdf::ANGLE_DELTA,
301312 txb_skip_luma_16: [pick(
302313 q_ctx,
@@ -637,6 +648,8 @@ impl Cdfs {
637648 drl_mode: cdf::DRL_MODE,
638649 mv_joint: cdf::MV_JOINT,
639650 mv_comp: [MvComponentCdfs::new(), MvComponentCdfs::new()],
651+ filter_intra: cdf::FILTER_INTRA,
652+ filter_intra_mode: cdf::FILTER_INTRA_MODE,
640653 }
641654 }
642655
crates/ec-av1/src/decode.rsmodified+304 -32
@@ -201,11 +201,18 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables) -> usize {
201201 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
202202 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
203203
204+ let trace = std::env::var_os("EC_AV1_TRACE").is_some();
204205 let group = dec.symbol(coding.eob_pt) + 1;
206+ if trace {
207+ eprintln!("TRACE eob_pt value={group}");
208+ }
205209 let bits = OFFSET_BITS[group];
206210 let mut offset = 0u32;
207211 if bits > 0 {
208212 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
213+ if trace {
214+ eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
215+ }
209216 offset = top << (bits - 1);
210217 if bits > 1 {
211218 offset |= dec.literal(bits - 1);
@@ -232,31 +239,53 @@ fn read_coeffs(
232239 skip_ctx: usize,
233240 sign_ctx: usize,
234241 ) -> Result<(Vec<i32>, TxType)> {
242+ let trace = std::env::var_os("EC_AV1_TRACE").is_some();
235243 let side = coding.side;
236244 let mut grid = vec![0i32; side * side];
237245 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
246+ if trace {
247+ eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
248+ }
238249 if all_zero {
239250 return Ok((grid, TxType::DctDct));
240251 }
241252 let mut tx_type = TxType::DctDct;
242253 if let Some(tx_type_cdf) = coding.tx_type.as_deref_mut() {
243254 let t = dec.symbol(tx_type_cdf);
255+ if trace {
256+ eprintln!("TRACE tx_type value={t}");
257+ }
244258 tx_type = TxType::from_symbol(t).ok_or_else(|| {
245259 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
246260 })?;
247261 }
248262
249263 let eob = read_eob(dec, coding);
264+ if trace {
265+ eprintln!("TRACE eob value={eob}");
266+ }
250267 let mut levels = vec![0i32; side * side];
251268 for scan_idx in (0..eob).rev() {
252269 let pos = scan[scan_idx] as usize;
253270 let (row, col) = (pos / side, pos % side);
254271 let level = if scan_idx == eob - 1 {
255272 let ctx = eob_coeff_ctx(scan_idx, side * side);
256- dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1
273+ let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
274+ if trace {
275+ eprintln!(
276+ "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
277+ );
278+ }
279+ v
257280 } else {
258281 let ctx = base_ctx(&levels, side, row, col);
259- dec.symbol(&mut coding.base[ctx]) as i32
282+ let v = dec.symbol(&mut coding.base[ctx]) as i32;
283+ if trace {
284+ eprintln!(
285+ "TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
286+ );
287+ }
288+ v
260289 };
261290 let level = if level > NUM_BASE_LEVELS {
262291 let ctx = br_ctx(&levels, side, row, col);
@@ -264,6 +293,11 @@ fn read_coeffs(
264293 let mut sent = 0;
265294 loop {
266295 let k = dec.symbol(&mut coding.br[ctx]) as i32;
296+ if trace {
297+ eprintln!(
298+ "TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}"
299+ );
300+ }
267301 level += k;
268302 sent += BR_STEP;
269303 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
@@ -283,12 +317,20 @@ fn read_coeffs(
283317 continue;
284318 }
285319 let negative = if pos == 0 {
286- dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1
320+ let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
321+ if trace {
322+ eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
323+ }
324+ v
287325 } else {
288326 dec.literal(1) == 1
289327 };
290328 let level = if level.abs_diff(0) as i32 > MAX_BR_LEVEL {
291- level + read_golomb(dec)? as i32
329+ let g = read_golomb(dec)?;
330+ if trace {
331+ eprintln!("TRACE golomb pos={pos} value={g}");
332+ }
333+ level + g as i32
292334 } else {
293335 level
294336 };
@@ -510,20 +552,49 @@ impl Neighbours {
510552 /// exactly — including its skip context, which the real key-frame writer
511553 /// always writes at a fixed context of zero (it never tracks a neighbour-based
512554 /// one for intra blocks; that is the inter-frame writer's rule instead).
513-/// Refuses a nonzero angle delta or a chroma-from-luma mode: this decoder
514-/// reconstructs the thirteen luma modes at their base angle, DC-only chroma.
555+/// Refuses a nonzero angle delta: this decoder reconstructs the thirteen
556+/// luma modes at their base angle only. Chroma is DC-only or, where CFL is
557+/// offered (`cfl`, `is_cfl_allowed`, spec 5.11.5), chroma-from-luma -- the
558+/// third element carries that mode's `(alpha_q3_u, alpha_q3_v)`, `None` for
559+/// plain DC chroma.
560+/// A block-size class index into [`cdf::FILTER_INTRA`]/`Cdfs::filter_intra`,
561+/// or `None` when `side` is past `av1_filter_intra_allowed_bsize`'s <=32
562+/// bound (spec `filter_intra_mode_info` never reads a symbol there).
563+fn filter_intra_size_class(side: usize) -> Option<usize> {
564+ match side {
565+ 4 => Some(0),
566+ 8 => Some(1),
567+ 16 => Some(2),
568+ 32 => Some(3),
569+ _ => None,
570+ }
571+}
572+
515573 fn read_intra_mode(
516574 dec: &mut SymbolDecoder,
517575 cdfs: &mut Cdfs,
518576 above_mode: usize,
519577 left_mode: usize,
520578 cfl: bool,
521-) -> Result<(bool, usize)> {
579+ side: usize,
580+ enable_filter_intra: bool,
581+) -> Result<(bool, usize, Option<(i32, i32)>)> {
582+ let trace = std::env::var_os("EC_AV1_TRACE").is_some();
522583 let skip = dec.symbol(&mut cdfs.skip[0]) != 0;
523- let mode =
524- dec.symbol(&mut cdfs.kf_y_mode[INTRA_MODE_CTX[above_mode]][INTRA_MODE_CTX[left_mode]]);
584+ if trace {
585+ eprintln!("TRACE skip value={}", skip as i32);
586+ }
587+ let above_ctx = INTRA_MODE_CTX[above_mode];
588+ let left_ctx = INTRA_MODE_CTX[left_mode];
589+ let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
590+ if trace {
591+ eprintln!("TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode}");
592+ }
525593 if (V_PRED..=D67_PRED).contains(&mode) {
526594 let angle = dec.symbol(&mut cdfs.angle_delta[mode - V_PRED]);
595+ if trace {
596+ eprintln!("TRACE angle_delta value={angle}");
597+ }
527598 if angle != ANGLE_DELTA_ZERO {
528599 return Err(unsupported(
529600 "a nonzero angle delta (this encoder never writes one)",
@@ -535,10 +606,118 @@ fn read_intra_mode(
535606 } else {
536607 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
537608 };
538- if uv_mode != DC_PRED {
539- return Err(unsupported("a chroma-from-luma mode (round 2)"));
609+ if trace {
610+ eprintln!("TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode}");
611+ }
612+ let alpha = if uv_mode == DC_PRED {
613+ None
614+ } else if cfl && uv_mode == UV_CFL_PRED {
615+ Some(read_cfl_alphas(dec, cdfs))
616+ } else {
617+ return Err(unsupported("a directional chroma mode (round 2)"));
618+ };
619+ // `read_filter_intra_mode_info` (spec 5.11.14, libaom decodemv.c): a
620+ // `use_filter_intra` symbol this decoder never read at all until
621+ // lane-av1real r10 -- silently skipping it left every bit past a
622+ // DC_PRED block at <=32x32 read one symbol short of libaom for the rest
623+ // of the tile (the pinned CfL stream's actual bug: partition/skip/mode
624+ // matched bit-exact, then `eob_pt` read 5 instead of 6, because this
625+ // symbol's bits were never consumed).
626+ if mode == DC_PRED
627+ && enable_filter_intra
628+ && let Some(class) = filter_intra_size_class(side)
629+ {
630+ let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
631+ if trace {
632+ eprintln!(
633+ "TRACE use_filter_intra side={side} value={}",
634+ use_filter_intra as i32
635+ );
636+ }
637+ if use_filter_intra {
638+ // libaom still reads `filter_intra_mode` to stay in sync, but
639+ // this decoder does not implement filter-intra prediction
640+ // (spec 7.11.2.3's 5-tap recursive filter) -- refuse rather
641+ // than silently miscode the reconstruction, the same pattern
642+ // as this crate's other `Error::unsupported` refusals.
643+ let _ = dec.symbol(&mut cdfs.filter_intra_mode);
644+ return Err(unsupported(
645+ "a filter-intra block (this decoder does not implement the 5.11.14 recursive predictor)",
646+ ));
647+ }
648+ }
649+ Ok((skip, mode, alpha))
650+}
651+
652+/// `UV_CFL_PRED` (spec 6.10.19's chroma intra mode enum): the fourteenth
653+/// entry of [`crate::cdf::UV_MODE_CFL`], one past the thirteen ordinary
654+/// intra modes.
655+const UV_CFL_PRED: usize = 13;
656+
657+/// `read_cfl_alphas` (libaom decodemv.c): the joint sign symbol (8-ary, spec
658+/// 5.11.45's `cfl_alpha_signs`), then each plane's alpha magnitude symbol
659+/// (16-ary, `cfl_alpha_u`/`cfl_alpha_v`) where its sign is nonzero -- context
660+/// indices `CFL_CONTEXT_U`/`CFL_CONTEXT_V` (libaom cfl.h) derived from the
661+/// joint sign the same way. Returns each plane's final signed `alpha_q3`
662+/// (`cfl_idx_to_alpha`, cfl.c): magnitude `idx + 1`, sign-zero collapsing to 0.
663+fn read_cfl_alphas(dec: &mut SymbolDecoder, cdfs: &mut Cdfs) -> (i32, i32) {
664+ let joint_sign = dec.symbol(&mut cdfs.cfl_sign) as i32;
665+ let sign_u = ((joint_sign + 1) * 11) >> 5;
666+ let sign_v = (joint_sign + 1) - 3 * sign_u;
667+ let alpha_u = if sign_u == 0 {
668+ 0
669+ } else {
670+ let ctx_u = (joint_sign + 1 - 3) as usize;
671+ let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_u]) as i32 + 1;
672+ if sign_u == 2 { mag } else { -mag }
673+ };
674+ let alpha_v = if sign_v == 0 {
675+ 0
676+ } else {
677+ let ctx_v = (sign_v * 3 + sign_u - 3) as usize;
678+ let mag = dec.symbol(&mut cdfs.cfl_alpha[ctx_v]) as i32 + 1;
679+ if sign_v == 2 { mag } else { -mag }
680+ };
681+ (alpha_u, alpha_v)
682+}
683+
684+/// `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` (libaom cfl.c):
685+/// the reconstructed luma samples under a `side`-square block, subsampled
686+/// 4:2:0 to Q3 (`(a+b+c+d) << 1`, each 2x2 group), then block-average
687+/// subtracted (`round_offset = num_pel/2`, right-shifted by `log2(num_pel)`)
688+/// to give the AC values [`cfl_scaled`] scales by alpha.
689+fn cfl_ac_q3(y: &PlaneBuf, px: usize, py: usize, side: usize) -> Vec<i32> {
690+ let cside = side / 2;
691+ let mut ac = vec![0i32; cside * cside];
692+ let mut sum = 0i32;
693+ for cy in 0..cside {
694+ for cx in 0..cside {
695+ let (lx, ly) = (px + cx * 2, py + cy * 2);
696+ let q3 = (i32::from(y.data[ly * y.width + lx])
697+ + i32::from(y.data[ly * y.width + lx + 1])
698+ + i32::from(y.data[(ly + 1) * y.width + lx])
699+ + i32::from(y.data[(ly + 1) * y.width + lx + 1]))
700+ << 1;
701+ ac[cy * cside + cx] = q3;
702+ sum += q3;
703+ }
704+ }
705+ let num_pel = (cside * cside) as i32;
706+ let avg = (sum + num_pel / 2) >> num_pel.trailing_zeros();
707+ ac.iter_mut().for_each(|v| *v -= avg);
708+ ac
709+}
710+
711+/// `get_scaled_luma_q0` (libaom cfl.h): `alpha_q3 * ac_q3`, rounded from Q6
712+/// back to whole samples with `ROUND_POWER_OF_TWO_SIGNED` (round-to-nearest,
713+/// ties away from zero on the shifted-out sign).
714+fn cfl_scaled(alpha_q3: i32, ac_q3: i32) -> i32 {
715+ let v = alpha_q3 * ac_q3;
716+ if v >= 0 {
717+ (v + 32) >> 6
718+ } else {
719+ -((-v + 32) >> 6)
540720 }
541- Ok((skip, mode))
542721 }
543722
544723 /// One plane's reconstruction buffer, `width * height` samples, and the
@@ -592,6 +771,10 @@ impl PlaneBuf {
592771
593772 /// Predicts under `mode` then adds `residual` (side*side, raster),
594773 /// writing the clamped reconstruction back into the plane at `(x, y)`.
774+ /// `cfl`, when `Some((alpha_q3, ac_q3))` (a `UV_CFL_PRED` chroma block),
775+ /// nudges the prediction by [`cfl_scaled`]'s per-sample amount before the
776+ /// residual is added — `av1_cfl_predict_block`'s own clip-then-add-residual
777+ /// order (cfl.c).
595778 fn reconstruct(
596779 &mut self,
597780 x: usize,
@@ -600,6 +783,7 @@ impl PlaneBuf {
600783 mode: usize,
601784 reach: Reach,
602785 residual: &[i32],
786+ cfl: Option<(i32, &[i32])>,
603787 ) {
604788 let (above, left, corner) = self.edges(x, y, side, reach);
605789 let mut prediction = vec![0u8; side * side];
@@ -613,8 +797,12 @@ impl PlaneBuf {
613797 );
614798 for row in 0..side {
615799 for col in 0..side {
616- let sample = (i32::from(prediction[row * side + col]) + residual[row * side + col])
617- .clamp(0, 255) as u8;
800+ let idx = row * side + col;
801+ let mut base = i32::from(prediction[idx]);
802+ if let Some((alpha_q3, ac_q3)) = cfl {
803+ base = (base + cfl_scaled(alpha_q3, ac_q3[idx])).clamp(0, 255);
804+ }
805+ let sample = (base + residual[idx]).clamp(0, 255) as u8;
618806 self.data[(y + row) * self.width + x + col] = sample;
619807 }
620808 }
@@ -643,6 +831,7 @@ fn read_plane(
643831 side: usize,
644832 tx_side: usize,
645833 base_q_idx: u8,
834+ cfl: Option<(i32, &[i32])>,
646835 ) -> Result<Vec<i32>> {
647836 let skip_ctx = if plane_idx == 0 {
648837 0
@@ -669,7 +858,14 @@ fn read_plane(
669858 full
670859 };
671860 let residual = dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), tx_type);
672- plane.reconstruct(x, y, side, predict_mode, reach, &residual);
861+ if std::env::var_os("EC_AV1_TRACE").is_some() {
862+ eprintln!(
863+ "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} levels[0..4]={:?} residual[0..4]={:?}",
864+ &levels[..4.min(levels.len())],
865+ &residual[..4.min(residual.len())]
866+ );
867+ }
868+ plane.reconstruct(x, y, side, predict_mode, reach, &residual, cfl);
673869 Ok(if tx_side == side {
674870 residual_grid_placeholder(&levels, side)
675871 } else {
@@ -705,15 +901,18 @@ fn decode_block(
705901 u: &mut PlaneBuf,
706902 v: &mut PlaneBuf,
707903 base_q_idx: u8,
904+ enable_filter_intra: bool,
708905 ) -> Result<()> {
709906 let (r, c) = at;
710907 let (px, py) = (c * SUB, r * SUB);
711- let (skip, mode) = read_intra_mode(
908+ let (skip, mode, alpha) = read_intra_mode(
712909 dec,
713910 cdfs,
714911 neighbours.above_mode[c],
715912 neighbours.left_mode[r],
716913 cfl,
914+ side,
915+ enable_filter_intra,
717916 )?;
718917 let reach = Reach::of(side, px, py, y.width, y.height);
719918 let (luma_grid, u_grid, v_grid);
@@ -722,7 +921,8 @@ fn decode_block(
722921 if skip {
723922 // A skipped block codes no residual syntax at all (spec 5.11.34):
724923 // straight prediction, on every plane.
725- y.reconstruct(px, py, side, mode, reach, &vec![0i32; side * side]);
924+ y.reconstruct(px, py, side, mode, reach, &vec![0i32; side * side], None);
925+ let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
726926 u.reconstruct(
727927 cpx,
728928 cpy,
@@ -730,6 +930,7 @@ fn decode_block(
730930 DC_PRED,
731931 Reach::none(),
732932 &vec![0i32; chroma_side * chroma_side],
933+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
733934 );
734935 v.reconstruct(
735936 cpx,
@@ -738,6 +939,7 @@ fn decode_block(
738939 DC_PRED,
739940 Reach::none(),
740941 &vec![0i32; chroma_side * chroma_side],
942+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
741943 );
742944 luma_grid = vec![0i32; side * side];
743945 u_grid = vec![0i32; chroma_side * chroma_side];
@@ -746,8 +948,9 @@ fn decode_block(
746948 let around = neighbours.around(at, side);
747949 luma_grid = read_plane(
748950 dec, cdfs, luma_set, scans.0, 0, around[0], mode, mode, reach, y, px, py, side,
749- luma_tx, base_q_idx,
951+ luma_tx, base_q_idx, None,
750952 )?;
953+ let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
751954 u_grid = read_plane(
752955 dec,
753956 cdfs,
@@ -764,6 +967,7 @@ fn decode_block(
764967 chroma_side,
765968 chroma_tx,
766969 base_q_idx,
970+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
767971 )?;
768972 v_grid = read_plane(
769973 dec,
@@ -781,6 +985,7 @@ fn decode_block(
781985 chroma_side,
782986 chroma_tx,
783987 base_q_idx,
988+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
784989 )?;
785990 }
786991 neighbours.record(at, side, mode, &[luma_grid, u_grid, v_grid]);
@@ -809,6 +1014,7 @@ fn decode_leaf8(
8091014 u: &mut PlaneBuf,
8101015 v: &mut PlaneBuf,
8111016 base_q_idx: u8,
1017+ enable_filter_intra: bool,
8121018 ) -> Result<usize> {
8131019 let (r, c) = outer_at;
8141020 let mut above_mode = neighbours.above_mode[c];
@@ -823,15 +1029,40 @@ fn decode_leaf8(
8231029 // An 8x8 leaf is well within `is_cfl_allowed`'s <=32x32 bound (spec
8241030 // 5.11.5), so it reads the CFL-allowed `uv_mode_cfl` CDF, like every other
8251031 // `decode_block` caller at 16x16 and up.
826- let (skip, mode) = read_intra_mode(dec, cdfs, above_mode, left_mode, true)?;
1032+ let (skip, mode, alpha) = read_intra_mode(
1033+ dec,
1034+ cdfs,
1035+ above_mode,
1036+ left_mode,
1037+ true,
1038+ 8,
1039+ enable_filter_intra,
1040+ )?;
8271041 let (px, py) = (leaf_mi.1 * MI, leaf_mi.0 * MI);
8281042 let reach = Reach::of(8, px, py, y.width, y.height);
8291043 let (cpx, cpy) = (px / 2, py / 2);
8301044 let (luma_grid, u_grid, v_grid);
8311045 if skip {
832- y.reconstruct(px, py, 8, mode, reach, &vec![0i32; 64]);
833- u.reconstruct(cpx, cpy, 4, DC_PRED, Reach::none(), &vec![0i32; 16]);
834- v.reconstruct(cpx, cpy, 4, DC_PRED, Reach::none(), &vec![0i32; 16]);
1046+ y.reconstruct(px, py, 8, mode, reach, &vec![0i32; 64], None);
1047+ let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
1048+ u.reconstruct(
1049+ cpx,
1050+ cpy,
1051+ 4,
1052+ DC_PRED,
1053+ Reach::none(),
1054+ &vec![0i32; 16],
1055+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
1056+ );
1057+ v.reconstruct(
1058+ cpx,
1059+ cpy,
1060+ 4,
1061+ DC_PRED,
1062+ Reach::none(),
1063+ &vec![0i32; 16],
1064+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
1065+ );
8351066 luma_grid = vec![0i32; 64];
8361067 u_grid = vec![0i32; 16];
8371068 v_grid = vec![0i32; 16];
@@ -853,7 +1084,9 @@ fn decode_leaf8(
8531084 8,
8541085 TX8,
8551086 base_q_idx,
1087+ None,
8561088 )?;
1089+ let ac = alpha.map(|_| cfl_ac_q3(y, px, py, 8));
8571090 u_grid = read_plane(
8581091 dec,
8591092 cdfs,
@@ -870,6 +1103,7 @@ fn decode_leaf8(
8701103 4,
8711104 TX4,
8721105 base_q_idx,
1106+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
8731107 )?;
8741108 v_grid = read_plane(
8751109 dec,
@@ -887,6 +1121,7 @@ fn decode_leaf8(
8871121 4,
8881122 TX4,
8891123 base_q_idx,
1124+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
8901125 )?;
8911126 }
8921127 neighbours.record_mi(leaf_mi, 8, &[luma_grid, u_grid, v_grid]);
@@ -918,6 +1153,7 @@ pub fn decode_key_frame_tile(
9181153 base_q_idx: u8,
9191154 frame_width: u32,
9201155 frame_height: u32,
1156+ enable_filter_intra: bool,
9211157 ) -> Result<Picture> {
9221158 if mi_cols == 0 || mi_rows == 0 {
9231159 return Err(unsupported("a frame with no mode-info grid"));
@@ -955,6 +1191,13 @@ pub fn decode_key_frame_tile(
9551191 let scan4 = default_scan(TX4);
9561192
9571193 let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
1194+ if std::env::var_os("EC_AV1_TRACE").is_some() {
1195+ eprintln!(
1196+ "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
1197+ data.len(),
1198+ &data[..data.len().min(8)]
1199+ );
1200+ }
9581201 let mut dec = SymbolDecoder::new(data);
9591202 let mut neighbours = Neighbours::new(
9601203 cols32 as usize * 2,
@@ -980,7 +1223,11 @@ pub fn decode_key_frame_tile(
9801223 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
9811224 // three-way write exactly.
9821225 let part = if has_cols && has_rows {
983- dec.symbol(&mut cdfs.partition_w64[ctx])
1226+ let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
1227+ if std::env::var_os("EC_AV1_TRACE").is_some() {
1228+ eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
1229+ }
1230+ p
9841231 } else {
9851232 match (has_cols, has_rows) {
9861233 (true, false) => {
@@ -1011,6 +1258,7 @@ pub fn decode_key_frame_tile(
10111258 &mut u,
10121259 &mut v,
10131260 base_q_idx,
1261+ enable_filter_intra,
10141262 )?;
10151263 }
10161264 PARTITION_SPLIT => {
@@ -1026,7 +1274,11 @@ pub fn decode_key_frame_tile(
10261274 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
10271275 );
10281276 let part32 = if has_cols32 && has_rows32 {
1029- dec.symbol(&mut cdfs.partition_w32[ctx32])
1277+ let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
1278+ if std::env::var_os("EC_AV1_TRACE").is_some() {
1279+ eprintln!("TRACE partition_w32 ctx={ctx32} value={p}");
1280+ }
1281+ p
10301282 } else {
10311283 match (has_cols32, has_rows32) {
10321284 (true, false) => {
@@ -1063,6 +1315,7 @@ pub fn decode_key_frame_tile(
10631315 &mut u,
10641316 &mut v,
10651317 base_q_idx,
1318+ enable_filter_intra,
10661319 )?;
10671320 }
10681321 PARTITION_SPLIT => {
@@ -1099,6 +1352,7 @@ pub fn decode_key_frame_tile(
10991352 &mut u,
11001353 &mut v,
11011354 base_q_idx,
1355+ enable_filter_intra,
11021356 )?;
11031357 continue;
11041358 }
@@ -1141,6 +1395,7 @@ pub fn decode_key_frame_tile(
11411395 &mut u,
11421396 &mut v,
11431397 base_q_idx,
1398+ enable_filter_intra,
11441399 )?;
11451400 prev_leaf = Some((leaf_mi, leaf_mode));
11461401 }
@@ -1202,6 +1457,7 @@ pub fn decode_key_frame_tile(
12021457 &mut u,
12031458 &mut v,
12041459 base_q_idx,
1460+ enable_filter_intra,
12051461 )?;
12061462 prev_leaf = Some((leaf_mi, leaf_mode));
12071463 }
@@ -1641,9 +1897,13 @@ fn decode_inter_block(
16411897 }
16421898 }
16431899 let uv_mode = dec.symbol(&mut cdfs.uv_mode_cfl[mode]);
1644- if uv_mode != DC_PRED {
1645- return Err(unsupported("a chroma-from-luma mode (round 2)"));
1646- }
1900+ let alpha = if uv_mode == DC_PRED {
1901+ None
1902+ } else if uv_mode == UV_CFL_PRED {
1903+ Some(read_cfl_alphas(dec, cdfs))
1904+ } else {
1905+ return Err(unsupported("a directional chroma mode (round 2)"));
1906+ };
16471907 mode_for_tx = mode;
16481908 let (mi_row, mi_col) = (r * SUB_MI as usize, c * SUB_MI as usize);
16491909 for dr in 0..side / 4 {
@@ -1664,7 +1924,8 @@ fn decode_inter_block(
16641924
16651925 let reach = Reach::of(side, px, py, y.width, y.height);
16661926 if skip {
1667- y.reconstruct(px, py, side, mode, reach, &vec![0i32; side * side]);
1927+ y.reconstruct(px, py, side, mode, reach, &vec![0i32; side * side], None);
1928+ let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
16681929 u.reconstruct(
16691930 cpx,
16701931 cpy,
@@ -1672,6 +1933,7 @@ fn decode_inter_block(
16721933 DC_PRED,
16731934 Reach::none(),
16741935 &vec![0i32; chroma_side * chroma_side],
1936+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
16751937 );
16761938 v.reconstruct(
16771939 cpx,
@@ -1680,6 +1942,7 @@ fn decode_inter_block(
16801942 DC_PRED,
16811943 Reach::none(),
16821944 &vec![0i32; chroma_side * chroma_side],
1945+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
16831946 );
16841947 luma_grid = vec![0i32; side * side];
16851948 u_grid = vec![0i32; chroma_side * chroma_side];
@@ -1702,7 +1965,9 @@ fn decode_inter_block(
17021965 side,
17031966 luma_tx,
17041967 base_q_idx,
1968+ None,
17051969 )?;
1970+ let ac = alpha.map(|_| cfl_ac_q3(y, px, py, side));
17061971 u_grid = read_plane(
17071972 dec,
17081973 cdfs,
@@ -1719,6 +1984,7 @@ fn decode_inter_block(
17191984 chroma_side,
17201985 chroma_tx,
17211986 base_q_idx,
1987+ alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)),
17221988 )?;
17231989 v_grid = read_plane(
17241990 dec,
@@ -1736,6 +2002,7 @@ fn decode_inter_block(
17362002 chroma_side,
17372003 chroma_tx,
17382004 base_q_idx,
2005+ alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)),
17392006 )?;
17402007 }
17412008 }
@@ -2012,7 +2279,7 @@ mod tests {
20122279
20132280 #[test]
20142281 fn a_frame_with_no_mode_info_grid_is_refused() {
2015- assert!(decode_key_frame_tile(&[0u8; 4], 0, 32, 32, 0, 128).is_err());
2282+ assert!(decode_key_frame_tile(&[0u8; 4], 0, 32, 32, 0, 128, false).is_err());
20162283 }
20172284
20182285 /// Encodes and decodes one picture with `modes`, asserting the decoder's
@@ -2040,8 +2307,10 @@ mod tests {
20402307 base_q_idx,
20412308 ..
20422309 }: Encoded = crate::encode::encode_key_frame_with_modes(&picture, 40, 0.0, modes).unwrap();
2043- let decoded =
2044- decode_key_frame_tile(&tile, mi_cols, mi_rows, base_q_idx, w as u32, h as u32).unwrap();
2310+ let decoded = decode_key_frame_tile(
2311+ &tile, mi_cols, mi_rows, base_q_idx, w as u32, h as u32, false,
2312+ )
2313+ .unwrap();
20452314 assert_eq!(decoded.width, w, "{w}x{h}: decoded width");
20462315 assert_eq!(decoded.height, h, "{w}x{h}: decoded height");
20472316 assert_eq!(decoded.y, reconstruction.y, "{w}x{h} luma mismatch");
@@ -2111,7 +2380,7 @@ mod tests {
21112380 );
21122381 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
21132382 let data = enc.finish();
2114- let decoded = decode_key_frame_tile(&data, 16, 16, 40, 64, 64).unwrap();
2383+ let decoded = decode_key_frame_tile(&data, 16, 16, 40, 64, 64, false).unwrap();
21152384 assert!(
21162385 decoded.y.iter().all(|&s| s == 128),
21172386 "a skipped DC_PRED block with no neighbours predicts flat mid-grey"
@@ -2290,6 +2559,7 @@ mod tests {
22902559 encoded.base_q_idx,
22912560 coded_w,
22922561 coded_h,
2562+ false,
22932563 )
22942564 .unwrap();
22952565 assert_eq!(ours.y, ffmpeg_decoded.y, "{width}x{height}: luma vs ffmpeg");
@@ -2357,6 +2627,7 @@ mod tests {
23572627 key.base_q_idx,
23582628 width as u32,
23592629 height as u32,
2630+ false,
23602631 )
23612632 .unwrap();
23622633 assert_eq!(
@@ -2623,6 +2894,7 @@ mod tests {
26232894 key.base_q_idx,
26242895 coded_w,
26252896 coded_h,
2897+ false,
26262898 )
26272899 .unwrap();
26282900 assert_eq!(reference.y, ffmpeg_frames[0].y, "frame 0 luma vs ffmpeg");
crates/ec-av1/src/stream.rsmodified+117 -3
@@ -10,7 +10,7 @@
1010 //! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is
1111 //! an implementation detail of how this crate happens to build it).
1212
13-use ec_av1_syntax::{Av1Parser, CdefParams, FrameType, ObuKind};
13+use ec_av1_syntax::{Av1Parser, CdefParams, FrameType, ObuKind, TxMode};
1414 use ec_core::{Error, Result};
1515
1616 use crate::decode::{decode_inter_frame_tile, decode_key_frame_tile};
@@ -75,11 +75,60 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
7575 "a frame with an active CDEF filter (not yet applied by this decoder)",
7676 ));
7777 }
78+ // Every `decode_block` call below assumes the block's transform is
79+ // its own full size (`TxMode::Largest`, which is all this crate's own
80+ // encoder ever writes, spec `read_tx_size` inferring the max depth
81+ // with no bits) -- it never reads a `tx_depth` symbol at all. A real
82+ // encoder's `TxMode::Select` (spec 5.9.2's `tx_mode` bit) codes one
83+ // per intra block, and skipping that read does not error -- the
84+ // decoder just goes on consuming the next bits as if they were the
85+ // uv_mode/coefficient symbols they are not, so the block "decodes"
86+ // syntactically clean into low-energy garbage: lane-av1real r3's
87+ // luma-near-flat-vs-ffmpeg-gradient bug. Refuse before that, the same
88+ // way as the CDEF case above, rather than silently miscode every
89+ // `TxMode::Select` stream.
90+ if header.tx_mode == TxMode::Select {
91+ return Err(Error::unsupported(
92+ "AV1 decode_stream",
93+ "a frame using TxMode::Select (this decoder never reads a tx_depth symbol, so it desyncs after the first intra block's mode)",
94+ ));
95+ }
96+ // lane-av1real r11's blindness-audit sweep (`read_intra_frame_mode_info`,
97+ // libaom decodemv.c): three more per-block/per-SB symbols this crate
98+ // never reads at all, each gated by a header field this decoder
99+ // otherwise accepts uncomplaining -- the same silent-desync shape
100+ // `use_filter_intra` was. `allow_screen_content_tools` gates both
101+ // `read_intrabc_info` and `read_palette_mode_info`; `delta.q_present`/
102+ // `delta.lf_present` gate `read_delta_qindex`/`read_delta_lflevel`
103+ // (spec 5.11.10/5.11.11, one symbol group per superblock). Refuse
104+ // before desyncing rather than silently miscode, the same pattern as
105+ // the CDEF/TxMode::Select refusals above.
106+ if header.allow_screen_content_tools {
107+ return Err(Error::unsupported(
108+ "AV1 decode_stream",
109+ "a frame with allow_screen_content_tools set (this decoder never reads intrabc/palette_mode_info)",
110+ ));
111+ }
112+ if header.delta.q_present || header.delta.lf_present {
113+ return Err(Error::unsupported(
114+ "AV1 decode_stream",
115+ "a frame with delta_q_present or delta_lf_present set (this decoder never reads the per-superblock delta symbols)",
116+ ));
117+ }
118+ if header.segmentation.enabled {
119+ return Err(Error::unsupported(
120+ "AV1 decode_stream",
121+ "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",
122+ ));
123+ }
78124 // `Tile::offset` is relative to the buffer `parse_obu` was handed
79125 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
80126 // to `obu_offset`, not to `data` as a whole.
81127 let start = obu_offset + tile.offset;
82128 let tile_bytes = data.get(start..start + tile.size).ok_or(Error::NeedMore)?;
129+ let enable_filter_intra = parser
130+ .sequence_header()
131+ .is_some_and(|seq| seq.enable_filter_intra);
83132
84133 let picture = if header.frame_type == FrameType::Key {
85134 decode_key_frame_tile(
@@ -89,6 +138,7 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
89138 header.quantization.base_q_idx,
90139 header.frame_width,
91140 header.frame_height,
141+ enable_filter_intra,
92142 )?
93143 } else {
94144 let reference = reference.as_ref().ok_or_else(|| {
@@ -170,6 +220,7 @@ mod tests {
170220 encoded.base_q_idx,
171221 width as u32,
172222 height as u32,
223+ false,
173224 )
174225 .unwrap();
175226 let via_stream = decode_stream(&encoded.stream).unwrap();
@@ -481,6 +532,52 @@ mod tests {
481532 assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
482533 }
483534
535+ /// As [`a_real_libaom_gradients_stream_decodes_pixel_exact`], but at
536+ /// 32x32 (below `is_cfl_allowed`'s 32x32 luma bound as a *single*
537+ /// undivided block, spec 5.11.5) rather than 64x64 -- a whole 64x64 SB
538+ /// is never CFL-eligible itself, only its <=32x32 partitions, and
539+ /// `testsrc2`/`gradients` at 64x64 with rect/ab/1to4/angle-delta search
540+ /// disabled reliably pick a whole-SB `PARTITION_NONE` (probed
541+ /// lane-av1real r2), so no fixture at that size exercises CfL at all.
542+ /// A 32x32 frame is exactly the whole-block, CFL-allowed case, and
543+ /// lane-av1real r2 found `gradients` there reliably selects
544+ /// `UV_CFL_PRED` (`uv_mode=13`) across a crf sweep -- `testsrc2` there
545+ /// stays DC. Proves the CfL port this round added, not just DC-chroma
546+ /// decode: pixel-exact against ffmpeg's own decode, not just "decoded".
547+ ///
548+ #[test]
549+ fn a_real_libaom_cfl_stream_decodes_pixel_exact() {
550+ if !have_ffmpeg() {
551+ eprintln!("SKIP a_real_libaom_cfl_stream_decodes_pixel_exact: no ffmpeg");
552+ return;
553+ }
554+ let (width, height) = (32, 32);
555+ let stream = libaom_encode_with(
556+ "gradients=size=32x32:c0=red:c1=blue:c2=green:rate=1:seed=42",
557+ width,
558+ height,
559+ 15,
560+ &[
561+ "-threads",
562+ "1",
563+ "-row-mt",
564+ "0",
565+ "-tile-columns",
566+ "0",
567+ "-tile-rows",
568+ "0",
569+ "-enable-cdef",
570+ "0",
571+ ],
572+ )
573+ .expect("ffmpeg encode");
574+ let frames = decode_stream(&stream).expect("decode_stream on a real libaom stream");
575+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
576+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "luma vs ffmpeg");
577+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "U vs ffmpeg");
578+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "V vs ffmpeg");
579+ }
580+
484581 /// scratch: isolate a pinned mismatching stream's first divergent pixel.
485582 #[test]
486583 #[ignore]
@@ -495,11 +592,18 @@ mod tests {
495592 pos += obu.total_size;
496593 if let ObuKind::Frame(header, _) = obu.kind {
497594 eprintln!("cdef: {:?}", header.cdef);
595+ eprintln!("quantization: {:?}", header.quantization);
596+ eprintln!(
597+ "coded_lossless: {:?} tx_mode: {:?}",
598+ header.coded_lossless, header.tx_mode
599+ );
600+ eprintln!("delta: {:?}", header.delta);
601+ eprintln!("segmentation: {:?}", header.segmentation);
498602 }
499603 }
500604 }
501- let width = 64;
502- let height = 64;
605+ let width = 32;
606+ let height = 32;
503607 let frames = decode_stream(&stream).expect("our decode");
504608 let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
505609 let ours = &frames[0];
@@ -531,5 +635,15 @@ mod tests {
531635 eprintln!("plane {plane_name}: MATCH");
532636 }
533637 }
638+ for row in 0..8 {
639+ eprintln!(
640+ "ours row{row}: {:?}",
641+ &ours.y[row * width..row * width + 8]
642+ );
643+ eprintln!(
644+ "theirs row{row}: {:?}",
645+ &theirs.y[row * width..row * width + 8]
646+ );
647+ }
534648 }
535649 }
crates/ec-av1/src/transform.rsmodified+35 -0
@@ -1050,6 +1050,41 @@ mod tests {
10501050 .collect()
10511051 }
10521052
1053+ #[test]
1054+ #[ignore]
1055+ fn scratch_probe_32x32_dequant() {
1056+ let mut levels = vec![0i32; 32 * 32];
1057+ levels[0] = -2;
1058+ levels[1] = -2;
1059+ levels[2] = -2;
1060+ let dq = crate::quant::dequant(&levels, 32, 8, 60);
1061+ eprintln!("dq[0..4]={:?}", &dq[0..4]);
1062+ let residual = dequant_and_inverse(&levels, 32, 8, 60);
1063+ eprintln!("row0: {:?}", &residual[0..32]);
1064+ eprintln!("row1: {:?}", &residual[32..64]);
1065+
1066+ // superposition probe: does inverse_transform_2d at side=32 sum
1067+ // three simultaneous low-frequency coefficients the same as it
1068+ // reconstructs each alone?
1069+ let side = 32usize;
1070+ let mut single_sum = vec![0i32; side * side];
1071+ for &(pos, val) in &[(0usize, -57i32), (1, -67), (2, -67)] {
1072+ let mut c = vec![0i32; side * side];
1073+ c[pos] = val;
1074+ let got = inverse_transform_2d(&c, side, 8);
1075+ for i in 0..side * side {
1076+ single_sum[i] += got[i];
1077+ }
1078+ }
1079+ let mut combined = vec![0i32; side * side];
1080+ combined[0] = -57;
1081+ combined[1] = -67;
1082+ combined[2] = -67;
1083+ let got_combined = inverse_transform_2d(&combined, side, 8);
1084+ eprintln!("single_sum row0: {:?}", &single_sum[0..8]);
1085+ eprintln!("combined row0: {:?}", &got_combined[0..8]);
1086+ }
1087+
10531088 fn rmse(a: &[i32], b: &[i32]) -> f64 {
10541089 let sum: f64 = a
10551090 .iter()