| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | use crate::decode::WithRef; |
| 20 | use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader}; |
| 21 | use ec_av1_syntax::{ |
| 22 | CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams, |
| 23 | LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode, |
| 24 | }; |
| 25 | use ec_core::{Error, Result}; |
| 26 | |
| 27 | use crate::cdf; |
| 28 | use crate::cdf_state::TxbSet; |
| 29 | use crate::frame::frame_obu; |
| 30 | use crate::intra::{ |
| 31 | D67_PRED, DC_PRED, H_PRED, KEY_FRAME_MODES, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED, |
| 32 | SMOOTH_V_PRED, V_PRED, |
| 33 | }; |
| 34 | use crate::mc; |
| 35 | use crate::motion; |
| 36 | use crate::mvstack::{MiGrid, MiInfo, MvStack, NO_REF1, find_mv_stack, mv16}; |
| 37 | use crate::obu::temporal_delimiter; |
| 38 | use crate::quant::ac_q; |
| 39 | use crate::sequence::sequence_header_obu; |
| 40 | use crate::tile::{ |
| 41 | BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits, |
| 42 | }; |
| 43 | use crate::transform::{ |
| 44 | TxType, dequant_and_inverse, dequant_and_inverse_typed, forward_and_quantize, |
| 45 | forward_and_quantize_typed, |
| 46 | }; |
| 47 | |
| 48 | |
| 49 | |
| 50 | const BLOCK: usize = 32; |
| 51 | |
| 52 | |
| 53 | const SUB: usize = 16; |
| 54 | |
| 55 | |
| 56 | pub(crate) const SUPERBLOCK: usize = 64; |
| 57 | |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | |
| 67 | pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) { |
| 68 | fctx.reach_sb_px.with(|c| c.set(px)); |
| 69 | } |
| 70 | |
| 71 | fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize { |
| 72 | fctx.reach_sb_px.with(|c| c.get()) |
| 73 | } |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | const LAMBDA_SCALE: f64 = 0.1; |
| 86 | |
| 87 | |
| 88 | |
| 89 | fn lambda_scale() -> f64 { |
| 90 | let swept = std::env::var("EC_AV1_LAMBDA") |
| 91 | .ok() |
| 92 | .and_then(|v| v.parse::<f64>().ok()); |
| 93 | match swept { |
| 94 | Some(scale) if cfg!(test) => scale, |
| 95 | _ => LAMBDA_SCALE, |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | #[cfg(test)] |
| 103 | thread_local! { |
| 104 | static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) }; |
| 105 | } |
| 106 | |
| 107 | |
| 108 | #[cfg(test)] |
| 109 | fn record_predicted_bits(bits: f64) { |
| 110 | PREDICTED_BITS.with(|p| p.borrow_mut().push(bits)); |
| 111 | } |
| 112 | |
| 113 | |
| 114 | |
| 115 | #[cfg(test)] |
| 116 | pub(crate) fn take_predicted_bits() -> Vec<f64> { |
| 117 | PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut())) |
| 118 | } |
| 119 | |
| 120 | |
| 121 | const SPLIT_INTER_8: bool = true; |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | fn tx_select_inter() -> bool { |
| 138 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 139 | *ON.get_or_init(|| { |
| 140 | !matches!( |
| 141 | std::env::var("EC_AV1_TX_SELECT_INTER").as_deref(), |
| 142 | Ok("0") | Ok("off") |
| 143 | ) |
| 144 | }) |
| 145 | } |
| 146 | |
| 147 | fn tx_select() -> bool { |
| 148 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 149 | *ON.get_or_init(|| { |
| 150 | !matches!( |
| 151 | std::env::var("EC_AV1_TX_SELECT").as_deref(), |
| 152 | Ok("0") | Ok("off") |
| 153 | ) |
| 154 | }) |
| 155 | } |
| 156 | |
| 157 | fn split_inter_8() -> bool { |
| 158 | match std::env::var("EC_AV1_SPLIT_INTER8").ok() { |
| 159 | Some(v) if cfg!(test) => v != "0", |
| 160 | _ => SPLIT_INTER_8, |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | |
| 165 | |
| 166 | const LEAF_NEW_MV: bool = true; |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | const EXTRA_REF_NEW_MV: bool = true; |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | |
| 183 | const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35; |
| 184 | |
| 185 | |
| 186 | fn extra_new_skip_margin() -> f64 { |
| 187 | match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() { |
| 188 | Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN), |
| 189 | _ => EXTRA_NEW_SKIP_MARGIN, |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | const LEAF_COMPOUND: bool = true; |
| 199 | |
| 200 | |
| 201 | fn leaf_compound() -> bool { |
| 202 | match std::env::var("EC_AV1_LEAF_COMPOUND").ok() { |
| 203 | Some(v) => v != "0", |
| 204 | None => LEAF_COMPOUND, |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | |
| 209 | fn leaf_new_mv() -> bool { |
| 210 | match std::env::var("EC_AV1_LEAF_NEWMV").ok() { |
| 211 | Some(v) if cfg!(test) => v != "0", |
| 212 | _ => LEAF_NEW_MV, |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | |
| 217 | |
| 218 | |
| 219 | |
| 220 | |
| 221 | const SPLIT_INTER_BLOCKS: bool = true; |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | fn split_inter_blocks() -> bool { |
| 227 | match std::env::var("EC_AV1_SPLIT_INTER").ok() { |
| 228 | Some(v) if cfg!(test) => v != "0", |
| 229 | _ => SPLIT_INTER_BLOCKS, |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | const RESTORATION: bool = true; |
| 238 | |
| 239 | |
| 240 | fn restoration_enabled() -> bool { |
| 241 | match std::env::var("EC_AV1_LR").ok() { |
| 242 | Some(v) if cfg!(test) => v != "0", |
| 243 | _ => RESTORATION, |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | const SPLIT_BREAKOUT_COEFFS: usize = 0; |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | const SPLIT_RD_THRESHOLD: f64 = 0.125; |
| 282 | |
| 283 | |
| 284 | fn split_rd_threshold() -> f64 { |
| 285 | static T: std::sync::OnceLock<f64> = std::sync::OnceLock::new(); |
| 286 | *T.get_or_init(|| { |
| 287 | std::env::var("EC_AV1_SPLIT_RD") |
| 288 | .ok() |
| 289 | .and_then(|v| v.parse().ok()) |
| 290 | .unwrap_or(SPLIT_RD_THRESHOLD) |
| 291 | }) |
| 292 | } |
| 293 | |
| 294 | |
| 295 | |
| 296 | fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool { |
| 297 | let t = split_rd_threshold(); |
| 298 | t > 0.0 && cost < t * lambda * (side * side) as f64 |
| 299 | } |
| 300 | |
| 301 | |
| 302 | |
| 303 | fn split_breakout_coeffs() -> usize { |
| 304 | match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() { |
| 305 | Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS), |
| 306 | _ => SPLIT_BREAKOUT_COEFFS, |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [ |
| 316 | std::sync::atomic::AtomicUsize::new(0), |
| 317 | std::sync::atomic::AtomicUsize::new(0), |
| 318 | std::sync::atomic::AtomicUsize::new(0), |
| 319 | std::sync::atomic::AtomicUsize::new(0), |
| 320 | ]; |
| 321 | |
| 322 | |
| 323 | fn partition_hit(which: usize) { |
| 324 | PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 325 | } |
| 326 | |
| 327 | |
| 328 | #[cfg(test)] |
| 329 | pub(crate) fn take_partition_hits() -> [usize; 4] { |
| 330 | [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 331 | } |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | pub fn census_on() -> bool { |
| 339 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 340 | *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1"))) |
| 341 | } |
| 342 | |
| 343 | |
| 344 | pub const CENSUS_KINDS: [&str; 11] = [ |
| 345 | "intra blocks searched (key frame + inter leaves)", |
| 346 | "intra luma mode trials", |
| 347 | "chroma searches", |
| 348 | "chroma mode trials (each = 2 plane trials)", |
| 349 | "tx-depth trials (transform units, depth >= 1)", |
| 350 | "inter 32x32 blocks searched", |
| 351 | "inter block intra-mode trials", |
| 352 | "inter mv candidates (each = 3 mc trials)", |
| 353 | "inter leaves searched (intra vs NEARESTMV/NEWMV)", |
| 354 | " of those, intra won", |
| 355 | " of those, the NEARESTMV trial coded no residual", |
| 356 | ]; |
| 357 | |
| 358 | |
| 359 | static CENSUS: [std::sync::atomic::AtomicUsize; 11] = |
| 360 | [const { std::sync::atomic::AtomicUsize::new(0) }; 11]; |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] = |
| 366 | [const { std::sync::atomic::AtomicUsize::new(0) }; 13]; |
| 367 | static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] = |
| 368 | [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; |
| 369 | |
| 370 | fn census_add(kind: usize, n: usize) { |
| 371 | if census_on() { |
| 372 | CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed); |
| 373 | } |
| 374 | } |
| 375 | |
| 376 | |
| 377 | pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) { |
| 378 | let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed); |
| 379 | ( |
| 380 | std::array::from_fn(|i| take(&CENSUS[i])), |
| 381 | std::array::from_fn(|i| take(&LUMA_RANK[i])), |
| 382 | std::array::from_fn(|i| take(&CHROMA_RANK[i])), |
| 383 | ) |
| 384 | } |
| 385 | |
| 386 | |
| 387 | |
| 388 | |
| 389 | fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize { |
| 390 | scored |
| 391 | .iter() |
| 392 | .filter(|&&(score, mode)| { |
| 393 | mode != winner |
| 394 | && score |
| 395 | < scored |
| 396 | .iter() |
| 397 | .find(|&&(_, m)| m == winner) |
| 398 | .map_or(f64::INFINITY, |&(s, _)| s) |
| 399 | }) |
| 400 | .count() |
| 401 | } |
| 402 | |
| 403 | |
| 404 | |
| 405 | const SPLIT_BLOCKS: bool = true; |
| 406 | |
| 407 | |
| 408 | |
| 409 | pub(crate) fn split_blocks() -> bool { |
| 410 | SPLIT_BLOCKS |
| 411 | } |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 423 | pub struct Picture { |
| 424 | |
| 425 | pub width: usize, |
| 426 | |
| 427 | pub height: usize, |
| 428 | |
| 429 | pub y: Vec<u16>, |
| 430 | |
| 431 | pub u: Vec<u16>, |
| 432 | |
| 433 | pub v: Vec<u16>, |
| 434 | } |
| 435 | |
| 436 | impl Picture { |
| 437 | |
| 438 | #[must_use] |
| 439 | pub fn grey(width: usize, height: usize) -> Self { |
| 440 | Self { |
| 441 | width, |
| 442 | height, |
| 443 | y: vec![128; width * height], |
| 444 | u: vec![128; width * height / 4], |
| 445 | v: vec![128; width * height / 4], |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | pub(crate) fn check(&self) -> Result<()> { |
| 450 | if self.width == 0 |
| 451 | || !self.width.is_multiple_of(BLOCK) |
| 452 | || !self.height.is_multiple_of(BLOCK) |
| 453 | || !self.height.is_multiple_of(BLOCK) |
| 454 | { |
| 455 | return Err(Error::unsupported( |
| 456 | "AV1 encode", |
| 457 | "the picture must be a whole number of 32x32 blocks in each direction", |
| 458 | )); |
| 459 | } |
| 460 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 461 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 462 | return Err(Error::unsupported( |
| 463 | "AV1 encode", |
| 464 | "each plane must carry one sample per position at 4:2:0", |
| 465 | )); |
| 466 | } |
| 467 | Ok(()) |
| 468 | } |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | |
| 474 | pub(crate) fn check_even(&self) -> Result<()> { |
| 475 | if self.width == 0 |
| 476 | || self.height == 0 |
| 477 | || !self.width.is_multiple_of(2) |
| 478 | || !self.height.is_multiple_of(2) |
| 479 | { |
| 480 | return Err(Error::unsupported( |
| 481 | "AV1 encode", |
| 482 | "the picture's width and height must each be even and nonzero", |
| 483 | )); |
| 484 | } |
| 485 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 486 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 487 | return Err(Error::unsupported( |
| 488 | "AV1 encode", |
| 489 | "each plane must carry one sample per position at 4:2:0", |
| 490 | )); |
| 491 | } |
| 492 | Ok(()) |
| 493 | } |
| 494 | |
| 495 | |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | |
| 501 | |
| 502 | pub(crate) fn padded_to(&self, align: usize) -> Picture { |
| 503 | let padded_width = self.width.next_multiple_of(align); |
| 504 | let padded_height = self.height.next_multiple_of(align); |
| 505 | if padded_width == self.width && padded_height == self.height { |
| 506 | return self.clone(); |
| 507 | } |
| 508 | Picture { |
| 509 | width: padded_width, |
| 510 | height: padded_height, |
| 511 | y: pad_plane( |
| 512 | &self.y, |
| 513 | self.width, |
| 514 | self.height, |
| 515 | padded_width, |
| 516 | padded_height, |
| 517 | ), |
| 518 | u: pad_plane( |
| 519 | &self.u, |
| 520 | self.width / 2, |
| 521 | self.height / 2, |
| 522 | padded_width / 2, |
| 523 | padded_height / 2, |
| 524 | ), |
| 525 | v: pad_plane( |
| 526 | &self.v, |
| 527 | self.width / 2, |
| 528 | self.height / 2, |
| 529 | padded_width / 2, |
| 530 | padded_height / 2, |
| 531 | ), |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | |
| 537 | |
| 538 | |
| 539 | |
| 540 | |
| 541 | |
| 542 | #[allow(clippy::too_many_arguments)] |
| 543 | fn intra_predict_u8( |
| 544 | mode: u8, |
| 545 | angle_delta: i32, |
| 546 | above: Option<&[u8]>, |
| 547 | left: Option<&[u8]>, |
| 548 | corner: Option<u8>, |
| 549 | bw: usize, |
| 550 | bh: usize, |
| 551 | enable_edge_filter: bool, |
| 552 | smooth_neighbor: bool, |
| 553 | dst: &mut [u8], fctx: &crate::decode::FrameCtx, |
| 554 | ) { |
| 555 | let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect()); |
| 556 | let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect()); |
| 557 | let mut dst16 = vec![0u16; dst.len()]; |
| 558 | crate::intra::predict( |
| 559 | mode, |
| 560 | angle_delta, |
| 561 | above16.as_deref(), |
| 562 | left16.as_deref(), |
| 563 | corner.map(u16::from), |
| 564 | bw, |
| 565 | bh, |
| 566 | enable_edge_filter, |
| 567 | smooth_neighbor, |
| 568 | &mut dst16, fctx, |
| 569 | ); |
| 570 | for (d, &s) in dst.iter_mut().zip(dst16.iter()) { |
| 571 | *d = s as u8; |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | |
| 576 | |
| 577 | |
| 578 | fn pad_plane<T: Copy + Default>( |
| 579 | source: &[T], |
| 580 | width: usize, |
| 581 | height: usize, |
| 582 | padded_width: usize, |
| 583 | padded_height: usize, |
| 584 | ) -> Vec<T> { |
| 585 | let mut out = vec![T::default(); padded_width * padded_height]; |
| 586 | for row in 0..padded_height { |
| 587 | let src = source[row.min(height - 1) * width..][..width].as_ref(); |
| 588 | let dst = &mut out[row * padded_width..][..padded_width]; |
| 589 | dst[..width].copy_from_slice(src); |
| 590 | dst[width..].fill(src[width - 1]); |
| 591 | } |
| 592 | out |
| 593 | } |
| 594 | |
| 595 | |
| 596 | |
| 597 | |
| 598 | fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> { |
| 599 | let mut out = Vec::with_capacity(width * height); |
| 600 | for row in 0..height { |
| 601 | out.extend_from_slice(&source[row * padded_width..][..width]); |
| 602 | } |
| 603 | out |
| 604 | } |
| 605 | |
| 606 | |
| 607 | |
| 608 | |
| 609 | |
| 610 | pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded { |
| 611 | let reconstruction = &encoded.reconstruction; |
| 612 | let cropped = if reconstruction.width == width && reconstruction.height == height { |
| 613 | reconstruction.clone() |
| 614 | } else { |
| 615 | Picture { |
| 616 | width, |
| 617 | height, |
| 618 | y: crop_plane(&reconstruction.y, reconstruction.width, width, height), |
| 619 | u: crop_plane( |
| 620 | &reconstruction.u, |
| 621 | reconstruction.width / 2, |
| 622 | width / 2, |
| 623 | height / 2, |
| 624 | ), |
| 625 | v: crop_plane( |
| 626 | &reconstruction.v, |
| 627 | reconstruction.width / 2, |
| 628 | width / 2, |
| 629 | height / 2, |
| 630 | ), |
| 631 | } |
| 632 | }; |
| 633 | Encoded { |
| 634 | stream: encoded.stream.clone(), |
| 635 | modes: encoded.modes.clone(), |
| 636 | inter_block_share: encoded.inter_block_share, |
| 637 | reconstruction: cropped, |
| 638 | tile: encoded.tile.clone(), |
| 639 | mi_cols: encoded.mi_cols, |
| 640 | mi_rows: encoded.mi_rows, |
| 641 | base_q_idx: encoded.base_q_idx, |
| 642 | tx_select: encoded.tx_select, |
| 643 | screen: encoded.screen, |
| 644 | start_cdfs: encoded.start_cdfs.clone(), |
| 645 | next_cdfs: encoded.next_cdfs.clone(), |
| 646 | loop_filter: encoded.loop_filter, |
| 647 | loop_restoration: encoded.loop_restoration, |
| 648 | allow_intrabc: encoded.allow_intrabc, |
| 649 | cdef: encoded.cdef, |
| 650 | } |
| 651 | } |
| 652 | |
| 653 | |
| 654 | |
| 655 | #[derive(Clone)] |
| 656 | pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs); |
| 657 | |
| 658 | impl std::fmt::Debug for CdfSnapshot { |
| 659 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 660 | f.write_str("CdfSnapshot") |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | |
| 665 | #[derive(Clone, Debug)] |
| 666 | pub struct Encoded { |
| 667 | |
| 668 | |
| 669 | pub stream: Vec<u8>, |
| 670 | |
| 671 | |
| 672 | pub reconstruction: Picture, |
| 673 | |
| 674 | |
| 675 | |
| 676 | pub modes: Vec<u8>, |
| 677 | |
| 678 | |
| 679 | |
| 680 | |
| 681 | pub inter_block_share: f64, |
| 682 | |
| 683 | |
| 684 | |
| 685 | |
| 686 | pub(crate) tile: Vec<u8>, |
| 687 | pub(crate) mi_cols: u32, |
| 688 | pub(crate) mi_rows: u32, |
| 689 | pub(crate) base_q_idx: u8, |
| 690 | |
| 691 | |
| 692 | |
| 693 | |
| 694 | |
| 695 | |
| 696 | pub(crate) tx_select: bool, |
| 697 | |
| 698 | |
| 699 | |
| 700 | |
| 701 | |
| 702 | |
| 703 | pub(crate) start_cdfs: CdfSnapshot, |
| 704 | |
| 705 | |
| 706 | |
| 707 | |
| 708 | pub(crate) next_cdfs: CdfSnapshot, |
| 709 | |
| 710 | |
| 711 | |
| 712 | |
| 713 | |
| 714 | pub(crate) loop_filter: LoopFilterParams, |
| 715 | |
| 716 | |
| 717 | pub(crate) cdef: CdefParams, |
| 718 | |
| 719 | |
| 720 | |
| 721 | |
| 722 | pub(crate) screen: bool, |
| 723 | |
| 724 | |
| 725 | |
| 726 | |
| 727 | pub(crate) loop_restoration: LoopRestorationParams, |
| 728 | |
| 729 | |
| 730 | |
| 731 | |
| 732 | pub(crate) allow_intrabc: bool, |
| 733 | } |
| 734 | |
| 735 | thread_local! { |
| 736 | |
| 737 | |
| 738 | |
| 739 | static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) }; |
| 740 | } |
| 741 | |
| 742 | |
| 743 | #[allow(dead_code)] |
| 744 | pub(crate) fn intrabc_source_share() -> f64 { |
| 745 | IBC_SHARE.with(std::cell::Cell::get) |
| 746 | } |
| 747 | |
| 748 | thread_local! { |
| 749 | |
| 750 | |
| 751 | |
| 752 | |
| 753 | |
| 754 | |
| 755 | |
| 756 | |
| 757 | |
| 758 | |
| 759 | static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 760 | } |
| 761 | |
| 762 | thread_local! { |
| 763 | |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 768 | |
| 769 | static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; |
| 770 | } |
| 771 | |
| 772 | #[cfg(test)] |
| 773 | pub(crate) fn force_screen(value: Option<bool>) { |
| 774 | SCREEN_FORCE.with(|c| c.set(value)); |
| 775 | } |
| 776 | |
| 777 | pub(crate) fn arm_seq_screen(on: bool) { |
| 778 | SEQ_SCREEN.with(|c| c.set(on)); |
| 779 | } |
| 780 | |
| 781 | fn seq_screen() -> bool { |
| 782 | SEQ_SCREEN.with(std::cell::Cell::get) |
| 783 | } |
| 784 | |
| 785 | |
| 786 | |
| 787 | |
| 788 | |
| 789 | |
| 790 | |
| 791 | |
| 792 | fn screen_colors() -> usize { |
| 793 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 794 | *N.get_or_init(|| { |
| 795 | std::env::var("EC_AV1_SCREEN_COLORS") |
| 796 | .ok() |
| 797 | .and_then(|v| v.parse().ok()) |
| 798 | .unwrap_or(32) |
| 799 | }) |
| 800 | } |
| 801 | |
| 802 | |
| 803 | |
| 804 | |
| 805 | |
| 806 | |
| 807 | fn screen_pct() -> usize { |
| 808 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 809 | *N.get_or_init(|| { |
| 810 | std::env::var("EC_AV1_SCREEN_PCT") |
| 811 | .ok() |
| 812 | .and_then(|v| v.parse().ok()) |
| 813 | .unwrap_or(3) |
| 814 | }) |
| 815 | } |
| 816 | |
| 817 | |
| 818 | |
| 819 | pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] = |
| 820 | [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; |
| 821 | |
| 822 | |
| 823 | |
| 824 | |
| 825 | |
| 826 | |
| 827 | fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool { |
| 828 | if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) { |
| 829 | SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 830 | return forced; |
| 831 | } |
| 832 | if let Ok(v) = std::env::var("EC_AV1_SCREEN") { |
| 833 | let on = v != "0"; |
| 834 | SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 835 | return on; |
| 836 | } |
| 837 | let (blk, limit) = (16usize, screen_colors()); |
| 838 | let mut counted = 0usize; |
| 839 | for by in (0..true_height).step_by(blk) { |
| 840 | for bx in (0..true_width).step_by(blk) { |
| 841 | let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk)); |
| 842 | let mut seen = [false; 256]; |
| 843 | let mut colors = 0usize; |
| 844 | for row in 0..h { |
| 845 | for col in 0..w { |
| 846 | let v = usize::from(y[(by + row) * width + bx + col]); |
| 847 | if !seen[v] { |
| 848 | seen[v] = true; |
| 849 | colors += 1; |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | if colors > 1 && colors <= limit { |
| 854 | counted += 1; |
| 855 | } |
| 856 | } |
| 857 | } |
| 858 | let on = counted * blk * blk * screen_pct() > true_width * true_height; |
| 859 | SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 860 | on |
| 861 | } |
| 862 | |
| 863 | |
| 864 | |
| 865 | |
| 866 | |
| 867 | |
| 868 | |
| 869 | |
| 870 | |
| 871 | |
| 872 | pub fn key_frame_headers( |
| 873 | width: usize, |
| 874 | height: usize, |
| 875 | base_q_idx: u8, |
| 876 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 877 | key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config()) |
| 878 | } |
| 879 | |
| 880 | |
| 881 | |
| 882 | |
| 883 | |
| 884 | fn unspecified_color_config() -> ColorConfig { |
| 885 | ColorConfig { |
| 886 | bit_depth: 8, |
| 887 | mono_chrome: false, |
| 888 | num_planes: 3, |
| 889 | color_primaries: 2, |
| 890 | transfer_characteristics: 2, |
| 891 | matrix_coefficients: 2, |
| 892 | color_range: false, |
| 893 | subsampling_x: 1, |
| 894 | subsampling_y: 1, |
| 895 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 896 | separate_uv_delta_q: false, |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | |
| 901 | |
| 902 | |
| 903 | |
| 904 | |
| 905 | |
| 906 | |
| 907 | |
| 908 | pub(crate) fn key_frame_headers_colour( |
| 909 | width: usize, |
| 910 | height: usize, |
| 911 | base_q_idx: u8, |
| 912 | color_config: ColorConfig, |
| 913 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 914 | let bits = |n: usize| -> Result<u32> { |
| 915 | let n = u32::try_from(n).map_err(|_| too_large())?; |
| 916 | if n == 0 || n > 1 << 16 { |
| 917 | return Err(too_large()); |
| 918 | } |
| 919 | Ok((32 - (n - 1).leading_zeros()).max(1)) |
| 920 | }; |
| 921 | let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?); |
| 922 | let (w, h) = (width as u32, height as u32); |
| 923 | let seq = SequenceHeader { |
| 924 | seq_profile: 0, |
| 925 | operating_points: vec![OperatingPoint { |
| 926 | seq_level_idx: 8, |
| 927 | ..OperatingPoint::default() |
| 928 | }], |
| 929 | frame_width_bits, |
| 930 | frame_height_bits, |
| 931 | max_frame_width: w, |
| 932 | max_frame_height: h, |
| 933 | use_128x128_superblock: false, |
| 934 | enable_filter_intra: false, |
| 935 | enable_intra_edge_filter: false, |
| 936 | enable_order_hint: true, |
| 937 | order_hint_bits: 7, |
| 938 | enable_superres: false, |
| 939 | |
| 940 | |
| 941 | |
| 942 | |
| 943 | |
| 944 | enable_cdef: true, |
| 945 | enable_restoration: true, |
| 946 | |
| 947 | |
| 948 | |
| 949 | |
| 950 | |
| 951 | |
| 952 | seq_force_screen_content_tools: if seq_screen() { |
| 953 | ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS |
| 954 | } else { |
| 955 | 0 |
| 956 | }, |
| 957 | seq_force_integer_mv: 0, |
| 958 | color_config, |
| 959 | still_picture: false, |
| 960 | reduced_still_picture_header: false, |
| 961 | timing_info: None, |
| 962 | decoder_model_info: None, |
| 963 | initial_display_delay_present_flag: false, |
| 964 | operating_point: 0, |
| 965 | operating_point_idc: 0, |
| 966 | frame_id_numbers_present_flag: false, |
| 967 | delta_frame_id_length: 0, |
| 968 | additional_frame_id_length: 0, |
| 969 | enable_interintra_compound: false, |
| 970 | enable_masked_compound: false, |
| 971 | enable_warped_motion: false, |
| 972 | enable_dual_filter: false, |
| 973 | enable_jnt_comp: false, |
| 974 | enable_ref_frame_mvs: false, |
| 975 | film_grain_params_present: false, |
| 976 | }; |
| 977 | |
| 978 | |
| 979 | |
| 980 | |
| 981 | let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3)); |
| 982 | let header = FrameHeader { |
| 983 | frame_type: FrameType::Key, |
| 984 | frame_is_intra: true, |
| 985 | show_frame: true, |
| 986 | error_resilient_mode: true, |
| 987 | |
| 988 | |
| 989 | disable_cdf_update: false, |
| 990 | |
| 991 | |
| 992 | disable_frame_end_update_cdf: true, |
| 993 | force_integer_mv: true, |
| 994 | refresh_frame_flags: 0xFF, |
| 995 | primary_ref_frame: PRIMARY_REF_NONE, |
| 996 | frame_width: w, |
| 997 | frame_height: h, |
| 998 | upscaled_width: w, |
| 999 | render_width: w, |
| 1000 | render_height: h, |
| 1001 | mi_cols, |
| 1002 | mi_rows, |
| 1003 | tile_info: TileInfo { |
| 1004 | uniform_spacing: true, |
| 1005 | cols: 1, |
| 1006 | rows: 1, |
| 1007 | mi_col_starts: vec![0, mi_cols], |
| 1008 | mi_row_starts: vec![0, mi_rows], |
| 1009 | tile_size_bytes: 1, |
| 1010 | ..TileInfo::default() |
| 1011 | }, |
| 1012 | quantization: QuantizationParams { |
| 1013 | base_q_idx, |
| 1014 | ..QuantizationParams::default() |
| 1015 | }, |
| 1016 | tx_mode: TxMode::Largest, |
| 1017 | |
| 1018 | |
| 1019 | |
| 1020 | |
| 1021 | |
| 1022 | |
| 1023 | |
| 1024 | |
| 1025 | |
| 1026 | |
| 1027 | |
| 1028 | |
| 1029 | reduced_tx_set: true, |
| 1030 | ..FrameHeader::default() |
| 1031 | }; |
| 1032 | Ok((seq, header)) |
| 1033 | } |
| 1034 | |
| 1035 | |
| 1036 | |
| 1037 | |
| 1038 | pub const GOLDEN_SLOT: u8 = 1; |
| 1039 | |
| 1040 | |
| 1041 | |
| 1042 | |
| 1043 | |
| 1044 | |
| 1045 | |
| 1046 | |
| 1047 | pub fn inter_frame_headers( |
| 1048 | width: usize, |
| 1049 | height: usize, |
| 1050 | base_q_idx: u8, |
| 1051 | order_hint: u32, |
| 1052 | last_slot: u8, |
| 1053 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 1054 | inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot) |
| 1055 | } |
| 1056 | |
| 1057 | |
| 1058 | |
| 1059 | |
| 1060 | |
| 1061 | |
| 1062 | |
| 1063 | |
| 1064 | |
| 1065 | pub fn inter_frame_headers_slots( |
| 1066 | width: usize, |
| 1067 | height: usize, |
| 1068 | base_q_idx: u8, |
| 1069 | order_hint: u32, |
| 1070 | last_slot: u8, |
| 1071 | self_slot: u8, |
| 1072 | altref_slot: u8, |
| 1073 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 1074 | let (seq, key) = key_frame_headers(width, height, base_q_idx)?; |
| 1075 | let header = FrameHeader { |
| 1076 | frame_type: FrameType::Inter, |
| 1077 | frame_is_intra: false, |
| 1078 | show_frame: true, |
| 1079 | error_resilient_mode: false, |
| 1080 | disable_cdf_update: false, |
| 1081 | |
| 1082 | |
| 1083 | |
| 1084 | disable_frame_end_update_cdf: false, |
| 1085 | force_integer_mv: false, |
| 1086 | order_hint, |
| 1087 | primary_ref_frame: 0, |
| 1088 | refresh_frame_flags: 1 << self_slot, |
| 1089 | |
| 1090 | |
| 1091 | |
| 1092 | |
| 1093 | |
| 1094 | ref_frame_idx: { |
| 1095 | let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME]; |
| 1096 | idx[3] = GOLDEN_SLOT; |
| 1097 | idx[6] = altref_slot; |
| 1098 | idx |
| 1099 | }, |
| 1100 | allow_high_precision_mv: false, |
| 1101 | interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, |
| 1102 | is_motion_mode_switchable: false, |
| 1103 | use_ref_frame_mvs: false, |
| 1104 | |
| 1105 | |
| 1106 | |
| 1107 | |
| 1108 | |
| 1109 | |
| 1110 | |
| 1111 | |
| 1112 | |
| 1113 | |
| 1114 | |
| 1115 | reduced_tx_set: true, |
| 1116 | ..key |
| 1117 | }; |
| 1118 | Ok((seq, header)) |
| 1119 | } |
| 1120 | |
| 1121 | fn too_large() -> Error { |
| 1122 | Error::unsupported( |
| 1123 | "AV1 encode", |
| 1124 | "the picture is larger than a frame size can carry", |
| 1125 | ) |
| 1126 | } |
| 1127 | |
| 1128 | |
| 1129 | |
| 1130 | struct Plane<'a> { |
| 1131 | source: &'a [u8], |
| 1132 | reconstruction: Vec<u8>, |
| 1133 | width: usize, |
| 1134 | height: usize, |
| 1135 | |
| 1136 | |
| 1137 | |
| 1138 | |
| 1139 | |
| 1140 | |
| 1141 | |
| 1142 | |
| 1143 | |
| 1144 | |
| 1145 | true_width: usize, |
| 1146 | true_height: usize, |
| 1147 | |
| 1148 | |
| 1149 | |
| 1150 | |
| 1151 | |
| 1152 | |
| 1153 | tile_x0: usize, |
| 1154 | tile_y0: usize, |
| 1155 | tile_x1: usize, |
| 1156 | tile_y1: usize, |
| 1157 | } |
| 1158 | |
| 1159 | impl Plane<'_> { |
| 1160 | |
| 1161 | |
| 1162 | |
| 1163 | fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) { |
| 1164 | self.tile_x0 = x0; |
| 1165 | self.tile_y0 = y0; |
| 1166 | self.tile_x1 = x1.min(self.width); |
| 1167 | self.tile_y1 = y1.min(self.height); |
| 1168 | } |
| 1169 | |
| 1170 | |
| 1171 | |
| 1172 | |
| 1173 | |
| 1174 | |
| 1175 | |
| 1176 | |
| 1177 | |
| 1178 | fn edges( |
| 1179 | &self, |
| 1180 | x: usize, |
| 1181 | y: usize, |
| 1182 | side: usize, |
| 1183 | reach: Reach, |
| 1184 | ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) { |
| 1185 | |
| 1186 | |
| 1187 | |
| 1188 | |
| 1189 | |
| 1190 | |
| 1191 | |
| 1192 | |
| 1193 | |
| 1194 | |
| 1195 | |
| 1196 | |
| 1197 | |
| 1198 | |
| 1199 | let own_across = x + side.min(self.true_width.saturating_sub(x)); |
| 1200 | let across = if reach.above_right { |
| 1201 | own_across + side.min(self.true_width.saturating_sub(own_across)) |
| 1202 | } else { |
| 1203 | own_across |
| 1204 | } |
| 1205 | .min(self.width); |
| 1206 | let own_down = y + side.min(self.true_height.saturating_sub(y)); |
| 1207 | let down = if reach.below_left { |
| 1208 | own_down + side.min(self.true_height.saturating_sub(own_down)) |
| 1209 | } else { |
| 1210 | own_down |
| 1211 | } |
| 1212 | .min(self.height); |
| 1213 | |
| 1214 | |
| 1215 | |
| 1216 | |
| 1217 | |
| 1218 | |
| 1219 | |
| 1220 | let across = across.min(self.tile_x1); |
| 1221 | let down = down.min(self.tile_y1); |
| 1222 | let above = (y > self.tile_y0 && across > x) |
| 1223 | .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec()); |
| 1224 | let left = (x > self.tile_x0 && down > y).then(|| { |
| 1225 | (y..down) |
| 1226 | .map(|row| self.reconstruction[row * self.width + x - 1]) |
| 1227 | .collect::<Vec<_>>() |
| 1228 | }); |
| 1229 | let corner = (x > self.tile_x0 && y > self.tile_y0) |
| 1230 | .then(|| self.reconstruction[(y - 1) * self.width + x - 1]); |
| 1231 | (above, left, corner) |
| 1232 | } |
| 1233 | |
| 1234 | |
| 1235 | |
| 1236 | |
| 1237 | fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial { |
| 1238 | self.trial_typed(at, mode, base_q_idx, deadzone, TxType::DctDct, fctx) |
| 1239 | } |
| 1240 | |
| 1241 | |
| 1242 | |
| 1243 | |
| 1244 | |
| 1245 | |
| 1246 | #[allow(clippy::too_many_arguments)] |
| 1247 | fn trial_typed( |
| 1248 | &self, |
| 1249 | at: At, |
| 1250 | mode: u8, |
| 1251 | base_q_idx: u8, |
| 1252 | deadzone: f64, |
| 1253 | tx_type: TxType, |
| 1254 | fctx: &crate::decode::FrameCtx, |
| 1255 | ) -> Trial { |
| 1256 | let At { |
| 1257 | x, y, side, reach, .. |
| 1258 | } = at; |
| 1259 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 1260 | |
| 1261 | |
| 1262 | |
| 1263 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 1264 | let prediction = &mut prediction[..side * side]; |
| 1265 | intra_predict_u8( |
| 1266 | mode, |
| 1267 | 0, |
| 1268 | above.as_deref(), |
| 1269 | left.as_deref(), |
| 1270 | corner, |
| 1271 | side, |
| 1272 | side, |
| 1273 | false, |
| 1274 | false, |
| 1275 | prediction, fctx, |
| 1276 | ); |
| 1277 | |
| 1278 | let mut residual = [0i32; BLOCK * BLOCK]; |
| 1279 | let residual = &mut residual[..side * side]; |
| 1280 | for row in 0..side { |
| 1281 | for col in 0..side { |
| 1282 | residual[row * side + col] = |
| 1283 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 1284 | - i32::from(prediction[row * side + col]); |
| 1285 | } |
| 1286 | } |
| 1287 | #[cfg(test)] |
| 1288 | let t = std::time::Instant::now(); |
| 1289 | let levels = |
| 1290 | forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); |
| 1291 | let coded = |
| 1292 | dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type); |
| 1293 | #[cfg(test)] |
| 1294 | stage_add(2, t.elapsed()); |
| 1295 | |
| 1296 | let mut reconstruction = vec![0u8; side * side]; |
| 1297 | let mut sse = 0.0; |
| 1298 | for row in 0..side { |
| 1299 | for col in 0..side { |
| 1300 | let i = row * side + col; |
| 1301 | let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; |
| 1302 | reconstruction[i] = sample; |
| 1303 | let error = f64::from( |
| 1304 | i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), |
| 1305 | ); |
| 1306 | sse += error * error; |
| 1307 | } |
| 1308 | } |
| 1309 | |
| 1310 | |
| 1311 | |
| 1312 | #[cfg(test)] |
| 1313 | let t = std::time::Instant::now(); |
| 1314 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 1315 | |
| 1316 | |
| 1317 | |
| 1318 | |
| 1319 | levels |
| 1320 | .iter() |
| 1321 | .filter(|&&level| level != 0) |
| 1322 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 1323 | .sum() |
| 1324 | } else { |
| 1325 | crate::tile::coeff_bits(&levels, at.set, crate::decode::q_ctx_of(base_q_idx)) |
| 1326 | }; |
| 1327 | #[cfg(test)] |
| 1328 | stage_add(3, t.elapsed()); |
| 1329 | Trial { |
| 1330 | levels, |
| 1331 | reconstruction, |
| 1332 | sse, |
| 1333 | bits, |
| 1334 | } |
| 1335 | } |
| 1336 | |
| 1337 | |
| 1338 | |
| 1339 | |
| 1340 | |
| 1341 | |
| 1342 | |
| 1343 | #[allow(clippy::too_many_arguments)] |
| 1344 | fn code_from_prediction( |
| 1345 | &self, |
| 1346 | x: usize, |
| 1347 | y: usize, |
| 1348 | side: usize, |
| 1349 | prediction: &[u8], |
| 1350 | skip: bool, |
| 1351 | base_q_idx: u8, |
| 1352 | deadzone: f64, |
| 1353 | set: TxbSet, |
| 1354 | ) -> Trial { |
| 1355 | if skip { |
| 1356 | let mut sse = 0.0; |
| 1357 | for row in 0..side { |
| 1358 | for col in 0..side { |
| 1359 | let error = f64::from( |
| 1360 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 1361 | - i32::from(prediction[row * side + col]), |
| 1362 | ); |
| 1363 | sse += error * error; |
| 1364 | } |
| 1365 | } |
| 1366 | return Trial { |
| 1367 | levels: vec![0i32; side * side], |
| 1368 | reconstruction: prediction.to_vec(), |
| 1369 | sse, |
| 1370 | bits: 0.0, |
| 1371 | }; |
| 1372 | } |
| 1373 | let mut residual = [0i32; BLOCK * BLOCK]; |
| 1374 | let residual = &mut residual[..side * side]; |
| 1375 | for row in 0..side { |
| 1376 | for col in 0..side { |
| 1377 | residual[row * side + col] = |
| 1378 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 1379 | - i32::from(prediction[row * side + col]); |
| 1380 | } |
| 1381 | } |
| 1382 | #[cfg(test)] |
| 1383 | let t = std::time::Instant::now(); |
| 1384 | let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone); |
| 1385 | let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); |
| 1386 | #[cfg(test)] |
| 1387 | stage_add(2, t.elapsed()); |
| 1388 | let mut reconstruction = vec![0u8; side * side]; |
| 1389 | let mut sse = 0.0; |
| 1390 | for row in 0..side { |
| 1391 | for col in 0..side { |
| 1392 | let i = row * side + col; |
| 1393 | let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; |
| 1394 | reconstruction[i] = sample; |
| 1395 | let error = f64::from( |
| 1396 | i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), |
| 1397 | ); |
| 1398 | sse += error * error; |
| 1399 | } |
| 1400 | } |
| 1401 | #[cfg(test)] |
| 1402 | let t = std::time::Instant::now(); |
| 1403 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 1404 | levels |
| 1405 | .iter() |
| 1406 | .filter(|&&level| level != 0) |
| 1407 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 1408 | .sum() |
| 1409 | } else { |
| 1410 | crate::tile::coeff_bits(&levels, set, crate::decode::q_ctx_of(base_q_idx)) |
| 1411 | }; |
| 1412 | #[cfg(test)] |
| 1413 | stage_add(3, t.elapsed()); |
| 1414 | Trial { |
| 1415 | levels, |
| 1416 | reconstruction, |
| 1417 | sse, |
| 1418 | bits, |
| 1419 | } |
| 1420 | } |
| 1421 | |
| 1422 | |
| 1423 | |
| 1424 | |
| 1425 | |
| 1426 | |
| 1427 | |
| 1428 | |
| 1429 | |
| 1430 | fn code_tx_depth( |
| 1431 | &mut self, |
| 1432 | at: At, |
| 1433 | mode: u8, |
| 1434 | depth: usize, |
| 1435 | search: &Search, fctx: &crate::decode::FrameCtx, |
| 1436 | ) -> (Vec<i32>, f64, f64) { |
| 1437 | let At { x, y, side, reach, .. } = at; |
| 1438 | let tx = side >> depth; |
| 1439 | let n = 1usize << depth; |
| 1440 | let set = match tx { |
| 1441 | 32 => TxbSet::Luma32, |
| 1442 | 16 => TxbSet::Luma16, |
| 1443 | 8 => TxbSet::Luma8, |
| 1444 | _ => TxbSet::Luma4, |
| 1445 | }; |
| 1446 | let mut levels = vec![0i32; side * side]; |
| 1447 | census_add(4, n * n); |
| 1448 | let (mut sse, mut bits) = (0.0, 0.0); |
| 1449 | for tu_row in 0..n { |
| 1450 | for tu_col in 0..n { |
| 1451 | let (col_off, row_off) = (tu_col * tx, tu_row * tx); |
| 1452 | let tu = At { |
| 1453 | x: x + col_off, |
| 1454 | y: y + row_off, |
| 1455 | side: tx, |
| 1456 | reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach), |
| 1457 | set, |
| 1458 | }; |
| 1459 | let trial = self.trial(tu, mode, search.base_q_idx, search.deadzone, fctx); |
| 1460 | sse += trial.sse; |
| 1461 | bits += trial.bits; |
| 1462 | self.commit(tu.x, tu.y, tx, &trial); |
| 1463 | for row in 0..tx { |
| 1464 | levels[(row_off + row) * side + col_off..][..tx] |
| 1465 | .copy_from_slice(&trial.levels[row * tx..][..tx]); |
| 1466 | } |
| 1467 | } |
| 1468 | } |
| 1469 | (levels, sse, bits) |
| 1470 | } |
| 1471 | |
| 1472 | |
| 1473 | fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { |
| 1474 | for row in 0..side { |
| 1475 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 1476 | .copy_from_slice(&trial.reconstruction[row * side..][..side]); |
| 1477 | } |
| 1478 | } |
| 1479 | |
| 1480 | |
| 1481 | |
| 1482 | |
| 1483 | |
| 1484 | fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 1485 | (y..y + side) |
| 1486 | .flat_map(|row| self.source[row * self.width + x..][..side].to_vec()) |
| 1487 | .collect() |
| 1488 | } |
| 1489 | |
| 1490 | |
| 1491 | |
| 1492 | fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 1493 | (y..y + side) |
| 1494 | .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec()) |
| 1495 | .collect() |
| 1496 | } |
| 1497 | |
| 1498 | |
| 1499 | fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) { |
| 1500 | for row in 0..side { |
| 1501 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 1502 | .copy_from_slice(&samples[row * side..][..side]); |
| 1503 | } |
| 1504 | } |
| 1505 | |
| 1506 | |
| 1507 | |
| 1508 | |
| 1509 | |
| 1510 | fn intra_scores( |
| 1511 | &self, |
| 1512 | at: At, |
| 1513 | modes: &[u8], |
| 1514 | mode_bits: &[f64; 13], |
| 1515 | lambda: f64, fctx: &crate::decode::FrameCtx, |
| 1516 | ) -> Vec<(f64, u8)> { |
| 1517 | let At { |
| 1518 | x, y, side, reach, .. |
| 1519 | } = at; |
| 1520 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 1521 | modes |
| 1522 | .iter() |
| 1523 | .map(|&mode| { |
| 1524 | let mut prediction = vec![0u8; side * side]; |
| 1525 | intra_predict_u8( |
| 1526 | mode, |
| 1527 | 0, |
| 1528 | above.as_deref(), |
| 1529 | left.as_deref(), |
| 1530 | corner, |
| 1531 | side, |
| 1532 | side, |
| 1533 | false, |
| 1534 | false, |
| 1535 | &mut prediction, fctx, |
| 1536 | ); |
| 1537 | let sad: f64 = (0..side * side) |
| 1538 | .map(|i| { |
| 1539 | let (row, col) = (i / side, i % side); |
| 1540 | f64::from( |
| 1541 | (i32::from(self.source[(y + row) * self.width + x + col]) |
| 1542 | - i32::from(prediction[i])) |
| 1543 | .abs(), |
| 1544 | ) |
| 1545 | }) |
| 1546 | .sum(); |
| 1547 | (sad + lambda * mode_bits[usize::from(mode)], mode) |
| 1548 | }) |
| 1549 | .collect() |
| 1550 | } |
| 1551 | |
| 1552 | |
| 1553 | |
| 1554 | |
| 1555 | |
| 1556 | |
| 1557 | |
| 1558 | |
| 1559 | |
| 1560 | |
| 1561 | |
| 1562 | fn search_block( |
| 1563 | &mut self, |
| 1564 | at: At, |
| 1565 | search: &Search, |
| 1566 | mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx, |
| 1567 | ) -> (Vec<Coeff>, u8, f64) { |
| 1568 | let At { |
| 1569 | x, y, side, reach, .. |
| 1570 | } = at; |
| 1571 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 1572 | |
| 1573 | |
| 1574 | |
| 1575 | |
| 1576 | let want_sad = search.top_k.is_some() || census_on(); |
| 1577 | let mut scored: Vec<(f64, u8, Vec<u8>)> = search |
| 1578 | .modes |
| 1579 | .iter() |
| 1580 | .map(|&mode| { |
| 1581 | let mut prediction = vec![0u8; side * side]; |
| 1582 | intra_predict_u8( |
| 1583 | mode, |
| 1584 | 0, |
| 1585 | above.as_deref(), |
| 1586 | left.as_deref(), |
| 1587 | corner, |
| 1588 | side, |
| 1589 | side, |
| 1590 | false, |
| 1591 | false, |
| 1592 | &mut prediction, fctx, |
| 1593 | ); |
| 1594 | let sad: f64 = if want_sad { |
| 1595 | (0..side * side) |
| 1596 | .map(|i| { |
| 1597 | let (row, col) = (i / side, i % side); |
| 1598 | f64::from( |
| 1599 | (i32::from(self.source[(y + row) * self.width + x + col]) |
| 1600 | - i32::from(prediction[i])) |
| 1601 | .abs(), |
| 1602 | ) |
| 1603 | }) |
| 1604 | .sum() |
| 1605 | } else { |
| 1606 | 0.0 |
| 1607 | }; |
| 1608 | ( |
| 1609 | sad + search.lambda * mode_bits[usize::from(mode)], |
| 1610 | mode, |
| 1611 | prediction, |
| 1612 | ) |
| 1613 | }) |
| 1614 | .collect(); |
| 1615 | if let Some(k) = search.top_k { |
| 1616 | if k < scored.len() { |
| 1617 | let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED); |
| 1618 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 1619 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 1620 | scored.truncate(if dc_entry.is_some() { |
| 1621 | k.saturating_sub(1) |
| 1622 | } else { |
| 1623 | k |
| 1624 | }); |
| 1625 | if let Some(dc_entry) = dc_entry { |
| 1626 | scored.push(dc_entry); |
| 1627 | } |
| 1628 | } |
| 1629 | } |
| 1630 | let ranking: Vec<(f64, u8)> = if census_on() { |
| 1631 | scored.iter().map(|&(score, mode, _)| (score, mode)).collect() |
| 1632 | } else { |
| 1633 | Vec::new() |
| 1634 | }; |
| 1635 | census_add(0, 1); |
| 1636 | census_add(1, scored.len()); |
| 1637 | let mut best: Option<(f64, u8, Trial)> = None; |
| 1638 | for (_, mode, prediction) in scored { |
| 1639 | let trial = self.code_from_prediction( |
| 1640 | x, |
| 1641 | y, |
| 1642 | side, |
| 1643 | &prediction, |
| 1644 | false, |
| 1645 | search.base_q_idx, |
| 1646 | search.deadzone, |
| 1647 | at.set, |
| 1648 | ); |
| 1649 | let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]); |
| 1650 | if best |
| 1651 | .as_ref() |
| 1652 | .is_none_or(|(best_cost, _, _)| cost < *best_cost) |
| 1653 | { |
| 1654 | best = Some((cost, mode, trial)); |
| 1655 | } |
| 1656 | } |
| 1657 | let (cost, mode, trial) = best.expect("the search offers at least one mode"); |
| 1658 | if census_on() { |
| 1659 | LUMA_RANK[sad_rank(&ranking, mode).min(12)] |
| 1660 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1661 | } |
| 1662 | self.commit(x, y, side, &trial); |
| 1663 | (coeffs(&trial.levels, side), mode, cost) |
| 1664 | } |
| 1665 | } |
| 1666 | |
| 1667 | |
| 1668 | |
| 1669 | #[derive(Clone, Copy)] |
| 1670 | struct At { |
| 1671 | x: usize, |
| 1672 | y: usize, |
| 1673 | side: usize, |
| 1674 | reach: Reach, |
| 1675 | |
| 1676 | |
| 1677 | set: TxbSet, |
| 1678 | } |
| 1679 | |
| 1680 | |
| 1681 | |
| 1682 | |
| 1683 | |
| 1684 | |
| 1685 | |
| 1686 | |
| 1687 | |
| 1688 | |
| 1689 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1690 | pub(crate) struct Reach { |
| 1691 | pub(crate) above_right: bool, |
| 1692 | pub(crate) below_left: bool, |
| 1693 | } |
| 1694 | |
| 1695 | |
| 1696 | |
| 1697 | |
| 1698 | |
| 1699 | |
| 1700 | |
| 1701 | const HAS_TOP_RIGHT: [&[u8]; 4] = [ |
| 1702 | &[255, 85, 119, 85, 127, 85, 119, 85], |
| 1703 | &[95, 87], |
| 1704 | |
| 1705 | |
| 1706 | &[ |
| 1707 | 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85, |
| 1708 | 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, |
| 1709 | ], |
| 1710 | |
| 1711 | |
| 1712 | |
| 1713 | |
| 1714 | |
| 1715 | |
| 1716 | |
| 1717 | |
| 1718 | &[ |
| 1719 | 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, |
| 1720 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85, |
| 1721 | 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, |
| 1722 | 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, |
| 1723 | 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, |
| 1724 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, |
| 1725 | 119, 119, 119, 119, 85, 85, 85, 85, |
| 1726 | ], |
| 1727 | ]; |
| 1728 | |
| 1729 | |
| 1730 | |
| 1731 | const HAS_BOTTOM_LEFT: [&[u8]; 4] = [ |
| 1732 | &[84, 16, 84, 0, 84, 16, 84, 0], |
| 1733 | &[4, 4], |
| 1734 | |
| 1735 | &[ |
| 1736 | 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1, |
| 1737 | 84, 85, 16, 17, 84, 85, 0, 0, |
| 1738 | ], |
| 1739 | |
| 1740 | |
| 1741 | &[ |
| 1742 | 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, |
| 1743 | 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, |
| 1744 | 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, |
| 1745 | 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, |
| 1746 | 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, |
| 1747 | 85, 85, 0, 0, 0, 0, |
| 1748 | ], |
| 1749 | ]; |
| 1750 | |
| 1751 | |
| 1752 | |
| 1753 | |
| 1754 | |
| 1755 | |
| 1756 | |
| 1757 | |
| 1758 | |
| 1759 | |
| 1760 | const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [ |
| 1761 | |
| 1762 | &[255, 0, 119, 0, 127, 0, 119, 0], |
| 1763 | |
| 1764 | &[15, 7], |
| 1765 | |
| 1766 | &[ |
| 1767 | 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119, |
| 1768 | 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, |
| 1769 | ], |
| 1770 | ]; |
| 1771 | |
| 1772 | |
| 1773 | const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [ |
| 1774 | |
| 1775 | &[254, 16, 254, 0, 254, 16, 254, 0], |
| 1776 | |
| 1777 | &[14, 14], |
| 1778 | |
| 1779 | &[ |
| 1780 | 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254, |
| 1781 | 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, |
| 1782 | ], |
| 1783 | ]; |
| 1784 | |
| 1785 | thread_local! { |
| 1786 | |
| 1787 | |
| 1788 | |
| 1789 | |
| 1790 | |
| 1791 | |
| 1792 | static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 1793 | } |
| 1794 | |
| 1795 | |
| 1796 | pub(crate) struct VertAbGuard(bool); |
| 1797 | |
| 1798 | impl Drop for VertAbGuard { |
| 1799 | fn drop(&mut self) { |
| 1800 | VERT_AB_PARTITION.with(|c| c.set(self.0)); |
| 1801 | } |
| 1802 | } |
| 1803 | |
| 1804 | |
| 1805 | |
| 1806 | |
| 1807 | |
| 1808 | |
| 1809 | |
| 1810 | |
| 1811 | |
| 1812 | |
| 1813 | |
| 1814 | |
| 1815 | |
| 1816 | |
| 1817 | |
| 1818 | const HAS_TR_4X8: [u8; 64] = [255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119]; |
| 1819 | |
| 1820 | const HAS_BL_4X8: [u8; 64] = [16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0]; |
| 1821 | |
| 1822 | const HAS_TR_8X4: [u8; 64] = [255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0]; |
| 1823 | |
| 1824 | const HAS_BL_8X4: [u8; 64] = [254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0]; |
| 1825 | |
| 1826 | const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119]; |
| 1827 | |
| 1828 | const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0]; |
| 1829 | |
| 1830 | const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0]; |
| 1831 | |
| 1832 | const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0]; |
| 1833 | |
| 1834 | const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119]; |
| 1835 | |
| 1836 | const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0]; |
| 1837 | |
| 1838 | const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5]; |
| 1839 | |
| 1840 | const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14]; |
| 1841 | |
| 1842 | const HAS_TR_32X64: [u8; 1] = [127]; |
| 1843 | |
| 1844 | const HAS_BL_32X64: [u8; 1] = [0]; |
| 1845 | |
| 1846 | const HAS_TR_64X32: [u8; 1] = [19]; |
| 1847 | |
| 1848 | const HAS_BL_64X32: [u8; 1] = [34]; |
| 1849 | |
| 1850 | const HAS_TR_4X16: [u8; 32] = [255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127]; |
| 1851 | |
| 1852 | const HAS_BL_4X16: [u8; 32] = [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0]; |
| 1853 | |
| 1854 | const HAS_TR_16X4: [u8; 32] = [255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0]; |
| 1855 | |
| 1856 | const HAS_BL_16X4: [u8; 32] = [254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0]; |
| 1857 | |
| 1858 | const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127]; |
| 1859 | |
| 1860 | const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0]; |
| 1861 | |
| 1862 | const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0]; |
| 1863 | |
| 1864 | const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14]; |
| 1865 | |
| 1866 | const HAS_TR_16X64: [u8; 2] = [255, 127]; |
| 1867 | |
| 1868 | const HAS_BL_16X64: [u8; 2] = [0, 0]; |
| 1869 | |
| 1870 | const HAS_TR_64X16: [u8; 2] = [3, 1]; |
| 1871 | |
| 1872 | const HAS_BL_64X16: [u8; 2] = [42, 42]; |
| 1873 | |
| 1874 | |
| 1875 | fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) { |
| 1876 | match (bw, bh) { |
| 1877 | (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8), |
| 1878 | (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4), |
| 1879 | (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16), |
| 1880 | (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8), |
| 1881 | (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32), |
| 1882 | (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16), |
| 1883 | (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64), |
| 1884 | (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32), |
| 1885 | (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16), |
| 1886 | (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4), |
| 1887 | (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32), |
| 1888 | (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8), |
| 1889 | (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64), |
| 1890 | (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16), |
| 1891 | _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"), |
| 1892 | } |
| 1893 | } |
| 1894 | |
| 1895 | impl Reach { |
| 1896 | |
| 1897 | |
| 1898 | |
| 1899 | |
| 1900 | |
| 1901 | |
| 1902 | |
| 1903 | |
| 1904 | |
| 1905 | |
| 1906 | |
| 1907 | |
| 1908 | |
| 1909 | |
| 1910 | pub(crate) fn of_tu( |
| 1911 | bw: usize, |
| 1912 | bh: usize, |
| 1913 | col_off: usize, |
| 1914 | row_off: usize, |
| 1915 | |
| 1916 | |
| 1917 | |
| 1918 | tx_w: usize, |
| 1919 | tx_h: usize, |
| 1920 | block: Self, |
| 1921 | ) -> Self { |
| 1922 | |
| 1923 | |
| 1924 | |
| 1925 | |
| 1926 | let wide = bw > 64; |
| 1927 | Self { |
| 1928 | above_right: if row_off > 0 { |
| 1929 | |
| 1930 | |
| 1931 | |
| 1932 | if wide { |
| 1933 | (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64 |
| 1934 | } else { |
| 1935 | col_off + tx_w < bw |
| 1936 | } |
| 1937 | } else if col_off + tx_w < bw { |
| 1938 | true |
| 1939 | } else { |
| 1940 | block.above_right |
| 1941 | }, |
| 1942 | below_left: if wide && col_off > 0 && col_off % 64 == 0 { |
| 1943 | |
| 1944 | |
| 1945 | |
| 1946 | (row_off % 64) + tx_h < bh.min(64) |
| 1947 | } else if col_off > 0 { |
| 1948 | false |
| 1949 | } else if row_off + tx_h < bh { |
| 1950 | true |
| 1951 | } else { |
| 1952 | block.below_left |
| 1953 | }, |
| 1954 | } |
| 1955 | } |
| 1956 | |
| 1957 | |
| 1958 | |
| 1959 | pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self { |
| 1960 | Self { |
| 1961 | above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx), |
| 1962 | below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx), |
| 1963 | } |
| 1964 | } |
| 1965 | |
| 1966 | |
| 1967 | |
| 1968 | |
| 1969 | |
| 1970 | |
| 1971 | pub(crate) fn of_rect( |
| 1972 | bw: usize, |
| 1973 | bh: usize, |
| 1974 | x: usize, |
| 1975 | y: usize, |
| 1976 | width: usize, |
| 1977 | height: usize, fctx: &crate::decode::FrameCtx, |
| 1978 | ) -> Self { |
| 1979 | Self { |
| 1980 | above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx), |
| 1981 | below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx), |
| 1982 | } |
| 1983 | } |
| 1984 | |
| 1985 | |
| 1986 | |
| 1987 | |
| 1988 | |
| 1989 | |
| 1990 | |
| 1991 | |
| 1992 | |
| 1993 | |
| 1994 | |
| 1995 | |
| 1996 | |
| 1997 | |
| 1998 | |
| 1999 | fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 2000 | let sb_mi: usize = reach_sb_px(fctx) / 4; |
| 2001 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 2002 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 2003 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 2004 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 2005 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 2006 | |
| 2007 | |
| 2008 | if blk_row == 0 { |
| 2009 | return true; |
| 2010 | } |
| 2011 | |
| 2012 | if ((blk_col + 1) << bw_log2) >= sb_mi { |
| 2013 | return false; |
| 2014 | } |
| 2015 | let table = rect_reach_tables(bw, bh).0; |
| 2016 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 2017 | } |
| 2018 | |
| 2019 | |
| 2020 | |
| 2021 | |
| 2022 | |
| 2023 | |
| 2024 | |
| 2025 | |
| 2026 | |
| 2027 | fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize { |
| 2028 | (blk_row << (5 - bw_log2)) + blk_col |
| 2029 | } |
| 2030 | |
| 2031 | |
| 2032 | fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 2033 | let sb_mi: usize = reach_sb_px(fctx) / 4; |
| 2034 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 2035 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 2036 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 2037 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 2038 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 2039 | |
| 2040 | |
| 2041 | if blk_col == 0 { |
| 2042 | return (blk_row << bh_log2) + (bh / 4) < sb_mi; |
| 2043 | } |
| 2044 | |
| 2045 | |
| 2046 | if ((blk_row + 1) << bh_log2) >= sb_mi { |
| 2047 | return false; |
| 2048 | } |
| 2049 | let table = rect_reach_tables(bw, bh).1; |
| 2050 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 2051 | } |
| 2052 | |
| 2053 | |
| 2054 | |
| 2055 | |
| 2056 | |
| 2057 | |
| 2058 | |
| 2059 | |
| 2060 | |
| 2061 | pub(crate) fn in_vert_ab() -> bool { |
| 2062 | VERT_AB_PARTITION.with(std::cell::Cell::get) |
| 2063 | } |
| 2064 | |
| 2065 | pub(crate) fn vert_ab_partition() -> VertAbGuard { |
| 2066 | VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true))) |
| 2067 | } |
| 2068 | |
| 2069 | |
| 2070 | |
| 2071 | pub(crate) fn none() -> Self { |
| 2072 | Self { |
| 2073 | above_right: false, |
| 2074 | below_left: false, |
| 2075 | } |
| 2076 | } |
| 2077 | |
| 2078 | |
| 2079 | |
| 2080 | |
| 2081 | |
| 2082 | fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 2083 | let (row, col, per_side) = Self::position(side, x, y, fctx); |
| 2084 | if row == 0 { |
| 2085 | return true; |
| 2086 | } |
| 2087 | if col + 1 == per_side { |
| 2088 | return false; |
| 2089 | } |
| 2090 | |
| 2091 | |
| 2092 | |
| 2093 | |
| 2094 | |
| 2095 | |
| 2096 | |
| 2097 | |
| 2098 | |
| 2099 | |
| 2100 | |
| 2101 | let table_row = Self::table(side); |
| 2102 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() { |
| 2103 | HAS_TOP_RIGHT_VERT[table_row] |
| 2104 | } else { |
| 2105 | HAS_TOP_RIGHT[table_row] |
| 2106 | }; |
| 2107 | Self::bit( |
| 2108 | table, |
| 2109 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 2110 | ) |
| 2111 | } |
| 2112 | |
| 2113 | |
| 2114 | |
| 2115 | |
| 2116 | |
| 2117 | fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 2118 | let (row, col, per_side) = Self::position(side, x, y, fctx); |
| 2119 | if col == 0 { |
| 2120 | return row * side + side < reach_sb_px(fctx); |
| 2121 | } |
| 2122 | if row + 1 == per_side { |
| 2123 | return false; |
| 2124 | } |
| 2125 | |
| 2126 | |
| 2127 | |
| 2128 | |
| 2129 | |
| 2130 | |
| 2131 | |
| 2132 | |
| 2133 | |
| 2134 | |
| 2135 | |
| 2136 | let table_row = Self::table(side); |
| 2137 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() { |
| 2138 | HAS_BOTTOM_LEFT_VERT[table_row] |
| 2139 | } else { |
| 2140 | HAS_BOTTOM_LEFT[table_row] |
| 2141 | }; |
| 2142 | Self::bit( |
| 2143 | table, |
| 2144 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 2145 | ) |
| 2146 | } |
| 2147 | |
| 2148 | |
| 2149 | |
| 2150 | fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) { |
| 2151 | let sb = reach_sb_px(fctx); |
| 2152 | ((y % sb) / side, (x % sb) / side, sb / side) |
| 2153 | } |
| 2154 | |
| 2155 | |
| 2156 | |
| 2157 | |
| 2158 | |
| 2159 | |
| 2160 | |
| 2161 | |
| 2162 | |
| 2163 | fn table_stride(side: usize) -> usize { |
| 2164 | 128 / side |
| 2165 | } |
| 2166 | |
| 2167 | |
| 2168 | fn table(side: usize) -> usize { |
| 2169 | if side == BLOCK { |
| 2170 | 1 |
| 2171 | } else if side == 8 { |
| 2172 | 2 |
| 2173 | } else if side == 4 { |
| 2174 | 3 |
| 2175 | } else { |
| 2176 | 0 |
| 2177 | } |
| 2178 | } |
| 2179 | |
| 2180 | |
| 2181 | fn bit(table: &[u8], index: usize) -> bool { |
| 2182 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 2183 | } |
| 2184 | } |
| 2185 | |
| 2186 | |
| 2187 | pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { |
| 2188 | let low = if symbol == 0 { 0 } else { cdf[symbol - 1] }; |
| 2189 | let width = cdf[symbol] - low; |
| 2190 | |
| 2191 | |
| 2192 | |
| 2193 | |
| 2194 | |
| 2195 | |
| 2196 | static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new(); |
| 2197 | PRICES.get_or_init(|| { |
| 2198 | (0..=32768u32) |
| 2199 | .map(|w| -(f64::from(w) / 32768.0).log2()) |
| 2200 | .collect() |
| 2201 | })[usize::from(width)] |
| 2202 | } |
| 2203 | |
| 2204 | |
| 2205 | |
| 2206 | |
| 2207 | |
| 2208 | |
| 2209 | |
| 2210 | |
| 2211 | |
| 2212 | |
| 2213 | |
| 2214 | |
| 2215 | |
| 2216 | |
| 2217 | |
| 2218 | |
| 2219 | fn max_tx_depth(side: usize) -> usize { |
| 2220 | match side { |
| 2221 | 8 => 1, |
| 2222 | 16 | 32 => 2, |
| 2223 | _ => 0, |
| 2224 | } |
| 2225 | } |
| 2226 | |
| 2227 | |
| 2228 | |
| 2229 | |
| 2230 | |
| 2231 | |
| 2232 | fn tx_depth_bits(side: usize, depth: usize) -> f64 { |
| 2233 | match side { |
| 2234 | 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth), |
| 2235 | 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth), |
| 2236 | 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth), |
| 2237 | _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth), |
| 2238 | } |
| 2239 | } |
| 2240 | |
| 2241 | |
| 2242 | |
| 2243 | static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] = |
| 2244 | [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; |
| 2245 | |
| 2246 | |
| 2247 | |
| 2248 | #[cfg(test)] |
| 2249 | pub(crate) fn take_tx_depth_hits() -> [usize; 3] { |
| 2250 | std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 2251 | } |
| 2252 | |
| 2253 | |
| 2254 | |
| 2255 | |
| 2256 | static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] = |
| 2257 | [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; |
| 2258 | |
| 2259 | |
| 2260 | |
| 2261 | |
| 2262 | |
| 2263 | |
| 2264 | static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] = |
| 2265 | [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; |
| 2266 | |
| 2267 | |
| 2268 | #[cfg(test)] |
| 2269 | pub(crate) fn take_ref_frame_hits() -> [usize; 8] { |
| 2270 | std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 2271 | } |
| 2272 | |
| 2273 | |
| 2274 | #[cfg(test)] |
| 2275 | pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] { |
| 2276 | std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 2277 | } |
| 2278 | |
| 2279 | |
| 2280 | |
| 2281 | |
| 2282 | |
| 2283 | |
| 2284 | fn txfm_split_bits(side: usize, depth: usize) -> f64 { |
| 2285 | let max_tx = side.min(64); |
| 2286 | let ctx = |tx: usize| { |
| 2287 | crate::decode::txfm_partition_ctx_rect( |
| 2288 | crate::decode::TXFM_CTX_INIT, |
| 2289 | crate::decode::TXFM_CTX_INIT, |
| 2290 | side, |
| 2291 | tx, |
| 2292 | tx, |
| 2293 | ) |
| 2294 | }; |
| 2295 | if depth == 0 { |
| 2296 | return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0); |
| 2297 | } |
| 2298 | symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1) |
| 2299 | + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0) |
| 2300 | } |
| 2301 | |
| 2302 | |
| 2303 | |
| 2304 | |
| 2305 | |
| 2306 | |
| 2307 | |
| 2308 | |
| 2309 | |
| 2310 | |
| 2311 | |
| 2312 | |
| 2313 | |
| 2314 | |
| 2315 | |
| 2316 | #[allow(clippy::too_many_arguments)] |
| 2317 | fn commit_inter_luma( |
| 2318 | luma: &mut Plane, |
| 2319 | (x, y): (usize, usize), |
| 2320 | side: usize, |
| 2321 | mv: (i32, i32), |
| 2322 | reference: (&[u16], usize, usize, usize), |
| 2323 | search: &Search, |
| 2324 | flat: &Trial, |
| 2325 | skip: bool, fctx: &crate::decode::FrameCtx, |
| 2326 | ) -> (Vec<i32>, u8, f64) { |
| 2327 | let eligible = tx_select() |
| 2328 | && tx_select_inter() |
| 2329 | && !skip |
| 2330 | && side >= 16 |
| 2331 | && x + side <= luma.true_width |
| 2332 | && y + side <= luma.true_height; |
| 2333 | if !eligible { |
| 2334 | luma.commit(x, y, side, flat); |
| 2335 | return (flat.levels.clone(), 0, 0.0); |
| 2336 | } |
| 2337 | let tx = side / 2; |
| 2338 | let set = if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter }; |
| 2339 | let mut levels = vec![0i32; side * side]; |
| 2340 | let (mut sse, mut bits) = (0.0, 0.0); |
| 2341 | let mut units = Vec::with_capacity(4); |
| 2342 | for tu_row in 0..2 { |
| 2343 | for tu_col in 0..2 { |
| 2344 | let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx); |
| 2345 | let trial = mc_trial( |
| 2346 | luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2, |
| 2347 | reference.3, false, search.base_q_idx, search.deadzone, set, fctx, |
| 2348 | ); |
| 2349 | sse += trial.sse; |
| 2350 | bits += trial.bits; |
| 2351 | for row in 0..tx { |
| 2352 | levels[(tu_row * tx + row) * side + tu_col * tx..][..tx] |
| 2353 | .copy_from_slice(&trial.levels[row * tx..][..tx]); |
| 2354 | } |
| 2355 | units.push((tu_x, tu_y, trial)); |
| 2356 | } |
| 2357 | } |
| 2358 | let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1)); |
| 2359 | let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0)); |
| 2360 | if split_cost < flat_cost { |
| 2361 | for (tu_x, tu_y, trial) in &units { |
| 2362 | luma.commit(*tu_x, *tu_y, tx, trial); |
| 2363 | } |
| 2364 | INTER_TX_SPLIT_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2365 | return (levels, 1, split_cost - flat_cost); |
| 2366 | } |
| 2367 | INTER_TX_SPLIT_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2368 | luma.commit(x, y, side, flat); |
| 2369 | (flat.levels.clone(), 0, 0.0) |
| 2370 | } |
| 2371 | |
| 2372 | |
| 2373 | |
| 2374 | |
| 2375 | |
| 2376 | |
| 2377 | |
| 2378 | |
| 2379 | |
| 2380 | |
| 2381 | |
| 2382 | |
| 2383 | |
| 2384 | |
| 2385 | fn palette_max_colors() -> usize { |
| 2386 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 2387 | *N.get_or_init(|| { |
| 2388 | std::env::var("EC_AV1_PAL_MAXCOLORS") |
| 2389 | .ok() |
| 2390 | .and_then(|v| v.parse().ok()) |
| 2391 | .unwrap_or(128) |
| 2392 | }) |
| 2393 | } |
| 2394 | |
| 2395 | |
| 2396 | |
| 2397 | |
| 2398 | |
| 2399 | |
| 2400 | |
| 2401 | |
| 2402 | fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> { |
| 2403 | let mut histogram = [0u32; 256]; |
| 2404 | for &v in block { |
| 2405 | histogram[usize::from(v)] += 1; |
| 2406 | } |
| 2407 | let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect(); |
| 2408 | if present.len() < 2 { |
| 2409 | return Vec::new(); |
| 2410 | } |
| 2411 | let exact = |colors: &[u16]| -> crate::tile::PaletteY { |
| 2412 | let mut base = [0u16; 8]; |
| 2413 | base[..colors.len()].copy_from_slice(colors); |
| 2414 | let map = block |
| 2415 | .iter() |
| 2416 | .map(|&v| { |
| 2417 | colors |
| 2418 | .iter() |
| 2419 | .enumerate() |
| 2420 | .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs()) |
| 2421 | .map(|(i, _)| i as u8) |
| 2422 | .expect("a palette holds at least two colours") |
| 2423 | }) |
| 2424 | .collect(); |
| 2425 | crate::tile::PaletteY { size: colors.len() as u8, colors: base, map } |
| 2426 | }; |
| 2427 | if present.len() <= 8 { |
| 2428 | return vec![exact(&present)]; |
| 2429 | } |
| 2430 | if present.len() > palette_max_colors() { |
| 2431 | return Vec::new(); |
| 2432 | } |
| 2433 | let (lo, hi) = ( |
| 2434 | i32::from(present[0]), |
| 2435 | i32::from(present[present.len() - 1]), |
| 2436 | ); |
| 2437 | let mut out = Vec::with_capacity(2); |
| 2438 | for n in [8usize, 4] { |
| 2439 | |
| 2440 | |
| 2441 | let mut centres: Vec<f64> = (0..n) |
| 2442 | .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64) |
| 2443 | .collect(); |
| 2444 | for _ in 0..4 { |
| 2445 | let mut sums = vec![0f64; n]; |
| 2446 | let mut counts = vec![0u32; n]; |
| 2447 | for (v, &count) in histogram.iter().enumerate() { |
| 2448 | if count == 0 { |
| 2449 | continue; |
| 2450 | } |
| 2451 | let k = (0..n) |
| 2452 | .min_by(|&a, &b| { |
| 2453 | (centres[a] - v as f64) |
| 2454 | .abs() |
| 2455 | .total_cmp(&(centres[b] - v as f64).abs()) |
| 2456 | }) |
| 2457 | .expect("n >= 2"); |
| 2458 | sums[k] += (v as u32 * count) as f64; |
| 2459 | counts[k] += count; |
| 2460 | } |
| 2461 | for k in 0..n { |
| 2462 | if counts[k] > 0 { |
| 2463 | centres[k] = sums[k] / f64::from(counts[k]); |
| 2464 | } |
| 2465 | } |
| 2466 | } |
| 2467 | let mut colors: Vec<u16> = centres |
| 2468 | .iter() |
| 2469 | .map(|&c| c.round().clamp(0.0, 255.0) as u16) |
| 2470 | .collect(); |
| 2471 | colors.sort_unstable(); |
| 2472 | colors.dedup(); |
| 2473 | if colors.len() >= 2 { |
| 2474 | out.push(exact(&colors)); |
| 2475 | } |
| 2476 | } |
| 2477 | out |
| 2478 | } |
| 2479 | |
| 2480 | #[allow(clippy::too_many_arguments)] |
| 2481 | |
| 2482 | |
| 2483 | |
| 2484 | |
| 2485 | |
| 2486 | |
| 2487 | |
| 2488 | |
| 2489 | |
| 2490 | |
| 2491 | |
| 2492 | |
| 2493 | |
| 2494 | |
| 2495 | |
| 2496 | |
| 2497 | |
| 2498 | |
| 2499 | fn intrabc_enabled() -> bool { |
| 2500 | if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) { |
| 2501 | return forced; |
| 2502 | } |
| 2503 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 2504 | *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1")) |
| 2505 | } |
| 2506 | |
| 2507 | thread_local! { |
| 2508 | |
| 2509 | |
| 2510 | |
| 2511 | |
| 2512 | static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; |
| 2513 | } |
| 2514 | |
| 2515 | #[allow(dead_code)] |
| 2516 | pub(crate) fn force_intrabc(value: Option<bool>) { |
| 2517 | INTRABC_FORCE.with(|c| c.set(value)); |
| 2518 | } |
| 2519 | |
| 2520 | |
| 2521 | |
| 2522 | |
| 2523 | |
| 2524 | |
| 2525 | fn intrabc_pct() -> usize { |
| 2526 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 2527 | *N.get_or_init(|| { |
| 2528 | std::env::var("EC_AV1_INTRABC_PCT") |
| 2529 | .ok() |
| 2530 | .and_then(|v| v.parse().ok()) |
| 2531 | .unwrap_or(10) |
| 2532 | }) |
| 2533 | } |
| 2534 | |
| 2535 | |
| 2536 | |
| 2537 | |
| 2538 | |
| 2539 | |
| 2540 | |
| 2541 | fn intrabc_step() -> usize { |
| 2542 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 2543 | *N.get_or_init(|| { |
| 2544 | let n: usize = std::env::var("EC_AV1_INTRABC_STEP") |
| 2545 | .ok() |
| 2546 | .and_then(|v| v.parse().ok()) |
| 2547 | .unwrap_or(4); |
| 2548 | if n % 2 == 0 { n.max(2) } else { 4 } |
| 2549 | }) |
| 2550 | } |
| 2551 | |
| 2552 | |
| 2553 | const IBC_HASH: usize = 16; |
| 2554 | |
| 2555 | |
| 2556 | |
| 2557 | const INTRABC_DELAY_SB64: i32 = 4; |
| 2558 | |
| 2559 | |
| 2560 | fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 { |
| 2561 | let mut h: u64 = 0xcbf2_9ce4_8422_2325; |
| 2562 | for row in 0..IBC_HASH { |
| 2563 | let base = (y + row) * width + x; |
| 2564 | for &v in &plane[base..base + IBC_HASH] { |
| 2565 | h ^= u64::from(v); |
| 2566 | h = h.wrapping_mul(0x100_0000_01b3); |
| 2567 | } |
| 2568 | } |
| 2569 | h |
| 2570 | } |
| 2571 | |
| 2572 | |
| 2573 | |
| 2574 | fn ibc_index( |
| 2575 | table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>, |
| 2576 | plane: &[u8], |
| 2577 | width: usize, |
| 2578 | (x0, y0): (usize, usize), |
| 2579 | (x1, y1): (usize, usize), |
| 2580 | ) { |
| 2581 | let step = intrabc_step(); |
| 2582 | if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH { |
| 2583 | return; |
| 2584 | } |
| 2585 | let mut y = y0.next_multiple_of(step); |
| 2586 | while y + IBC_HASH <= y1 { |
| 2587 | let mut x = x0.next_multiple_of(step); |
| 2588 | while x + IBC_HASH <= x1 { |
| 2589 | table |
| 2590 | .entry(ibc_hash(plane, width, x, y)) |
| 2591 | .or_default() |
| 2592 | .push((x as u32, y as u32)); |
| 2593 | x += step; |
| 2594 | } |
| 2595 | y += step; |
| 2596 | } |
| 2597 | } |
| 2598 | |
| 2599 | |
| 2600 | |
| 2601 | |
| 2602 | |
| 2603 | fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) { |
| 2604 | if true_width < 4 * 64 || true_height < 2 * 64 { |
| 2605 | return (false, 0.0); |
| 2606 | } |
| 2607 | let mut table = std::collections::HashMap::new(); |
| 2608 | ibc_index(&mut table, y, width, (0, 0), (true_width, true_height)); |
| 2609 | let (mut total, mut matched) = (0usize, 0usize); |
| 2610 | let mut by = 0; |
| 2611 | while by + IBC_HASH <= true_height { |
| 2612 | let mut bx = 0; |
| 2613 | while bx + IBC_HASH <= true_width { |
| 2614 | total += 1; |
| 2615 | if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) { |
| 2616 | if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) { |
| 2617 | matched += 1; |
| 2618 | } |
| 2619 | } |
| 2620 | bx += IBC_HASH; |
| 2621 | } |
| 2622 | by += IBC_HASH; |
| 2623 | } |
| 2624 | let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 }; |
| 2625 | (share * 100.0 >= intrabc_pct() as f64, share) |
| 2626 | } |
| 2627 | |
| 2628 | |
| 2629 | |
| 2630 | |
| 2631 | |
| 2632 | |
| 2633 | struct Ibc { |
| 2634 | |
| 2635 | |
| 2636 | |
| 2637 | |
| 2638 | |
| 2639 | table: std::collections::HashMap<u64, Vec<(u32, u32)>>, |
| 2640 | |
| 2641 | tile: (usize, usize, usize, usize), |
| 2642 | |
| 2643 | |
| 2644 | |
| 2645 | |
| 2646 | |
| 2647 | last_dv: Option<(i32, i32)>, |
| 2648 | |
| 2649 | |
| 2650 | hits: usize, |
| 2651 | lookups: usize, |
| 2652 | found: usize, |
| 2653 | } |
| 2654 | |
| 2655 | impl Ibc { |
| 2656 | fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self { |
| 2657 | let mut table = std::collections::HashMap::new(); |
| 2658 | ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3)); |
| 2659 | Self { |
| 2660 | table, |
| 2661 | tile, |
| 2662 | last_dv: None, |
| 2663 | hits: 0, |
| 2664 | lookups: 0, |
| 2665 | found: 0, |
| 2666 | } |
| 2667 | } |
| 2668 | |
| 2669 | |
| 2670 | |
| 2671 | |
| 2672 | |
| 2673 | |
| 2674 | |
| 2675 | |
| 2676 | fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool { |
| 2677 | let (dr, dc) = (dv.0 / 8, dv.1 / 8); |
| 2678 | if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 { |
| 2679 | return false; |
| 2680 | } |
| 2681 | let (tx0, ty0, tx1, ty1) = ( |
| 2682 | self.tile.0 as i32, |
| 2683 | self.tile.1 as i32, |
| 2684 | self.tile.2 as i32, |
| 2685 | self.tile.3 as i32, |
| 2686 | ); |
| 2687 | let (sx, sy) = (x as i32 + dc, y as i32 + dr); |
| 2688 | let (w, h) = (w as i32, h as i32); |
| 2689 | if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 { |
| 2690 | return false; |
| 2691 | } |
| 2692 | let active_sb_row = (y as i32 - ty0) >> 6; |
| 2693 | let active_sb_col = (x as i32 - tx0) >> 6; |
| 2694 | let src_sb_row = (sy + h - 1 - ty0) >> 6; |
| 2695 | let src_sb_col = (sx + w - 1 - tx0) >> 6; |
| 2696 | |
| 2697 | if src_sb_row >= active_sb_row { |
| 2698 | return false; |
| 2699 | } |
| 2700 | let total = ((tx1 - tx0 - 1) >> 6) + 1; |
| 2701 | if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64 |
| 2702 | { |
| 2703 | return false; |
| 2704 | } |
| 2705 | |
| 2706 | let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row); |
| 2707 | src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf |
| 2708 | } |
| 2709 | } |
| 2710 | |
| 2711 | |
| 2712 | |
| 2713 | |
| 2714 | |
| 2715 | static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] = |
| 2716 | [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; |
| 2717 | |
| 2718 | impl Drop for Ibc { |
| 2719 | fn drop(&mut self) { |
| 2720 | for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() { |
| 2721 | IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed); |
| 2722 | } |
| 2723 | } |
| 2724 | } |
| 2725 | |
| 2726 | |
| 2727 | |
| 2728 | #[allow(dead_code)] |
| 2729 | pub(crate) fn take_intrabc_search() -> [usize; 3] { |
| 2730 | std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 2731 | } |
| 2732 | |
| 2733 | |
| 2734 | |
| 2735 | |
| 2736 | fn dv_component_bits(diff: i32) -> f64 { |
| 2737 | let z = diff.unsigned_abs() as i32 - 1; |
| 2738 | let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); |
| 2739 | let class = mv_class_of(z); |
| 2740 | bits += symbol_bits(&cdf::MV_CLASS, class); |
| 2741 | let local = z - mv_class_base(class); |
| 2742 | if class == 0 { |
| 2743 | bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize); |
| 2744 | } else { |
| 2745 | let d = local >> 3; |
| 2746 | for i in 0..class { |
| 2747 | bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); |
| 2748 | } |
| 2749 | } |
| 2750 | bits |
| 2751 | } |
| 2752 | |
| 2753 | |
| 2754 | |
| 2755 | |
| 2756 | fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 { |
| 2757 | let diff = (dv.0 - pred.0, dv.1 - pred.1); |
| 2758 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 2759 | (false, false) => 0, |
| 2760 | (false, true) => 1, |
| 2761 | (true, false) => 2, |
| 2762 | (true, true) => 3, |
| 2763 | }; |
| 2764 | let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0; |
| 2765 | if diff.0 != 0 { |
| 2766 | bits += dv_component_bits(diff.0); |
| 2767 | } |
| 2768 | if diff.1 != 0 { |
| 2769 | bits += dv_component_bits(diff.1); |
| 2770 | } |
| 2771 | bits |
| 2772 | } |
| 2773 | |
| 2774 | |
| 2775 | |
| 2776 | |
| 2777 | |
| 2778 | fn ibc_sse( |
| 2779 | luma: &Plane, |
| 2780 | chroma: &[Plane; 2], |
| 2781 | (x, y): (usize, usize), |
| 2782 | (sx, sy): (usize, usize), |
| 2783 | side: usize, |
| 2784 | ) -> f64 { |
| 2785 | let mut sse = 0.0f64; |
| 2786 | for row in 0..side { |
| 2787 | let src = &luma.source[(y + row) * luma.width + x..][..side]; |
| 2788 | let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..side]; |
| 2789 | for (&s, &r) in src.iter().zip(rec) { |
| 2790 | let d = f64::from(i32::from(s) - i32::from(r)); |
| 2791 | sse += d * d; |
| 2792 | } |
| 2793 | } |
| 2794 | let half = side / 2; |
| 2795 | for plane in chroma { |
| 2796 | for row in 0..half { |
| 2797 | let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..half]; |
| 2798 | let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..half]; |
| 2799 | for (&s, &r) in src.iter().zip(rec) { |
| 2800 | let d = f64::from(i32::from(s) - i32::from(r)); |
| 2801 | sse += d * d; |
| 2802 | } |
| 2803 | } |
| 2804 | } |
| 2805 | sse |
| 2806 | } |
| 2807 | |
| 2808 | |
| 2809 | |
| 2810 | |
| 2811 | |
| 2812 | |
| 2813 | |
| 2814 | fn ibc_commit( |
| 2815 | luma: &mut Plane, |
| 2816 | chroma: &mut [Plane; 2], |
| 2817 | (x, y): (usize, usize), |
| 2818 | (sx, sy): (usize, usize), |
| 2819 | side: usize, |
| 2820 | ) { |
| 2821 | for row in 0..side { |
| 2822 | let from = (sy + row) * luma.width + sx; |
| 2823 | let to = (y + row) * luma.width + x; |
| 2824 | let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec(); |
| 2825 | luma.reconstruction[to..to + side].copy_from_slice(&copied); |
| 2826 | } |
| 2827 | let half = side / 2; |
| 2828 | for plane in chroma { |
| 2829 | for row in 0..half { |
| 2830 | let from = (sy / 2 + row) * plane.width + sx / 2; |
| 2831 | let to = (y / 2 + row) * plane.width + x / 2; |
| 2832 | let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec(); |
| 2833 | plane.reconstruction[to..to + half].copy_from_slice(&copied); |
| 2834 | } |
| 2835 | } |
| 2836 | } |
| 2837 | |
| 2838 | |
| 2839 | |
| 2840 | |
| 2841 | |
| 2842 | fn ibc_search( |
| 2843 | ibc: &mut Ibc, |
| 2844 | luma: &Plane, |
| 2845 | chroma: &[Plane; 2], |
| 2846 | (x, y): (usize, usize), |
| 2847 | side: usize, |
| 2848 | lambda: f64, |
| 2849 | ) -> Option<((i32, i32), f64, (usize, usize))> { |
| 2850 | let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8)); |
| 2851 | let mut best: Option<((i32, i32), f64, (usize, usize))> = None; |
| 2852 | let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| { |
| 2853 | let dv = ( |
| 2854 | (sy as i32 - y as i32) * 8, |
| 2855 | (sx as i32 - x as i32) * 8, |
| 2856 | ); |
| 2857 | if !ibc.dv_valid(x, y, side, side, dv) { |
| 2858 | return; |
| 2859 | } |
| 2860 | let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred); |
| 2861 | if best.as_ref().is_none_or(|b| cost < b.1) { |
| 2862 | *best = Some((dv, cost, (sx, sy))); |
| 2863 | } |
| 2864 | }; |
| 2865 | ibc.lookups += 1; |
| 2866 | let key = ibc_hash(luma.source, luma.width, x, y); |
| 2867 | |
| 2868 | |
| 2869 | |
| 2870 | |
| 2871 | |
| 2872 | |
| 2873 | let hits: Vec<(u32, u32)> = ibc |
| 2874 | .table |
| 2875 | .get(&key) |
| 2876 | .map(|h| { |
| 2877 | let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32)); |
| 2878 | h[..end].iter().rev().take(32).copied().collect() |
| 2879 | }) |
| 2880 | .unwrap_or_default(); |
| 2881 | for (hx, hy) in hits { |
| 2882 | consider(&*ibc, hx as usize, hy as usize, &mut best); |
| 2883 | } |
| 2884 | if let Some(dv) = ibc.last_dv { |
| 2885 | let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8); |
| 2886 | if sx >= 0 && sy >= 0 { |
| 2887 | consider(&*ibc, sx as usize, sy as usize, &mut best); |
| 2888 | } |
| 2889 | } |
| 2890 | if best.is_some() { |
| 2891 | ibc.found += 1; |
| 2892 | } |
| 2893 | best |
| 2894 | } |
| 2895 | |
| 2896 | fn code_square( |
| 2897 | luma: &mut Plane, |
| 2898 | chroma: &mut [Plane; 2], |
| 2899 | (x, y): (usize, usize), |
| 2900 | side: usize, |
| 2901 | search: &Search, |
| 2902 | mode_bits: &[f64; 13], |
| 2903 | |
| 2904 | |
| 2905 | |
| 2906 | tx_select: bool, |
| 2907 | |
| 2908 | |
| 2909 | ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx, |
| 2910 | ) -> (BlockCoeffs, f64) { |
| 2911 | let (luma_set, chroma_set) = if side == BLOCK { |
| 2912 | (TxbSet::Luma32, TxbSet::Chroma16) |
| 2913 | } else if side == 8 { |
| 2914 | |
| 2915 | |
| 2916 | |
| 2917 | |
| 2918 | |
| 2919 | |
| 2920 | |
| 2921 | (TxbSet::Luma8, TxbSet::Chroma4) |
| 2922 | } else { |
| 2923 | (TxbSet::Luma16, TxbSet::Chroma8) |
| 2924 | }; |
| 2925 | let at = At { |
| 2926 | x, |
| 2927 | y, |
| 2928 | side, |
| 2929 | reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx), |
| 2930 | set: luma_set, |
| 2931 | }; |
| 2932 | let (mut luma_coeffs, mode, mut cost) = luma.search_block(at, search, mode_bits, fctx); |
| 2933 | |
| 2934 | |
| 2935 | |
| 2936 | let mut tx_depth = 0u8; |
| 2937 | if tx_select && max_tx_depth(side) > 0 { |
| 2938 | let mut best = ( |
| 2939 | cost + search.lambda * tx_depth_bits(side, 0), |
| 2940 | 0usize, |
| 2941 | luma.snapshot(x, y, side), |
| 2942 | luma_coeffs, |
| 2943 | ); |
| 2944 | for depth in 1..=max_tx_depth(side) { |
| 2945 | let (levels, sse, bits) = luma.code_tx_depth(at, mode, depth, search, fctx); |
| 2946 | let cost_d = sse |
| 2947 | + search.lambda |
| 2948 | * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth)); |
| 2949 | if cost_d < best.0 { |
| 2950 | best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side)); |
| 2951 | } |
| 2952 | } |
| 2953 | luma.restore(x, y, side, &best.2); |
| 2954 | cost = best.0; |
| 2955 | tx_depth = best.1 as u8; |
| 2956 | luma_coeffs = best.3; |
| 2957 | TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2958 | } |
| 2959 | |
| 2960 | |
| 2961 | |
| 2962 | |
| 2963 | |
| 2964 | let mut mode = mode; |
| 2965 | let mut palette = None; |
| 2966 | if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { |
| 2967 | let source: Vec<u8> = (y..y + side) |
| 2968 | .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec()) |
| 2969 | .collect(); |
| 2970 | let kept = luma.snapshot(x, y, side); |
| 2971 | for pal in palette_candidates(&source) { |
| 2972 | let n = usize::from(pal.size); |
| 2973 | let prediction: Vec<u8> = pal |
| 2974 | .map |
| 2975 | .iter() |
| 2976 | .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8) |
| 2977 | .collect(); |
| 2978 | let trial = luma.code_from_prediction( |
| 2979 | x, |
| 2980 | y, |
| 2981 | side, |
| 2982 | &prediction, |
| 2983 | false, |
| 2984 | search.base_q_idx, |
| 2985 | search.deadzone, |
| 2986 | luma_set, |
| 2987 | ); |
| 2988 | let cost_p = trial.sse |
| 2989 | + search.lambda |
| 2990 | * (trial.bits |
| 2991 | + mode_bits[DC_PRED as usize] |
| 2992 | + crate::tile::palette_bits(&pal, side) |
| 2993 | + if tx_select { tx_depth_bits(side, 0) } else { 0.0 }); |
| 2994 | if cost_p < cost { |
| 2995 | cost = cost_p; |
| 2996 | mode = DC_PRED as u8; |
| 2997 | tx_depth = 0; |
| 2998 | luma_coeffs = coeffs(&trial.levels, side); |
| 2999 | luma.commit(x, y, side, &trial); |
| 3000 | palette = Some(pal); |
| 3001 | } |
| 3002 | } |
| 3003 | if palette.is_none() { |
| 3004 | luma.restore(x, y, side, &kept); |
| 3005 | } |
| 3006 | } |
| 3007 | |
| 3008 | |
| 3009 | |
| 3010 | let ([u, v], uv_mode, chroma_cost, palette_uv) = |
| 3011 | search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx); |
| 3012 | cost += chroma_cost; |
| 3013 | |
| 3014 | |
| 3015 | |
| 3016 | |
| 3017 | if let Some(ibc) = ibc { |
| 3018 | if let Some((dv, cost_ibc, src)) = |
| 3019 | ibc_search(ibc, luma, chroma, (x, y), side, search.lambda) |
| 3020 | { |
| 3021 | if cost_ibc < cost { |
| 3022 | ibc_commit(luma, chroma, (x, y), src, side); |
| 3023 | ibc.last_dv = Some(dv); |
| 3024 | ibc.hits += 1; |
| 3025 | return ( |
| 3026 | BlockCoeffs { |
| 3027 | skip: true, |
| 3028 | dv: Some(dv), |
| 3029 | ..BlockCoeffs::default() |
| 3030 | }, |
| 3031 | cost_ibc, |
| 3032 | ); |
| 3033 | } |
| 3034 | } |
| 3035 | } |
| 3036 | ( |
| 3037 | BlockCoeffs { |
| 3038 | u, |
| 3039 | v, |
| 3040 | luma: luma_coeffs, |
| 3041 | mode, |
| 3042 | uv_mode, |
| 3043 | tx_depth, |
| 3044 | palette, |
| 3045 | palette_uv, |
| 3046 | ..BlockCoeffs::default() |
| 3047 | }, |
| 3048 | cost, |
| 3049 | ) |
| 3050 | } |
| 3051 | |
| 3052 | |
| 3053 | |
| 3054 | |
| 3055 | |
| 3056 | |
| 3057 | |
| 3058 | const CHROMA_MODES: [u8; 7] = [ |
| 3059 | DC_PRED, |
| 3060 | V_PRED, |
| 3061 | H_PRED, |
| 3062 | SMOOTH_PRED, |
| 3063 | SMOOTH_V_PRED, |
| 3064 | SMOOTH_H_PRED, |
| 3065 | PAETH_PRED, |
| 3066 | ]; |
| 3067 | |
| 3068 | |
| 3069 | #[cfg(test)] |
| 3070 | const UV_MODE_NAMES: [&str; 13] = [ |
| 3071 | "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", |
| 3072 | "SMOOTH_H", "PAETH", |
| 3073 | ]; |
| 3074 | |
| 3075 | |
| 3076 | |
| 3077 | |
| 3078 | static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] = |
| 3079 | [const { std::sync::atomic::AtomicUsize::new(0) }; 13]; |
| 3080 | |
| 3081 | |
| 3082 | |
| 3083 | #[cfg(test)] |
| 3084 | pub(crate) fn take_uv_mode_hits() -> [usize; 13] { |
| 3085 | std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 3086 | } |
| 3087 | |
| 3088 | |
| 3089 | |
| 3090 | |
| 3091 | |
| 3092 | |
| 3093 | |
| 3094 | |
| 3095 | |
| 3096 | |
| 3097 | |
| 3098 | #[allow(clippy::too_many_arguments)] |
| 3099 | |
| 3100 | |
| 3101 | |
| 3102 | |
| 3103 | |
| 3104 | |
| 3105 | |
| 3106 | |
| 3107 | |
| 3108 | |
| 3109 | fn chroma_top_k() -> Option<usize> { |
| 3110 | static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new(); |
| 3111 | *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() { |
| 3112 | Some(v) => v.parse::<usize>().ok().filter(|&k| k > 0), |
| 3113 | None => CHROMA_TOP_K, |
| 3114 | }) |
| 3115 | } |
| 3116 | |
| 3117 | |
| 3118 | |
| 3119 | |
| 3120 | |
| 3121 | |
| 3122 | |
| 3123 | |
| 3124 | |
| 3125 | const CHROMA_TOP_K: Option<usize> = None; |
| 3126 | |
| 3127 | fn search_chroma( |
| 3128 | chroma: &mut [Plane; 2], |
| 3129 | (x, y): (usize, usize), |
| 3130 | side: usize, |
| 3131 | set: TxbSet, |
| 3132 | search: &Search, |
| 3133 | luma_mode: u8, |
| 3134 | fctx: &crate::decode::FrameCtx, |
| 3135 | ) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) { |
| 3136 | let at = At { |
| 3137 | x: x / 2, |
| 3138 | y: y / 2, |
| 3139 | side: side / 2, |
| 3140 | reach: Reach::none(), |
| 3141 | set, |
| 3142 | }; |
| 3143 | |
| 3144 | |
| 3145 | |
| 3146 | |
| 3147 | |
| 3148 | let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> { |
| 3149 | let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); |
| 3150 | let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); |
| 3151 | u.iter() |
| 3152 | .zip(v.iter()) |
| 3153 | .map(|(&(us, mode), &(vs, _))| (us + vs, mode)) |
| 3154 | .collect() |
| 3155 | }; |
| 3156 | let modes: Vec<u8> = match chroma_top_k() { |
| 3157 | Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k), |
| 3158 | _ => CHROMA_MODES.to_vec(), |
| 3159 | }; |
| 3160 | let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)]; |
| 3161 | let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED)); |
| 3162 | let ranking: Vec<(f64, u8)> = if census_on() { |
| 3163 | sad_scores(chroma) |
| 3164 | } else { |
| 3165 | Vec::new() |
| 3166 | }; |
| 3167 | census_add(2, 1); |
| 3168 | census_add(3, modes.len()); |
| 3169 | let mut best: Option<(f64, u8, Trial, Trial)> = None; |
| 3170 | for mode in modes { |
| 3171 | let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits; |
| 3172 | if (V_PRED..=D67_PRED).contains(&mode) { |
| 3173 | bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3); |
| 3174 | } |
| 3175 | let tx_type = crate::decode::default_intra_tx_type(mode); |
| 3176 | let u = chroma[0].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx); |
| 3177 | let v = chroma[1].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx); |
| 3178 | let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits); |
| 3179 | if best.as_ref().is_none_or(|(b, ..)| cost < *b) { |
| 3180 | best = Some((cost, mode, u, v)); |
| 3181 | } |
| 3182 | } |
| 3183 | let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty"); |
| 3184 | |
| 3185 | |
| 3186 | |
| 3187 | |
| 3188 | |
| 3189 | |
| 3190 | |
| 3191 | |
| 3192 | let mut palette_uv = None; |
| 3193 | if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { |
| 3194 | debug_assert_eq!(crate::tile::palette_uv_side(side), at.side); |
| 3195 | let plane_source = |p: &Plane| -> Vec<u8> { |
| 3196 | (at.y..at.y + at.side) |
| 3197 | .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec()) |
| 3198 | .collect() |
| 3199 | }; |
| 3200 | let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1])); |
| 3201 | for pal in palette_candidates(&u_source) { |
| 3202 | let n = usize::from(pal.size); |
| 3203 | |
| 3204 | |
| 3205 | |
| 3206 | let mut sums = [0u32; 8]; |
| 3207 | let mut counts = [0u32; 8]; |
| 3208 | for (&i, &sample) in pal.map.iter().zip(v_source.iter()) { |
| 3209 | let k = usize::from(i).min(n - 1); |
| 3210 | sums[k] += u32::from(sample); |
| 3211 | counts[k] += 1; |
| 3212 | } |
| 3213 | let mut v_colors = [0u16; 8]; |
| 3214 | for k in 0..n { |
| 3215 | v_colors[k] = if counts[k] > 0 { |
| 3216 | ((sums[k] + counts[k] / 2) / counts[k]) as u16 |
| 3217 | } else { |
| 3218 | 0 |
| 3219 | }; |
| 3220 | } |
| 3221 | let candidate = crate::tile::PaletteUv { |
| 3222 | size: pal.size, |
| 3223 | u_colors: pal.colors, |
| 3224 | v_colors, |
| 3225 | map: pal.map, |
| 3226 | }; |
| 3227 | let predict = |colors: &[u16; 8]| -> Vec<u8> { |
| 3228 | candidate |
| 3229 | .map |
| 3230 | .iter() |
| 3231 | .map(|&i| colors[usize::from(i).min(n - 1)] as u8) |
| 3232 | .collect() |
| 3233 | }; |
| 3234 | let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors)); |
| 3235 | let u_trial = chroma[0].code_from_prediction( |
| 3236 | at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set, |
| 3237 | ); |
| 3238 | let v_trial = chroma[1].code_from_prediction( |
| 3239 | at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set, |
| 3240 | ); |
| 3241 | let cost_p = u_trial.sse |
| 3242 | + v_trial.sse |
| 3243 | + search.lambda |
| 3244 | * (u_trial.bits |
| 3245 | + v_trial.bits |
| 3246 | + crate::tile::palette_uv_bits(&candidate, side)); |
| 3247 | if cost_p < cost { |
| 3248 | cost = cost_p; |
| 3249 | mode = DC_PRED; |
| 3250 | u = u_trial; |
| 3251 | v = v_trial; |
| 3252 | palette_uv = Some(candidate); |
| 3253 | } |
| 3254 | } |
| 3255 | } |
| 3256 | if census_on() { |
| 3257 | CHROMA_RANK[sad_rank(&ranking, mode).min(6)] |
| 3258 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3259 | } |
| 3260 | UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 3261 | chroma[0].commit(at.x, at.y, at.side, &u); |
| 3262 | chroma[1].commit(at.x, at.y, at.side, &v); |
| 3263 | ( |
| 3264 | [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)], |
| 3265 | mode, |
| 3266 | cost, |
| 3267 | palette_uv, |
| 3268 | ) |
| 3269 | } |
| 3270 | |
| 3271 | |
| 3272 | |
| 3273 | |
| 3274 | |
| 3275 | |
| 3276 | |
| 3277 | |
| 3278 | |
| 3279 | |
| 3280 | |
| 3281 | |
| 3282 | #[allow(clippy::too_many_arguments)] |
| 3283 | fn code_square_inter( |
| 3284 | luma: &mut Plane, |
| 3285 | chroma: &mut [Plane; 2], |
| 3286 | (x, y): (usize, usize), |
| 3287 | side: usize, |
| 3288 | search: &Search, |
| 3289 | mode_bits: &[f64; 13], |
| 3290 | reference: &Picture, |
| 3291 | stack: &MvStack, |
| 3292 | |
| 3293 | |
| 3294 | |
| 3295 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 3296 | fctx: &crate::decode::FrameCtx, |
| 3297 | ) -> (BlockCoeffs, f64) { |
| 3298 | let (intra_block, intra_cost) = |
| 3299 | code_square( |
| 3300 | luma, |
| 3301 | chroma, |
| 3302 | (x, y), |
| 3303 | side, |
| 3304 | search, |
| 3305 | mode_bits, |
| 3306 | tx_select() && tx_select_inter(), |
| 3307 | None, |
| 3308 | fctx, |
| 3309 | ); |
| 3310 | let luma_set = if side == 8 { |
| 3311 | TxbSet::Luma8Inter |
| 3312 | } else { |
| 3313 | TxbSet::Luma16Inter |
| 3314 | }; |
| 3315 | let chroma_set = if side == 8 { |
| 3316 | TxbSet::Chroma4 |
| 3317 | } else { |
| 3318 | TxbSet::Chroma8 |
| 3319 | }; |
| 3320 | |
| 3321 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 3322 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 3323 | let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 3324 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) |
| 3325 | + symbol_bits(&cdf::SINGLE_REF[0][3], 0); |
| 3326 | let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) |
| 3327 | + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) |
| 3328 | + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); |
| 3329 | |
| 3330 | let mv = stack.nearest_mv; |
| 3331 | let ref_luma = ( |
| 3332 | &reference.y, |
| 3333 | reference.width, |
| 3334 | luma.true_width, |
| 3335 | luma.true_height, |
| 3336 | ); |
| 3337 | let ref_u = ( |
| 3338 | &reference.u, |
| 3339 | reference.width / 2, |
| 3340 | chroma[0].true_width, |
| 3341 | chroma[0].true_height, |
| 3342 | ); |
| 3343 | let ref_v = ( |
| 3344 | &reference.v, |
| 3345 | reference.width / 2, |
| 3346 | chroma[1].true_width, |
| 3347 | chroma[1].true_height, |
| 3348 | ); |
| 3349 | let luma_trial = mc_trial( |
| 3350 | luma, |
| 3351 | x, |
| 3352 | y, |
| 3353 | side, |
| 3354 | mv, |
| 3355 | true, |
| 3356 | ref_luma.0, |
| 3357 | ref_luma.1, |
| 3358 | ref_luma.2, |
| 3359 | ref_luma.3, |
| 3360 | false, |
| 3361 | search.base_q_idx, |
| 3362 | search.deadzone, |
| 3363 | luma_set, fctx, |
| 3364 | ); |
| 3365 | let u = mc_trial( |
| 3366 | &chroma[0], |
| 3367 | x / 2, |
| 3368 | y / 2, |
| 3369 | side / 2, |
| 3370 | mv, |
| 3371 | false, |
| 3372 | ref_u.0, |
| 3373 | ref_u.1, |
| 3374 | ref_u.2, |
| 3375 | ref_u.3, |
| 3376 | false, |
| 3377 | search.base_q_idx, |
| 3378 | search.deadzone, |
| 3379 | chroma_set, fctx, |
| 3380 | ); |
| 3381 | let v = mc_trial( |
| 3382 | &chroma[1], |
| 3383 | x / 2, |
| 3384 | y / 2, |
| 3385 | side / 2, |
| 3386 | mv, |
| 3387 | false, |
| 3388 | ref_v.0, |
| 3389 | ref_v.1, |
| 3390 | ref_v.2, |
| 3391 | ref_v.3, |
| 3392 | false, |
| 3393 | search.base_q_idx, |
| 3394 | search.deadzone, |
| 3395 | chroma_set, fctx, |
| 3396 | ); |
| 3397 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 3398 | && u.levels.iter().all(|&l| l == 0) |
| 3399 | && v.levels.iter().all(|&l| l == 0); |
| 3400 | let inter_cost = luma_trial.sse |
| 3401 | + u.sse |
| 3402 | + v.sse |
| 3403 | + search.lambda |
| 3404 | * (skip_bits(skip) |
| 3405 | + intra_inter_bits(true) |
| 3406 | + single_ref_bits |
| 3407 | + mode_bits_inter |
| 3408 | + if skip { |
| 3409 | 0.0 |
| 3410 | } else { |
| 3411 | luma_trial.bits + u.bits + v.bits |
| 3412 | }); |
| 3413 | |
| 3414 | |
| 3415 | |
| 3416 | |
| 3417 | |
| 3418 | |
| 3419 | |
| 3420 | |
| 3421 | |
| 3422 | |
| 3423 | |
| 3424 | |
| 3425 | |
| 3426 | |
| 3427 | |
| 3428 | |
| 3429 | |
| 3430 | |
| 3431 | |
| 3432 | |
| 3433 | |
| 3434 | let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None); |
| 3435 | |
| 3436 | |
| 3437 | |
| 3438 | |
| 3439 | let mut searched_new: Option<(i32, i32)> = None; |
| 3440 | if leaf_new_mv() { |
| 3441 | let source_block = luma.source_block(x, y, side); |
| 3442 | let (seeds, seed_n) = mv_seeds(stack); |
| 3443 | let found = motion::search( |
| 3444 | ref_luma.0, |
| 3445 | ref_luma.1, |
| 3446 | ref_luma.2, |
| 3447 | ref_luma.3, |
| 3448 | &source_block, |
| 3449 | x, |
| 3450 | y, |
| 3451 | side, |
| 3452 | side, |
| 3453 | stack.pred_mv, |
| 3454 | &seeds[..seed_n], |
| 3455 | search.lambda, fctx, |
| 3456 | 1, |
| 3457 | ); |
| 3458 | let new_mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 3459 | if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) { |
| 3460 | searched_new = Some(new_mv); |
| 3461 | |
| 3462 | |
| 3463 | let (luma_new, u_new, v_new) = if new_mv == mv { |
| 3464 | (luma_trial.clone(), u.clone(), v.clone()) |
| 3465 | } else { |
| 3466 | ( |
| 3467 | mc_trial( |
| 3468 | luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2, |
| 3469 | ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx, |
| 3470 | ), |
| 3471 | mc_trial( |
| 3472 | &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1, |
| 3473 | ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set, |
| 3474 | fctx, |
| 3475 | ), |
| 3476 | mc_trial( |
| 3477 | &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1, |
| 3478 | ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set, |
| 3479 | fctx, |
| 3480 | ), |
| 3481 | ) |
| 3482 | }; |
| 3483 | let skip_new = luma_new.levels.iter().all(|&l| l == 0) |
| 3484 | && u_new.levels.iter().all(|&l| l == 0) |
| 3485 | && v_new.levels.iter().all(|&l| l == 0); |
| 3486 | let drl_bits = if stack.entries.len() > 1 { |
| 3487 | symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0) |
| 3488 | } else { |
| 3489 | 0.0 |
| 3490 | }; |
| 3491 | let cost_new = luma_new.sse |
| 3492 | + u_new.sse |
| 3493 | + v_new.sse |
| 3494 | + search.lambda |
| 3495 | * (skip_bits(skip_new) |
| 3496 | + intra_inter_bits(true) |
| 3497 | + single_ref_bits |
| 3498 | + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) |
| 3499 | + drl_bits |
| 3500 | + mv_bits |
| 3501 | + if skip_new { |
| 3502 | 0.0 |
| 3503 | } else { |
| 3504 | luma_new.bits + u_new.bits + v_new.bits |
| 3505 | }); |
| 3506 | if cost_new < best.0 { |
| 3507 | best = ( |
| 3508 | cost_new, |
| 3509 | Some(( |
| 3510 | luma_new, |
| 3511 | u_new, |
| 3512 | v_new, |
| 3513 | skip_new, |
| 3514 | InterInfo { |
| 3515 | ref1: None, |
| 3516 | mv1: (0, 0), |
| 3517 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3518 | mode: InterMode::NewMv, |
| 3519 | mv: new_mv, |
| 3520 | ref_mv_idx: 0, |
| 3521 | }, |
| 3522 | )), |
| 3523 | ); |
| 3524 | } |
| 3525 | } |
| 3526 | } |
| 3527 | |
| 3528 | |
| 3529 | |
| 3530 | |
| 3531 | |
| 3532 | |
| 3533 | |
| 3534 | |
| 3535 | |
| 3536 | for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) { |
| 3537 | let (ref1, g) = (*ref1, *g); |
| 3538 | let uni = |
| 3539 | (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1); |
| 3540 | let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1) |
| 3541 | + if uni { |
| 3542 | symbol_bits(&cdf::COMP_REF_TYPE[0], 1) |
| 3543 | + symbol_bits(&cdf::COMP_REF[0][0], 0) |
| 3544 | + symbol_bits(&cdf::COMP_REF[0][1], 0) |
| 3545 | + symbol_bits(&cdf::COMP_BWDREF[0][0], 1) |
| 3546 | } else { |
| 3547 | symbol_bits(&cdf::COMP_REF_TYPE[0], 0) |
| 3548 | + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0) |
| 3549 | + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1) |
| 3550 | + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1) |
| 3551 | }; |
| 3552 | let mode_ctx = |
| 3553 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 3554 | let mode_bits_of = |
| 3555 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 3556 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 3557 | ( |
| 3558 | cstack.nearest_mv, |
| 3559 | mode_bits_of(0), |
| 3560 | InterInfo { |
| 3561 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3562 | mode: InterMode::NearestNearestMv, |
| 3563 | mv: cstack.nearest_mv.0, |
| 3564 | mv1: cstack.nearest_mv.1, |
| 3565 | ref1: Some(ref1), |
| 3566 | ref_mv_idx: 0, |
| 3567 | }, |
| 3568 | ), |
| 3569 | ( |
| 3570 | ((0, 0), (0, 0)), |
| 3571 | mode_bits_of(6), |
| 3572 | InterInfo { |
| 3573 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3574 | mode: InterMode::GlobalGlobalMv, |
| 3575 | mv: (0, 0), |
| 3576 | mv1: (0, 0), |
| 3577 | ref1: Some(ref1), |
| 3578 | ref_mv_idx: 0, |
| 3579 | }, |
| 3580 | ), |
| 3581 | ]; |
| 3582 | |
| 3583 | |
| 3584 | |
| 3585 | let cbase = cstack |
| 3586 | .entries |
| 3587 | .first() |
| 3588 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 3589 | if let Some(new_mv) = searched_new { |
| 3590 | if let Some(b0) = mv_residual_bits(new_mv, cbase.0) { |
| 3591 | ccands.push(( |
| 3592 | (new_mv, cstack.nearest_mv.1), |
| 3593 | mode_bits_of(3) + b0, |
| 3594 | InterInfo { |
| 3595 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3596 | mode: InterMode::NewNearestMv, |
| 3597 | mv: new_mv, |
| 3598 | mv1: cstack.nearest_mv.1, |
| 3599 | ref1: Some(ref1), |
| 3600 | ref_mv_idx: 0, |
| 3601 | }, |
| 3602 | )); |
| 3603 | } |
| 3604 | } |
| 3605 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 3606 | ccands.dedup_by_key(|c| c.0); |
| 3607 | let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); |
| 3608 | let g_u = ( |
| 3609 | g.u.as_slice(), |
| 3610 | g.width / 2, |
| 3611 | chroma[0].true_width, |
| 3612 | chroma[0].true_height, |
| 3613 | ); |
| 3614 | let g_v = ( |
| 3615 | g.v.as_slice(), |
| 3616 | g.width / 2, |
| 3617 | chroma[1].true_width, |
| 3618 | chroma[1].true_height, |
| 3619 | ); |
| 3620 | for (mvs, bits, info) in ccands { |
| 3621 | let luma_c = mc_trial_compound( |
| 3622 | luma, x, y, side, mvs, true, |
| 3623 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, |
| 3624 | search.base_q_idx, search.deadzone, luma_set, fctx, |
| 3625 | ); |
| 3626 | let u_c = mc_trial_compound( |
| 3627 | &chroma[0], x / 2, y / 2, side / 2, mvs, false, |
| 3628 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, |
| 3629 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 3630 | ); |
| 3631 | let v_c = mc_trial_compound( |
| 3632 | &chroma[1], x / 2, y / 2, side / 2, mvs, false, |
| 3633 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, |
| 3634 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 3635 | ); |
| 3636 | let skip_c = luma_c.levels.iter().all(|&l| l == 0) |
| 3637 | && u_c.levels.iter().all(|&l| l == 0) |
| 3638 | && v_c.levels.iter().all(|&l| l == 0); |
| 3639 | let cost_c = luma_c.sse |
| 3640 | + u_c.sse |
| 3641 | + v_c.sse |
| 3642 | + search.lambda |
| 3643 | * (skip_bits(skip_c) |
| 3644 | + intra_inter_bits(true) |
| 3645 | + bits |
| 3646 | + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits }); |
| 3647 | if cost_c < best.0 { |
| 3648 | best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info))); |
| 3649 | } |
| 3650 | } |
| 3651 | } |
| 3652 | |
| 3653 | if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best { |
| 3654 | if cost < intra_cost { |
| 3655 | |
| 3656 | |
| 3657 | |
| 3658 | |
| 3659 | |
| 3660 | |
| 3661 | let (levels, tx_depth, dcost) = if info.ref1.is_some() { |
| 3662 | luma.commit(x, y, side, &luma_new); |
| 3663 | (luma_new.levels.clone(), 0, 0.0) |
| 3664 | } else { |
| 3665 | commit_inter_luma( |
| 3666 | luma, (x, y), side, info.mv, |
| 3667 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 3668 | search, &luma_new, skip_new, fctx, |
| 3669 | ) |
| 3670 | }; |
| 3671 | chroma[0].commit(x / 2, y / 2, side / 2, &u_new); |
| 3672 | chroma[1].commit(x / 2, y / 2, side / 2, &v_new); |
| 3673 | return ( |
| 3674 | BlockCoeffs { |
| 3675 | luma: coeffs(&levels, side), |
| 3676 | u: coeffs(&u_new.levels, side / 2), |
| 3677 | v: coeffs(&v_new.levels, side / 2), |
| 3678 | mode: DC_PRED as u8, |
| 3679 | uv_mode: DC_PRED, |
| 3680 | skip: skip_new, |
| 3681 | eight: None, |
| 3682 | dv: None, |
| 3683 | palette: None, |
| 3684 | palette_uv: None, |
| 3685 | tx_depth, |
| 3686 | inter: Some(info), |
| 3687 | }, |
| 3688 | cost + dcost, |
| 3689 | ); |
| 3690 | } |
| 3691 | } |
| 3692 | |
| 3693 | census_add(8, 1); |
| 3694 | if skip { |
| 3695 | census_add(10, 1); |
| 3696 | } |
| 3697 | if inter_cost >= intra_cost { |
| 3698 | census_add(9, 1); |
| 3699 | } |
| 3700 | if inter_cost < intra_cost { |
| 3701 | let (levels, tx_depth, dcost) = commit_inter_luma( |
| 3702 | luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, fctx, |
| 3703 | ); |
| 3704 | chroma[0].commit(x / 2, y / 2, side / 2, &u); |
| 3705 | chroma[1].commit(x / 2, y / 2, side / 2, &v); |
| 3706 | (BlockCoeffs { |
| 3707 | luma: coeffs(&levels, side), |
| 3708 | u: coeffs(&u.levels, side / 2), |
| 3709 | v: coeffs(&v.levels, side / 2), |
| 3710 | mode: DC_PRED as u8, |
| 3711 | uv_mode: DC_PRED, |
| 3712 | skip, |
| 3713 | eight: None, |
| 3714 | dv: None, |
| 3715 | palette: None, |
| 3716 | palette_uv: None, |
| 3717 | tx_depth, |
| 3718 | inter: Some(InterInfo { |
| 3719 | ref1: None, |
| 3720 | mv1: (0, 0), |
| 3721 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3722 | mode: InterMode::NearestMv, |
| 3723 | mv, |
| 3724 | ref_mv_idx: 0, |
| 3725 | }), |
| 3726 | }, inter_cost + dcost) |
| 3727 | } else { |
| 3728 | (intra_block, intra_cost) |
| 3729 | } |
| 3730 | } |
| 3731 | |
| 3732 | |
| 3733 | |
| 3734 | |
| 3735 | |
| 3736 | fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: Option<InterInfo>) { |
| 3737 | let info = match inter { |
| 3738 | Some(info) => MiInfo { |
| 3739 | is_inter: true, |
| 3740 | ref_frame: info.ref_frame, |
| 3741 | |
| 3742 | |
| 3743 | |
| 3744 | |
| 3745 | |
| 3746 | |
| 3747 | ref_frame1: info.ref1.unwrap_or(NO_REF1), |
| 3748 | mv1: mv16(info.mv1), |
| 3749 | mv: mv16(info.mv), |
| 3750 | |
| 3751 | |
| 3752 | is_new_mv: matches!( |
| 3753 | info.mode, |
| 3754 | InterMode::NewMv |
| 3755 | | InterMode::NewNewMv |
| 3756 | | InterMode::NearestNewMv |
| 3757 | | InterMode::NewNearestMv |
| 3758 | ), |
| 3759 | size, |
| 3760 | size_h: size, |
| 3761 | is_global_mv0: false, |
| 3762 | is_global_mv1: false, |
| 3763 | }, |
| 3764 | None => MiInfo { |
| 3765 | is_inter: false, |
| 3766 | ref_frame: -1, |
| 3767 | ref_frame1: NO_REF1, |
| 3768 | mv1: (0, 0), |
| 3769 | mv: (0, 0), |
| 3770 | is_new_mv: false, |
| 3771 | size, |
| 3772 | size_h: size, |
| 3773 | is_global_mv0: false, |
| 3774 | is_global_mv1: false, |
| 3775 | }, |
| 3776 | }; |
| 3777 | for dr in 0..usize::from(size) { |
| 3778 | for dc in 0..usize::from(size) { |
| 3779 | grid.set(mi_row + dr, mi_col + dc, info); |
| 3780 | } |
| 3781 | } |
| 3782 | } |
| 3783 | |
| 3784 | |
| 3785 | |
| 3786 | fn snapshot( |
| 3787 | luma: &Plane, |
| 3788 | chroma: &[Plane; 2], |
| 3789 | (x, y): (usize, usize), |
| 3790 | side: usize, |
| 3791 | ) -> [Vec<u8>; 3] { |
| 3792 | [ |
| 3793 | luma.snapshot(x, y, side), |
| 3794 | chroma[0].snapshot(x / 2, y / 2, side / 2), |
| 3795 | chroma[1].snapshot(x / 2, y / 2, side / 2), |
| 3796 | ] |
| 3797 | } |
| 3798 | |
| 3799 | |
| 3800 | fn restore( |
| 3801 | luma: &mut Plane, |
| 3802 | chroma: &mut [Plane; 2], |
| 3803 | (x, y): (usize, usize), |
| 3804 | side: usize, |
| 3805 | saved: &[Vec<u8>; 3], |
| 3806 | ) { |
| 3807 | luma.restore(x, y, side, &saved[0]); |
| 3808 | chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]); |
| 3809 | chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]); |
| 3810 | } |
| 3811 | |
| 3812 | |
| 3813 | |
| 3814 | |
| 3815 | |
| 3816 | |
| 3817 | fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> { |
| 3818 | let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED); |
| 3819 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 3820 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 3821 | scored.truncate(if dc_entry.is_some() { |
| 3822 | top_k.saturating_sub(1) |
| 3823 | } else { |
| 3824 | top_k |
| 3825 | }); |
| 3826 | if let Some(dc_entry) = dc_entry { |
| 3827 | scored.push(dc_entry); |
| 3828 | } |
| 3829 | let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect(); |
| 3830 | modes.iter().copied().filter(|m| keep.contains(m)).collect() |
| 3831 | } |
| 3832 | |
| 3833 | fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { |
| 3834 | let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]] |
| 3835 | [INTRA_MODE_CTX[usize::from(left_mode)]]; |
| 3836 | std::array::from_fn(|mode| { |
| 3837 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 3838 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 3839 | } else { |
| 3840 | 0.0 |
| 3841 | }; |
| 3842 | symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 3843 | }) |
| 3844 | } |
| 3845 | |
| 3846 | |
| 3847 | struct Search<'a> { |
| 3848 | |
| 3849 | |
| 3850 | screen: bool, |
| 3851 | base_q_idx: u8, |
| 3852 | deadzone: f64, |
| 3853 | lambda: f64, |
| 3854 | modes: &'a [u8], |
| 3855 | |
| 3856 | |
| 3857 | |
| 3858 | |
| 3859 | |
| 3860 | |
| 3861 | top_k: Option<usize>, |
| 3862 | } |
| 3863 | |
| 3864 | |
| 3865 | |
| 3866 | |
| 3867 | fn prune_top_k() -> Option<usize> { |
| 3868 | #[cfg(test)] |
| 3869 | { |
| 3870 | if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) { |
| 3871 | return k; |
| 3872 | } |
| 3873 | } |
| 3874 | let swept = std::env::var("EC_AV1_PRUNE_K") |
| 3875 | .ok() |
| 3876 | .and_then(|v| v.parse::<usize>().ok()); |
| 3877 | match swept { |
| 3878 | Some(k) if cfg!(test) => Some(k), |
| 3879 | _ => PRUNE_TOP_K, |
| 3880 | } |
| 3881 | } |
| 3882 | |
| 3883 | |
| 3884 | |
| 3885 | |
| 3886 | #[cfg(test)] |
| 3887 | thread_local! { |
| 3888 | static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> = |
| 3889 | const { std::cell::Cell::new(None) }; |
| 3890 | } |
| 3891 | |
| 3892 | #[cfg(test)] |
| 3893 | fn set_test_top_k_override(value: Option<usize>) { |
| 3894 | TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value))); |
| 3895 | } |
| 3896 | |
| 3897 | |
| 3898 | |
| 3899 | const PRUNE_TOP_K: Option<usize> = None; |
| 3900 | |
| 3901 | |
| 3902 | |
| 3903 | |
| 3904 | |
| 3905 | |
| 3906 | fn prune_top_k_inter() -> Option<usize> { |
| 3907 | #[cfg(test)] |
| 3908 | { |
| 3909 | if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) { |
| 3910 | return k; |
| 3911 | } |
| 3912 | } |
| 3913 | let swept = std::env::var("EC_AV1_PRUNE_K_INTER") |
| 3914 | .ok() |
| 3915 | .and_then(|v| v.parse::<usize>().ok()); |
| 3916 | match swept { |
| 3917 | Some(k) if cfg!(test) => Some(k), |
| 3918 | _ => INTER_PRUNE_TOP_K, |
| 3919 | } |
| 3920 | } |
| 3921 | |
| 3922 | |
| 3923 | |
| 3924 | #[cfg(test)] |
| 3925 | thread_local! { |
| 3926 | static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> = |
| 3927 | const { std::cell::Cell::new(None) }; |
| 3928 | } |
| 3929 | |
| 3930 | #[cfg(test)] |
| 3931 | fn set_test_top_k_override_inter(value: Option<usize>) { |
| 3932 | TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value))); |
| 3933 | } |
| 3934 | |
| 3935 | |
| 3936 | |
| 3937 | |
| 3938 | |
| 3939 | |
| 3940 | |
| 3941 | |
| 3942 | const INTER_PRUNE_TOP_K: Option<usize> = Some(3); |
| 3943 | |
| 3944 | |
| 3945 | |
| 3946 | |
| 3947 | |
| 3948 | |
| 3949 | |
| 3950 | |
| 3951 | |
| 3952 | #[cfg(test)] |
| 3953 | thread_local! { |
| 3954 | static STAGE_NS: [std::cell::Cell<u64>; 4] = [ |
| 3955 | std::cell::Cell::new(0), |
| 3956 | std::cell::Cell::new(0), |
| 3957 | std::cell::Cell::new(0), |
| 3958 | std::cell::Cell::new(0), |
| 3959 | ]; |
| 3960 | } |
| 3961 | |
| 3962 | #[cfg(test)] |
| 3963 | pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { |
| 3964 | STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); |
| 3965 | } |
| 3966 | |
| 3967 | #[cfg(test)] |
| 3968 | fn stage_reset() { |
| 3969 | STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0))); |
| 3970 | } |
| 3971 | |
| 3972 | #[cfg(test)] |
| 3973 | fn stage_read() -> [std::time::Duration; 4] { |
| 3974 | STAGE_NS.with(|c| { |
| 3975 | c.each_ref() |
| 3976 | .map(|cell| std::time::Duration::from_nanos(cell.get())) |
| 3977 | }) |
| 3978 | } |
| 3979 | |
| 3980 | |
| 3981 | #[derive(Clone)] |
| 3982 | struct Trial { |
| 3983 | levels: Vec<i32>, |
| 3984 | reconstruction: Vec<u8>, |
| 3985 | sse: f64, |
| 3986 | bits: f64, |
| 3987 | } |
| 3988 | |
| 3989 | |
| 3990 | fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> { |
| 3991 | levels |
| 3992 | .iter() |
| 3993 | .enumerate() |
| 3994 | .filter(|&(_, &level)| level != 0) |
| 3995 | .map(|(i, &level)| Coeff { |
| 3996 | row: (i / side) as u8, |
| 3997 | col: (i % side) as u8, |
| 3998 | level, |
| 3999 | }) |
| 4000 | .collect() |
| 4001 | } |
| 4002 | |
| 4003 | thread_local! { |
| 4004 | |
| 4005 | |
| 4006 | |
| 4007 | |
| 4008 | |
| 4009 | |
| 4010 | static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) }; |
| 4011 | } |
| 4012 | |
| 4013 | |
| 4014 | pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) { |
| 4015 | TILE_LOG2.with(|c| c.set((cols_log2, rows_log2))); |
| 4016 | } |
| 4017 | |
| 4018 | fn armed_tiles() -> (u32, u32) { |
| 4019 | let armed = TILE_LOG2.with(std::cell::Cell::get); |
| 4020 | if armed != (0, 0) { |
| 4021 | return armed; |
| 4022 | } |
| 4023 | |
| 4024 | |
| 4025 | |
| 4026 | |
| 4027 | match std::env::var("EC_AV1_TILES").ok() { |
| 4028 | Some(v) if cfg!(test) => { |
| 4029 | let mut f = v.split(':'); |
| 4030 | let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0); |
| 4031 | let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0); |
| 4032 | (cols, rows) |
| 4033 | } |
| 4034 | _ => armed, |
| 4035 | } |
| 4036 | } |
| 4037 | |
| 4038 | |
| 4039 | |
| 4040 | |
| 4041 | |
| 4042 | |
| 4043 | |
| 4044 | |
| 4045 | fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)> |
| 4046 | where |
| 4047 | F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send, |
| 4048 | { |
| 4049 | let _t = crate::par::timer(crate::par::S_TILE_WRITE); |
| 4050 | type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>; |
| 4051 | let threads = crate::par::tile_threads().min(tiles); |
| 4052 | let mut slots: Vec<Slot> = Vec::new(); |
| 4053 | if threads <= 1 { |
| 4054 | for index in 0..tiles { |
| 4055 | slots.push(Some(code(index))); |
| 4056 | } |
| 4057 | } else { |
| 4058 | let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect()); |
| 4059 | { |
| 4060 | let batch = crate::par::Batch::new("ec-av1-tile"); |
| 4061 | for (from, to) in crate::par::bands(tiles, threads) { |
| 4062 | let done = &done; |
| 4063 | let code = &code; |
| 4064 | batch.submit(move || { |
| 4065 | for index in from..to { |
| 4066 | let coded = code(index); |
| 4067 | done.lock().expect("tile slots")[index] = Some(coded); |
| 4068 | } |
| 4069 | }); |
| 4070 | } |
| 4071 | } |
| 4072 | slots = done.into_inner().expect("tile slots"); |
| 4073 | } |
| 4074 | let mut out = Vec::with_capacity(tiles); |
| 4075 | let mut stored = None; |
| 4076 | for (index, slot) in slots.into_iter().enumerate() { |
| 4077 | let (bytes, cdfs) = slot.expect("every tile was coded")?; |
| 4078 | if index == store { |
| 4079 | stored = cdfs; |
| 4080 | } |
| 4081 | out.push(bytes); |
| 4082 | } |
| 4083 | Ok((out, stored)) |
| 4084 | } |
| 4085 | |
| 4086 | |
| 4087 | |
| 4088 | |
| 4089 | |
| 4090 | |
| 4091 | |
| 4092 | |
| 4093 | |
| 4094 | |
| 4095 | |
| 4096 | |
| 4097 | |
| 4098 | |
| 4099 | |
| 4100 | fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>> |
| 4101 | where |
| 4102 | T: Send, |
| 4103 | F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync, |
| 4104 | { |
| 4105 | let _t = crate::par::timer(crate::par::S_TILE_SEARCH); |
| 4106 | let threads = crate::par::tile_threads().min(tiles); |
| 4107 | if threads <= 1 { |
| 4108 | return (0..tiles).map(|index| job(index, fctx)).collect(); |
| 4109 | } |
| 4110 | type Slot<T> = Option<Result<T>>; |
| 4111 | let done: std::sync::Mutex<Vec<Slot<T>>> = |
| 4112 | std::sync::Mutex::new((0..tiles).map(|_| None).collect()); |
| 4113 | { |
| 4114 | let batch = crate::par::Batch::new("ec-av1-tile-search"); |
| 4115 | for (from, to) in crate::par::bands(tiles, threads) { |
| 4116 | let done = &done; |
| 4117 | let job = &job; |
| 4118 | let ctx = crate::decode::filter_ctx_copy(fctx); |
| 4119 | batch.submit(move || { |
| 4120 | for index in from..to { |
| 4121 | let searched = job(index, &ctx); |
| 4122 | done.lock().expect("tile slots")[index] = Some(searched); |
| 4123 | } |
| 4124 | }); |
| 4125 | } |
| 4126 | } |
| 4127 | done.into_inner() |
| 4128 | .expect("tile slots") |
| 4129 | .into_iter() |
| 4130 | .map(|slot| slot.expect("every tile was searched")) |
| 4131 | .collect() |
| 4132 | } |
| 4133 | |
| 4134 | |
| 4135 | |
| 4136 | |
| 4137 | |
| 4138 | |
| 4139 | |
| 4140 | fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> { |
| 4141 | Plane { |
| 4142 | source, |
| 4143 | reconstruction: vec![128; source.len()], |
| 4144 | width, |
| 4145 | height, |
| 4146 | true_width, |
| 4147 | true_height, |
| 4148 | tile_x0: 0, |
| 4149 | tile_y0: 0, |
| 4150 | tile_x1: width, |
| 4151 | tile_y1: height, |
| 4152 | } |
| 4153 | } |
| 4154 | |
| 4155 | |
| 4156 | |
| 4157 | |
| 4158 | |
| 4159 | |
| 4160 | |
| 4161 | |
| 4162 | |
| 4163 | |
| 4164 | |
| 4165 | |
| 4166 | #[allow(unsafe_code)] |
| 4167 | fn copy_rect( |
| 4168 | dst: crate::par::Shared<'_, Vec<u8>>, |
| 4169 | src: &[u8], |
| 4170 | stride: usize, |
| 4171 | x0: usize, |
| 4172 | y0: usize, |
| 4173 | x1: usize, |
| 4174 | y1: usize, |
| 4175 | ) { |
| 4176 | |
| 4177 | let dst = unsafe { dst.get() }; |
| 4178 | for y in y0..y1 { |
| 4179 | let (a, b) = (y * stride + x0, y * stride + x1); |
| 4180 | dst[a..b].copy_from_slice(&src[a..b]); |
| 4181 | } |
| 4182 | } |
| 4183 | |
| 4184 | |
| 4185 | |
| 4186 | |
| 4187 | |
| 4188 | |
| 4189 | fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo { |
| 4190 | ec_av1_syntax::TileInfo { |
| 4191 | uniform_spacing: true, |
| 4192 | cols: layout.cols(), |
| 4193 | rows: layout.rows(), |
| 4194 | cols_log2: layout.cols_log2, |
| 4195 | rows_log2: layout.rows_log2, |
| 4196 | mi_col_starts: layout.mi_col_starts(), |
| 4197 | mi_row_starts: layout.mi_row_starts(), |
| 4198 | context_update_tile_id: layout.largest_tile() as u32, |
| 4199 | tile_size_bytes, |
| 4200 | } |
| 4201 | } |
| 4202 | |
| 4203 | |
| 4204 | |
| 4205 | |
| 4206 | |
| 4207 | |
| 4208 | |
| 4209 | fn clip_planes_to_tile( |
| 4210 | luma: &mut Plane<'_>, |
| 4211 | chroma: &mut [Plane<'_>; 2], |
| 4212 | rect: crate::tile::TileRect, |
| 4213 | ) { |
| 4214 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 4215 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 4216 | luma.set_tile(x0, y0, x1, y1); |
| 4217 | for plane in chroma.iter_mut() { |
| 4218 | plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2)); |
| 4219 | } |
| 4220 | } |
| 4221 | |
| 4222 | |
| 4223 | |
| 4224 | |
| 4225 | |
| 4226 | |
| 4227 | |
| 4228 | |
| 4229 | |
| 4230 | |
| 4231 | |
| 4232 | |
| 4233 | |
| 4234 | |
| 4235 | |
| 4236 | |
| 4237 | |
| 4238 | |
| 4239 | |
| 4240 | |
| 4241 | |
| 4242 | |
| 4243 | |
| 4244 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { |
| 4245 | encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::new()) |
| 4246 | } |
| 4247 | |
| 4248 | |
| 4249 | |
| 4250 | |
| 4251 | |
| 4252 | |
| 4253 | |
| 4254 | pub fn encode_key_frame_with_modes( |
| 4255 | picture: &Picture, |
| 4256 | base_q_idx: u8, |
| 4257 | deadzone: f64, |
| 4258 | modes: &[u8], |
| 4259 | ) -> Result<Encoded> { |
| 4260 | encode_key_frame_with_modes_with_ctx( |
| 4261 | picture, |
| 4262 | base_q_idx, |
| 4263 | deadzone, |
| 4264 | modes, |
| 4265 | &crate::decode::FrameCtx::new(), |
| 4266 | ) |
| 4267 | } |
| 4268 | |
| 4269 | |
| 4270 | |
| 4271 | |
| 4272 | |
| 4273 | |
| 4274 | pub fn encode_sequence( |
| 4275 | pictures: &[Picture], |
| 4276 | base_q_idx: u8, |
| 4277 | deadzone: f64, |
| 4278 | ) -> Result<EncodedSequence> { |
| 4279 | encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::new()) |
| 4280 | } |
| 4281 | |
| 4282 | pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> { |
| 4283 | encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx) |
| 4284 | } |
| 4285 | |
| 4286 | |
| 4287 | |
| 4288 | |
| 4289 | |
| 4290 | |
| 4291 | |
| 4292 | |
| 4293 | |
| 4294 | |
| 4295 | |
| 4296 | |
| 4297 | pub(crate) fn encode_key_frame_with_modes_with_ctx( |
| 4298 | picture: &Picture, |
| 4299 | base_q_idx: u8, |
| 4300 | deadzone: f64, |
| 4301 | modes: &[u8], fctx: &crate::decode::FrameCtx, |
| 4302 | ) -> Result<Encoded> { |
| 4303 | picture.check_even()?; |
| 4304 | let padded = picture.padded_to(BLOCK); |
| 4305 | let encoded = encode_key_frame_inner( |
| 4306 | &padded, |
| 4307 | base_q_idx, |
| 4308 | deadzone, |
| 4309 | modes, |
| 4310 | split_blocks(), |
| 4311 | (picture.width, picture.height), |
| 4312 | unspecified_color_config(), fctx, |
| 4313 | )?; |
| 4314 | Ok(crop_encoded(&encoded, picture.width, picture.height)) |
| 4315 | } |
| 4316 | |
| 4317 | |
| 4318 | |
| 4319 | |
| 4320 | |
| 4321 | pub(crate) fn encode_key_frame_inner( |
| 4322 | picture: &Picture, |
| 4323 | base_q_idx: u8, |
| 4324 | deadzone: f64, |
| 4325 | modes: &[u8], |
| 4326 | split_blocks: bool, |
| 4327 | render: (usize, usize), |
| 4328 | color_config: ColorConfig, fctx: &crate::decode::FrameCtx, |
| 4329 | ) -> Result<Encoded> { |
| 4330 | picture.check()?; |
| 4331 | if modes.is_empty() { |
| 4332 | return Err(Error::unsupported( |
| 4333 | "AV1 encode", |
| 4334 | "a mode search needs at least one mode to choose from", |
| 4335 | )); |
| 4336 | } |
| 4337 | if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) { |
| 4338 | return Err(Error::unsupported( |
| 4339 | "AV1 encode", |
| 4340 | format!("intra mode {bad} is not one the encoder predicts"), |
| 4341 | )); |
| 4342 | } |
| 4343 | |
| 4344 | |
| 4345 | |
| 4346 | |
| 4347 | |
| 4348 | |
| 4349 | |
| 4350 | |
| 4351 | |
| 4352 | |
| 4353 | |
| 4354 | let screen = screen_content( |
| 4355 | &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(), |
| 4356 | picture.width, |
| 4357 | (picture.width).min(render.0), |
| 4358 | (picture.height).min(render.1), |
| 4359 | ); |
| 4360 | arm_seq_screen(screen); |
| 4361 | |
| 4362 | |
| 4363 | |
| 4364 | |
| 4365 | |
| 4366 | |
| 4367 | |
| 4368 | |
| 4369 | |
| 4370 | |
| 4371 | let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) { |
| 4372 | intrabc_worth_it( |
| 4373 | &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(), |
| 4374 | picture.width, |
| 4375 | picture.width.min(render.0), |
| 4376 | picture.height.min(render.1), |
| 4377 | ) |
| 4378 | } else { |
| 4379 | (false, 0.0) |
| 4380 | }; |
| 4381 | IBC_SHARE.with(|c| c.set(ibc_share)); |
| 4382 | let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; |
| 4383 | header.allow_screen_content_tools = screen; |
| 4384 | header.allow_intrabc = allow_intrabc; |
| 4385 | header.render_width = render.0 as u32; |
| 4386 | header.render_height = render.1 as u32; |
| 4387 | |
| 4388 | |
| 4389 | |
| 4390 | |
| 4391 | |
| 4392 | let tx_select = tx_select(); |
| 4393 | if tx_select { |
| 4394 | header.tx_mode = TxMode::Select; |
| 4395 | } |
| 4396 | let (tile_cols_log2, tile_rows_log2) = armed_tiles(); |
| 4397 | |
| 4398 | |
| 4399 | |
| 4400 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 4401 | |
| 4402 | |
| 4403 | |
| 4404 | |
| 4405 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 4406 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 4407 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 4408 | let mut luma = Plane { |
| 4409 | source: &picture_y8, |
| 4410 | reconstruction: vec![128; picture_y8.len()], |
| 4411 | width: picture.width, |
| 4412 | height: picture.height, |
| 4413 | true_width, |
| 4414 | true_height, |
| 4415 | tile_x0: 0, |
| 4416 | tile_y0: 0, |
| 4417 | tile_x1: picture.width, |
| 4418 | tile_y1: picture.height, |
| 4419 | }; |
| 4420 | let mut chroma = [ |
| 4421 | Plane { |
| 4422 | source: &picture_u8, |
| 4423 | reconstruction: vec![128; picture_u8.len()], |
| 4424 | width: picture.width / 2, |
| 4425 | height: picture.height / 2, |
| 4426 | true_width: true_width / 2, |
| 4427 | true_height: true_height / 2, |
| 4428 | tile_x0: 0, |
| 4429 | tile_y0: 0, |
| 4430 | tile_x1: picture.width / 2, |
| 4431 | tile_y1: picture.height / 2, |
| 4432 | }, |
| 4433 | Plane { |
| 4434 | source: &picture_v8, |
| 4435 | reconstruction: vec![128; picture_v8.len()], |
| 4436 | width: picture.width / 2, |
| 4437 | height: picture.height / 2, |
| 4438 | true_width: true_width / 2, |
| 4439 | true_height: true_height / 2, |
| 4440 | tile_x0: 0, |
| 4441 | tile_y0: 0, |
| 4442 | tile_x1: picture.width / 2, |
| 4443 | tile_y1: picture.height / 2, |
| 4444 | }, |
| 4445 | ]; |
| 4446 | |
| 4447 | |
| 4448 | |
| 4449 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 4450 | let search = Search { |
| 4451 | base_q_idx, |
| 4452 | deadzone, |
| 4453 | lambda: lambda_scale() * step * step, |
| 4454 | modes, |
| 4455 | top_k: prune_top_k(), |
| 4456 | screen, |
| 4457 | }; |
| 4458 | |
| 4459 | |
| 4460 | |
| 4461 | |
| 4462 | |
| 4463 | |
| 4464 | |
| 4465 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 4466 | let (cols, rows) = (cols as usize, rows as usize); |
| 4467 | |
| 4468 | |
| 4469 | |
| 4470 | |
| 4471 | |
| 4472 | |
| 4473 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 4474 | |
| 4475 | let layout = |
| 4476 | crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); |
| 4477 | header.tile_info = tile_info_of(&layout, 1); |
| 4478 | |
| 4479 | |
| 4480 | |
| 4481 | |
| 4482 | let header_tile_info = header.tile_info.clone(); |
| 4483 | |
| 4484 | |
| 4485 | |
| 4486 | |
| 4487 | |
| 4488 | |
| 4489 | |
| 4490 | let (frame_width, frame_height) = (picture.width, picture.height); |
| 4491 | let luma_out = crate::par::Shared::new(&mut luma.reconstruction); |
| 4492 | let [cb, cr] = &mut chroma; |
| 4493 | let chroma_out = [ |
| 4494 | crate::par::Shared::new(&mut cb.reconstruction), |
| 4495 | crate::par::Shared::new(&mut cr.reconstruction), |
| 4496 | ]; |
| 4497 | let search_tile = |index: usize, |
| 4498 | fctx: &crate::decode::FrameCtx| |
| 4499 | -> Result<Vec<(usize, Superblock, Vec<u8>)>> { |
| 4500 | let rect = layout.rect(index); |
| 4501 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 4502 | let mut chroma = [ |
| 4503 | fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 4504 | fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 4505 | ]; |
| 4506 | clip_planes_to_tile(&mut luma, &mut chroma, rect); |
| 4507 | let mut above_mode = vec![DC_PRED; cols * 2]; |
| 4508 | let mut left_mode = vec![DC_PRED; rows * 2]; |
| 4509 | let mut ibc = allow_intrabc.then(|| { |
| 4510 | Ibc::new( |
| 4511 | ( |
| 4512 | rect.mi_col0 as usize * 4, |
| 4513 | rect.mi_row0 as usize * 4, |
| 4514 | (rect.mi_col1 as usize * 4).min(true_width), |
| 4515 | (rect.mi_row1 as usize * 4).min(true_height), |
| 4516 | ), |
| 4517 | &picture_y8, |
| 4518 | frame_width, |
| 4519 | ) |
| 4520 | }); |
| 4521 | let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new(); |
| 4522 | for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize { |
| 4523 | for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize { |
| 4524 | let mut modes = Vec::with_capacity(4); |
| 4525 | |
| 4526 | |
| 4527 | |
| 4528 | let mut blocks = Vec::with_capacity(4); |
| 4529 | for quadrant in 0..4 { |
| 4530 | let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2); |
| 4531 | if col >= cols || row >= rows { |
| 4532 | continue; |
| 4533 | } |
| 4534 | let (x, y) = (col * BLOCK, row * BLOCK); |
| 4535 | let (c0, r0) = (col * 2, row * 2); |
| 4536 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 4537 | |
| 4538 | |
| 4539 | |
| 4540 | |
| 4541 | |
| 4542 | |
| 4543 | |
| 4544 | |
| 4545 | let (has_cols32, has_rows32) = ( |
| 4546 | crate::tile::has_half( |
| 4547 | col as u32 * crate::tile::BLOCK_MI, |
| 4548 | crate::tile::BLOCK_MI, |
| 4549 | header.mi_cols, |
| 4550 | ), |
| 4551 | crate::tile::has_half( |
| 4552 | row as u32 * crate::tile::BLOCK_MI, |
| 4553 | crate::tile::BLOCK_MI, |
| 4554 | header.mi_rows, |
| 4555 | ), |
| 4556 | ); |
| 4557 | let whole_legal = has_cols32 && has_rows32; |
| 4558 | |
| 4559 | |
| 4560 | |
| 4561 | |
| 4562 | |
| 4563 | |
| 4564 | let sub_half = |sr: usize, sc: usize| { |
| 4565 | ( |
| 4566 | crate::tile::has_half( |
| 4567 | sc as u32 * crate::tile::SUB_MI, |
| 4568 | crate::tile::SUB_MI, |
| 4569 | header.mi_cols, |
| 4570 | ), |
| 4571 | crate::tile::has_half( |
| 4572 | sr as u32 * crate::tile::SUB_MI, |
| 4573 | crate::tile::SUB_MI, |
| 4574 | header.mi_rows, |
| 4575 | ), |
| 4576 | ) |
| 4577 | }; |
| 4578 | let both_axes_cut = (0..4) |
| 4579 | .map(|i| (r0 + i / 2, c0 + i % 2)) |
| 4580 | .filter(|&(sr, sc)| { |
| 4581 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 4582 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 4583 | }) |
| 4584 | .any(|(sr, sc)| { |
| 4585 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 4586 | !has_cols16 && !has_rows16 |
| 4587 | }); |
| 4588 | if !whole_legal && both_axes_cut { |
| 4589 | return Err(Error::unsupported( |
| 4590 | "AV1 encode", |
| 4591 | format!( |
| 4592 | "the 32x32 block at ({col},{row}) straddles the true frame edge \ |
| 4593 | in a way that needs a rectangular (HORZ/VERT) transform this \ |
| 4594 | encoder does not code yet" |
| 4595 | ), |
| 4596 | )); |
| 4597 | } |
| 4598 | |
| 4599 | |
| 4600 | |
| 4601 | let (whole, mut cost_whole) = code_square( |
| 4602 | &mut luma, |
| 4603 | &mut chroma, |
| 4604 | (x, y), |
| 4605 | BLOCK, |
| 4606 | &search, |
| 4607 | &mode_bits(above_mode[c0], left_mode[r0]), |
| 4608 | tx_select, |
| 4609 | ibc.as_mut(), fctx, |
| 4610 | ); |
| 4611 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 4612 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 4613 | |
| 4614 | |
| 4615 | |
| 4616 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); |
| 4617 | let mut split = Vec::with_capacity(4); |
| 4618 | let mut cost_split = search.lambda |
| 4619 | * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); |
| 4620 | let mut split_modes = Vec::with_capacity(4); |
| 4621 | for sub in 0..4 { |
| 4622 | let (sc, sr) = (c0 + sub % 2, r0 + sub / 2); |
| 4623 | |
| 4624 | |
| 4625 | |
| 4626 | |
| 4627 | |
| 4628 | |
| 4629 | if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows |
| 4630 | || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols |
| 4631 | { |
| 4632 | continue; |
| 4633 | } |
| 4634 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 4635 | if has_cols16 && has_rows16 { |
| 4636 | let (block, cost) = code_square( |
| 4637 | &mut luma, |
| 4638 | &mut chroma, |
| 4639 | (x + (sub % 2) * SUB, y + (sub / 2) * SUB), |
| 4640 | SUB, |
| 4641 | &search, |
| 4642 | &mode_bits(above_mode[sc], left_mode[sr]), |
| 4643 | tx_select, |
| 4644 | ibc.as_mut(), fctx, |
| 4645 | ); |
| 4646 | cost_split += cost; |
| 4647 | split_modes.push(block.mode); |
| 4648 | above_mode[sc] = block.mode; |
| 4649 | left_mode[sr] = block.mode; |
| 4650 | split.push(block); |
| 4651 | } else { |
| 4652 | |
| 4653 | |
| 4654 | |
| 4655 | |
| 4656 | |
| 4657 | |
| 4658 | |
| 4659 | |
| 4660 | let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]); |
| 4661 | let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB); |
| 4662 | let mut leaves = Vec::with_capacity(2); |
| 4663 | for i in 0..4 { |
| 4664 | let leaf_x = x_sub + (i % 2) * 8; |
| 4665 | let leaf_y = y_sub + (i / 2) * 8; |
| 4666 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 4667 | continue; |
| 4668 | } |
| 4669 | let (leaf, cost) = code_square( |
| 4670 | &mut luma, |
| 4671 | &mut chroma, |
| 4672 | (leaf_x, leaf_y), |
| 4673 | 8, |
| 4674 | &search, |
| 4675 | &leaf_mode_bits, |
| 4676 | tx_select, |
| 4677 | None, fctx, |
| 4678 | ); |
| 4679 | cost_split += cost; |
| 4680 | split_modes.push(leaf.mode); |
| 4681 | leaves.push(leaf); |
| 4682 | } |
| 4683 | split.push(BlockCoeffs { |
| 4684 | eight: Some(leaves), |
| 4685 | ..BlockCoeffs::default() |
| 4686 | }); |
| 4687 | } |
| 4688 | } |
| 4689 | |
| 4690 | |
| 4691 | |
| 4692 | |
| 4693 | |
| 4694 | |
| 4695 | |
| 4696 | |
| 4697 | |
| 4698 | if !whole_legal || (split_blocks && cost_split < cost_whole) { |
| 4699 | modes.extend_from_slice(&split_modes); |
| 4700 | blocks.push(Quadrant::Split(split)); |
| 4701 | } else { |
| 4702 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); |
| 4703 | for cell in 0..2 { |
| 4704 | above_mode[c0 + cell] = whole.mode; |
| 4705 | left_mode[r0 + cell] = whole.mode; |
| 4706 | } |
| 4707 | modes.push(whole.mode); |
| 4708 | blocks.push(Quadrant::Whole(whole)); |
| 4709 | } |
| 4710 | } |
| 4711 | coded.push((sb_row * sb_cols + sb_col, Superblock::Split(blocks), modes)); |
| 4712 | } |
| 4713 | } |
| 4714 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 4715 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 4716 | copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1); |
| 4717 | for (&out, tile) in chroma_out.iter().zip(&chroma) { |
| 4718 | copy_rect( |
| 4719 | out, |
| 4720 | &tile.reconstruction, |
| 4721 | frame_width / 2, |
| 4722 | x0 / 2, |
| 4723 | y0 / 2, |
| 4724 | x1.div_ceil(2), |
| 4725 | y1.div_ceil(2), |
| 4726 | ); |
| 4727 | } |
| 4728 | Ok(coded) |
| 4729 | }; |
| 4730 | let searched = search_tiles(layout.count(), fctx, search_tile)?; |
| 4731 | |
| 4732 | |
| 4733 | |
| 4734 | let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect(); |
| 4735 | for (at, superblock, block_modes) in searched.into_iter().flatten() { |
| 4736 | in_order[at] = Some((superblock, block_modes)); |
| 4737 | } |
| 4738 | let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); |
| 4739 | let mut modes = Vec::with_capacity(cols * rows); |
| 4740 | for slot in in_order { |
| 4741 | let (superblock, block_modes) = slot.expect("every superblock belongs to a tile"); |
| 4742 | superblocks.push(superblock); |
| 4743 | modes.extend_from_slice(&block_modes); |
| 4744 | } |
| 4745 | |
| 4746 | #[cfg(test)] |
| 4747 | record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); |
| 4748 | |
| 4749 | |
| 4750 | |
| 4751 | |
| 4752 | |
| 4753 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 4754 | let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); |
| 4755 | let start_cdfs = CdfSnapshot(cdfs); |
| 4756 | |
| 4757 | |
| 4758 | |
| 4759 | |
| 4760 | let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; |
| 4761 | let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; |
| 4762 | |
| 4763 | |
| 4764 | |
| 4765 | |
| 4766 | let code_tiles = |bits: u8, |
| 4767 | sb_cols: usize, |
| 4768 | grid: &[u8], |
| 4769 | units: &[Option<crate::restoration::WienerInfo>]| |
| 4770 | -> Result<Vec<Vec<u8>>> { |
| 4771 | let (out, _) = write_tiles(layout.count(), usize::MAX, |index| { |
| 4772 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); |
| 4773 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 4774 | let mut cdfs = start_cdfs.0.clone(); |
| 4775 | crate::tile::arm_screen(screen); |
| 4776 | crate::tile::arm_intrabc(allow_intrabc); |
| 4777 | let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( |
| 4778 | mi_cols, |
| 4779 | mi_rows, |
| 4780 | base_q_idx, |
| 4781 | &superblocks, |
| 4782 | tx_select, |
| 4783 | &mut cdfs, |
| 4784 | layout.rect(index), |
| 4785 | )?; |
| 4786 | Ok((bytes, None)) |
| 4787 | })?; |
| 4788 | Ok(out) |
| 4789 | }; |
| 4790 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| 4791 | |
| 4792 | |
| 4793 | |
| 4794 | |
| 4795 | |
| 4796 | pick_and_apply_filters( |
| 4797 | &mut header, |
| 4798 | &mut luma, |
| 4799 | &mut chroma, |
| 4800 | [&picture_y8, &picture_u8, &picture_v8], |
| 4801 | |
| 4802 | |
| 4803 | |
| 4804 | |
| 4805 | !allow_intrabc, |
| 4806 | &mut tiles, |
| 4807 | search.lambda, |
| 4808 | fctx, |
| 4809 | |
| 4810 | |
| 4811 | |
| 4812 | |
| 4813 | |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |
| 4814 | |lf, cdef, h, tiles: &[Vec<u8>], lr| { |
| 4815 | let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); |
| 4816 | crate::decode::decode_key_frame_tiles_lr( |
| 4817 | &payloads, |
| 4818 | &header_tile_info, |
| 4819 | h.mi_cols, |
| 4820 | h.mi_rows, |
| 4821 | base_q_idx, |
| 4822 | h.frame_width, |
| 4823 | h.frame_height, |
| 4824 | seq.enable_filter_intra, |
| 4825 | cdef, |
| 4826 | lf, |
| 4827 | tx_select, |
| 4828 | h.reduced_tx_set, |
| 4829 | h.allow_screen_content_tools, |
| 4830 | h.allow_intrabc, |
| 4831 | lr, |
| 4832 | fctx, |
| 4833 | ) |
| 4834 | }, |
| 4835 | )?; |
| 4836 | let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); |
| 4837 | header.tile_info.tile_size_bytes = tile_size_bytes; |
| 4838 | let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); |
| 4839 | let mut stream = temporal_delimiter(); |
| 4840 | stream.extend_from_slice(&sequence_header_obu(&seq)?); |
| 4841 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 4842 | |
| 4843 | let [u, v] = chroma; |
| 4844 | Ok(Encoded { |
| 4845 | stream, |
| 4846 | modes, |
| 4847 | inter_block_share: 0.0, |
| 4848 | reconstruction: Picture { |
| 4849 | width: luma.width, |
| 4850 | height: luma.height, |
| 4851 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 4852 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 4853 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 4854 | }, |
| 4855 | tile, |
| 4856 | mi_cols: header.mi_cols, |
| 4857 | mi_rows: header.mi_rows, |
| 4858 | base_q_idx, |
| 4859 | tx_select, |
| 4860 | screen, |
| 4861 | next_cdfs: start_cdfs.clone(), |
| 4862 | start_cdfs, |
| 4863 | loop_filter: header.loop_filter, |
| 4864 | cdef: header.cdef, |
| 4865 | loop_restoration: header.loop_restoration, |
| 4866 | allow_intrabc, |
| 4867 | }) |
| 4868 | } |
| 4869 | |
| 4870 | |
| 4871 | |
| 4872 | |
| 4873 | |
| 4874 | |
| 4875 | |
| 4876 | |
| 4877 | |
| 4878 | |
| 4879 | |
| 4880 | |
| 4881 | |
| 4882 | |
| 4883 | |
| 4884 | fn pick_and_apply_filters( |
| 4885 | header: &mut FrameHeader, |
| 4886 | luma: &mut Plane<'_>, |
| 4887 | chroma: &mut [Plane<'_>; 2], |
| 4888 | source: [&[u8]; 3], |
| 4889 | search: bool, |
| 4890 | |
| 4891 | |
| 4892 | |
| 4893 | |
| 4894 | |
| 4895 | tiles: &mut Vec<Vec<u8>>, |
| 4896 | lambda: f64, |
| 4897 | fctx: &crate::decode::FrameCtx, |
| 4898 | recode: impl Fn( |
| 4899 | u8, |
| 4900 | usize, |
| 4901 | &[u8], |
| 4902 | &[Option<crate::restoration::WienerInfo>], |
| 4903 | ) -> Result<Vec<Vec<u8>>>, |
| 4904 | decode: impl Fn( |
| 4905 | &LoopFilterParams, |
| 4906 | &CdefParams, |
| 4907 | &FrameHeader, |
| 4908 | &[Vec<u8>], |
| 4909 | &LoopRestorationParams, |
| 4910 | ) -> Result<Picture>, |
| 4911 | ) -> Result<()> { |
| 4912 | if !search { |
| 4913 | return Ok(()); |
| 4914 | } |
| 4915 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 4916 | let hdr = header.clone(); |
| 4917 | |
| 4918 | |
| 4919 | let damping = 3 + (header.quantization.base_q_idx >> 6); |
| 4920 | let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 4921 | let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize); |
| 4922 | let none_lr = LoopRestorationParams::default(); |
| 4923 | |
| 4924 | |
| 4925 | |
| 4926 | |
| 4927 | |
| 4928 | crate::decode::clear_filter_replay(); |
| 4929 | |
| 4930 | |
| 4931 | |
| 4932 | |
| 4933 | let _bands = crate::par::override_filter_threads(crate::par::tile_threads()); |
| 4934 | let ft = crate::par::timer(crate::par::S_FILTER); |
| 4935 | let search_result = crate::filter_search::pick_filters( |
| 4936 | |lf, cdef| { |
| 4937 | if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) { |
| 4938 | return Ok(picture); |
| 4939 | } |
| 4940 | crate::decode::arm_filter_replay(); |
| 4941 | let _t = crate::par::timer(crate::par::S_FIRST); |
| 4942 | decode(lf, cdef, &hdr, tiles, &none_lr) |
| 4943 | }, |
| 4944 | source, |
| 4945 | luma.width, |
| 4946 | (fw, fh), |
| 4947 | damping, |
| 4948 | (sb_cols, sb_rows), |
| 4949 | lambda, |
| 4950 | ); |
| 4951 | drop(ft); |
| 4952 | crate::decode::clear_filter_replay(); |
| 4953 | let (lf, cdef, idx_grid, picture) = search_result?; |
| 4954 | header.loop_filter = lf; |
| 4955 | header.cdef = cdef; |
| 4956 | |
| 4957 | |
| 4958 | |
| 4959 | |
| 4960 | |
| 4961 | |
| 4962 | |
| 4963 | |
| 4964 | |
| 4965 | |
| 4966 | |
| 4967 | |
| 4968 | |
| 4969 | |
| 4970 | let lr_on = restoration_enabled(); |
| 4971 | fctx.capture_stages.set(lr_on); |
| 4972 | let mut filtered = if idx_grid.is_empty() { |
| 4973 | if lr_on { |
| 4974 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 4975 | decode(&lf, &cdef, &hdr, tiles, &none_lr)? |
| 4976 | } else { |
| 4977 | picture |
| 4978 | } |
| 4979 | } else { |
| 4980 | let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?; |
| 4981 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 4982 | let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?; |
| 4983 | *tiles = coded; |
| 4984 | picture |
| 4985 | }; |
| 4986 | fctx.capture_stages.set(false); |
| 4987 | let mut lr = LoopRestorationParams::default(); |
| 4988 | if lr_on { |
| 4989 | let mut want = LoopRestorationParams { |
| 4990 | loop_restoration_size: [64, 64, 64], |
| 4991 | uses_lr: true, |
| 4992 | ..LoopRestorationParams::default() |
| 4993 | }; |
| 4994 | want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; |
| 4995 | let lrt = crate::par::timer(crate::par::S_LR); |
| 4996 | let units = match crate::decode::take_filter_stages(fctx) { |
| 4997 | Some(stages) => crate::filter_search::pick_restoration( |
| 4998 | &stages, |
| 4999 | source[0], |
| 5000 | luma.width, |
| 5001 | (fw, fh), |
| 5002 | &want, |
| 5003 | lambda, |
| 5004 | fctx, |
| 5005 | ), |
| 5006 | None => Vec::new(), |
| 5007 | }; |
| 5008 | |
| 5009 | |
| 5010 | |
| 5011 | |
| 5012 | drop(lrt); |
| 5013 | if units.iter().any(Option::is_some) { |
| 5014 | let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; |
| 5015 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 5016 | filtered = decode(&lf, &cdef, &hdr, &coded, &want)?; |
| 5017 | *tiles = coded; |
| 5018 | lr = want; |
| 5019 | } |
| 5020 | } |
| 5021 | header.loop_restoration = lr; |
| 5022 | let dec_cw = filtered.width.div_ceil(2); |
| 5023 | let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); |
| 5024 | crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh); |
| 5025 | crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch); |
| 5026 | crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch); |
| 5027 | Ok(()) |
| 5028 | } |
| 5029 | |
| 5030 | |
| 5031 | |
| 5032 | |
| 5033 | const SIZE_GROUP_32: usize = 3; |
| 5034 | |
| 5035 | |
| 5036 | |
| 5037 | |
| 5038 | const LAST_FRAME: i8 = 1; |
| 5039 | |
| 5040 | |
| 5041 | |
| 5042 | |
| 5043 | |
| 5044 | |
| 5045 | |
| 5046 | fn inter_mode_bits() -> [f64; 13] { |
| 5047 | std::array::from_fn(|mode| { |
| 5048 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 5049 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 5050 | } else { |
| 5051 | 0.0 |
| 5052 | }; |
| 5053 | symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode) |
| 5054 | + angle |
| 5055 | + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 5056 | }) |
| 5057 | } |
| 5058 | |
| 5059 | |
| 5060 | |
| 5061 | |
| 5062 | |
| 5063 | |
| 5064 | |
| 5065 | |
| 5066 | fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 { |
| 5067 | (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 } |
| 5068 | } |
| 5069 | |
| 5070 | |
| 5071 | |
| 5072 | |
| 5073 | fn mv_class_base(class: usize) -> i32 { |
| 5074 | if class == 0 { 0 } else { 2i32 << (class + 2) } |
| 5075 | } |
| 5076 | |
| 5077 | |
| 5078 | |
| 5079 | fn mv_class_of(z: i32) -> usize { |
| 5080 | let mut class = 0; |
| 5081 | while class < 10 && mv_class_base(class + 1) <= z { |
| 5082 | class += 1; |
| 5083 | } |
| 5084 | class |
| 5085 | } |
| 5086 | |
| 5087 | |
| 5088 | |
| 5089 | |
| 5090 | |
| 5091 | |
| 5092 | |
| 5093 | |
| 5094 | |
| 5095 | |
| 5096 | |
| 5097 | fn mv_component_bits(diff: i32) -> Option<f64> { |
| 5098 | let mag = diff.unsigned_abs() as i32; |
| 5099 | let z = mag - 1; |
| 5100 | if z & 1 == 0 { |
| 5101 | return None; |
| 5102 | } |
| 5103 | let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); |
| 5104 | let class = mv_class_of(z); |
| 5105 | bits += symbol_bits(&cdf::MV_CLASS, class); |
| 5106 | let local = z - mv_class_base(class); |
| 5107 | if class == 0 { |
| 5108 | let bit = (local >> 3) & 1; |
| 5109 | let fr = (local >> 1) & 3; |
| 5110 | bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize); |
| 5111 | bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize); |
| 5112 | } else { |
| 5113 | let d = local >> 3; |
| 5114 | let fr = (local >> 1) & 3; |
| 5115 | for i in 0..class { |
| 5116 | bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); |
| 5117 | } |
| 5118 | bits += symbol_bits(&cdf::MV_FR, fr as usize); |
| 5119 | } |
| 5120 | Some(bits) |
| 5121 | } |
| 5122 | |
| 5123 | |
| 5124 | |
| 5125 | |
| 5126 | |
| 5127 | fn extra_ref_new_mv() -> bool { |
| 5128 | match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() { |
| 5129 | Some(v) if cfg!(test) => v != "0", |
| 5130 | _ => EXTRA_REF_NEW_MV, |
| 5131 | } |
| 5132 | } |
| 5133 | |
| 5134 | |
| 5135 | |
| 5136 | |
| 5137 | |
| 5138 | |
| 5139 | |
| 5140 | pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] { |
| 5141 | let last = order_hint.wrapping_sub(1) & 0x7f; |
| 5142 | let alt = if has_altref { |
| 5143 | order_hint.wrapping_sub(2) & 0x7f |
| 5144 | } else { |
| 5145 | key_hint |
| 5146 | }; |
| 5147 | [last, last, last, key_hint, last, last, alt] |
| 5148 | } |
| 5149 | |
| 5150 | |
| 5151 | |
| 5152 | |
| 5153 | |
| 5154 | |
| 5155 | |
| 5156 | const REFERENCE_SELECT: bool = true; |
| 5157 | |
| 5158 | |
| 5159 | pub(crate) fn reference_select() -> bool { |
| 5160 | match std::env::var("EC_AV1_COMPOUND").ok() { |
| 5161 | Some(v) if cfg!(test) => v != "0", |
| 5162 | _ => REFERENCE_SELECT, |
| 5163 | } |
| 5164 | } |
| 5165 | |
| 5166 | |
| 5167 | |
| 5168 | fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 { |
| 5169 | let mut bits = 0.0; |
| 5170 | let mut idx = start; |
| 5171 | while idx < start + 2 && stack.entries.len() > idx + 1 { |
| 5172 | let advance = idx < target; |
| 5173 | bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); |
| 5174 | if !advance { |
| 5175 | break; |
| 5176 | } |
| 5177 | idx += 1; |
| 5178 | } |
| 5179 | bits |
| 5180 | } |
| 5181 | |
| 5182 | |
| 5183 | |
| 5184 | |
| 5185 | fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> { |
| 5186 | let mut best: Option<(f64, u8)> = None; |
| 5187 | for idx in 0..3usize { |
| 5188 | if idx > 0 && stack.entries.len() <= idx { |
| 5189 | break; |
| 5190 | } |
| 5191 | let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); |
| 5192 | if let Some(b) = mv_residual_bits(mv, base) { |
| 5193 | let total = b + drl_bits_for(stack, 0, idx); |
| 5194 | if best.is_none_or(|(t, _)| total < t) { |
| 5195 | best = Some((total, idx as u8)); |
| 5196 | } |
| 5197 | } |
| 5198 | } |
| 5199 | best |
| 5200 | } |
| 5201 | |
| 5202 | |
| 5203 | |
| 5204 | |
| 5205 | |
| 5206 | |
| 5207 | fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) { |
| 5208 | let mut seeds = [(0, 0); 4]; |
| 5209 | let mut n = 1; |
| 5210 | for e in stack.entries.iter().take(3) { |
| 5211 | seeds[n] = e.mv; |
| 5212 | n += 1; |
| 5213 | } |
| 5214 | (seeds, n) |
| 5215 | } |
| 5216 | |
| 5217 | |
| 5218 | |
| 5219 | |
| 5220 | |
| 5221 | |
| 5222 | |
| 5223 | |
| 5224 | |
| 5225 | fn ref_distance(ref_frame: i8) -> u32 { |
| 5226 | let (bits, order_hint, hints) = crate::tile::order_hints(); |
| 5227 | let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize; |
| 5228 | let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i]) |
| 5229 | .unsigned_abs() |
| 5230 | .max(1); |
| 5231 | if crate::envflags::env_flag!("EC_TRACE_DIST") { |
| 5232 | eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]); |
| 5233 | } |
| 5234 | d |
| 5235 | } |
| 5236 | |
| 5237 | fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> { |
| 5238 | let diff = (mv.0 - pred.0, mv.1 - pred.1); |
| 5239 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 5240 | (false, false) => 0, |
| 5241 | (false, true) => 1, |
| 5242 | (true, false) => 2, |
| 5243 | (true, true) => 3, |
| 5244 | }; |
| 5245 | let mut bits = symbol_bits(&cdf::MV_JOINT, joint); |
| 5246 | for d in [diff.0, diff.1] { |
| 5247 | if d != 0 { |
| 5248 | bits += mv_component_bits(d)?; |
| 5249 | } |
| 5250 | } |
| 5251 | Some(bits) |
| 5252 | } |
| 5253 | |
| 5254 | |
| 5255 | |
| 5256 | |
| 5257 | |
| 5258 | |
| 5259 | |
| 5260 | |
| 5261 | |
| 5262 | |
| 5263 | fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) { |
| 5264 | let round = |m: i32, p: i32| { |
| 5265 | let diff = m - p; |
| 5266 | let mag = diff.unsigned_abs() as i32; |
| 5267 | let even = mag - mag % 2; |
| 5268 | if even == 0 { |
| 5269 | p |
| 5270 | } else { |
| 5271 | p + even * diff.signum() |
| 5272 | } |
| 5273 | }; |
| 5274 | (round(mv.0, pred.0), round(mv.1, pred.1)) |
| 5275 | } |
| 5276 | |
| 5277 | |
| 5278 | |
| 5279 | #[allow(clippy::too_many_arguments)] |
| 5280 | fn mc_trial( |
| 5281 | plane: &Plane, |
| 5282 | x: usize, |
| 5283 | y: usize, |
| 5284 | side: usize, |
| 5285 | mv: (i32, i32), |
| 5286 | luma: bool, |
| 5287 | reference: &[u16], |
| 5288 | stride: usize, |
| 5289 | ref_width: usize, |
| 5290 | ref_height: usize, |
| 5291 | skip: bool, |
| 5292 | base_q_idx: u8, |
| 5293 | deadzone: f64, |
| 5294 | set: TxbSet, fctx: &crate::decode::FrameCtx, |
| 5295 | ) -> Trial { |
| 5296 | let x_q4 = mv_to_q4(x, mv.1, luma); |
| 5297 | let y_q4 = mv_to_q4(y, mv.0, luma); |
| 5298 | |
| 5299 | |
| 5300 | |
| 5301 | |
| 5302 | |
| 5303 | |
| 5304 | |
| 5305 | let mut prediction16 = [0u16; BLOCK * BLOCK]; |
| 5306 | let prediction16 = &mut prediction16[..side * side]; |
| 5307 | mc::predict( |
| 5308 | reference, |
| 5309 | stride, |
| 5310 | ref_width, |
| 5311 | ref_height, |
| 5312 | x_q4, |
| 5313 | y_q4, |
| 5314 | side, |
| 5315 | side, |
| 5316 | prediction16, fctx, |
| 5317 | ); |
| 5318 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 5319 | let prediction = &mut prediction[..side * side]; |
| 5320 | for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) { |
| 5321 | *dst = src as u8; |
| 5322 | } |
| 5323 | plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set) |
| 5324 | } |
| 5325 | |
| 5326 | |
| 5327 | |
| 5328 | |
| 5329 | |
| 5330 | |
| 5331 | |
| 5332 | #[allow(clippy::too_many_arguments)] |
| 5333 | fn mc_trial_compound( |
| 5334 | plane: &Plane, |
| 5335 | x: usize, |
| 5336 | y: usize, |
| 5337 | side: usize, |
| 5338 | (mv0, mv1): ((i32, i32), (i32, i32)), |
| 5339 | luma: bool, |
| 5340 | ref0: (&[u16], usize, usize, usize), |
| 5341 | ref1: (&[u16], usize, usize, usize), |
| 5342 | base_q_idx: u8, |
| 5343 | deadzone: f64, |
| 5344 | set: TxbSet, fctx: &crate::decode::FrameCtx, |
| 5345 | ) -> Trial { |
| 5346 | let mut inter0 = [0i32; BLOCK * BLOCK]; |
| 5347 | let mut inter1 = [0i32; BLOCK * BLOCK]; |
| 5348 | let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]); |
| 5349 | for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] { |
| 5350 | mc::predict_compound_intermediate( |
| 5351 | r.0, |
| 5352 | r.1, |
| 5353 | r.2, |
| 5354 | r.3, |
| 5355 | mv_to_q4(x, mv.1, luma), |
| 5356 | mv_to_q4(y, mv.0, luma), |
| 5357 | mc::REF_NO_SCALE, |
| 5358 | side, |
| 5359 | side, |
| 5360 | mc::InterpFilterKind::Regular, |
| 5361 | mc::InterpFilterKind::Regular, |
| 5362 | dst, |
| 5363 | ); |
| 5364 | } |
| 5365 | let mut blended16 = [0u16; BLOCK * BLOCK]; |
| 5366 | let blended16 = &mut blended16[..side * side]; |
| 5367 | mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx); |
| 5368 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 5369 | let prediction = &mut prediction[..side * side]; |
| 5370 | for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) { |
| 5371 | *dst = src as u8; |
| 5372 | } |
| 5373 | plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set) |
| 5374 | } |
| 5375 | |
| 5376 | |
| 5377 | |
| 5378 | |
| 5379 | |
| 5380 | |
| 5381 | |
| 5382 | |
| 5383 | |
| 5384 | |
| 5385 | |
| 5386 | |
| 5387 | |
| 5388 | |
| 5389 | |
| 5390 | |
| 5391 | |
| 5392 | |
| 5393 | |
| 5394 | #[allow(clippy::too_many_arguments)] |
| 5395 | fn search_inter_block( |
| 5396 | luma: &mut Plane, |
| 5397 | chroma: &mut [Plane; 2], |
| 5398 | (x, y): (usize, usize), |
| 5399 | search: &Search, |
| 5400 | mode_bits: &[f64; 13], |
| 5401 | reference: &Picture, |
| 5402 | stack: &MvStack, |
| 5403 | |
| 5404 | |
| 5405 | |
| 5406 | |
| 5407 | |
| 5408 | extra: &[(i8, &Picture, &MvStack)], |
| 5409 | |
| 5410 | |
| 5411 | |
| 5412 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx, |
| 5413 | ) -> (BlockCoeffs, f64) { |
| 5414 | |
| 5415 | |
| 5416 | |
| 5417 | |
| 5418 | let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16); |
| 5419 | let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx); |
| 5420 | |
| 5421 | |
| 5422 | |
| 5423 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 5424 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 5425 | |
| 5426 | |
| 5427 | |
| 5428 | let single_ref_bits = |ref_frame: i8| { |
| 5429 | symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 5430 | + if ref_frame == crate::mvstack::GOLDEN_FRAME { |
| 5431 | symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1) |
| 5432 | } else { |
| 5433 | symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0) |
| 5434 | } |
| 5435 | }; |
| 5436 | |
| 5437 | struct Candidate { |
| 5438 | cost: f64, |
| 5439 | luma: Trial, |
| 5440 | u: Trial, |
| 5441 | v: Trial, |
| 5442 | mode: u8, |
| 5443 | skip: bool, |
| 5444 | inter: Option<InterInfo>, |
| 5445 | } |
| 5446 | let mut best: Option<Candidate> = None; |
| 5447 | let mut consider = |candidate: Candidate| { |
| 5448 | if best.as_ref().is_none_or(|b| candidate.cost < b.cost) { |
| 5449 | best = Some(candidate); |
| 5450 | } |
| 5451 | }; |
| 5452 | |
| 5453 | |
| 5454 | |
| 5455 | |
| 5456 | |
| 5457 | |
| 5458 | |
| 5459 | |
| 5460 | |
| 5461 | let u_trial = chroma[0].trial( |
| 5462 | At { |
| 5463 | x: x / 2, |
| 5464 | y: y / 2, |
| 5465 | side: BLOCK / 2, |
| 5466 | reach: Reach::none(), |
| 5467 | set: chroma_set, |
| 5468 | }, |
| 5469 | DC_PRED, |
| 5470 | search.base_q_idx, |
| 5471 | search.deadzone, fctx, |
| 5472 | ); |
| 5473 | let v_trial = chroma[1].trial( |
| 5474 | At { |
| 5475 | x: x / 2, |
| 5476 | y: y / 2, |
| 5477 | side: BLOCK / 2, |
| 5478 | reach: Reach::none(), |
| 5479 | set: chroma_set, |
| 5480 | }, |
| 5481 | DC_PRED, |
| 5482 | search.base_q_idx, |
| 5483 | search.deadzone, fctx, |
| 5484 | ); |
| 5485 | |
| 5486 | let intra_modes: Vec<u8> = match search.top_k { |
| 5487 | Some(k) if k < search.modes.len() => { |
| 5488 | let scored = luma.intra_scores( |
| 5489 | At { |
| 5490 | x, |
| 5491 | y, |
| 5492 | side: BLOCK, |
| 5493 | reach, |
| 5494 | set: luma_set, |
| 5495 | }, |
| 5496 | search.modes, |
| 5497 | mode_bits, |
| 5498 | search.lambda, fctx, |
| 5499 | ); |
| 5500 | prune_by_sad(search.modes, scored, k) |
| 5501 | } |
| 5502 | _ => search.modes.to_vec(), |
| 5503 | }; |
| 5504 | census_add(5, 1); |
| 5505 | census_add(6, intra_modes.len()); |
| 5506 | for &mode in &intra_modes { |
| 5507 | let luma_trial = luma.trial( |
| 5508 | At { |
| 5509 | x, |
| 5510 | y, |
| 5511 | side: BLOCK, |
| 5512 | reach, |
| 5513 | set: luma_set, |
| 5514 | }, |
| 5515 | mode, |
| 5516 | search.base_q_idx, |
| 5517 | search.deadzone, fctx, |
| 5518 | ); |
| 5519 | let u = u_trial.clone(); |
| 5520 | let v = v_trial.clone(); |
| 5521 | let cost = luma_trial.sse |
| 5522 | + u.sse |
| 5523 | + v.sse |
| 5524 | + search.lambda |
| 5525 | * (luma_trial.bits |
| 5526 | + u.bits |
| 5527 | + v.bits |
| 5528 | + mode_bits[usize::from(mode)] |
| 5529 | + skip_bits(false) |
| 5530 | + intra_inter_bits(false)); |
| 5531 | consider(Candidate { |
| 5532 | cost, |
| 5533 | luma: luma_trial, |
| 5534 | u, |
| 5535 | v, |
| 5536 | mode, |
| 5537 | skip: false, |
| 5538 | inter: None, |
| 5539 | }); |
| 5540 | } |
| 5541 | |
| 5542 | |
| 5543 | |
| 5544 | |
| 5545 | |
| 5546 | |
| 5547 | |
| 5548 | |
| 5549 | |
| 5550 | |
| 5551 | |
| 5552 | let ref_luma = ( |
| 5553 | &reference.y, |
| 5554 | reference.width, |
| 5555 | luma.true_width, |
| 5556 | luma.true_height, |
| 5557 | ); |
| 5558 | let ref_u = ( |
| 5559 | &reference.u, |
| 5560 | reference.width / 2, |
| 5561 | chroma[0].true_width, |
| 5562 | chroma[0].true_height, |
| 5563 | ); |
| 5564 | let ref_v = ( |
| 5565 | &reference.v, |
| 5566 | reference.width / 2, |
| 5567 | chroma[1].true_width, |
| 5568 | chroma[1].true_height, |
| 5569 | ); |
| 5570 | |
| 5571 | |
| 5572 | |
| 5573 | |
| 5574 | |
| 5575 | |
| 5576 | let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); |
| 5577 | let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); |
| 5578 | |
| 5579 | |
| 5580 | |
| 5581 | |
| 5582 | let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target); |
| 5583 | let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME); |
| 5584 | let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ |
| 5585 | ( |
| 5586 | stack.nearest_mv, |
| 5587 | last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), |
| 5588 | InterInfo { |
| 5589 | ref1: None, |
| 5590 | mv1: (0, 0), |
| 5591 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5592 | mode: InterMode::NearestMv, |
| 5593 | mv: stack.nearest_mv, |
| 5594 | ref_mv_idx: 0, |
| 5595 | }, |
| 5596 | ), |
| 5597 | |
| 5598 | |
| 5599 | |
| 5600 | ( |
| 5601 | (0, 0), |
| 5602 | last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), |
| 5603 | InterInfo { |
| 5604 | ref1: None, |
| 5605 | mv1: (0, 0), |
| 5606 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5607 | mode: InterMode::GlobalMv, |
| 5608 | mv: (0, 0), |
| 5609 | ref_mv_idx: 0, |
| 5610 | }, |
| 5611 | ), |
| 5612 | ]; |
| 5613 | let near_bits = |
| 5614 | last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); |
| 5615 | for idx in 1..=2usize { |
| 5616 | if let Some(e) = stack.entries.get(idx) { |
| 5617 | cands.push(( |
| 5618 | e.mv, |
| 5619 | near_bits + drl_bits(1, idx), |
| 5620 | InterInfo { |
| 5621 | ref1: None, |
| 5622 | mv1: (0, 0), |
| 5623 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5624 | mode: InterMode::NearMv, |
| 5625 | mv: e.mv, |
| 5626 | ref_mv_idx: idx as u8, |
| 5627 | }, |
| 5628 | )); |
| 5629 | } |
| 5630 | } |
| 5631 | |
| 5632 | let source_block = luma.source_block(x, y, BLOCK); |
| 5633 | let (seeds, seed_n) = mv_seeds(stack); |
| 5634 | #[cfg(test)] |
| 5635 | let t = std::time::Instant::now(); |
| 5636 | let found = motion::search( |
| 5637 | ref_luma.0, |
| 5638 | ref_luma.1, |
| 5639 | ref_luma.2, |
| 5640 | ref_luma.3, |
| 5641 | &source_block, |
| 5642 | x, |
| 5643 | y, |
| 5644 | BLOCK, |
| 5645 | BLOCK, |
| 5646 | stack.pred_mv, |
| 5647 | &seeds[..seed_n], |
| 5648 | search.lambda, fctx, |
| 5649 | 1, |
| 5650 | ); |
| 5651 | #[cfg(test)] |
| 5652 | stage_add(0, t.elapsed()); |
| 5653 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 5654 | |
| 5655 | |
| 5656 | |
| 5657 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { |
| 5658 | cands.push(( |
| 5659 | mv, |
| 5660 | last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, |
| 5661 | InterInfo { |
| 5662 | ref1: None, |
| 5663 | mv1: (0, 0), |
| 5664 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5665 | mode: InterMode::NewMv, |
| 5666 | mv, |
| 5667 | ref_mv_idx, |
| 5668 | }, |
| 5669 | )); |
| 5670 | } |
| 5671 | |
| 5672 | |
| 5673 | |
| 5674 | let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new(); |
| 5675 | for &(ref_frame, g, gstack) in extra { |
| 5676 | let g_ref_bits = single_ref_bits(ref_frame); |
| 5677 | let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); |
| 5678 | cands.push(( |
| 5679 | gstack.nearest_mv, |
| 5680 | g_ref_bits |
| 5681 | + g_not_new |
| 5682 | + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1) |
| 5683 | + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0), |
| 5684 | InterInfo { |
| 5685 | ref1: None, |
| 5686 | mv1: (0, 0), |
| 5687 | ref_frame, |
| 5688 | mode: InterMode::NearestMv, |
| 5689 | mv: gstack.nearest_mv, |
| 5690 | ref_mv_idx: 0, |
| 5691 | }, |
| 5692 | )); |
| 5693 | cands.push(( |
| 5694 | (0, 0), |
| 5695 | g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0), |
| 5696 | InterInfo { |
| 5697 | ref1: None, |
| 5698 | mv1: (0, 0), |
| 5699 | ref_frame, |
| 5700 | mode: InterMode::GlobalMv, |
| 5701 | mv: (0, 0), |
| 5702 | ref_mv_idx: 0, |
| 5703 | }, |
| 5704 | )); |
| 5705 | |
| 5706 | |
| 5707 | |
| 5708 | |
| 5709 | |
| 5710 | |
| 5711 | |
| 5712 | |
| 5713 | let margin = extra_new_skip_margin(); |
| 5714 | let skip_search = extra_ref_new_mv() |
| 5715 | && margin > 0.0 |
| 5716 | && motion::cost_at( |
| 5717 | &g.y, |
| 5718 | g.width, |
| 5719 | luma.true_width, |
| 5720 | luma.true_height, |
| 5721 | &source_block, |
| 5722 | x, |
| 5723 | y, |
| 5724 | BLOCK, |
| 5725 | BLOCK, |
| 5726 | gstack.nearest_mv, |
| 5727 | gstack.pred_mv, |
| 5728 | search.lambda, |
| 5729 | fctx, |
| 5730 | ) * margin |
| 5731 | <= found.cost; |
| 5732 | if extra_ref_new_mv() && !skip_search { |
| 5733 | let (gseeds, gn) = mv_seeds(gstack); |
| 5734 | #[cfg(test)] |
| 5735 | let t = std::time::Instant::now(); |
| 5736 | let gfound = motion::search( |
| 5737 | &g.y, |
| 5738 | g.width, |
| 5739 | luma.true_width, |
| 5740 | luma.true_height, |
| 5741 | &source_block, |
| 5742 | x, |
| 5743 | y, |
| 5744 | BLOCK, |
| 5745 | BLOCK, |
| 5746 | gstack.pred_mv, |
| 5747 | &gseeds[..gn], |
| 5748 | search.lambda, fctx, |
| 5749 | ref_distance(ref_frame), |
| 5750 | ); |
| 5751 | #[cfg(test)] |
| 5752 | stage_add(0, t.elapsed()); |
| 5753 | let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); |
| 5754 | extra_new_mvs.push((ref_frame, gmv)); |
| 5755 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { |
| 5756 | cands.push(( |
| 5757 | gmv, |
| 5758 | g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits, |
| 5759 | InterInfo { |
| 5760 | ref1: None, |
| 5761 | mv1: (0, 0), |
| 5762 | ref_frame, |
| 5763 | mode: InterMode::NewMv, |
| 5764 | mv: gmv, |
| 5765 | ref_mv_idx, |
| 5766 | }, |
| 5767 | )); |
| 5768 | } |
| 5769 | } |
| 5770 | } |
| 5771 | |
| 5772 | |
| 5773 | |
| 5774 | |
| 5775 | |
| 5776 | |
| 5777 | |
| 5778 | |
| 5779 | |
| 5780 | |
| 5781 | |
| 5782 | let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR"); |
| 5783 | let half_new = true; |
| 5784 | for (ref1, g, cstack) in compound { |
| 5785 | let (ref1, g) = (*ref1, *g); |
| 5786 | let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME) |
| 5787 | .contains(&ref1); |
| 5788 | let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1) |
| 5789 | + if uni { |
| 5790 | |
| 5791 | |
| 5792 | symbol_bits(&cdf::COMP_REF_TYPE[0], 1) |
| 5793 | + symbol_bits(&cdf::COMP_REF[0][0], 0) |
| 5794 | + symbol_bits(&cdf::COMP_REF[0][1], 0) |
| 5795 | + symbol_bits(&cdf::COMP_BWDREF[0][0], 1) |
| 5796 | } else { |
| 5797 | |
| 5798 | symbol_bits(&cdf::COMP_REF_TYPE[0], 0) |
| 5799 | + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0) |
| 5800 | + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1) |
| 5801 | + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1) |
| 5802 | }; |
| 5803 | let mode_ctx = |
| 5804 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 5805 | let mode_bits_of = |
| 5806 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 5807 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 5808 | ( |
| 5809 | cstack.nearest_mv, |
| 5810 | mode_bits_of(0), |
| 5811 | InterInfo { |
| 5812 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5813 | mode: InterMode::NearestNearestMv, |
| 5814 | mv: cstack.nearest_mv.0, |
| 5815 | mv1: cstack.nearest_mv.1, |
| 5816 | ref1: Some(ref1), |
| 5817 | ref_mv_idx: 0, |
| 5818 | }, |
| 5819 | ), |
| 5820 | ( |
| 5821 | ((0, 0), (0, 0)), |
| 5822 | mode_bits_of(6), |
| 5823 | InterInfo { |
| 5824 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5825 | mode: InterMode::GlobalGlobalMv, |
| 5826 | mv: (0, 0), |
| 5827 | mv1: (0, 0), |
| 5828 | ref1: Some(ref1), |
| 5829 | ref_mv_idx: 0, |
| 5830 | }, |
| 5831 | ), |
| 5832 | ]; |
| 5833 | |
| 5834 | |
| 5835 | |
| 5836 | if let Some(e) = cstack.entries.get(1).filter(|_| near_near) { |
| 5837 | let drl = if cstack.entries.len() > 2 { |
| 5838 | symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0) |
| 5839 | } else { |
| 5840 | 0.0 |
| 5841 | }; |
| 5842 | ccands.push(( |
| 5843 | (e.mv0, e.mv1), |
| 5844 | mode_bits_of(1) + drl, |
| 5845 | InterInfo { |
| 5846 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5847 | mode: InterMode::NearNearMv, |
| 5848 | mv: e.mv0, |
| 5849 | mv1: e.mv1, |
| 5850 | ref1: Some(ref1), |
| 5851 | ref_mv_idx: 0, |
| 5852 | }, |
| 5853 | )); |
| 5854 | } |
| 5855 | |
| 5856 | |
| 5857 | |
| 5858 | |
| 5859 | let cbase = cstack |
| 5860 | .entries |
| 5861 | .first() |
| 5862 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 5863 | if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) { |
| 5864 | ccands.push(( |
| 5865 | (mv, cstack.nearest_mv.1), |
| 5866 | mode_bits_of(3) + b0, |
| 5867 | InterInfo { |
| 5868 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5869 | mode: InterMode::NewNearestMv, |
| 5870 | mv, |
| 5871 | mv1: cstack.nearest_mv.1, |
| 5872 | ref1: Some(ref1), |
| 5873 | ref_mv_idx: 0, |
| 5874 | }, |
| 5875 | )); |
| 5876 | } |
| 5877 | if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) { |
| 5878 | if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) { |
| 5879 | ccands.push(( |
| 5880 | (cstack.nearest_mv.0, mv1), |
| 5881 | mode_bits_of(2) + b1, |
| 5882 | InterInfo { |
| 5883 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5884 | mode: InterMode::NearestNewMv, |
| 5885 | mv: cstack.nearest_mv.0, |
| 5886 | mv1, |
| 5887 | ref1: Some(ref1), |
| 5888 | ref_mv_idx: 0, |
| 5889 | }, |
| 5890 | )); |
| 5891 | } |
| 5892 | let base = cbase; |
| 5893 | if let (Some(b0), Some(b1)) = ( |
| 5894 | mv_residual_bits(mv, base.0), |
| 5895 | mv_residual_bits(mv1, base.1), |
| 5896 | ) { |
| 5897 | ccands.push(( |
| 5898 | (mv, mv1), |
| 5899 | mode_bits_of(7) + b0 + b1, |
| 5900 | InterInfo { |
| 5901 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5902 | mode: InterMode::NewNewMv, |
| 5903 | mv, |
| 5904 | mv1, |
| 5905 | ref1: Some(ref1), |
| 5906 | ref_mv_idx: 0, |
| 5907 | }, |
| 5908 | )); |
| 5909 | } |
| 5910 | } |
| 5911 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 5912 | ccands.dedup_by_key(|c| c.0); |
| 5913 | let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); |
| 5914 | let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height); |
| 5915 | let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height); |
| 5916 | for (mvs, bits, info) in ccands { |
| 5917 | let luma_trial = mc_trial_compound( |
| 5918 | luma, x, y, BLOCK, mvs, true, |
| 5919 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, |
| 5920 | search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx, |
| 5921 | ); |
| 5922 | let u = mc_trial_compound( |
| 5923 | &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false, |
| 5924 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, |
| 5925 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 5926 | ); |
| 5927 | let v = mc_trial_compound( |
| 5928 | &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false, |
| 5929 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, |
| 5930 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 5931 | ); |
| 5932 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 5933 | && u.levels.iter().all(|&l| l == 0) |
| 5934 | && v.levels.iter().all(|&l| l == 0); |
| 5935 | let cost = luma_trial.sse |
| 5936 | + u.sse |
| 5937 | + v.sse |
| 5938 | + search.lambda |
| 5939 | * (skip_bits(skip) |
| 5940 | + intra_inter_bits(true) |
| 5941 | + bits |
| 5942 | + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); |
| 5943 | consider(Candidate { |
| 5944 | cost, |
| 5945 | luma: luma_trial, |
| 5946 | u, |
| 5947 | v, |
| 5948 | mode: DC_PRED, |
| 5949 | skip, |
| 5950 | inter: Some(info), |
| 5951 | }); |
| 5952 | } |
| 5953 | } |
| 5954 | |
| 5955 | |
| 5956 | |
| 5957 | cands.sort_by(|a, b| { |
| 5958 | (a.2.ref_frame, a.0) |
| 5959 | .cmp(&(b.2.ref_frame, b.0)) |
| 5960 | .then(a.1.total_cmp(&b.1)) |
| 5961 | }); |
| 5962 | cands.dedup_by_key(|c| (c.2.ref_frame, c.0)); |
| 5963 | census_add(7, cands.len()); |
| 5964 | { |
| 5965 | for (mv, mode_bits_inter, info) in cands { |
| 5966 | let (ref_luma, ref_u, ref_v) = match extra |
| 5967 | .iter() |
| 5968 | .find(|(r, _, _)| *r == info.ref_frame) |
| 5969 | { |
| 5970 | Some(&(_, g, _)) => ( |
| 5971 | (&g.y, g.width, luma.true_width, luma.true_height), |
| 5972 | (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 5973 | (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 5974 | ), |
| 5975 | None => (ref_luma, ref_u, ref_v), |
| 5976 | }; |
| 5977 | let luma_trial = mc_trial( |
| 5978 | luma, |
| 5979 | x, |
| 5980 | y, |
| 5981 | BLOCK, |
| 5982 | mv, |
| 5983 | true, |
| 5984 | ref_luma.0, |
| 5985 | ref_luma.1, |
| 5986 | ref_luma.2, |
| 5987 | ref_luma.3, |
| 5988 | false, |
| 5989 | search.base_q_idx, |
| 5990 | search.deadzone, |
| 5991 | TxbSet::Luma32Inter, fctx, |
| 5992 | ); |
| 5993 | let u = mc_trial( |
| 5994 | &chroma[0], |
| 5995 | x / 2, |
| 5996 | y / 2, |
| 5997 | BLOCK / 2, |
| 5998 | mv, |
| 5999 | false, |
| 6000 | ref_u.0, |
| 6001 | ref_u.1, |
| 6002 | ref_u.2, |
| 6003 | ref_u.3, |
| 6004 | false, |
| 6005 | search.base_q_idx, |
| 6006 | search.deadzone, |
| 6007 | chroma_set, fctx, |
| 6008 | ); |
| 6009 | let v = mc_trial( |
| 6010 | &chroma[1], |
| 6011 | x / 2, |
| 6012 | y / 2, |
| 6013 | BLOCK / 2, |
| 6014 | mv, |
| 6015 | false, |
| 6016 | ref_v.0, |
| 6017 | ref_v.1, |
| 6018 | ref_v.2, |
| 6019 | ref_v.3, |
| 6020 | false, |
| 6021 | search.base_q_idx, |
| 6022 | search.deadzone, |
| 6023 | chroma_set, fctx, |
| 6024 | ); |
| 6025 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 6026 | && u.levels.iter().all(|&l| l == 0) |
| 6027 | && v.levels.iter().all(|&l| l == 0); |
| 6028 | let cost = luma_trial.sse |
| 6029 | + u.sse |
| 6030 | + v.sse |
| 6031 | + search.lambda |
| 6032 | * (skip_bits(skip) |
| 6033 | + intra_inter_bits(true) |
| 6034 | + mode_bits_inter |
| 6035 | + if skip { |
| 6036 | 0.0 |
| 6037 | } else { |
| 6038 | luma_trial.bits + u.bits + v.bits |
| 6039 | }); |
| 6040 | consider(Candidate { |
| 6041 | cost, |
| 6042 | luma: luma_trial, |
| 6043 | u, |
| 6044 | v, |
| 6045 | mode: DC_PRED, |
| 6046 | skip, |
| 6047 | inter: Some(info), |
| 6048 | }); |
| 6049 | } |
| 6050 | } |
| 6051 | |
| 6052 | let best = best.expect("the search offers at least the intra modes"); |
| 6053 | luma.commit(x, y, BLOCK, &best.luma); |
| 6054 | chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u); |
| 6055 | chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); |
| 6056 | ( |
| 6057 | BlockCoeffs { |
| 6058 | luma: coeffs(&best.luma.levels, BLOCK), |
| 6059 | u: coeffs(&best.u.levels, BLOCK / 2), |
| 6060 | v: coeffs(&best.v.levels, BLOCK / 2), |
| 6061 | mode: best.mode, |
| 6062 | uv_mode: DC_PRED, |
| 6063 | skip: best.skip, |
| 6064 | inter: best.inter, |
| 6065 | eight: None, |
| 6066 | dv: None, |
| 6067 | palette: None, |
| 6068 | palette_uv: None, |
| 6069 | tx_depth: 0, |
| 6070 | }, |
| 6071 | best.cost, |
| 6072 | ) |
| 6073 | } |
| 6074 | |
| 6075 | |
| 6076 | |
| 6077 | |
| 6078 | |
| 6079 | |
| 6080 | |
| 6081 | |
| 6082 | |
| 6083 | |
| 6084 | |
| 6085 | #[derive(Debug, Clone, Copy)] |
| 6086 | pub(crate) struct PyramidFrame { |
| 6087 | |
| 6088 | |
| 6089 | pub last_slot: u8, |
| 6090 | |
| 6091 | pub self_slot: u8, |
| 6092 | |
| 6093 | |
| 6094 | pub altref_slot: u8, |
| 6095 | |
| 6096 | |
| 6097 | pub show_frame: bool, |
| 6098 | |
| 6099 | pub sign_bias: crate::mvstack::SignBiasTable, |
| 6100 | } |
| 6101 | |
| 6102 | |
| 6103 | |
| 6104 | |
| 6105 | pub(crate) fn encode_inter_frame( |
| 6106 | picture: &Picture, |
| 6107 | reference: &Picture, |
| 6108 | base_q_idx: u8, |
| 6109 | deadzone: f64, |
| 6110 | order_hint: u32, |
| 6111 | |
| 6112 | |
| 6113 | |
| 6114 | |
| 6115 | |
| 6116 | order_hints: [u32; 7], |
| 6117 | render: (usize, usize), |
| 6118 | |
| 6119 | |
| 6120 | |
| 6121 | |
| 6122 | start_cdfs: Option<&crate::cdf_state::Cdfs>, |
| 6123 | |
| 6124 | |
| 6125 | |
| 6126 | golden: Option<&Picture>, |
| 6127 | |
| 6128 | |
| 6129 | |
| 6130 | altref: Option<&Picture>, fctx: &crate::decode::FrameCtx, |
| 6131 | |
| 6132 | |
| 6133 | pyramid: Option<PyramidFrame>, |
| 6134 | ) -> Result<Encoded> { |
| 6135 | picture.check()?; |
| 6136 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| 6137 | return Err(Error::unsupported( |
| 6138 | "AV1 encode", |
| 6139 | "an inter frame is coded only for a picture that is a whole number \ |
| 6140 | of 64x64 superblocks -- the inter tile writer never splits a \ |
| 6141 | superblock's partition below that", |
| 6142 | )); |
| 6143 | } |
| 6144 | if reference.width != picture.width || reference.height != picture.height { |
| 6145 | return Err(Error::unsupported( |
| 6146 | "AV1 encode", |
| 6147 | "the reference picture must be the same size as the one being coded", |
| 6148 | )); |
| 6149 | } |
| 6150 | |
| 6151 | |
| 6152 | |
| 6153 | |
| 6154 | |
| 6155 | const LAST_SLOT: u8 = 0; |
| 6156 | |
| 6157 | |
| 6158 | |
| 6159 | |
| 6160 | let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot); |
| 6161 | let last_slot = pyramid.map_or( |
| 6162 | if order_hint <= 1 { |
| 6163 | LAST_SLOT |
| 6164 | } else if (order_hint - 1) % 2 == 1 { |
| 6165 | 0 |
| 6166 | } else { |
| 6167 | 2 |
| 6168 | }, |
| 6169 | |p| p.last_slot, |
| 6170 | ); |
| 6171 | |
| 6172 | |
| 6173 | |
| 6174 | |
| 6175 | |
| 6176 | |
| 6177 | let (seq, mut header) = inter_frame_headers_slots( |
| 6178 | render.0, |
| 6179 | render.1, |
| 6180 | base_q_idx, |
| 6181 | order_hint, |
| 6182 | last_slot, |
| 6183 | self_slot, |
| 6184 | match pyramid { |
| 6185 | Some(p) => p.altref_slot, |
| 6186 | None if altref.is_some() => self_slot, |
| 6187 | None => GOLDEN_SLOT, |
| 6188 | }, |
| 6189 | )?; |
| 6190 | header.render_width = render.0 as u32; |
| 6191 | header.render_height = render.1 as u32; |
| 6192 | let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias); |
| 6193 | |
| 6194 | |
| 6195 | |
| 6196 | |
| 6197 | |
| 6198 | |
| 6199 | header.order_hints = order_hints; |
| 6200 | header.reference_select = reference_select(); |
| 6201 | |
| 6202 | |
| 6203 | |
| 6204 | |
| 6205 | |
| 6206 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 6207 | if let Some(p) = pyramid { |
| 6208 | header.show_frame = p.show_frame; |
| 6209 | header.showable_frame = !p.show_frame; |
| 6210 | header.ref_frame_sign_bias = p.sign_bias; |
| 6211 | } |
| 6212 | |
| 6213 | |
| 6214 | |
| 6215 | |
| 6216 | let tx_select = tx_select() && tx_select_inter(); |
| 6217 | if tx_select { |
| 6218 | header.tx_mode = TxMode::Select; |
| 6219 | } |
| 6220 | |
| 6221 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 6222 | |
| 6223 | |
| 6224 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 6225 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 6226 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 6227 | |
| 6228 | |
| 6229 | |
| 6230 | |
| 6231 | |
| 6232 | let screen = seq_screen() |
| 6233 | && screen_content(&picture_y8, picture.width, true_width, true_height); |
| 6234 | header.allow_screen_content_tools = screen; |
| 6235 | let mut luma = Plane { |
| 6236 | source: &picture_y8, |
| 6237 | reconstruction: vec![128; picture_y8.len()], |
| 6238 | width: picture.width, |
| 6239 | height: picture.height, |
| 6240 | true_width, |
| 6241 | true_height, |
| 6242 | tile_x0: 0, |
| 6243 | tile_y0: 0, |
| 6244 | tile_x1: picture.width, |
| 6245 | tile_y1: picture.height, |
| 6246 | }; |
| 6247 | let mut chroma = [ |
| 6248 | Plane { |
| 6249 | source: &picture_u8, |
| 6250 | reconstruction: vec![128; picture_u8.len()], |
| 6251 | width: picture.width / 2, |
| 6252 | height: picture.height / 2, |
| 6253 | true_width: true_width / 2, |
| 6254 | true_height: true_height / 2, |
| 6255 | tile_x0: 0, |
| 6256 | tile_y0: 0, |
| 6257 | tile_x1: picture.width / 2, |
| 6258 | tile_y1: picture.height / 2, |
| 6259 | }, |
| 6260 | Plane { |
| 6261 | source: &picture_v8, |
| 6262 | reconstruction: vec![128; picture_v8.len()], |
| 6263 | width: picture.width / 2, |
| 6264 | height: picture.height / 2, |
| 6265 | true_width: true_width / 2, |
| 6266 | true_height: true_height / 2, |
| 6267 | tile_x0: 0, |
| 6268 | tile_y0: 0, |
| 6269 | tile_x1: picture.width / 2, |
| 6270 | tile_y1: picture.height / 2, |
| 6271 | }, |
| 6272 | ]; |
| 6273 | |
| 6274 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 6275 | let search = Search { |
| 6276 | base_q_idx, |
| 6277 | deadzone, |
| 6278 | lambda: lambda_scale() * step * step, |
| 6279 | modes: &KEY_FRAME_MODES, |
| 6280 | top_k: prune_top_k_inter(), |
| 6281 | screen, |
| 6282 | }; |
| 6283 | let mode_bits_table = inter_mode_bits(); |
| 6284 | |
| 6285 | |
| 6286 | |
| 6287 | |
| 6288 | |
| 6289 | |
| 6290 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 6291 | let (cols, rows) = (cols as usize, rows as usize); |
| 6292 | let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 6293 | let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize); |
| 6294 | |
| 6295 | let (tile_cols_log2, tile_rows_log2) = armed_tiles(); |
| 6296 | let layout = |
| 6297 | crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); |
| 6298 | header.tile_info = tile_info_of(&layout, 1); |
| 6299 | let header_tile_info = header.tile_info.clone(); |
| 6300 | |
| 6301 | |
| 6302 | |
| 6303 | |
| 6304 | let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows]; |
| 6305 | |
| 6306 | |
| 6307 | |
| 6308 | |
| 6309 | |
| 6310 | |
| 6311 | |
| 6312 | let (frame_width, frame_height) = (picture.width, picture.height); |
| 6313 | let luma_out = crate::par::Shared::new(&mut luma.reconstruction); |
| 6314 | let [cb, cr] = &mut chroma; |
| 6315 | let chroma_out = [ |
| 6316 | crate::par::Shared::new(&mut cb.reconstruction), |
| 6317 | crate::par::Shared::new(&mut cr.reconstruction), |
| 6318 | ]; |
| 6319 | let search_tile = |index: usize, |
| 6320 | fctx: &crate::decode::FrameCtx| |
| 6321 | -> Result<Vec<(usize, Quadrant)>> { |
| 6322 | |
| 6323 | |
| 6324 | |
| 6325 | |
| 6326 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 6327 | let rect = layout.rect(index); |
| 6328 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 6329 | let mut chroma = [ |
| 6330 | fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 6331 | fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 6332 | ]; |
| 6333 | clip_planes_to_tile(&mut luma, &mut chroma, rect); |
| 6334 | let mut grid = MiGrid::new(mi_cols, mi_rows); |
| 6335 | grid.set_sign_bias(sign_bias); |
| 6336 | grid.set_tile_bounds( |
| 6337 | rect.mi_row0 as usize, |
| 6338 | rect.mi_col0 as usize, |
| 6339 | rect.mi_row1 as usize, |
| 6340 | rect.mi_col1 as usize, |
| 6341 | ); |
| 6342 | let mut blocks: Vec<(usize, Quadrant)> = Vec::new(); |
| 6343 | for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize { |
| 6344 | for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize { |
| 6345 | for quadrant in 0..4 { |
| 6346 | let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 6347 | |
| 6348 | |
| 6349 | if r32 >= rows || c32 >= cols { |
| 6350 | continue; |
| 6351 | } |
| 6352 | |
| 6353 | |
| 6354 | |
| 6355 | |
| 6356 | |
| 6357 | |
| 6358 | |
| 6359 | |
| 6360 | let (has_cols32, has_rows32) = ( |
| 6361 | crate::tile::has_half( |
| 6362 | c32 as u32 * crate::tile::BLOCK_MI, |
| 6363 | crate::tile::BLOCK_MI, |
| 6364 | header.mi_cols, |
| 6365 | ), |
| 6366 | crate::tile::has_half( |
| 6367 | r32 as u32 * crate::tile::BLOCK_MI, |
| 6368 | crate::tile::BLOCK_MI, |
| 6369 | header.mi_rows, |
| 6370 | ), |
| 6371 | ); |
| 6372 | if has_cols32 && has_rows32 { |
| 6373 | let (x, y) = (c32 * BLOCK, r32 * BLOCK); |
| 6374 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); |
| 6375 | let stack = |
| 6376 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); |
| 6377 | let extra_stacks: Vec<(i8, &Picture, MvStack)> = [ |
| 6378 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 6379 | (crate::mvstack::ALTREF_FRAME, altref), |
| 6380 | ] |
| 6381 | .into_iter() |
| 6382 | .filter_map(|(r, pic)| { |
| 6383 | pic.map(|p| { |
| 6384 | ( |
| 6385 | r, |
| 6386 | p, |
| 6387 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows), |
| 6388 | ) |
| 6389 | }) |
| 6390 | }) |
| 6391 | .collect(); |
| 6392 | let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks |
| 6393 | .iter() |
| 6394 | .map(|(r, p, st)| (*r, *p, st)) |
| 6395 | .collect(); |
| 6396 | |
| 6397 | |
| 6398 | |
| 6399 | |
| 6400 | let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 6401 | if header.reference_select { |
| 6402 | extra_stacks |
| 6403 | .iter() |
| 6404 | .map(|&(r, p, _)| { |
| 6405 | ( |
| 6406 | r, |
| 6407 | p, |
| 6408 | crate::mvstack::find_mv_stack_compound( |
| 6409 | &grid, |
| 6410 | mi_row, |
| 6411 | mi_col, |
| 6412 | 8, |
| 6413 | 8, |
| 6414 | (crate::mvstack::LAST_FRAME, r), |
| 6415 | mi_cols, |
| 6416 | mi_rows, |
| 6417 | grid.sign_bias_table(), |
| 6418 | &[(0, 0); 7], |
| 6419 | None, |
| 6420 | ), |
| 6421 | ) |
| 6422 | }) |
| 6423 | .collect() |
| 6424 | } else { |
| 6425 | Vec::new() |
| 6426 | }; |
| 6427 | |
| 6428 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 6429 | let (block, mut cost_whole) = search_inter_block( |
| 6430 | &mut luma, |
| 6431 | &mut chroma, |
| 6432 | (x, y), |
| 6433 | &search, |
| 6434 | &mode_bits_table, |
| 6435 | reference, |
| 6436 | &stack, |
| 6437 | &extra, |
| 6438 | &compound, fctx, |
| 6439 | ); |
| 6440 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 6441 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 6442 | |
| 6443 | |
| 6444 | |
| 6445 | |
| 6446 | |
| 6447 | |
| 6448 | |
| 6449 | |
| 6450 | |
| 6451 | |
| 6452 | |
| 6453 | |
| 6454 | |
| 6455 | let leaf_positions: Vec<(usize, usize)> = (0..4) |
| 6456 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 6457 | .collect(); |
| 6458 | let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| { |
| 6459 | crate::tile::has_half( |
| 6460 | sc as u32 * crate::tile::SUB_MI, |
| 6461 | crate::tile::SUB_MI, |
| 6462 | header.mi_cols, |
| 6463 | ) && crate::tile::has_half( |
| 6464 | sr as u32 * crate::tile::SUB_MI, |
| 6465 | crate::tile::SUB_MI, |
| 6466 | header.mi_rows, |
| 6467 | ) |
| 6468 | }); |
| 6469 | |
| 6470 | |
| 6471 | let breakout = split_breakout_coeffs(); |
| 6472 | let split = (!block.skip |
| 6473 | && !split_rd_breakout(cost_whole, BLOCK, search.lambda) |
| 6474 | && (breakout == 0 || block.luma.len() > 4 * breakout) |
| 6475 | && leaves_legal |
| 6476 | && split_inter_blocks()) |
| 6477 | .then(|| { |
| 6478 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); |
| 6479 | let mut cost = search.lambda * partition_bits(BLOCK, true); |
| 6480 | let mut leaves = Vec::with_capacity(4); |
| 6481 | for &(sr, sc) in &leaf_positions { |
| 6482 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 6483 | let (lx, ly) = (sc * SUB, sr * SUB); |
| 6484 | let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 6485 | let stack = find_mv_stack( |
| 6486 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 6487 | ); |
| 6488 | let cstacks: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 6489 | if header.reference_select && leaf_compound() { |
| 6490 | [ |
| 6491 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 6492 | (crate::mvstack::ALTREF_FRAME, altref), |
| 6493 | ] |
| 6494 | .into_iter() |
| 6495 | .filter_map(|(r, pic)| { |
| 6496 | pic.map(|p| { |
| 6497 | ( |
| 6498 | r, |
| 6499 | p, |
| 6500 | crate::mvstack::find_mv_stack_compound( |
| 6501 | &grid, mi_row, mi_col, 4, 4, |
| 6502 | (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows, |
| 6503 | grid.sign_bias_table(), &[(0, 0); 7], None, |
| 6504 | ), |
| 6505 | ) |
| 6506 | }) |
| 6507 | }) |
| 6508 | .collect() |
| 6509 | } else { |
| 6510 | Vec::new() |
| 6511 | }; |
| 6512 | let (leaf, leaf_cost) = code_square_inter( |
| 6513 | &mut luma, |
| 6514 | &mut chroma, |
| 6515 | (lx, ly), |
| 6516 | SUB, |
| 6517 | &search, |
| 6518 | &mode_bits_table, |
| 6519 | reference, |
| 6520 | &stack, &cstacks, fctx, |
| 6521 | ); |
| 6522 | let leaf_cost = leaf_cost |
| 6523 | + search.lambda * partition_bits(SUB, false); |
| 6524 | let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 6525 | |
| 6526 | |
| 6527 | |
| 6528 | |
| 6529 | |
| 6530 | |
| 6531 | let eight = (!leaf.skip |
| 6532 | && !split_rd_breakout(leaf_cost, SUB, search.lambda) |
| 6533 | && (breakout == 0 || leaf.luma.len() > breakout) |
| 6534 | && split_inter_8()) |
| 6535 | .then(|| { |
| 6536 | restore( |
| 6537 | &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base, |
| 6538 | ); |
| 6539 | let mut cost8 = search.lambda |
| 6540 | * (partition_bits(SUB, true) |
| 6541 | + 4.0 * partition_bits(8, false)); |
| 6542 | let mut eight = Vec::with_capacity(4); |
| 6543 | for i in 0..4 { |
| 6544 | let (mr, mc) = |
| 6545 | (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2); |
| 6546 | let stack8 = find_mv_stack( |
| 6547 | &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 6548 | ); |
| 6549 | let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 6550 | if header.reference_select && leaf_compound() { |
| 6551 | [ |
| 6552 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 6553 | (crate::mvstack::ALTREF_FRAME, altref), |
| 6554 | ] |
| 6555 | .into_iter() |
| 6556 | .filter_map(|(r, pic)| { |
| 6557 | pic.map(|p| { |
| 6558 | ( |
| 6559 | r, |
| 6560 | p, |
| 6561 | crate::mvstack::find_mv_stack_compound( |
| 6562 | &grid, mr, mc, 2, 2, |
| 6563 | (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows, |
| 6564 | grid.sign_bias_table(), &[(0, 0); 7], None, |
| 6565 | ), |
| 6566 | ) |
| 6567 | }) |
| 6568 | }) |
| 6569 | .collect() |
| 6570 | } else { |
| 6571 | Vec::new() |
| 6572 | }; |
| 6573 | let (leaf8, cost) = code_square_inter( |
| 6574 | &mut luma, |
| 6575 | &mut chroma, |
| 6576 | (lx + (i % 2) * 8, ly + (i / 2) * 8), |
| 6577 | 8, |
| 6578 | &search, |
| 6579 | &mode_bits_table, |
| 6580 | reference, |
| 6581 | &stack8, &cstacks8, fctx, |
| 6582 | ); |
| 6583 | cost8 += cost; |
| 6584 | record_mi(&mut grid, mr, mc, 2, leaf8.inter); |
| 6585 | eight.push(leaf8); |
| 6586 | } |
| 6587 | (eight, cost8) |
| 6588 | }); |
| 6589 | match eight { |
| 6590 | Some((eight, cost8)) if cost8 < leaf_cost => { |
| 6591 | partition_hit(3); |
| 6592 | cost += cost8; |
| 6593 | leaves.push(BlockCoeffs { |
| 6594 | eight: Some(eight), |
| 6595 | ..BlockCoeffs::default() |
| 6596 | }); |
| 6597 | continue; |
| 6598 | } |
| 6599 | Some(_) => restore( |
| 6600 | &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf, |
| 6601 | ), |
| 6602 | None => {} |
| 6603 | } |
| 6604 | partition_hit(2); |
| 6605 | cost += leaf_cost; |
| 6606 | record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter); |
| 6607 | leaves.push(leaf); |
| 6608 | } |
| 6609 | (leaves, cost) |
| 6610 | }); |
| 6611 | if let Some((leaves, cost)) = split { |
| 6612 | if cost < cost_whole { |
| 6613 | |
| 6614 | |
| 6615 | |
| 6616 | partition_hit(1); |
| 6617 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 6618 | continue; |
| 6619 | } |
| 6620 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); |
| 6621 | } |
| 6622 | partition_hit(0); |
| 6623 | record_mi(&mut grid, mi_row, mi_col, 8, block.inter); |
| 6624 | blocks.push((r32 * cols + c32, Quadrant::Whole(block))); |
| 6625 | } else { |
| 6626 | |
| 6627 | |
| 6628 | let sub_positions: Vec<(usize, usize)> = (0..4) |
| 6629 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 6630 | .filter(|&(sr, sc)| { |
| 6631 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 6632 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 6633 | }) |
| 6634 | .collect(); |
| 6635 | |
| 6636 | |
| 6637 | |
| 6638 | |
| 6639 | |
| 6640 | |
| 6641 | |
| 6642 | |
| 6643 | |
| 6644 | let mut leaves = Vec::with_capacity(sub_positions.len()); |
| 6645 | for (sr, sc) in sub_positions { |
| 6646 | let (has_cols16, has_rows16) = ( |
| 6647 | crate::tile::has_half( |
| 6648 | sc as u32 * crate::tile::SUB_MI, |
| 6649 | crate::tile::SUB_MI, |
| 6650 | header.mi_cols, |
| 6651 | ), |
| 6652 | crate::tile::has_half( |
| 6653 | sr as u32 * crate::tile::SUB_MI, |
| 6654 | crate::tile::SUB_MI, |
| 6655 | header.mi_rows, |
| 6656 | ), |
| 6657 | ); |
| 6658 | if !has_cols16 && !has_rows16 { |
| 6659 | return Err(Error::unsupported( |
| 6660 | "AV1 encode", |
| 6661 | format!( |
| 6662 | "the 16x16 block at ({sc},{sr}) straddles the true \ |
| 6663 | frame edge in a way that needs a rectangular \ |
| 6664 | (HORZ/VERT) transform this encoder does not code yet" |
| 6665 | ), |
| 6666 | )); |
| 6667 | } |
| 6668 | if has_cols16 && has_rows16 { |
| 6669 | let (x, y) = (sc * SUB, sr * SUB); |
| 6670 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 6671 | let stack = find_mv_stack( |
| 6672 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 6673 | ); |
| 6674 | let (block, _) = code_square_inter( |
| 6675 | &mut luma, |
| 6676 | &mut chroma, |
| 6677 | (x, y), |
| 6678 | SUB, |
| 6679 | &search, |
| 6680 | &mode_bits_table, |
| 6681 | reference, |
| 6682 | &stack, &[], fctx, |
| 6683 | ); |
| 6684 | |
| 6685 | |
| 6686 | |
| 6687 | |
| 6688 | |
| 6689 | |
| 6690 | record_mi(&mut grid, mi_row, mi_col, 4, block.inter); |
| 6691 | leaves.push(block); |
| 6692 | } else { |
| 6693 | let (x_sub, y_sub) = (sc * SUB, sr * SUB); |
| 6694 | let (mi_row0, mi_col0) = (sr * 4, sc * 4); |
| 6695 | let mut eight = Vec::with_capacity(2); |
| 6696 | for i in 0..4 { |
| 6697 | let leaf_x = x_sub + (i % 2) * 8; |
| 6698 | let leaf_y = y_sub + (i / 2) * 8; |
| 6699 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 6700 | continue; |
| 6701 | } |
| 6702 | let (mi_row, mi_col) = |
| 6703 | (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); |
| 6704 | let stack = find_mv_stack( |
| 6705 | &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 6706 | ); |
| 6707 | let (leaf, _) = code_square_inter( |
| 6708 | &mut luma, |
| 6709 | &mut chroma, |
| 6710 | (leaf_x, leaf_y), |
| 6711 | 8, |
| 6712 | &search, |
| 6713 | &mode_bits_table, |
| 6714 | reference, |
| 6715 | &stack, &[], fctx, |
| 6716 | ); |
| 6717 | |
| 6718 | |
| 6719 | record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter); |
| 6720 | eight.push(leaf); |
| 6721 | } |
| 6722 | leaves.push(BlockCoeffs { |
| 6723 | eight: Some(eight), |
| 6724 | ..BlockCoeffs::default() |
| 6725 | }); |
| 6726 | } |
| 6727 | } |
| 6728 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 6729 | } |
| 6730 | } |
| 6731 | } |
| 6732 | } |
| 6733 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 6734 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 6735 | copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1); |
| 6736 | for (&out, tile) in chroma_out.iter().zip(&chroma) { |
| 6737 | copy_rect( |
| 6738 | out, |
| 6739 | &tile.reconstruction, |
| 6740 | frame_width / 2, |
| 6741 | x0 / 2, |
| 6742 | y0 / 2, |
| 6743 | x1.div_ceil(2), |
| 6744 | y1.div_ceil(2), |
| 6745 | ); |
| 6746 | } |
| 6747 | Ok(blocks) |
| 6748 | }; |
| 6749 | for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)? |
| 6750 | .into_iter() |
| 6751 | .flatten() |
| 6752 | { |
| 6753 | blocks[at] = quadrant; |
| 6754 | } |
| 6755 | |
| 6756 | let modes = blocks |
| 6757 | .iter() |
| 6758 | .flat_map(Quadrant::blocks) |
| 6759 | .map(|b| b.mode) |
| 6760 | .collect::<Vec<_>>(); |
| 6761 | let inter_block_share = blocks |
| 6762 | .iter() |
| 6763 | .flat_map(Quadrant::blocks) |
| 6764 | .filter(|b| b.inter.is_some()) |
| 6765 | .count() as f64 |
| 6766 | / modes.len() as f64; |
| 6767 | for block in blocks.iter().flat_map(Quadrant::blocks) { |
| 6768 | if let Some(info) = block.inter { |
| 6769 | let r = (info.ref_frame as usize).min(7); |
| 6770 | REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 6771 | } |
| 6772 | } |
| 6773 | #[cfg(test)] |
| 6774 | record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); |
| 6775 | |
| 6776 | |
| 6777 | |
| 6778 | |
| 6779 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 6780 | let cdfs = start_cdfs |
| 6781 | .cloned() |
| 6782 | .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); |
| 6783 | let start_cdfs = CdfSnapshot(cdfs); |
| 6784 | let reference_select_bit = header.reference_select; |
| 6785 | let order_hint_bits = seq.order_hint_bits; |
| 6786 | let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; |
| 6787 | let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; |
| 6788 | |
| 6789 | |
| 6790 | |
| 6791 | let store_tile = layout.largest_tile(); |
| 6792 | let end_cdfs = std::cell::RefCell::new(None); |
| 6793 | |
| 6794 | |
| 6795 | let code_tiles = |bits: u8, |
| 6796 | sb_cols: usize, |
| 6797 | cdef_grid: &[u8], |
| 6798 | units: &[Option<crate::restoration::WienerInfo>]| |
| 6799 | -> Result<Vec<Vec<u8>>> { |
| 6800 | let (out, stored) = write_tiles(layout.count(), store_tile, |index| { |
| 6801 | crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); |
| 6802 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 6803 | crate::tile::arm_sign_bias(sign_bias); |
| 6804 | |
| 6805 | crate::tile::arm_reference_select(reference_select_bit); |
| 6806 | crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); |
| 6807 | crate::tile::arm_screen(screen); |
| 6808 | let mut cdfs = start_cdfs.0.clone(); |
| 6809 | |
| 6810 | |
| 6811 | |
| 6812 | |
| 6813 | let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); |
| 6814 | mv_grid.set_sign_bias(sign_bias); |
| 6815 | let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs( |
| 6816 | mi_cols, |
| 6817 | mi_rows, |
| 6818 | base_q_idx, |
| 6819 | &blocks, |
| 6820 | tx_select, |
| 6821 | &mut cdfs, |
| 6822 | layout.rect(index), |
| 6823 | &mut mv_grid, |
| 6824 | )?; |
| 6825 | Ok((bytes, Some(cdfs))) |
| 6826 | })?; |
| 6827 | if let Some(cdfs) = stored { |
| 6828 | *end_cdfs.borrow_mut() = Some(cdfs); |
| 6829 | } |
| 6830 | Ok(out) |
| 6831 | }; |
| 6832 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| 6833 | |
| 6834 | |
| 6835 | |
| 6836 | |
| 6837 | |
| 6838 | |
| 6839 | |
| 6840 | |
| 6841 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 6842 | let trial_ref = if (reference.width, reference.height) == (fw, fh) { |
| 6843 | reference.clone() |
| 6844 | } else { |
| 6845 | Picture { |
| 6846 | width: fw, |
| 6847 | height: fh, |
| 6848 | y: crop_plane(&reference.y, reference.width, fw, fh), |
| 6849 | u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2), |
| 6850 | v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), |
| 6851 | } |
| 6852 | }; |
| 6853 | |
| 6854 | |
| 6855 | |
| 6856 | let trial_golden = golden.map(|g| { |
| 6857 | if (g.width, g.height) == (fw, fh) { |
| 6858 | g.clone() |
| 6859 | } else { |
| 6860 | Picture { |
| 6861 | width: fw, |
| 6862 | height: fh, |
| 6863 | y: crop_plane(&g.y, g.width, fw, fh), |
| 6864 | u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2), |
| 6865 | v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2), |
| 6866 | } |
| 6867 | } |
| 6868 | }); |
| 6869 | let trial_altref = altref.map(|a| { |
| 6870 | if (a.width, a.height) == (fw, fh) { |
| 6871 | a.clone() |
| 6872 | } else { |
| 6873 | Picture { |
| 6874 | width: fw, |
| 6875 | height: fh, |
| 6876 | y: crop_plane(&a.y, a.width, fw, fh), |
| 6877 | u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2), |
| 6878 | v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2), |
| 6879 | } |
| 6880 | } |
| 6881 | }); |
| 6882 | let mut refs: [Option<&Picture>; 8] = [None; 8]; |
| 6883 | refs[1] = Some(&trial_ref); |
| 6884 | refs[4] = trial_golden.as_ref(); |
| 6885 | refs[7] = trial_altref.as_ref(); |
| 6886 | let refpix = crate::decode::RefPix::ready(refs); |
| 6887 | pick_and_apply_filters( |
| 6888 | &mut header, |
| 6889 | &mut luma, |
| 6890 | &mut chroma, |
| 6891 | [&picture_y8, &picture_u8, &picture_v8], |
| 6892 | |
| 6893 | |
| 6894 | |
| 6895 | |
| 6896 | true, |
| 6897 | &mut tiles, |
| 6898 | search.lambda, |
| 6899 | fctx, |
| 6900 | |
| 6901 | |
| 6902 | |
| 6903 | |
| 6904 | |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |
| 6905 | |lf, cdef, h, tiles: &[Vec<u8>], lr| { |
| 6906 | let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); |
| 6907 | crate::decode::decode_inter_frame_tiles_lr( |
| 6908 | &payloads, |
| 6909 | &header_tile_info, |
| 6910 | h.mi_cols, |
| 6911 | h.mi_rows, |
| 6912 | base_q_idx, |
| 6913 | h.frame_width, |
| 6914 | h.frame_height, |
| 6915 | &refpix, |
| 6916 | cdef, |
| 6917 | lf, |
| 6918 | h.allow_high_precision_mv, |
| 6919 | h.force_integer_mv, |
| 6920 | Some(mc::InterpFilterKind::Regular), |
| 6921 | seq.enable_dual_filter, |
| 6922 | h.reference_select, |
| 6923 | tx_select, |
| 6924 | lr, |
| 6925 | |
| 6926 | |
| 6927 | |
| 6928 | Some(start_cdfs.0.clone()), |
| 6929 | sign_bias, |
| 6930 | h.allow_screen_content_tools, |
| 6931 | fctx, |
| 6932 | ) |
| 6933 | }, |
| 6934 | )?; |
| 6935 | let mut cdfs = end_cdfs |
| 6936 | .into_inner() |
| 6937 | .unwrap_or_else(|| start_cdfs.0.clone()); |
| 6938 | cdfs.reset_counts(); |
| 6939 | let next_cdfs = CdfSnapshot(cdfs); |
| 6940 | let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); |
| 6941 | header.tile_info.tile_size_bytes = tile_size_bytes; |
| 6942 | let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); |
| 6943 | let mut stream = temporal_delimiter(); |
| 6944 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 6945 | |
| 6946 | let [u, v] = chroma; |
| 6947 | Ok(Encoded { |
| 6948 | stream, |
| 6949 | modes, |
| 6950 | inter_block_share, |
| 6951 | reconstruction: Picture { |
| 6952 | width: luma.width, |
| 6953 | height: luma.height, |
| 6954 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 6955 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 6956 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 6957 | }, |
| 6958 | tile, |
| 6959 | mi_cols: header.mi_cols, |
| 6960 | mi_rows: header.mi_rows, |
| 6961 | base_q_idx, |
| 6962 | tx_select, |
| 6963 | screen, |
| 6964 | start_cdfs, |
| 6965 | next_cdfs, |
| 6966 | loop_filter: header.loop_filter, |
| 6967 | cdef: header.cdef, |
| 6968 | loop_restoration: header.loop_restoration, |
| 6969 | |
| 6970 | |
| 6971 | allow_intrabc: false, |
| 6972 | }) |
| 6973 | } |
| 6974 | |
| 6975 | |
| 6976 | |
| 6977 | |
| 6978 | |
| 6979 | #[derive(Clone, Debug)] |
| 6980 | pub struct EncodedSequence { |
| 6981 | |
| 6982 | |
| 6983 | |
| 6984 | |
| 6985 | pub stream: Vec<u8>, |
| 6986 | |
| 6987 | pub frames: Vec<Encoded>, |
| 6988 | } |
| 6989 | |
| 6990 | |
| 6991 | |
| 6992 | |
| 6993 | |
| 6994 | |
| 6995 | |
| 6996 | |
| 6997 | |
| 6998 | |
| 6999 | |
| 7000 | |
| 7001 | |
| 7002 | pub(crate) fn encode_sequence_with_ctx( |
| 7003 | pictures: &[Picture], |
| 7004 | base_q_idx: u8, |
| 7005 | deadzone: f64, fctx: &crate::decode::FrameCtx, |
| 7006 | ) -> Result<EncodedSequence> { |
| 7007 | let Some((first, rest)) = pictures.split_first() else { |
| 7008 | return Err(Error::unsupported( |
| 7009 | "AV1 encode", |
| 7010 | "a sequence needs at least one picture", |
| 7011 | )); |
| 7012 | }; |
| 7013 | first.check_even()?; |
| 7014 | let render = (first.width, first.height); |
| 7015 | |
| 7016 | |
| 7017 | |
| 7018 | |
| 7019 | |
| 7020 | let key = encode_key_frame_inner( |
| 7021 | &first.padded_to(SUPERBLOCK), |
| 7022 | base_q_idx, |
| 7023 | deadzone, |
| 7024 | &KEY_FRAME_MODES, |
| 7025 | split_blocks(), |
| 7026 | render, |
| 7027 | unspecified_color_config(), fctx, |
| 7028 | )?; |
| 7029 | let mut stream = key.stream.clone(); |
| 7030 | |
| 7031 | |
| 7032 | |
| 7033 | let golden = key.reconstruction.clone(); |
| 7034 | |
| 7035 | |
| 7036 | let mut prev2: Option<Picture> = None; |
| 7037 | let mut carried = key.next_cdfs.clone(); |
| 7038 | let mut reference = key.reconstruction.clone(); |
| 7039 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 7040 | for (i, picture) in rest.iter().enumerate() { |
| 7041 | picture.check_even()?; |
| 7042 | if (picture.width, picture.height) != render { |
| 7043 | return Err(Error::unsupported( |
| 7044 | "AV1 encode", |
| 7045 | "every picture in a sequence must be the same size as the first", |
| 7046 | )); |
| 7047 | } |
| 7048 | let order_hint = (i + 1) as u32; |
| 7049 | let inter = encode_inter_frame( |
| 7050 | &picture.padded_to(SUPERBLOCK), |
| 7051 | &reference, |
| 7052 | base_q_idx, |
| 7053 | deadzone, |
| 7054 | order_hint, |
| 7055 | flat_order_hints(order_hint, 0, prev2.is_some()), |
| 7056 | render, |
| 7057 | Some(&carried.0), |
| 7058 | Some(&golden), |
| 7059 | prev2.as_ref(), fctx, |
| 7060 | None, |
| 7061 | )?; |
| 7062 | stream.extend_from_slice(&inter.stream); |
| 7063 | carried = inter.next_cdfs.clone(); |
| 7064 | prev2 = Some(std::mem::replace( |
| 7065 | &mut reference, |
| 7066 | inter.reconstruction.clone(), |
| 7067 | )); |
| 7068 | frames.push(crop_encoded(&inter, render.0, render.1)); |
| 7069 | } |
| 7070 | Ok(EncodedSequence { stream, frames }) |
| 7071 | } |
| 7072 | |
| 7073 | #[cfg(test)] |
| 7074 | mod tests { |
| 7075 | |
| 7076 | |
| 7077 | |
| 7078 | |
| 7079 | |
| 7080 | |
| 7081 | |
| 7082 | |
| 7083 | |
| 7084 | |
| 7085 | #[test] |
| 7086 | fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { |
| 7087 | for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 7088 | let (bw_log2, bh_log2) = |
| 7089 | ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize); |
| 7090 | let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); |
| 7091 | for (name, table) in |
| 7092 | [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)] |
| 7093 | { |
| 7094 | assert_eq!( |
| 7095 | table.len() * 8, |
| 7096 | rows * cols, |
| 7097 | "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" |
| 7098 | ); |
| 7099 | let mut seen = vec![0u32; table.len() * 8]; |
| 7100 | for blk_row in 0..rows { |
| 7101 | for blk_col in 0..cols { |
| 7102 | let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); |
| 7103 | assert!( |
| 7104 | idx < seen.len(), |
| 7105 | "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" |
| 7106 | ); |
| 7107 | seen[idx] += 1; |
| 7108 | } |
| 7109 | } |
| 7110 | assert!( |
| 7111 | seen.iter().all(|&n| n == 1), |
| 7112 | "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ |
| 7113 | (row stride is not {cols})" |
| 7114 | ); |
| 7115 | } |
| 7116 | } |
| 7117 | } |
| 7118 | use super::*; |
| 7119 | use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED}; |
| 7120 | use std::io::Write; |
| 7121 | use std::process::{Command, Stdio}; |
| 7122 | |
| 7123 | |
| 7124 | |
| 7125 | |
| 7126 | |
| 7127 | |
| 7128 | |
| 7129 | |
| 7130 | |
| 7131 | |
| 7132 | |
| 7133 | |
| 7134 | |
| 7135 | |
| 7136 | |
| 7137 | |
| 7138 | |
| 7139 | |
| 7140 | |
| 7141 | |
| 7142 | |
| 7143 | #[test] |
| 7144 | fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { |
| 7145 | let fctx = &crate::decode::FrameCtx::new(); |
| 7146 | |
| 7147 | const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ |
| 7148 | (4, 8, 64, 9280, 64, 550), |
| 7149 | (8, 4, 64, 3712, 64, 9630), |
| 7150 | (8, 16, 16, 2352, 16, 134), |
| 7151 | (16, 8, 16, 960, 16, 2400), |
| 7152 | (16, 32, 4, 620, 4, 32), |
| 7153 | (32, 16, 4, 32, 4, 184), |
| 7154 | (32, 64, 1, 127, 1, 0), |
| 7155 | (64, 32, 1, 19, 1, 34), |
| 7156 | (4, 16, 32, 5472, 32, 14), |
| 7157 | (16, 4, 32, 960, 32, 6464), |
| 7158 | (8, 32, 8, 1400, 8, 2), |
| 7159 | (32, 8, 8, 32, 8, 1136), |
| 7160 | (16, 64, 2, 382, 2, 0), |
| 7161 | (64, 16, 2, 4, 2, 84), |
| 7162 | ]; |
| 7163 | |
| 7164 | |
| 7165 | |
| 7166 | |
| 7167 | fn libaom_reach( |
| 7168 | bw: usize, |
| 7169 | bh: usize, |
| 7170 | x: usize, |
| 7171 | y: usize, |
| 7172 | width: usize, |
| 7173 | height: usize, _fctx: &crate::decode::FrameCtx, |
| 7174 | ) -> (bool, bool) { |
| 7175 | let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); |
| 7176 | let (_bw_unit, bh_unit) = (bw / 4, bh / 4); |
| 7177 | let sb_mi_size = 16usize; |
| 7178 | let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; |
| 7179 | let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; |
| 7180 | let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; |
| 7181 | let (tr_table, bl_table) = rect_reach_tables(bw, bh); |
| 7182 | let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; |
| 7183 | |
| 7184 | let top_right = if y == 0 || x + bw >= width { |
| 7185 | false |
| 7186 | } else if blk_row_in_sb == 0 { |
| 7187 | |
| 7188 | |
| 7189 | true |
| 7190 | } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { |
| 7191 | false |
| 7192 | } else { |
| 7193 | bit(tr_table) |
| 7194 | }; |
| 7195 | |
| 7196 | let bottom_left = if x == 0 || y + bh >= height { |
| 7197 | false |
| 7198 | } else if blk_col_in_sb == 0 { |
| 7199 | |
| 7200 | (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size |
| 7201 | } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { |
| 7202 | false |
| 7203 | } else { |
| 7204 | bit(bl_table) |
| 7205 | }; |
| 7206 | (top_right, bottom_left) |
| 7207 | } |
| 7208 | for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { |
| 7209 | let (tr, bl) = rect_reach_tables(bw, bh); |
| 7210 | let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>(); |
| 7211 | assert_eq!( |
| 7212 | (tr.len(), sum(tr), bl.len(), sum(bl)), |
| 7213 | (tr_len, tr_sum, bl_len, bl_sum), |
| 7214 | "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" |
| 7215 | ); |
| 7216 | |
| 7217 | |
| 7218 | for sb_y in [0usize, 64] { |
| 7219 | for sb_x in [0usize, 64] { |
| 7220 | for y in (sb_y..sb_y + 64).step_by(bh) { |
| 7221 | for x in (sb_x..sb_x + 64).step_by(bw) { |
| 7222 | let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx); |
| 7223 | let want = libaom_reach(bw, bh, x, y, 256, 256, fctx); |
| 7224 | assert_eq!( |
| 7225 | (got.above_right, got.below_left), |
| 7226 | want, |
| 7227 | "{bw}x{bh} at ({x}, {y})" |
| 7228 | ); |
| 7229 | } |
| 7230 | } |
| 7231 | } |
| 7232 | } |
| 7233 | } |
| 7234 | } |
| 7235 | |
| 7236 | |
| 7237 | |
| 7238 | |
| 7239 | |
| 7240 | |
| 7241 | |
| 7242 | |
| 7243 | fn have_ffmpeg() -> bool { |
| 7244 | let present = Command::new("ffmpeg") |
| 7245 | .arg("-version") |
| 7246 | .stdout(Stdio::null()) |
| 7247 | .stderr(Stdio::null()) |
| 7248 | .status() |
| 7249 | .is_ok_and(|s| s.success()); |
| 7250 | assert!( |
| 7251 | present |
| 7252 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 7253 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 7254 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 7255 | ); |
| 7256 | present |
| 7257 | } |
| 7258 | |
| 7259 | |
| 7260 | fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { |
| 7261 | let mut child = Command::new("ffmpeg") |
| 7262 | .args([ |
| 7263 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 7264 | ]) |
| 7265 | .stdin(Stdio::piped()) |
| 7266 | .stdout(Stdio::piped()) |
| 7267 | .stderr(Stdio::piped()) |
| 7268 | .spawn() |
| 7269 | .expect("ffmpeg failed to start"); |
| 7270 | |
| 7271 | |
| 7272 | |
| 7273 | |
| 7274 | |
| 7275 | |
| 7276 | |
| 7277 | let mut stdin = child.stdin.take().expect("ffmpeg stdin"); |
| 7278 | let payload = stream.to_vec(); |
| 7279 | let writer = std::thread::spawn(move || { |
| 7280 | let _ = stdin.write_all(&payload); |
| 7281 | }); |
| 7282 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 7283 | writer.join().expect("ffmpeg stdin writer thread"); |
| 7284 | assert!( |
| 7285 | out.status.success(), |
| 7286 | "ffmpeg refused the stream: {}", |
| 7287 | String::from_utf8_lossy(&out.stderr) |
| 7288 | ); |
| 7289 | let (luma, chroma) = (width * height, width * height / 4); |
| 7290 | assert_eq!( |
| 7291 | out.stdout.len(), |
| 7292 | luma + 2 * chroma, |
| 7293 | "expected one 4:2:0 frame" |
| 7294 | ); |
| 7295 | Picture { |
| 7296 | width, |
| 7297 | height, |
| 7298 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 7299 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 7300 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 7301 | } |
| 7302 | } |
| 7303 | |
| 7304 | |
| 7305 | |
| 7306 | |
| 7307 | |
| 7308 | |
| 7309 | |
| 7310 | |
| 7311 | |
| 7312 | |
| 7313 | |
| 7314 | |
| 7315 | |
| 7316 | #[test] |
| 7317 | fn the_filter_search_picks_real_filters() { |
| 7318 | let fctx = &crate::decode::FrameCtx::new(); |
| 7319 | let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect(); |
| 7320 | let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap(); |
| 7321 | let fired = encoded |
| 7322 | .frames |
| 7323 | .iter() |
| 7324 | .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0) |
| 7325 | .count(); |
| 7326 | assert!( |
| 7327 | fired > 0, |
| 7328 | "no frame of this sequence chose any in-loop filtering: {:?}", |
| 7329 | encoded |
| 7330 | .frames |
| 7331 | .iter() |
| 7332 | .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0])) |
| 7333 | .collect::<Vec<_>>() |
| 7334 | ); |
| 7335 | |
| 7336 | |
| 7337 | |
| 7338 | let decoded = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 7339 | assert_eq!(decoded.len(), encoded.frames.len()); |
| 7340 | for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() { |
| 7341 | assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma"); |
| 7342 | assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U"); |
| 7343 | assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V"); |
| 7344 | } |
| 7345 | } |
| 7346 | |
| 7347 | fn test_card(width: usize, height: usize) -> Picture { |
| 7348 | let mut picture = Picture::grey(width, height); |
| 7349 | for y in 0..height { |
| 7350 | for x in 0..width { |
| 7351 | let gradient = x as f64 * 200.0 / width as f64; |
| 7352 | let ripple = 30.0 |
| 7353 | * (x as f64 * std::f64::consts::PI / 23.0).sin() |
| 7354 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 7355 | let edge = if x > width * 3 / 7 && y > height / 3 { |
| 7356 | 40.0 |
| 7357 | } else { |
| 7358 | 0.0 |
| 7359 | }; |
| 7360 | picture.y[y * width + x] = |
| 7361 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 7362 | } |
| 7363 | } |
| 7364 | for y in 0..height / 2 { |
| 7365 | for x in 0..width / 2 { |
| 7366 | let i = y * width / 2 + x; |
| 7367 | picture.u[i] = (100 + (x * 60 / (width / 2))) as u16; |
| 7368 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 7369 | } |
| 7370 | } |
| 7371 | picture |
| 7372 | } |
| 7373 | |
| 7374 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 7375 | let squared: f64 = a |
| 7376 | .iter() |
| 7377 | .zip(b) |
| 7378 | .map(|(&x, &y)| { |
| 7379 | let d = f64::from(x) - f64::from(y); |
| 7380 | d * d |
| 7381 | }) |
| 7382 | .sum(); |
| 7383 | if squared == 0.0 { |
| 7384 | return f64::INFINITY; |
| 7385 | } |
| 7386 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 7387 | } |
| 7388 | |
| 7389 | |
| 7390 | |
| 7391 | |
| 7392 | |
| 7393 | |
| 7394 | |
| 7395 | #[test] |
| 7396 | fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() { |
| 7397 | let fctx = &crate::decode::FrameCtx::new(); |
| 7398 | if !have_ffmpeg() { |
| 7399 | eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg"); |
| 7400 | return; |
| 7401 | } |
| 7402 | for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] { |
| 7403 | let picture = test_card(width, height); |
| 7404 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7405 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7406 | assert_eq!( |
| 7407 | decoded.y, encoded.reconstruction.y, |
| 7408 | "{width}x{height}: luma" |
| 7409 | ); |
| 7410 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 7411 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 7412 | } |
| 7413 | |
| 7414 | |
| 7415 | let (width, height) = (64usize, 64usize); |
| 7416 | let picture = test_card(width, height); |
| 7417 | let _ = take_tx_depth_hits(); |
| 7418 | for &q in &[15u8, 45, 100, 200] { |
| 7419 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 7420 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7421 | assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma"); |
| 7422 | assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); |
| 7423 | assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); |
| 7424 | } |
| 7425 | |
| 7426 | |
| 7427 | |
| 7428 | |
| 7429 | |
| 7430 | |
| 7431 | |
| 7432 | let depths = take_tx_depth_hits(); |
| 7433 | assert!( |
| 7434 | depths[1] + depths[2] > 0, |
| 7435 | "no block split its transform: depths {depths:?}" |
| 7436 | ); |
| 7437 | } |
| 7438 | |
| 7439 | |
| 7440 | |
| 7441 | |
| 7442 | #[cfg(test)] |
| 7443 | fn screen_card(width: usize, height: usize) -> Picture { |
| 7444 | const INK: [u16; 4] = [16, 90, 180, 235]; |
| 7445 | let mut picture = Picture::grey(width, height); |
| 7446 | for y in 0..height { |
| 7447 | for x in 0..width { |
| 7448 | let cell = (x / 24 + y / 24) % 2; |
| 7449 | let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20); |
| 7450 | picture.y[y * width + x] = INK[cell * 2 + bar]; |
| 7451 | } |
| 7452 | } |
| 7453 | |
| 7454 | |
| 7455 | |
| 7456 | |
| 7457 | |
| 7458 | const CHROMA_U: [u16; 4] = [96, 118, 150, 176]; |
| 7459 | const CHROMA_V: [u16; 4] = [148, 126, 104, 92]; |
| 7460 | for y in 0..height / 2 { |
| 7461 | for x in 0..width / 2 { |
| 7462 | let cell = (x / 12 + 2 * (y / 12)) % 4; |
| 7463 | picture.u[y * (width / 2) + x] = CHROMA_U[cell]; |
| 7464 | picture.v[y * (width / 2) + x] = CHROMA_V[cell]; |
| 7465 | } |
| 7466 | } |
| 7467 | picture |
| 7468 | } |
| 7469 | |
| 7470 | |
| 7471 | |
| 7472 | |
| 7473 | |
| 7474 | |
| 7475 | |
| 7476 | #[test] |
| 7477 | fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() { |
| 7478 | let fctx = &crate::decode::FrameCtx::new(); |
| 7479 | let (width, height) = (192usize, 96usize); |
| 7480 | let _ = crate::tile::take_palette_hits(); |
| 7481 | let picture = screen_card(width, height); |
| 7482 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7483 | assert!( |
| 7484 | encoded.screen, |
| 7485 | "the detector did not fire on screen content -- no palette syntax was coded at all" |
| 7486 | ); |
| 7487 | let hits = crate::tile::take_palette_hits(); |
| 7488 | assert!(hits[0] > 0, "no block took a palette: {hits:?}"); |
| 7489 | eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); |
| 7490 | |
| 7491 | |
| 7492 | |
| 7493 | |
| 7494 | let uv_hits = crate::tile::take_palette_uv_hits(); |
| 7495 | assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}"); |
| 7496 | let uv_cached = crate::tile::take_palette_uv_cache_hits(); |
| 7497 | eprintln!( |
| 7498 | "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache", |
| 7499 | uv_hits[0], |
| 7500 | &uv_hits[2..] |
| 7501 | ); |
| 7502 | assert!( |
| 7503 | uv_cached > 0, |
| 7504 | "no chroma base colour came out of the neighbour cache -- \ |
| 7505 | `write_palette_colors_uv`'s cache half is unproven by the oracle below" |
| 7506 | ); |
| 7507 | let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 7508 | assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); |
| 7509 | assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); |
| 7510 | assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); |
| 7511 | if !have_ffmpeg() { |
| 7512 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 7513 | return; |
| 7514 | } |
| 7515 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7516 | assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); |
| 7517 | assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); |
| 7518 | assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); |
| 7519 | |
| 7520 | |
| 7521 | |
| 7522 | let moved: Vec<Picture> = (0..4) |
| 7523 | .map(|f| { |
| 7524 | let base = screen_card(width, height); |
| 7525 | let mut out = Picture::grey(width, height); |
| 7526 | for y in 0..height { |
| 7527 | for x in 0..width { |
| 7528 | let sx = (x + f * 7) % width; |
| 7529 | out.y[y * width + x] = base.y[y * width + sx]; |
| 7530 | } |
| 7531 | } |
| 7532 | for y in 0..height / 2 { |
| 7533 | for x in 0..width / 2 { |
| 7534 | let sx = (x + f * 3) % (width / 2); |
| 7535 | out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx]; |
| 7536 | out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx]; |
| 7537 | } |
| 7538 | } |
| 7539 | out |
| 7540 | }) |
| 7541 | .collect(); |
| 7542 | let _ = crate::tile::take_palette_hits(); |
| 7543 | let _ = crate::tile::take_palette_uv_hits(); |
| 7544 | let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); |
| 7545 | let gop_hits = crate::tile::take_palette_hits(); |
| 7546 | let gop_uv_hits = crate::tile::take_palette_uv_hits(); |
| 7547 | let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); |
| 7548 | eprintln!( |
| 7549 | "GOP: {} frames with screen tools after the key frame, {} palette blocks, \ |
| 7550 | {} chroma palette blocks", |
| 7551 | inter_screen, gop_hits[0], gop_uv_hits[0] |
| 7552 | ); |
| 7553 | assert!( |
| 7554 | gop_uv_hits[0] > 0, |
| 7555 | "no block of the GOP took a chroma palette: {gop_uv_hits:?}" |
| 7556 | ); |
| 7557 | assert!( |
| 7558 | inter_screen > 0, |
| 7559 | "no inter frame set allow_screen_content_tools" |
| 7560 | ); |
| 7561 | let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap(); |
| 7562 | for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() { |
| 7563 | assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma"); |
| 7564 | } |
| 7565 | if have_ffmpeg() { |
| 7566 | let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len()); |
| 7567 | for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() { |
| 7568 | assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma"); |
| 7569 | assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U"); |
| 7570 | assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V"); |
| 7571 | } |
| 7572 | } |
| 7573 | |
| 7574 | |
| 7575 | |
| 7576 | let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap(); |
| 7577 | assert!(!film.screen, "the detector fired on the film-shaped test card"); |
| 7578 | } |
| 7579 | |
| 7580 | |
| 7581 | |
| 7582 | |
| 7583 | |
| 7584 | |
| 7585 | #[test] |
| 7586 | #[ignore = "needs the real-library manifest and ffmpeg"] |
| 7587 | fn probe_intrabc_key_frame() { |
| 7588 | let fctx = &crate::decode::FrameCtx::new(); |
| 7589 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 7590 | .join("../../fixtures"); |
| 7591 | let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else { |
| 7592 | eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest"); |
| 7593 | return; |
| 7594 | }; |
| 7595 | let Some(clip) = manifest |
| 7596 | .lines() |
| 7597 | .skip(1) |
| 7598 | .filter_map(|l| l.split('\t').next()) |
| 7599 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) |
| 7600 | else { |
| 7601 | eprintln!("SKIP probe_intrabc_key_frame: no OBS recording"); |
| 7602 | return; |
| 7603 | }; |
| 7604 | let (width, height) = (640usize, 384usize); |
| 7605 | let picture = clip_frame(clip, "0", width, height); |
| 7606 | eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |"); |
| 7607 | for q in [5u8, 20, 35, 45] { |
| 7608 | for on in [false, true] { |
| 7609 | force_intrabc(Some(on)); |
| 7610 | let _ = crate::tile::take_intrabc_hits(); |
| 7611 | let _ = take_intrabc_search(); |
| 7612 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 7613 | let hits = crate::tile::take_intrabc_hits(); |
| 7614 | let search = take_intrabc_search(); |
| 7615 | eprintln!( |
| 7616 | "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |", |
| 7617 | if encoded.allow_intrabc { "on" } else { "off" }, |
| 7618 | encoded.stream.len(), |
| 7619 | psnr_all(&encoded.reconstruction, &picture), |
| 7620 | hits[0], |
| 7621 | &hits[1..], |
| 7622 | search[0], search[1], search[2], |
| 7623 | ); |
| 7624 | } |
| 7625 | } |
| 7626 | force_intrabc(None); |
| 7627 | } |
| 7628 | |
| 7629 | |
| 7630 | |
| 7631 | |
| 7632 | |
| 7633 | |
| 7634 | |
| 7635 | #[test] |
| 7636 | fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() { |
| 7637 | let fctx = &crate::decode::FrameCtx::new(); |
| 7638 | |
| 7639 | |
| 7640 | |
| 7641 | let (width, height) = (512usize, 256usize); |
| 7642 | let picture = screen_card(width, height); |
| 7643 | let _ = crate::tile::take_intrabc_hits(); |
| 7644 | |
| 7645 | |
| 7646 | |
| 7647 | force_intrabc(Some(true)); |
| 7648 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7649 | force_intrabc(None); |
| 7650 | assert!( |
| 7651 | encoded.allow_intrabc, |
| 7652 | "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)", |
| 7653 | intrabc_source_share() * 100.0 |
| 7654 | ); |
| 7655 | let hits = crate::tile::take_intrabc_hits(); |
| 7656 | eprintln!( |
| 7657 | "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%", |
| 7658 | hits[0], |
| 7659 | &hits[1..], |
| 7660 | intrabc_source_share() * 100.0 |
| 7661 | ); |
| 7662 | let search = take_intrabc_search(); |
| 7663 | eprintln!( |
| 7664 | "intrabc searches {} found-valid {} won-RD {}", |
| 7665 | search[0], search[1], search[2] |
| 7666 | ); |
| 7667 | assert!( |
| 7668 | hits[0] > 0, |
| 7669 | "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}" |
| 7670 | ); |
| 7671 | let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 7672 | assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); |
| 7673 | assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); |
| 7674 | assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); |
| 7675 | if !have_ffmpeg() { |
| 7676 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 7677 | return; |
| 7678 | } |
| 7679 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7680 | assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); |
| 7681 | assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); |
| 7682 | assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); |
| 7683 | } |
| 7684 | |
| 7685 | |
| 7686 | |
| 7687 | |
| 7688 | |
| 7689 | |
| 7690 | |
| 7691 | |
| 7692 | |
| 7693 | #[test] |
| 7694 | fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() { |
| 7695 | let fctx = &crate::decode::FrameCtx::new(); |
| 7696 | if !have_ffmpeg() { |
| 7697 | eprintln!( |
| 7698 | "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg" |
| 7699 | ); |
| 7700 | return; |
| 7701 | } |
| 7702 | let (width, height) = (64usize, 64usize); |
| 7703 | let picture = Picture::grey(width, height); |
| 7704 | let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7705 | |
| 7706 | let (seq, _) = key_frame_headers(width, height, 100).unwrap(); |
| 7707 | let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); |
| 7708 | |
| 7709 | let residual_block = BlockCoeffs { |
| 7710 | luma: vec![Coeff { |
| 7711 | row: 0, |
| 7712 | col: 0, |
| 7713 | level: 4, |
| 7714 | }], |
| 7715 | u: Vec::new(), |
| 7716 | v: Vec::new(), |
| 7717 | mode: 0, |
| 7718 | uv_mode: 0, |
| 7719 | skip: false, |
| 7720 | eight: None, |
| 7721 | dv: None, |
| 7722 | palette: None, |
| 7723 | palette_uv: None, |
| 7724 | tx_depth: 0, |
| 7725 | inter: Some(InterInfo { |
| 7726 | ref1: None, |
| 7727 | mv1: (0, 0), |
| 7728 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7729 | mode: InterMode::NearestMv, |
| 7730 | mv: (0, 0), |
| 7731 | ref_mv_idx: 0, |
| 7732 | }), |
| 7733 | }; |
| 7734 | let skipped_block = BlockCoeffs { |
| 7735 | skip: true, |
| 7736 | inter: Some(InterInfo { |
| 7737 | ref1: None, |
| 7738 | mv1: (0, 0), |
| 7739 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7740 | mode: InterMode::NearestMv, |
| 7741 | mv: (0, 0), |
| 7742 | ref_mv_idx: 0, |
| 7743 | }), |
| 7744 | ..BlockCoeffs::default() |
| 7745 | }; |
| 7746 | let blocks = vec![ |
| 7747 | Quadrant::Whole(residual_block), |
| 7748 | Quadrant::Whole(skipped_block.clone()), |
| 7749 | Quadrant::Whole(skipped_block.clone()), |
| 7750 | Quadrant::Whole(skipped_block), |
| 7751 | ]; |
| 7752 | let tile = |
| 7753 | crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks) |
| 7754 | .unwrap(); |
| 7755 | |
| 7756 | |
| 7757 | |
| 7758 | |
| 7759 | |
| 7760 | |
| 7761 | let mut stream = key.stream.clone(); |
| 7762 | stream.extend_from_slice(&temporal_delimiter()); |
| 7763 | stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap()); |
| 7764 | |
| 7765 | ffmpeg_decode_sequence(&stream, width, height, 2); |
| 7766 | } |
| 7767 | |
| 7768 | |
| 7769 | |
| 7770 | |
| 7771 | fn ffprobe_size(stream: &[u8]) -> (u32, u32) { |
| 7772 | |
| 7773 | |
| 7774 | |
| 7775 | static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 7776 | let path = std::env::temp_dir().join(format!( |
| 7777 | "ec-av1-probe-{}-{}.obu", |
| 7778 | std::process::id(), |
| 7779 | PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) |
| 7780 | )); |
| 7781 | let _ = std::fs::remove_file(&path); |
| 7782 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 7783 | let out = Command::new("ffprobe") |
| 7784 | .args([ |
| 7785 | "-v", |
| 7786 | "error", |
| 7787 | "-f", |
| 7788 | "obu", |
| 7789 | "-select_streams", |
| 7790 | "v:0", |
| 7791 | "-show_entries", |
| 7792 | "stream=width,height", |
| 7793 | "-of", |
| 7794 | "csv=p=0", |
| 7795 | ]) |
| 7796 | .arg(&path) |
| 7797 | .output() |
| 7798 | .expect("ffprobe failed to run"); |
| 7799 | let _ = std::fs::remove_file(&path); |
| 7800 | assert!( |
| 7801 | out.status.success(), |
| 7802 | "ffprobe refused the stream: {}", |
| 7803 | String::from_utf8_lossy(&out.stderr) |
| 7804 | ); |
| 7805 | let text = String::from_utf8_lossy(&out.stdout); |
| 7806 | let mut fields = text.trim().split(','); |
| 7807 | let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); |
| 7808 | let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); |
| 7809 | (width, height) |
| 7810 | } |
| 7811 | |
| 7812 | |
| 7813 | |
| 7814 | |
| 7815 | |
| 7816 | |
| 7817 | |
| 7818 | |
| 7819 | |
| 7820 | |
| 7821 | |
| 7822 | |
| 7823 | |
| 7824 | |
| 7825 | |
| 7826 | #[test] |
| 7827 | fn a_frame_round_trips_at_its_own_size() { |
| 7828 | let fctx = &crate::decode::FrameCtx::new(); |
| 7829 | if !have_ffmpeg() { |
| 7830 | eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg"); |
| 7831 | return; |
| 7832 | } |
| 7833 | |
| 7834 | |
| 7835 | |
| 7836 | for &(width, height) in &[ |
| 7837 | (1920usize, 1080usize), |
| 7838 | (640, 352), |
| 7839 | (1280, 720), |
| 7840 | (64, 56), |
| 7841 | (854, 480), |
| 7842 | (216, 96), |
| 7843 | (192, 120), |
| 7844 | ] { |
| 7845 | let picture = test_card(width, height); |
| 7846 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7847 | assert_eq!( |
| 7848 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 7849 | (width, height), |
| 7850 | "{width}x{height}: reconstruction is cropped to the picture's own size" |
| 7851 | ); |
| 7852 | assert_eq!( |
| 7853 | ffprobe_size(&encoded.stream), |
| 7854 | (width as u32, height as u32), |
| 7855 | "{width}x{height}: ffprobe reports the true (display) size, not the padded one" |
| 7856 | ); |
| 7857 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7858 | assert_eq!( |
| 7859 | decoded.y, encoded.reconstruction.y, |
| 7860 | "{width}x{height}: luma" |
| 7861 | ); |
| 7862 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 7863 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 7864 | } |
| 7865 | } |
| 7866 | |
| 7867 | |
| 7868 | |
| 7869 | |
| 7870 | |
| 7871 | |
| 7872 | |
| 7873 | |
| 7874 | |
| 7875 | |
| 7876 | |
| 7877 | |
| 7878 | |
| 7879 | |
| 7880 | |
| 7881 | |
| 7882 | |
| 7883 | |
| 7884 | |
| 7885 | |
| 7886 | |
| 7887 | |
| 7888 | |
| 7889 | |
| 7890 | |
| 7891 | |
| 7892 | #[test] |
| 7893 | fn an_854x480_picture_round_trips_through_its_padding() { |
| 7894 | let fctx = &crate::decode::FrameCtx::new(); |
| 7895 | if !have_ffmpeg() { |
| 7896 | return; |
| 7897 | } |
| 7898 | let (width, height) = (854usize, 480usize); |
| 7899 | let picture = test_card(width, height); |
| 7900 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7901 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7902 | assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); |
| 7903 | assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); |
| 7904 | assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); |
| 7905 | } |
| 7906 | |
| 7907 | |
| 7908 | |
| 7909 | |
| 7910 | |
| 7911 | |
| 7912 | |
| 7913 | |
| 7914 | |
| 7915 | |
| 7916 | |
| 7917 | |
| 7918 | |
| 7919 | |
| 7920 | |
| 7921 | |
| 7922 | |
| 7923 | #[test] |
| 7924 | fn of_tu_follows_the_block_row_including_under_vert_ab() { |
| 7925 | let fctx = &crate::decode::FrameCtx::new(); |
| 7926 | |
| 7927 | |
| 7928 | |
| 7929 | |
| 7930 | |
| 7931 | let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); |
| 7932 | assert_eq!( |
| 7933 | Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right, |
| 7934 | plain.above_right, |
| 7935 | "ordinary table: the top-right TX4 unit takes the block's row" |
| 7936 | ); |
| 7937 | let guard = Reach::vert_ab_partition(); |
| 7938 | let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); |
| 7939 | assert_eq!( |
| 7940 | Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right, |
| 7941 | vert.above_right, |
| 7942 | "vert AB: the unit follows the vert row the block just picked" |
| 7943 | ); |
| 7944 | assert_ne!( |
| 7945 | plain.above_right, vert.above_right, |
| 7946 | "this position is the cell where the vert tables disagree; pick another if libaom's tables change" |
| 7947 | ); |
| 7948 | drop(guard); |
| 7949 | } |
| 7950 | |
| 7951 | |
| 7952 | |
| 7953 | |
| 7954 | |
| 7955 | |
| 7956 | |
| 7957 | |
| 7958 | #[test] |
| 7959 | fn reach_matches_libaom_has_top_right_and_has_bottom_left() { |
| 7960 | let fctx = &crate::decode::FrameCtx::new(); |
| 7961 | |
| 7962 | |
| 7963 | |
| 7964 | |
| 7965 | fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool { |
| 7966 | if y == 0 || x + side >= width { |
| 7967 | return false; |
| 7968 | } |
| 7969 | let (row, col, per_side) = ( |
| 7970 | (y % SUPERBLOCK) / side, |
| 7971 | (x % SUPERBLOCK) / side, |
| 7972 | SUPERBLOCK / side, |
| 7973 | ); |
| 7974 | if row == 0 { |
| 7975 | return true; |
| 7976 | } |
| 7977 | if col + 1 == per_side { |
| 7978 | return false; |
| 7979 | } |
| 7980 | let stride = 128 / side; |
| 7981 | let index = row * stride + col; |
| 7982 | let table = if side == BLOCK { |
| 7983 | [95u8, 87].to_vec() |
| 7984 | } else { |
| 7985 | vec![255, 85, 119, 85, 127, 85, 119, 85] |
| 7986 | }; |
| 7987 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 7988 | } |
| 7989 | |
| 7990 | fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool { |
| 7991 | if x == 0 || y + side >= height { |
| 7992 | return false; |
| 7993 | } |
| 7994 | let (row, col, per_side) = ( |
| 7995 | (y % SUPERBLOCK) / side, |
| 7996 | (x % SUPERBLOCK) / side, |
| 7997 | SUPERBLOCK / side, |
| 7998 | ); |
| 7999 | if col == 0 { |
| 8000 | return row * side + side < SUPERBLOCK; |
| 8001 | } |
| 8002 | if row + 1 == per_side { |
| 8003 | return false; |
| 8004 | } |
| 8005 | let stride = 128 / side; |
| 8006 | let index = row * stride + col; |
| 8007 | let table = if side == BLOCK { |
| 8008 | [4u8, 4].to_vec() |
| 8009 | } else { |
| 8010 | vec![84, 16, 84, 0, 84, 16, 84, 0] |
| 8011 | }; |
| 8012 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 8013 | } |
| 8014 | |
| 8015 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 8016 | for side in [16usize, BLOCK] { |
| 8017 | for y in (0..height).step_by(side) { |
| 8018 | for x in (0..width).step_by(side) { |
| 8019 | let reach = Reach::of(side, x, y, width, height, fctx); |
| 8020 | assert_eq!( |
| 8021 | reach.above_right, |
| 8022 | libaom_top_right(side, x, y, width, height), |
| 8023 | "side={side} x={x} y={y}: above_right" |
| 8024 | ); |
| 8025 | assert_eq!( |
| 8026 | reach.below_left, |
| 8027 | libaom_bottom_left(side, x, y, height, fctx), |
| 8028 | "side={side} x={x} y={y}: below_left" |
| 8029 | ); |
| 8030 | } |
| 8031 | } |
| 8032 | } |
| 8033 | } |
| 8034 | |
| 8035 | |
| 8036 | |
| 8037 | |
| 8038 | |
| 8039 | |
| 8040 | |
| 8041 | |
| 8042 | |
| 8043 | |
| 8044 | |
| 8045 | |
| 8046 | |
| 8047 | |
| 8048 | |
| 8049 | #[test] |
| 8050 | fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { |
| 8051 | |
| 8052 | |
| 8053 | fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 8054 | let (plane_bw_unit, count) = (bw / 4, tx / 4); |
| 8055 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 8056 | let _ = bh; |
| 8057 | if row_off_u > 0 { |
| 8058 | col_off_u + count < plane_bw_unit |
| 8059 | } else if col_off_u + count < plane_bw_unit { |
| 8060 | true |
| 8061 | } else { |
| 8062 | blk |
| 8063 | } |
| 8064 | } |
| 8065 | fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 8066 | let (plane_bh_unit, count) = (bh / 4, tx / 4); |
| 8067 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 8068 | let _ = bw; |
| 8069 | if col_off_u > 0 { |
| 8070 | false |
| 8071 | } else if row_off_u + count < plane_bh_unit { |
| 8072 | true |
| 8073 | } else { |
| 8074 | blk |
| 8075 | } |
| 8076 | } |
| 8077 | for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 8078 | for &tx in &[4usize, 8, 16, 32] { |
| 8079 | if tx > bw.min(bh) { |
| 8080 | continue; |
| 8081 | } |
| 8082 | for row_off in (0..bh).step_by(tx) { |
| 8083 | for col_off in (0..bw).step_by(tx) { |
| 8084 | for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] { |
| 8085 | let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk); |
| 8086 | assert_eq!( |
| 8087 | got.above_right, |
| 8088 | libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), |
| 8089 | "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 8090 | ); |
| 8091 | assert_eq!( |
| 8092 | got.below_left, |
| 8093 | libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), |
| 8094 | "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 8095 | ); |
| 8096 | } |
| 8097 | } |
| 8098 | } |
| 8099 | } |
| 8100 | } |
| 8101 | } |
| 8102 | |
| 8103 | #[test] |
| 8104 | fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { |
| 8105 | let fctx = &crate::decode::FrameCtx::new(); |
| 8106 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 8107 | |
| 8108 | |
| 8109 | let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK); |
| 8110 | let mut flipped = 0; |
| 8111 | for row in 0..8 { |
| 8112 | for col in 1..8 { |
| 8113 | let (x, y) = (sb_x + col * 8, sb_y + row * 8); |
| 8114 | let raster = Reach::of(8, x, y, width, height, fctx).below_left; |
| 8115 | let vert = { |
| 8116 | let _guard = Reach::vert_ab_partition(); |
| 8117 | Reach::of(8, x, y, width, height, fctx).below_left |
| 8118 | }; |
| 8119 | |
| 8120 | |
| 8121 | if row % 2 == 0 && col % 2 == 1 { |
| 8122 | assert!(!raster, "raster below_left at row={row} col={col}"); |
| 8123 | assert!(vert, "vert below_left at row={row} col={col}"); |
| 8124 | flipped += 1; |
| 8125 | } else { |
| 8126 | assert_eq!(raster, vert, "guard moved row={row} col={col}"); |
| 8127 | } |
| 8128 | } |
| 8129 | } |
| 8130 | assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip"); |
| 8131 | |
| 8132 | assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left); |
| 8133 | } |
| 8134 | |
| 8135 | |
| 8136 | |
| 8137 | #[test] |
| 8138 | fn odd_dimensions_are_refused() { |
| 8139 | let fctx = &crate::decode::FrameCtx::new(); |
| 8140 | for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { |
| 8141 | let picture = Picture::grey(width, height); |
| 8142 | let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) |
| 8143 | .expect_err(&format!("{width}x{height} is odd and must be refused")); |
| 8144 | assert!( |
| 8145 | err.to_string().contains("even"), |
| 8146 | "{width}x{height}: error was {err}" |
| 8147 | ); |
| 8148 | } |
| 8149 | } |
| 8150 | |
| 8151 | |
| 8152 | |
| 8153 | |
| 8154 | |
| 8155 | #[test] |
| 8156 | fn sequence_round_trips_at_a_non_multiple_size() { |
| 8157 | let fctx = &crate::decode::FrameCtx::new(); |
| 8158 | if !have_ffmpeg() { |
| 8159 | eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg"); |
| 8160 | return; |
| 8161 | } |
| 8162 | let (width, height) = (160usize, 96usize); |
| 8163 | let pictures: Vec<Picture> = (0..3) |
| 8164 | .map(|i| panned_test_card(width, height, i * 3)) |
| 8165 | .collect(); |
| 8166 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 8167 | assert_eq!(encoded.frames.len(), 3); |
| 8168 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 8169 | assert_eq!( |
| 8170 | (frame.reconstruction.width, frame.reconstruction.height), |
| 8171 | (width, height), |
| 8172 | "frame {i}: reconstruction size" |
| 8173 | ); |
| 8174 | } |
| 8175 | |
| 8176 | |
| 8177 | assert_eq!( |
| 8178 | ffprobe_size(&encoded.stream), |
| 8179 | (width as u32, height as u32), |
| 8180 | "sequence: ffprobe reports the true (display) size" |
| 8181 | ); |
| 8182 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 8183 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 8184 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 8185 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 8186 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 8187 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 8188 | } |
| 8189 | } |
| 8190 | |
| 8191 | |
| 8192 | |
| 8193 | |
| 8194 | |
| 8195 | |
| 8196 | |
| 8197 | |
| 8198 | #[test] |
| 8199 | fn a_sequence_round_trips_at_the_exactly_half_straddle_size() { |
| 8200 | let fctx = &crate::decode::FrameCtx::new(); |
| 8201 | if !have_ffmpeg() { |
| 8202 | eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg"); |
| 8203 | return; |
| 8204 | } |
| 8205 | let (width, height) = (1280usize, 720usize); |
| 8206 | let pictures: Vec<Picture> = (0..3) |
| 8207 | .map(|i| panned_test_card(width, height, i * 3)) |
| 8208 | .collect(); |
| 8209 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 8210 | assert_eq!(encoded.frames.len(), 3); |
| 8211 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 8212 | assert_eq!( |
| 8213 | (frame.reconstruction.width, frame.reconstruction.height), |
| 8214 | (width, height), |
| 8215 | "frame {i}: reconstruction size" |
| 8216 | ); |
| 8217 | } |
| 8218 | assert_eq!( |
| 8219 | ffprobe_size(&encoded.stream), |
| 8220 | (width as u32, height as u32), |
| 8221 | "ffprobe reports the true (display) 1280x720 size" |
| 8222 | ); |
| 8223 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 8224 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 8225 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 8226 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 8227 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 8228 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 8229 | } |
| 8230 | } |
| 8231 | |
| 8232 | |
| 8233 | |
| 8234 | |
| 8235 | |
| 8236 | |
| 8237 | |
| 8238 | |
| 8239 | |
| 8240 | |
| 8241 | |
| 8242 | |
| 8243 | #[test] |
| 8244 | fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { |
| 8245 | let fctx = &crate::decode::FrameCtx::new(); |
| 8246 | let (width, height) = (640usize, 360usize); |
| 8247 | let picture = Picture::grey(width, height); |
| 8248 | encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle"); |
| 8249 | |
| 8250 | |
| 8251 | |
| 8252 | let pictures = vec![picture.clone(), picture]; |
| 8253 | encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) |
| 8254 | .expect("inter frame now codes the mod-32==8 straddle too"); |
| 8255 | } |
| 8256 | |
| 8257 | |
| 8258 | |
| 8259 | |
| 8260 | |
| 8261 | |
| 8262 | #[test] |
| 8263 | fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() { |
| 8264 | let fctx = &crate::decode::FrameCtx::new(); |
| 8265 | if !have_ffmpeg() { |
| 8266 | eprintln!( |
| 8267 | "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \ |
| 8268 | no ffmpeg" |
| 8269 | ); |
| 8270 | return; |
| 8271 | } |
| 8272 | let (width, height) = (640usize, 360usize); |
| 8273 | for shift in [0i64, 7, 19] { |
| 8274 | let picture = panned_test_card(width, height, shift); |
| 8275 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 8276 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 8277 | assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma"); |
| 8278 | assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U"); |
| 8279 | assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V"); |
| 8280 | } |
| 8281 | } |
| 8282 | |
| 8283 | |
| 8284 | |
| 8285 | |
| 8286 | |
| 8287 | #[test] |
| 8288 | fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { |
| 8289 | let fctx = &crate::decode::FrameCtx::new(); |
| 8290 | if !have_ffmpeg() { |
| 8291 | eprintln!( |
| 8292 | "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg" |
| 8293 | ); |
| 8294 | return; |
| 8295 | } |
| 8296 | let (width, height) = (640usize, 360usize); |
| 8297 | let pictures: Vec<Picture> = (0..4) |
| 8298 | .map(|i| panned_test_card(width, height, i * 3)) |
| 8299 | .collect(); |
| 8300 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 8301 | assert_eq!(encoded.frames.len(), 4); |
| 8302 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 8303 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 8304 | } |
| 8305 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); |
| 8306 | assert_eq!(decoded.len(), 4, "decoded frame count"); |
| 8307 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 8308 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 8309 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 8310 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 8311 | } |
| 8312 | } |
| 8313 | |
| 8314 | |
| 8315 | fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { |
| 8316 | let out = Command::new("ffmpeg") |
| 8317 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"]) |
| 8318 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 8319 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 8320 | .output() |
| 8321 | .expect("ffmpeg failed to run"); |
| 8322 | assert!( |
| 8323 | out.status.success(), |
| 8324 | "ffmpeg: {}", |
| 8325 | String::from_utf8_lossy(&out.stderr) |
| 8326 | ); |
| 8327 | let (luma, chroma) = (width * height, width * height / 4); |
| 8328 | assert_eq!( |
| 8329 | out.stdout.len(), |
| 8330 | luma + 2 * chroma, |
| 8331 | "expected one 4:2:0 frame" |
| 8332 | ); |
| 8333 | Picture { |
| 8334 | width, |
| 8335 | height, |
| 8336 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 8337 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 8338 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 8339 | } |
| 8340 | } |
| 8341 | |
| 8342 | |
| 8343 | |
| 8344 | |
| 8345 | #[test] |
| 8346 | #[ignore = "a sweep, not a gate"] |
| 8347 | fn probe_lambda() { |
| 8348 | let fctx = &crate::decode::FrameCtx::new(); |
| 8349 | let mut pictures = vec![ |
| 8350 | ("test card".to_string(), test_card(160, 96)), |
| 8351 | ("stripes".to_string(), stripes(160, 96, true)), |
| 8352 | ]; |
| 8353 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 8354 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 8355 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 8356 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 8357 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 8358 | } |
| 8359 | } |
| 8360 | for (name, picture) in pictures { |
| 8361 | let dc = ladder(&picture, &[DC_PRED], fctx); |
| 8362 | let searched = ladder(&picture, &NON_DIRECTIONAL, fctx); |
| 8363 | println!( |
| 8364 | "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point", |
| 8365 | bd_rate(&dc, &searched) * 100.0, |
| 8366 | 10f64.powf(searched[1].1), |
| 8367 | searched[1].0, |
| 8368 | 10f64.powf(dc[1].1), |
| 8369 | dc[1].0, |
| 8370 | ); |
| 8371 | } |
| 8372 | } |
| 8373 | |
| 8374 | |
| 8375 | |
| 8376 | #[test] |
| 8377 | #[ignore = "a sweep, not a gate"] |
| 8378 | fn probe_ladder() { |
| 8379 | let fctx = &crate::decode::FrameCtx::new(); |
| 8380 | for (name, picture) in sweep_pictures() { |
| 8381 | let all = ladder(&picture, &KEY_FRAME_MODES, fctx); |
| 8382 | let points = all |
| 8383 | .iter() |
| 8384 | .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes))) |
| 8385 | .collect::<Vec<_>>() |
| 8386 | .join(" "); |
| 8387 | println!("ladder {name}: {points}"); |
| 8388 | } |
| 8389 | } |
| 8390 | |
| 8391 | |
| 8392 | |
| 8393 | |
| 8394 | #[test] |
| 8395 | #[ignore = "a sweep, not a gate"] |
| 8396 | fn probe_split() { |
| 8397 | let fctx = &crate::decode::FrameCtx::new(); |
| 8398 | for (name, picture) in sweep_pictures() { |
| 8399 | let ladder = |split: bool| { |
| 8400 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 8401 | .iter() |
| 8402 | .map(|&q| { |
| 8403 | let encoded = encode_key_frame_inner( |
| 8404 | &picture, |
| 8405 | q, |
| 8406 | 0.5, |
| 8407 | &KEY_FRAME_MODES, |
| 8408 | split, |
| 8409 | (picture.width, picture.height), |
| 8410 | unspecified_color_config(), fctx, |
| 8411 | ) |
| 8412 | .unwrap(); |
| 8413 | ( |
| 8414 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 8415 | (encoded.stream.len() as f64).log10(), |
| 8416 | ) |
| 8417 | }) |
| 8418 | .collect(); |
| 8419 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 8420 | points |
| 8421 | }; |
| 8422 | let (whole, split) = (ladder(false), ladder(true)); |
| 8423 | let blocks = encode_key_frame_inner( |
| 8424 | &picture, |
| 8425 | 90, |
| 8426 | 0.5, |
| 8427 | &KEY_FRAME_MODES, |
| 8428 | true, |
| 8429 | (picture.width, picture.height), |
| 8430 | unspecified_color_config(), fctx, |
| 8431 | ) |
| 8432 | .unwrap() |
| 8433 | .modes |
| 8434 | .len(); |
| 8435 | let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK); |
| 8436 | println!( |
| 8437 | "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90", |
| 8438 | bd_rate(&whole, &split) * 100.0 |
| 8439 | ); |
| 8440 | } |
| 8441 | } |
| 8442 | |
| 8443 | |
| 8444 | |
| 8445 | |
| 8446 | |
| 8447 | fn stripes(width: usize, height: usize, vertical: bool) -> Picture { |
| 8448 | let mut picture = Picture::grey(width, height); |
| 8449 | for y in 0..height { |
| 8450 | for x in 0..width { |
| 8451 | let along = if vertical { x } else { y }; |
| 8452 | picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 }; |
| 8453 | } |
| 8454 | } |
| 8455 | picture |
| 8456 | } |
| 8457 | |
| 8458 | |
| 8459 | |
| 8460 | |
| 8461 | fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> { |
| 8462 | let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?; |
| 8463 | let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count(); |
| 8464 | Some(format!( |
| 8465 | "{differ} samples differ, first at ({}, {}): ours {} theirs {}", |
| 8466 | i % width, |
| 8467 | i / width, |
| 8468 | ours[i], |
| 8469 | theirs[i] |
| 8470 | )) |
| 8471 | } |
| 8472 | |
| 8473 | |
| 8474 | |
| 8475 | |
| 8476 | #[test] |
| 8477 | fn every_mode_decodes_to_what_the_encoder_predicted() { |
| 8478 | let fctx = &crate::decode::FrameCtx::new(); |
| 8479 | if !have_ffmpeg() { |
| 8480 | eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg"); |
| 8481 | return; |
| 8482 | } |
| 8483 | |
| 8484 | |
| 8485 | |
| 8486 | for (width, height) in [(128, 96), (160, 96)] { |
| 8487 | let picture = test_card(width, height); |
| 8488 | for mode in KEY_FRAME_MODES { |
| 8489 | let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap(); |
| 8490 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 8491 | for (plane, ours, theirs, stride) in [ |
| 8492 | ("luma", &encoded.reconstruction.y, &decoded.y, width), |
| 8493 | ("U", &encoded.reconstruction.u, &decoded.u, width / 2), |
| 8494 | ("V", &encoded.reconstruction.v, &decoded.v, width / 2), |
| 8495 | ] { |
| 8496 | assert!( |
| 8497 | first_difference(ours, theirs, stride).is_none(), |
| 8498 | "{width}x{height} mode {mode}, {plane}: {}", |
| 8499 | first_difference(ours, theirs, stride).unwrap() |
| 8500 | ); |
| 8501 | } |
| 8502 | assert!( |
| 8503 | encoded.modes.iter().all(|&m| m == mode), |
| 8504 | "mode {mode}: the encoder coded something else" |
| 8505 | ); |
| 8506 | } |
| 8507 | } |
| 8508 | } |
| 8509 | |
| 8510 | |
| 8511 | |
| 8512 | |
| 8513 | |
| 8514 | #[test] |
| 8515 | fn the_search_picks_the_direction_the_picture_runs() { |
| 8516 | let fctx = &crate::decode::FrameCtx::new(); |
| 8517 | for (vertical, want) in [(true, V_PRED), (false, H_PRED)] { |
| 8518 | let picture = stripes(128, 96, vertical); |
| 8519 | |
| 8520 | |
| 8521 | |
| 8522 | |
| 8523 | |
| 8524 | let encoded = |
| 8525 | encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap(); |
| 8526 | |
| 8527 | |
| 8528 | let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count(); |
| 8529 | assert!( |
| 8530 | picked * 2 > encoded.modes.len() - 1, |
| 8531 | "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}", |
| 8532 | encoded.modes.len() - 1, |
| 8533 | encoded.modes |
| 8534 | ); |
| 8535 | } |
| 8536 | } |
| 8537 | |
| 8538 | |
| 8539 | |
| 8540 | |
| 8541 | |
| 8542 | |
| 8543 | |
| 8544 | fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 { |
| 8545 | let low = reference[0].0.max(other[0].0); |
| 8546 | let high = reference[reference.len() - 1] |
| 8547 | .0 |
| 8548 | .min(other[other.len() - 1].0); |
| 8549 | |
| 8550 | |
| 8551 | |
| 8552 | |
| 8553 | |
| 8554 | |
| 8555 | |
| 8556 | |
| 8557 | if high <= low { |
| 8558 | let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min); |
| 8559 | let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max); |
| 8560 | let dominates = other[0].0 > reference[reference.len() - 1].0 |
| 8561 | && other_hi_rate <= ref_lo_rate; |
| 8562 | assert!( |
| 8563 | dominates, |
| 8564 | "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}" |
| 8565 | ); |
| 8566 | return -1.0; |
| 8567 | } |
| 8568 | let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { |
| 8569 | let i = curve |
| 8570 | .windows(2) |
| 8571 | .position(|w| psnr >= w[0].0 && psnr <= w[1].0) |
| 8572 | .unwrap_or(0); |
| 8573 | let (x0, y0) = curve[i]; |
| 8574 | let (x1, y1) = curve[i + 1]; |
| 8575 | y0 + (y1 - y0) * (psnr - x0) / (x1 - x0) |
| 8576 | }; |
| 8577 | let steps = 64; |
| 8578 | let mut area = 0.0; |
| 8579 | for step in 0..steps { |
| 8580 | let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps); |
| 8581 | area += log_rate_at(other, psnr) - log_rate_at(reference, psnr); |
| 8582 | } |
| 8583 | 10f64.powf(area / f64::from(steps)) - 1.0 |
| 8584 | } |
| 8585 | |
| 8586 | |
| 8587 | |
| 8588 | fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> { |
| 8589 | |
| 8590 | |
| 8591 | |
| 8592 | force_screen(Some(false)); |
| 8593 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 8594 | .iter() |
| 8595 | .map(|&q| { |
| 8596 | let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap(); |
| 8597 | ( |
| 8598 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 8599 | (encoded.stream.len() as f64).log10(), |
| 8600 | ) |
| 8601 | }) |
| 8602 | .collect(); |
| 8603 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 8604 | points |
| 8605 | } |
| 8606 | |
| 8607 | |
| 8608 | |
| 8609 | |
| 8610 | |
| 8611 | #[test] |
| 8612 | fn the_search_beats_dc_alone() { |
| 8613 | let fctx = &crate::decode::FrameCtx::new(); |
| 8614 | for (name, picture, want) in [ |
| 8615 | ("test card", test_card(160, 96), -0.05), |
| 8616 | ("stripes", stripes(160, 96, true), -0.40), |
| 8617 | ] { |
| 8618 | let saved = bd_rate( |
| 8619 | &ladder(&picture, &[DC_PRED], fctx), |
| 8620 | &ladder(&picture, &NON_DIRECTIONAL, fctx), |
| 8621 | ); |
| 8622 | assert!( |
| 8623 | saved < want, |
| 8624 | "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%", |
| 8625 | saved * 100.0, |
| 8626 | -want * 100.0 |
| 8627 | ); |
| 8628 | } |
| 8629 | } |
| 8630 | |
| 8631 | |
| 8632 | |
| 8633 | fn sweep_pictures() -> Vec<(String, Picture)> { |
| 8634 | let mut pictures = vec![ |
| 8635 | ("test card".to_string(), test_card(160, 96)), |
| 8636 | ("stripes".to_string(), stripes(160, 96, true)), |
| 8637 | ("diagonal".to_string(), diagonal(160, 96, true)), |
| 8638 | ]; |
| 8639 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 8640 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 8641 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 8642 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 8643 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 8644 | } |
| 8645 | } |
| 8646 | pictures |
| 8647 | } |
| 8648 | |
| 8649 | |
| 8650 | |
| 8651 | |
| 8652 | #[test] |
| 8653 | #[ignore = "a sweep, not a gate"] |
| 8654 | fn probe_directional() { |
| 8655 | let fctx = &crate::decode::FrameCtx::new(); |
| 8656 | for (name, picture) in sweep_pictures() { |
| 8657 | let dc = ladder(&picture, &[DC_PRED], fctx); |
| 8658 | let flat = ladder(&picture, &NON_DIRECTIONAL, fctx); |
| 8659 | let all = ladder(&picture, &KEY_FRAME_MODES, fctx); |
| 8660 | let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap(); |
| 8661 | let directional = encoded |
| 8662 | .modes |
| 8663 | .iter() |
| 8664 | .filter(|&&m| (3..=8).contains(&m)) |
| 8665 | .count(); |
| 8666 | |
| 8667 | |
| 8668 | let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 8669 | a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0) |
| 8670 | }; |
| 8671 | let against = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 8672 | if overlap(a, b) { |
| 8673 | format!("{:+.2}%", bd_rate(a, b) * 100.0) |
| 8674 | } else { |
| 8675 | "no overlap".to_string() |
| 8676 | } |
| 8677 | }; |
| 8678 | println!( |
| 8679 | "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional", |
| 8680 | against(&flat, &all), |
| 8681 | against(&dc, &all), |
| 8682 | encoded.modes.len(), |
| 8683 | ); |
| 8684 | } |
| 8685 | } |
| 8686 | |
| 8687 | |
| 8688 | |
| 8689 | |
| 8690 | |
| 8691 | fn diagonal(width: usize, height: usize, down_right: bool) -> Picture { |
| 8692 | let mut picture = Picture::grey(width, height); |
| 8693 | for y in 0..height { |
| 8694 | for x in 0..width { |
| 8695 | let along = if down_right { x + height - y } else { x + y }; |
| 8696 | picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 }; |
| 8697 | } |
| 8698 | } |
| 8699 | picture |
| 8700 | } |
| 8701 | |
| 8702 | |
| 8703 | |
| 8704 | fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) { |
| 8705 | |
| 8706 | |
| 8707 | |
| 8708 | force_screen(Some(false)); |
| 8709 | let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); |
| 8710 | let blocks = &encoded.modes[1..]; |
| 8711 | let mut counts = [0usize; 13]; |
| 8712 | for &mode in blocks { |
| 8713 | counts[usize::from(mode)] += 1; |
| 8714 | } |
| 8715 | let (mode, count) = counts |
| 8716 | .iter() |
| 8717 | .enumerate() |
| 8718 | .max_by_key(|&(_, count)| *count) |
| 8719 | .expect("thirteen modes"); |
| 8720 | (mode as u8, *count, blocks.len()) |
| 8721 | } |
| 8722 | |
| 8723 | |
| 8724 | |
| 8725 | |
| 8726 | |
| 8727 | #[test] |
| 8728 | fn the_search_picks_the_diagonal_the_picture_runs() { |
| 8729 | let fctx = &crate::decode::FrameCtx::new(); |
| 8730 | for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] { |
| 8731 | let picture = diagonal(160, 96, down_right); |
| 8732 | let (mode, count, blocks) = favourite_mode(&picture, fctx); |
| 8733 | assert_eq!( |
| 8734 | mode, want, |
| 8735 | "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}" |
| 8736 | ); |
| 8737 | } |
| 8738 | } |
| 8739 | |
| 8740 | |
| 8741 | |
| 8742 | |
| 8743 | |
| 8744 | |
| 8745 | |
| 8746 | #[test] |
| 8747 | fn the_diagonals_beat_the_modes_that_read_no_further() { |
| 8748 | let fctx = &crate::decode::FrameCtx::new(); |
| 8749 | for (name, picture, want) in [ |
| 8750 | ("down-right", diagonal(160, 96, true), -0.20), |
| 8751 | ("down-left", diagonal(160, 96, false), -0.20), |
| 8752 | ("test card", test_card(160, 96), 0.01), |
| 8753 | ] { |
| 8754 | let saved = bd_rate( |
| 8755 | &ladder(&picture, &NON_DIRECTIONAL, fctx), |
| 8756 | &ladder(&picture, &KEY_FRAME_MODES, fctx), |
| 8757 | ); |
| 8758 | assert!( |
| 8759 | saved < want, |
| 8760 | "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%", |
| 8761 | saved * 100.0, |
| 8762 | -want * 100.0 |
| 8763 | ); |
| 8764 | } |
| 8765 | } |
| 8766 | |
| 8767 | |
| 8768 | |
| 8769 | #[test] |
| 8770 | fn a_mode_the_encoder_cannot_predict_is_refused() { |
| 8771 | let fctx = &crate::decode::FrameCtx::new(); |
| 8772 | let picture = test_card(64, 64); |
| 8773 | let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx) |
| 8774 | .unwrap_err() |
| 8775 | .to_string(); |
| 8776 | assert!( |
| 8777 | message.contains("intra mode 13"), |
| 8778 | "the refusal must name the mode, got {message}" |
| 8779 | ); |
| 8780 | assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err()); |
| 8781 | } |
| 8782 | |
| 8783 | |
| 8784 | |
| 8785 | |
| 8786 | |
| 8787 | |
| 8788 | #[test] |
| 8789 | fn the_encoded_picture_is_the_one_that_went_in() { |
| 8790 | let fctx = &crate::decode::FrameCtx::new(); |
| 8791 | let picture = test_card(160, 96); |
| 8792 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 8793 | let luma = psnr(&encoded.reconstruction.y, &picture.y); |
| 8794 | assert!(luma > 36.0, "luma PSNR {luma} at q 100"); |
| 8795 | for (plane, (got, want)) in [ |
| 8796 | (encoded.reconstruction.u.as_slice(), picture.u.as_slice()), |
| 8797 | (encoded.reconstruction.v.as_slice(), picture.v.as_slice()), |
| 8798 | ] |
| 8799 | .iter() |
| 8800 | .enumerate() |
| 8801 | { |
| 8802 | let chroma = psnr(got, want); |
| 8803 | assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100"); |
| 8804 | } |
| 8805 | } |
| 8806 | |
| 8807 | |
| 8808 | |
| 8809 | |
| 8810 | #[test] |
| 8811 | fn fidelity_and_rate_move_with_the_quantizer() { |
| 8812 | let fctx = &crate::decode::FrameCtx::new(); |
| 8813 | let picture = test_card(128, 128); |
| 8814 | let mut previous: Option<(usize, f64)> = None; |
| 8815 | for &q in &[70u8, 90, 110] { |
| 8816 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 8817 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 8818 | if let Some((bytes, better)) = previous { |
| 8819 | assert!( |
| 8820 | encoded.stream.len() < bytes, |
| 8821 | "q {q}: {} bytes", |
| 8822 | encoded.stream.len() |
| 8823 | ); |
| 8824 | assert!(quality < better, "q {q}: PSNR {quality}"); |
| 8825 | } |
| 8826 | previous = Some((encoded.stream.len(), quality)); |
| 8827 | } |
| 8828 | |
| 8829 | let mut previous = None; |
| 8830 | for &deadzone in &[0.5f64, 0.3, 0.15] { |
| 8831 | let encoded = encode_key_frame_with_ctx(&picture, 100, deadzone, fctx).unwrap(); |
| 8832 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 8833 | if let Some((bytes, better)) = previous { |
| 8834 | assert!( |
| 8835 | encoded.stream.len() < bytes, |
| 8836 | "deadzone {deadzone}: {} bytes", |
| 8837 | encoded.stream.len() |
| 8838 | ); |
| 8839 | assert!(quality < better, "deadzone {deadzone}: PSNR {quality}"); |
| 8840 | } |
| 8841 | previous = Some((encoded.stream.len(), quality)); |
| 8842 | } |
| 8843 | |
| 8844 | |
| 8845 | |
| 8846 | |
| 8847 | |
| 8848 | |
| 8849 | |
| 8850 | |
| 8851 | |
| 8852 | |
| 8853 | |
| 8854 | |
| 8855 | |
| 8856 | |
| 8857 | |
| 8858 | |
| 8859 | |
| 8860 | |
| 8861 | |
| 8862 | |
| 8863 | |
| 8864 | |
| 8865 | for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { |
| 8866 | let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len(); |
| 8867 | let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len(); |
| 8868 | assert!( |
| 8869 | hi_bytes as f64 <= lo_bytes as f64 * 1.10, |
| 8870 | "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" |
| 8871 | ); |
| 8872 | } |
| 8873 | } |
| 8874 | |
| 8875 | |
| 8876 | |
| 8877 | #[test] |
| 8878 | fn a_flat_picture_costs_almost_nothing() { |
| 8879 | let fctx = &crate::decode::FrameCtx::new(); |
| 8880 | let mut picture = Picture::grey(128, 128); |
| 8881 | picture.y.fill(97); |
| 8882 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 8883 | |
| 8884 | |
| 8885 | assert!( |
| 8886 | encoded.stream.len() < 100, |
| 8887 | "{} bytes for a flat picture", |
| 8888 | encoded.stream.len() |
| 8889 | ); |
| 8890 | for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) { |
| 8891 | assert_eq!(s, 97, "sample {i} of a flat picture"); |
| 8892 | } |
| 8893 | } |
| 8894 | |
| 8895 | |
| 8896 | |
| 8897 | |
| 8898 | |
| 8899 | |
| 8900 | |
| 8901 | |
| 8902 | |
| 8903 | |
| 8904 | |
| 8905 | |
| 8906 | |
| 8907 | #[test] |
| 8908 | fn a_picture_off_the_block_grid_is_refused() { |
| 8909 | let fctx = &crate::decode::FrameCtx::new(); |
| 8910 | let msg = encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx) |
| 8911 | .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform") |
| 8912 | .to_string(); |
| 8913 | assert!(msg.contains("rectangular"), "refusal: {msg}"); |
| 8914 | |
| 8915 | let mut short = Picture::grey(64, 64); |
| 8916 | short.u.truncate(10); |
| 8917 | assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err()); |
| 8918 | } |
| 8919 | |
| 8920 | |
| 8921 | |
| 8922 | |
| 8923 | |
| 8924 | |
| 8925 | |
| 8926 | |
| 8927 | |
| 8928 | |
| 8929 | |
| 8930 | |
| 8931 | |
| 8932 | |
| 8933 | |
| 8934 | |
| 8935 | |
| 8936 | |
| 8937 | |
| 8938 | |
| 8939 | |
| 8940 | |
| 8941 | |
| 8942 | |
| 8943 | |
| 8944 | |
| 8945 | |
| 8946 | |
| 8947 | |
| 8948 | |
| 8949 | |
| 8950 | |
| 8951 | |
| 8952 | |
| 8953 | |
| 8954 | |
| 8955 | |
| 8956 | |
| 8957 | |
| 8958 | |
| 8959 | |
| 8960 | |
| 8961 | |
| 8962 | |
| 8963 | |
| 8964 | |
| 8965 | |
| 8966 | |
| 8967 | |
| 8968 | |
| 8969 | |
| 8970 | |
| 8971 | |
| 8972 | |
| 8973 | |
| 8974 | |
| 8975 | |
| 8976 | |
| 8977 | |
| 8978 | |
| 8979 | |
| 8980 | |
| 8981 | |
| 8982 | |
| 8983 | |
| 8984 | |
| 8985 | |
| 8986 | |
| 8987 | |
| 8988 | |
| 8989 | |
| 8990 | #[test] |
| 8991 | fn a_single_axis_straddle_round_trips_through_ffmpeg() { |
| 8992 | let fctx = &crate::decode::FrameCtx::new(); |
| 8993 | if !have_ffmpeg() { |
| 8994 | eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg"); |
| 8995 | return; |
| 8996 | } |
| 8997 | let (width, height) = (40usize, 32usize); |
| 8998 | let picture = test_card(width, height); |
| 8999 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 9000 | assert_eq!( |
| 9001 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 9002 | (width, height) |
| 9003 | ); |
| 9004 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 9005 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 9006 | } |
| 9007 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 9008 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 9009 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 9010 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 9011 | } |
| 9012 | |
| 9013 | |
| 9014 | |
| 9015 | |
| 9016 | |
| 9017 | |
| 9018 | |
| 9019 | #[test] |
| 9020 | fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() { |
| 9021 | let fctx = &crate::decode::FrameCtx::new(); |
| 9022 | let Ok(clip) = std::env::var("EC_AV1_CLIP") else { |
| 9023 | eprintln!( |
| 9024 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \ |
| 9025 | set EC_AV1_CLIP to a clip" |
| 9026 | ); |
| 9027 | return; |
| 9028 | }; |
| 9029 | if !have_ffmpeg() { |
| 9030 | eprintln!( |
| 9031 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 9032 | ); |
| 9033 | return; |
| 9034 | } |
| 9035 | let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into()); |
| 9036 | |
| 9037 | |
| 9038 | let (width, height) = (640usize, 352usize); |
| 9039 | let picture = clip_frame(&clip, &skip, width, height); |
| 9040 | |
| 9041 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 9042 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 9043 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 9044 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 9045 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 9046 | eprintln!( |
| 9047 | "{} bytes, luma PSNR {:.2} dB", |
| 9048 | encoded.stream.len(), |
| 9049 | psnr(&decoded.y, &picture.y) |
| 9050 | ); |
| 9051 | } |
| 9052 | |
| 9053 | |
| 9054 | |
| 9055 | |
| 9056 | |
| 9057 | |
| 9058 | fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture { |
| 9059 | let mut picture = Picture::grey(width, height); |
| 9060 | for y in 0..height { |
| 9061 | for x in 0..width { |
| 9062 | let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; |
| 9063 | let gradient = sx * 200.0 / width as f64; |
| 9064 | let ripple = 30.0 |
| 9065 | * (sx * std::f64::consts::PI / 23.0).sin() |
| 9066 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 9067 | let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 { |
| 9068 | 40.0 |
| 9069 | } else { |
| 9070 | 0.0 |
| 9071 | }; |
| 9072 | picture.y[y * width + x] = |
| 9073 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 9074 | } |
| 9075 | } |
| 9076 | for y in 0..height / 2 { |
| 9077 | for x in 0..width / 2 { |
| 9078 | let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; |
| 9079 | let i = y * width / 2 + x; |
| 9080 | picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; |
| 9081 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 9082 | } |
| 9083 | } |
| 9084 | picture |
| 9085 | } |
| 9086 | |
| 9087 | |
| 9088 | fn ffmpeg_decode_sequence( |
| 9089 | stream: &[u8], |
| 9090 | width: usize, |
| 9091 | height: usize, |
| 9092 | frames: usize, |
| 9093 | ) -> Vec<Picture> { |
| 9094 | let mut child = Command::new("ffmpeg") |
| 9095 | .args([ |
| 9096 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 9097 | ]) |
| 9098 | .stdin(Stdio::piped()) |
| 9099 | .stdout(Stdio::piped()) |
| 9100 | .stderr(Stdio::piped()) |
| 9101 | .spawn() |
| 9102 | .expect("ffmpeg failed to start"); |
| 9103 | |
| 9104 | |
| 9105 | |
| 9106 | |
| 9107 | |
| 9108 | |
| 9109 | |
| 9110 | let mut stdin = child.stdin.take().expect("ffmpeg stdin"); |
| 9111 | let payload = stream.to_vec(); |
| 9112 | let writer = std::thread::spawn(move || { |
| 9113 | let _ = stdin.write_all(&payload); |
| 9114 | }); |
| 9115 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 9116 | writer.join().expect("ffmpeg stdin writer thread"); |
| 9117 | assert!( |
| 9118 | out.status.success(), |
| 9119 | "ffmpeg refused the stream: {}", |
| 9120 | String::from_utf8_lossy(&out.stderr) |
| 9121 | ); |
| 9122 | let (luma, chroma) = (width * height, width * height / 4); |
| 9123 | let frame_bytes = luma + 2 * chroma; |
| 9124 | assert_eq!( |
| 9125 | out.stdout.len(), |
| 9126 | frame_bytes * frames, |
| 9127 | "expected {frames} 4:2:0 frames, ffmpeg said: {}", |
| 9128 | String::from_utf8_lossy(&out.stderr) |
| 9129 | ); |
| 9130 | (0..frames) |
| 9131 | .map(|i| { |
| 9132 | let base = i * frame_bytes; |
| 9133 | Picture { |
| 9134 | width, |
| 9135 | height, |
| 9136 | y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(), |
| 9137 | u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 9138 | v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(), |
| 9139 | } |
| 9140 | }) |
| 9141 | .collect() |
| 9142 | } |
| 9143 | |
| 9144 | |
| 9145 | |
| 9146 | |
| 9147 | |
| 9148 | |
| 9149 | |
| 9150 | #[test] |
| 9151 | fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() { |
| 9152 | let fctx = &crate::decode::FrameCtx::new(); |
| 9153 | if !have_ffmpeg() { |
| 9154 | eprintln!( |
| 9155 | "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 9156 | ); |
| 9157 | return; |
| 9158 | } |
| 9159 | let (width, height) = (128usize, 64usize); |
| 9160 | let pictures: Vec<Picture> = (0..5) |
| 9161 | .map(|i| panned_test_card(width, height, i * 3)) |
| 9162 | .collect(); |
| 9163 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 9164 | assert_eq!(encoded.frames.len(), 5); |
| 9165 | |
| 9166 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5); |
| 9167 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 9168 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma"); |
| 9169 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U"); |
| 9170 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V"); |
| 9171 | } |
| 9172 | |
| 9173 | eprintln!("frame bytes luma PSNR (dB) inter share"); |
| 9174 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 9175 | eprintln!( |
| 9176 | "{i:5} {:5} {:14.2} {:11.2}", |
| 9177 | frame.stream.len(), |
| 9178 | psnr(&frame.reconstruction.y, &pictures[i].y), |
| 9179 | frame.inter_block_share |
| 9180 | ); |
| 9181 | } |
| 9182 | } |
| 9183 | |
| 9184 | |
| 9185 | |
| 9186 | |
| 9187 | |
| 9188 | |
| 9189 | |
| 9190 | |
| 9191 | #[test] |
| 9192 | fn every_frame_of_a_sequence_decodes_through_our_own_decoder() { |
| 9193 | let fctx = &crate::decode::FrameCtx::new(); |
| 9194 | let (width, height) = (128usize, 64usize); |
| 9195 | let pictures: Vec<Picture> = |
| 9196 | (0..5).map(|i| panned_test_card(width, height, i * 3)).collect(); |
| 9197 | let _ = take_inter_tx_split_hits(); |
| 9198 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 9199 | let split = take_inter_tx_split_hits(); |
| 9200 | eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]); |
| 9201 | |
| 9202 | |
| 9203 | |
| 9204 | if tx_select() && tx_select_inter() { |
| 9205 | assert!(split[1] > 0, "the inter var-tx split never fired"); |
| 9206 | } |
| 9207 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 9208 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 9209 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 9210 | let recon = &frame.reconstruction; |
| 9211 | for (plane, got, want, stride) in [ |
| 9212 | ("luma", &dec.y, &recon.y, width), |
| 9213 | ("U", &dec.u, &recon.u, width / 2), |
| 9214 | ("V", &dec.v, &recon.v, width / 2), |
| 9215 | ] { |
| 9216 | assert_eq!(got.len(), want.len(), "frame {i}: {plane} size"); |
| 9217 | if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) { |
| 9218 | panic!( |
| 9219 | "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \ |
| 9220 | reconstruction {} ({} of {} samples differ)", |
| 9221 | at % stride, |
| 9222 | at / stride, |
| 9223 | got[at], |
| 9224 | want[at], |
| 9225 | got.iter().zip(want).filter(|(a, b)| a != b).count(), |
| 9226 | got.len(), |
| 9227 | ); |
| 9228 | } |
| 9229 | } |
| 9230 | } |
| 9231 | } |
| 9232 | |
| 9233 | |
| 9234 | |
| 9235 | |
| 9236 | |
| 9237 | |
| 9238 | |
| 9239 | |
| 9240 | |
| 9241 | |
| 9242 | |
| 9243 | |
| 9244 | #[test] |
| 9245 | fn predicted_coeff_bits_track_the_tile_the_writer_wrote() { |
| 9246 | let fctx = &crate::decode::FrameCtx::new(); |
| 9247 | let (width, height) = (256usize, 128usize); |
| 9248 | let pictures: Vec<Picture> = (0..5) |
| 9249 | .map(|i| panned_test_card(width, height, i * 2)) |
| 9250 | .collect(); |
| 9251 | let _ = take_predicted_bits(); |
| 9252 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 9253 | let predicted = take_predicted_bits(); |
| 9254 | assert_eq!(predicted.len(), encoded.frames.len()); |
| 9255 | |
| 9256 | eprintln!("frame predicted bits written bits drift"); |
| 9257 | |
| 9258 | |
| 9259 | |
| 9260 | |
| 9261 | |
| 9262 | let mut worst_over: f64 = 0.0; |
| 9263 | let mut worst_under: f64 = 0.0; |
| 9264 | for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() { |
| 9265 | let written = frame.tile.len() as f64 * 8.0; |
| 9266 | let drift = (written - bits) / written; |
| 9267 | worst_over = worst_over.max(-drift); |
| 9268 | worst_under = worst_under.max(drift); |
| 9269 | eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0); |
| 9270 | } |
| 9271 | |
| 9272 | |
| 9273 | |
| 9274 | |
| 9275 | |
| 9276 | |
| 9277 | |
| 9278 | |
| 9279 | assert!( |
| 9280 | worst_over <= 0.16, |
| 9281 | "the search's rate term OVER-priced by {:.2}% against the bits the writer spent", |
| 9282 | worst_over * 100.0 |
| 9283 | ); |
| 9284 | |
| 9285 | |
| 9286 | |
| 9287 | |
| 9288 | |
| 9289 | |
| 9290 | |
| 9291 | assert!( |
| 9292 | worst_under <= 0.32, |
| 9293 | "the writer spent {:.2}% more than the search priced -- more than \ |
| 9294 | the mode/mv syntax outside the coefficient sum explains", |
| 9295 | worst_under * 100.0 |
| 9296 | ); |
| 9297 | } |
| 9298 | |
| 9299 | |
| 9300 | |
| 9301 | |
| 9302 | |
| 9303 | |
| 9304 | |
| 9305 | |
| 9306 | #[test] |
| 9307 | fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() { |
| 9308 | let fctx = &crate::decode::FrameCtx::new(); |
| 9309 | let (width, height) = (256usize, 128usize); |
| 9310 | let pictures: Vec<Picture> = (0..5) |
| 9311 | .map(|i| panned_test_card(width, height, i * 2)) |
| 9312 | .collect(); |
| 9313 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 9314 | |
| 9315 | let key_bytes = encoded.frames[0].stream.len(); |
| 9316 | eprintln!("frame bytes inter share"); |
| 9317 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 9318 | eprintln!( |
| 9319 | "{i:5} {:5} {:11.2}", |
| 9320 | frame.stream.len(), |
| 9321 | frame.inter_block_share |
| 9322 | ); |
| 9323 | } |
| 9324 | assert!( |
| 9325 | encoded.frames[1..] |
| 9326 | .iter() |
| 9327 | .any(|f| f.stream.len() < key_bytes), |
| 9328 | "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes" |
| 9329 | ); |
| 9330 | assert!( |
| 9331 | encoded.frames[1..] |
| 9332 | .iter() |
| 9333 | .any(|f| f.inter_block_share > 0.0), |
| 9334 | "no inter frame coded a single inter block -- the search never fired" |
| 9335 | ); |
| 9336 | } |
| 9337 | |
| 9338 | |
| 9339 | |
| 9340 | |
| 9341 | |
| 9342 | #[test] |
| 9343 | #[ignore = "a perf probe, not a gate"] |
| 9344 | fn stage_timing_breakdown() { |
| 9345 | let fctx = &crate::decode::FrameCtx::new(); |
| 9346 | use std::time::Instant; |
| 9347 | |
| 9348 | for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] { |
| 9349 | let picture = test_card(width, height); |
| 9350 | |
| 9351 | let t = Instant::now(); |
| 9352 | let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap(); |
| 9353 | let dc_only_t = t.elapsed(); |
| 9354 | |
| 9355 | let t = Instant::now(); |
| 9356 | let non_directional = |
| 9357 | encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap(); |
| 9358 | let non_directional_t = t.elapsed(); |
| 9359 | |
| 9360 | let t = Instant::now(); |
| 9361 | let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 9362 | let all_modes_t = t.elapsed(); |
| 9363 | |
| 9364 | eprintln!( |
| 9365 | "\n=== key frame {width}x{height} ===\n\ |
| 9366 | 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\ |
| 9367 | 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\ |
| 9368 | 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)", |
| 9369 | dc_only.stream.len(), |
| 9370 | non_directional.stream.len(), |
| 9371 | all_modes.stream.len(), |
| 9372 | ); |
| 9373 | |
| 9374 | |
| 9375 | |
| 9376 | |
| 9377 | let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK); |
| 9378 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 9379 | let t = Instant::now(); |
| 9380 | let inter = |
| 9381 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None).unwrap(); |
| 9382 | let inter_t = t.elapsed(); |
| 9383 | eprintln!( |
| 9384 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| 9385 | {:.2})", |
| 9386 | inter.stream.len(), |
| 9387 | inter.inter_block_share |
| 9388 | ); |
| 9389 | } |
| 9390 | |
| 9391 | |
| 9392 | |
| 9393 | |
| 9394 | for side in [16usize, 32] { |
| 9395 | const N: u32 = 20_000; |
| 9396 | let residual: Vec<i32> = (0..side * side) |
| 9397 | .map(|i| ((i * 37 % 61) as i32) - 30) |
| 9398 | .collect(); |
| 9399 | |
| 9400 | let t = Instant::now(); |
| 9401 | let mut levels = Vec::new(); |
| 9402 | for _ in 0..N { |
| 9403 | levels = forward_and_quantize(&residual, side, 8, 100, 0.5); |
| 9404 | } |
| 9405 | let forward_t = t.elapsed() / N; |
| 9406 | |
| 9407 | let t = Instant::now(); |
| 9408 | for _ in 0..N { |
| 9409 | std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100)); |
| 9410 | } |
| 9411 | let inverse_t = t.elapsed() / N; |
| 9412 | |
| 9413 | let set = if side == 32 { |
| 9414 | crate::cdf_state::TxbSet::Luma32 |
| 9415 | } else { |
| 9416 | crate::cdf_state::TxbSet::Luma16 |
| 9417 | }; |
| 9418 | let t = Instant::now(); |
| 9419 | for _ in 0..N { |
| 9420 | std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2)); |
| 9421 | } |
| 9422 | let entropy_t = t.elapsed() / N; |
| 9423 | |
| 9424 | let above = vec![128u8; side * 2]; |
| 9425 | let left = vec![128u8; side * 2]; |
| 9426 | let mut prediction = vec![0u8; side * side]; |
| 9427 | let t = Instant::now(); |
| 9428 | for _ in 0..N { |
| 9429 | intra_predict_u8( |
| 9430 | D45_PRED, |
| 9431 | 0, |
| 9432 | Some(&above), |
| 9433 | Some(&left), |
| 9434 | Some(128), |
| 9435 | side, |
| 9436 | side, |
| 9437 | false, |
| 9438 | false, |
| 9439 | &mut prediction, fctx, |
| 9440 | ); |
| 9441 | } |
| 9442 | let predict_t = t.elapsed() / N; |
| 9443 | |
| 9444 | eprintln!( |
| 9445 | "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ |
| 9446 | predict (1 directional mode): {predict_t:>9.2?}\n\ |
| 9447 | forward_and_quantize: {forward_t:>9.2?}\n\ |
| 9448 | dequant_and_inverse: {inverse_t:>9.2?}\n\ |
| 9449 | coeff_bits: {entropy_t:>9.2?}" |
| 9450 | ); |
| 9451 | } |
| 9452 | } |
| 9453 | |
| 9454 | |
| 9455 | |
| 9456 | |
| 9457 | |
| 9458 | |
| 9459 | |
| 9460 | |
| 9461 | |
| 9462 | |
| 9463 | |
| 9464 | #[test] |
| 9465 | #[ignore = "a perf probe, not a gate"] |
| 9466 | fn stage_timing_breakdown_inter() { |
| 9467 | let fctx = &crate::decode::FrameCtx::new(); |
| 9468 | use std::time::Instant; |
| 9469 | |
| 9470 | let (width, height) = (1280usize, 720); |
| 9471 | let picture = test_card(width, height); |
| 9472 | let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 9473 | let padded_ref = key.reconstruction.padded_to(SUPERBLOCK); |
| 9474 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 9475 | |
| 9476 | stage_reset(); |
| 9477 | let t = Instant::now(); |
| 9478 | let inter = |
| 9479 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None).unwrap(); |
| 9480 | let total_t = t.elapsed(); |
| 9481 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 9482 | let accounted = motion_search + transform_quant + entropy; |
| 9483 | |
| 9484 | |
| 9485 | |
| 9486 | |
| 9487 | let other = total_t.saturating_sub(accounted); |
| 9488 | |
| 9489 | eprintln!( |
| 9490 | "\n=== inter frame {width}x{height}, one frame ===\n\ |
| 9491 | total: {total_t:>9.2?} ({} bytes)\n\ |
| 9492 | motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \ |
| 9493 | {interpolation:>9.2?})\n\ |
| 9494 | transform + quantize: {transform_quant:>9.2?}\n\ |
| 9495 | coeff_bits (entropy pricing): {entropy:>9.2?}\n\ |
| 9496 | everything else (13-mode intra {other:>9.2?}\n\ |
| 9497 | candidate loop's own predict/bookkeeping, NEARESTMV's own \ |
| 9498 | predict, RD glue):", |
| 9499 | inter.stream.len(), |
| 9500 | ); |
| 9501 | } |
| 9502 | |
| 9503 | |
| 9504 | |
| 9505 | |
| 9506 | |
| 9507 | |
| 9508 | |
| 9509 | |
| 9510 | |
| 9511 | |
| 9512 | #[test] |
| 9513 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 9514 | fn prune_k_quality_sweep() { |
| 9515 | let fctx = &crate::decode::FrameCtx::new(); |
| 9516 | if !have_ffmpeg() { |
| 9517 | eprintln!("SKIP prune_k_quality_sweep: no ffmpeg"); |
| 9518 | return; |
| 9519 | } |
| 9520 | let (width, height) = (640usize, 352usize); |
| 9521 | let frames: &[(&str, &str, &str)] = &[ |
| 9522 | |
| 9523 | |
| 9524 | ( |
| 9525 | "dark/flat", |
| 9526 | "/home/user/Videos/reela.mp4", |
| 9527 | "3", |
| 9528 | ), |
| 9529 | ( |
| 9530 | "detailed", |
| 9531 | "/home/user/Downloads/reelb.mkv", |
| 9532 | "1200", |
| 9533 | ), |
| 9534 | ( |
| 9535 | "film", |
| 9536 | "/home/user/Videos/Films/reelc.mkv", |
| 9537 | "600", |
| 9538 | ), |
| 9539 | ]; |
| 9540 | for &(label, clip, skip) in frames { |
| 9541 | if !std::path::Path::new(clip).exists() { |
| 9542 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 9543 | continue; |
| 9544 | } |
| 9545 | let picture = clip_frame(clip, skip, width, height); |
| 9546 | for &q in &[60u8, 150] { |
| 9547 | |
| 9548 | |
| 9549 | |
| 9550 | set_test_top_k_override(None); |
| 9551 | let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 9552 | let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y); |
| 9553 | eprint!( |
| 9554 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 9555 | baseline.stream.len(), |
| 9556 | baseline_psnr |
| 9557 | ); |
| 9558 | for &k in &[3usize, 4, 6] { |
| 9559 | set_test_top_k_override(Some(k)); |
| 9560 | let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 9561 | let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y); |
| 9562 | eprint!( |
| 9563 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 9564 | pruned.stream.len(), |
| 9565 | pruned_psnr, |
| 9566 | pruned_psnr - baseline_psnr |
| 9567 | ); |
| 9568 | } |
| 9569 | eprintln!(); |
| 9570 | } |
| 9571 | } |
| 9572 | set_test_top_k_override(None); |
| 9573 | } |
| 9574 | |
| 9575 | |
| 9576 | |
| 9577 | fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] { |
| 9578 | let out = Command::new("ffmpeg") |
| 9579 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"]) |
| 9580 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 9581 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 9582 | .output() |
| 9583 | .expect("ffmpeg failed to run"); |
| 9584 | assert!( |
| 9585 | out.status.success(), |
| 9586 | "ffmpeg: {}", |
| 9587 | String::from_utf8_lossy(&out.stderr) |
| 9588 | ); |
| 9589 | let (luma, chroma) = (width * height, width * height / 4); |
| 9590 | let frame_len = luma + 2 * chroma; |
| 9591 | assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames"); |
| 9592 | std::array::from_fn(|i| { |
| 9593 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 9594 | Picture { |
| 9595 | width, |
| 9596 | height, |
| 9597 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 9598 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 9599 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 9600 | } |
| 9601 | }) |
| 9602 | } |
| 9603 | |
| 9604 | |
| 9605 | |
| 9606 | |
| 9607 | |
| 9608 | |
| 9609 | |
| 9610 | |
| 9611 | |
| 9612 | #[test] |
| 9613 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 9614 | fn prune_k_quality_sweep_inter() { |
| 9615 | let fctx = &crate::decode::FrameCtx::new(); |
| 9616 | if !have_ffmpeg() { |
| 9617 | eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg"); |
| 9618 | return; |
| 9619 | } |
| 9620 | let (width, height) = (1280usize, 704usize); |
| 9621 | let frames: &[(&str, &str, &str)] = &[ |
| 9622 | ( |
| 9623 | "dark/flat", |
| 9624 | "/home/user/Videos/reela.mp4", |
| 9625 | "3", |
| 9626 | ), |
| 9627 | ( |
| 9628 | "detailed", |
| 9629 | "/home/user/Downloads/reelb.mkv", |
| 9630 | "1200", |
| 9631 | ), |
| 9632 | ( |
| 9633 | "film", |
| 9634 | "/home/user/Videos/Films/reelc.mkv", |
| 9635 | "600", |
| 9636 | ), |
| 9637 | ]; |
| 9638 | for &(label, clip, skip) in frames { |
| 9639 | if !std::path::Path::new(clip).exists() { |
| 9640 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 9641 | continue; |
| 9642 | } |
| 9643 | let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height); |
| 9644 | for &q in &[60u8, 150] { |
| 9645 | |
| 9646 | |
| 9647 | |
| 9648 | set_test_top_k_override_inter(None); |
| 9649 | let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap(); |
| 9650 | let baseline = encode_inter_frame( |
| 9651 | &inter_source, |
| 9652 | &key.reconstruction, |
| 9653 | q, |
| 9654 | 0.5, |
| 9655 | 1, |
| 9656 | flat_order_hints(1, 0, false), |
| 9657 | (width, height), None, None, None, fctx, None, |
| 9658 | ) |
| 9659 | .unwrap(); |
| 9660 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| 9661 | eprint!( |
| 9662 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 9663 | baseline.stream.len(), |
| 9664 | baseline_psnr |
| 9665 | ); |
| 9666 | for &k in &[3usize, 4, 6] { |
| 9667 | set_test_top_k_override_inter(Some(k)); |
| 9668 | let pruned = encode_inter_frame( |
| 9669 | &inter_source, |
| 9670 | &key.reconstruction, |
| 9671 | q, |
| 9672 | 0.5, |
| 9673 | 1, |
| 9674 | flat_order_hints(1, 0, false), |
| 9675 | (width, height), None, None, None, fctx, None, |
| 9676 | ) |
| 9677 | .unwrap(); |
| 9678 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
| 9679 | eprint!( |
| 9680 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 9681 | pruned.stream.len(), |
| 9682 | pruned_psnr, |
| 9683 | pruned_psnr - baseline_psnr |
| 9684 | ); |
| 9685 | } |
| 9686 | eprintln!(); |
| 9687 | } |
| 9688 | } |
| 9689 | set_test_top_k_override_inter(None); |
| 9690 | } |
| 9691 | |
| 9692 | |
| 9693 | |
| 9694 | |
| 9695 | fn clip_frames( |
| 9696 | clip: &str, |
| 9697 | skip: &str, |
| 9698 | width: usize, |
| 9699 | height: usize, |
| 9700 | frames: usize, |
| 9701 | ) -> Vec<Picture> { |
| 9702 | let out = Command::new("ffmpeg") |
| 9703 | .args(["-v", "error", "-ss", skip, "-i", clip]) |
| 9704 | .args(["-frames:v", &frames.to_string()]) |
| 9705 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 9706 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 9707 | .output() |
| 9708 | .expect("ffmpeg failed to run"); |
| 9709 | assert!( |
| 9710 | out.status.success(), |
| 9711 | "ffmpeg: {}", |
| 9712 | String::from_utf8_lossy(&out.stderr) |
| 9713 | ); |
| 9714 | let (luma, chroma) = (width * height, width * height / 4); |
| 9715 | let frame_len = luma + 2 * chroma; |
| 9716 | assert_eq!( |
| 9717 | out.stdout.len(), |
| 9718 | frame_len * frames, |
| 9719 | "expected {frames} 4:2:0 frames" |
| 9720 | ); |
| 9721 | (0..frames) |
| 9722 | .map(|i| { |
| 9723 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 9724 | Picture { |
| 9725 | width, |
| 9726 | height, |
| 9727 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 9728 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 9729 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 9730 | } |
| 9731 | }) |
| 9732 | .collect() |
| 9733 | } |
| 9734 | |
| 9735 | |
| 9736 | |
| 9737 | |
| 9738 | |
| 9739 | |
| 9740 | |
| 9741 | |
| 9742 | |
| 9743 | |
| 9744 | |
| 9745 | |
| 9746 | |
| 9747 | |
| 9748 | |
| 9749 | |
| 9750 | |
| 9751 | |
| 9752 | |
| 9753 | #[test] |
| 9754 | fn real_clip_encodes_within_its_quality_and_size_budget() { |
| 9755 | let fctx = &crate::decode::FrameCtx::new(); |
| 9756 | if !have_ffmpeg() { |
| 9757 | eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg"); |
| 9758 | return; |
| 9759 | } |
| 9760 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 9761 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 9762 | if !clip.exists() { |
| 9763 | eprintln!( |
| 9764 | "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing", |
| 9765 | clip.display() |
| 9766 | ); |
| 9767 | return; |
| 9768 | } |
| 9769 | let (width, height, frame_count) = (640usize, 384usize, 12usize); |
| 9770 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 9771 | let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 9772 | assert_eq!(encoded.frames.len(), frame_count); |
| 9773 | |
| 9774 | |
| 9775 | |
| 9776 | |
| 9777 | |
| 9778 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 9779 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 9780 | |
| 9781 | |
| 9782 | let mean_psnr: f64 = decoded |
| 9783 | .iter() |
| 9784 | .zip(&source) |
| 9785 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 9786 | .sum::<f64>() |
| 9787 | / frame_count as f64; |
| 9788 | assert!( |
| 9789 | mean_psnr >= 44.91, |
| 9790 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor" |
| 9791 | ); |
| 9792 | |
| 9793 | |
| 9794 | assert!( |
| 9795 | encoded.stream.len() <= 80_340, |
| 9796 | "stream grew to {} bytes, over the 80340-byte ceiling", |
| 9797 | encoded.stream.len() |
| 9798 | ); |
| 9799 | } |
| 9800 | |
| 9801 | |
| 9802 | |
| 9803 | |
| 9804 | |
| 9805 | |
| 9806 | |
| 9807 | |
| 9808 | |
| 9809 | |
| 9810 | |
| 9811 | |
| 9812 | |
| 9813 | |
| 9814 | #[test] |
| 9815 | fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() { |
| 9816 | let fctx = &crate::decode::FrameCtx::new(); |
| 9817 | if !have_ffmpeg() { |
| 9818 | eprintln!( |
| 9819 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 9820 | no ffmpeg" |
| 9821 | ); |
| 9822 | return; |
| 9823 | } |
| 9824 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 9825 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 9826 | if !clip.exists() { |
| 9827 | eprintln!( |
| 9828 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 9829 | {} missing", |
| 9830 | clip.display() |
| 9831 | ); |
| 9832 | return; |
| 9833 | } |
| 9834 | let (width, height, frame_count) = (704usize, 400usize, 8usize); |
| 9835 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 9836 | let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 9837 | assert_eq!(encoded.frames.len(), frame_count); |
| 9838 | |
| 9839 | |
| 9840 | |
| 9841 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 9842 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 9843 | |
| 9844 | |
| 9845 | let mean_psnr: f64 = decoded |
| 9846 | .iter() |
| 9847 | .zip(&source) |
| 9848 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 9849 | .sum::<f64>() |
| 9850 | / frame_count as f64; |
| 9851 | assert!( |
| 9852 | mean_psnr >= 44.98, |
| 9853 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor" |
| 9854 | ); |
| 9855 | |
| 9856 | |
| 9857 | assert!( |
| 9858 | encoded.stream.len() <= 62_703, |
| 9859 | "stream grew to {} bytes, over the 62703-byte ceiling", |
| 9860 | encoded.stream.len() |
| 9861 | ); |
| 9862 | } |
| 9863 | |
| 9864 | |
| 9865 | |
| 9866 | |
| 9867 | |
| 9868 | |
| 9869 | |
| 9870 | #[test] |
| 9871 | #[ignore = "a perf probe, not a gate"] |
| 9872 | fn sequence_bench_sanity() { |
| 9873 | let fctx = &crate::decode::FrameCtx::new(); |
| 9874 | use std::time::Instant; |
| 9875 | let (width, height) = (1280usize, 720usize); |
| 9876 | let pictures: Vec<Picture> = (0..24) |
| 9877 | .map(|i| panned_test_card(width, height, i * 3)) |
| 9878 | .collect(); |
| 9879 | let t = Instant::now(); |
| 9880 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 9881 | let elapsed = t.elapsed(); |
| 9882 | let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum(); |
| 9883 | eprintln!( |
| 9884 | "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes", |
| 9885 | elapsed / 24 |
| 9886 | ); |
| 9887 | } |
| 9888 | |
| 9889 | |
| 9890 | |
| 9891 | |
| 9892 | |
| 9893 | #[test] |
| 9894 | #[ignore = "a calibration probe, not a gate"] |
| 9895 | fn calibration_sweep_base_q_idx() { |
| 9896 | let fctx = &crate::decode::FrameCtx::new(); |
| 9897 | if !have_ffmpeg() { |
| 9898 | eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg"); |
| 9899 | return; |
| 9900 | } |
| 9901 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 9902 | for clip in [ |
| 9903 | "h264-1080p-23.976-8bit.mp4", |
| 9904 | "h264-1080p-60-8bit.mp4", |
| 9905 | ] { |
| 9906 | let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 9907 | .join("../../fixtures/video") |
| 9908 | .join(clip); |
| 9909 | if !path.exists() { |
| 9910 | eprintln!("SKIP {clip}: fixture missing"); |
| 9911 | continue; |
| 9912 | } |
| 9913 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 9914 | eprintln!("--- {clip} ---"); |
| 9915 | for q in [40u8, 70, 100, 130, 160, 190, 220, 240] { |
| 9916 | let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap(); |
| 9917 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames); |
| 9918 | let mean_psnr: f64 = decoded |
| 9919 | .iter() |
| 9920 | .zip(&source) |
| 9921 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 9922 | .sum::<f64>() |
| 9923 | / frames as f64; |
| 9924 | let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64; |
| 9925 | eprintln!( |
| 9926 | "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB", |
| 9927 | encoded.stream.len() |
| 9928 | ); |
| 9929 | } |
| 9930 | } |
| 9931 | } |
| 9932 | |
| 9933 | |
| 9934 | |
| 9935 | |
| 9936 | |
| 9937 | |
| 9938 | |
| 9939 | |
| 9940 | |
| 9941 | |
| 9942 | fn psnr_all(decoded: &Picture, source: &Picture) -> f64 { |
| 9943 | let cat = |p: &Picture| { |
| 9944 | let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len()); |
| 9945 | v.extend_from_slice(&p.y); |
| 9946 | v.extend_from_slice(&p.u); |
| 9947 | v.extend_from_slice(&p.v); |
| 9948 | v |
| 9949 | }; |
| 9950 | psnr(&cat(decoded), &cat(source)) |
| 9951 | } |
| 9952 | |
| 9953 | |
| 9954 | fn raw_yuv420p(source: &[Picture]) -> Vec<u8> { |
| 9955 | let mut raw = Vec::new(); |
| 9956 | for p in source { |
| 9957 | for plane in [&p.y, &p.u, &p.v] { |
| 9958 | raw.extend(plane.iter().map(|&s| s as u8)); |
| 9959 | } |
| 9960 | } |
| 9961 | raw |
| 9962 | } |
| 9963 | |
| 9964 | |
| 9965 | |
| 9966 | |
| 9967 | |
| 9968 | |
| 9969 | fn external_ladder( |
| 9970 | source: &[Picture], |
| 9971 | width: usize, |
| 9972 | height: usize, |
| 9973 | encoder: &str, |
| 9974 | points: &[Vec<String>], |
| 9975 | ) -> (Vec<(f64, f64)>, f64) { |
| 9976 | |
| 9977 | let dir = std::env::temp_dir(); |
| 9978 | let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id())); |
| 9979 | std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source"); |
| 9980 | let mut ladder = Vec::new(); |
| 9981 | let mut wall = 0.0; |
| 9982 | for (i, params) in points.iter().enumerate() { |
| 9983 | let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id())); |
| 9984 | let start = std::time::Instant::now(); |
| 9985 | let out = Command::new("ffmpeg") |
| 9986 | .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) |
| 9987 | .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"]) |
| 9988 | .arg(&raw_path) |
| 9989 | .args(["-an", "-threads", "1"]) |
| 9990 | .args(["-g", &source.len().to_string(), "-c:v", encoder]) |
| 9991 | .args(params) |
| 9992 | .args(["-f", "obu"]) |
| 9993 | .arg(&obu) |
| 9994 | .output() |
| 9995 | .expect("ffmpeg failed to run"); |
| 9996 | wall += start.elapsed().as_secs_f64(); |
| 9997 | assert!( |
| 9998 | out.status.success(), |
| 9999 | "{encoder} {params:?}: {}", |
| 10000 | String::from_utf8_lossy(&out.stderr) |
| 10001 | ); |
| 10002 | let stream = std::fs::read(&obu).expect("reference stream"); |
| 10003 | let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); |
| 10004 | let mean: f64 = decoded |
| 10005 | .iter() |
| 10006 | .zip(source) |
| 10007 | .map(|(d, s)| psnr_all(d, s)) |
| 10008 | .sum::<f64>() |
| 10009 | / source.len() as f64; |
| 10010 | ladder.push((mean, (stream.len() as f64).log10())); |
| 10011 | let _ = std::fs::remove_file(&obu); |
| 10012 | } |
| 10013 | let _ = std::fs::remove_file(&raw_path); |
| 10014 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 10015 | (ladder, wall) |
| 10016 | } |
| 10017 | |
| 10018 | |
| 10019 | |
| 10020 | |
| 10021 | |
| 10022 | fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> { |
| 10023 | for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { |
| 10024 | if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) { |
| 10025 | return Some((plane, i, i64::from(l[i]), i64::from(r[i]))); |
| 10026 | } |
| 10027 | if l.len() != r.len() { |
| 10028 | return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64)); |
| 10029 | } |
| 10030 | } |
| 10031 | None |
| 10032 | } |
| 10033 | |
| 10034 | |
| 10035 | |
| 10036 | |
| 10037 | |
| 10038 | |
| 10039 | |
| 10040 | |
| 10041 | |
| 10042 | fn our_ladder( |
| 10043 | name: &str, |
| 10044 | source: &[Picture], |
| 10045 | width: usize, |
| 10046 | height: usize, |
| 10047 | fctx: &crate::decode::FrameCtx, |
| 10048 | ) -> (Vec<(f64, f64)>, f64) { |
| 10049 | let mut ladder = Vec::new(); |
| 10050 | let mut wall = 0.0; |
| 10051 | for &q in &[150u8, 120, 90, 60] { |
| 10052 | let start = std::time::Instant::now(); |
| 10053 | let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap(); |
| 10054 | wall += start.elapsed().as_secs_f64(); |
| 10055 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len()); |
| 10056 | let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 10057 | assert_eq!( |
| 10058 | ours.len(), |
| 10059 | source.len(), |
| 10060 | "{name} q={q}: our decoder's display-order frame count" |
| 10061 | ); |
| 10062 | for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() { |
| 10063 | if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) { |
| 10064 | panic!( |
| 10065 | "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \ |
| 10066 | {got}, the encoder reconstructed {want}" |
| 10067 | ); |
| 10068 | } |
| 10069 | } |
| 10070 | for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() { |
| 10071 | if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) { |
| 10072 | panic!( |
| 10073 | "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \ |
| 10074 | {got}, the encoder reconstructed {want}" |
| 10075 | ); |
| 10076 | } |
| 10077 | } |
| 10078 | let mean: f64 = decoded |
| 10079 | .iter() |
| 10080 | .zip(source) |
| 10081 | .map(|(d, s)| psnr_all(d, s)) |
| 10082 | .sum::<f64>() |
| 10083 | / source.len() as f64; |
| 10084 | ladder.push((mean, (encoded.stream.len() as f64).log10())); |
| 10085 | } |
| 10086 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 10087 | (ladder, wall) |
| 10088 | } |
| 10089 | |
| 10090 | |
| 10091 | |
| 10092 | |
| 10093 | |
| 10094 | fn pyramid_from_env() -> Option<crate::encoder::Pyramid> { |
| 10095 | let spec = std::env::var("EC_AV1_PYRAMID").ok()?; |
| 10096 | let mut f = spec.split(':'); |
| 10097 | let mini_gop = f.next()?.parse().ok()?; |
| 10098 | let d = crate::encoder::Pyramid::default(); |
| 10099 | Some(crate::encoder::Pyramid { |
| 10100 | mini_gop, |
| 10101 | arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), |
| 10102 | leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), |
| 10103 | }) |
| 10104 | } |
| 10105 | |
| 10106 | |
| 10107 | |
| 10108 | |
| 10109 | |
| 10110 | |
| 10111 | |
| 10112 | fn our_ladder_pyramid( |
| 10113 | name: &str, |
| 10114 | source: &[Picture], |
| 10115 | width: usize, |
| 10116 | height: usize, |
| 10117 | pyramid: crate::encoder::Pyramid, |
| 10118 | ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4]) { |
| 10119 | use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level}; |
| 10120 | let slot = |l: Level| match l { |
| 10121 | Level::Key => 0, |
| 10122 | Level::Arf => 1, |
| 10123 | Level::Leaf => 2, |
| 10124 | Level::ShowExisting => 3, |
| 10125 | }; |
| 10126 | let mut ladder = Vec::new(); |
| 10127 | let mut wall = 0.0; |
| 10128 | let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]); |
| 10129 | for &q in &[150u8, 120, 90, 60] { |
| 10130 | let config = EncoderConfig { |
| 10131 | width, |
| 10132 | height, |
| 10133 | base_q_idx: q, |
| 10134 | gop: source.len(), |
| 10135 | colour: Colour::Unspecified, |
| 10136 | tile_cols_log2: 0, |
| 10137 | tile_rows_log2: 0, |
| 10138 | }; |
| 10139 | let start = std::time::Instant::now(); |
| 10140 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 10141 | let mut packets = Vec::new(); |
| 10142 | for picture in source { |
| 10143 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 10144 | } |
| 10145 | packets.extend(enc.flush().unwrap()); |
| 10146 | wall += start.elapsed().as_secs_f64(); |
| 10147 | let mut stream = Vec::new(); |
| 10148 | for p in &packets { |
| 10149 | counts[slot(p.level)] += 1; |
| 10150 | bytes[slot(p.level)] += p.data.len(); |
| 10151 | stream.extend_from_slice(&p.data); |
| 10152 | } |
| 10153 | |
| 10154 | |
| 10155 | |
| 10156 | |
| 10157 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 10158 | assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count"); |
| 10159 | let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); |
| 10160 | for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() { |
| 10161 | if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) { |
| 10162 | panic!( |
| 10163 | "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \ |
| 10164 | decoded {got}, our decoder decoded {want}" |
| 10165 | ); |
| 10166 | } |
| 10167 | } |
| 10168 | let mean: f64 = decoded |
| 10169 | .iter() |
| 10170 | .zip(source) |
| 10171 | .map(|(d, s)| psnr_all(d, s)) |
| 10172 | .sum::<f64>() |
| 10173 | / source.len() as f64; |
| 10174 | ladder.push((mean, (stream.len() as f64).log10())); |
| 10175 | } |
| 10176 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 10177 | (ladder, wall, counts, bytes) |
| 10178 | } |
| 10179 | |
| 10180 | |
| 10181 | |
| 10182 | |
| 10183 | |
| 10184 | |
| 10185 | |
| 10186 | |
| 10187 | |
| 10188 | |
| 10189 | |
| 10190 | #[test] |
| 10191 | fn the_encoders_own_streams_are_byte_identical_to_their_pins() { |
| 10192 | if !have_ffmpeg() { |
| 10193 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg"); |
| 10194 | return; |
| 10195 | } |
| 10196 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 10197 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 10198 | if !clip.exists() { |
| 10199 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip"); |
| 10200 | return; |
| 10201 | } |
| 10202 | let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4); |
| 10203 | |
| 10204 | |
| 10205 | let fnv = |b: &[u8]| { |
| 10206 | b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| { |
| 10207 | (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3) |
| 10208 | }) |
| 10209 | }; |
| 10210 | let pins: [(u8, usize, u64); 2] = |
| 10211 | [(150, 7084, 0xe6a9_2f62_3855_0eee), (60, 26116, 0xa831_9866_b799_80fc)]; |
| 10212 | for (q, bytes, hash) in pins { |
| 10213 | let encoded = encode_sequence(&source, q, 0.5).unwrap(); |
| 10214 | assert_eq!( |
| 10215 | (encoded.stream.len(), fnv(&encoded.stream)), |
| 10216 | (bytes, hash), |
| 10217 | "q={q}: the encoder's stream moved" |
| 10218 | ); |
| 10219 | } |
| 10220 | } |
| 10221 | |
| 10222 | |
| 10223 | fn assert_monotone(name: &str, ladder: &[(f64, f64)]) { |
| 10224 | assert_eq!(ladder.len(), 4, "{name}: wanted four quality points"); |
| 10225 | for w in ladder.windows(2) { |
| 10226 | assert!( |
| 10227 | w[1].0 > w[0].0 && w[1].1 > w[0].1, |
| 10228 | "{name}: not monotone, {ladder:?}" |
| 10229 | ); |
| 10230 | } |
| 10231 | } |
| 10232 | |
| 10233 | |
| 10234 | |
| 10235 | |
| 10236 | |
| 10237 | #[test] |
| 10238 | #[ignore = "reads the real library"] |
| 10239 | fn probe_screen_detect() { |
| 10240 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 10241 | let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); |
| 10242 | for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] { |
| 10243 | let path = fixtures.join("video").join(name); |
| 10244 | if path.exists() { |
| 10245 | clips.push((name.to_string(), path)); |
| 10246 | } |
| 10247 | } |
| 10248 | if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) |
| 10249 | && let Some(p) = manifest |
| 10250 | .lines() |
| 10251 | .skip(1) |
| 10252 | .filter_map(|l| l.split('\t').next()) |
| 10253 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) |
| 10254 | { |
| 10255 | clips.push(("screen".to_string(), std::path::PathBuf::from(p))); |
| 10256 | } |
| 10257 | let (width, height) = (640usize, 384usize); |
| 10258 | for (name, path) in &clips { |
| 10259 | let frames = clip_frames(path.to_str().unwrap(), "0", width, height, 4); |
| 10260 | for (f, picture) in frames.iter().enumerate() { |
| 10261 | let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 10262 | let mut hist = [0usize; 257]; |
| 10263 | let mut blocks = 0usize; |
| 10264 | for by in (0..height).step_by(16) { |
| 10265 | for bx in (0..width).step_by(16) { |
| 10266 | let mut seen = [false; 256]; |
| 10267 | let mut colors = 0usize; |
| 10268 | for row in 0..16 { |
| 10269 | for col in 0..16 { |
| 10270 | let v = usize::from(y[(by + row) * width + bx + col]); |
| 10271 | if !seen[v] { |
| 10272 | seen[v] = true; |
| 10273 | colors += 1; |
| 10274 | } |
| 10275 | } |
| 10276 | } |
| 10277 | hist[colors] += 1; |
| 10278 | blocks += 1; |
| 10279 | } |
| 10280 | } |
| 10281 | let share = |limit: usize| { |
| 10282 | 100.0 * hist[2..=limit.min(256)].iter().sum::<usize>() as f64 |
| 10283 | / blocks.max(1) as f64 |
| 10284 | }; |
| 10285 | eprintln!( |
| 10286 | "{name} frame {f}: <=4 {:.1}% <=8 {:.1}% <=16 {:.1}% <=32 {:.1}% <=64 {:.1}% <=128 {:.1}%", |
| 10287 | share(4), |
| 10288 | share(8), |
| 10289 | share(16), |
| 10290 | share(32), |
| 10291 | share(64), |
| 10292 | share(128), |
| 10293 | ); |
| 10294 | } |
| 10295 | } |
| 10296 | } |
| 10297 | |
| 10298 | |
| 10299 | |
| 10300 | |
| 10301 | |
| 10302 | |
| 10303 | |
| 10304 | |
| 10305 | |
| 10306 | |
| 10307 | |
| 10308 | |
| 10309 | |
| 10310 | |
| 10311 | |
| 10312 | |
| 10313 | |
| 10314 | |
| 10315 | |
| 10316 | |
| 10317 | |
| 10318 | |
| 10319 | |
| 10320 | |
| 10321 | |
| 10322 | |
| 10323 | |
| 10324 | |
| 10325 | |
| 10326 | |
| 10327 | |
| 10328 | |
| 10329 | |
| 10330 | |
| 10331 | |
| 10332 | |
| 10333 | |
| 10334 | |
| 10335 | |
| 10336 | |
| 10337 | |
| 10338 | |
| 10339 | |
| 10340 | |
| 10341 | |
| 10342 | |
| 10343 | |
| 10344 | |
| 10345 | |
| 10346 | |
| 10347 | |
| 10348 | |
| 10349 | |
| 10350 | |
| 10351 | |
| 10352 | |
| 10353 | |
| 10354 | |
| 10355 | |
| 10356 | |
| 10357 | |
| 10358 | |
| 10359 | |
| 10360 | |
| 10361 | |
| 10362 | |
| 10363 | |
| 10364 | |
| 10365 | |
| 10366 | |
| 10367 | |
| 10368 | |
| 10369 | |
| 10370 | |
| 10371 | |
| 10372 | |
| 10373 | |
| 10374 | |
| 10375 | |
| 10376 | |
| 10377 | |
| 10378 | #[test] |
| 10379 | #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"] |
| 10380 | fn bd_rate_vs_libaom_and_rav1e() { |
| 10381 | if !have_ffmpeg() { |
| 10382 | eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg"); |
| 10383 | return; |
| 10384 | } |
| 10385 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 10386 | let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); |
| 10387 | for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] { |
| 10388 | let path = fixtures.join("video").join(name); |
| 10389 | if path.exists() { |
| 10390 | clips.push((name.to_string(), path)); |
| 10391 | } else { |
| 10392 | eprintln!("SKIP clip {name}: missing"); |
| 10393 | } |
| 10394 | } |
| 10395 | |
| 10396 | |
| 10397 | match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) { |
| 10398 | Ok(manifest) => { |
| 10399 | let screen = manifest |
| 10400 | .lines() |
| 10401 | .skip(1) |
| 10402 | .filter_map(|l| l.split('\t').next()) |
| 10403 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()); |
| 10404 | match screen { |
| 10405 | Some(p) => clips.push(( |
| 10406 | format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)), |
| 10407 | std::path::PathBuf::from(p), |
| 10408 | )), |
| 10409 | None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"), |
| 10410 | } |
| 10411 | } |
| 10412 | Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"), |
| 10413 | } |
| 10414 | assert!(!clips.is_empty(), "no source clip available"); |
| 10415 | |
| 10416 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 10417 | let aom_points: Vec<Vec<String>> = [5, 20, 35, 45] |
| 10418 | .iter() |
| 10419 | .map(|q| { |
| 10420 | ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()] |
| 10421 | .map(String::from) |
| 10422 | .to_vec() |
| 10423 | }) |
| 10424 | .collect(); |
| 10425 | let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200] |
| 10426 | .iter() |
| 10427 | .map(|q| { |
| 10428 | vec![ |
| 10429 | "-rav1e-params".to_string(), |
| 10430 | format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"), |
| 10431 | ] |
| 10432 | }) |
| 10433 | .collect(); |
| 10434 | println!( |
| 10435 | "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread" |
| 10436 | ); |
| 10437 | println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"); |
| 10438 | println!("|---|---|---|---|---|"); |
| 10439 | for (name, path) in &clips { |
| 10440 | let fctx = &crate::decode::FrameCtx::new(); |
| 10441 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 10442 | let _ = take_partition_hits(); |
| 10443 | let _ = crate::tile::take_palette_hits(); |
| 10444 | SCREEN_FRAMES.iter().for_each(|c| { |
| 10445 | c.store(0, std::sync::atomic::Ordering::Relaxed); |
| 10446 | }); |
| 10447 | let _ = take_uv_mode_hits(); |
| 10448 | let _ = crate::tile::take_inter_mode_hits(); |
| 10449 | let _ = crate::tile::take_drl_hits(); |
| 10450 | let _ = crate::tile::take_ref_hits(); |
| 10451 | let _ = crate::tile::take_compound_mode_hits(); |
| 10452 | let _ = crate::tile::take_compound_pair_hits(); |
| 10453 | let _ = crate::tile::take_compound_size_hits(); |
| 10454 | let _ = crate::motion::take_census(); |
| 10455 | let (ours, ours_wall) = match pyramid_from_env() { |
| 10456 | None => our_ladder(name, &source, width, height, fctx), |
| 10457 | Some(pyramid) => { |
| 10458 | let (ladder, wall, counts, bytes) = |
| 10459 | our_ladder_pyramid(name, &source, width, height, pyramid); |
| 10460 | eprintln!( |
| 10461 | "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \ |
| 10462 | show_existing {}; bytes key {} arf {} leaf {} show_existing {}", |
| 10463 | counts[0], counts[1], counts[2], counts[3], |
| 10464 | bytes[0], bytes[1], bytes[2], bytes[3], |
| 10465 | ); |
| 10466 | (ladder, wall) |
| 10467 | } |
| 10468 | }; |
| 10469 | |
| 10470 | |
| 10471 | |
| 10472 | let [whole32, split32, whole16, split16] = take_partition_hits(); |
| 10473 | |
| 10474 | |
| 10475 | |
| 10476 | let [nearest, near, global, new] = crate::tile::take_inter_mode_hits(); |
| 10477 | let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits(); |
| 10478 | let refs = crate::tile::take_ref_hits(); |
| 10479 | let modes_total = (nearest + near + global + new).max(1); |
| 10480 | eprintln!( |
| 10481 | "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \ |
| 10482 | GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \ |
| 10483 | {drl0}/{drl1}/{drl2}/{drl3}", |
| 10484 | 100.0 * nearest as f64 / modes_total as f64, |
| 10485 | 100.0 * near as f64 / modes_total as f64, |
| 10486 | 100.0 * global as f64 / modes_total as f64, |
| 10487 | 100.0 * new as f64 / modes_total as f64, |
| 10488 | ); |
| 10489 | |
| 10490 | |
| 10491 | |
| 10492 | |
| 10493 | let comp_modes = crate::tile::take_compound_mode_hits(); |
| 10494 | let comp_pairs = crate::tile::take_compound_pair_hits(); |
| 10495 | let comp_sizes = crate::tile::take_compound_size_hits(); |
| 10496 | let comp_total: usize = comp_modes.iter().sum(); |
| 10497 | eprintln!( |
| 10498 | "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \ |
| 10499 | NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \ |
| 10500 | GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}", |
| 10501 | modes_total + comp_total, |
| 10502 | 100.0 * comp_total as f64 / (modes_total + comp_total) as f64, |
| 10503 | comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3], |
| 10504 | comp_modes[6], comp_modes[7], |
| 10505 | comp_pairs[3], comp_pairs[6], |
| 10506 | ); |
| 10507 | eprintln!( |
| 10508 | "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}", |
| 10509 | comp_sizes[1], comp_sizes[2], comp_sizes[3], |
| 10510 | ); |
| 10511 | |
| 10512 | |
| 10513 | |
| 10514 | |
| 10515 | let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census(); |
| 10516 | let per = |n: u64| n as f64 / calls.max(1) as f64; |
| 10517 | eprintln!( |
| 10518 | "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \ |
| 10519 | {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \ |
| 10520 | +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%", |
| 10521 | per(evals), |
| 10522 | 100.0 * subpel as f64 / evals.max(1) as f64, |
| 10523 | per(rounds), |
| 10524 | 100.0 * near_pred as f64 / calls.max(1) as f64, |
| 10525 | 100.0 * unmoved as f64 / calls.max(1) as f64, |
| 10526 | ); |
| 10527 | eprintln!( |
| 10528 | "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})", |
| 10529 | refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6] |
| 10530 | ); |
| 10531 | eprintln!( |
| 10532 | "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \ |
| 10533 | 16x16 leaves split into 8s {split16} of {} ({:.1}%)", |
| 10534 | whole32 + split32, |
| 10535 | 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64, |
| 10536 | whole16 + split16, |
| 10537 | 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64 |
| 10538 | ); |
| 10539 | |
| 10540 | |
| 10541 | let levels = crate::filter_search::take_chosen_levels(); |
| 10542 | type Chosen = ((u8, u8), (u8, u8), (u8, u8)); |
| 10543 | let mean = |f: fn(&Chosen) -> u8| { |
| 10544 | levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64 |
| 10545 | }; |
| 10546 | eprintln!( |
| 10547 | "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \ |
| 10548 | cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}", |
| 10549 | levels.len(), |
| 10550 | mean(|l| l.0.0), |
| 10551 | mean(|l| l.0.1), |
| 10552 | mean(|l| l.1.0), |
| 10553 | mean(|l| l.1.1), |
| 10554 | mean(|l| l.2.0), |
| 10555 | mean(|l| l.2.1), |
| 10556 | ); |
| 10557 | |
| 10558 | |
| 10559 | |
| 10560 | let presets = crate::filter_search::take_cdef_presets(); |
| 10561 | let mut by_bits = [0usize; 4]; |
| 10562 | for (b, _) in &presets { |
| 10563 | by_bits[usize::from(*b)] += 1; |
| 10564 | } |
| 10565 | let units: usize = presets.iter().flat_map(|(_, c)| c).sum(); |
| 10566 | let on_extra: usize = presets |
| 10567 | .iter() |
| 10568 | .flat_map(|(_, c)| c.iter().skip(1)) |
| 10569 | .sum(); |
| 10570 | eprintln!( |
| 10571 | "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \ |
| 10572 | on a non-default preset ({:.1}%)", |
| 10573 | by_bits[0], |
| 10574 | by_bits[1], |
| 10575 | by_bits[2], |
| 10576 | by_bits[3], |
| 10577 | on_extra, |
| 10578 | units, |
| 10579 | 100.0 * on_extra as f64 / units.max(1) as f64 |
| 10580 | ); |
| 10581 | |
| 10582 | |
| 10583 | let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram(); |
| 10584 | eprintln!( |
| 10585 | "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)", |
| 10586 | 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64 |
| 10587 | ); |
| 10588 | |
| 10589 | |
| 10590 | |
| 10591 | |
| 10592 | |
| 10593 | |
| 10594 | |
| 10595 | let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); |
| 10596 | let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); |
| 10597 | let palette = crate::tile::take_palette_hits(); |
| 10598 | eprintln!( |
| 10599 | "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}", |
| 10600 | palette[0], |
| 10601 | (2..=8) |
| 10602 | .filter(|&n| palette[n] > 0) |
| 10603 | .map(|n| format!("{n}={}", palette[n])) |
| 10604 | .collect::<Vec<_>>() |
| 10605 | .join(" ") |
| 10606 | ); |
| 10607 | let palette_uv = crate::tile::take_palette_uv_hits(); |
| 10608 | eprintln!( |
| 10609 | "{name}: chroma palette blocks {} sizes {}", |
| 10610 | palette_uv[0], |
| 10611 | (2..=8) |
| 10612 | .filter(|&n| palette_uv[n] > 0) |
| 10613 | .map(|n| format!("{n}={}", palette_uv[n])) |
| 10614 | .collect::<Vec<_>>() |
| 10615 | .join(" ") |
| 10616 | ); |
| 10617 | let uv = take_uv_mode_hits(); |
| 10618 | let uv_total: usize = uv.iter().sum(); |
| 10619 | eprintln!( |
| 10620 | "{name}: uv modes {}", |
| 10621 | uv.iter() |
| 10622 | .enumerate() |
| 10623 | .filter(|&(_, &n)| n > 0) |
| 10624 | .map(|(m, &n)| format!( |
| 10625 | "{}={n} ({:.1}%)", |
| 10626 | UV_MODE_NAMES[m], |
| 10627 | 100.0 * n as f64 / uv_total.max(1) as f64 |
| 10628 | )) |
| 10629 | .collect::<Vec<_>>() |
| 10630 | .join(" ") |
| 10631 | ); |
| 10632 | |
| 10633 | |
| 10634 | |
| 10635 | let depths = take_tx_depth_hits(); |
| 10636 | let depth_total: usize = depths.iter().sum(); |
| 10637 | eprintln!( |
| 10638 | "{name}: intra tx depths {}", |
| 10639 | depths |
| 10640 | .iter() |
| 10641 | .enumerate() |
| 10642 | .map(|(d, &n)| format!( |
| 10643 | "{d}={n} ({:.1}%)", |
| 10644 | 100.0 * n as f64 / depth_total.max(1) as f64 |
| 10645 | )) |
| 10646 | .collect::<Vec<_>>() |
| 10647 | .join(" ") |
| 10648 | ); |
| 10649 | |
| 10650 | |
| 10651 | |
| 10652 | let splits = take_inter_tx_split_hits(); |
| 10653 | let split_total: usize = splits.iter().sum(); |
| 10654 | eprintln!( |
| 10655 | "{name}: inter var-tx depths {}", |
| 10656 | splits |
| 10657 | .iter() |
| 10658 | .enumerate() |
| 10659 | .map(|(d, &n)| format!( |
| 10660 | "{d}={n} ({:.1}%)", |
| 10661 | 100.0 * n as f64 / split_total.max(1) as f64 |
| 10662 | )) |
| 10663 | .collect::<Vec<_>>() |
| 10664 | .join(" ") |
| 10665 | ); |
| 10666 | let (aom, aom_wall) = |
| 10667 | external_ladder(&source, width, height, "libaom-av1", &aom_points); |
| 10668 | let (rav1e, rav1e_wall) = |
| 10669 | external_ladder(&source, width, height, "librav1e", &rav1e_points); |
| 10670 | assert_monotone(&format!("{name}: ours"), &ours); |
| 10671 | assert_monotone(&format!("{name}: libaom"), &aom); |
| 10672 | assert_monotone(&format!("{name}: rav1e"), &rav1e); |
| 10673 | let points = ours |
| 10674 | .iter() |
| 10675 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 10676 | .collect::<Vec<_>>() |
| 10677 | .join(", "); |
| 10678 | println!( |
| 10679 | "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |", |
| 10680 | bd_rate(&aom, &ours) * 100.0, |
| 10681 | bd_rate(&rav1e, &ours) * 100.0, |
| 10682 | ); |
| 10683 | println!( |
| 10684 | "| references | libaom {} | rav1e {} | | |", |
| 10685 | aom.iter() |
| 10686 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 10687 | .collect::<Vec<_>>() |
| 10688 | .join(", "), |
| 10689 | rav1e |
| 10690 | .iter() |
| 10691 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 10692 | .collect::<Vec<_>>() |
| 10693 | .join(", "), |
| 10694 | ); |
| 10695 | } |
| 10696 | } |
| 10697 | } |