forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1cdffwd': cross-frame CDF forwarding, and the two bugs behind it

Browse files at this commit

ce44f724f747a4ac898496e4264fd0e72b49d0e8Ahmet Kaan GümüşParent: ab252be8f9acc8
Real inter streams (primary_ref_frame set) now decode: forwarded CDF
state per reference slot with spec 7.20's counter reset, the mv_hp
bits real hp streams carry (dropped as dead because our own writer
never sets the flag -- the silently-unread-symbol class again), and
reference pictures addressed by ref_frame_idx slot instead of a
last-decode global. Gate: real aomenc inter sequences decode
pixel-exact with default CDF behavior, 6/6 runs.
crates/ec-av1/src/cdf_state.rsmodified+131 -4
@@ -96,6 +96,7 @@ pub(crate) struct TxbTables<'a> {
9696 }
9797
9898 /// Every table a key frame's tile writer adapts.
99+#[derive(Clone)]
99100 pub(crate) struct Cdfs {
100101 /// The partition symbol of a 64x64 superblock.
101102 pub partition_w64: [[u16; 11]; 4],
@@ -271,14 +272,19 @@ pub(crate) struct MvComponentCdfs {
271272 pub class0_bit: [u16; 3],
272273 /// The fractional part of a small-class magnitude, by its integer bit.
273274 pub class0_fr: [[u16; 5]; 2],
274- // `class0_hp`/`hp` (spec's half-pel-bit CDFs) are never written: this
275- // encoder always sets `allow_high_precision_mv = false`, so the syntax
276- // that reads them (spec 5.9.32 `mv_class0_hp`/`mv_hp`) never fires --
277- // dropped rather than kept dead. Add back if/when hp mode ships.
275+ /// The half-pel bit of a small-class magnitude (spec `mv_class0_hp`),
276+ /// read only when the frame header sets `allow_high_precision_mv` (a
277+ /// real encoder's choice, not this crate's own writer's -- which always
278+ /// leaves the flag off and so never needs this table, but a foreign
279+ /// stream this decoder reads can set it per frame).
280+ pub class0_hp: [u16; 3],
278281 /// One bit of an above-small-class magnitude, by its position.
279282 pub bit: [[u16; 3]; 10],
280283 /// The fractional part of an above-small-class magnitude.
281284 pub fr: [u16; 5],
285+ /// The half-pel bit of an above-small-class magnitude (spec `mv_hp`),
286+ /// same `allow_high_precision_mv` gating as [`Self::class0_hp`].
287+ pub hp: [u16; 3],
282288 /// The component's sign.
283289 pub sign: [u16; 3],
284290 }
@@ -289,8 +295,10 @@ impl MvComponentCdfs {
289295 class: cdf::MV_CLASS,
290296 class0_bit: cdf::MV_CLASS0_BIT,
291297 class0_fr: cdf::MV_CLASS0_FR,
298+ class0_hp: cdf::MV_CLASS0_HP,
292299 bit: cdf::MV_BIT,
293300 fr: cdf::MV_FR,
301+ hp: cdf::MV_HP,
294302 sign: cdf::MV_SIGN,
295303 }
296304 }
@@ -308,7 +316,126 @@ pub(crate) fn pick<T: Copy>(q_ctx: usize, q0: T, q1: T, q2: T, q3: T) -> T {
308316 }
309317 }
310318
319+/// `reset_cdf_symbol_counter` (spec 7.20's `save_cdfs`, libaom
320+/// `av1_reset_cdf_symbol_counters`, `entropy.c`): every adapting table's last
321+/// entry is a symbol counter that slows [`update_cdf`](crate::msac)'s rate
322+/// down for a table's first 32 observations. A tile decoded with
323+/// `disable_frame_end_update_cdf == false` saves its *adapted* table into the
324+/// reference slots the frame refreshes, but the counters go back to zero
325+/// first -- forwarding the raw counts (this crate's bug until it was found:
326+/// the counts climbed unchecked, so every table forwarded across two or more
327+/// frames adapted *faster* than the real decoder's, a divergence too small to
328+/// flip any one symbol in a single hop but compounding into a visible
329+/// mismatch by the third).
330+fn reset1<const N: usize>(a: &mut [u16; N]) {
331+ a[N - 1] = 0;
332+}
333+fn reset2<const N: usize, const M: usize>(a: &mut [[u16; N]; M]) {
334+ a.iter_mut().for_each(reset1);
335+}
336+fn reset3<const N: usize, const M: usize, const K: usize>(a: &mut [[[u16; N]; M]; K]) {
337+ a.iter_mut().for_each(reset2);
338+}
339+
340+impl MvComponentCdfs {
341+ fn reset_counts(&mut self) {
342+ reset1(&mut self.class);
343+ reset1(&mut self.class0_bit);
344+ reset2(&mut self.class0_fr);
345+ reset1(&mut self.class0_hp);
346+ reset2(&mut self.bit);
347+ reset1(&mut self.fr);
348+ reset1(&mut self.hp);
349+ reset1(&mut self.sign);
350+ }
351+}
352+
311353 impl Cdfs {
354+ /// Zeroes every table's symbol counter (its last entry), leaving the
355+ /// probabilities themselves untouched -- spec 7.20's `save_cdfs`. Call
356+ /// this on the tile's own end-of-tile adapted state before storing it
357+ /// into a reference slot for cross-frame forwarding; never on a table
358+ /// still being read within the same tile.
359+ pub(crate) fn reset_counts(&mut self) {
360+ reset2(&mut self.partition_w64);
361+ reset2(&mut self.partition_w32);
362+ reset2(&mut self.skip);
363+ reset3(&mut self.kf_y_mode);
364+ reset2(&mut self.uv_mode_no_cfl);
365+ reset2(&mut self.uv_mode_cfl);
366+ reset1(&mut self.cfl_sign);
367+ reset2(&mut self.cfl_alpha);
368+ reset2(&mut self.angle_delta);
369+ reset2(&mut self.txb_skip_luma_16);
370+ reset2(&mut self.txb_skip_luma_8);
371+ reset2(&mut self.txb_skip_chroma_8);
372+ reset2(&mut self.txb_skip_chroma_4);
373+ reset1(&mut self.eob_pt_256_luma);
374+ reset1(&mut self.eob_pt_64_luma);
375+ reset1(&mut self.eob_pt_64_chroma);
376+ reset1(&mut self.eob_pt_16_chroma);
377+ reset2(&mut self.eob_extra_luma_16);
378+ reset2(&mut self.eob_extra_luma_8);
379+ reset2(&mut self.eob_extra_chroma_8);
380+ reset2(&mut self.eob_extra_chroma_4);
381+ reset2(&mut self.base_luma_16);
382+ reset2(&mut self.base_luma_8);
383+ reset2(&mut self.base_chroma_8);
384+ reset2(&mut self.base_chroma_4);
385+ reset2(&mut self.base_eob_luma_16);
386+ reset2(&mut self.base_eob_luma_8);
387+ reset2(&mut self.base_eob_chroma_8);
388+ reset2(&mut self.base_eob_chroma_4);
389+ reset2(&mut self.br_luma_16);
390+ reset2(&mut self.br_luma_8);
391+ reset2(&mut self.br_chroma_8);
392+ reset2(&mut self.br_chroma_4);
393+ reset2(&mut self.partition_w16);
394+ reset2(&mut self.partition_w8);
395+ reset2(&mut self.txb_skip_luma_32);
396+ reset2(&mut self.txb_skip_luma_64);
397+ reset2(&mut self.txb_skip_chroma_16);
398+ reset2(&mut self.txb_skip_chroma_32);
399+ reset1(&mut self.eob_pt_1024_luma);
400+ reset1(&mut self.eob_pt_1024_chroma);
401+ reset1(&mut self.eob_pt_256_chroma);
402+ reset2(&mut self.eob_extra_luma_32);
403+ reset2(&mut self.eob_extra_luma_64);
404+ reset2(&mut self.eob_extra_chroma_16);
405+ reset2(&mut self.eob_extra_chroma_32);
406+ reset2(&mut self.base_luma_32);
407+ reset2(&mut self.base_luma_64);
408+ reset2(&mut self.base_chroma_16);
409+ reset2(&mut self.base_chroma_32);
410+ reset2(&mut self.base_eob_luma_32);
411+ reset2(&mut self.base_eob_luma_64);
412+ reset2(&mut self.base_eob_chroma_16);
413+ reset2(&mut self.base_eob_chroma_32);
414+ reset2(&mut self.br_luma_32);
415+ reset2(&mut self.br_chroma_16);
416+ reset2(&mut self.br_chroma_32);
417+ reset2(&mut self.dc_sign_luma);
418+ reset2(&mut self.intra_tx_type_16);
419+ reset2(&mut self.intra_tx_type_8);
420+ reset1(&mut self.inter_tx_type_32);
421+ reset1(&mut self.inter_tx_type_16);
422+ reset1(&mut self.inter_tx_type_8);
423+ reset2(&mut self.dc_sign_chroma);
424+ reset2(&mut self.intra_inter);
425+ reset3(&mut self.single_ref);
426+ reset2(&mut self.y_mode);
427+ reset2(&mut self.new_mv);
428+ reset2(&mut self.zero_mv);
429+ reset2(&mut self.ref_mv);
430+ reset2(&mut self.drl_mode);
431+ reset1(&mut self.mv_joint);
432+ self.mv_comp
433+ .iter_mut()
434+ .for_each(MvComponentCdfs::reset_counts);
435+ reset2(&mut self.filter_intra);
436+ reset1(&mut self.filter_intra_mode);
437+ }
438+
312439 /// The defaults a key frame starts from (spec 8.4, `init_coeff_cdfs` and
313440 /// `init_non_coeff_cdfs`), for coefficient q-context `q_ctx` (0..=3, spec
314441 /// 8.3.2's `Get_Qctx`). The non-coefficient tables do not vary with the
crates/ec-av1/src/decode.rsmodified+165 -38
@@ -115,7 +115,7 @@ fn unsupported(what: impl Into<String>) -> Error {
115115 /// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
116116 /// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
117117 /// same rule.
118-fn q_ctx_of(base_q_idx: u8) -> usize {
118+pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
119119 match base_q_idx {
120120 0..=20 => 0,
121121 21..=60 => 1,
@@ -2078,6 +2078,41 @@ pub fn decode_key_frame_tile(
20782078 cdef: &CdefParams,
20792079 loop_filter: &LoopFilterParams,
20802080 ) -> Result<Picture> {
2081+ decode_key_frame_tile_with_cdfs(
2082+ data,
2083+ mi_cols,
2084+ mi_rows,
2085+ base_q_idx,
2086+ frame_width,
2087+ frame_height,
2088+ enable_filter_intra,
2089+ cdef,
2090+ loop_filter,
2091+ None,
2092+ )
2093+ .map(|(picture, _)| picture)
2094+}
2095+
2096+/// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
2097+/// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
2098+/// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
2099+/// when `None` (the only case [`decode_key_frame_tile`] itself ever needs,
2100+/// since a key frame's own header always forces `primary_ref_frame ==
2101+/// PRIMARY_REF_NONE`). Returns the tile's own end-of-tile adapted table
2102+/// alongside the picture, for the caller to save into whichever reference
2103+/// slots this frame's `refresh_frame_flags` names.
2104+pub(crate) fn decode_key_frame_tile_with_cdfs(
2105+ data: &[u8],
2106+ mi_cols: u32,
2107+ mi_rows: u32,
2108+ base_q_idx: u8,
2109+ frame_width: u32,
2110+ frame_height: u32,
2111+ enable_filter_intra: bool,
2112+ cdef: &CdefParams,
2113+ loop_filter: &LoopFilterParams,
2114+ initial_cdfs: Option<Cdfs>,
2115+) -> Result<(Picture, Cdfs)> {
20812116 if mi_cols == 0 || mi_rows == 0 {
20822117 return Err(unsupported("a frame with no mode-info grid"));
20832118 }
@@ -2113,7 +2148,7 @@ pub fn decode_key_frame_tile(
21132148 let scan8 = default_scan(TX8);
21142149 let scan4 = default_scan(TX4);
21152150
2116- let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
2151+ let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
21172152 if std::env::var_os("EC_AV1_TRACE").is_some() {
21182153 eprintln!(
21192154 "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
@@ -2416,13 +2451,16 @@ pub fn decode_key_frame_tile(
24162451
24172452 let (fw, fh) = (frame_width as usize, frame_height as usize);
24182453 if fw == width && fh == height {
2419- return Ok(Picture {
2420- width,
2421- height,
2422- y: y.data,
2423- u: u.data,
2424- v: v.data,
2425- });
2454+ return Ok((
2455+ Picture {
2456+ width,
2457+ height,
2458+ y: y.data,
2459+ u: u.data,
2460+ v: v.data,
2461+ },
2462+ cdfs,
2463+ ));
24262464 }
24272465 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
24282466 let mut out = Vec::with_capacity(w * h);
@@ -2431,13 +2469,16 @@ pub fn decode_key_frame_tile(
24312469 }
24322470 out
24332471 };
2434- Ok(Picture {
2435- width: fw,
2436- height: fh,
2437- y: crop(&y, fw, fh),
2438- u: crop(&u, fw / 2, fh / 2),
2439- v: crop(&v, fw / 2, fh / 2),
2440- })
2472+ Ok((
2473+ Picture {
2474+ width: fw,
2475+ height: fh,
2476+ y: crop(&y, fw, fh),
2477+ u: crop(&u, fw / 2, fh / 2),
2478+ v: crop(&v, fw / 2, fh / 2),
2479+ },
2480+ cdfs,
2481+ ))
24412482 }
24422483
24432484 /// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),
@@ -2468,20 +2509,38 @@ fn mv_class_base(class: usize) -> i32 {
24682509 /// One motion vector component's non-zero diff (spec 5.11.32
24692510 /// `read_mv_component`), the inverse of [`crate::tile`]'s private
24702511 /// `write_mv_component`.
2471-fn read_mv_component(dec: &mut SymbolDecoder, c: &mut MvComponentCdfs) -> i32 {
2512+fn read_mv_component(
2513+ dec: &mut SymbolDecoder,
2514+ c: &mut MvComponentCdfs,
2515+ allow_high_precision_mv: bool,
2516+) -> i32 {
24722517 let sign = dec.symbol(&mut c.sign);
24732518 let class = dec.symbol(&mut c.class);
24742519 let local = if class == 0 {
24752520 let bit = dec.symbol(&mut c.class0_bit);
24762521 let fr = dec.symbol(&mut c.class0_fr[bit]);
2477- (bit << 3) | (fr << 1) | 1
2522+ // spec 5.11.32 `mv_class0_hp`: read only when the frame allows
2523+ // high-precision motion vectors, else implicitly 1 (the low bit
2524+ // stays at half-pel precision) -- this crate's own writer always
2525+ // leaves the flag off, but a foreign stream can set it per frame.
2526+ let hp = if allow_high_precision_mv {
2527+ dec.symbol(&mut c.class0_hp)
2528+ } else {
2529+ 1
2530+ };
2531+ (bit << 3) | (fr << 1) | hp
24782532 } else {
24792533 let mut d = 0;
24802534 for i in 0..class {
24812535 d |= dec.symbol(&mut c.bit[i]) << i;
24822536 }
24832537 let fr = dec.symbol(&mut c.fr);
2484- (d << 3) | (fr << 1) | 1
2538+ let hp = if allow_high_precision_mv {
2539+ dec.symbol(&mut c.hp)
2540+ } else {
2541+ 1
2542+ };
2543+ (d << 3) | (fr << 1) | hp
24852544 };
24862545 let mag = mv_class_base(class) + local as i32 + 1;
24872546 if sign == 1 { -mag } else { mag }
@@ -2494,14 +2553,15 @@ fn read_mv(
24942553 mv_comp: &mut [MvComponentCdfs; 2],
24952554 mv_joint: &mut [u16; 5],
24962555 pred: (i32, i32),
2556+ allow_high_precision_mv: bool,
24972557 ) -> (i32, i32) {
24982558 let joint = dec.symbol(mv_joint);
24992559 let mut diff = (0, 0);
25002560 if joint == 2 || joint == 3 {
2501- diff.0 = read_mv_component(dec, &mut mv_comp[0]);
2561+ diff.0 = read_mv_component(dec, &mut mv_comp[0], allow_high_precision_mv);
25022562 }
25032563 if joint == 1 || joint == 3 {
2504- diff.1 = read_mv_component(dec, &mut mv_comp[1]);
2564+ diff.1 = read_mv_component(dec, &mut mv_comp[1], allow_high_precision_mv);
25052565 }
25062566 (pred.0 + diff.0, pred.1 + diff.1)
25072567 }
@@ -2609,6 +2669,7 @@ fn decode_inter_block(
26092669 scan_luma: &[u16],
26102670 scan_chroma: &[u16],
26112671 size_group: usize,
2672+ allow_high_precision_mv: bool,
26122673 ) -> Result<()> {
26132674 const LAST_FRAME: i8 = 1;
26142675
@@ -2657,7 +2718,13 @@ fn decode_inter_block(
26572718 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
26582719 }
26592720 (
2660- read_mv(dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, stack.pred_mv),
2721+ read_mv(
2722+ dec,
2723+ &mut cdfs.mv_comp,
2724+ &mut cdfs.mv_joint,
2725+ stack.pred_mv,
2726+ allow_high_precision_mv,
2727+ ),
26612728 true,
26622729 )
26632730 } else {
@@ -2691,6 +2758,12 @@ fn decode_inter_block(
26912758 };
26922759 (mv, false)
26932760 };
2761+ if std::env::var_os("EC_AV1_TRACE").is_some() {
2762+ eprintln!(
2763+ "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side}",
2764+ skip as u8, mv.0, mv.1
2765+ );
2766+ }
26942767 for dr in 0..bw4 {
26952768 for dc in 0..bw4 {
26962769 grid.set(
@@ -2997,6 +3070,7 @@ fn decode_inter_block8(
29973070 scan8: &[u16],
29983071 scan4: &[u16],
29993072 prev_leaf: Option<((usize, usize), bool, bool)>,
3073+ allow_high_precision_mv: bool,
30003074 ) -> Result<(bool, bool)> {
30013075 const LAST_FRAME: i8 = 1;
30023076 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
@@ -3059,7 +3133,13 @@ fn decode_inter_block8(
30593133 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
30603134 }
30613135 (
3062- read_mv(dec, &mut cdfs.mv_comp, &mut cdfs.mv_joint, stack.pred_mv),
3136+ read_mv(
3137+ dec,
3138+ &mut cdfs.mv_comp,
3139+ &mut cdfs.mv_joint,
3140+ stack.pred_mv,
3141+ allow_high_precision_mv,
3142+ ),
30633143 true,
30643144 )
30653145 } else {
@@ -3366,7 +3446,42 @@ pub fn decode_inter_frame_tile(
33663446 reference: &Picture,
33673447 cdef: &CdefParams,
33683448 loop_filter: &LoopFilterParams,
3449+ allow_high_precision_mv: bool,
33693450 ) -> Result<Picture> {
3451+ decode_inter_frame_tile_with_cdfs(
3452+ data,
3453+ mi_cols,
3454+ mi_rows,
3455+ base_q_idx,
3456+ frame_width,
3457+ frame_height,
3458+ reference,
3459+ cdef,
3460+ loop_filter,
3461+ None,
3462+ allow_high_precision_mv,
3463+ )
3464+ .map(|(picture, _)| picture)
3465+}
3466+
3467+/// [`decode_inter_frame_tile`], threading a cross-frame CDF forward -- see
3468+/// [`decode_key_frame_tile_with_cdfs`]'s doc for `initial_cdfs`/the returned
3469+/// end-of-tile table. An inter frame's own header can name
3470+/// `primary_ref_frame == PRIMARY_REF_NONE` too (an error-resilient stream),
3471+/// so `None` is a real case here, not only a convenience default.
3472+pub(crate) fn decode_inter_frame_tile_with_cdfs(
3473+ data: &[u8],
3474+ mi_cols: u32,
3475+ mi_rows: u32,
3476+ base_q_idx: u8,
3477+ frame_width: u32,
3478+ frame_height: u32,
3479+ reference: &Picture,
3480+ cdef: &CdefParams,
3481+ loop_filter: &LoopFilterParams,
3482+ initial_cdfs: Option<Cdfs>,
3483+ allow_high_precision_mv: bool,
3484+) -> Result<(Picture, Cdfs)> {
33703485 if mi_cols == 0 || mi_rows == 0 {
33713486 return Err(unsupported("a frame with no mode-info grid"));
33723487 }
@@ -3429,7 +3544,7 @@ pub fn decode_inter_frame_tile(
34293544 let scan8 = default_scan(TX8);
34303545 let scan4 = default_scan(TX4);
34313546
3432- let mut cdfs = Cdfs::new(q_ctx_of(base_q_idx));
3547+ let mut cdfs = initial_cdfs.unwrap_or_else(|| Cdfs::new(q_ctx_of(base_q_idx)));
34333548 let mut dec = SymbolDecoder::new(data);
34343549 let mut neighbours = Neighbours::new(
34353550 cols as usize * 2,
@@ -3512,6 +3627,7 @@ pub fn decode_inter_frame_tile(
35123627 &scan32,
35133628 &scan16,
35143629 3,
3630+ allow_high_precision_mv,
35153631 )?;
35163632 }
35173633 PARTITION_SPLIT => {
@@ -3564,6 +3680,7 @@ pub fn decode_inter_frame_tile(
35643680 &scan16,
35653681 &scan8,
35663682 2,
3683+ allow_high_precision_mv,
35673684 )?;
35683685 } else {
35693686 let ctx16 = neighbours.partition_ctx(at16, SUB);
@@ -3612,6 +3729,7 @@ pub fn decode_inter_frame_tile(
36123729 &scan8,
36133730 &scan4,
36143731 prev_leaf,
3732+ allow_high_precision_mv,
36153733 )?;
36163734 prev_leaf = Some((leaf_mi, skip, is_inter));
36173735 }
@@ -3634,13 +3752,16 @@ pub fn decode_inter_frame_tile(
36343752
36353753 let (fw, fh) = (frame_width as usize, frame_height as usize);
36363754 if fw == width && fh == height {
3637- return Ok(Picture {
3638- width,
3639- height,
3640- y: y.data,
3641- u: u.data,
3642- v: v.data,
3643- });
3755+ return Ok((
3756+ Picture {
3757+ width,
3758+ height,
3759+ y: y.data,
3760+ u: u.data,
3761+ v: v.data,
3762+ },
3763+ cdfs,
3764+ ));
36443765 }
36453766 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
36463767 let mut out = Vec::with_capacity(w * h);
@@ -3649,13 +3770,16 @@ pub fn decode_inter_frame_tile(
36493770 }
36503771 out
36513772 };
3652- Ok(Picture {
3653- width: fw,
3654- height: fh,
3655- y: crop(&y, fw, fh),
3656- u: crop(&u, fw / 2, fh / 2),
3657- v: crop(&v, fw / 2, fh / 2),
3658- })
3773+ Ok((
3774+ Picture {
3775+ width: fw,
3776+ height: fh,
3777+ y: crop(&y, fw, fh),
3778+ u: crop(&u, fw / 2, fh / 2),
3779+ v: crop(&v, fw / 2, fh / 2),
3780+ },
3781+ cdfs,
3782+ ))
36593783 }
36603784
36613785 #[cfg(test)]
@@ -4085,6 +4209,7 @@ mod tests {
40854209 &reference,
40864210 &CdefParams::default(),
40874211 &LoopFilterParams::default(),
4212+ false,
40884213 )
40894214 .unwrap();
40904215 assert_eq!(
@@ -4258,6 +4383,7 @@ mod tests {
42584383 &[],
42594384 &[],
42604385 0,
4386+ false,
42614387 )
42624388 .unwrap();
42634389
@@ -4345,6 +4471,7 @@ mod tests {
43454471 &reference,
43464472 &CdefParams::default(),
43474473 &LoopFilterParams::default(),
4474+ false,
43484475 )
43494476 .unwrap();
43504477 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");
crates/ec-av1/src/msac.rsmodified+10 -0
@@ -299,6 +299,7 @@ impl<'a> SymbolDecoder<'a> {
299299 /// [`SymbolEncoder::symbol_fixed`].
300300 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
301301 let nsyms = cdf.len() - 1;
302+ let rng_before = self.range;
302303 let mut cur = self.range;
303304 let mut prev;
304305 let mut symbol = 0;
@@ -314,6 +315,15 @@ impl<'a> SymbolDecoder<'a> {
314315 }
315316 self.range = prev - cur;
316317 self.value -= cur;
318+ if std::env::var_os("EC_RNG").is_some() {
319+ use std::sync::atomic::{AtomicU64, Ordering};
320+ static EC_RNG_N: AtomicU64 = AtomicU64::new(0);
321+ let n = EC_RNG_N.fetch_add(1, Ordering::Relaxed);
322+ eprintln!(
323+ "EC_RNG n={n} rng_before={rng_before} rng_after={} nsyms={nsyms} symbol={symbol}",
324+ self.range
325+ );
326+ }
317327
318328 // Renormalise back into `[2^15, 2^16)`, the same shift the encoder
319329 // applied when it narrowed to this symbol.
crates/ec-av1/src/stream.rsmodified+348 -49
@@ -1,20 +1,31 @@
11 //! The stream-level entry point a real decoder needs: walk a raw AV1 OBU
22 //! stream (`Encoded::stream`, or any low-overhead-format bitstream this
33 //! crate's own writers produce) via [`ec_av1_syntax::Av1Parser`] and dispatch
4-//! each frame's tile payload to [`crate::decode::decode_key_frame_tile`] /
5-//! [`crate::decode::decode_inter_frame_tile`], threading a single-slot DPB
6-//! exactly as [`crate::encode::encode_sequence`] does on the write side.
4+//! each frame's tile payload to [`crate::decode::decode_key_frame_tile_with_cdfs`] /
5+//! [`crate::decode::decode_inter_frame_tile_with_cdfs`], threading a
6+//! single-slot picture DPB exactly as [`crate::encode::encode_sequence`] does
7+//! on the write side, plus the full 8-slot *CDF* reference bank spec 7.20
8+//! (`load_cdfs`) and 7.4 (the reference frame update) describe: a frame whose
9+//! header names `primary_ref_frame != PRIMARY_REF_NONE` resumes from the
10+//! adapted table a previous frame's `refresh_frame_flags` left in that slot,
11+//! rather than the spec 8.4 defaults.
712 //!
813 //! This is the only reachable path for a caller that does not have the
914 //! encoder's own `Encoded::tile`/`mi_cols`/`mi_rows`/`base_q_idx` fields (they
1015 //! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is
1116 //! an implementation detail of how this crate happens to build it).
1217
13-use ec_av1_syntax::{Av1Parser, FrameType, ObuKind, TxMode, WarpModel};
18+use ec_av1_syntax::{
19+ Av1Parser, FrameType, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, TxMode, WarpModel,
20+};
1421 use ec_core::{Error, Result};
1522
23+use crate::cdf_state::Cdfs;
1624 use crate::decode;
17-use crate::decode::{decode_inter_frame_tile, decode_key_frame_tile};
25+use crate::decode::{
26+ decode_inter_frame_tile_with_cdfs, decode_key_frame_tile, decode_key_frame_tile_with_cdfs,
27+ q_ctx_of,
28+};
1829 use crate::encode::Picture;
1930
2031 /// Decode every frame in a raw AV1 OBU stream, in coding order.
@@ -35,7 +46,24 @@ use crate::encode::Picture;
3546 pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
3647 let mut parser = Av1Parser::new();
3748 let mut pictures = Vec::new();
38- let mut reference: Option<Picture> = None;
49+ // Spec 7.20/7.4: each of the 8 reference slots remembers the picture a
50+ // previous frame's `refresh_frame_flags` stored into it, exactly like the
51+ // CDF slots below -- `LAST_FRAME` names a slot via `ref_frame_idx[0]`,
52+ // not simply "the previous frame decoded"; a frame whose own predecessor
53+ // didn't refresh that slot (an altref/hidden frame, or any GOP with more
54+ // than one live reference) must keep predicting from whatever picture is
55+ // still sitting there. Round 7's cdffwd hunt: a global `reference`
56+ // overwritten every frame silently always used "the most recent decode"
57+ // instead, producing a bit-exact motion vector into the WRONG picture --
58+ // luma-only (chroma coincidentally shares this fixture's flat regions)
59+ // and small-magnitude (the two pictures mostly agree), which is exactly
60+ // what made it look like a rounding bug rather than a wrong reference.
61+ let mut ref_slots: [Option<Picture>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
62+ // Spec 7.20/7.4: each of the 8 reference slots remembers the CDF state a
63+ // previous frame's `refresh_frame_flags` stored into it -- the frame's
64+ // own end-of-tile adapted table, or (when the frame set
65+ // `disable_frame_end_update_cdf`) the table it started from, unchanged.
66+ let mut cdf_slots: [Option<Cdfs>; NUM_REF_FRAMES] = std::array::from_fn(|_| None);
3967
4068 let mut pos = 0usize;
4169 while pos < data.len() {
@@ -110,6 +138,18 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
110138 "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",
111139 ));
112140 }
141+ // Loop restoration carries per-restoration-unit symbols in the tile
142+ // (spec 5.11.57 `read_lr`, one group per LR unit reached from the
143+ // superblock walk) that this decoder never reads -- same
144+ // silent-desync shape as the refusals above. Traced live 2026-08-27:
145+ // an aomenc inter frame with `Sgrproj` on the V plane desynced the
146+ // partition walk into out-of-alphabet garbage.
147+ if header.loop_restoration.uses_lr {
148+ return Err(Error::unsupported(
149+ "AV1 decode_stream",
150+ "a frame with loop restoration enabled (this decoder never reads the per-unit lr symbols)",
151+ ));
152+ }
113153 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
114154 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
115155 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the
@@ -125,6 +165,17 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
125165 "an inter frame whose LAST_FRAME global motion is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)",
126166 ));
127167 }
168+ // `context_update_tile_id` (spec `decode_tile`/`exit_symbol`) names
169+ // which tile's end-of-tile adapted CDFs become the frame's own; this
170+ // decoder only ever decodes tile 0 (`tiles.first()` above), so a
171+ // multi-tile frame is refused rather than silently forwarding the
172+ // wrong tile's table (or leaving the rest of the picture undecoded).
173+ if header.tile_info.cols > 1 || header.tile_info.rows > 1 {
174+ return Err(Error::unsupported(
175+ "AV1 decode_stream",
176+ "a frame with more than one tile (this decoder only ever decodes tile 0)",
177+ ));
178+ }
128179 // `Tile::offset` is relative to the buffer `parse_obu` was handed
129180 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
130181 // to `obu_offset`, not to `data` as a whole.
@@ -134,8 +185,25 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
134185 .sequence_header()
135186 .is_some_and(|seq| seq.enable_filter_intra);
136187
137- let picture = if header.frame_type == FrameType::Key {
138- decode_key_frame_tile(
188+ // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
189+ // from that reference slot's saved CDF state instead of the spec 8.4
190+ // defaults `decode_key/inter_frame_tile_with_cdfs`'s `None` case
191+ // builds.
192+ let initial_cdfs = if header.primary_ref_frame == PRIMARY_REF_NONE {
193+ None
194+ } else {
195+ let slot = header.ref_frame_idx[header.primary_ref_frame as usize] as usize;
196+ Some(cdf_slots[slot].clone().ok_or_else(|| {
197+ Error::unsupported(
198+ "AV1 decode_stream",
199+ "a frame naming primary_ref_frame at a reference slot with no saved CDF state",
200+ )
201+ })?)
202+ };
203+ let started_from = initial_cdfs.clone();
204+
205+ let (picture, end_cdfs) = if header.frame_type == FrameType::Key {
206+ decode_key_frame_tile_with_cdfs(
139207 tile_bytes,
140208 header.mi_cols,
141209 header.mi_rows,
@@ -145,15 +213,17 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
145213 enable_filter_intra,
146214 &header.cdef,
147215 &header.loop_filter,
216+ initial_cdfs,
148217 )?
149218 } else {
150- let reference = reference.as_ref().ok_or_else(|| {
219+ let last_slot = header.ref_frame_idx[0] as usize;
220+ let reference = ref_slots[last_slot].as_ref().ok_or_else(|| {
151221 Error::unsupported(
152222 "AV1 decode_stream",
153223 "an inter frame with no key frame before it",
154224 )
155225 })?;
156- decode_inter_frame_tile(
226+ decode_inter_frame_tile_with_cdfs(
157227 tile_bytes,
158228 header.mi_cols,
159229 header.mi_rows,
@@ -163,9 +233,47 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
163233 reference,
164234 &header.cdef,
165235 &header.loop_filter,
236+ initial_cdfs,
237+ header.allow_high_precision_mv,
166238 )?
167239 };
168- reference = Some(picture.clone());
240+ // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
241+ // *initial* table into the slots it refreshes, not the adapted
242+ // end-of-tile one.
243+ let stored_cdfs = if header.disable_frame_end_update_cdf {
244+ started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
245+ } else {
246+ // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`):
247+ // the adapted table is saved with every symbol counter zeroed,
248+ // not with the counts the tile's own decode left behind.
249+ let mut end_cdfs = end_cdfs;
250+ end_cdfs.reset_counts();
251+ end_cdfs
252+ };
253+ if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
254+ use std::io::Write;
255+ if let Ok(mut f) = std::fs::OpenOptions::new()
256+ .create(true)
257+ .append(true)
258+ .open(&path)
259+ {
260+ let _ = writeln!(f, "=== frame idx={} ===", pictures.len());
261+ let _ = writeln!(f, "partition_w64 {:?}", stored_cdfs.partition_w64);
262+ let _ = writeln!(f, "partition_w32 {:?}", stored_cdfs.partition_w32);
263+ let _ = writeln!(f, "partition_w16 {:?}", stored_cdfs.partition_w16);
264+ let _ = writeln!(f, "skip {:?}", stored_cdfs.skip);
265+ let _ = writeln!(f, "new_mv {:?}", stored_cdfs.new_mv);
266+ let _ = writeln!(f, "zero_mv {:?}", stored_cdfs.zero_mv);
267+ let _ = writeln!(f, "ref_mv {:?}", stored_cdfs.ref_mv);
268+ let _ = writeln!(f, "mv_joint {:?}", stored_cdfs.mv_joint);
269+ }
270+ }
271+ for i in 0..NUM_REF_FRAMES {
272+ if header.refresh_frame_flags & (1 << i) != 0 {
273+ cdf_slots[i] = Some(stored_cdfs.clone());
274+ ref_slots[i] = Some(picture.clone());
275+ }
276+ }
169277 pictures.push(picture);
170278 }
171279 Ok(pictures)
@@ -837,6 +945,10 @@ mod tests {
837945 "--enable-angle-delta=0",
838946 "--enable-tx-size-search=0",
839947 "--enable-cdef=0",
948+ // Loop restoration is a named refusal (aomenc's RD picks
949+ // Sgrproj on this kind of content) -- off in every recipe
950+ // whose test targets a different surface.
951+ "--enable-restoration=0",
840952 "--max-partition-size=32",
841953 "--enable-palette=0",
842954 "--enable-intrabc=0",
@@ -964,6 +1076,10 @@ mod tests {
9641076 "--enable-angle-delta=0",
9651077 "--enable-tx-size-search=0",
9661078 "--enable-cdef=0",
1079+ // Loop restoration is a named refusal (aomenc's RD picks
1080+ // Sgrproj on this kind of content) -- off in every recipe
1081+ // whose test targets a different surface.
1082+ "--enable-restoration=0",
9671083 "--max-partition-size=32",
9681084 "--enable-palette=0",
9691085 "--enable-intrabc=0",
@@ -1014,6 +1130,180 @@ mod tests {
10141130 }
10151131 }
10161132
1133+ /// The decisive cross-frame CDF forwarding test: identical to
1134+ /// [`a_real_aomenc_inter_sequence_with_deblocking_decodes_pixel_exact`]
1135+ /// except it drops `--error-resilient=1`, so aomenc codes every inter
1136+ /// frame's `primary_ref_frame` at its default (not `PRIMARY_REF_NONE`)
1137+ /// and expects the decoder to resume from the previous frame's *adapted*
1138+ /// CDF state (spec 7.20 `load_cdfs`). Without cross-frame forwarding,
1139+ /// frame 1's very first tile symbol desyncs (an out-of-alphabet
1140+ /// partition read); with it, every frame decodes pixel-exact.
1141+ #[test]
1142+ fn a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact() {
1143+ if !have_ffmpeg() {
1144+ eprintln!(
1145+ "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no ffmpeg"
1146+ );
1147+ return;
1148+ }
1149+ if !have_aomenc() {
1150+ eprintln!(
1151+ "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: no aomenc at {}",
1152+ aomenc_path().display()
1153+ );
1154+ return;
1155+ }
1156+ let (width, height, frame_count) = (64usize, 64usize, 4usize);
1157+ // aomenc's RD is nondeterministic run to run even on a fixed fixture:
1158+ // most encodes of this recipe trip one of the decoder's NAMED round-2
1159+ // refusals (a reference other than LAST_FRAME, a sub-16 partition --
1160+ // genuine coverage gaps, separately documented), and only some produce
1161+ // a stream fully inside this decoder's declared support. So: attempt
1162+ // several seeds, and the first stream that DECODES must be pixel-exact
1163+ // -- that assertion is what guards the forwarded-CDF state (a wrong
1164+ // table decodes plausible-but-wrong pixels; the counter-reset bug this
1165+ // gate caught did exactly that). Exhausting every attempt on named
1166+ // refusals skips loudly, listing them.
1167+ let mut refusals = Vec::new();
1168+ for attempt in 0..8u32 {
1169+ let seed = 42 + attempt;
1170+ let source = format!("gradients=size=64x64:seed={seed}:duration=0.16:rate=25");
1171+ let y4m = Command::new("ffmpeg")
1172+ .args([
1173+ "-v",
1174+ "error",
1175+ "-f",
1176+ "lavfi",
1177+ "-i",
1178+ &source,
1179+ "-pix_fmt",
1180+ "yuv420p",
1181+ "-f",
1182+ "yuv4mpegpipe",
1183+ "-",
1184+ ])
1185+ .stdin(Stdio::null())
1186+ .stdout(Stdio::piped())
1187+ .stderr(Stdio::piped())
1188+ .output()
1189+ .expect("ffmpeg failed to run");
1190+ assert!(
1191+ y4m.status.success(),
1192+ "ffmpeg fixture: {}",
1193+ String::from_utf8_lossy(&y4m.stderr)
1194+ );
1195+ let mut child = Command::new(aomenc_path())
1196+ .args([
1197+ "--codec=av1",
1198+ "--passes=1",
1199+ "--end-usage=q",
1200+ "--cq-level=55",
1201+ "--cpu-used=0",
1202+ "--lag-in-frames=0",
1203+ "--auto-alt-ref=0",
1204+ "--kf-max-dist=1000",
1205+ // `--threads=1` (not the default): a multithreaded RD search
1206+ // makes aomenc's screen-content-tools heuristic race (seen
1207+ // flaky under `cargo test`'s own parallelism -- the same
1208+ // fixture, same seed, occasionally sets
1209+ // `allow_screen_content_tools`, a round-2 gap unrelated to
1210+ // CDF forwarding), so pin it to one thread for a
1211+ // deterministic header.
1212+ "--threads=1",
1213+ "--row-mt=0",
1214+ // No `--error-resilient=1` here (that is the whole point of
1215+ // this test), but every other reference/compound tool this
1216+ // decoder's round-2 inter path does not model is still
1217+ // disabled the same way `--error-resilient=1` incidentally
1218+ // disabled it in the sibling test above: without
1219+ // `--enable-order-hint=0` aomenc's RD search picks a
1220+ // non-`LAST_FRAME` reference (`GOLDEN_FRAME`) for some
1221+ // blocks even in this short a sequence, which is a separate,
1222+ // already-documented round-2 gap ("a reference frame other
1223+ // than LAST_FRAME"), not a CDF-forwarding one.
1224+ "--enable-order-hint=0",
1225+ "--enable-warped-motion=0",
1226+ "--enable-obmc=0",
1227+ "--enable-masked-comp=0",
1228+ "--enable-interintra-comp=0",
1229+ "--enable-dist-wtd-comp=0",
1230+ "--enable-diff-wtd-comp=0",
1231+ "--enable-onesided-comp=0",
1232+ "--enable-interintra-wedge=0",
1233+ "--enable-smooth-interintra=0",
1234+ "--enable-rect-partitions=0",
1235+ "--enable-ab-partitions=0",
1236+ "--enable-1to4-partitions=0",
1237+ "--enable-filter-intra=0",
1238+ "--enable-smooth-intra=0",
1239+ "--enable-paeth-intra=0",
1240+ "--enable-directional-intra=0",
1241+ "--enable-angle-delta=0",
1242+ "--enable-tx-size-search=0",
1243+ "--enable-cdef=0",
1244+ // Loop restoration is a named refusal (aomenc's RD picks
1245+ // Sgrproj on this kind of content) -- off in every recipe
1246+ // whose test targets a different surface.
1247+ "--enable-restoration=0",
1248+ "--max-partition-size=32",
1249+ "--enable-palette=0",
1250+ "--enable-intrabc=0",
1251+ "--enable-cfl-intra=0",
1252+ "--obu",
1253+ "-o",
1254+ "-",
1255+ "-",
1256+ ])
1257+ .stdin(Stdio::piped())
1258+ .stdout(Stdio::piped())
1259+ .stderr(Stdio::piped())
1260+ .spawn()
1261+ .expect("aomenc failed to start");
1262+ child
1263+ .stdin
1264+ .take()
1265+ .expect("aomenc stdin")
1266+ .write_all(&y4m.stdout)
1267+ .expect("writing y4m to aomenc");
1268+ let out = child.wait_with_output().expect("aomenc failed to run");
1269+ assert!(
1270+ out.status.success(),
1271+ "aomenc refused the fixture: {}",
1272+ String::from_utf8_lossy(&out.stderr)
1273+ );
1274+ let stream = out.stdout;
1275+ // A named `unsupported` refusal is a documented coverage gap (each
1276+ // one carries its own test debt elsewhere), not a forwarding verdict
1277+ // -- try the next seed. Any stream that DECODES must be pixel-exact,
1278+ // and any non-refusal error is a hard failure.
1279+ let frames = match decode_stream(&stream) {
1280+ Err(e) => {
1281+ let msg = e.to_string();
1282+ assert!(
1283+ msg.contains("unsupported"),
1284+ "cross-frame CDF forwarding failed outright (seed {seed}): {msg}"
1285+ );
1286+ refusals.push(format!("seed {seed}: {msg}"));
1287+ continue;
1288+ }
1289+ Ok(frames) => frames,
1290+ };
1291+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
1292+ assert_eq!(frames.len(), frame_count);
1293+ for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() {
1294+ assert_eq!(got.y, want.y, "frame {i} luma vs ffmpeg (seed {seed})");
1295+ assert_eq!(got.u, want.u, "frame {i} U vs ffmpeg (seed {seed})");
1296+ assert_eq!(got.v, want.v, "frame {i} V vs ffmpeg (seed {seed})");
1297+ }
1298+ return;
1299+ }
1300+ eprintln!(
1301+ "SKIP a_real_aomenc_inter_sequence_with_cdf_forwarding_decodes_pixel_exact: every \
1302+ attempt hit a named refusal:\n{}",
1303+ refusals.join("\n")
1304+ );
1305+ }
1306+
10171307 /// scratch: isolate a pinned mismatching stream's first divergent pixel.
10181308 #[test]
10191309 #[ignore]
@@ -1035,51 +1325,60 @@ mod tests {
10351325 );
10361326 eprintln!("delta: {:?}", header.delta);
10371327 eprintln!("segmentation: {:?}", header.segmentation);
1328+ eprintln!("loop_restoration: {:?}", header.loop_restoration);
1329+ eprintln!(
1330+ "use_128x128_superblock: {:?} disable_cdf_update: {:?} disable_frame_end_update_cdf: {:?} primary_ref_frame: {:?} allow_high_precision_mv: {:?} force_integer_mv: {:?}",
1331+ p.sequence_header().map(|s| s.use_128x128_superblock),
1332+ header.disable_cdf_update,
1333+ header.disable_frame_end_update_cdf,
1334+ header.primary_ref_frame,
1335+ header.allow_high_precision_mv,
1336+ header.force_integer_mv,
1337+ );
10381338 }
10391339 }
10401340 }
1041- let width = 32;
1042- let height = 32;
1341+ let width = std::env::var("EC_AV1_PIN_W")
1342+ .map(|s| s.parse().unwrap())
1343+ .unwrap_or(64);
1344+ let height = std::env::var("EC_AV1_PIN_H")
1345+ .map(|s| s.parse().unwrap())
1346+ .unwrap_or(64);
1347+ let frame_count = std::env::var("EC_AV1_PIN_N")
1348+ .map(|s| s.parse().unwrap())
1349+ .unwrap_or(4);
10431350 let frames = decode_stream(&stream).expect("our decode");
1044- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
1045- let ours = &frames[0];
1046- let theirs = &ffmpeg_frames[0];
1047- for (plane_name, a, b, w) in [
1048- ("y", &ours.y, &theirs.y, width),
1049- ("u", &ours.u, &theirs.u, width / 2),
1050- ("v", &ours.v, &theirs.v, width / 2),
1051- ] {
1052- let mut first = None;
1053- let mut count = 0;
1054- for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
1055- if x != y {
1056- count += 1;
1057- if first.is_none() {
1058- first = Some(i);
1351+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
1352+ for f in 0..frame_count.min(frames.len()).min(ffmpeg_frames.len()) {
1353+ let ours = &frames[f];
1354+ let theirs = &ffmpeg_frames[f];
1355+ for (plane_name, a, b, w) in [
1356+ ("y", &ours.y, &theirs.y, width),
1357+ ("u", &ours.u, &theirs.u, width / 2),
1358+ ("v", &ours.v, &theirs.v, width / 2),
1359+ ] {
1360+ let mut first = None;
1361+ let mut count = 0;
1362+ for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
1363+ if x != y {
1364+ count += 1;
1365+ if first.is_none() {
1366+ first = Some(i);
1367+ }
10591368 }
10601369 }
1370+ if let Some(i) = first {
1371+ eprintln!(
1372+ "frame {f} plane {plane_name}: {count} mismatches, first at offset {i} (row {}, col {}) ours={} theirs={}",
1373+ i / w,
1374+ i % w,
1375+ a[i],
1376+ b[i]
1377+ );
1378+ } else {
1379+ eprintln!("frame {f} plane {plane_name}: MATCH");
1380+ }
10611381 }
1062- if let Some(i) = first {
1063- eprintln!(
1064- "plane {plane_name}: {count} mismatches, first at offset {i} (row {}, col {}) ours={} theirs={}",
1065- i / w,
1066- i % w,
1067- a[i],
1068- b[i]
1069- );
1070- } else {
1071- eprintln!("plane {plane_name}: MATCH");
1072- }
1073- }
1074- for row in 0..8 {
1075- eprintln!(
1076- "ours row{row}: {:?}",
1077- &ours.y[row * width..row * width + 8]
1078- );
1079- eprintln!(
1080- "theirs row{row}: {:?}",
1081- &theirs.y[row * width..row * width + 8]
1082- );
10831382 }
10841383 }
10851384 }