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> {
96 }96 }
97 97
98 /// Every table a key frame's tile writer adapts.98 /// Every table a key frame's tile writer adapts.
99+#[derive(Clone)]
99 pub(crate) struct Cdfs {100 pub(crate) struct Cdfs {
100 /// The partition symbol of a 64x64 superblock.101 /// The partition symbol of a 64x64 superblock.
101 pub partition_w64: [[u16; 11]; 4],102 pub partition_w64: [[u16; 11]; 4],
@@ -271,14 +272,19 @@ pub(crate) struct MvComponentCdfs {
271 pub class0_bit: [u16; 3],272 pub class0_bit: [u16; 3],
272 /// The fractional part of a small-class magnitude, by its integer bit.273 /// The fractional part of a small-class magnitude, by its integer bit.
273 pub class0_fr: [[u16; 5]; 2],274 pub class0_fr: [[u16; 5]; 2],
274- // `class0_hp`/`hp` (spec's half-pel-bit CDFs) are never written: this275+ /// The half-pel bit of a small-class magnitude (spec `mv_class0_hp`),
275- // encoder always sets `allow_high_precision_mv = false`, so the syntax276+ /// read only when the frame header sets `allow_high_precision_mv` (a
276- // that reads them (spec 5.9.32 `mv_class0_hp`/`mv_hp`) never fires --277+ /// real encoder's choice, not this crate's own writer's -- which always
277- // dropped rather than kept dead. Add back if/when hp mode ships.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],
278 /// One bit of an above-small-class magnitude, by its position.281 /// One bit of an above-small-class magnitude, by its position.
279 pub bit: [[u16; 3]; 10],282 pub bit: [[u16; 3]; 10],
280 /// The fractional part of an above-small-class magnitude.283 /// The fractional part of an above-small-class magnitude.
281 pub fr: [u16; 5],284 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],
282 /// The component's sign.288 /// The component's sign.
283 pub sign: [u16; 3],289 pub sign: [u16; 3],
284 }290 }
@@ -289,8 +295,10 @@ impl MvComponentCdfs {
289 class: cdf::MV_CLASS,295 class: cdf::MV_CLASS,
290 class0_bit: cdf::MV_CLASS0_BIT,296 class0_bit: cdf::MV_CLASS0_BIT,
291 class0_fr: cdf::MV_CLASS0_FR,297 class0_fr: cdf::MV_CLASS0_FR,
298+ class0_hp: cdf::MV_CLASS0_HP,
292 bit: cdf::MV_BIT,299 bit: cdf::MV_BIT,
293 fr: cdf::MV_FR,300 fr: cdf::MV_FR,
301+ hp: cdf::MV_HP,
294 sign: cdf::MV_SIGN,302 sign: cdf::MV_SIGN,
295 }303 }
296 }304 }
@@ -308,7 +316,126 @@ pub(crate) fn pick<T: Copy>(q_ctx: usize, q0: T, q1: T, q2: T, q3: T) -> T {
308 }316 }
309 }317 }
310 318
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+
311 impl Cdfs {353 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+
312 /// The defaults a key frame starts from (spec 8.4, `init_coeff_cdfs` and439 /// The defaults a key frame starts from (spec 8.4, `init_coeff_cdfs` and
313 /// `init_non_coeff_cdfs`), for coefficient q-context `q_ctx` (0..=3, spec440 /// `init_non_coeff_cdfs`), for coefficient q-context `q_ctx` (0..=3, spec
314 /// 8.3.2's `Get_Qctx`). The non-coefficient tables do not vary with the441 /// 8.3.2's `Get_Qctx`). The non-coefficient tables do not vary with the
crates/ec-av1/src/decode.rsmodified+145 -18
@@ -115,7 +115,7 @@ fn unsupported(what: impl Into<String>) -> Error {
115 /// The coefficient q-context a frame's `base_q_idx` picks its default CDFs115 /// The coefficient q-context a frame's `base_q_idx` picks its default CDFs
116 /// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the116 /// from (spec `Get_Qctx`), mirroring [`crate::tile`]'s private copy of the
117 /// same rule.117 /// same rule.
118-fn q_ctx_of(base_q_idx: u8) -> usize {118+pub(crate) fn q_ctx_of(base_q_idx: u8) -> usize {
119 match base_q_idx {119 match base_q_idx {
120 0..=20 => 0,120 0..=20 => 0,
121 21..=60 => 1,121 21..=60 => 1,
@@ -2078,6 +2078,41 @@ pub fn decode_key_frame_tile(
2078 cdef: &CdefParams,2078 cdef: &CdefParams,
2079 loop_filter: &LoopFilterParams,2079 loop_filter: &LoopFilterParams,
2080 ) -> Result<Picture> {2080 ) -> 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)> {
2081 if mi_cols == 0 || mi_rows == 0 {2116 if mi_cols == 0 || mi_rows == 0 {
2082 return Err(unsupported("a frame with no mode-info grid"));2117 return Err(unsupported("a frame with no mode-info grid"));
2083 }2118 }
@@ -2113,7 +2148,7 @@ pub fn decode_key_frame_tile(
2113 let scan8 = default_scan(TX8);2148 let scan8 = default_scan(TX8);
2114 let scan4 = default_scan(TX4);2149 let scan4 = default_scan(TX4);
2115 2150
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)));
2117 if std::env::var_os("EC_AV1_TRACE").is_some() {2152 if std::env::var_os("EC_AV1_TRACE").is_some() {
2118 eprintln!(2153 eprintln!(
2119 "TRACE key_tile_bytes len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",2154 "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(
2416 2451
2417 let (fw, fh) = (frame_width as usize, frame_height as usize);2452 let (fw, fh) = (frame_width as usize, frame_height as usize);
2418 if fw == width && fh == height {2453 if fw == width && fh == height {
2419- return Ok(Picture {2454+ return Ok((
2455+ Picture {
2420 width,2456 width,
2421 height,2457 height,
2422 y: y.data,2458 y: y.data,
2423 u: u.data,2459 u: u.data,
2424 v: v.data,2460 v: v.data,
2425- });2461+ },
2462+ cdfs,
2463+ ));
2426 }2464 }
2427 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {2465 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
2428 let mut out = Vec::with_capacity(w * h);2466 let mut out = Vec::with_capacity(w * h);
@@ -2431,13 +2469,16 @@ pub fn decode_key_frame_tile(
2431 }2469 }
2432 out2470 out
2433 };2471 };
2434- Ok(Picture {2472+ Ok((
2473+ Picture {
2435 width: fw,2474 width: fw,
2436 height: fh,2475 height: fh,
2437 y: crop(&y, fw, fh),2476 y: crop(&y, fw, fh),
2438 u: crop(&u, fw / 2, fh / 2),2477 u: crop(&u, fw / 2, fh / 2),
2439 v: crop(&v, fw / 2, fh / 2),2478 v: crop(&v, fw / 2, fh / 2),
2440- })2479+ },
2480+ cdfs,
2481+ ))
2441 }2482 }
2442 2483
2443 /// The `is_inter` context (spec 5.11.16 via `av1_get_intra_inter_context`),2484 /// 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 {
2468 /// One motion vector component's non-zero diff (spec 5.11.322509 /// One motion vector component's non-zero diff (spec 5.11.32
2469 /// `read_mv_component`), the inverse of [`crate::tile`]'s private2510 /// `read_mv_component`), the inverse of [`crate::tile`]'s private
2470 /// `write_mv_component`.2511 /// `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 {
2472 let sign = dec.symbol(&mut c.sign);2517 let sign = dec.symbol(&mut c.sign);
2473 let class = dec.symbol(&mut c.class);2518 let class = dec.symbol(&mut c.class);
2474 let local = if class == 0 {2519 let local = if class == 0 {
2475 let bit = dec.symbol(&mut c.class0_bit);2520 let bit = dec.symbol(&mut c.class0_bit);
2476 let fr = dec.symbol(&mut c.class0_fr[bit]);2521 let fr = dec.symbol(&mut c.class0_fr[bit]);
2477- (bit << 3) | (fr << 1) | 12522+ // 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
2478 } else {2532 } else {
2479 let mut d = 0;2533 let mut d = 0;
2480 for i in 0..class {2534 for i in 0..class {
2481 d |= dec.symbol(&mut c.bit[i]) << i;2535 d |= dec.symbol(&mut c.bit[i]) << i;
2482 }2536 }
2483 let fr = dec.symbol(&mut c.fr);2537 let fr = dec.symbol(&mut c.fr);
2484- (d << 3) | (fr << 1) | 12538+ let hp = if allow_high_precision_mv {
2539+ dec.symbol(&mut c.hp)
2540+ } else {
2541+ 1
2542+ };
2543+ (d << 3) | (fr << 1) | hp
2485 };2544 };
2486 let mag = mv_class_base(class) + local as i32 + 1;2545 let mag = mv_class_base(class) + local as i32 + 1;
2487 if sign == 1 { -mag } else { mag }2546 if sign == 1 { -mag } else { mag }
@@ -2494,14 +2553,15 @@ fn read_mv(
2494 mv_comp: &mut [MvComponentCdfs; 2],2553 mv_comp: &mut [MvComponentCdfs; 2],
2495 mv_joint: &mut [u16; 5],2554 mv_joint: &mut [u16; 5],
2496 pred: (i32, i32),2555 pred: (i32, i32),
2556+ allow_high_precision_mv: bool,
2497 ) -> (i32, i32) {2557 ) -> (i32, i32) {
2498 let joint = dec.symbol(mv_joint);2558 let joint = dec.symbol(mv_joint);
2499 let mut diff = (0, 0);2559 let mut diff = (0, 0);
2500 if joint == 2 || joint == 3 {2560 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);
2502 }2562 }
2503 if joint == 1 || joint == 3 {2563 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);
2505 }2565 }
2506 (pred.0 + diff.0, pred.1 + diff.1)2566 (pred.0 + diff.0, pred.1 + diff.1)
2507 }2567 }
@@ -2609,6 +2669,7 @@ fn decode_inter_block(
2609 scan_luma: &[u16],2669 scan_luma: &[u16],
2610 scan_chroma: &[u16],2670 scan_chroma: &[u16],
2611 size_group: usize,2671 size_group: usize,
2672+ allow_high_precision_mv: bool,
2612 ) -> Result<()> {2673 ) -> Result<()> {
2613 const LAST_FRAME: i8 = 1;2674 const LAST_FRAME: i8 = 1;
2614 2675
@@ -2657,7 +2718,13 @@ fn decode_inter_block(
2657 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);2718 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
2658 }2719 }
2659 (2720 (
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+ ),
2661 true,2728 true,
2662 )2729 )
2663 } else {2730 } else {
@@ -2691,6 +2758,12 @@ fn decode_inter_block(
2691 };2758 };
2692 (mv, false)2759 (mv, false)
2693 };2760 };
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+ }
2694 for dr in 0..bw4 {2767 for dr in 0..bw4 {
2695 for dc in 0..bw4 {2768 for dc in 0..bw4 {
2696 grid.set(2769 grid.set(
@@ -2997,6 +3070,7 @@ fn decode_inter_block8(
2997 scan8: &[u16],3070 scan8: &[u16],
2998 scan4: &[u16],3071 scan4: &[u16],
2999 prev_leaf: Option<((usize, usize), bool, bool)>,3072 prev_leaf: Option<((usize, usize), bool, bool)>,
3073+ allow_high_precision_mv: bool,
3000 ) -> Result<(bool, bool)> {3074 ) -> Result<(bool, bool)> {
3001 const LAST_FRAME: i8 = 1;3075 const LAST_FRAME: i8 = 1;
3002 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).3076 /// `Y_MODE`'s size group (`common_data.h`'s `size_group_lookup[BLOCK_8X8]`).
@@ -3059,7 +3133,13 @@ fn decode_inter_block8(
3059 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);3133 dec.symbol(&mut cdfs.drl_mode[stack.drl_ctx[0]]);
3060 }3134 }
3061 (3135 (
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+ ),
3063 true,3143 true,
3064 )3144 )
3065 } else {3145 } else {
@@ -3366,7 +3446,42 @@ pub fn decode_inter_frame_tile(
3366 reference: &Picture,3446 reference: &Picture,
3367 cdef: &CdefParams,3447 cdef: &CdefParams,
3368 loop_filter: &LoopFilterParams,3448 loop_filter: &LoopFilterParams,
3449+ allow_high_precision_mv: bool,
3369 ) -> Result<Picture> {3450 ) -> 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)> {
3370 if mi_cols == 0 || mi_rows == 0 {3485 if mi_cols == 0 || mi_rows == 0 {
3371 return Err(unsupported("a frame with no mode-info grid"));3486 return Err(unsupported("a frame with no mode-info grid"));
3372 }3487 }
@@ -3429,7 +3544,7 @@ pub fn decode_inter_frame_tile(
3429 let scan8 = default_scan(TX8);3544 let scan8 = default_scan(TX8);
3430 let scan4 = default_scan(TX4);3545 let scan4 = default_scan(TX4);
3431 3546
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)));
3433 let mut dec = SymbolDecoder::new(data);3548 let mut dec = SymbolDecoder::new(data);
3434 let mut neighbours = Neighbours::new(3549 let mut neighbours = Neighbours::new(
3435 cols as usize * 2,3550 cols as usize * 2,
@@ -3512,6 +3627,7 @@ pub fn decode_inter_frame_tile(
3512 &scan32,3627 &scan32,
3513 &scan16,3628 &scan16,
3514 3,3629 3,
3630+ allow_high_precision_mv,
3515 )?;3631 )?;
3516 }3632 }
3517 PARTITION_SPLIT => {3633 PARTITION_SPLIT => {
@@ -3564,6 +3680,7 @@ pub fn decode_inter_frame_tile(
3564 &scan16,3680 &scan16,
3565 &scan8,3681 &scan8,
3566 2,3682 2,
3683+ allow_high_precision_mv,
3567 )?;3684 )?;
3568 } else {3685 } else {
3569 let ctx16 = neighbours.partition_ctx(at16, SUB);3686 let ctx16 = neighbours.partition_ctx(at16, SUB);
@@ -3612,6 +3729,7 @@ pub fn decode_inter_frame_tile(
3612 &scan8,3729 &scan8,
3613 &scan4,3730 &scan4,
3614 prev_leaf,3731 prev_leaf,
3732+ allow_high_precision_mv,
3615 )?;3733 )?;
3616 prev_leaf = Some((leaf_mi, skip, is_inter));3734 prev_leaf = Some((leaf_mi, skip, is_inter));
3617 }3735 }
@@ -3634,13 +3752,16 @@ pub fn decode_inter_frame_tile(
3634 3752
3635 let (fw, fh) = (frame_width as usize, frame_height as usize);3753 let (fw, fh) = (frame_width as usize, frame_height as usize);
3636 if fw == width && fh == height {3754 if fw == width && fh == height {
3637- return Ok(Picture {3755+ return Ok((
3756+ Picture {
3638 width,3757 width,
3639 height,3758 height,
3640 y: y.data,3759 y: y.data,
3641 u: u.data,3760 u: u.data,
3642 v: v.data,3761 v: v.data,
3643- });3762+ },
3763+ cdfs,
3764+ ));
3644 }3765 }
3645 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {3766 let crop = |plane: &PlaneBuf, w: usize, h: usize| -> Vec<u8> {
3646 let mut out = Vec::with_capacity(w * h);3767 let mut out = Vec::with_capacity(w * h);
@@ -3649,13 +3770,16 @@ pub fn decode_inter_frame_tile(
3649 }3770 }
3650 out3771 out
3651 };3772 };
3652- Ok(Picture {3773+ Ok((
3774+ Picture {
3653 width: fw,3775 width: fw,
3654 height: fh,3776 height: fh,
3655 y: crop(&y, fw, fh),3777 y: crop(&y, fw, fh),
3656 u: crop(&u, fw / 2, fh / 2),3778 u: crop(&u, fw / 2, fh / 2),
3657 v: crop(&v, fw / 2, fh / 2),3779 v: crop(&v, fw / 2, fh / 2),
3658- })3780+ },
3781+ cdfs,
3782+ ))
3659 }3783 }
3660 3784
3661 #[cfg(test)]3785 #[cfg(test)]
@@ -4085,6 +4209,7 @@ mod tests {
4085 &reference,4209 &reference,
4086 &CdefParams::default(),4210 &CdefParams::default(),
4087 &LoopFilterParams::default(),4211 &LoopFilterParams::default(),
4212+ false,
4088 )4213 )
4089 .unwrap();4214 .unwrap();
4090 assert_eq!(4215 assert_eq!(
@@ -4258,6 +4383,7 @@ mod tests {
4258 &[],4383 &[],
4259 &[],4384 &[],
4260 0,4385 0,
4386+ false,
4261 )4387 )
4262 .unwrap();4388 .unwrap();
4263 4389
@@ -4345,6 +4471,7 @@ mod tests {
4345 &reference,4471 &reference,
4346 &CdefParams::default(),4472 &CdefParams::default(),
4347 &LoopFilterParams::default(),4473 &LoopFilterParams::default(),
4474+ false,
4348 )4475 )
4349 .unwrap();4476 .unwrap();
4350 assert_eq!(decoded.y, ffmpeg_frames[i].y, "frame {i} luma vs ffmpeg");4477 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> {
299 /// [`SymbolEncoder::symbol_fixed`].299 /// [`SymbolEncoder::symbol_fixed`].
300 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {300 pub fn symbol_fixed(&mut self, cdf: &[u16]) -> usize {
301 let nsyms = cdf.len() - 1;301 let nsyms = cdf.len() - 1;
302+ let rng_before = self.range;
302 let mut cur = self.range;303 let mut cur = self.range;
303 let mut prev;304 let mut prev;
304 let mut symbol = 0;305 let mut symbol = 0;
@@ -314,6 +315,15 @@ impl<'a> SymbolDecoder<'a> {
314 }315 }
315 self.range = prev - cur;316 self.range = prev - cur;
316 self.value -= cur;317 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+ }
317 327
318 // Renormalise back into `[2^15, 2^16)`, the same shift the encoder328 // Renormalise back into `[2^15, 2^16)`, the same shift the encoder
319 // applied when it narrowed to this symbol.329 // applied when it narrowed to this symbol.
crates/ec-av1/src/stream.rsmodified+326 -27
@@ -1,20 +1,31 @@
1 //! The stream-level entry point a real decoder needs: walk a raw AV1 OBU1 //! The stream-level entry point a real decoder needs: walk a raw AV1 OBU
2 //! stream (`Encoded::stream`, or any low-overhead-format bitstream this2 //! stream (`Encoded::stream`, or any low-overhead-format bitstream this
3 //! crate's own writers produce) via [`ec_av1_syntax::Av1Parser`] and dispatch3 //! 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`] /4+//! each frame's tile payload to [`crate::decode::decode_key_frame_tile_with_cdfs`] /
5-//! [`crate::decode::decode_inter_frame_tile`], threading a single-slot DPB5+//! [`crate::decode::decode_inter_frame_tile_with_cdfs`], threading a
6-//! exactly as [`crate::encode::encode_sequence`] does on the write side.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.
7 //!12 //!
8 //! This is the only reachable path for a caller that does not have the13 //! This is the only reachable path for a caller that does not have the
9 //! encoder's own `Encoded::tile`/`mi_cols`/`mi_rows`/`base_q_idx` fields (they14 //! encoder's own `Encoded::tile`/`mi_cols`/`mi_rows`/`base_q_idx` fields (they
10 //! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is15 //! are `pub(crate)`, and rightly so: the wire is `stream`, everything else is
11 //! an implementation detail of how this crate happens to build it).16 //! an implementation detail of how this crate happens to build it).
12 17
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+};
14 use ec_core::{Error, Result};21 use ec_core::{Error, Result};
15 22
23+use crate::cdf_state::Cdfs;
16 use crate::decode;24 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+};
18 use crate::encode::Picture;29 use crate::encode::Picture;
19 30
20 /// Decode every frame in a raw AV1 OBU stream, in coding order.31 /// Decode every frame in a raw AV1 OBU stream, in coding order.
@@ -35,7 +46,24 @@ use crate::encode::Picture;
35 pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {46 pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
36 let mut parser = Av1Parser::new();47 let mut parser = Av1Parser::new();
37 let mut pictures = Vec::new();48 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);
39 67
40 let mut pos = 0usize;68 let mut pos = 0usize;
41 while pos < data.len() {69 while pos < data.len() {
@@ -110,6 +138,18 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
110 "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",138 "a frame with segmentation enabled (this decoder never reads a per-block segment_id symbol)",
111 ));139 ));
112 }140 }
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+ }
113 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec153 // `decode_inter_block`/`decode_inter_block8`'s `GLOBALMV` arm (spec
114 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`154 // 5.11.26's `read_inter_intra`... really `assign_mv`'s `GLOBALMV`
115 // case, spec 7.10.2.1) uses `gm_get_motion_vector`, which is the155 // 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>> {
125 "an inter frame whose LAST_FRAME global motion is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)",165 "an inter frame whose LAST_FRAME global motion is not IDENTITY (GLOBALMV needs the full warp derivation this decoder does not carry)",
126 ));166 ));
127 }167 }
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+ }
128 // `Tile::offset` is relative to the buffer `parse_obu` was handed179 // `Tile::offset` is relative to the buffer `parse_obu` was handed
129 // (`&data[pos..]` at the time this OBU was parsed), so it is relative180 // (`&data[pos..]` at the time this OBU was parsed), so it is relative
130 // to `obu_offset`, not to `data` as a whole.181 // to `obu_offset`, not to `data` as a whole.
@@ -134,8 +185,25 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
134 .sequence_header()185 .sequence_header()
135 .is_some_and(|seq| seq.enable_filter_intra);186 .is_some_and(|seq| seq.enable_filter_intra);
136 187
137- let picture = if header.frame_type == FrameType::Key {188+ // Spec 7.20 `load_cdfs`: a frame naming a `primary_ref_frame` resumes
138- decode_key_frame_tile(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(
139 tile_bytes,207 tile_bytes,
140 header.mi_cols,208 header.mi_cols,
141 header.mi_rows,209 header.mi_rows,
@@ -145,15 +213,17 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
145 enable_filter_intra,213 enable_filter_intra,
146 &header.cdef,214 &header.cdef,
147 &header.loop_filter,215 &header.loop_filter,
216+ initial_cdfs,
148 )?217 )?
149 } else {218 } 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(|| {
151 Error::unsupported(221 Error::unsupported(
152 "AV1 decode_stream",222 "AV1 decode_stream",
153 "an inter frame with no key frame before it",223 "an inter frame with no key frame before it",
154 )224 )
155 })?;225 })?;
156- decode_inter_frame_tile(226+ decode_inter_frame_tile_with_cdfs(
157 tile_bytes,227 tile_bytes,
158 header.mi_cols,228 header.mi_cols,
159 header.mi_rows,229 header.mi_rows,
@@ -163,9 +233,47 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
163 reference,233 reference,
164 &header.cdef,234 &header.cdef,
165 &header.loop_filter,235 &header.loop_filter,
236+ initial_cdfs,
237+ header.allow_high_precision_mv,
166 )?238 )?
167 };239 };
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+ }
169 pictures.push(picture);277 pictures.push(picture);
170 }278 }
171 Ok(pictures)279 Ok(pictures)
@@ -837,6 +945,10 @@ mod tests {
837 "--enable-angle-delta=0",945 "--enable-angle-delta=0",
838 "--enable-tx-size-search=0",946 "--enable-tx-size-search=0",
839 "--enable-cdef=0",947 "--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",
840 "--max-partition-size=32",952 "--max-partition-size=32",
841 "--enable-palette=0",953 "--enable-palette=0",
842 "--enable-intrabc=0",954 "--enable-intrabc=0",
@@ -964,6 +1076,10 @@ mod tests {
964 "--enable-angle-delta=0",1076 "--enable-angle-delta=0",
965 "--enable-tx-size-search=0",1077 "--enable-tx-size-search=0",
966 "--enable-cdef=0",1078 "--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",
967 "--max-partition-size=32",1083 "--max-partition-size=32",
968 "--enable-palette=0",1084 "--enable-palette=0",
969 "--enable-intrabc=0",1085 "--enable-intrabc=0",
@@ -1014,6 +1130,180 @@ mod tests {
1014 }1130 }
1015 }1131 }
1016 1132
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+
1017 /// scratch: isolate a pinned mismatching stream's first divergent pixel.1307 /// scratch: isolate a pinned mismatching stream's first divergent pixel.
1018 #[test]1308 #[test]
1019 #[ignore]1309 #[ignore]
@@ -1035,15 +1325,33 @@ mod tests {
1035 );1325 );
1036 eprintln!("delta: {:?}", header.delta);1326 eprintln!("delta: {:?}", header.delta);
1037 eprintln!("segmentation: {:?}", header.segmentation);1327 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+ );
1038 }1338 }
1039 }1339 }
1040 }1340 }
1041- let width = 32;1341+ let width = std::env::var("EC_AV1_PIN_W")
1042- let height = 32;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);
1043 let frames = decode_stream(&stream).expect("our decode");1350 let frames = decode_stream(&stream).expect("our decode");
1044- let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);1351+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, frame_count);
1045- let ours = &frames[0];1352+ for f in 0..frame_count.min(frames.len()).min(ffmpeg_frames.len()) {
1046- let theirs = &ffmpeg_frames[0];1353+ let ours = &frames[f];
1354+ let theirs = &ffmpeg_frames[f];
1047 for (plane_name, a, b, w) in [1355 for (plane_name, a, b, w) in [
1048 ("y", &ours.y, &theirs.y, width),1356 ("y", &ours.y, &theirs.y, width),
1049 ("u", &ours.u, &theirs.u, width / 2),1357 ("u", &ours.u, &theirs.u, width / 2),
@@ -1061,25 +1369,16 @@ mod tests {
1061 }1369 }
1062 if let Some(i) = first {1370 if let Some(i) = first {
1063 eprintln!(1371 eprintln!(
1064- "plane {plane_name}: {count} mismatches, first at offset {i} (row {}, col {}) ours={} theirs={}",1372+ "frame {f} plane {plane_name}: {count} mismatches, first at offset {i} (row {}, col {}) ours={} theirs={}",
1065 i / w,1373 i / w,
1066 i % w,1374 i % w,
1067 a[i],1375 a[i],
1068 b[i]1376 b[i]
1069 );1377 );
1070 } else {1378 } else {
1071- eprintln!("plane {plane_name}: MATCH");1379+ eprintln!("frame {f} plane {plane_name}: MATCH");
1072 }1380 }
1073 }1381 }
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- );
1083 }1382 }
1084 }1383 }
1085 }1384 }