Merge branch 'lane-av1-size': pad-to-32 with cropped reconstructions
Browse files at this commit3 changed files +593 -57
- crates/ec-av1/src/encode.rs +412 -18
- crates/ec-av1/src/msac.rs +9 -0
- crates/ec-av1/src/mvstack.rs +172 -39
crates/ec-av1/src/encode.rsmodified+412 -18
| @@ -129,6 +129,137 @@ impl Picture { | |||
| 129 | } | 129 | } |
| 130 | Ok(()) | 130 | Ok(()) |
| 131 | } | 131 | } |
| 132 | + | ||
| 133 | + /// What the public entry points require of the picture they are handed, | ||
| 134 | + /// before it is padded to the block grid: even, nonzero dimensions (4:2:0 | ||
| 135 | + /// needs a whole chroma sample per two luma ones) and one sample per | ||
| 136 | + /// position on each plane. | ||
| 137 | + fn check_even(&self) -> Result<()> { | ||
| 138 | + if self.width == 0 | ||
| 139 | + || self.height == 0 | ||
| 140 | + || !self.width.is_multiple_of(2) | ||
| 141 | + || !self.height.is_multiple_of(2) | ||
| 142 | + { | ||
| 143 | + return Err(Error::unsupported( | ||
| 144 | + "AV1 encode", | ||
| 145 | + "the picture's width and height must each be even and nonzero", | ||
| 146 | + )); | ||
| 147 | + } | ||
| 148 | + let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); | ||
| 149 | + if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { | ||
| 150 | + return Err(Error::unsupported( | ||
| 151 | + "AV1 encode", | ||
| 152 | + "each plane must carry one sample per position at 4:2:0", | ||
| 153 | + )); | ||
| 154 | + } | ||
| 155 | + Ok(()) | ||
| 156 | + } | ||
| 157 | + | ||
| 158 | + /// This picture, padded by edge replication to the next whole number of | ||
| 159 | + /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key | ||
| 160 | + /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a | ||
| 161 | + /// sequence (what the inter tile writer's partition needs on top of | ||
| 162 | + /// that). Identity (a plain clone, not a copy through the replication | ||
| 163 | + /// loop) when the picture is already that size — the multiple-of-32 (or | ||
| 164 | + /// -64) fast path is unchanged. | ||
| 165 | + fn padded_to(&self, align: usize) -> Picture { | ||
| 166 | + let padded_width = self.width.next_multiple_of(align); | ||
| 167 | + let padded_height = self.height.next_multiple_of(align); | ||
| 168 | + if padded_width == self.width && padded_height == self.height { | ||
| 169 | + return self.clone(); | ||
| 170 | + } | ||
| 171 | + Picture { | ||
| 172 | + width: padded_width, | ||
| 173 | + height: padded_height, | ||
| 174 | + y: pad_plane( | ||
| 175 | + &self.y, | ||
| 176 | + self.width, | ||
| 177 | + self.height, | ||
| 178 | + padded_width, | ||
| 179 | + padded_height, | ||
| 180 | + ), | ||
| 181 | + u: pad_plane( | ||
| 182 | + &self.u, | ||
| 183 | + self.width / 2, | ||
| 184 | + self.height / 2, | ||
| 185 | + padded_width / 2, | ||
| 186 | + padded_height / 2, | ||
| 187 | + ), | ||
| 188 | + v: pad_plane( | ||
| 189 | + &self.v, | ||
| 190 | + self.width / 2, | ||
| 191 | + self.height / 2, | ||
| 192 | + padded_width / 2, | ||
| 193 | + padded_height / 2, | ||
| 194 | + ), | ||
| 195 | + } | ||
| 196 | + } | ||
| 197 | +} | ||
| 198 | + | ||
| 199 | +/// Pads one plane to `(padded_width, padded_height)` by repeating its last | ||
| 200 | +/// row and column, so the block coder always sees a whole number of blocks. | ||
| 201 | +/// [`crop_plane`] undoes this on the way back out. | ||
| 202 | +fn pad_plane( | ||
| 203 | + source: &[u8], | ||
| 204 | + width: usize, | ||
| 205 | + height: usize, | ||
| 206 | + padded_width: usize, | ||
| 207 | + padded_height: usize, | ||
| 208 | +) -> Vec<u8> { | ||
| 209 | + let mut out = vec![0u8; padded_width * padded_height]; | ||
| 210 | + for row in 0..padded_height { | ||
| 211 | + let src = source[row.min(height - 1) * width..][..width].as_ref(); | ||
| 212 | + let dst = &mut out[row * padded_width..][..padded_width]; | ||
| 213 | + dst[..width].copy_from_slice(src); | ||
| 214 | + dst[width..].fill(src[width - 1]); | ||
| 215 | + } | ||
| 216 | + out | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +/// The top-left `width` x `height` region of a plane that is `padded_width` | ||
| 220 | +/// wide, which is the render-size crop [`Picture::padded`]'s replication | ||
| 221 | +/// exists to let a decoder undo. | ||
| 222 | +fn crop_plane(source: &[u8], padded_width: usize, width: usize, height: usize) -> Vec<u8> { | ||
| 223 | + let mut out = Vec::with_capacity(width * height); | ||
| 224 | + for row in 0..height { | ||
| 225 | + out.extend_from_slice(&source[row * padded_width..][..width]); | ||
| 226 | + } | ||
| 227 | + out | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size | ||
| 231 | +/// region a decoder produces, which is the public contract for what a caller | ||
| 232 | +/// sees back — the padded planes the encoder coded against never leave this | ||
| 233 | +/// module. Identity when the reconstruction is already that size. | ||
| 234 | +fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded { | ||
| 235 | + let reconstruction = &encoded.reconstruction; | ||
| 236 | + let cropped = if reconstruction.width == width && reconstruction.height == height { | ||
| 237 | + reconstruction.clone() | ||
| 238 | + } else { | ||
| 239 | + Picture { | ||
| 240 | + width, | ||
| 241 | + height, | ||
| 242 | + y: crop_plane(&reconstruction.y, reconstruction.width, width, height), | ||
| 243 | + u: crop_plane( | ||
| 244 | + &reconstruction.u, | ||
| 245 | + reconstruction.width / 2, | ||
| 246 | + width / 2, | ||
| 247 | + height / 2, | ||
| 248 | + ), | ||
| 249 | + v: crop_plane( | ||
| 250 | + &reconstruction.v, | ||
| 251 | + reconstruction.width / 2, | ||
| 252 | + width / 2, | ||
| 253 | + height / 2, | ||
| 254 | + ), | ||
| 255 | + } | ||
| 256 | + }; | ||
| 257 | + Encoded { | ||
| 258 | + stream: encoded.stream.clone(), | ||
| 259 | + modes: encoded.modes.clone(), | ||
| 260 | + inter_block_share: encoded.inter_block_share, | ||
| 261 | + reconstruction: cropped, | ||
| 262 | + } | ||
| 132 | } | 263 | } |
| 133 | 264 | ||
| 134 | /// What one call to [`encode_key_frame`] produced. | 265 | /// What one call to [`encode_key_frame`] produced. |
| @@ -818,9 +949,15 @@ fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> { | |||
| 818 | /// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and | 949 | /// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and |
| 819 | /// smaller values trade fidelity for rate. | 950 | /// smaller values trade fidelity for rate. |
| 820 | /// | 951 | /// |
| 952 | +/// The picture may be any even width and height: the encoder pads it by edge | ||
| 953 | +/// replication to a whole number of 32x32 blocks internally, and the frame it | ||
| 954 | +/// writes crops back to the picture's own size (`render_width`/ | ||
| 955 | +/// `render_height`), so [`Encoded::reconstruction`] is always the picture's | ||
| 956 | +/// own size, never the padded one. | ||
| 957 | +/// | ||
| 821 | /// # Errors | 958 | /// # Errors |
| 822 | -/// Returns an error when the picture is not a whole number of 32x32 blocks, | 959 | +/// Returns an error when the picture's width or height is zero or odd, or |
| 823 | -/// or when its planes are not 4:2:0 of that size. | 960 | +/// when its planes are not 4:2:0 of that size. |
| 824 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { | 961 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { |
| 825 | encode_key_frame_with_modes(picture, base_q_idx, deadzone, &KEY_FRAME_MODES) | 962 | encode_key_frame_with_modes(picture, base_q_idx, deadzone, &KEY_FRAME_MODES) |
| 826 | } | 963 | } |
| @@ -842,17 +979,30 @@ pub fn encode_key_frame_with_modes( | |||
| 842 | deadzone: f64, | 979 | deadzone: f64, |
| 843 | modes: &[u8], | 980 | modes: &[u8], |
| 844 | ) -> Result<Encoded> { | 981 | ) -> Result<Encoded> { |
| 845 | - encode_key_frame_inner(picture, base_q_idx, deadzone, modes, split_blocks()) | 982 | + picture.check_even()?; |
| 983 | + let padded = picture.padded_to(BLOCK); | ||
| 984 | + let encoded = encode_key_frame_inner( | ||
| 985 | + &padded, | ||
| 986 | + base_q_idx, | ||
| 987 | + deadzone, | ||
| 988 | + modes, | ||
| 989 | + split_blocks(), | ||
| 990 | + (picture.width, picture.height), | ||
| 991 | + )?; | ||
| 992 | + Ok(crop_encoded(&encoded, picture.width, picture.height)) | ||
| 846 | } | 993 | } |
| 847 | 994 | ||
| 848 | /// [`encode_key_frame_with_modes`] with the partition decision forced, which is | 995 | /// [`encode_key_frame_with_modes`] with the partition decision forced, which is |
| 849 | -/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. | 996 | +/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is |
| 997 | +/// already padded to a whole number of 32x32 blocks; `render` is the real | ||
| 998 | +/// (pre-pad) size the frame header tells a decoder to crop back to. | ||
| 850 | fn encode_key_frame_inner( | 999 | fn encode_key_frame_inner( |
| 851 | picture: &Picture, | 1000 | picture: &Picture, |
| 852 | base_q_idx: u8, | 1001 | base_q_idx: u8, |
| 853 | deadzone: f64, | 1002 | deadzone: f64, |
| 854 | modes: &[u8], | 1003 | modes: &[u8], |
| 855 | split_blocks: bool, | 1004 | split_blocks: bool, |
| 1005 | + render: (usize, usize), | ||
| 856 | ) -> Result<Encoded> { | 1006 | ) -> Result<Encoded> { |
| 857 | picture.check()?; | 1007 | picture.check()?; |
| 858 | if modes.is_empty() { | 1008 | if modes.is_empty() { |
| @@ -867,7 +1017,9 @@ fn encode_key_frame_inner( | |||
| 867 | format!("intra mode {bad} is not one the encoder predicts"), | 1017 | format!("intra mode {bad} is not one the encoder predicts"), |
| 868 | )); | 1018 | )); |
| 869 | } | 1019 | } |
| 870 | - let (seq, header) = key_frame_headers(picture.width, picture.height, base_q_idx)?; | 1020 | + let (seq, mut header) = key_frame_headers(picture.width, picture.height, base_q_idx)?; |
| 1021 | + header.render_width = render.0 as u32; | ||
| 1022 | + header.render_height = render.1 as u32; | ||
| 871 | 1023 | ||
| 872 | let mut luma = Plane { | 1024 | let mut luma = Plane { |
| 873 | source: &picture.y, | 1025 | source: &picture.y, |
| @@ -1492,6 +1644,7 @@ fn encode_inter_frame( | |||
| 1492 | base_q_idx: u8, | 1644 | base_q_idx: u8, |
| 1493 | deadzone: f64, | 1645 | deadzone: f64, |
| 1494 | order_hint: u32, | 1646 | order_hint: u32, |
| 1647 | + render: (usize, usize), | ||
| 1495 | ) -> Result<Encoded> { | 1648 | ) -> Result<Encoded> { |
| 1496 | picture.check()?; | 1649 | picture.check()?; |
| 1497 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { | 1650 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| @@ -1514,13 +1667,15 @@ fn encode_inter_frame( | |||
| 1514 | // overwrites slot 0, so the frame just coded is always what the next one | 1667 | // overwrites slot 0, so the frame just coded is always what the next one |
| 1515 | // predicts against. | 1668 | // predicts against. |
| 1516 | const LAST_SLOT: u8 = 0; | 1669 | const LAST_SLOT: u8 = 0; |
| 1517 | - let (seq, header) = inter_frame_headers( | 1670 | + let (seq, mut header) = inter_frame_headers( |
| 1518 | picture.width, | 1671 | picture.width, |
| 1519 | picture.height, | 1672 | picture.height, |
| 1520 | base_q_idx, | 1673 | base_q_idx, |
| 1521 | order_hint, | 1674 | order_hint, |
| 1522 | LAST_SLOT, | 1675 | LAST_SLOT, |
| 1523 | )?; | 1676 | )?; |
| 1677 | + header.render_width = render.0 as u32; | ||
| 1678 | + header.render_height = render.1 as u32; | ||
| 1524 | 1679 | ||
| 1525 | let mut luma = Plane { | 1680 | let mut luma = Plane { |
| 1526 | source: &picture.y, | 1681 | source: &picture.y, |
| @@ -1638,8 +1793,10 @@ pub struct EncodedSequence { | |||
| 1638 | /// Encodes a sequence of pictures as a key frame followed by one inter frame | 1793 | /// Encodes a sequence of pictures as a key frame followed by one inter frame |
| 1639 | /// per remaining picture, each predicting from the previous frame's own | 1794 | /// per remaining picture, each predicting from the previous frame's own |
| 1640 | /// decoded reconstruction — never from the source, which is what a decoder | 1795 | /// decoded reconstruction — never from the source, which is what a decoder |
| 1641 | -/// cannot see. `pictures` must be a whole number of 64x64 superblocks in | 1796 | +/// cannot see. Every picture must be the same even size (any even width and |
| 1642 | -/// each direction (the inter tile writer's own constraint) and non-empty. | 1797 | +/// height — each is padded to a whole number of 64x64 superblocks |
| 1798 | +/// internally, which is what lets an inter frame's reference always match | ||
| 1799 | +/// the frame being coded against it), and `pictures` must be non-empty. | ||
| 1643 | /// | 1800 | /// |
| 1644 | /// # Errors | 1801 | /// # Errors |
| 1645 | /// Returns an error when `pictures` is empty, when any picture besides the | 1802 | /// Returns an error when `pictures` is empty, when any picture besides the |
| @@ -1656,16 +1813,44 @@ pub fn encode_sequence( | |||
| 1656 | "a sequence needs at least one picture", | 1813 | "a sequence needs at least one picture", |
| 1657 | )); | 1814 | )); |
| 1658 | }; | 1815 | }; |
| 1659 | - let key = encode_key_frame(first, base_q_idx, deadzone)?; | 1816 | + first.check_even()?; |
| 1817 | + let render = (first.width, first.height); | ||
| 1818 | + // The key frame and every inter frame after it are coded at the same | ||
| 1819 | + // padded size, so the reference each inter frame predicts from -- the | ||
| 1820 | + // previous frame's own uncropped reconstruction, at the size a decoder's | ||
| 1821 | + // reference buffer actually holds -- always matches the frame being | ||
| 1822 | + // coded against it. | ||
| 1823 | + let key = encode_key_frame_inner( | ||
| 1824 | + &first.padded_to(SUPERBLOCK), | ||
| 1825 | + base_q_idx, | ||
| 1826 | + deadzone, | ||
| 1827 | + &KEY_FRAME_MODES, | ||
| 1828 | + split_blocks(), | ||
| 1829 | + render, | ||
| 1830 | + )?; | ||
| 1660 | let mut stream = key.stream.clone(); | 1831 | let mut stream = key.stream.clone(); |
| 1661 | let mut reference = key.reconstruction.clone(); | 1832 | let mut reference = key.reconstruction.clone(); |
| 1662 | - let mut frames = vec![key]; | 1833 | + let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 1663 | for (i, picture) in rest.iter().enumerate() { | 1834 | for (i, picture) in rest.iter().enumerate() { |
| 1835 | + picture.check_even()?; | ||
| 1836 | + if (picture.width, picture.height) != render { | ||
| 1837 | + return Err(Error::unsupported( | ||
| 1838 | + "AV1 encode", | ||
| 1839 | + "every picture in a sequence must be the same size as the first", | ||
| 1840 | + )); | ||
| 1841 | + } | ||
| 1664 | let order_hint = (i + 1) as u32; | 1842 | let order_hint = (i + 1) as u32; |
| 1665 | - let inter = encode_inter_frame(picture, &reference, base_q_idx, deadzone, order_hint)?; | 1843 | + let inter = encode_inter_frame( |
| 1844 | + &picture.padded_to(SUPERBLOCK), | ||
| 1845 | + &reference, | ||
| 1846 | + base_q_idx, | ||
| 1847 | + deadzone, | ||
| 1848 | + order_hint, | ||
| 1849 | + render, | ||
| 1850 | + )?; | ||
| 1666 | stream.extend_from_slice(&inter.stream); | 1851 | stream.extend_from_slice(&inter.stream); |
| 1667 | reference = inter.reconstruction.clone(); | 1852 | reference = inter.reconstruction.clone(); |
| 1668 | - frames.push(inter); | 1853 | + frames.push(crop_encoded(&inter, render.0, render.1)); |
| 1669 | } | 1854 | } |
| 1670 | Ok(EncodedSequence { stream, frames }) | 1855 | Ok(EncodedSequence { stream, frames }) |
| 1671 | } | 1856 | } |
| @@ -1873,6 +2058,198 @@ mod tests { | |||
| 1873 | ffmpeg_decode_sequence(&stream, width, height, 2); | 2058 | ffmpeg_decode_sequence(&stream, width, height, 2); |
| 1874 | } | 2059 | } |
| 1875 | 2060 | ||
| 2061 | + /// The top-left `width` x `height` region of a decoded picture, for | ||
| 2062 | + /// comparing against [`Encoded::reconstruction`] (already cropped to | ||
| 2063 | + /// the same region) when ffmpeg hands back the padded, coded-size one. | ||
| 2064 | + fn crop_picture(picture: &Picture, width: usize, height: usize) -> Picture { | ||
| 2065 | + Picture { | ||
| 2066 | + width, | ||
| 2067 | + height, | ||
| 2068 | + y: crop_plane(&picture.y, picture.width, width, height), | ||
| 2069 | + u: crop_plane(&picture.u, picture.width / 2, width / 2, height / 2), | ||
| 2070 | + v: crop_plane(&picture.v, picture.width / 2, width / 2, height / 2), | ||
| 2071 | + } | ||
| 2072 | + } | ||
| 2073 | + | ||
| 2074 | + /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded | ||
| 2075 | + /// frame size an AV1 decoder allocates, not necessarily the render size | ||
| 2076 | + /// (see [`a_frame_round_trips_at_its_own_size`]). | ||
| 2077 | + fn ffprobe_size(stream: &[u8]) -> (u32, u32) { | ||
| 2078 | + let path = std::env::temp_dir().join(format!("ec-av1-probe-{}.obu", std::process::id())); | ||
| 2079 | + let _ = std::fs::remove_file(&path); | ||
| 2080 | + std::fs::write(&path, stream).expect("writing the probe stream"); | ||
| 2081 | + let out = Command::new("ffprobe") | ||
| 2082 | + .args([ | ||
| 2083 | + "-v", | ||
| 2084 | + "error", | ||
| 2085 | + "-f", | ||
| 2086 | + "obu", | ||
| 2087 | + "-select_streams", | ||
| 2088 | + "v:0", | ||
| 2089 | + "-show_entries", | ||
| 2090 | + "stream=width,height", | ||
| 2091 | + "-of", | ||
| 2092 | + "csv=p=0", | ||
| 2093 | + ]) | ||
| 2094 | + .arg(&path) | ||
| 2095 | + .output() | ||
| 2096 | + .expect("ffprobe failed to run"); | ||
| 2097 | + let _ = std::fs::remove_file(&path); | ||
| 2098 | + assert!( | ||
| 2099 | + out.status.success(), | ||
| 2100 | + "ffprobe refused the stream: {}", | ||
| 2101 | + String::from_utf8_lossy(&out.stderr) | ||
| 2102 | + ); | ||
| 2103 | + let text = String::from_utf8_lossy(&out.stdout); | ||
| 2104 | + let mut fields = text.trim().split(','); | ||
| 2105 | + let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); | ||
| 2106 | + let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); | ||
| 2107 | + (width, height) | ||
| 2108 | + } | ||
| 2109 | + | ||
| 2110 | + /// A key frame at an arbitrary even size round-trips through ffmpeg over | ||
| 2111 | + /// its own render rectangle: [`Encoded::reconstruction`] is exactly the | ||
| 2112 | + /// picture's own size, and what ffmpeg decodes over that same top-left | ||
| 2113 | + /// region equals it sample for sample. | ||
| 2114 | + /// | ||
| 2115 | + /// This does not check that `ffprobe` reports the picture's own size, | ||
| 2116 | + /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded | ||
| 2117 | + /// (block-padded) frame size, the same one libaom itself would code for | ||
| 2118 | + /// a non-block-aligned picture. `render_width`/`render_height` (which | ||
| 2119 | + /// this crate sets correctly, spec 5.9.6) is a display hint no AV1 | ||
| 2120 | + /// decoder is required to crop pixels by, and ffmpeg's does not -- | ||
| 2121 | + /// checked empirically against ffprobe here and against a real libaom | ||
| 2122 | + /// encode separately. So the coded size, not the render size, is what | ||
| 2123 | + /// `ffprobe` is asserted to report below. | ||
| 2124 | + #[test] | ||
| 2125 | + fn a_frame_round_trips_at_its_own_size() { | ||
| 2126 | + if !have_ffmpeg() { | ||
| 2127 | + eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg"); | ||
| 2128 | + return; | ||
| 2129 | + } | ||
| 2130 | + // 854x480 is deliberately not in this list -- it hits an open, | ||
| 2131 | + // content-dependent desync unrelated to padding wiring; see | ||
| 2132 | + // `open_defect_854x480_padded_key_frame_desyncs`. | ||
| 2133 | + for &(width, height) in &[(1920usize, 1080usize), (640, 352), (1280, 720)] { | ||
| 2134 | + let picture = test_card(width, height); | ||
| 2135 | + let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); | ||
| 2136 | + assert_eq!( | ||
| 2137 | + (encoded.reconstruction.width, encoded.reconstruction.height), | ||
| 2138 | + (width, height), | ||
| 2139 | + "{width}x{height}: reconstruction is cropped to the picture's own size" | ||
| 2140 | + ); | ||
| 2141 | + let (padded_width, padded_height) = ( | ||
| 2142 | + width.next_multiple_of(BLOCK), | ||
| 2143 | + height.next_multiple_of(BLOCK), | ||
| 2144 | + ); | ||
| 2145 | + assert_eq!( | ||
| 2146 | + ffprobe_size(&encoded.stream), | ||
| 2147 | + (padded_width as u32, padded_height as u32), | ||
| 2148 | + "{width}x{height}: ffprobe reports the coded (padded) size" | ||
| 2149 | + ); | ||
| 2150 | + let decoded = ffmpeg_decode(&encoded.stream, padded_width, padded_height); | ||
| 2151 | + let cropped = crop_picture(&decoded, width, height); | ||
| 2152 | + assert_eq!( | ||
| 2153 | + cropped.y, encoded.reconstruction.y, | ||
| 2154 | + "{width}x{height}: luma" | ||
| 2155 | + ); | ||
| 2156 | + assert_eq!(cropped.u, encoded.reconstruction.u, "{width}x{height}: U"); | ||
| 2157 | + assert_eq!(cropped.v, encoded.reconstruction.v, "{width}x{height}: V"); | ||
| 2158 | + } | ||
| 2159 | + } | ||
| 2160 | + | ||
| 2161 | + /// Reproduces an open defect this lane's sweep found: 854x480 (padded to | ||
| 2162 | + /// 864x480, an *edge-replication* padded key frame -- not a preexisting | ||
| 2163 | + /// bug, since 864x480 coded directly with no padding involved is | ||
| 2164 | + /// bit-exact) desyncs against ffmpeg's decode starting at luma (row 161, | ||
| 2165 | + /// col 369), well inside the real (non-padded) region, not at the | ||
| 2166 | + /// padding edge. 640x352, 1280x720, 854x480's own height (480, already | ||
| 2167 | + /// 32-aligned) and 1920x1080 all round-trip clean, and the padding/crop | ||
| 2168 | + /// plumbing itself is exercised bit-exact by | ||
| 2169 | + /// `a_frame_round_trips_at_its_own_size` and the 64x64-superblock | ||
| 2170 | + /// sequence case, so this looks like a content-triggered desync inside | ||
| 2171 | + /// the coefficient/intra coding this lane was told not to touch | ||
| 2172 | + /// (`tile.rs`), not a padding-wiring bug. Left `#[ignore]`d rather than | ||
| 2173 | + /// silently dropped from the charter's size list -- next lane should | ||
| 2174 | + /// start from the row/col this test prints. | ||
| 2175 | + #[test] | ||
| 2176 | + #[ignore = "open defect: content-dependent desync at 854x480 padded, not padding wiring -- see doc comment"] | ||
| 2177 | + fn open_defect_854x480_padded_key_frame_desyncs() { | ||
| 2178 | + if !have_ffmpeg() { | ||
| 2179 | + return; | ||
| 2180 | + } | ||
| 2181 | + let (width, height) = (854usize, 480usize); | ||
| 2182 | + let picture = test_card(width, height); | ||
| 2183 | + let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); | ||
| 2184 | + let (padded_width, padded_height) = ( | ||
| 2185 | + width.next_multiple_of(BLOCK), | ||
| 2186 | + height.next_multiple_of(BLOCK), | ||
| 2187 | + ); | ||
| 2188 | + let decoded = ffmpeg_decode(&encoded.stream, padded_width, padded_height); | ||
| 2189 | + let cropped = crop_picture(&decoded, width, height); | ||
| 2190 | + assert_eq!(cropped.y, encoded.reconstruction.y, "854x480: luma"); | ||
| 2191 | + } | ||
| 2192 | + | ||
| 2193 | + /// An odd width or height is refused by name, not by however the padder | ||
| 2194 | + /// or the block coder would happen to fail on it. | ||
| 2195 | + #[test] | ||
| 2196 | + fn odd_dimensions_are_refused() { | ||
| 2197 | + for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { | ||
| 2198 | + let picture = Picture::grey(width, height); | ||
| 2199 | + let err = encode_key_frame(&picture, 100, 0.5) | ||
| 2200 | + .expect_err(&format!("{width}x{height} is odd and must be refused")); | ||
| 2201 | + assert!( | ||
| 2202 | + err.to_string().contains("even"), | ||
| 2203 | + "{width}x{height}: error was {err}" | ||
| 2204 | + ); | ||
| 2205 | + } | ||
| 2206 | + } | ||
| 2207 | + | ||
| 2208 | + /// A sequence at a size that is not a multiple of the block grid decodes | ||
| 2209 | + /// to the right frame count and the right size for every frame, | ||
| 2210 | + /// including the inter frames whose reference is the previous frame's | ||
| 2211 | + /// own (padded) reconstruction. | ||
| 2212 | + #[test] | ||
| 2213 | + fn sequence_round_trips_at_a_non_multiple_size() { | ||
| 2214 | + if !have_ffmpeg() { | ||
| 2215 | + eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg"); | ||
| 2216 | + return; | ||
| 2217 | + } | ||
| 2218 | + let (width, height) = (160usize, 96usize); | ||
| 2219 | + let pictures: Vec<Picture> = (0..3) | ||
| 2220 | + .map(|i| panned_test_card(width, height, i * 3)) | ||
| 2221 | + .collect(); | ||
| 2222 | + let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); | ||
| 2223 | + assert_eq!(encoded.frames.len(), 3); | ||
| 2224 | + for (i, frame) in encoded.frames.iter().enumerate() { | ||
| 2225 | + assert_eq!( | ||
| 2226 | + (frame.reconstruction.width, frame.reconstruction.height), | ||
| 2227 | + (width, height), | ||
| 2228 | + "frame {i}: reconstruction size" | ||
| 2229 | + ); | ||
| 2230 | + } | ||
| 2231 | + // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the | ||
| 2232 | + // coded (superblock-padded) size a sequence's frames share, not the | ||
| 2233 | + // render size. | ||
| 2234 | + let (padded_width, padded_height) = ( | ||
| 2235 | + width.next_multiple_of(SUPERBLOCK), | ||
| 2236 | + height.next_multiple_of(SUPERBLOCK), | ||
| 2237 | + ); | ||
| 2238 | + assert_eq!( | ||
| 2239 | + ffprobe_size(&encoded.stream), | ||
| 2240 | + (padded_width as u32, padded_height as u32), | ||
| 2241 | + "sequence: ffprobe reports the coded (padded) size" | ||
| 2242 | + ); | ||
| 2243 | + let decoded = ffmpeg_decode_sequence(&encoded.stream, padded_width, padded_height, 3); | ||
| 2244 | + assert_eq!(decoded.len(), 3, "decoded frame count"); | ||
| 2245 | + for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { | ||
| 2246 | + let cropped = crop_picture(decoded, width, height); | ||
| 2247 | + assert_eq!(cropped.y, frame.reconstruction.y, "frame {i}: luma"); | ||
| 2248 | + assert_eq!(cropped.u, frame.reconstruction.u, "frame {i}: U"); | ||
| 2249 | + assert_eq!(cropped.v, frame.reconstruction.v, "frame {i}: V"); | ||
| 2250 | + } | ||
| 2251 | + } | ||
| 2252 | + | ||
| 1876 | /// One frame of a real clip, scaled to a whole number of 32x32 blocks. | 2253 | /// One frame of a real clip, scaled to a whole number of 32x32 blocks. |
| 1877 | fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { | 2254 | fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { |
| 1878 | let out = Command::new("ffmpeg") | 2255 | let out = Command::new("ffmpeg") |
| @@ -1959,8 +2336,14 @@ mod tests { | |||
| 1959 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] | 2336 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 1960 | .iter() | 2337 | .iter() |
| 1961 | .map(|&q| { | 2338 | .map(|&q| { |
| 1962 | - let encoded = | 2339 | + let encoded = encode_key_frame_inner( |
| 1963 | - encode_key_frame_inner(&picture, q, 0.5, &KEY_FRAME_MODES, split) | 2340 | + &picture, |
| 2341 | + q, | ||
| 2342 | + 0.5, | ||
| 2343 | + &KEY_FRAME_MODES, | ||
| 2344 | + split, | ||
| 2345 | + (picture.width, picture.height), | ||
| 2346 | + ) | ||
| 1964 | .unwrap(); | 2347 | .unwrap(); |
| 1965 | ( | 2348 | ( |
| 1966 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), | 2349 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| @@ -1972,7 +2355,14 @@ mod tests { | |||
| 1972 | points | 2355 | points |
| 1973 | }; | 2356 | }; |
| 1974 | let (whole, split) = (ladder(false), ladder(true)); | 2357 | let (whole, split) = (ladder(false), ladder(true)); |
| 1975 | - let blocks = encode_key_frame_inner(&picture, 90, 0.5, &KEY_FRAME_MODES, true) | 2358 | + let blocks = encode_key_frame_inner( |
| 2359 | + &picture, | ||
| 2360 | + 90, | ||
| 2361 | + 0.5, | ||
| 2362 | + &KEY_FRAME_MODES, | ||
| 2363 | + true, | ||
| 2364 | + (picture.width, picture.height), | ||
| 2365 | + ) | ||
| 1976 | .unwrap() | 2366 | .unwrap() |
| 1977 | .modes | 2367 | .modes |
| 1978 | .len(); | 2368 | .len(); |
| @@ -2384,11 +2774,15 @@ mod tests { | |||
| 2384 | } | 2774 | } |
| 2385 | 2775 | ||
| 2386 | /// The sizes the encoder refuses, refused for a reason rather than by | 2776 | /// The sizes the encoder refuses, refused for a reason rather than by |
| 2387 | - /// panicking somewhere below. | 2777 | + /// panicking somewhere below. 40x32 and 32x48 are off the 32x32 block |
| 2778 | + /// grid, which used to be refused outright; the encoder now pads a | ||
| 2779 | + /// picture like that internally (see `a_frame_round_trips_at_its_own_size`) | ||
| 2780 | + /// rather than refusing it, so those two are an accept, not a refusal, | ||
| 2781 | + /// here. | ||
| 2388 | #[test] | 2782 | #[test] |
| 2389 | fn a_picture_off_the_block_grid_is_refused() { | 2783 | fn a_picture_off_the_block_grid_is_refused() { |
| 2390 | - assert!(encode_key_frame(&Picture::grey(40, 32), 100, 0.5).is_err()); | 2784 | + assert!(encode_key_frame(&Picture::grey(40, 32), 100, 0.5).is_ok()); |
| 2391 | - assert!(encode_key_frame(&Picture::grey(32, 48), 100, 0.5).is_err()); | 2785 | + assert!(encode_key_frame(&Picture::grey(32, 48), 100, 0.5).is_ok()); |
| 2392 | let mut short = Picture::grey(64, 64); | 2786 | let mut short = Picture::grey(64, 64); |
| 2393 | short.u.truncate(10); | 2787 | short.u.truncate(10); |
| 2394 | assert!(encode_key_frame(&short, 100, 0.5).is_err()); | 2788 | assert!(encode_key_frame(&short, 100, 0.5).is_err()); |
crates/ec-av1/src/msac.rsmodified+9 -0
| @@ -77,6 +77,15 @@ impl SymbolEncoder { | |||
| 77 | self.bits | 77 | self.bits |
| 78 | } | 78 | } |
| 79 | 79 | ||
| 80 | + /// The exact bit position the stream has committed to so far (libaom's | ||
| 81 | + /// `od_ec_enc_tell`, `entenc.c`): `cnt + 10` undoes the `-9` `cnt` starts | ||
| 82 | + /// at and reserves the one bit `finish` always spends, and `precarry` | ||
| 83 | + /// holds one `u16` per byte already flushed. Pairs with the decoder's | ||
| 84 | + /// `aom_reader_tell`, which counts the same bits consumed. | ||
| 85 | + pub fn tell(&self) -> i32 { | ||
| 86 | + self.cnt + 10 + self.precarry.len() as i32 * 8 | ||
| 87 | + } | ||
| 88 | + | ||
| 80 | /// Forgets the cost accumulated so far, so that the next stretch of | 89 | /// Forgets the cost accumulated so far, so that the next stretch of |
| 81 | /// symbols can be priced on its own. | 90 | /// symbols can be priced on its own. |
| 82 | pub fn reset_bits(&mut self) { | 91 | pub fn reset_bits(&mut self) { |
crates/ec-av1/src/mvstack.rsmodified+172 -39
| @@ -12,29 +12,68 @@ | |||
| 12 | //! `newmv_count > 0` tests) and `av1_drl_ctx` (`mvref_common.h`), plus MV | 12 | //! `newmv_count > 0` tests) and `av1_drl_ctx` (`mvref_common.h`), plus MV |
| 13 | //! clamping (7.10.2.14, libaom's `clamp_mv_ref`). | 13 | //! clamping (7.10.2.14, libaom's `clamp_mv_ref`). |
| 14 | //! | 14 | //! |
| 15 | -//! This module's scan is already reduced to the immediate row/col/top-right | 15 | +//! This module's immediate row/col/top-right scan alone is *not* enough to |
| 16 | -//! positions with no extended-offset scan (see below), which lets those | 16 | +//! get `RefMvContext` (`ref_mv_ctx`) right, even though it *is* enough for |
| 17 | -//! context formulas collapse exactly rather than approximately: libaom's | 17 | +//! `NewMvContext`/`ZeroMvContext`. Ported straight from libaom's |
| 18 | -//! `ref_match_count` comes from the *same* row/col match counters as | 18 | +//! `av1_find_mv_stack` (`av1/common/mvref_common.c`, `setup_ref_mv_list`, |
| 19 | -//! `nearest_match` once the extended scan is gone, so `ref_match_count == | 19 | +//! ~line 480 on): after the immediate row (-1), col (-1) and top-right |
| 20 | -//! nearest_match` always here, and every candidate this module finds is one | 20 | +//! probes settle `nearest_match` (and `mode_context`'s `new_mv` bits, which |
| 21 | -//! of libaom's "nearest" ones, so the `REF_CAT_LEVEL` (640) bonus | 21 | +//! depend on `nearest_match` alone), libaom runs one more probe *before* |
| 22 | -//! `av1_find_mv_stack` adds to nearest candidates before computing DRL | 22 | +//! computing `ref_match_count` — `scan_blk_mbmi` at the diagonal top-left |
| 23 | -//! context applies to all of them uniformly — which is why [`find_mv_stack`] | 23 | +//! corner `(-1, -1)` — whose match folds into `row_match_count` (and hence |
| 24 | -//! always reports `drl_ctx == 0`: with the extended scan absent, no | 24 | +//! can flip `ref_match_count`'s row term true) without ever touching the |
| 25 | -//! candidate here can ever be a "non-nearest" (sub-640) one for a pair | 25 | +//! already-captured `nearest_match`. So `ref_match_count >= nearest_match` |
| 26 | -//! comparison to distinguish. Likewise, the `GLOBALMV_OFFSET` bit of | 26 | +//! always, sometimes strictly greater, and `ref_mv_ctx` (the `REFMV_OFFSET` |
| 27 | -//! libaom's `mode_context` is set only inside | 27 | +//! half of libaom's `mode_context` switch, mvref_common.c ~line 619-643) |
| 28 | +//! genuinely depends on both counts, not `nearest_match` alone — that | ||
| 29 | +//! collapse was the bug this module shipped with for several rounds (see | ||
| 30 | +//! the crate report). [`find_mv_stack`] now runs that corner probe and | ||
| 31 | +//! computes `ref_mv_ctx` from the true `(nearest_match, ref_match_count)` | ||
| 32 | +//! pair. | ||
| 33 | +//! | ||
| 34 | +//! The corner probe's own candidate is added to the stack too (matching | ||
| 35 | +//! libaom: a genuinely new MV there becomes a real, if low-weight, entry), | ||
| 36 | +//! but — like the reduced row/col/top-right scans — at this module's own | ||
| 37 | +//! `IMMEDIATE_WEIGHT` scale rather than libaom's real `len * max(2, inc)` | ||
| 38 | +//! (row/col) or `2 * mi_size_wide[BLOCK_8X8]` (corner/top-right) weights. | ||
| 39 | +//! That scale mismatch is harmless for every caller this module has: the | ||
| 40 | +//! only real caller (`tile.rs`) always asks for a fixed `bw4 == bh4 == 8` | ||
| 41 | +//! block, at which size libaom's row and col weights are *always tied* | ||
| 42 | +//! (both scan a full-width same-size neighbour) and its corner/top-right | ||
| 43 | +//! weight is *always* far below either — exactly the ordering | ||
| 44 | +//! `IMMEDIATE_WEIGHT` already reproduces, so sort order and the | ||
| 45 | +//! `REF_CAT_LEVEL`-vs-not DRL split (which only tests a threshold, not a | ||
| 46 | +//! magnitude) come out identical either way. A caller with mixed block | ||
| 47 | +//! sizes would need the real weight formula; none exists today. | ||
| 48 | +//! | ||
| 49 | +//! The corner probe's own match does *not* count toward the real | ||
| 50 | +//! `newmv_count` that feeds `new_mv_ctx` (libaom passes it a `dummy_newmv_count` | ||
| 51 | +//! there) — only row/col/top-right do. | ||
| 52 | +//! | ||
| 53 | +//! Also ported (from `av1_drl_ctx`, `mvref_common.h`): the `REF_CAT_LEVEL` | ||
| 54 | +//! (640) bonus applies only to the entries the row/col/top-right scan found | ||
| 55 | +//! (`nearest_refmv_count`), added to their stored weight *before* the corner | ||
| 56 | +//! probe can add a new, unboosted entry — so `drl_ctx` can now be non-zero | ||
| 57 | +//! when the corner probe contributes a genuinely new candidate. | ||
| 58 | +//! | ||
| 59 | +//! The `GLOBALMV_OFFSET` bit of libaom's `mode_context` is set only inside | ||
| 28 | //! `cm->features.allow_ref_frame_mvs` (temporal MV projection), which this | 60 | //! `cm->features.allow_ref_frame_mvs` (temporal MV projection), which this |
| 29 | //! module never has (`use_ref_frame_mvs = 0`), so `zero_mv_ctx` is always 0 | 61 | //! module never has (`use_ref_frame_mvs = 0`), so `zero_mv_ctx` is always 0 |
| 30 | -//! here — again exact for the case this module covers, not a stand-in. | 62 | +//! here — exact for the case this module covers, not a stand-in. |
| 31 | //! | 63 | //! |
| 32 | //! Deliberately reduced away (see the crate report, not reproduced bit-exact | 64 | //! Deliberately reduced away (see the crate report, not reproduced bit-exact |
| 33 | //! here): compound/multi-reference candidates, the temporal MV projection | 65 | //! here): compound/multi-reference candidates, the temporal MV projection |
| 34 | -//! scan, and the `>1` row/col scans at offset 3 and their skip-by-block-size | 66 | +//! scan, the real (non-corner) `idx = 2..MVREF_ROW_COLS` extended row/col |
| 35 | -//! stepping (which is also why the "extra search" that pads a short stack to | 67 | +//! scan positions (libaom's own `processed_rows`/`processed_cols` bookkeeping |
| 36 | -//! two entries, spec 7.10.2.12, is not implemented — this module's stack can | 68 | +//! means those never fire for this module's fixed 8-mi block geometry — the |
| 37 | -//! be shorter than two candidates where libaom's never is). | 69 | +//! immediate-offset scan's coverage window already reaches as far as the |
| 70 | +//! extended offsets can, so nothing there is left unscanned), the | ||
| 71 | +//! single-reference "extension" pass that re-walks the same row/col | ||
| 72 | +//! neighbours through `process_single_ref_mv_candidate` (a no-op here: with | ||
| 73 | +//! only one reference frame ever in play, whatever it would add was already | ||
| 74 | +//! added by the row/col scan), and the "extra search" that pads a short | ||
| 75 | +//! stack to two entries (spec 7.10.2.12) — this module's stack can be | ||
| 76 | +//! shorter than two candidates where libaom's never is. | ||
| 38 | 77 | ||
| 39 | /// One 4x4 `mi` unit's motion state, as the encode loop will have filled it | 78 | /// One 4x4 `mi` unit's motion state, as the encode loop will have filled it |
| 40 | /// in by the time it asks for a block's MV stack. | 79 | /// in by the time it asks for a block's MV stack. |
| @@ -240,6 +279,34 @@ fn scan_top_right( | |||
| 240 | false | 279 | false |
| 241 | } | 280 | } |
| 242 | 281 | ||
| 282 | +/// The diagonal top-left corner probe (libaom `scan_blk_mbmi` at | ||
| 283 | +/// `row_offset = col_offset = -1`, mvref_common.c's "second outer area", | ||
| 284 | +/// called *after* `nearest_match` is already captured): the single unit | ||
| 285 | +/// diagonally above-left of the block. Its match folds into the row bucket | ||
| 286 | +/// too (see module doc) but must never move `nearest_match` itself or the | ||
| 287 | +/// real `newmv_count` — callers pass a throwaway counter for the latter. | ||
| 288 | +fn scan_corner( | ||
| 289 | + grid: &MiGrid, | ||
| 290 | + mi_row: usize, | ||
| 291 | + mi_col: usize, | ||
| 292 | + ref_frame: i8, | ||
| 293 | + candidates: &mut Vec<StackEntry>, | ||
| 294 | + newmv_count: &mut u32, | ||
| 295 | +) -> bool { | ||
| 296 | + let (Some(row), Some(col)) = (mi_row.checked_sub(1), mi_col.checked_sub(1)) else { | ||
| 297 | + return false; | ||
| 298 | + }; | ||
| 299 | + if let Some(info) = grid.get(row, col) | ||
| 300 | + && info.is_inter | ||
| 301 | + && info.ref_frame == ref_frame | ||
| 302 | + { | ||
| 303 | + add_candidate(candidates, info.mv, IMMEDIATE_WEIGHT); | ||
| 304 | + *newmv_count += u32::from(info.is_new_mv); | ||
| 305 | + return true; | ||
| 306 | + } | ||
| 307 | + false | ||
| 308 | +} | ||
| 309 | + | ||
| 243 | /// `MV_BORDER` (spec 7.10.2.14): 16 pixels of slack in 1/8-pel units, added | 310 | /// `MV_BORDER` (spec 7.10.2.14): 16 pixels of slack in 1/8-pel units, added |
| 244 | /// on top of the block's own span before a candidate is clamped to the | 311 | /// on top of the block's own span before a candidate is clamped to the |
| 245 | /// frame. | 312 | /// frame. |
| @@ -318,8 +385,38 @@ pub fn find_mv_stack( | |||
| 318 | &mut newmv_count, | 385 | &mut newmv_count, |
| 319 | ); | 386 | ); |
| 320 | 387 | ||
| 388 | + // libaom's `row_match_count`/`col_match_count` (mvref_common.c) fold the | ||
| 389 | + // top-right probe into the row side, so "found above" for context | ||
| 390 | + // purposes means the row scan *or* the top-right one matched. | ||
| 391 | + let row_matched = found_above || found_top_right; | ||
| 392 | + let nearest_match = usize::from(row_matched) + usize::from(found_left); | ||
| 393 | + | ||
| 394 | + // av1_find_mv_stack boosts only the entries the immediate scan found — | ||
| 395 | + // exactly `candidates` at this point, before the corner probe (below) | ||
| 396 | + // can add anything else (mvref_common.c ~line 544-545). | ||
| 397 | + for entry in &mut candidates { | ||
| 398 | + entry.weight += REF_CAT_LEVEL; | ||
| 399 | + } | ||
| 400 | + | ||
| 401 | + // The diagonal top-left corner probe (module doc): folds into the row | ||
| 402 | + // side for `ref_match_count` without moving the already-captured | ||
| 403 | + // `nearest_match`, and its own newmv-ness is a dummy count libaom | ||
| 404 | + // discards (`&dummy_newmv_count` at the real call site). | ||
| 405 | + let mut dummy_newmv_count = 0u32; | ||
| 406 | + let corner_matched = scan_corner( | ||
| 407 | + grid, | ||
| 408 | + mi_row, | ||
| 409 | + mi_col, | ||
| 410 | + ref_frame, | ||
| 411 | + &mut candidates, | ||
| 412 | + &mut dummy_newmv_count, | ||
| 413 | + ); | ||
| 414 | + let ref_match_count = usize::from(row_matched || corner_matched) + usize::from(found_left); | ||
| 415 | + | ||
| 321 | // Highest weight first; a stable sort keeps scan order (above, left, | 416 | // Highest weight first; a stable sort keeps scan order (above, left, |
| 322 | - // top-right) among ties, matching spec 7.10.2.6. | 417 | + // top-right, corner) among ties, matching spec 7.10.2.6. The corner |
| 418 | + // probe's un-boosted entry (if new) always sorts after the boosted | ||
| 419 | + // ones above, matching libaom's separate two-phase ranking. | ||
| 323 | candidates.sort_by_key(|e| std::cmp::Reverse(e.weight)); | 420 | candidates.sort_by_key(|e| std::cmp::Reverse(e.weight)); |
| 324 | candidates.truncate(MAX_STACK_SIZE); | 421 | candidates.truncate(MAX_STACK_SIZE); |
| 325 | 422 | ||
| @@ -332,18 +429,10 @@ pub fn find_mv_stack( | |||
| 332 | nearest_mv | 429 | nearest_mv |
| 333 | }; | 430 | }; |
| 334 | 431 | ||
| 335 | - // libaom's `row_match_count`/`col_match_count` (mvref_common.c) fold the | ||
| 336 | - // top-right probe into the row side, so "found above" for context | ||
| 337 | - // purposes means the row scan *or* the top-right one matched. | ||
| 338 | - let row_matched = found_above || found_top_right; | ||
| 339 | - let nearest_match = usize::from(row_matched) + usize::from(found_left); | ||
| 340 | - | ||
| 341 | // Exact port of the `mode_context[ref_frame]` switch (mvref_common.c | 432 | // Exact port of the `mode_context[ref_frame]` switch (mvref_common.c |
| 342 | - // ~line 619-643): with no extended-offset scan, `ref_match_count` here is | 433 | + // ~line 619-643). `new_mv_ctx` depends on `nearest_match` and the real |
| 343 | - // always equal to `nearest_match` (both come from the same row/col match | 434 | + // `newmv_count` alone — libaom's switch never reads `ref_match_count` |
| 344 | - // counters this module never advances further), so the `ref_match_count` | 435 | + // for those bits, so this half was already exact before this round. |
| 345 | - // branches of libaom's switch collapse into the constants below — see | ||
| 346 | - // module doc. | ||
| 347 | let new_mv_ctx = match nearest_match { | 436 | let new_mv_ctx = match nearest_match { |
| 348 | 0 => 0, | 437 | 0 => 0, |
| 349 | 1 => { | 438 | 1 => { |
| @@ -361,9 +450,22 @@ pub fn find_mv_stack( | |||
| 361 | } | 450 | } |
| 362 | } | 451 | } |
| 363 | }; | 452 | }; |
| 453 | + // `ref_mv_ctx` (the `REFMV_OFFSET` half of the same switch) genuinely | ||
| 454 | + // depends on both counts — this is the part that was wrongly collapsed | ||
| 455 | + // to `nearest_match` alone (see module doc / crate report). | ||
| 364 | let ref_mv_ctx = match nearest_match { | 456 | let ref_mv_ctx = match nearest_match { |
| 457 | + 0 => match ref_match_count { | ||
| 365 | 0 => 0, | 458 | 0 => 0, |
| 366 | - 1 => 3, | 459 | + 1 => 1, |
| 460 | + _ => 2, | ||
| 461 | + }, | ||
| 462 | + 1 => { | ||
| 463 | + if ref_match_count >= 2 { | ||
| 464 | + 4 | ||
| 465 | + } else { | ||
| 466 | + 3 | ||
| 467 | + } | ||
| 468 | + } | ||
| 367 | _ => 5, | 469 | _ => 5, |
| 368 | }; | 470 | }; |
| 369 | // GLOBALMV_OFFSET is only ever set by temporal MV projection | 471 | // GLOBALMV_OFFSET is only ever set by temporal MV projection |
| @@ -371,13 +473,13 @@ pub fn find_mv_stack( | |||
| 371 | // (see module doc) — exact, not a stand-in. | 473 | // (see module doc) — exact, not a stand-in. |
| 372 | let zero_mv_ctx = 0; | 474 | let zero_mv_ctx = 0; |
| 373 | 475 | ||
| 374 | - // av1_drl_ctx (mvref_common.h): every candidate here is one of libaom's | 476 | + // av1_drl_ctx (mvref_common.h): weight was boosted in place above for |
| 375 | - // "nearest" ones (see module doc), so each gets `REF_CAT_LEVEL` before | 477 | + // the nearest entries only, so this now compares the real stored weight |
| 376 | - // the comparison, which is why this always lands on 0. | 478 | + // against the threshold directly, the way libaom does. |
| 377 | let drl_ctx = candidates | 479 | let drl_ctx = candidates |
| 378 | .windows(2) | 480 | .windows(2) |
| 379 | .map(|w| { | 481 | .map(|w| { |
| 380 | - let (a, b) = (w[0].weight + REF_CAT_LEVEL, w[1].weight + REF_CAT_LEVEL); | 482 | + let (a, b) = (w[0].weight, w[1].weight); |
| 381 | if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL { | 483 | if a >= REF_CAT_LEVEL && b >= REF_CAT_LEVEL { |
| 382 | 0 | 484 | 0 |
| 383 | } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL { | 485 | } else if a >= REF_CAT_LEVEL && b < REF_CAT_LEVEL { |
| @@ -443,8 +545,10 @@ mod tests { | |||
| 443 | 545 | ||
| 444 | assert_eq!(stack.entries.len(), 1); | 546 | assert_eq!(stack.entries.len(), 1); |
| 445 | assert_eq!(stack.entries[0].mv, mv); | 547 | assert_eq!(stack.entries[0].mv, mv); |
| 446 | - // 2 above cells + 2 left cells + 1 top-right, each weight 2. | 548 | + // 2 above cells + 2 left cells + 1 top-right, each weight 2, plus the |
| 447 | - assert_eq!(stack.entries[0].weight, 10); | 549 | + // REF_CAT_LEVEL boost av1_find_mv_stack applies to every entry the |
| 550 | + // immediate row/col/top-right scan found (module doc). | ||
| 551 | + assert_eq!(stack.entries[0].weight, 10 + REF_CAT_LEVEL); | ||
| 448 | assert_eq!(stack.nearest_mv, mv); | 552 | assert_eq!(stack.nearest_mv, mv); |
| 449 | // Exact ctx (see module doc): both sides matched (nearest_match=2) | 553 | // Exact ctx (see module doc): both sides matched (nearest_match=2) |
| 450 | // and no neighbour was coded NEWMV, which is libaom's | 554 | // and no neighbour was coded NEWMV, which is libaom's |
| @@ -469,19 +573,22 @@ mod tests { | |||
| 469 | 573 | ||
| 470 | let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1, 8, 8); | 574 | let stack = find_mv_stack(&grid, 3, 3, 2, 3, 1, 8, 8); |
| 471 | 575 | ||
| 576 | + // Both are entries the immediate scan found, so both get the | ||
| 577 | + // REF_CAT_LEVEL boost (module doc) — their relative order is | ||
| 578 | + // unaffected. | ||
| 472 | assert_eq!(stack.entries.len(), 2); | 579 | assert_eq!(stack.entries.len(), 2); |
| 473 | assert_eq!( | 580 | assert_eq!( |
| 474 | stack.entries[0], | 581 | stack.entries[0], |
| 475 | StackEntry { | 582 | StackEntry { |
| 476 | mv: left_mv, | 583 | mv: left_mv, |
| 477 | - weight: 6 | 584 | + weight: 6 + REF_CAT_LEVEL |
| 478 | } | 585 | } |
| 479 | ); | 586 | ); |
| 480 | assert_eq!( | 587 | assert_eq!( |
| 481 | stack.entries[1], | 588 | stack.entries[1], |
| 482 | StackEntry { | 589 | StackEntry { |
| 483 | mv: above_mv, | 590 | mv: above_mv, |
| 484 | - weight: 4 | 591 | + weight: 4 + REF_CAT_LEVEL |
| 485 | } | 592 | } |
| 486 | ); | 593 | ); |
| 487 | assert_eq!(stack.nearest_mv, left_mv); | 594 | assert_eq!(stack.nearest_mv, left_mv); |
| @@ -573,6 +680,32 @@ mod tests { | |||
| 573 | assert_eq!(stack.ref_mv_ctx, 3); | 680 | assert_eq!(stack.ref_mv_ctx, 3); |
| 574 | } | 681 | } |
| 575 | 682 | ||
| 683 | + #[test] | ||
| 684 | + fn a_diagonal_corner_match_raises_ref_mv_ctx_past_nearest_match() { | ||
| 685 | + // Block at (2, 2), 1x1 mi unit: only the col to the left matches | ||
| 686 | + // (nearest_match == 1, so a pre-fix `ref_mv_ctx` collapse would say | ||
| 687 | + // 3 regardless of anything else — this is the exact round-10 defect | ||
| 688 | + // shape). The row above has no match of its own, but the diagonal | ||
| 689 | + // top-left corner (1, 1) does; libaom folds that into the row side | ||
| 690 | + // of `ref_match_count` (raising it to 2) without ever touching the | ||
| 691 | + // already-captured `nearest_match`. | ||
| 692 | + let mut grid = MiGrid::new(8, 8); | ||
| 693 | + grid.set(2, 1, inter((4, 4))); | ||
| 694 | + grid.set(1, 1, inter((8, 8))); | ||
| 695 | + | ||
| 696 | + let stack = find_mv_stack(&grid, 2, 2, 1, 1, 1, 8, 8); | ||
| 697 | + | ||
| 698 | + assert_eq!(stack.new_mv_ctx, 3); // depends on nearest_match alone: unchanged | ||
| 699 | + assert_eq!(stack.ref_mv_ctx, 4); // nearest_match=1, ref_match_count=2 | ||
| 700 | + // The corner's distinct MV becomes its own low-weight stack entry, | ||
| 701 | + // ranked behind the boosted nearest one — DRL context sees a real | ||
| 702 | + // (non-nearest) second candidate for the first time. | ||
| 703 | + assert_eq!(stack.entries.len(), 2); | ||
| 704 | + assert_eq!(stack.entries[0].mv, (4, 4)); | ||
| 705 | + assert_eq!(stack.entries[1].mv, (8, 8)); | ||
| 706 | + assert_eq!(stack.drl_ctx, vec![1]); | ||
| 707 | + } | ||
| 708 | + | ||
| 576 | #[test] | 709 | #[test] |
| 577 | fn single_ref_ctx_matches_libaoms_collapsed_forward_only_case() { | 710 | fn single_ref_ctx_matches_libaoms_collapsed_forward_only_case() { |
| 578 | assert_eq!(single_ref_ctx(false), 1); | 711 | assert_eq!(single_ref_ctx(false), 1); |