Seven intra modes, picked per block by rate-distortion
Browse files at this commit4331d177bfa8a60efe23bcf2dd6d94d3e27cf818Parent: 6a2f7f2- feat
- seven intra modes, picked per block by rate-distortion
4 changed files +691 -77
- crates/ec-av1/src/encode.rs +416 -77
- crates/ec-av1/src/intra.rs +176 -0
- crates/ec-av1/src/lib.rs +1 -0
- lanes/av1-predict-r1.report.md +98 -0
crates/ec-av1/src/encode.rsmodified+416 -77
| @@ -1,11 +1,13 @@ | |||
| 1 | //! A key-frame picture encoder: a planar 4:2:0 picture in, an AV1 stream out. | 1 | //! A key-frame picture encoder: a planar 4:2:0 picture in, an AV1 stream out. |
| 2 | //! | 2 | //! |
| 3 | -//! This is the layer that turns the pieces below it — DC intra prediction, the | 3 | +//! This is the layer that turns the pieces below it — the intra predictors of |
| 4 | -//! forward transform and quantizer of [`crate::transform`], and the tile writer | 4 | +//! [`crate::intra`], the forward transform and quantizer of |
| 5 | -//! of [`crate::tile`] — into something that takes a picture. Every block is | 5 | +//! [`crate::transform`], and the tile writer of [`crate::tile`] — into |
| 6 | -//! DC-predicted and 32x32 (its chroma 16x16), which is the subset the tile | 6 | +//! something that takes a picture. Every block is 32x32 (its chroma 16x16), |
| 7 | -//! writer codes; block sizes, transform types and mode decision are what a | 7 | +//! which is the subset the tile writer codes, and each one picks its luma mode |
| 8 | -//! rate-distortion loop above this would choose between. | 8 | +//! from the seven non-directional ones by rate-distortion; chroma is predicted |
| 9 | +//! DC, which is the mode the tile writer codes for it. Block sizes and | ||
| 10 | +//! transform types are what a loop above this would choose between. | ||
| 9 | //! | 11 | //! |
| 10 | //! The encoder carries its own reconstruction, because prediction reads it: a | 12 | //! The encoder carries its own reconstruction, because prediction reads it: a |
| 11 | //! block predicts from the reconstructed samples above and to its left, exactly | 13 | //! block predicts from the reconstructed samples above and to its left, exactly |
| @@ -20,7 +22,9 @@ use ec_av1_syntax::{ | |||
| 20 | use ec_core::{Error, Result}; | 22 | use ec_core::{Error, Result}; |
| 21 | 23 | ||
| 22 | use crate::frame::frame_obu; | 24 | use crate::frame::frame_obu; |
| 25 | +use crate::intra::{DC_PRED, NON_DIRECTIONAL}; | ||
| 23 | use crate::obu::temporal_delimiter; | 26 | use crate::obu::temporal_delimiter; |
| 27 | +use crate::quant::ac_q; | ||
| 24 | use crate::sequence::sequence_header_obu; | 28 | use crate::sequence::sequence_header_obu; |
| 25 | use crate::tile::{BlockCoeffs, Coeff, Superblock, sb_coeff_key_frame_tile}; | 29 | use crate::tile::{BlockCoeffs, Coeff, Superblock, sb_coeff_key_frame_tile}; |
| 26 | use crate::transform::{dequant_and_inverse, forward_and_quantize}; | 30 | use crate::transform::{dequant_and_inverse, forward_and_quantize}; |
| @@ -28,6 +32,17 @@ use crate::transform::{dequant_and_inverse, forward_and_quantize}; | |||
| 28 | /// The side of the luma blocks this encoder codes, in samples. | 32 | /// The side of the luma blocks this encoder codes, in samples. |
| 29 | const BLOCK: usize = 32; | 33 | const BLOCK: usize = 32; |
| 30 | 34 | ||
| 35 | +/// How heavily the mode search weighs rate against squared error, in units of | ||
| 36 | +/// the quantizer's reconstruction step squared per bit. | ||
| 37 | +/// | ||
| 38 | +/// Swept over three clips and two synthetic pictures at 0, 0.05, 0.1, 0.2, 0.4 | ||
| 39 | +/// and 0.8 (`probe_lambda`, and the table in the lane report): 0 leaves half the | ||
| 40 | +/// saving on the table on a picture that runs one way (-35.6% against -59.5% on | ||
| 41 | +/// stripes), and everything from 0.1 up gives a little back on screen capture | ||
| 42 | +/// (-10.7% against -11.5%) and on a hand-held clip. 0.05 is the best point on | ||
| 43 | +/// every clip measured. | ||
| 44 | +const LAMBDA_SCALE: f64 = 0.05; | ||
| 45 | + | ||
| 31 | /// One 8-bit planar 4:2:0 picture. | 46 | /// One 8-bit planar 4:2:0 picture. |
| 32 | #[derive(Clone, Debug, PartialEq, Eq)] | 47 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 33 | pub struct Picture { | 48 | pub struct Picture { |
| @@ -87,6 +102,9 @@ pub struct Encoded { | |||
| 87 | /// What a decoder will produce from `stream` — the encoder's own | 102 | /// What a decoder will produce from `stream` — the encoder's own |
| 88 | /// reconstruction, which its prediction was built on. | 103 | /// reconstruction, which its prediction was built on. |
| 89 | pub reconstruction: Picture, | 104 | pub reconstruction: Picture, |
| 105 | + /// The luma intra mode each block was coded under, in the order the blocks | ||
| 106 | + /// are coded — raster order among the quadrants of each superblock. | ||
| 107 | + pub modes: Vec<u8>, | ||
| 90 | } | 108 | } |
| 91 | 109 | ||
| 92 | /// The sequence and frame headers a picture of this size is coded under: one | 110 | /// The sequence and frame headers a picture of this size is coded under: one |
| @@ -204,27 +222,6 @@ fn too_large() -> Error { | |||
| 204 | ) | 222 | ) |
| 205 | } | 223 | } |
| 206 | 224 | ||
| 207 | -/// `dc_predict` (spec 7.11.2): the average of the reconstructed row above and | ||
| 208 | -/// the reconstructed column to the left, of whichever of them exists. | ||
| 209 | -fn dc_predict(above: Option<&[u8]>, left: Option<&[u8]>) -> u8 { | ||
| 210 | - match (above, left) { | ||
| 211 | - (None, None) => 128, | ||
| 212 | - (Some(a), None) => { | ||
| 213 | - let sum: u32 = a.iter().map(|&s| u32::from(s)).sum(); | ||
| 214 | - ((sum + (a.len() as u32 >> 1)) / a.len() as u32) as u8 | ||
| 215 | - } | ||
| 216 | - (None, Some(l)) => { | ||
| 217 | - let sum: u32 = l.iter().map(|&s| u32::from(s)).sum(); | ||
| 218 | - ((sum + (l.len() as u32 >> 1)) / l.len() as u32) as u8 | ||
| 219 | - } | ||
| 220 | - (Some(a), Some(l)) => { | ||
| 221 | - let sum: u32 = a.iter().chain(l).map(|&s| u32::from(s)).sum(); | ||
| 222 | - let count = (a.len() + l.len()) as u32; | ||
| 223 | - ((sum + (count >> 1)) / count) as u8 | ||
| 224 | - } | ||
| 225 | - } | ||
| 226 | -} | ||
| 227 | - | ||
| 228 | /// One plane of the picture being coded, and the reconstruction being built | 225 | /// One plane of the picture being coded, and the reconstruction being built |
| 229 | /// beside it. | 226 | /// beside it. |
| 230 | struct Plane<'a> { | 227 | struct Plane<'a> { |
| @@ -235,53 +232,167 @@ struct Plane<'a> { | |||
| 235 | } | 232 | } |
| 236 | 233 | ||
| 237 | impl Plane<'_> { | 234 | impl Plane<'_> { |
| 238 | - /// Codes one block: predicts it from the reconstruction, transforms and | 235 | + /// The reconstructed samples a block at `(x, y)` predicts from: the row |
| 239 | - /// quantizes what is left, writes the reconstruction back and hands the | 236 | + /// above it, the column to its left and the sample between them, each |
| 240 | - /// levels to the caller. | 237 | + /// missing where the block sits against an edge of the frame. |
| 241 | - fn code_block( | 238 | + fn edges( |
| 242 | - &mut self, | 239 | + &self, |
| 243 | x: usize, | 240 | x: usize, |
| 244 | y: usize, | 241 | y: usize, |
| 245 | side: usize, | 242 | side: usize, |
| 246 | - base_q_idx: u8, | 243 | + ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) { |
| 247 | - deadzone: f64, | 244 | + let above = |
| 248 | - ) -> Vec<Coeff> { | 245 | + (y > 0).then(|| self.reconstruction[(y - 1) * self.width + x..][..side].to_vec()); |
| 249 | - let above = (y > 0).then(|| &self.reconstruction[(y - 1) * self.width + x..][..side]); | ||
| 250 | let left = (x > 0).then(|| { | 246 | let left = (x > 0).then(|| { |
| 251 | (0..side) | 247 | (0..side) |
| 252 | .map(|i| self.reconstruction[(y + i) * self.width + x - 1]) | 248 | .map(|i| self.reconstruction[(y + i) * self.width + x - 1]) |
| 253 | .collect::<Vec<_>>() | 249 | .collect::<Vec<_>>() |
| 254 | }); | 250 | }); |
| 255 | - let prediction = i32::from(dc_predict(above, left.as_deref())); | 251 | + let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]); |
| 252 | + (above, left, corner) | ||
| 253 | + } | ||
| 254 | + | ||
| 255 | + /// Codes one block under one mode without committing it: hands back the | ||
| 256 | + /// levels, the block the decoder would reconstruct, the squared error | ||
| 257 | + /// against the source and an estimate of what the levels cost in bits. | ||
| 258 | + fn trial( | ||
| 259 | + &self, | ||
| 260 | + x: usize, | ||
| 261 | + y: usize, | ||
| 262 | + side: usize, | ||
| 263 | + mode: u8, | ||
| 264 | + base_q_idx: u8, | ||
| 265 | + deadzone: f64, | ||
| 266 | + ) -> Trial { | ||
| 267 | + let (above, left, corner) = self.edges(x, y, side); | ||
| 268 | + let mut prediction = vec![0u8; side * side]; | ||
| 269 | + crate::intra::predict( | ||
| 270 | + mode, | ||
| 271 | + above.as_deref(), | ||
| 272 | + left.as_deref(), | ||
| 273 | + corner, | ||
| 274 | + side, | ||
| 275 | + &mut prediction, | ||
| 276 | + ); | ||
| 256 | 277 | ||
| 257 | let mut residual = vec![0i32; side * side]; | 278 | let mut residual = vec![0i32; side * side]; |
| 258 | for row in 0..side { | 279 | for row in 0..side { |
| 259 | for col in 0..side { | 280 | for col in 0..side { |
| 260 | residual[row * side + col] = | 281 | residual[row * side + col] = |
| 261 | - i32::from(self.source[(y + row) * self.width + x + col]) - prediction; | 282 | + i32::from(self.source[(y + row) * self.width + x + col]) |
| 283 | + - i32::from(prediction[row * side + col]); | ||
| 262 | } | 284 | } |
| 263 | } | 285 | } |
| 264 | let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone); | 286 | let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone); |
| 265 | let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); | 287 | let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); |
| 288 | + | ||
| 289 | + let mut reconstruction = vec![0u8; side * side]; | ||
| 290 | + let mut sse = 0.0; | ||
| 266 | for row in 0..side { | 291 | for row in 0..side { |
| 267 | for col in 0..side { | 292 | for col in 0..side { |
| 268 | - self.reconstruction[(y + row) * self.width + x + col] = | 293 | + let i = row * side + col; |
| 269 | - (prediction + coded[row * side + col]).clamp(0, 255) as u8; | 294 | + let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; |
| 295 | + reconstruction[i] = sample; | ||
| 296 | + let error = f64::from( | ||
| 297 | + i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), | ||
| 298 | + ); | ||
| 299 | + sse += error * error; | ||
| 270 | } | 300 | } |
| 271 | } | 301 | } |
| 272 | - levels | 302 | + // What a level costs is close enough to its magnitude's width plus a |
| 303 | + // sign and a run, which is all the search needs to rank modes. | ||
| 304 | + let bits: f64 = levels | ||
| 273 | .iter() | 305 | .iter() |
| 274 | - .enumerate() | 306 | + .filter(|&&level| level != 0) |
| 275 | - .filter(|&(_, &level)| level != 0) | 307 | + .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 276 | - .map(|(i, &level)| Coeff { | 308 | + .sum(); |
| 277 | - row: (i / side) as u8, | 309 | + Trial { |
| 278 | - col: (i % side) as u8, | 310 | + levels, |
| 279 | - level, | 311 | + reconstruction, |
| 280 | - }) | 312 | + sse, |
| 281 | - .collect() | 313 | + bits, |
| 314 | + } | ||
| 315 | + } | ||
| 316 | + | ||
| 317 | + /// Writes a trial's reconstruction back into the plane. | ||
| 318 | + fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { | ||
| 319 | + for row in 0..side { | ||
| 320 | + self.reconstruction[(y + row) * self.width + x..][..side] | ||
| 321 | + .copy_from_slice(&trial.reconstruction[row * side..][..side]); | ||
| 322 | + } | ||
| 323 | + } | ||
| 324 | + | ||
| 325 | + /// Codes one block under a fixed mode, committing it. | ||
| 326 | + fn code_block( | ||
| 327 | + &mut self, | ||
| 328 | + x: usize, | ||
| 329 | + y: usize, | ||
| 330 | + side: usize, | ||
| 331 | + mode: u8, | ||
| 332 | + base_q_idx: u8, | ||
| 333 | + deadzone: f64, | ||
| 334 | + ) -> Vec<Coeff> { | ||
| 335 | + let trial = self.trial(x, y, side, mode, base_q_idx, deadzone); | ||
| 336 | + self.commit(x, y, side, &trial); | ||
| 337 | + coeffs(&trial.levels, side) | ||
| 338 | + } | ||
| 339 | + | ||
| 340 | + /// Codes one block under every mode the search offers and commits the one | ||
| 341 | + /// whose squared error and estimated rate come out cheapest. | ||
| 342 | + fn search_block( | ||
| 343 | + &mut self, | ||
| 344 | + x: usize, | ||
| 345 | + y: usize, | ||
| 346 | + side: usize, | ||
| 347 | + search: &Search, | ||
| 348 | + ) -> (Vec<Coeff>, u8) { | ||
| 349 | + let mut best: Option<(f64, u8, Trial)> = None; | ||
| 350 | + for &mode in search.modes { | ||
| 351 | + let trial = self.trial(x, y, side, mode, search.base_q_idx, search.deadzone); | ||
| 352 | + let cost = trial.sse + search.lambda * trial.bits; | ||
| 353 | + if best | ||
| 354 | + .as_ref() | ||
| 355 | + .is_none_or(|(best_cost, _, _)| cost < *best_cost) | ||
| 356 | + { | ||
| 357 | + best = Some((cost, mode, trial)); | ||
| 358 | + } | ||
| 359 | + } | ||
| 360 | + let (_, mode, trial) = best.expect("the search offers at least one mode"); | ||
| 361 | + self.commit(x, y, side, &trial); | ||
| 362 | + (coeffs(&trial.levels, side), mode) | ||
| 282 | } | 363 | } |
| 283 | } | 364 | } |
| 284 | 365 | ||
| 366 | +/// What the luma mode search picks between, and under what terms. | ||
| 367 | +struct Search<'a> { | ||
| 368 | + base_q_idx: u8, | ||
| 369 | + deadzone: f64, | ||
| 370 | + lambda: f64, | ||
| 371 | + modes: &'a [u8], | ||
| 372 | +} | ||
| 373 | + | ||
| 374 | +/// One mode's coding of one block, before it is committed. | ||
| 375 | +struct Trial { | ||
| 376 | + levels: Vec<i32>, | ||
| 377 | + reconstruction: Vec<u8>, | ||
| 378 | + sse: f64, | ||
| 379 | + bits: f64, | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +/// The non-zero levels of a block, as the tile writer takes them. | ||
| 383 | +fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> { | ||
| 384 | + levels | ||
| 385 | + .iter() | ||
| 386 | + .enumerate() | ||
| 387 | + .filter(|&(_, &level)| level != 0) | ||
| 388 | + .map(|(i, &level)| Coeff { | ||
| 389 | + row: (i / side) as u8, | ||
| 390 | + col: (i % side) as u8, | ||
| 391 | + level, | ||
| 392 | + }) | ||
| 393 | + .collect() | ||
| 394 | +} | ||
| 395 | + | ||
| 285 | /// Encodes one picture as a key frame. | 396 | /// Encodes one picture as a key frame. |
| 286 | /// | 397 | /// |
| 287 | /// `base_q_idx` is the frame's quantizer index, and has to sit in the band | 398 | /// `base_q_idx` is the frame's quantizer index, and has to sit in the band |
| @@ -294,7 +405,38 @@ impl Plane<'_> { | |||
| 294 | /// when its planes are not 4:2:0 of that size, or when the tile writer refuses | 405 | /// when its planes are not 4:2:0 of that size, or when the tile writer refuses |
| 295 | /// the quantizer index. | 406 | /// the quantizer index. |
| 296 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { | 407 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { |
| 408 | + encode_key_frame_with_modes(picture, base_q_idx, deadzone, &NON_DIRECTIONAL) | ||
| 409 | +} | ||
| 410 | + | ||
| 411 | +/// Encodes one picture as a key frame, choosing each block's luma mode from | ||
| 412 | +/// `modes` alone. | ||
| 413 | +/// | ||
| 414 | +/// This is what an ablation measures against: `&[DC_PRED]` is the encoder | ||
| 415 | +/// before the mode search, and [`NON_DIRECTIONAL`] is what | ||
| 416 | +/// [`encode_key_frame`] uses. | ||
| 417 | +/// | ||
| 418 | +/// # Errors | ||
| 419 | +/// The same as [`encode_key_frame`], and additionally when `modes` is empty or | ||
| 420 | +/// names a mode [`crate::intra::predict`] does not predict. | ||
| 421 | +pub fn encode_key_frame_with_modes( | ||
| 422 | + picture: &Picture, | ||
| 423 | + base_q_idx: u8, | ||
| 424 | + deadzone: f64, | ||
| 425 | + modes: &[u8], | ||
| 426 | +) -> Result<Encoded> { | ||
| 297 | picture.check()?; | 427 | picture.check()?; |
| 428 | + if modes.is_empty() { | ||
| 429 | + return Err(Error::unsupported( | ||
| 430 | + "AV1 encode", | ||
| 431 | + "a mode search needs at least one mode to choose from", | ||
| 432 | + )); | ||
| 433 | + } | ||
| 434 | + if let Some(bad) = modes.iter().find(|m| !NON_DIRECTIONAL.contains(m)) { | ||
| 435 | + return Err(Error::unsupported( | ||
| 436 | + "AV1 encode", | ||
| 437 | + format!("intra mode {bad} is not one the encoder predicts"), | ||
| 438 | + )); | ||
| 439 | + } | ||
| 298 | let (seq, header) = key_frame_headers(picture.width, picture.height, base_q_idx)?; | 440 | let (seq, header) = key_frame_headers(picture.width, picture.height, base_q_idx)?; |
| 299 | 441 | ||
| 300 | let mut luma = Plane { | 442 | let mut luma = Plane { |
| @@ -318,9 +460,20 @@ pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Res | |||
| 318 | }, | 460 | }, |
| 319 | ]; | 461 | ]; |
| 320 | 462 | ||
| 463 | + // The search trades a bit for the squared error it saves, in the units the | ||
| 464 | + // reconstruction is measured in: one step of the quantizer, squared. | ||
| 465 | + let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; | ||
| 466 | + let search = Search { | ||
| 467 | + base_q_idx, | ||
| 468 | + deadzone, | ||
| 469 | + lambda: LAMBDA_SCALE * step * step, | ||
| 470 | + modes, | ||
| 471 | + }; | ||
| 472 | + | ||
| 321 | let (cols, rows) = (picture.width / BLOCK, picture.height / BLOCK); | 473 | let (cols, rows) = (picture.width / BLOCK, picture.height / BLOCK); |
| 322 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); | 474 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 323 | let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); | 475 | let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); |
| 476 | + let mut modes = Vec::with_capacity(cols * rows); | ||
| 324 | for sb_row in 0..sb_rows { | 477 | for sb_row in 0..sb_rows { |
| 325 | for sb_col in 0..sb_cols { | 478 | for sb_col in 0..sb_cols { |
| 326 | // The quadrants of a superblock are coded in the order the decoder | 479 | // The quadrants of a superblock are coded in the order the decoder |
| @@ -333,11 +486,15 @@ pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Res | |||
| 333 | continue; | 486 | continue; |
| 334 | } | 487 | } |
| 335 | let (x, y) = (col * BLOCK, row * BLOCK); | 488 | let (x, y) = (col * BLOCK, row * BLOCK); |
| 489 | + let (luma_coeffs, mode) = luma.search_block(x, y, BLOCK, &search); | ||
| 490 | + modes.push(mode); | ||
| 336 | blocks.push(BlockCoeffs { | 491 | blocks.push(BlockCoeffs { |
| 337 | - luma: luma.code_block(x, y, BLOCK, base_q_idx, deadzone), | 492 | + // Chroma is predicted DC because that is the mode the tile |
| 338 | - u: chroma[0].code_block(x / 2, y / 2, BLOCK / 2, base_q_idx, deadzone), | 493 | + // writer codes for it. |
| 339 | - v: chroma[1].code_block(x / 2, y / 2, BLOCK / 2, base_q_idx, deadzone), | 494 | + u: chroma[0].code_block(x / 2, y / 2, BLOCK / 2, DC_PRED, base_q_idx, deadzone), |
| 340 | - mode: 0, | 495 | + v: chroma[1].code_block(x / 2, y / 2, BLOCK / 2, DC_PRED, base_q_idx, deadzone), |
| 496 | + luma: luma_coeffs, | ||
| 497 | + mode, | ||
| 341 | }); | 498 | }); |
| 342 | } | 499 | } |
| 343 | superblocks.push(Superblock::Split(blocks)); | 500 | superblocks.push(Superblock::Split(blocks)); |
| @@ -352,6 +509,7 @@ pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Res | |||
| 352 | let [u, v] = chroma; | 509 | let [u, v] = chroma; |
| 353 | Ok(Encoded { | 510 | Ok(Encoded { |
| 354 | stream, | 511 | stream, |
| 512 | + modes, | ||
| 355 | reconstruction: Picture { | 513 | reconstruction: Picture { |
| 356 | width: luma.width, | 514 | width: luma.width, |
| 357 | height: luma.height, | 515 | height: luma.height, |
| @@ -365,6 +523,7 @@ pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Res | |||
| 365 | #[cfg(test)] | 523 | #[cfg(test)] |
| 366 | mod tests { | 524 | mod tests { |
| 367 | use super::*; | 525 | use super::*; |
| 526 | + use crate::intra::{H_PRED, V_PRED}; | ||
| 368 | use std::io::Write; | 527 | use std::io::Write; |
| 369 | use std::process::{Command, Stdio}; | 528 | use std::process::{Command, Stdio}; |
| 370 | 529 | ||
| @@ -485,6 +644,209 @@ mod tests { | |||
| 485 | } | 644 | } |
| 486 | } | 645 | } |
| 487 | 646 | ||
| 647 | + /// One frame of a real clip, scaled to a whole number of 32x32 blocks. | ||
| 648 | + fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { | ||
| 649 | + let out = Command::new("ffmpeg") | ||
| 650 | + .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"]) | ||
| 651 | + .args(["-vf", &format!("scale={width}:{height}")]) | ||
| 652 | + .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | ||
| 653 | + .output() | ||
| 654 | + .expect("ffmpeg failed to run"); | ||
| 655 | + assert!( | ||
| 656 | + out.status.success(), | ||
| 657 | + "ffmpeg: {}", | ||
| 658 | + String::from_utf8_lossy(&out.stderr) | ||
| 659 | + ); | ||
| 660 | + let (luma, chroma) = (width * height, width * height / 4); | ||
| 661 | + assert_eq!( | ||
| 662 | + out.stdout.len(), | ||
| 663 | + luma + 2 * chroma, | ||
| 664 | + "expected one 4:2:0 frame" | ||
| 665 | + ); | ||
| 666 | + Picture { | ||
| 667 | + width, | ||
| 668 | + height, | ||
| 669 | + y: out.stdout[..luma].to_vec(), | ||
| 670 | + u: out.stdout[luma..luma + chroma].to_vec(), | ||
| 671 | + v: out.stdout[luma + chroma..].to_vec(), | ||
| 672 | + } | ||
| 673 | + } | ||
| 674 | + | ||
| 675 | + /// Prints what the mode search saves over DC prediction alone, for the | ||
| 676 | + /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the | ||
| 677 | + /// weight the search puts on rate can be swept. | ||
| 678 | + #[test] | ||
| 679 | + #[ignore = "a sweep, not a gate"] | ||
| 680 | + fn probe_lambda() { | ||
| 681 | + let mut pictures = vec![ | ||
| 682 | + ("test card".to_string(), test_card(160, 96)), | ||
| 683 | + ("stripes".to_string(), stripes(160, 96, true)), | ||
| 684 | + ]; | ||
| 685 | + if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { | ||
| 686 | + for entry in clips.split(':').filter(|e| !e.is_empty()) { | ||
| 687 | + let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); | ||
| 688 | + let name = path.rsplit('/').next().unwrap_or(path).to_string(); | ||
| 689 | + pictures.push((name, clip_frame(path, skip, 640, 352))); | ||
| 690 | + } | ||
| 691 | + } | ||
| 692 | + for (name, picture) in pictures { | ||
| 693 | + let dc = ladder(&picture, &[DC_PRED]); | ||
| 694 | + let searched = ladder(&picture, &NON_DIRECTIONAL); | ||
| 695 | + println!( | ||
| 696 | + "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point", | ||
| 697 | + bd_rate(&dc, &searched) * 100.0, | ||
| 698 | + 10f64.powf(searched[1].1), | ||
| 699 | + searched[1].0, | ||
| 700 | + 10f64.powf(dc[1].1), | ||
| 701 | + dc[1].0, | ||
| 702 | + ); | ||
| 703 | + } | ||
| 704 | + } | ||
| 705 | + | ||
| 706 | + /// A striped picture, running one way or the other. The stripes are what | ||
| 707 | + /// separates a vertical predictor from a horizontal one: a mode search | ||
| 708 | + /// reading a transposed edge would pick the wrong one of the pair, which no | ||
| 709 | + /// symmetric picture would show. | ||
| 710 | + fn stripes(width: usize, height: usize, vertical: bool) -> Picture { | ||
| 711 | + let mut picture = Picture::grey(width, height); | ||
| 712 | + for y in 0..height { | ||
| 713 | + for x in 0..width { | ||
| 714 | + let along = if vertical { x } else { y }; | ||
| 715 | + picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 }; | ||
| 716 | + } | ||
| 717 | + } | ||
| 718 | + picture | ||
| 719 | + } | ||
| 720 | + | ||
| 721 | + /// Every mode the encoder offers has to predict what the decoder predicts, | ||
| 722 | + /// not just the ones a particular picture happens to choose: each is forced | ||
| 723 | + /// over a whole picture and the reconstruction gated against ffmpeg. | ||
| 724 | + #[test] | ||
| 725 | + fn every_mode_decodes_to_what_the_encoder_predicted() { | ||
| 726 | + if !have_ffmpeg() { | ||
| 727 | + eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg"); | ||
| 728 | + return; | ||
| 729 | + } | ||
| 730 | + let picture = test_card(128, 96); | ||
| 731 | + for mode in NON_DIRECTIONAL { | ||
| 732 | + let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap(); | ||
| 733 | + let decoded = ffmpeg_decode(&encoded.stream, 128, 96); | ||
| 734 | + assert_eq!(decoded.y, encoded.reconstruction.y, "mode {mode}: luma"); | ||
| 735 | + assert_eq!(decoded.u, encoded.reconstruction.u, "mode {mode}: U"); | ||
| 736 | + assert_eq!(decoded.v, encoded.reconstruction.v, "mode {mode}: V"); | ||
| 737 | + assert!( | ||
| 738 | + encoded.modes.iter().all(|&m| m == mode), | ||
| 739 | + "mode {mode}: the encoder coded something else" | ||
| 740 | + ); | ||
| 741 | + } | ||
| 742 | + } | ||
| 743 | + | ||
| 744 | + /// The search has to follow the picture: vertical stripes are cheapest | ||
| 745 | + /// predicted from the row above, horizontal ones from the column to the | ||
| 746 | + /// left. Reading the edges the other way round would swap the two answers | ||
| 747 | + /// while leaving every fidelity gate intact. | ||
| 748 | + #[test] | ||
| 749 | + fn the_search_picks_the_direction_the_picture_runs() { | ||
| 750 | + for (vertical, want) in [(true, V_PRED), (false, H_PRED)] { | ||
| 751 | + let picture = stripes(128, 96, vertical); | ||
| 752 | + let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); | ||
| 753 | + // The first block of the picture has neither neighbour, so it | ||
| 754 | + // cannot tell the modes apart; every other one can. | ||
| 755 | + let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count(); | ||
| 756 | + assert!( | ||
| 757 | + picked * 2 > encoded.modes.len() - 1, | ||
| 758 | + "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}", | ||
| 759 | + encoded.modes.len() - 1, | ||
| 760 | + encoded.modes | ||
| 761 | + ); | ||
| 762 | + } | ||
| 763 | + } | ||
| 764 | + | ||
| 765 | + /// What the search is for: the same picture, at the same quantizer, coded | ||
| 766 | + /// smaller and more faithfully than DC alone can manage. | ||
| 767 | + /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid | ||
| 768 | + /// between the two rate-distortion curves in log-rate against PSNR, as a | ||
| 769 | + /// fraction of the reference's rate. Negative means the second curve costs | ||
| 770 | + /// less for the same picture. | ||
| 771 | + fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 { | ||
| 772 | + let low = reference[0].0.max(other[0].0); | ||
| 773 | + let high = reference[reference.len() - 1] | ||
| 774 | + .0 | ||
| 775 | + .min(other[other.len() - 1].0); | ||
| 776 | + assert!(high > low, "the two ladders have to overlap in PSNR"); | ||
| 777 | + let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { | ||
| 778 | + let i = curve | ||
| 779 | + .windows(2) | ||
| 780 | + .position(|w| psnr >= w[0].0 && psnr <= w[1].0) | ||
| 781 | + .unwrap_or(0); | ||
| 782 | + let (x0, y0) = curve[i]; | ||
| 783 | + let (x1, y1) = curve[i + 1]; | ||
| 784 | + y0 + (y1 - y0) * (psnr - x0) / (x1 - x0) | ||
| 785 | + }; | ||
| 786 | + let steps = 64; | ||
| 787 | + let mut area = 0.0; | ||
| 788 | + for step in 0..steps { | ||
| 789 | + let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps); | ||
| 790 | + area += log_rate_at(other, psnr) - log_rate_at(reference, psnr); | ||
| 791 | + } | ||
| 792 | + 10f64.powf(area / f64::from(steps)) - 1.0 | ||
| 793 | + } | ||
| 794 | + | ||
| 795 | + /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by | ||
| 796 | + /// fidelity. | ||
| 797 | + fn ladder(picture: &Picture, modes: &[u8]) -> Vec<(f64, f64)> { | ||
| 798 | + let mut points: Vec<(f64, f64)> = [110u8, 90, 70] | ||
| 799 | + .iter() | ||
| 800 | + .map(|&q| { | ||
| 801 | + let encoded = encode_key_frame_with_modes(picture, q, 0.5, modes).unwrap(); | ||
| 802 | + ( | ||
| 803 | + psnr(&encoded.reconstruction.y, picture.y.as_slice()), | ||
| 804 | + (encoded.stream.len() as f64).log10(), | ||
| 805 | + ) | ||
| 806 | + }) | ||
| 807 | + .collect(); | ||
| 808 | + points.sort_by(|a, b| a.0.total_cmp(&b.0)); | ||
| 809 | + points | ||
| 810 | + } | ||
| 811 | + | ||
| 812 | + /// What the search is for: the same pictures cost less to code at the same | ||
| 813 | + /// fidelity than DC prediction alone can manage. A picture that runs one | ||
| 814 | + /// way saves far more than a busy one, which is the shape a working | ||
| 815 | + /// directional pair has. | ||
| 816 | + #[test] | ||
| 817 | + fn the_search_beats_dc_alone() { | ||
| 818 | + for (name, picture, want) in [ | ||
| 819 | + ("test card", test_card(160, 96), -0.05), | ||
| 820 | + ("stripes", stripes(160, 96, true), -0.40), | ||
| 821 | + ] { | ||
| 822 | + let saved = bd_rate( | ||
| 823 | + &ladder(&picture, &[DC_PRED]), | ||
| 824 | + &ladder(&picture, &NON_DIRECTIONAL), | ||
| 825 | + ); | ||
| 826 | + assert!( | ||
| 827 | + saved < want, | ||
| 828 | + "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%", | ||
| 829 | + saved * 100.0, | ||
| 830 | + -want * 100.0 | ||
| 831 | + ); | ||
| 832 | + } | ||
| 833 | + } | ||
| 834 | + | ||
| 835 | + /// A mode the encoder cannot predict must be refused rather than coded as | ||
| 836 | + /// something else, and a search with nothing to choose from likewise. | ||
| 837 | + #[test] | ||
| 838 | + fn a_mode_the_encoder_cannot_predict_is_refused() { | ||
| 839 | + let picture = test_card(64, 64); | ||
| 840 | + let message = encode_key_frame_with_modes(&picture, 100, 0.5, &[3]) | ||
| 841 | + .unwrap_err() | ||
| 842 | + .to_string(); | ||
| 843 | + assert!( | ||
| 844 | + message.contains("intra mode 3"), | ||
| 845 | + "the refusal must name the mode, got {message}" | ||
| 846 | + ); | ||
| 847 | + assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[]).is_err()); | ||
| 848 | + } | ||
| 849 | + | ||
| 488 | /// The picture that comes back is the picture that went in, to within the | 850 | /// The picture that comes back is the picture that went in, to within the |
| 489 | /// quantizer. A prediction that read the wrong neighbours, or a block | 851 | /// quantizer. A prediction that read the wrong neighbours, or a block |
| 490 | /// written into the wrong place, would still decode to what the encoder | 852 | /// written into the wrong place, would still decode to what the encoder |
| @@ -602,30 +964,7 @@ mod tests { | |||
| 602 | // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the | 964 | // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the |
| 603 | // test quick while still spanning many superblocks. | 965 | // test quick while still spanning many superblocks. |
| 604 | let (width, height) = (640usize, 352usize); | 966 | let (width, height) = (640usize, 352usize); |
| 605 | - let out = Command::new("ffmpeg") | 967 | + let picture = clip_frame(&clip, &skip, width, height); |
| 606 | - .args(["-v", "error", "-ss", &skip, "-i", &clip, "-frames:v", "1"]) | ||
| 607 | - .args(["-vf", &format!("scale={width}:{height}")]) | ||
| 608 | - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) | ||
| 609 | - .output() | ||
| 610 | - .expect("ffmpeg failed to run"); | ||
| 611 | - assert!( | ||
| 612 | - out.status.success(), | ||
| 613 | - "ffmpeg: {}", | ||
| 614 | - String::from_utf8_lossy(&out.stderr) | ||
| 615 | - ); | ||
| 616 | - let (luma, chroma) = (width * height, width * height / 4); | ||
| 617 | - assert_eq!( | ||
| 618 | - out.stdout.len(), | ||
| 619 | - luma + 2 * chroma, | ||
| 620 | - "expected one 4:2:0 frame" | ||
| 621 | - ); | ||
| 622 | - let picture = Picture { | ||
| 623 | - width, | ||
| 624 | - height, | ||
| 625 | - y: out.stdout[..luma].to_vec(), | ||
| 626 | - u: out.stdout[luma..luma + chroma].to_vec(), | ||
| 627 | - v: out.stdout[luma + chroma..].to_vec(), | ||
| 628 | - }; | ||
| 629 | 968 | ||
| 630 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); | 969 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 631 | let decoded = ffmpeg_decode(&encoded.stream, width, height); | 970 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
crates/ec-av1/src/intra.rsadded+176 -0
| @@ -0,0 +1,176 @@ | |||
| 1 | +//! Intra prediction, the half of spec 7.11.2 a key frame needs. | ||
| 2 | +//! | ||
| 3 | +//! The seven modes here are the ones that read no further than the row above | ||
| 4 | +//! and the column to the left of the block: the eight directional modes reach | ||
| 5 | +//! past a block's own width into samples whose availability the decoder tracks | ||
| 6 | +//! in its own bookkeeping, and are not written yet. | ||
| 7 | + | ||
| 8 | +/// The average of the neighbours (spec 7.11.2.5). | ||
| 9 | +pub const DC_PRED: u8 = 0; | ||
| 10 | +/// The row above, repeated down the block. | ||
| 11 | +pub const V_PRED: u8 = 1; | ||
| 12 | +/// The column to the left, repeated across the block. | ||
| 13 | +pub const H_PRED: u8 = 2; | ||
| 14 | +/// The two smooth predictions crossed (spec 7.11.2.6). | ||
| 15 | +pub const SMOOTH_PRED: u8 = 9; | ||
| 16 | +/// Smooth down from the row above to the bottom-left sample. | ||
| 17 | +pub const SMOOTH_V_PRED: u8 = 10; | ||
| 18 | +/// Smooth across from the column left to the top-right sample. | ||
| 19 | +pub const SMOOTH_H_PRED: u8 = 11; | ||
| 20 | +/// Whichever of above, left and the corner is nearest their gradient. | ||
| 21 | +pub const PAETH_PRED: u8 = 12; | ||
| 22 | + | ||
| 23 | +/// The modes this module predicts, in the order a search should try them. | ||
| 24 | +pub const NON_DIRECTIONAL: [u8; 7] = [ | ||
| 25 | + DC_PRED, | ||
| 26 | + V_PRED, | ||
| 27 | + H_PRED, | ||
| 28 | + SMOOTH_PRED, | ||
| 29 | + SMOOTH_V_PRED, | ||
| 30 | + SMOOTH_H_PRED, | ||
| 31 | + PAETH_PRED, | ||
| 32 | +]; | ||
| 33 | + | ||
| 34 | +/// `Sm_Weights` (spec 9.3), the blocks of the table for sides 4 to 64 laid end | ||
| 35 | +/// to end so that the weights for a side start at that side's own index. | ||
| 36 | +const SM_WEIGHTS: [u16; 128] = [ | ||
| 37 | + 0, 0, // unused: a side is at least 2 | ||
| 38 | + 255, 128, // 2 | ||
| 39 | + 255, 149, 85, 64, // 4 | ||
| 40 | + 255, 197, 146, 105, 73, 50, 37, 32, // 8 | ||
| 41 | + 255, 225, 196, 170, 145, 123, 102, 84, 68, 54, 43, 33, 26, 20, 17, 16, // 16 | ||
| 42 | + 255, 240, 225, 210, 196, 182, 169, 157, 145, 133, 122, 111, 101, 92, 83, 74, 66, 59, 52, 45, | ||
| 43 | + 39, 34, 29, 25, 21, 17, 14, 12, 10, 9, 8, 8, // 32 | ||
| 44 | + 255, 248, 240, 233, 225, 218, 210, 203, 196, 189, 182, 176, 169, 163, 156, 150, 144, 138, 133, | ||
| 45 | + 127, 121, 116, 111, 106, 101, 96, 91, 86, 82, 77, 73, 69, 65, 61, 57, 54, 50, 47, 44, 41, 38, | ||
| 46 | + 35, 32, 29, 27, 25, 22, 20, 18, 16, 15, 13, 12, 10, 9, 8, 7, 6, 6, 5, 5, 4, 4, 4, // 64 | ||
| 47 | +]; | ||
| 48 | + | ||
| 49 | +/// `Round2` (spec 4.7): halves round up. | ||
| 50 | +fn round2(value: i32, shift: u32) -> i32 { | ||
| 51 | + (value + (1 << (shift - 1))) >> shift | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// The edges a block predicts from, as the decoder builds them (spec 7.11.2.2): | ||
| 55 | +/// a side that does not exist is filled from the side that does, and the corner | ||
| 56 | +/// falls back the same way. | ||
| 57 | +struct Edges { | ||
| 58 | + above: Vec<i32>, | ||
| 59 | + left: Vec<i32>, | ||
| 60 | + corner: i32, | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +impl Edges { | ||
| 64 | + fn build(above: Option<&[u8]>, left: Option<&[u8]>, corner: Option<u8>, side: usize) -> Self { | ||
| 65 | + let above_row = match (above, left) { | ||
| 66 | + (Some(a), _) => a.iter().map(|&s| i32::from(s)).collect(), | ||
| 67 | + (None, Some(l)) => vec![i32::from(l[0]); side], | ||
| 68 | + (None, None) => vec![127; side], | ||
| 69 | + }; | ||
| 70 | + let left_col = match (left, above) { | ||
| 71 | + (Some(l), _) => l.iter().map(|&s| i32::from(s)).collect(), | ||
| 72 | + (None, Some(a)) => vec![i32::from(a[0]); side], | ||
| 73 | + (None, None) => vec![129; side], | ||
| 74 | + }; | ||
| 75 | + let corner = match (corner, above, left) { | ||
| 76 | + (Some(c), Some(_), Some(_)) => i32::from(c), | ||
| 77 | + (_, Some(a), _) => i32::from(a[0]), | ||
| 78 | + (_, None, Some(l)) => i32::from(l[0]), | ||
| 79 | + (_, None, None) => 128, | ||
| 80 | + }; | ||
| 81 | + Self { | ||
| 82 | + above: above_row, | ||
| 83 | + left: left_col, | ||
| 84 | + corner, | ||
| 85 | + } | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +/// Predicts one square block into `dst`, row-major and `side * side` long. | ||
| 90 | +/// | ||
| 91 | +/// `above` is the reconstructed row above the block and `left` its | ||
| 92 | +/// reconstructed left column, each `side` samples long, and `corner` the | ||
| 93 | +/// sample diagonally above-left; `None` where the block sits against an edge | ||
| 94 | +/// of the frame. | ||
| 95 | +/// | ||
| 96 | +/// # Panics | ||
| 97 | +/// Panics on a mode this module does not predict, or when `dst` is not | ||
| 98 | +/// `side * side` long. | ||
| 99 | +pub fn predict( | ||
| 100 | + mode: u8, | ||
| 101 | + above: Option<&[u8]>, | ||
| 102 | + left: Option<&[u8]>, | ||
| 103 | + corner: Option<u8>, | ||
| 104 | + side: usize, | ||
| 105 | + dst: &mut [u8], | ||
| 106 | +) { | ||
| 107 | + assert_eq!(dst.len(), side * side, "the destination is the block"); | ||
| 108 | + let edges = Edges::build(above, left, corner, side); | ||
| 109 | + let (a, l) = (&edges.above, &edges.left); | ||
| 110 | + let weights = &SM_WEIGHTS[side..side * 2]; | ||
| 111 | + for row in 0..side { | ||
| 112 | + for col in 0..side { | ||
| 113 | + let value = match mode { | ||
| 114 | + DC_PRED => dc(above, left), | ||
| 115 | + V_PRED => a[col], | ||
| 116 | + H_PRED => l[row], | ||
| 117 | + SMOOTH_PRED => round2( | ||
| 118 | + i32::from(weights[row]) * a[col] | ||
| 119 | + + (256 - i32::from(weights[row])) * l[side - 1] | ||
| 120 | + + i32::from(weights[col]) * l[row] | ||
| 121 | + + (256 - i32::from(weights[col])) * a[side - 1], | ||
| 122 | + 9, | ||
| 123 | + ), | ||
| 124 | + SMOOTH_V_PRED => round2( | ||
| 125 | + i32::from(weights[row]) * a[col] | ||
| 126 | + + (256 - i32::from(weights[row])) * l[side - 1], | ||
| 127 | + 8, | ||
| 128 | + ), | ||
| 129 | + SMOOTH_H_PRED => round2( | ||
| 130 | + i32::from(weights[col]) * l[row] | ||
| 131 | + + (256 - i32::from(weights[col])) * a[side - 1], | ||
| 132 | + 8, | ||
| 133 | + ), | ||
| 134 | + PAETH_PRED => paeth(a[col], l[row], edges.corner), | ||
| 135 | + other => panic!("intra mode {other} is not one this module predicts"), | ||
| 136 | + }; | ||
| 137 | + dst[row * side + col] = value.clamp(0, 255) as u8; | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +/// `dc_predict` (spec 7.11.2.5): the average of whichever neighbours exist. | ||
| 143 | +fn dc(above: Option<&[u8]>, left: Option<&[u8]>) -> i32 { | ||
| 144 | + let average = |samples: &[u8]| { | ||
| 145 | + let sum: u32 = samples.iter().map(|&s| u32::from(s)).sum(); | ||
| 146 | + ((sum + (samples.len() as u32 >> 1)) / samples.len() as u32) as i32 | ||
| 147 | + }; | ||
| 148 | + match (above, left) { | ||
| 149 | + (None, None) => 128, | ||
| 150 | + (Some(a), None) => average(a), | ||
| 151 | + (None, Some(l)) => average(l), | ||
| 152 | + (Some(a), Some(l)) => { | ||
| 153 | + let sum: u32 = a.iter().chain(l).map(|&s| u32::from(s)).sum(); | ||
| 154 | + let count = (a.len() + l.len()) as u32; | ||
| 155 | + ((sum + (count >> 1)) / count) as i32 | ||
| 156 | + } | ||
| 157 | + } | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +/// `paeth_predict` (spec 7.11.2.2): of the three neighbours, the one nearest | ||
| 161 | +/// the gradient they describe. | ||
| 162 | +fn paeth(above: i32, left: i32, corner: i32) -> i32 { | ||
| 163 | + let base = above + left - corner; | ||
| 164 | + let (d_left, d_above, d_corner) = ( | ||
| 165 | + (base - left).abs(), | ||
| 166 | + (base - above).abs(), | ||
| 167 | + (base - corner).abs(), | ||
| 168 | + ); | ||
| 169 | + if d_left <= d_above && d_left <= d_corner { | ||
| 170 | + left | ||
| 171 | + } else if d_above <= d_corner { | ||
| 172 | + above | ||
| 173 | + } else { | ||
| 174 | + corner | ||
| 175 | + } | ||
| 176 | +} | ||
crates/ec-av1/src/lib.rsmodified+1 -0
| @@ -16,6 +16,7 @@ pub mod bits; | |||
| 16 | pub mod cdf; | 16 | pub mod cdf; |
| 17 | pub mod encode; | 17 | pub mod encode; |
| 18 | pub mod frame; | 18 | pub mod frame; |
| 19 | +pub mod intra; | ||
| 19 | pub mod msac; | 20 | pub mod msac; |
| 20 | pub mod obu; | 21 | pub mod obu; |
| 21 | pub mod quant; | 22 | pub mod quant; |
lanes/av1-predict-r1.report.mdadded+98 -0
| @@ -0,0 +1,98 @@ | |||
| 1 | +# lane-av1-predict r1 — the seven non-directional intra modes, chosen per block | ||
| 2 | + | ||
| 3 | +## What landed | ||
| 4 | + | ||
| 5 | +`crates/ec-av1/src/intra.rs`: the intra predictors of spec 7.11.2 that read no | ||
| 6 | +further than the row above and the column to the left of a block — DC, V, H, | ||
| 7 | +SMOOTH, SMOOTH_V, SMOOTH_H and PAETH — including the edge construction that | ||
| 8 | +fills a missing side from the side that exists (127/129/128 where neither does). | ||
| 9 | + | ||
| 10 | +`encode.rs` now searches those seven per 32x32 luma block: each is transformed, | ||
| 11 | +quantized, reconstructed and scored as `SSE + lambda * bits`, and the winner is | ||
| 12 | +committed and written as the block's luma mode. Chroma stays DC, which is the | ||
| 13 | +mode the tile writer codes for it. `encode_key_frame_with_modes` exposes the mode | ||
| 14 | +set so an ablation can hold the encoder at DC alone, and `Encoded::modes` reports | ||
| 15 | +what each block picked. | ||
| 16 | + | ||
| 17 | +## Gates | ||
| 18 | + | ||
| 19 | +| gate | result | | ||
| 20 | +| --- | --- | | ||
| 21 | +| `cargo test --release -p ec-av1` | 73 passed, 1 ignored (the sweep probe) | | ||
| 22 | +| `every_mode_decodes_to_what_the_encoder_predicted` | each of the seven forced over a whole picture, ffmpeg reconstruction sample-exact on all three planes | | ||
| 23 | +| `ffmpeg_decodes_exactly_what_the_encoder_reconstructed` | sample-exact at 64x64, 96x64, 160x96 with the search live | | ||
| 24 | +| `the_search_picks_the_direction_the_picture_runs` | vertical stripes pick V_PRED, horizontal pick H_PRED | | ||
| 25 | +| `the_search_beats_dc_alone` | BD-rate against DC alone < -5% on the test card, < -40% on stripes | | ||
| 26 | +| `a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed` | sample-exact on three clips (below) | | ||
| 27 | +| clippy `--all-targets` | 0 warnings | | ||
| 28 | + | ||
| 29 | +## Mutation kills | ||
| 30 | + | ||
| 31 | +| mutation | tests killed | | ||
| 32 | +| --- | --- | | ||
| 33 | +| one `Sm_Weights` entry off by one (sides 4 and 32) | 2 | | ||
| 34 | +| PAETH returning above where it should return left | 1 | | ||
| 35 | +| SMOOTH_V weighted by the column index instead of the row | 1 | | ||
| 36 | +| V_PRED and H_PRED swapped | 3 | | ||
| 37 | + | ||
| 38 | +The transposition mutations are the reason the striped pictures exist: every | ||
| 39 | +fidelity gate survives a transposed predictor, because a symmetric picture cannot | ||
| 40 | +tell the two apart. See the class note `reference-layout-not-spec`. | ||
| 41 | + | ||
| 42 | +## The weight the search puts on rate | ||
| 43 | + | ||
| 44 | +`LAMBDA_SCALE`, swept with `probe_lambda` over three of his clips and two | ||
| 45 | +synthetic pictures — BD-rate against DC alone, negative is better: | ||
| 46 | + | ||
| 47 | +| lambda | test card | stripes | film (ReelC) | screen capture (OBS) | hand-held | | ||
| 48 | +| --- | --- | --- | --- | --- | --- | | ||
| 49 | +| 0 | -6.2% | -35.6% | -0.0% | -3.7% | +0.6% | | ||
| 50 | +| 0.05 | **-7.8%** | **-59.5%** | **-1.1%** | **-11.5%** | **+0.0%** | | ||
| 51 | +| 0.1 | -7.2% | -59.5% | -1.1% | -10.7% | +0.5% | | ||
| 52 | +| 0.2 | -7.0% | -59.5% | -0.8% | -10.7% | +0.7% | | ||
| 53 | +| 0.4 | -7.0% | -59.5% | -0.5% | -10.8% | +1.1% | | ||
| 54 | +| 0.8 | -7.0% | -59.5% | -0.5% | -10.8% | +1.3% | | ||
| 55 | + | ||
| 56 | +0.05 is the best point on every clip measured, so that is the default. | ||
| 57 | + | ||
| 58 | +The hand-held clip's column is the honest part: the search can come out *behind* | ||
| 59 | +DC alone there, because the cost it scores does not include what signalling a | ||
| 60 | +non-DC mode costs — the mode symbol itself, and the neighbour contexts it moves. | ||
| 61 | +At 0.05 that costs 0.0%; at 0.4 it costs 1.1%. Disposition: **accepted** — | ||
| 62 | +the fix is to score the real symbol cost, which needs the tile writer's CDFs in | ||
| 63 | +the search loop, and that is the next lane's business. | ||
| 64 | + | ||
| 65 | +## His data | ||
| 66 | + | ||
| 67 | +One frame of each, scaled to 640x352, at q100 / deadzone 0.5. Every one decodes | ||
| 68 | +sample-exactly to what the encoder reconstructed. | ||
| 69 | + | ||
| 70 | +| clip | bytes | luma PSNR | | ||
| 71 | +| --- | --- | --- | | ||
| 72 | +| ReelC (film) | 18570 | 40.68 dB | | ||
| 73 | +| OBS screen capture 2026-08-25 16-27-54 | 4808 | 46.06 dB | | ||
| 74 | +| reela | 1531 | 51.81 dB | | ||
| 75 | + | ||
| 76 | +Against libaom (`-c:v libaom-av1 -cpu-used 4`, same frame of ReelC): | ||
| 77 | + | ||
| 78 | +| encoder | bytes | luma PSNR | | ||
| 79 | +| --- | --- | --- | | ||
| 80 | +| ours, q100 | 18570 | 40.68 | | ||
| 81 | +| libaom crf 20 | 16943 | 42.91 | | ||
| 82 | +| libaom crf 25 | 13733 | 41.46 | | ||
| 83 | +| libaom crf 30 | 10620 | 39.75 | | ||
| 84 | + | ||
| 85 | +Interpolated at our 40.68 dB, libaom spends about 12.3 kB against our 18.6 kB: | ||
| 86 | +we cost roughly **+51% rate**, about **2.0 dB** at matched size. Before this lane | ||
| 87 | +the same comparison stood at 2.4 dB. | ||
| 88 | + | ||
| 89 | +## Not in this lane | ||
| 90 | + | ||
| 91 | +- The eight directional modes. They read past a block's own width into | ||
| 92 | + above-right and below-left samples, whose availability the decoder tracks in | ||
| 93 | + its `BlockDecoded` bookkeeping; predicting them means reproducing that walk. | ||
| 94 | +- Filter-intra and CfL (both off in the sequence header), palette, and the | ||
| 95 | + intra edge filter. | ||
| 96 | +- A rate term that counts the mode symbol and the coefficient symbols as the | ||
| 97 | + writer actually codes them, rather than a magnitude estimate. | ||
| 98 | +- Block sizes other than 32x32, transform-size selection, and CDF adaptation. | ||