diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 87e10e72..fd714113 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -13279,7 +13279,7 @@ mod tests { eprintln!("SKIP probe_intrabc_key_frame: no OBS recording"); return; }; - let (width, height) = (640usize, 384usize); + let (width, height) = (1280usize, 768usize); let picture = clip_frame(clip, "0", width, height); eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |"); for q in [5u8, 20, 35, 45] { @@ -14938,6 +14938,77 @@ mod tests { /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is /// the instrument the inter `TxMode::Select` hunt lacked; on failure it /// names the first differing frame, plane and position. + /// lane-sb128b: the writer used to price a `NEWMV` residual against + /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the + /// write-time stack could not carry, while the drl symbols signalled the + /// clamped index -- so the decoder derived a DIFFERENT motion vector with + /// the entropy stream still in sync, and the drift only surfaced frames + /// later as a drl desync (on film B, as the encoder's own trial decode + /// refusing a reference slot). + /// + /// The clamp needs a stack that shrinks between search and write, which + /// is what a 128x128 superblock's visit order does; the counter is the + /// point (class `gate-blind-to-feature`): a green round trip on a clip + /// that never clamps proves nothing. + /// + /// `#[ignore]`: [`force_sb128`] moves a process-global. + /// + /// cargo test -p ec-av1 --release --lib -- --ignored \ + /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture + #[test] + #[ignore = "sets the process-global superblock size: run it alone"] + fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() { + let _knobs = crate::speed::knob_write(); + if !have_ffmpeg() { + eprintln!("SKIP: no ffmpeg"); + return; + } + force_sb128(true); + let dir = std::env::temp_dir().join(format!("ec-av1-sb128b-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let clip = dir.join("mandelbrot-1280x768.y4m"); + let ok = Command::new("ffmpeg") + .args(["-v", "error", "-y", "-f", "lavfi", "-i", "mandelbrot=size=1280x768:rate=24"]) + .args(["-frames:v", "12", "-pix_fmt", "yuv420p"]) + .arg(&clip) + .status() + .expect("ffmpeg failed to run") + .success(); + assert!(ok, "ffmpeg could not write the synthetic clip"); + let path = clip.to_str().unwrap(); + let (width, height) = (1280usize, 768usize); + let pictures = crate::probe::source(path, "0", "null", width, height, 12); + + let _ = crate::tile::take_drl_clamp_hits(); + let encoded = encode_sequence(&pictures, 150, 0.5).unwrap(); + let clamps = crate::tile::take_drl_clamp_hits(); + assert!( + clamps > 0, + "this clip never asked for a drl index the write-time stack could not carry, \ + so it cannot witness the defect" + ); + eprintln!("clamped drl indices: {clamps}"); + + let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); + assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); + for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { + let recon = &frame.reconstruction; + for (plane, got, want) in [ + ("luma", &dec.y, &recon.y), + ("U", &dec.u, &recon.u), + ("V", &dec.v, &recon.v), + ] { + let differ = got.iter().zip(want).filter(|(a, b)| a != b).count(); + assert_eq!( + differ, 0, + "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \ + own reconstruction", + got.len() + ); + } + } + } + #[test] fn every_frame_of_a_sequence_decodes_through_our_own_decoder() { let _knobs = crate::speed::knob_read(); diff --git a/crates/ec-av1/src/tile.rs b/crates/ec-av1/src/tile.rs index 092d9e86..fcb280ca 100644 --- a/crates/ec-av1/src/tile.rs +++ b/crates/ec-av1/src/tile.rs @@ -1042,10 +1042,13 @@ fn write_compound_block( } walk += 1; } - stack - .entries - .get(walk) - .map_or(stack.near_mv, |e| (e.mv0, e.mv1)) + let near = |i: usize| { + stack.entries.get(i).map_or(stack.near_mv, |e| (e.mv0, e.mv1)) + }; + if walk != idx && near(walk) != near(idx) { + note_drl_clamp(idx, walk, stack.entries.len()); + } + near(walk) } InterMode::NearestNewMv | InterMode::NewNearestMv => { // Neither mode codes a DRL index (the decoder leaves `ref_mv_idx` @@ -1074,10 +1077,13 @@ fn write_compound_block( } walk += 1; } - let base = stack - .entries - .get(walk) - .map_or(stack.nearest_mv, |e| (e.mv0, e.mv1)); + let nearest = |i: usize| { + stack.entries.get(i).map_or(stack.nearest_mv, |e| (e.mv0, e.mv1)) + }; + if walk != idx && nearest(walk) != nearest(idx) { + note_drl_clamp(idx, walk, stack.entries.len()); + } + let base = nearest(walk); write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base.0)?; write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv1, base.1)?; (info.mv, info.mv1) @@ -5937,6 +5943,26 @@ pub(crate) fn take_ref_hits() -> [usize; 7] { } /// Bumps the two histograms for one coded inter block. +/// How many blocks this process wrote whose search-chosen `ref_mv_idx` the +/// write-time stack could not carry, so the writer signalled a SMALLER index +/// (lane-sb128b). Every one of these used to price its residual against a +/// predictor the decoder never derives. +static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Counts one clamped DRL index whose predictor differs from the one the +/// search asked for -- the harmful case, and the only one a witness can see. +fn note_drl_clamp(target: usize, signalled: usize, entries: usize) { + DRL_CLAMP_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if crate::envflags::env_flag!("EC_AV1_TRACE") { + eprintln!("DRL_CLAMP target={target} signalled={signalled} entries={entries}"); + } +} + +/// Takes and clears [`DRL_CLAMP_HITS`], for a gate's own before/after delta. +pub(crate) fn take_drl_clamp_hits() -> usize { + DRL_CLAMP_HITS.swap(0, std::sync::atomic::Ordering::Relaxed) +} + fn note_inter_mode(mode: usize, drl: usize) { INTER_MODE_HITS[mode].fetch_add(1, std::sync::atomic::Ordering::Relaxed); DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); @@ -6016,8 +6042,12 @@ fn write_inter_mode( match info.mode { InterMode::NewMv => { enc.symbol(0, &mut cdfs.new_mv[stack.new_mv_ctx]); - let idx = write_drl_idx(enc, cdfs, stack, 0, idx); - let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); + let signalled = write_drl_idx(enc, cdfs, stack, 0, idx); + let base = stack.entries.get(signalled).map_or(stack.pred_mv, |e| e.mv); + if signalled != idx && base != stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv) { + note_drl_clamp(idx, signalled, stack.entries.len()); + } + let idx = signalled; write_mv(enc, &mut cdfs.mv_comp, &mut cdfs.mv_joint, info.mv, base)?; note_inter_mode(3, idx); Ok((info.mv, true)) @@ -6041,8 +6071,12 @@ fn write_inter_mode( enc.symbol(1, &mut cdfs.ref_mv[stack.ref_mv_ctx]); // NEARMV // `RefMvIdx` starts at 1 for NEARMV (spec 5.11.24). let idx = idx.max(1); - let idx = write_drl_idx(enc, cdfs, stack, 1, idx); - let mv = stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv); + let signalled = write_drl_idx(enc, cdfs, stack, 1, idx); + let mv = stack.entries.get(signalled).map_or(stack.near_mv, |e| e.mv); + if signalled != idx && mv != stack.entries.get(idx).map_or(stack.near_mv, |e| e.mv) { + note_drl_clamp(idx, signalled, stack.entries.len()); + } + let idx = signalled; note_inter_mode(1, idx); Ok((mv, false)) }