From f0c06d5d587946a1d9e1bb18f65807bec3e5079f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 1 Sep 2026 21:28:31 +0300 Subject: [PATCH] feat(av1): AFFINE global motion gated and unrefused -- stock aomenc can never write one Stock libaom pins its encoder-side global-motion model search to ROTZOOM at both ends (av1/encoder/global_motion_facade.c:24-25), so no --enable-global-motion=1 recipe over any content can produce a 6-parameter model -- that is why lane-gm r4/r5/r6 refused AFFINE by name for four rounds rather than gate it. scripts/build-aom-affine-oracle.sh widens exactly that range in a side build (~/.cache/aom-affine, shared oracle untouched); the new gate a_real_affine_global_motion_stream_decodes_pixel_exact encodes rotation plus a progressive anisotropic stretch (the motion a ROTZOOM model cannot express) and decodes it pixel-exact against ffmpeg at 8 and 10 bit, hard- asserting the new affine_gm_hits() counter. No decoder change was needed: read_global_motion_params already reads params 4/5 with their own subexp references and warp.rs's shear validity check plus warp_affine are model-agnostic. Result: 24/24 frames exact both depths, affine_gm_hits 44 (8-bit) / 48 (10-bit). --- crates/ec-av1/src/decode.rs | 18 +++ crates/ec-av1/src/refusal_inventory.rs | 1 - crates/ec-av1/src/stream.rs | 204 +++++++++++++++++++++++-- scripts/build-aom-affine-oracle.sh | 48 ++++++ 4 files changed, 259 insertions(+), 12 deletions(-) create mode 100755 scripts/build-aom-affine-oracle.sh diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index be8f124f..0de03400 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -638,6 +638,21 @@ pub(crate) fn warp_selected_hits() -> usize { WARP_SELECTED_HITS.with(|c| c.get()) } +// lane-gmaffine r1: how many blocks built their prediction from a +// SIX-parameter (`AFFINE`) global-motion model through +// `crate::warp::global_warp_params` -- the gate's proof that a stream really +// carried an AFFINE `global_motion_params` AND that a block was predicted +// with it, not merely that the header parsed one. +thread_local! { + static AFFINE_GM_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`AFFINE_GM_HITS`]. +pub(crate) fn affine_gm_hits() -> usize { + AFFINE_GM_HITS.with(|c| c.get()) +} + // How many blocks decoded `interintra == 1` with the non-wedge blended // prediction applied (lane-interintra r1) -- the gate's proof that a // stream actually exercised interintra. @@ -9994,6 +10009,9 @@ fn decode_inter_block( let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize]; if warp_params.is_none() && is_global_mv_block && !force_integer_mv && !gm_ref.invalid { warp_params = crate::warp::global_warp_params(gm_ref.params); + if warp_params.is_some() && gm_ref.model == ec_av1_syntax::WarpModel::Affine { + AFFINE_GM_HITS.with(|c| c.set(c.get() + 1)); + } } if std::env::var_os("EC_AV1_TELL").is_some() { eprintln!( diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index fb771602..ed4be014 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -65,7 +65,6 @@ const REFUSALS: &[&str] = &[ "a show_existing_frame header naming an empty reference slot", "an 8x8 leaf that coded WARPED_CAUSAL (motion_mode == 2): av1_find_projection/the affine warp filter are not ported, only motion_mode_allowed's alphabet choice is", "an inter frame using TxMode::Select (this decoder's inter path never reads a tx_depth symbol, so it desyncs after the first block's mode)", - "an inter frame whose global motion for a single-reference frame is AFFINE (unverified this round; ROTZOOM/TRANSLATION/IDENTITY are proven)", "an inter frame with no key frame before it", "an inter SB-level partition type other than SPLIT (this decoder's inter tile path only recurses a superblock as SPLIT)", "an inter partition below 16x16 (8x8 and smaller inter blocks are not coded yet)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 8a2b0df0..0664e3bc 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -17,7 +17,6 @@ use ec_av1_syntax::{ Av1Parser, FrameHeader, FrameType, NUM_REF_FRAMES, ObuKind, PRIMARY_REF_NONE, Tile, TxMode, - WarpModel, }; use ec_core::{Error, Result}; @@ -327,16 +326,20 @@ pub fn decode_stream(data: &[u8]) -> Result> { // needed). AFFINE is untested this round (no aomenc fixture in the // wedge gate reached a 6-parameter model) -- keep refusing it by // name rather than shipping an unverified decode. - if header.frame_type != FrameType::Key - && header.global_motion[..7] - .iter() - .any(|gm| gm.model == WarpModel::Affine) - { - return Err(Error::unsupported( - "AV1 decode_stream", - "an inter frame whose global motion for a single-reference frame is AFFINE (unverified this round; ROTZOOM/TRANSLATION/IDENTITY are proven)", - )); - } + // lane-gmaffine r1: AFFINE is now GATED, not refused. Stock libaom + // can never write a 6-parameter model -- its encoder-side search is + // pinned to ROTZOOM (`av1/encoder/global_motion_facade.c:24`, + // `FIRST_GLOBAL_TRANS_TYPE == LAST_GLOBAL_TRANS_TYPE == ROTZOOM`) -- + // which is why four rounds of `--enable-global-motion=1` recipes + // never reached the case. `scripts/build-aom-affine-oracle.sh` widens + // exactly that search range in a side build, and + // `a_real_affine_global_motion_stream_decodes_pixel_exact` below + // decodes its output pixel-exact against ffmpeg with + // `affine_gm_hits() > 0`, i.e. real blocks predicted through the + // 6-parameter warp. Nothing in the decoder needed changing: the + // header reader already reads params 4/5 with their own subexp refs + // (`ec-av1-syntax` `read_global_motion_params`) and `warp.rs`'s + // shear-validity check + `warp_affine` are model-agnostic. // lane-gm r4/r5/r6: r4 found a NEW mismatch on frames with two // concurrently active ROTZOOM/AFFINE ref slots (GOLDEN + BWDREF) and // refused the shape by name rather than guess-fix it. r5 localized @@ -5208,6 +5211,185 @@ mod tests { ); } + /// The affine-capable encoder (`scripts/build-aom-affine-oracle.sh`), + /// separate from the shared oracle because stock libaom's global-motion + /// model search is pinned to ROTZOOM and can never emit AFFINE. + fn affine_aomenc_path() -> std::path::PathBuf { + if let Some(p) = std::env::var_os("EC_AV1_AFFINE_AOMENC") { + return std::path::PathBuf::from(p); + } + let home = std::env::var_os("HOME").unwrap_or_default(); + std::path::PathBuf::from(home).join(".cache/aom-affine/build/aomenc") + } + + fn have_affine_aomenc() -> bool { + let present = affine_aomenc_path().is_file(); + assert!( + present || std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none(), + "EC_AV1_REQUIRE_AOMENC is set but no affine-capable aomenc at {} -- run \ + scripts/build-aom-affine-oracle.sh", + affine_aomenc_path().display() + ); + present + } + + /// lane-gmaffine r1: an inter frame whose `global_motion_params` carries a + /// SIX-parameter (`AFFINE`) model for a single-reference frame -- refused + /// by name since lane-gm r4 because no aomenc recipe ever reached it. + /// The reason it never did is in libaom's own encoder, not in the + /// content: `av1/encoder/global_motion_facade.c:24` pins the model search + /// to `ROTZOOM` at both ends, so *no* `--enable-global-motion=1` command + /// line over any source can produce the case. The decoder must still + /// handle it (the bitstream allows it, `read_global_motion_params` reads + /// params 4/5 with their own subexp references, and ffmpeg decodes it), + /// so this gate widens exactly that one encoder-side search range in a + /// side build and encodes with it. Everything downstream is ordinary + /// libaom and the pixel oracle is still ffmpeg. + /// + /// Content: rotation composed with a progressive *anisotropic* stretch -- + /// a similarity transform plus unequal axis scaling is precisely what a + /// 4-parameter ROTZOOM model cannot express, which is what makes the + /// encoder's RD pick AFFINE. `affine_gm_hits()` hard-asserts that real + /// blocks were predicted through the 6-parameter warp, not merely that a + /// header parsed one (class `gate-blind-to-feature`). + #[test] + fn a_real_affine_global_motion_stream_decodes_pixel_exact() { + const NAME: &str = "a_real_affine_global_motion_stream_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_affine_aomenc() { + eprintln!( + "SKIP {NAME}: no affine-capable aomenc at {} (scripts/build-aom-affine-oracle.sh)", + affine_aomenc_path().display() + ); + return; + } + let (width, height, frame_count) = (64usize, 64usize, 24usize); + let duration = frame_count as f64 / 25.0; + // Both depths: his own AV1 library is yuv420p10le throughout, and a + // 10-bit AFFINE warp runs the same `warp_affine` over wider samples. + for depth in [8u32, 10u32] { + // `-t` is the real bound on mandelbrot (it ignores `end_pts` and + // has hung a gate for an hour); the 96x96 source is rotated and + // then stretched horizontally only, and cropped back to 64x64. + let source = format!( + "mandelbrot=size=96x96:rate=25,rotate=a=0.12*t:c=black,\ + scale=w='ceil(96*(1+0.03*n)/2)*2':h=96:eval=frame,crop={width}:{height}" + ); + let pix_fmt = if depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let mut ff_args: Vec<&str> = + vec!["-v", "error", "-f", "lavfi", "-i", &source, "-pix_fmt", pix_fmt]; + // y4m has no official 10-bit tag, same as the 10-bit gate above. + if depth == 10 { + ff_args.extend(["-strict", "-1"]); + } + let duration_arg = duration.to_string(); + ff_args.extend(["-t", &duration_arg, "-f", "yuv4mpegpipe", "-"]); + let y4m = Command::new("ffmpeg") + .args(&ff_args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let bit_depth = format!("--bit-depth={depth}"); + let input_bit_depth = format!("--input-bit-depth={depth}"); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--kf-max-dist=1000", + "--threads=1", + "--row-mt=0", + "--auto-alt-ref=0", + "--lag-in-frames=0", + "--enable-fwd-kf=0", + "--enable-order-hint=1", + "--enable-global-motion=1", + "--enable-warped-motion=0", + "--enable-obmc=0", + "--tune-content=default", + "--enable-masked-comp=0", + "--enable-interintra-comp=0", + "--enable-onesided-comp=0", + "--enable-rect-partitions=0", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--enable-filter-intra=0", + "--enable-smooth-intra=0", + "--enable-paeth-intra=0", + "--enable-directional-intra=0", + "--enable-angle-delta=0", + "--enable-tx-size-search=0", + "--enable-cdef=0", + "--enable-restoration=0", + "--max-partition-size=32", + "--min-partition-size=32", + "--enable-palette=0", + "--enable-intrabc=0", + "--enable-cfl-intra=0", + "--enable-ref-frame-mvs=0", + &bit_depth, + &input_bit_depth, + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(affine_aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("affine aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = crate::decode::affine_gm_hits(); + let frames = + decode_stream(&stream).unwrap_or_else(|e| panic!("{NAME} ({depth}-bit): {e}")); + let ffmpeg_frames = if depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!(got.y, want.y, "{NAME} {depth}-bit frame {i} luma vs ffmpeg"); + assert_eq!(got.u, want.u, "{NAME} {depth}-bit frame {i} U vs ffmpeg"); + assert_eq!(got.v, want.v, "{NAME} {depth}-bit frame {i} V vs ffmpeg"); + } + let hits = crate::decode::affine_gm_hits() - before; + assert!( + hits > 0, + "{NAME} ({depth}-bit): decoded pixel-exact but no block was predicted through a \ + 6-parameter global-motion warp -- the AFFINE path is unexercised" + ); + eprintln!("{NAME}: {depth}-bit, {frame_count} frames pixel-exact, affine_gm_hits={hits}"); + } + } + /// lane-rect16 r1/r2: a plain default-settings aomenc run over lavfi /// `mandelbrot` (`--cpu-used=4 --end-usage=q --cq-level=32`, no /// `--enable-*` flags) used to refuse frame 0 outright with "a partition diff --git a/scripts/build-aom-affine-oracle.sh b/scripts/build-aom-affine-oracle.sh new file mode 100755 index 00000000..34effa76 --- /dev/null +++ b/scripts/build-aom-affine-oracle.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Provision an aomenc that can emit AFFINE global motion. +# +# Stock libaom NEVER writes a 6-parameter (AFFINE) global-motion model: its +# encoder-side model search is pinned to ROTZOOM, +# +# av1/encoder/global_motion_facade.c:24 +# #define FIRST_GLOBAL_TRANS_TYPE ROTZOOM +# #define LAST_GLOBAL_TRANS_TYPE ROTZOOM +# +# so no `--enable-global-motion=1` recipe over any content can produce the +# AFFINE case the decoder must still handle (the *bitstream* allows it, the +# spec's `global_motion_params` reads 6 params, and ffmpeg decodes it). This +# builds a side copy of the oracle source with that search range widened to +# AFFINE -- decode-normative output, still ordinary libaom, still verified +# against ffmpeg -- into its own prefix so the shared oracle at +# ~/.cache/aom-oracle (used by every other gate) is untouched. +# +# Used by the `a_real_affine_global_motion_stream_decodes_pixel_exact` gate in +# crates/ec-av1/src/stream.rs. +set -euo pipefail + +ROOT="${AOM_AFFINE_ROOT:-$HOME/.cache/aom-affine}" +ORACLE_SRC="${AOM_ORACLE_ROOT:-$HOME/.cache/aom-oracle}/src" +SRC="$ROOT/src" +BUILD="$ROOT/build" + +if [ ! -d "$ORACLE_SRC/.git" ]; then + echo "no oracle source at $ORACLE_SRC -- run scripts/build-aom-oracle.sh first" >&2 + exit 1 +fi + +if [ ! -d "$SRC" ]; then + mkdir -p "$ROOT" + cp -a "$ORACLE_SRC" "$SRC" +fi + +facade="$SRC/av1/encoder/global_motion_facade.c" +sed -i 's/^#define LAST_GLOBAL_TRANS_TYPE ROTZOOM$/#define LAST_GLOBAL_TRANS_TYPE AFFINE/' "$facade" +grep -q '^#define LAST_GLOBAL_TRANS_TYPE AFFINE$' "$facade" || + { echo "patch did not apply to $facade" >&2; exit 1; } + +cmake -S "$SRC" -B "$BUILD" -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DENABLE_TESTS=0 -DENABLE_DOCS=0 -DENABLE_EXAMPLES=1 +ninja -C "$BUILD" aomenc + +echo "affine-capable encoder ready: $BUILD/aomenc"