diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index b70d3ef2..1f79237a 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -129,6 +129,137 @@ impl Picture { } Ok(()) } + + /// What the public entry points require of the picture they are handed, + /// before it is padded to the block grid: even, nonzero dimensions (4:2:0 + /// needs a whole chroma sample per two luma ones) and one sample per + /// position on each plane. + fn check_even(&self) -> Result<()> { + if self.width == 0 + || self.height == 0 + || !self.width.is_multiple_of(2) + || !self.height.is_multiple_of(2) + { + return Err(Error::unsupported( + "AV1 encode", + "the picture's width and height must each be even and nonzero", + )); + } + let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); + if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { + return Err(Error::unsupported( + "AV1 encode", + "each plane must carry one sample per position at 4:2:0", + )); + } + Ok(()) + } + + /// This picture, padded by edge replication to the next whole number of + /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key + /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a + /// sequence (what the inter tile writer's partition needs on top of + /// that). Identity (a plain clone, not a copy through the replication + /// loop) when the picture is already that size — the multiple-of-32 (or + /// -64) fast path is unchanged. + fn padded_to(&self, align: usize) -> Picture { + let padded_width = self.width.next_multiple_of(align); + let padded_height = self.height.next_multiple_of(align); + if padded_width == self.width && padded_height == self.height { + return self.clone(); + } + Picture { + width: padded_width, + height: padded_height, + y: pad_plane( + &self.y, + self.width, + self.height, + padded_width, + padded_height, + ), + u: pad_plane( + &self.u, + self.width / 2, + self.height / 2, + padded_width / 2, + padded_height / 2, + ), + v: pad_plane( + &self.v, + self.width / 2, + self.height / 2, + padded_width / 2, + padded_height / 2, + ), + } + } +} + +/// Pads one plane to `(padded_width, padded_height)` by repeating its last +/// row and column, so the block coder always sees a whole number of blocks. +/// [`crop_plane`] undoes this on the way back out. +fn pad_plane( + source: &[u8], + width: usize, + height: usize, + padded_width: usize, + padded_height: usize, +) -> Vec { + let mut out = vec![0u8; padded_width * padded_height]; + for row in 0..padded_height { + let src = source[row.min(height - 1) * width..][..width].as_ref(); + let dst = &mut out[row * padded_width..][..padded_width]; + dst[..width].copy_from_slice(src); + dst[width..].fill(src[width - 1]); + } + out +} + +/// The top-left `width` x `height` region of a plane that is `padded_width` +/// wide, which is the render-size crop [`Picture::padded`]'s replication +/// exists to let a decoder undo. +fn crop_plane(source: &[u8], padded_width: usize, width: usize, height: usize) -> Vec { + let mut out = Vec::with_capacity(width * height); + for row in 0..height { + out.extend_from_slice(&source[row * padded_width..][..width]); + } + out +} + +/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size +/// region a decoder produces, which is the public contract for what a caller +/// sees back — the padded planes the encoder coded against never leave this +/// module. Identity when the reconstruction is already that size. +fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded { + let reconstruction = &encoded.reconstruction; + let cropped = if reconstruction.width == width && reconstruction.height == height { + reconstruction.clone() + } else { + Picture { + width, + height, + y: crop_plane(&reconstruction.y, reconstruction.width, width, height), + u: crop_plane( + &reconstruction.u, + reconstruction.width / 2, + width / 2, + height / 2, + ), + v: crop_plane( + &reconstruction.v, + reconstruction.width / 2, + width / 2, + height / 2, + ), + } + }; + Encoded { + stream: encoded.stream.clone(), + modes: encoded.modes.clone(), + inter_block_share: encoded.inter_block_share, + reconstruction: cropped, + } } /// What one call to [`encode_key_frame`] produced. @@ -818,9 +949,15 @@ fn coeffs(levels: &[i32], side: usize) -> Vec { /// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and /// smaller values trade fidelity for rate. /// +/// The picture may be any even width and height: the encoder pads it by edge +/// replication to a whole number of 32x32 blocks internally, and the frame it +/// writes crops back to the picture's own size (`render_width`/ +/// `render_height`), so [`Encoded::reconstruction`] is always the picture's +/// own size, never the padded one. +/// /// # Errors -/// Returns an error when the picture is not a whole number of 32x32 blocks, -/// or when its planes are not 4:2:0 of that size. +/// Returns an error when the picture's width or height is zero or odd, or +/// when its planes are not 4:2:0 of that size. pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result { encode_key_frame_with_modes(picture, base_q_idx, deadzone, &KEY_FRAME_MODES) } @@ -842,17 +979,30 @@ pub fn encode_key_frame_with_modes( deadzone: f64, modes: &[u8], ) -> Result { - encode_key_frame_inner(picture, base_q_idx, deadzone, modes, split_blocks()) + picture.check_even()?; + let padded = picture.padded_to(BLOCK); + let encoded = encode_key_frame_inner( + &padded, + base_q_idx, + deadzone, + modes, + split_blocks(), + (picture.width, picture.height), + )?; + Ok(crop_encoded(&encoded, picture.width, picture.height)) } /// [`encode_key_frame_with_modes`] with the partition decision forced, which is -/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. +/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is +/// already padded to a whole number of 32x32 blocks; `render` is the real +/// (pre-pad) size the frame header tells a decoder to crop back to. fn encode_key_frame_inner( picture: &Picture, base_q_idx: u8, deadzone: f64, modes: &[u8], split_blocks: bool, + render: (usize, usize), ) -> Result { picture.check()?; if modes.is_empty() { @@ -867,7 +1017,9 @@ fn encode_key_frame_inner( format!("intra mode {bad} is not one the encoder predicts"), )); } - let (seq, header) = key_frame_headers(picture.width, picture.height, base_q_idx)?; + let (seq, mut header) = key_frame_headers(picture.width, picture.height, base_q_idx)?; + header.render_width = render.0 as u32; + header.render_height = render.1 as u32; let mut luma = Plane { source: &picture.y, @@ -1492,6 +1644,7 @@ fn encode_inter_frame( base_q_idx: u8, deadzone: f64, order_hint: u32, + render: (usize, usize), ) -> Result { picture.check()?; if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { @@ -1514,13 +1667,15 @@ fn encode_inter_frame( // overwrites slot 0, so the frame just coded is always what the next one // predicts against. const LAST_SLOT: u8 = 0; - let (seq, header) = inter_frame_headers( + let (seq, mut header) = inter_frame_headers( picture.width, picture.height, base_q_idx, order_hint, LAST_SLOT, )?; + header.render_width = render.0 as u32; + header.render_height = render.1 as u32; let mut luma = Plane { source: &picture.y, @@ -1638,8 +1793,10 @@ pub struct EncodedSequence { /// Encodes a sequence of pictures as a key frame followed by one inter frame /// per remaining picture, each predicting from the previous frame's own /// decoded reconstruction — never from the source, which is what a decoder -/// cannot see. `pictures` must be a whole number of 64x64 superblocks in -/// each direction (the inter tile writer's own constraint) and non-empty. +/// cannot see. Every picture must be the same even size (any even width and +/// height — each is padded to a whole number of 64x64 superblocks +/// internally, which is what lets an inter frame's reference always match +/// the frame being coded against it), and `pictures` must be non-empty. /// /// # Errors /// Returns an error when `pictures` is empty, when any picture besides the @@ -1656,16 +1813,44 @@ pub fn encode_sequence( "a sequence needs at least one picture", )); }; - let key = encode_key_frame(first, base_q_idx, deadzone)?; + first.check_even()?; + let render = (first.width, first.height); + // The key frame and every inter frame after it are coded at the same + // padded size, so the reference each inter frame predicts from -- the + // previous frame's own uncropped reconstruction, at the size a decoder's + // reference buffer actually holds -- always matches the frame being + // coded against it. + let key = encode_key_frame_inner( + &first.padded_to(SUPERBLOCK), + base_q_idx, + deadzone, + &KEY_FRAME_MODES, + split_blocks(), + render, + )?; let mut stream = key.stream.clone(); let mut reference = key.reconstruction.clone(); - let mut frames = vec![key]; + let mut frames = vec![crop_encoded(&key, render.0, render.1)]; for (i, picture) in rest.iter().enumerate() { + picture.check_even()?; + if (picture.width, picture.height) != render { + return Err(Error::unsupported( + "AV1 encode", + "every picture in a sequence must be the same size as the first", + )); + } let order_hint = (i + 1) as u32; - let inter = encode_inter_frame(picture, &reference, base_q_idx, deadzone, order_hint)?; + let inter = encode_inter_frame( + &picture.padded_to(SUPERBLOCK), + &reference, + base_q_idx, + deadzone, + order_hint, + render, + )?; stream.extend_from_slice(&inter.stream); reference = inter.reconstruction.clone(); - frames.push(inter); + frames.push(crop_encoded(&inter, render.0, render.1)); } Ok(EncodedSequence { stream, frames }) } @@ -1873,6 +2058,198 @@ mod tests { ffmpeg_decode_sequence(&stream, width, height, 2); } + /// The top-left `width` x `height` region of a decoded picture, for + /// comparing against [`Encoded::reconstruction`] (already cropped to + /// the same region) when ffmpeg hands back the padded, coded-size one. + fn crop_picture(picture: &Picture, width: usize, height: usize) -> Picture { + Picture { + width, + height, + y: crop_plane(&picture.y, picture.width, width, height), + u: crop_plane(&picture.u, picture.width / 2, width / 2, height / 2), + v: crop_plane(&picture.v, picture.width / 2, width / 2, height / 2), + } + } + + /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded + /// frame size an AV1 decoder allocates, not necessarily the render size + /// (see [`a_frame_round_trips_at_its_own_size`]). + fn ffprobe_size(stream: &[u8]) -> (u32, u32) { + let path = std::env::temp_dir().join(format!("ec-av1-probe-{}.obu", std::process::id())); + let _ = std::fs::remove_file(&path); + std::fs::write(&path, stream).expect("writing the probe stream"); + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-f", + "obu", + "-select_streams", + "v:0", + "-show_entries", + "stream=width,height", + "-of", + "csv=p=0", + ]) + .arg(&path) + .output() + .expect("ffprobe failed to run"); + let _ = std::fs::remove_file(&path); + assert!( + out.status.success(), + "ffprobe refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + let text = String::from_utf8_lossy(&out.stdout); + let mut fields = text.trim().split(','); + let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); + let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); + (width, height) + } + + /// A key frame at an arbitrary even size round-trips through ffmpeg over + /// its own render rectangle: [`Encoded::reconstruction`] is exactly the + /// picture's own size, and what ffmpeg decodes over that same top-left + /// region equals it sample for sample. + /// + /// This does not check that `ffprobe` reports the picture's own size, + /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded + /// (block-padded) frame size, the same one libaom itself would code for + /// a non-block-aligned picture. `render_width`/`render_height` (which + /// this crate sets correctly, spec 5.9.6) is a display hint no AV1 + /// decoder is required to crop pixels by, and ffmpeg's does not -- + /// checked empirically against ffprobe here and against a real libaom + /// encode separately. So the coded size, not the render size, is what + /// `ffprobe` is asserted to report below. + #[test] + fn a_frame_round_trips_at_its_own_size() { + if !have_ffmpeg() { + eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg"); + return; + } + // 854x480 is deliberately not in this list -- it hits an open, + // content-dependent desync unrelated to padding wiring; see + // `open_defect_854x480_padded_key_frame_desyncs`. + for &(width, height) in &[(1920usize, 1080usize), (640, 352), (1280, 720)] { + let picture = test_card(width, height); + let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); + assert_eq!( + (encoded.reconstruction.width, encoded.reconstruction.height), + (width, height), + "{width}x{height}: reconstruction is cropped to the picture's own size" + ); + let (padded_width, padded_height) = ( + width.next_multiple_of(BLOCK), + height.next_multiple_of(BLOCK), + ); + assert_eq!( + ffprobe_size(&encoded.stream), + (padded_width as u32, padded_height as u32), + "{width}x{height}: ffprobe reports the coded (padded) size" + ); + let decoded = ffmpeg_decode(&encoded.stream, padded_width, padded_height); + let cropped = crop_picture(&decoded, width, height); + assert_eq!( + cropped.y, encoded.reconstruction.y, + "{width}x{height}: luma" + ); + assert_eq!(cropped.u, encoded.reconstruction.u, "{width}x{height}: U"); + assert_eq!(cropped.v, encoded.reconstruction.v, "{width}x{height}: V"); + } + } + + /// Reproduces an open defect this lane's sweep found: 854x480 (padded to + /// 864x480, an *edge-replication* padded key frame -- not a preexisting + /// bug, since 864x480 coded directly with no padding involved is + /// bit-exact) desyncs against ffmpeg's decode starting at luma (row 161, + /// col 369), well inside the real (non-padded) region, not at the + /// padding edge. 640x352, 1280x720, 854x480's own height (480, already + /// 32-aligned) and 1920x1080 all round-trip clean, and the padding/crop + /// plumbing itself is exercised bit-exact by + /// `a_frame_round_trips_at_its_own_size` and the 64x64-superblock + /// sequence case, so this looks like a content-triggered desync inside + /// the coefficient/intra coding this lane was told not to touch + /// (`tile.rs`), not a padding-wiring bug. Left `#[ignore]`d rather than + /// silently dropped from the charter's size list -- next lane should + /// start from the row/col this test prints. + #[test] + #[ignore = "open defect: content-dependent desync at 854x480 padded, not padding wiring -- see doc comment"] + fn open_defect_854x480_padded_key_frame_desyncs() { + if !have_ffmpeg() { + return; + } + let (width, height) = (854usize, 480usize); + let picture = test_card(width, height); + let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); + let (padded_width, padded_height) = ( + width.next_multiple_of(BLOCK), + height.next_multiple_of(BLOCK), + ); + let decoded = ffmpeg_decode(&encoded.stream, padded_width, padded_height); + let cropped = crop_picture(&decoded, width, height); + assert_eq!(cropped.y, encoded.reconstruction.y, "854x480: luma"); + } + + /// An odd width or height is refused by name, not by however the padder + /// or the block coder would happen to fail on it. + #[test] + fn odd_dimensions_are_refused() { + for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { + let picture = Picture::grey(width, height); + let err = encode_key_frame(&picture, 100, 0.5) + .expect_err(&format!("{width}x{height} is odd and must be refused")); + assert!( + err.to_string().contains("even"), + "{width}x{height}: error was {err}" + ); + } + } + + /// A sequence at a size that is not a multiple of the block grid decodes + /// to the right frame count and the right size for every frame, + /// including the inter frames whose reference is the previous frame's + /// own (padded) reconstruction. + #[test] + fn sequence_round_trips_at_a_non_multiple_size() { + if !have_ffmpeg() { + eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg"); + return; + } + let (width, height) = (160usize, 96usize); + let pictures: Vec = (0..3) + .map(|i| panned_test_card(width, height, i * 3)) + .collect(); + let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); + assert_eq!(encoded.frames.len(), 3); + for (i, frame) in encoded.frames.iter().enumerate() { + assert_eq!( + (frame.reconstruction.width, frame.reconstruction.height), + (width, height), + "frame {i}: reconstruction size" + ); + } + // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the + // coded (superblock-padded) size a sequence's frames share, not the + // render size. + let (padded_width, padded_height) = ( + width.next_multiple_of(SUPERBLOCK), + height.next_multiple_of(SUPERBLOCK), + ); + assert_eq!( + ffprobe_size(&encoded.stream), + (padded_width as u32, padded_height as u32), + "sequence: ffprobe reports the coded (padded) size" + ); + let decoded = ffmpeg_decode_sequence(&encoded.stream, padded_width, padded_height, 3); + assert_eq!(decoded.len(), 3, "decoded frame count"); + for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { + let cropped = crop_picture(decoded, width, height); + assert_eq!(cropped.y, frame.reconstruction.y, "frame {i}: luma"); + assert_eq!(cropped.u, frame.reconstruction.u, "frame {i}: U"); + assert_eq!(cropped.v, frame.reconstruction.v, "frame {i}: V"); + } + } + /// One frame of a real clip, scaled to a whole number of 32x32 blocks. fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { let out = Command::new("ffmpeg") @@ -1959,9 +2336,15 @@ mod tests { let mut points: Vec<(f64, f64)> = [110u8, 90, 70] .iter() .map(|&q| { - let encoded = - encode_key_frame_inner(&picture, q, 0.5, &KEY_FRAME_MODES, split) - .unwrap(); + let encoded = encode_key_frame_inner( + &picture, + q, + 0.5, + &KEY_FRAME_MODES, + split, + (picture.width, picture.height), + ) + .unwrap(); ( psnr(&encoded.reconstruction.y, picture.y.as_slice()), (encoded.stream.len() as f64).log10(), @@ -1972,10 +2355,17 @@ mod tests { points }; let (whole, split) = (ladder(false), ladder(true)); - let blocks = encode_key_frame_inner(&picture, 90, 0.5, &KEY_FRAME_MODES, true) - .unwrap() - .modes - .len(); + let blocks = encode_key_frame_inner( + &picture, + 90, + 0.5, + &KEY_FRAME_MODES, + true, + (picture.width, picture.height), + ) + .unwrap() + .modes + .len(); let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK); println!( "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90", @@ -2384,11 +2774,15 @@ mod tests { } /// The sizes the encoder refuses, refused for a reason rather than by - /// panicking somewhere below. + /// panicking somewhere below. 40x32 and 32x48 are off the 32x32 block + /// grid, which used to be refused outright; the encoder now pads a + /// picture like that internally (see `a_frame_round_trips_at_its_own_size`) + /// rather than refusing it, so those two are an accept, not a refusal, + /// here. #[test] fn a_picture_off_the_block_grid_is_refused() { - assert!(encode_key_frame(&Picture::grey(40, 32), 100, 0.5).is_err()); - assert!(encode_key_frame(&Picture::grey(32, 48), 100, 0.5).is_err()); + assert!(encode_key_frame(&Picture::grey(40, 32), 100, 0.5).is_ok()); + assert!(encode_key_frame(&Picture::grey(32, 48), 100, 0.5).is_ok()); let mut short = Picture::grey(64, 64); short.u.truncate(10); assert!(encode_key_frame(&short, 100, 0.5).is_err()); diff --git a/crates/ec-av1/src/msac.rs b/crates/ec-av1/src/msac.rs index 6cee6e73..ef17b2c4 100644 --- a/crates/ec-av1/src/msac.rs +++ b/crates/ec-av1/src/msac.rs @@ -77,6 +77,15 @@ impl SymbolEncoder { self.bits } + /// The exact bit position the stream has committed to so far (libaom's + /// `od_ec_enc_tell`, `entenc.c`): `cnt + 10` undoes the `-9` `cnt` starts + /// at and reserves the one bit `finish` always spends, and `precarry` + /// holds one `u16` per byte already flushed. Pairs with the decoder's + /// `aom_reader_tell`, which counts the same bits consumed. + pub fn tell(&self) -> i32 { + self.cnt + 10 + self.precarry.len() as i32 * 8 + } + /// Forgets the cost accumulated so far, so that the next stretch of /// symbols can be priced on its own. pub fn reset_bits(&mut self) { diff --git a/crates/ec-av1/src/mvstack.rs b/crates/ec-av1/src/mvstack.rs index 3533150d..bad19a95 100644 --- a/crates/ec-av1/src/mvstack.rs +++ b/crates/ec-av1/src/mvstack.rs @@ -12,29 +12,68 @@ //! `newmv_count > 0` tests) and `av1_drl_ctx` (`mvref_common.h`), plus MV //! clamping (7.10.2.14, libaom's `clamp_mv_ref`). //! -//! This module's scan is already reduced to the immediate row/col/top-right -//! positions with no extended-offset scan (see below), which lets those -//! context formulas collapse exactly rather than approximately: libaom's -//! `ref_match_count` comes from the *same* row/col match counters as -//! `nearest_match` once the extended scan is gone, so `ref_match_count == -//! nearest_match` always here, and every candidate this module finds is one -//! of libaom's "nearest" ones, so the `REF_CAT_LEVEL` (640) bonus -//! `av1_find_mv_stack` adds to nearest candidates before computing DRL -//! context applies to all of them uniformly — which is why [`find_mv_stack`] -//! always reports `drl_ctx == 0`: with the extended scan absent, no -//! candidate here can ever be a "non-nearest" (sub-640) one for a pair -//! comparison to distinguish. Likewise, the `GLOBALMV_OFFSET` bit of -//! libaom's `mode_context` is set only inside +//! This module's immediate row/col/top-right scan alone is *not* enough to +//! get `RefMvContext` (`ref_mv_ctx`) right, even though it *is* enough for +//! `NewMvContext`/`ZeroMvContext`. Ported straight from libaom's +//! `av1_find_mv_stack` (`av1/common/mvref_common.c`, `setup_ref_mv_list`, +//! ~line 480 on): after the immediate row (-1), col (-1) and top-right +//! probes settle `nearest_match` (and `mode_context`'s `new_mv` bits, which +//! depend on `nearest_match` alone), libaom runs one more probe *before* +//! computing `ref_match_count` — `scan_blk_mbmi` at the diagonal top-left +//! corner `(-1, -1)` — whose match folds into `row_match_count` (and hence +//! can flip `ref_match_count`'s row term true) without ever touching the +//! already-captured `nearest_match`. So `ref_match_count >= nearest_match` +//! always, sometimes strictly greater, and `ref_mv_ctx` (the `REFMV_OFFSET` +//! half of libaom's `mode_context` switch, mvref_common.c ~line 619-643) +//! genuinely depends on both counts, not `nearest_match` alone — that +//! collapse was the bug this module shipped with for several rounds (see +//! the crate report). [`find_mv_stack`] now runs that corner probe and +//! computes `ref_mv_ctx` from the true `(nearest_match, ref_match_count)` +//! pair. +//! +//! The corner probe's own candidate is added to the stack too (matching +//! libaom: a genuinely new MV there becomes a real, if low-weight, entry), +//! but — like the reduced row/col/top-right scans — at this module's own +//! `IMMEDIATE_WEIGHT` scale rather than libaom's real `len * max(2, inc)` +//! (row/col) or `2 * mi_size_wide[BLOCK_8X8]` (corner/top-right) weights. +//! That scale mismatch is harmless for every caller this module has: the +//! only real caller (`tile.rs`) always asks for a fixed `bw4 == bh4 == 8` +//! block, at which size libaom's row and col weights are *always tied* +//! (both scan a full-width same-size neighbour) and its corner/top-right +//! weight is *always* far below either — exactly the ordering +//! `IMMEDIATE_WEIGHT` already reproduces, so sort order and the +//! `REF_CAT_LEVEL`-vs-not DRL split (which only tests a threshold, not a +//! magnitude) come out identical either way. A caller with mixed block +//! sizes would need the real weight formula; none exists today. +//! +//! The corner probe's own match does *not* count toward the real +//! `newmv_count` that feeds `new_mv_ctx` (libaom passes it a `dummy_newmv_count` +//! there) — only row/col/top-right do. +//! +//! Also ported (from `av1_drl_ctx`, `mvref_common.h`): the `REF_CAT_LEVEL` +//! (640) bonus applies only to the entries the row/col/top-right scan found +//! (`nearest_refmv_count`), added to their stored weight *before* the corner +//! probe can add a new, unboosted entry — so `drl_ctx` can now be non-zero +//! when the corner probe contributes a genuinely new candidate. +//! +//! The `GLOBALMV_OFFSET` bit of libaom's `mode_context` is set only inside //! `cm->features.allow_ref_frame_mvs` (temporal MV projection), which this //! module never has (`use_ref_frame_mvs = 0`), so `zero_mv_ctx` is always 0 -//! here — again exact for the case this module covers, not a stand-in. +//! here — exact for the case this module covers, not a stand-in. //! //! Deliberately reduced away (see the crate report, not reproduced bit-exact //! here): compound/multi-reference candidates, the temporal MV projection -//! scan, and the `>1` row/col scans at offset 3 and their skip-by-block-size -//! stepping (which is also why the "extra search" that pads a short stack to -//! two entries, spec 7.10.2.12, is not implemented — this module's stack can -//! be shorter than two candidates where libaom's never is). +//! scan, the real (non-corner) `idx = 2..MVREF_ROW_COLS` extended row/col +//! scan positions (libaom's own `processed_rows`/`processed_cols` bookkeeping +//! means those never fire for this module's fixed 8-mi block geometry — the +//! immediate-offset scan's coverage window already reaches as far as the +//! extended offsets can, so nothing there is left unscanned), the +//! single-reference "extension" pass that re-walks the same row/col +//! neighbours through `process_single_ref_mv_candidate` (a no-op here: with +//! only one reference frame ever in play, whatever it would add was already +//! added by the row/col scan), and the "extra search" that pads a short +//! stack to two entries (spec 7.10.2.12) — this module's stack can be +//! shorter than two candidates where libaom's never is. /// One 4x4 `mi` unit's motion state, as the encode loop will have filled it /// in by the time it asks for a block's MV stack. @@ -240,6 +279,34 @@ fn scan_top_right( false } +/// The diagonal top-left corner probe (libaom `scan_blk_mbmi` at +/// `row_offset = col_offset = -1`, mvref_common.c's "second outer area", +/// called *after* `nearest_match` is already captured): the single unit +/// diagonally above-left of the block. Its match folds into the row bucket +/// too (see module doc) but must never move `nearest_match` itself or the +/// real `newmv_count` — callers pass a throwaway counter for the latter. +fn scan_corner( + grid: &MiGrid, + mi_row: usize, + mi_col: usize, + ref_frame: i8, + candidates: &mut Vec, + newmv_count: &mut u32, +) -> bool { + let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else { + return false; + }; + if let Some(info) = grid.get(row, col) + && info.is_inter + && info.ref_frame == ref_frame + { + add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT); + *newmv_count += u32::from(info.is_new_mv); + return true; + } + false +} + /// `MV_BORDER` (spec 7.10.2.14): 16 pixels of slack in 1/8-pel units, added /// on top of the block's own span before a candidate is clamped to the /// frame. @@ -318,8 +385,38 @@ pub fn find_mv_stack( &mut newmv_count, ); + // libaom's `row_match_count`/`col_match_count` (mvref_common.c) fold the + // top-right probe into the row side, so "found above" for context + // purposes means the row scan *or* the top-right one matched. + let row_matched = found_above || found_top_right; + let nearest_match = usize::from(row_matched) + usize::from(found_left); + + // av1_find_mv_stack boosts only the entries the immediate scan found — + // exactly `candidates` at this point, before the corner probe (below) + // can add anything else (mvref_common.c ~line 544-545). + for entry in &mut candidates { + entry.weight += REF_CAT_LEVEL; + } + + // The diagonal top-left corner probe (module doc): folds into the row + // side for `ref_match_count` without moving the already-captured + // `nearest_match`, and its own newmv-ness is a dummy count libaom + // discards (`&dummy_newmv_count` at the real call site). + let mut dummy_newmv_count = 0u32; + let corner_matched = scan_corner( + grid, + mi_row, + mi_col, + ref_frame, + &mut candidates, + &mut dummy_newmv_count, + ); + let ref_match_count = usize::from(row_matched || corner_matched) + usize::from(found_left); + // Highest weight first; a stable sort keeps scan order (above, left, - // top-right) among ties, matching spec 7.10.2.6. + // top-right, corner) among ties, matching spec 7.10.2.6. The corner + // probe's un-boosted entry (if new) always sorts after the boosted + // ones above, matching libaom's separate two-phase ranking. candidates.sort_by_key(|e| std::cmp::Reverse(e.weight)); candidates.truncate(MAX_STACK_SIZE); @@ -332,18 +429,10 @@ pub fn find_mv_stack( nearest_mv }; - // libaom's `row_match_count`/`col_match_count` (mvref_common.c) fold the - // top-right probe into the row side, so "found above" for context - // purposes means the row scan *or* the top-right one matched. - let row_matched = found_above || found_top_right; - let nearest_match = usize::from(row_matched) + usize::from(found_left); - // Exact port of the `mode_context[ref_frame]` switch (mvref_common.c - // ~line 619-643): with no extended-offset scan, `ref_match_count` here is - // always equal to `nearest_match` (both come from the same row/col match - // counters this module never advances further), so the `ref_match_count` - // branches of libaom's switch collapse into the constants below — see - // module doc. + // ~line 619-643). `new_mv_ctx` depends on `nearest_match` and the real + // `newmv_count` alone — libaom's switch never reads `ref_match_count` + // for those bits, so this half was already exact before this round. let new_mv_ctx = match nearest_match { 0 => 0, 1 => { @@ -361,9 +450,22 @@ pub fn find_mv_stack( } } }; + // `ref_mv_ctx` (the `REFMV_OFFSET` half of the same switch) genuinely + // depends on both counts — this is the part that was wrongly collapsed + // to `nearest_match` alone (see module doc / crate report). let ref_mv_ctx = match nearest_match { - 0 => 0, - 1 => 3, + 0 => match ref_match_count { + 0 => 0, + 1 => 1, + _ => 2, + }, + 1 => { + if ref_match_count >= 2 { + 4 + } else { + 3 + } + } _ => 5, }; // GLOBALMV_OFFSET is only ever set by temporal MV projection @@ -371,13 +473,13 @@ pub fn find_mv_stack( // (see module doc) — exact, not a stand-in. let zero_mv_ctx = 0; - // av1_drl_ctx (mvref_common.h): every candidate here is one of libaom's - // "nearest" ones (see module doc), so each gets `REF_CAT_LEVEL` before - // the comparison, which is why this always lands on 0. + // av1_drl_ctx (mvref_common.h): weight was boosted in place above for + // the nearest entries only, so this now compares the real stored weight + // against the threshold directly, the way libaom does. let drl_ctx = candidates .windows(2) .map(|w| { - let (a, b) = (w[0].weight + REF_CAT_LEVEL, w[1].weight + REF_CAT_LEVEL); + let (a, b) = (w[0].weight, w[1].weight); if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL { 0 } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL { @@ -443,8 +545,10 @@ mod tests { assert_eq!(stack.entries.len(), 1); assert_eq!(stack.entries[0].mv, mv); - // 2 above cells + 2 left cells + 1 top-right, each weight 2. - assert_eq!(stack.entries[0].weight, 10); + // 2 above cells + 2 left cells + 1 top-right, each weight 2, plus the + // REF_CAT_LEVEL boost av1_find_mv_stack applies to every entry the + // immediate row/col/top-right scan found (module doc). + assert_eq!(stack.entries[0].weight, 10 + REF_CAT_LEVEL); assert_eq!(stack.nearest_mv, mv); // Exact ctx (see module doc): both sides matched (nearest_match=2) // and no neighbour was coded NEWMV, which is libaom's @@ -469,19 +573,22 @@ mod tests { let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1, 8, 8); + // Both are entries the immediate scan found, so both get the + // REF_CAT_LEVEL boost (module doc) — their relative order is + // unaffected. assert_eq!(stack.entries.len(), 2); assert_eq!( stack.entries[0], StackEntry { mv: left_mv, - weight: 6 + weight: 6 + REF_CAT_LEVEL } ); assert_eq!( stack.entries[1], StackEntry { mv: above_mv, - weight: 4 + weight: 4 + REF_CAT_LEVEL } ); assert_eq!(stack.nearest_mv, left_mv); @@ -573,6 +680,32 @@ mod tests { assert_eq!(stack.ref_mv_ctx, 3); } + #[test] + fn a_diagonal_corner_match_raises_ref_mv_ctx_past_nearest_match() { + // Block at (2, 2), 1x1 mi unit: only the col to the left matches + // (nearest_match == 1, so a pre-fix `ref_mv_ctx` collapse would say + // 3 regardless of anything else — this is the exact round-10 defect + // shape). The row above has no match of its own, but the diagonal + // top-left corner (1, 1) does; libaom folds that into the row side + // of `ref_match_count` (raising it to 2) without ever touching the + // already-captured `nearest_match`. + let mut grid = MiGrid::new(8, 8); + grid.set(2, 1, inter((4, 4))); + grid.set(1, 1, inter((8, 8))); + + let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8); + + assert_eq!(stack.new_mv_ctx, 3); // depends on nearest_match alone: unchanged + assert_eq!(stack.ref_mv_ctx, 4); // nearest_match=1, ref_match_count=2 + // The corner's distinct MV becomes its own low-weight stack entry, + // ranked behind the boosted nearest one — DRL context sees a real + // (non-nearest) second candidate for the first time. + assert_eq!(stack.entries.len(), 2); + assert_eq!(stack.entries[0].mv, (4, 4)); + assert_eq!(stack.entries[1].mv, (8, 8)); + assert_eq!(stack.drl_ctx, vec![1]); + } + #[test] fn single_ref_ctx_matches_libaoms_collapsed_forward_only_case() { assert_eq!(single_ref_ctx(false), 1);