forge
Explore
Log in

Don't you dare go Hollow

Motion_mode alphabet ignored force_integer_mv (and scaled refs)

Browse files at this commit

a9eda256e795d9320e4f6176da9208d8516ad019Ahmet Kaan GümüşParent: 01c42f6
  • fix
    • motion_mode alphabet ignored force_integer_mv (and scaled refs)
Show full message
fix(av1): motion_mode alphabet ignored force_integer_mv (and scaled refs)

libaom motion_mode_allowed (blockd.h ~1484) only returns WARPED_CAUSAL when
!xd->cur_frame_force_integer_mv && !av1_is_scaled(block_ref_scale_factors[0]);
our warp_eligible had neither clause, so a screen-content frame whose header
set force_integer_mv read the 3-symbol motion_mode_cdf where libaom wrote the
2-symbol obmc_cdf -- a silent tile desync with no refusal naming it (class
wrong-alphabet-same-value). Same clause swept into decode_inter_block8's own
8x8-leaf read.

Gate: a_real_force_integer_mv_warp_{,10bit_}stream_decodes_pixel_exact --
--tune-content=screen, --enable-warped-motion=1 --enable-obmc=1
--enable-global-motion=0 over static screen-content tiles with whole-pixel
motion (what aomenc's av1_is_integer_mv needs). Hard-asserts a decoded frame
header with force_integer_mv=1 and >=1 block forced onto the 2-symbol
alphabet. 6/6 pixel-exact both bit depths; the same gate is 0/6 with 6 named
refusals when the !force_integer_mv clause is removed.
crates/ec-av1/src/decode.rsmodified+79 -23
@@ -1113,6 +1113,42 @@ thread_local! {
11131113 const { std::cell::Cell::new(0) };
11141114 }
11151115
1116+// lane-fimv r1 (class wrong-alphabet-same-value): how many blocks took the
1117+// 2-symbol `obmc_cdf` alphabet *because* `force_integer_mv` (or a scaled
1118+// reference) vetoed `WARPED_CAUSAL` in libaom `motion_mode_allowed`, while
1119+// `allow_warped_motion == 1` and `num_proj_ref >= 1` would otherwise have
1120+// picked the 3-symbol `motion_mode_cdf`. These are exactly the blocks this
1121+// decoder used to read with the wrong alphabet, so a gate that asserts this
1122+// counter advanced proves the fixed path fired (class
1123+// `gate-blind-to-feature`).
1124+thread_local! {
1125+ static FIMV_ALPHABET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1126+}
1127+
1128+/// Current value of [`FIMV_ALPHABET_HITS`].
1129+pub fn fimv_alphabet_hits() -> usize {
1130+ FIMV_ALPHABET_HITS.with(|c| c.get())
1131+}
1132+
1133+// lane-fimv r1: how many frame headers this decoder has decoded with
1134+/// `force_integer_mv == 1` (bumped by `stream.rs` per frame). Lets a gate
1135+// prove the encoder really produced the header state under test rather than
1136+// assume it.
1137+thread_local! {
1138+ static FIMV_FRAME_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
1139+}
1140+
1141+/// Current value of [`FIMV_FRAME_HITS`].
1142+pub fn fimv_frame_hits() -> usize {
1143+ FIMV_FRAME_HITS.with(|c| c.get())
1144+}
1145+
1146+/// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
1147+/// `force_integer_mv` bit is set.
1148+pub fn note_force_integer_mv_frame() {
1149+ FIMV_FRAME_HITS.with(|c| c.set(c.get() + 1));
1150+}
1151+
11161152 /// Current value of [`OBMC_HITS`].
11171153 pub(crate) fn obmc_hits() -> usize {
11181154 OBMC_HITS.with(|c| c.get())
@@ -12345,27 +12381,40 @@ fn decode_inter_block(
1234512381 // `motion_mode_allowed` reads the 3-symbol `motion_mode_cdf`
1234612382 // instead of the 2-symbol `obmc_cdf` exactly when
1234712383 // `num_proj_ref >= 1` under `allow_warped_motion`.
12348- // lane-scaledref r2: libaom `motion_mode_allowed`
12349- // (`blockd.h:1484`) requires
12350- // `!av1_is_scaled(block_ref_scale_factors[0])` for
12351- // WARPED_CAUSAL -- under a scaled reference (superres) the
12352- // block reads the 2-symbol `obmc_cdf`, never the 3-symbol
12384+ // lane-scaledref r2 + lane-fimv r1: libaom
12385+ // `motion_mode_allowed` (`blockd.h:1484`) requires BOTH
12386+ // `!av1_is_scaled(block_ref_scale_factors[0])` and
12387+ // `!xd->cur_frame_force_integer_mv` for WARPED_CAUSAL --
12388+ // under a scaled reference (superres) OR on a frame whose
12389+ // header set `force_integer_mv` (screen content) the block
12390+ // reads the 2-symbol `obmc_cdf`, never the 3-symbol
1235312391 // `motion_mode_cdf`. Reading the wrong alphabet here narrows
1235412392 // the arithmetic coder by the wrong amount and predicts the
12355- // rest of the tile off a diverged state: it was silently
12356- // wrong pixels (r1's `--enable-warped-motion=1` superres
12357- // mismatch), not a desync error.
12393+ // rest of the tile off a diverged state: silently wrong
12394+ // pixels, not a desync error. `force_integer_mv` is the
12395+ // per-frame value (spec 5.9.2: coded per frame only when
12396+ // `seq_force_integer_mv == SELECT_INTEGER_MV`, threaded from
12397+ // `FrameHeader::force_integer_mv`).
1235812398 let ref_is_scaled =
1235912399 mc::scale_factor(py_ref.width, frame_width) != mc::REF_NO_SCALE;
12360- let warp_eligible = allow_warped_motion
12361- && !ref_is_scaled
12362- && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1;
12363- if allow_warped_motion
12364- && ref_is_scaled
12365- && num_proj_ref(grid, mi_row, mi_col, bw4, bh4, mi_cols as usize, mi_rows as usize, ref_frame) >= 1
12366- {
12400+ let proj_ok = num_proj_ref(
12401+ grid,
12402+ mi_row,
12403+ mi_col,
12404+ bw4,
12405+ bh4,
12406+ mi_cols as usize,
12407+ mi_rows as usize,
12408+ ref_frame,
12409+ ) >= 1;
12410+ let warp_eligible =
12411+ allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
12412+ if allow_warped_motion && proj_ok && ref_is_scaled {
1236712413 SCALED_WARP_SUPPRESSED_HITS.with(|c| c.set(c.get() + 1));
1236812414 }
12415+ if allow_warped_motion && proj_ok && !ref_is_scaled && force_integer_mv {
12416+ FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
12417+ }
1236912418 if warp_eligible {
1237012419 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
1237112420 match mode {
@@ -13999,14 +14048,21 @@ fn decode_inter_block8(
1399914048 // lane-warp round 1: same 3-vs-2-symbol split as the 16x16+ leaf
1400014049 // (see its own doc) -- this leaf is always `LAST_FRAME`-only
1400114050 // (grid.set below hardcodes it).
14002- // lane-scaledref r2 sibling of the 16x16+ leaf's fix: libaom
14003- // drops WARPED_CAUSAL eligibility (so this reads `obmc_cdf`)
14004- // when the reference is scaled. Not gated here because an 8x8
14005- // leaf under a scaled reference is refused before this function
14006- // runs (see the block8 refusal below, ~12500) -- whoever lifts
14007- // that refusal must add `&& !ref_is_scaled` here too.
14008- let warp_eligible = allow_warped_motion
14009- && num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, LAST_FRAME) >= 1;
14051+ // lane-scaledref r2 / lane-fimv r1 sibling of the 16x16+ leaf's
14052+ // fix: libaom drops WARPED_CAUSAL eligibility (so this reads
14053+ // `obmc_cdf`) when the reference is scaled or the frame set
14054+ // `force_integer_mv`. The scaled half is not gated here because
14055+ // an 8x8 leaf under a scaled reference is refused before this
14056+ // function runs (see the block8 refusal below, ~12500) --
14057+ // whoever lifts that refusal must add `&& !ref_is_scaled` here
14058+ // too.
14059+ let proj_ok =
14060+ num_proj_ref(grid, mi_row, mi_col, 2, 2, mi_cols as usize, mi_rows as usize, LAST_FRAME)
14061+ >= 1;
14062+ let warp_eligible = allow_warped_motion && !force_integer_mv && proj_ok;
14063+ if allow_warped_motion && proj_ok && force_integer_mv {
14064+ FIMV_ALPHABET_HITS.with(|c| c.set(c.get() + 1));
14065+ }
1401014066 if warp_eligible {
1401114067 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
1401214068 match mode {
crates/ec-av1/src/stream.rsmodified+213 -0
@@ -607,6 +607,11 @@ pub fn decode_stream(data: &[u8]) -> Result<Vec<Picture>> {
607607 // refuses by name there if the slot is still empty -- widened
608608 // (lane-av1refs) from `GOLDEN_FRAME`'s own slot alone to every
609609 // one of the 7 single-reference slots.
610+ // lane-fimv r1: record the header state the fimv gate asserts on
611+ // (`motion_mode_allowed`'s `!cur_frame_force_integer_mv` clause).
612+ if header.force_integer_mv {
613+ decode::note_force_integer_mv_frame();
614+ }
610615 let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| {
611616 if ref_frame == 0 {
612617 None
@@ -8133,6 +8138,214 @@ mod tests {
81338138 assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
81348139 }
81358140
8141+ /// lane-fimv r1 (class `wrong-alphabet-same-value`): libaom
8142+ /// `motion_mode_allowed` (blockd.h ~1484) only returns `WARPED_CAUSAL`
8143+ /// when `!xd->cur_frame_force_integer_mv`, so on a frame whose header set
8144+ /// `force_integer_mv` an otherwise warp-eligible block reads the 2-symbol
8145+ /// `obmc_cdf`, not the 3-symbol `motion_mode_cdf`. This decoder read the
8146+ /// 3-symbol alphabet there (silent tile desync, no refusal named it).
8147+ ///
8148+ /// The fixture is screen content that is mostly static with only
8149+ /// whole-pixel motion, which is exactly what aomenc's own
8150+ /// `av1_is_integer_mv` (`encoder_utils.c:1357`, >=80% of blocks matching
8151+ /// their collocated block) needs to set `cur_frame_force_integer_mv`
8152+ /// under `--tune-content=screen` (seq `force_integer_mv == 2`, adaptive:
8153+ /// `encoder.c:4171`). Two hard asserts, both class
8154+ /// `gate-blind-to-feature`: at least one decoded frame header carried
8155+ /// `force_integer_mv = 1`, and at least one block took the 2-symbol
8156+ /// alphabet where `allow_warped_motion = 1` and `num_proj_ref >= 1` would
8157+ /// have picked the 3-symbol one. A decode error or a pixel mismatch is a
8158+ /// FAILURE, never a skip.
8159+ #[track_caller]
8160+ fn run_fimv_motion_mode_gate(name: &str, ten_bit: bool) {
8161+ let _gate_lock = lock_gate_counters();
8162+ assert!(have_ffmpeg(), "{name}: ffmpeg required");
8163+ assert!(have_aomenc(), "{name}: no aomenc at {}", aomenc_path().display());
8164+ let (width, height, frame_count) = (64usize, 64usize, 20usize);
8165+ let fimv_frames_before = crate::decode::fimv_frame_hits();
8166+ let alphabet_before = crate::decode::fimv_alphabet_hits();
8167+ let mut matched = 0u32;
8168+ let mut named_refusals = 0u32;
8169+ let mut attempts = 0u32;
8170+ let mut refusals = Vec::new();
8171+ for cq in [32u32, 45, 55] {
8172+ for step in [4u32, 8] {
8173+ attempts += 1;
8174+ let duration = frame_count as f64 / 25.0;
8175+ // Flat screen-content tiles with hard edges, translating by a
8176+ // whole number of pixels per frame: static enough for
8177+ // `av1_is_integer_mv`, moving enough for a real inter block
8178+ // with overlappable neighbours.
8179+ let source = format!(
8180+ "color=c=black:s={width}x{height}:r=25,\
8181+ drawbox=x='8+{step}*mod(trunc(t*25)\\,3)':y=8:w=20:h=20:color=white:t=fill,\
8182+ drawbox=x=36:y='6+{step}*mod(trunc(t*25)+1\\,3)':w=16:h=16:color=0x808080:t=fill,\
8183+ drawbox=x=4:y=44:w=56:h=12:color=0xC0C0C0:t=fill"
8184+ );
8185+ let pix_fmt = if ten_bit { "yuv420p10le" } else { "yuv420p" };
8186+ let y4m = Command::new("ffmpeg")
8187+ .args([
8188+ "-v", "error", "-f", "lavfi", "-i", &source, "-t",
8189+ &duration.to_string(), "-pix_fmt", pix_fmt, "-strict", "-1",
8190+ "-f", "yuv4mpegpipe", "-",
8191+ ])
8192+ .stdin(Stdio::null())
8193+ .stdout(Stdio::piped())
8194+ .stderr(Stdio::piped())
8195+ .output()
8196+ .expect("ffmpeg failed to run");
8197+ assert!(
8198+ y4m.status.success(),
8199+ "ffmpeg fixture: {}",
8200+ String::from_utf8_lossy(&y4m.stderr)
8201+ );
8202+ let cq_arg = format!("--cq-level={cq}");
8203+ let mut args: Vec<&str> = vec![
8204+ "--codec=av1",
8205+ "--passes=1",
8206+ "--end-usage=q",
8207+ &cq_arg,
8208+ "--cpu-used=0",
8209+ "--kf-max-dist=1000",
8210+ "--threads=1",
8211+ "--row-mt=0",
8212+ // single reference only: the 10-bit compound MC defect
8213+ // (see `a_real_compound_global_warp_10bit_stream_...`)
8214+ // is unrelated to this lane and would mask it.
8215+ "--auto-alt-ref=0",
8216+ "--lag-in-frames=0",
8217+ "--enable-fwd-kf=0",
8218+ "--enable-order-hint=1",
8219+ // the flag combination this gate exists for: warp allowed
8220+ // by the header, OBMC available, global motion off (so the
8221+ // GLOBALMV suppression is not what picks the alphabet).
8222+ "--tune-content=screen",
8223+ "--enable-warped-motion=1",
8224+ "--enable-obmc=1",
8225+ "--enable-global-motion=0",
8226+ "--enable-masked-comp=0",
8227+ "--enable-onesided-comp=0",
8228+ "--enable-interintra-comp=0",
8229+ "--enable-interintra-wedge=0",
8230+ "--enable-smooth-interintra=0",
8231+ "--enable-dist-wtd-comp=0",
8232+ // partition/intra tools this decoder does not code yet --
8233+ // the same exclusion list every inter gate here carries.
8234+ "--enable-rect-partitions=0",
8235+ "--enable-ab-partitions=0",
8236+ "--enable-1to4-partitions=0",
8237+ "--enable-filter-intra=0",
8238+ "--enable-smooth-intra=0",
8239+ "--enable-paeth-intra=0",
8240+ "--enable-directional-intra=0",
8241+ "--enable-angle-delta=0",
8242+ "--enable-tx-size-search=0",
8243+ "--enable-cdef=0",
8244+ "--enable-restoration=0",
8245+ "--max-partition-size=32",
8246+ "--min-partition-size=32",
8247+ "--enable-palette=0",
8248+ "--enable-intrabc=0",
8249+ "--enable-cfl-intra=0",
8250+ "--enable-ref-frame-mvs=0",
8251+ ];
8252+ if ten_bit {
8253+ args.extend_from_slice(&["--input-bit-depth=10", "--bit-depth=10"]);
8254+ }
8255+ args.extend_from_slice(&["--obu", "-o", "-", "-"]);
8256+ let mut child = Command::new(aomenc_path())
8257+ .args(&args)
8258+ .stdin(Stdio::piped())
8259+ .stdout(Stdio::piped())
8260+ .stderr(Stdio::piped())
8261+ .spawn()
8262+ .expect("aomenc failed to start");
8263+ child
8264+ .stdin
8265+ .take()
8266+ .expect("aomenc stdin")
8267+ .write_all(&y4m.stdout)
8268+ .expect("writing y4m to aomenc");
8269+ let out = child.wait_with_output().expect("aomenc failed to run");
8270+ assert!(
8271+ out.status.success(),
8272+ "aomenc refused the fixture: {}",
8273+ String::from_utf8_lossy(&out.stderr)
8274+ );
8275+ let stream = out.stdout;
8276+ let frames = match decode_stream(&stream) {
8277+ Err(e) => {
8278+ let msg = e.to_string();
8279+ assert!(
8280+ msg.contains("unsupported"),
8281+ "{name} failed outright (cq {cq} step {step}): {msg}"
8282+ );
8283+ named_refusals += 1;
8284+ refusals.push(format!("cq {cq} step {step}: {msg}"));
8285+ continue;
8286+ }
8287+ Ok(frames) => frames,
8288+ };
8289+ let want = if ten_bit {
8290+ ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count)
8291+ } else {
8292+ ffmpeg_decode_sequence(&stream, width, height, frame_count)
8293+ };
8294+ assert_eq!(frames.len(), frame_count);
8295+ if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP")
8296+ && frames
8297+ .iter()
8298+ .zip(&want)
8299+ .any(|(g, w)| g.y != w.y || g.u != w.u || g.v != w.v)
8300+ {
8301+ std::fs::write(&path, &stream).expect("writing pinned stream");
8302+ eprintln!("EC_AV1_GATE_DUMP: wrote mismatching stream (cq {cq}) to {path}");
8303+ }
8304+ for (i, (got, want)) in frames.iter().zip(&want).enumerate() {
8305+ assert_eq!(got.y, want.y, "{name} frame {i} luma vs ffmpeg (cq {cq} step {step})");
8306+ assert_eq!(got.u, want.u, "{name} frame {i} U vs ffmpeg (cq {cq} step {step})");
8307+ assert_eq!(got.v, want.v, "{name} frame {i} V vs ffmpeg (cq {cq} step {step})");
8308+ }
8309+ matched += 1;
8310+ }
8311+ }
8312+ let fimv_frames = crate::decode::fimv_frame_hits() - fimv_frames_before;
8313+ let alphabet = crate::decode::fimv_alphabet_hits() - alphabet_before;
8314+ eprintln!(
8315+ "{name}: {matched}/{attempts} pixel-exact, {named_refusals} named refusals, \
8316+ force_integer_mv frames={fimv_frames}, forced-2-symbol blocks={alphabet}\n{}",
8317+ refusals.join("\n")
8318+ );
8319+ assert!(matched > 0, "{name}: every attempt refused -- no pixel comparison ran");
8320+ assert!(
8321+ fimv_frames > 0,
8322+ "{name}: no decoded frame header had force_integer_mv=1 \
8323+ ({matched} matches of {attempts}) -- gate vacuous"
8324+ );
8325+ assert!(
8326+ alphabet > 0,
8327+ "{name}: no block read the 2-symbol obmc alphabet where \
8328+ allow_warped_motion=1 and num_proj_ref>=1 would have picked the \
8329+ 3-symbol motion_mode alphabet -- gate vacuous"
8330+ );
8331+ }
8332+
8333+ /// 8-bit arm of [`run_fimv_motion_mode_gate`].
8334+ #[test]
8335+ fn a_real_force_integer_mv_warp_stream_decodes_pixel_exact() {
8336+ run_fimv_motion_mode_gate("a_real_force_integer_mv_warp_stream_decodes_pixel_exact", false);
8337+ }
8338+
8339+ /// 10-bit arm of [`run_fimv_motion_mode_gate`] -- both of his films are
8340+ /// `yuv420p10le`.
8341+ #[test]
8342+ fn a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact() {
8343+ run_fimv_motion_mode_gate(
8344+ "a_real_force_integer_mv_warp_10bit_stream_decodes_pixel_exact",
8345+ true,
8346+ );
8347+ }
8348+
81368349 /// 8-bit arm of [`run_compound_global_warp_gate`].
81378350 #[test]
81388351 fn a_real_compound_global_warp_stream_decodes_pixel_exact() {