| 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 | |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | const LEAF_SECOND_NEW_MARGIN: f64 = 0.8; |
| 211 | |
| 212 | |
| 213 | |
| 214 | fn leaf_second_new_margin() -> f64 { |
| 215 | match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() { |
| 216 | Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN), |
| 217 | None => LEAF_SECOND_NEW_MARGIN, |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | |
| 222 | fn leaf_second_new_mv() -> bool { |
| 223 | match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() { |
| 224 | Some(v) => v != "0", |
| 225 | None => true, |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | const LEAF_COMPOUND: bool = true; |
| 235 | |
| 236 | |
| 237 | fn leaf_compound() -> bool { |
| 238 | match std::env::var("EC_AV1_LEAF_COMPOUND").ok() { |
| 239 | Some(v) => v != "0", |
| 240 | None => LEAF_COMPOUND, |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | |
| 245 | fn leaf_new_mv() -> bool { |
| 246 | match std::env::var("EC_AV1_LEAF_NEWMV").ok() { |
| 247 | Some(v) if cfg!(test) => v != "0", |
| 248 | _ => LEAF_NEW_MV, |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | const SPLIT_INTER_BLOCKS: bool = true; |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | fn split_inter_blocks() -> bool { |
| 263 | match std::env::var("EC_AV1_SPLIT_INTER").ok() { |
| 264 | Some(v) if cfg!(test) => v != "0", |
| 265 | _ => SPLIT_INTER_BLOCKS, |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | const RESTORATION: bool = true; |
| 274 | |
| 275 | |
| 276 | fn restoration_enabled() -> bool { |
| 277 | match std::env::var("EC_AV1_LR").ok() { |
| 278 | Some(v) if cfg!(test) => v != "0", |
| 279 | _ => RESTORATION, |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | |
| 284 | |
| 285 | |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | |
| 294 | |
| 295 | |
| 296 | const SPLIT_BREAKOUT_COEFFS: usize = 0; |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 304 | |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | const SPLIT_RD_THRESHOLD: f64 = 0.125; |
| 318 | |
| 319 | |
| 320 | fn split_rd_threshold() -> f64 { |
| 321 | static T: std::sync::OnceLock<f64> = std::sync::OnceLock::new(); |
| 322 | *T.get_or_init(|| { |
| 323 | std::env::var("EC_AV1_SPLIT_RD") |
| 324 | .ok() |
| 325 | .and_then(|v| v.parse().ok()) |
| 326 | .unwrap_or(SPLIT_RD_THRESHOLD) |
| 327 | }) |
| 328 | } |
| 329 | |
| 330 | |
| 331 | |
| 332 | fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool { |
| 333 | let t = split_rd_threshold(); |
| 334 | t > 0.0 && cost < t * lambda * (side * side) as f64 |
| 335 | } |
| 336 | |
| 337 | |
| 338 | |
| 339 | fn split_breakout_coeffs() -> usize { |
| 340 | match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() { |
| 341 | Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS), |
| 342 | _ => SPLIT_BREAKOUT_COEFFS, |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | |
| 351 | static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [ |
| 352 | std::sync::atomic::AtomicUsize::new(0), |
| 353 | std::sync::atomic::AtomicUsize::new(0), |
| 354 | std::sync::atomic::AtomicUsize::new(0), |
| 355 | std::sync::atomic::AtomicUsize::new(0), |
| 356 | ]; |
| 357 | |
| 358 | |
| 359 | fn partition_hit(which: usize) { |
| 360 | PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 361 | } |
| 362 | |
| 363 | |
| 364 | #[cfg(test)] |
| 365 | pub(crate) fn take_partition_hits() -> [usize; 4] { |
| 366 | [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 367 | } |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | pub fn census_on() -> bool { |
| 375 | static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); |
| 376 | *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1"))) |
| 377 | } |
| 378 | |
| 379 | |
| 380 | pub const CENSUS_KINDS: [&str; 11] = [ |
| 381 | "intra blocks searched (key frame + inter leaves)", |
| 382 | "intra luma mode trials", |
| 383 | "chroma searches", |
| 384 | "chroma mode trials (each = 2 plane trials)", |
| 385 | "tx-depth trials (transform units, depth >= 1)", |
| 386 | "inter 32x32 blocks searched", |
| 387 | "inter block intra-mode trials", |
| 388 | "inter mv candidates (each = 3 mc trials)", |
| 389 | "inter leaves searched (intra vs NEARESTMV/NEWMV)", |
| 390 | " of those, intra won", |
| 391 | " of those, the NEARESTMV trial coded no residual", |
| 392 | ]; |
| 393 | |
| 394 | |
| 395 | static CENSUS: [std::sync::atomic::AtomicUsize; 11] = |
| 396 | [const { std::sync::atomic::AtomicUsize::new(0) }; 11]; |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] = |
| 402 | [const { std::sync::atomic::AtomicUsize::new(0) }; 13]; |
| 403 | static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] = |
| 404 | [const { std::sync::atomic::AtomicUsize::new(0) }; 7]; |
| 405 | |
| 406 | fn census_add(kind: usize, n: usize) { |
| 407 | if census_on() { |
| 408 | CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed); |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | |
| 413 | pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) { |
| 414 | let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed); |
| 415 | ( |
| 416 | std::array::from_fn(|i| take(&CENSUS[i])), |
| 417 | std::array::from_fn(|i| take(&LUMA_RANK[i])), |
| 418 | std::array::from_fn(|i| take(&CHROMA_RANK[i])), |
| 419 | ) |
| 420 | } |
| 421 | |
| 422 | |
| 423 | |
| 424 | |
| 425 | fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize { |
| 426 | scored |
| 427 | .iter() |
| 428 | .filter(|&&(score, mode)| { |
| 429 | mode != winner |
| 430 | && score |
| 431 | < scored |
| 432 | .iter() |
| 433 | .find(|&&(_, m)| m == winner) |
| 434 | .map_or(f64::INFINITY, |&(s, _)| s) |
| 435 | }) |
| 436 | .count() |
| 437 | } |
| 438 | |
| 439 | |
| 440 | |
| 441 | const SPLIT_BLOCKS: bool = true; |
| 442 | |
| 443 | |
| 444 | |
| 445 | pub(crate) fn split_blocks() -> bool { |
| 446 | SPLIT_BLOCKS |
| 447 | } |
| 448 | |
| 449 | |
| 450 | |
| 451 | |
| 452 | |
| 453 | |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 459 | pub struct Picture { |
| 460 | |
| 461 | pub width: usize, |
| 462 | |
| 463 | pub height: usize, |
| 464 | |
| 465 | pub y: Vec<u16>, |
| 466 | |
| 467 | pub u: Vec<u16>, |
| 468 | |
| 469 | pub v: Vec<u16>, |
| 470 | } |
| 471 | |
| 472 | impl Picture { |
| 473 | |
| 474 | #[must_use] |
| 475 | pub fn grey(width: usize, height: usize) -> Self { |
| 476 | Self { |
| 477 | width, |
| 478 | height, |
| 479 | y: vec![128; width * height], |
| 480 | u: vec![128; width * height / 4], |
| 481 | v: vec![128; width * height / 4], |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | pub(crate) fn check(&self) -> Result<()> { |
| 486 | if self.width == 0 |
| 487 | || !self.width.is_multiple_of(BLOCK) |
| 488 | || !self.height.is_multiple_of(BLOCK) |
| 489 | || !self.height.is_multiple_of(BLOCK) |
| 490 | { |
| 491 | return Err(Error::unsupported( |
| 492 | "AV1 encode", |
| 493 | "the picture must be a whole number of 32x32 blocks in each direction", |
| 494 | )); |
| 495 | } |
| 496 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 497 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 498 | return Err(Error::unsupported( |
| 499 | "AV1 encode", |
| 500 | "each plane must carry one sample per position at 4:2:0", |
| 501 | )); |
| 502 | } |
| 503 | Ok(()) |
| 504 | } |
| 505 | |
| 506 | |
| 507 | |
| 508 | |
| 509 | |
| 510 | pub(crate) fn check_even(&self) -> Result<()> { |
| 511 | if self.width == 0 |
| 512 | || self.height == 0 |
| 513 | || !self.width.is_multiple_of(2) |
| 514 | || !self.height.is_multiple_of(2) |
| 515 | { |
| 516 | return Err(Error::unsupported( |
| 517 | "AV1 encode", |
| 518 | "the picture's width and height must each be even and nonzero", |
| 519 | )); |
| 520 | } |
| 521 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 522 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 523 | return Err(Error::unsupported( |
| 524 | "AV1 encode", |
| 525 | "each plane must carry one sample per position at 4:2:0", |
| 526 | )); |
| 527 | } |
| 528 | Ok(()) |
| 529 | } |
| 530 | |
| 531 | |
| 532 | |
| 533 | |
| 534 | |
| 535 | |
| 536 | |
| 537 | |
| 538 | pub(crate) fn padded_to(&self, align: usize) -> Picture { |
| 539 | let padded_width = self.width.next_multiple_of(align); |
| 540 | let padded_height = self.height.next_multiple_of(align); |
| 541 | if padded_width == self.width && padded_height == self.height { |
| 542 | return self.clone(); |
| 543 | } |
| 544 | Picture { |
| 545 | width: padded_width, |
| 546 | height: padded_height, |
| 547 | y: pad_plane( |
| 548 | &self.y, |
| 549 | self.width, |
| 550 | self.height, |
| 551 | padded_width, |
| 552 | padded_height, |
| 553 | ), |
| 554 | u: pad_plane( |
| 555 | &self.u, |
| 556 | self.width / 2, |
| 557 | self.height / 2, |
| 558 | padded_width / 2, |
| 559 | padded_height / 2, |
| 560 | ), |
| 561 | v: pad_plane( |
| 562 | &self.v, |
| 563 | self.width / 2, |
| 564 | self.height / 2, |
| 565 | padded_width / 2, |
| 566 | padded_height / 2, |
| 567 | ), |
| 568 | } |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | |
| 573 | |
| 574 | |
| 575 | |
| 576 | |
| 577 | |
| 578 | #[allow(clippy::too_many_arguments)] |
| 579 | fn intra_predict_u8( |
| 580 | mode: u8, |
| 581 | angle_delta: i32, |
| 582 | above: Option<&[u8]>, |
| 583 | left: Option<&[u8]>, |
| 584 | corner: Option<u8>, |
| 585 | bw: usize, |
| 586 | bh: usize, |
| 587 | enable_edge_filter: bool, |
| 588 | smooth_neighbor: bool, |
| 589 | dst: &mut [u8], fctx: &crate::decode::FrameCtx, |
| 590 | ) { |
| 591 | let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect()); |
| 592 | let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect()); |
| 593 | let mut dst16 = vec![0u16; dst.len()]; |
| 594 | crate::intra::predict( |
| 595 | mode, |
| 596 | angle_delta, |
| 597 | above16.as_deref(), |
| 598 | left16.as_deref(), |
| 599 | corner.map(u16::from), |
| 600 | bw, |
| 601 | bh, |
| 602 | enable_edge_filter, |
| 603 | smooth_neighbor, |
| 604 | &mut dst16, fctx, |
| 605 | ); |
| 606 | for (d, &s) in dst.iter_mut().zip(dst16.iter()) { |
| 607 | *d = s as u8; |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | |
| 612 | |
| 613 | |
| 614 | fn pad_plane<T: Copy + Default>( |
| 615 | source: &[T], |
| 616 | width: usize, |
| 617 | height: usize, |
| 618 | padded_width: usize, |
| 619 | padded_height: usize, |
| 620 | ) -> Vec<T> { |
| 621 | let mut out = vec![T::default(); padded_width * padded_height]; |
| 622 | for row in 0..padded_height { |
| 623 | let src = source[row.min(height - 1) * width..][..width].as_ref(); |
| 624 | let dst = &mut out[row * padded_width..][..padded_width]; |
| 625 | dst[..width].copy_from_slice(src); |
| 626 | dst[width..].fill(src[width - 1]); |
| 627 | } |
| 628 | out |
| 629 | } |
| 630 | |
| 631 | |
| 632 | |
| 633 | |
| 634 | fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> { |
| 635 | let mut out = Vec::with_capacity(width * height); |
| 636 | for row in 0..height { |
| 637 | out.extend_from_slice(&source[row * padded_width..][..width]); |
| 638 | } |
| 639 | out |
| 640 | } |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | |
| 646 | pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded { |
| 647 | let reconstruction = &encoded.reconstruction; |
| 648 | let cropped = if reconstruction.width == width && reconstruction.height == height { |
| 649 | reconstruction.clone() |
| 650 | } else { |
| 651 | Picture { |
| 652 | width, |
| 653 | height, |
| 654 | y: crop_plane(&reconstruction.y, reconstruction.width, width, height), |
| 655 | u: crop_plane( |
| 656 | &reconstruction.u, |
| 657 | reconstruction.width / 2, |
| 658 | width / 2, |
| 659 | height / 2, |
| 660 | ), |
| 661 | v: crop_plane( |
| 662 | &reconstruction.v, |
| 663 | reconstruction.width / 2, |
| 664 | width / 2, |
| 665 | height / 2, |
| 666 | ), |
| 667 | } |
| 668 | }; |
| 669 | Encoded { |
| 670 | stream: encoded.stream.clone(), |
| 671 | modes: encoded.modes.clone(), |
| 672 | inter_block_share: encoded.inter_block_share, |
| 673 | reconstruction: cropped, |
| 674 | tile: encoded.tile.clone(), |
| 675 | mi_cols: encoded.mi_cols, |
| 676 | mi_rows: encoded.mi_rows, |
| 677 | base_q_idx: encoded.base_q_idx, |
| 678 | tx_select: encoded.tx_select, |
| 679 | screen: encoded.screen, |
| 680 | start_cdfs: encoded.start_cdfs.clone(), |
| 681 | next_cdfs: encoded.next_cdfs.clone(), |
| 682 | loop_filter: encoded.loop_filter, |
| 683 | loop_restoration: encoded.loop_restoration, |
| 684 | cdef: encoded.cdef, |
| 685 | } |
| 686 | } |
| 687 | |
| 688 | |
| 689 | |
| 690 | #[derive(Clone)] |
| 691 | pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs); |
| 692 | |
| 693 | impl std::fmt::Debug for CdfSnapshot { |
| 694 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 695 | f.write_str("CdfSnapshot") |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | |
| 700 | #[derive(Clone, Debug)] |
| 701 | pub struct Encoded { |
| 702 | |
| 703 | |
| 704 | pub stream: Vec<u8>, |
| 705 | |
| 706 | |
| 707 | pub reconstruction: Picture, |
| 708 | |
| 709 | |
| 710 | |
| 711 | pub modes: Vec<u8>, |
| 712 | |
| 713 | |
| 714 | |
| 715 | |
| 716 | pub inter_block_share: f64, |
| 717 | |
| 718 | |
| 719 | |
| 720 | |
| 721 | pub(crate) tile: Vec<u8>, |
| 722 | pub(crate) mi_cols: u32, |
| 723 | pub(crate) mi_rows: u32, |
| 724 | pub(crate) base_q_idx: u8, |
| 725 | |
| 726 | |
| 727 | |
| 728 | |
| 729 | |
| 730 | |
| 731 | pub(crate) tx_select: bool, |
| 732 | |
| 733 | |
| 734 | |
| 735 | |
| 736 | |
| 737 | |
| 738 | pub(crate) start_cdfs: CdfSnapshot, |
| 739 | |
| 740 | |
| 741 | |
| 742 | |
| 743 | pub(crate) next_cdfs: CdfSnapshot, |
| 744 | |
| 745 | |
| 746 | |
| 747 | |
| 748 | |
| 749 | pub(crate) loop_filter: LoopFilterParams, |
| 750 | |
| 751 | |
| 752 | pub(crate) cdef: CdefParams, |
| 753 | |
| 754 | |
| 755 | |
| 756 | |
| 757 | pub(crate) screen: bool, |
| 758 | |
| 759 | |
| 760 | |
| 761 | |
| 762 | pub(crate) loop_restoration: LoopRestorationParams, |
| 763 | } |
| 764 | |
| 765 | thread_local! { |
| 766 | |
| 767 | |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | |
| 774 | |
| 775 | |
| 776 | static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 777 | } |
| 778 | |
| 779 | thread_local! { |
| 780 | |
| 781 | |
| 782 | |
| 783 | |
| 784 | |
| 785 | |
| 786 | static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) }; |
| 787 | } |
| 788 | |
| 789 | #[cfg(test)] |
| 790 | pub(crate) fn force_screen(value: Option<bool>) { |
| 791 | SCREEN_FORCE.with(|c| c.set(value)); |
| 792 | } |
| 793 | |
| 794 | pub(crate) fn arm_seq_screen(on: bool) { |
| 795 | SEQ_SCREEN.with(|c| c.set(on)); |
| 796 | } |
| 797 | |
| 798 | fn seq_screen() -> bool { |
| 799 | SEQ_SCREEN.with(std::cell::Cell::get) |
| 800 | } |
| 801 | |
| 802 | |
| 803 | |
| 804 | |
| 805 | |
| 806 | |
| 807 | |
| 808 | |
| 809 | fn screen_colors() -> usize { |
| 810 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 811 | *N.get_or_init(|| { |
| 812 | std::env::var("EC_AV1_SCREEN_COLORS") |
| 813 | .ok() |
| 814 | .and_then(|v| v.parse().ok()) |
| 815 | .unwrap_or(32) |
| 816 | }) |
| 817 | } |
| 818 | |
| 819 | |
| 820 | |
| 821 | |
| 822 | |
| 823 | |
| 824 | fn screen_pct() -> usize { |
| 825 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 826 | *N.get_or_init(|| { |
| 827 | std::env::var("EC_AV1_SCREEN_PCT") |
| 828 | .ok() |
| 829 | .and_then(|v| v.parse().ok()) |
| 830 | .unwrap_or(3) |
| 831 | }) |
| 832 | } |
| 833 | |
| 834 | |
| 835 | |
| 836 | pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] = |
| 837 | [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; |
| 838 | |
| 839 | |
| 840 | |
| 841 | |
| 842 | |
| 843 | |
| 844 | fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool { |
| 845 | if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) { |
| 846 | SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 847 | return forced; |
| 848 | } |
| 849 | if let Ok(v) = std::env::var("EC_AV1_SCREEN") { |
| 850 | let on = v != "0"; |
| 851 | SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 852 | return on; |
| 853 | } |
| 854 | let (blk, limit) = (16usize, screen_colors()); |
| 855 | let mut counted = 0usize; |
| 856 | for by in (0..true_height).step_by(blk) { |
| 857 | for bx in (0..true_width).step_by(blk) { |
| 858 | let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk)); |
| 859 | let mut seen = [false; 256]; |
| 860 | let mut colors = 0usize; |
| 861 | for row in 0..h { |
| 862 | for col in 0..w { |
| 863 | let v = usize::from(y[(by + row) * width + bx + col]); |
| 864 | if !seen[v] { |
| 865 | seen[v] = true; |
| 866 | colors += 1; |
| 867 | } |
| 868 | } |
| 869 | } |
| 870 | if colors > 1 && colors <= limit { |
| 871 | counted += 1; |
| 872 | } |
| 873 | } |
| 874 | } |
| 875 | let on = counted * blk * blk * screen_pct() > true_width * true_height; |
| 876 | SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 877 | on |
| 878 | } |
| 879 | |
| 880 | |
| 881 | |
| 882 | |
| 883 | |
| 884 | |
| 885 | |
| 886 | |
| 887 | |
| 888 | |
| 889 | pub fn key_frame_headers( |
| 890 | width: usize, |
| 891 | height: usize, |
| 892 | base_q_idx: u8, |
| 893 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 894 | key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config()) |
| 895 | } |
| 896 | |
| 897 | |
| 898 | |
| 899 | |
| 900 | |
| 901 | fn unspecified_color_config() -> ColorConfig { |
| 902 | ColorConfig { |
| 903 | bit_depth: 8, |
| 904 | mono_chrome: false, |
| 905 | num_planes: 3, |
| 906 | color_primaries: 2, |
| 907 | transfer_characteristics: 2, |
| 908 | matrix_coefficients: 2, |
| 909 | color_range: false, |
| 910 | subsampling_x: 1, |
| 911 | subsampling_y: 1, |
| 912 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 913 | separate_uv_delta_q: false, |
| 914 | } |
| 915 | } |
| 916 | |
| 917 | |
| 918 | |
| 919 | |
| 920 | |
| 921 | |
| 922 | |
| 923 | |
| 924 | |
| 925 | pub(crate) fn key_frame_headers_colour( |
| 926 | width: usize, |
| 927 | height: usize, |
| 928 | base_q_idx: u8, |
| 929 | color_config: ColorConfig, |
| 930 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 931 | let bits = |n: usize| -> Result<u32> { |
| 932 | let n = u32::try_from(n).map_err(|_| too_large())?; |
| 933 | if n == 0 || n > 1 << 16 { |
| 934 | return Err(too_large()); |
| 935 | } |
| 936 | Ok((32 - (n - 1).leading_zeros()).max(1)) |
| 937 | }; |
| 938 | let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?); |
| 939 | let (w, h) = (width as u32, height as u32); |
| 940 | let seq = SequenceHeader { |
| 941 | seq_profile: 0, |
| 942 | operating_points: vec![OperatingPoint { |
| 943 | seq_level_idx: 8, |
| 944 | ..OperatingPoint::default() |
| 945 | }], |
| 946 | frame_width_bits, |
| 947 | frame_height_bits, |
| 948 | max_frame_width: w, |
| 949 | max_frame_height: h, |
| 950 | use_128x128_superblock: false, |
| 951 | enable_filter_intra: false, |
| 952 | enable_intra_edge_filter: false, |
| 953 | enable_order_hint: true, |
| 954 | order_hint_bits: 7, |
| 955 | enable_superres: false, |
| 956 | |
| 957 | |
| 958 | |
| 959 | |
| 960 | |
| 961 | enable_cdef: true, |
| 962 | enable_restoration: true, |
| 963 | |
| 964 | |
| 965 | |
| 966 | |
| 967 | |
| 968 | |
| 969 | seq_force_screen_content_tools: if seq_screen() { |
| 970 | ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS |
| 971 | } else { |
| 972 | 0 |
| 973 | }, |
| 974 | seq_force_integer_mv: 0, |
| 975 | color_config, |
| 976 | still_picture: false, |
| 977 | reduced_still_picture_header: false, |
| 978 | timing_info: None, |
| 979 | decoder_model_info: None, |
| 980 | initial_display_delay_present_flag: false, |
| 981 | operating_point: 0, |
| 982 | operating_point_idc: 0, |
| 983 | frame_id_numbers_present_flag: false, |
| 984 | delta_frame_id_length: 0, |
| 985 | additional_frame_id_length: 0, |
| 986 | enable_interintra_compound: false, |
| 987 | enable_masked_compound: false, |
| 988 | enable_warped_motion: false, |
| 989 | enable_dual_filter: false, |
| 990 | enable_jnt_comp: false, |
| 991 | enable_ref_frame_mvs: false, |
| 992 | film_grain_params_present: false, |
| 993 | }; |
| 994 | |
| 995 | |
| 996 | |
| 997 | |
| 998 | let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3)); |
| 999 | let header = FrameHeader { |
| 1000 | frame_type: FrameType::Key, |
| 1001 | frame_is_intra: true, |
| 1002 | show_frame: true, |
| 1003 | error_resilient_mode: true, |
| 1004 | |
| 1005 | |
| 1006 | disable_cdf_update: false, |
| 1007 | |
| 1008 | |
| 1009 | disable_frame_end_update_cdf: true, |
| 1010 | force_integer_mv: true, |
| 1011 | refresh_frame_flags: 0xFF, |
| 1012 | primary_ref_frame: PRIMARY_REF_NONE, |
| 1013 | frame_width: w, |
| 1014 | frame_height: h, |
| 1015 | upscaled_width: w, |
| 1016 | render_width: w, |
| 1017 | render_height: h, |
| 1018 | mi_cols, |
| 1019 | mi_rows, |
| 1020 | tile_info: TileInfo { |
| 1021 | uniform_spacing: true, |
| 1022 | cols: 1, |
| 1023 | rows: 1, |
| 1024 | mi_col_starts: vec![0, mi_cols], |
| 1025 | mi_row_starts: vec![0, mi_rows], |
| 1026 | tile_size_bytes: 1, |
| 1027 | ..TileInfo::default() |
| 1028 | }, |
| 1029 | quantization: QuantizationParams { |
| 1030 | base_q_idx, |
| 1031 | ..QuantizationParams::default() |
| 1032 | }, |
| 1033 | tx_mode: TxMode::Largest, |
| 1034 | |
| 1035 | |
| 1036 | |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | |
| 1042 | |
| 1043 | |
| 1044 | |
| 1045 | |
| 1046 | reduced_tx_set: true, |
| 1047 | ..FrameHeader::default() |
| 1048 | }; |
| 1049 | Ok((seq, header)) |
| 1050 | } |
| 1051 | |
| 1052 | |
| 1053 | |
| 1054 | |
| 1055 | pub const GOLDEN_SLOT: u8 = 1; |
| 1056 | |
| 1057 | |
| 1058 | |
| 1059 | |
| 1060 | |
| 1061 | |
| 1062 | |
| 1063 | |
| 1064 | pub fn inter_frame_headers( |
| 1065 | width: usize, |
| 1066 | height: usize, |
| 1067 | base_q_idx: u8, |
| 1068 | order_hint: u32, |
| 1069 | last_slot: u8, |
| 1070 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 1071 | inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot) |
| 1072 | } |
| 1073 | |
| 1074 | |
| 1075 | |
| 1076 | |
| 1077 | |
| 1078 | |
| 1079 | |
| 1080 | |
| 1081 | |
| 1082 | pub fn inter_frame_headers_slots( |
| 1083 | width: usize, |
| 1084 | height: usize, |
| 1085 | base_q_idx: u8, |
| 1086 | order_hint: u32, |
| 1087 | last_slot: u8, |
| 1088 | self_slot: u8, |
| 1089 | altref_slot: u8, |
| 1090 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 1091 | let (seq, key) = key_frame_headers(width, height, base_q_idx)?; |
| 1092 | let header = FrameHeader { |
| 1093 | frame_type: FrameType::Inter, |
| 1094 | frame_is_intra: false, |
| 1095 | show_frame: true, |
| 1096 | error_resilient_mode: false, |
| 1097 | disable_cdf_update: false, |
| 1098 | |
| 1099 | |
| 1100 | |
| 1101 | disable_frame_end_update_cdf: false, |
| 1102 | force_integer_mv: false, |
| 1103 | order_hint, |
| 1104 | primary_ref_frame: 0, |
| 1105 | refresh_frame_flags: 1 << self_slot, |
| 1106 | |
| 1107 | |
| 1108 | |
| 1109 | |
| 1110 | |
| 1111 | ref_frame_idx: { |
| 1112 | let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME]; |
| 1113 | idx[3] = GOLDEN_SLOT; |
| 1114 | idx[6] = altref_slot; |
| 1115 | idx |
| 1116 | }, |
| 1117 | allow_high_precision_mv: false, |
| 1118 | interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, |
| 1119 | is_motion_mode_switchable: false, |
| 1120 | use_ref_frame_mvs: false, |
| 1121 | |
| 1122 | |
| 1123 | |
| 1124 | |
| 1125 | |
| 1126 | |
| 1127 | |
| 1128 | |
| 1129 | |
| 1130 | |
| 1131 | |
| 1132 | reduced_tx_set: true, |
| 1133 | ..key |
| 1134 | }; |
| 1135 | Ok((seq, header)) |
| 1136 | } |
| 1137 | |
| 1138 | fn too_large() -> Error { |
| 1139 | Error::unsupported( |
| 1140 | "AV1 encode", |
| 1141 | "the picture is larger than a frame size can carry", |
| 1142 | ) |
| 1143 | } |
| 1144 | |
| 1145 | |
| 1146 | |
| 1147 | struct Plane<'a> { |
| 1148 | source: &'a [u8], |
| 1149 | reconstruction: Vec<u8>, |
| 1150 | width: usize, |
| 1151 | height: usize, |
| 1152 | |
| 1153 | |
| 1154 | |
| 1155 | |
| 1156 | |
| 1157 | |
| 1158 | |
| 1159 | |
| 1160 | |
| 1161 | |
| 1162 | true_width: usize, |
| 1163 | true_height: usize, |
| 1164 | |
| 1165 | |
| 1166 | |
| 1167 | |
| 1168 | |
| 1169 | |
| 1170 | tile_x0: usize, |
| 1171 | tile_y0: usize, |
| 1172 | tile_x1: usize, |
| 1173 | tile_y1: usize, |
| 1174 | } |
| 1175 | |
| 1176 | impl Plane<'_> { |
| 1177 | |
| 1178 | |
| 1179 | |
| 1180 | fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) { |
| 1181 | self.tile_x0 = x0; |
| 1182 | self.tile_y0 = y0; |
| 1183 | self.tile_x1 = x1.min(self.width); |
| 1184 | self.tile_y1 = y1.min(self.height); |
| 1185 | } |
| 1186 | |
| 1187 | |
| 1188 | |
| 1189 | |
| 1190 | |
| 1191 | |
| 1192 | |
| 1193 | |
| 1194 | |
| 1195 | fn edges( |
| 1196 | &self, |
| 1197 | x: usize, |
| 1198 | y: usize, |
| 1199 | side: usize, |
| 1200 | reach: Reach, |
| 1201 | ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) { |
| 1202 | |
| 1203 | |
| 1204 | |
| 1205 | |
| 1206 | |
| 1207 | |
| 1208 | |
| 1209 | |
| 1210 | |
| 1211 | |
| 1212 | |
| 1213 | |
| 1214 | |
| 1215 | |
| 1216 | let own_across = x + side.min(self.true_width.saturating_sub(x)); |
| 1217 | let across = if reach.above_right { |
| 1218 | own_across + side.min(self.true_width.saturating_sub(own_across)) |
| 1219 | } else { |
| 1220 | own_across |
| 1221 | } |
| 1222 | .min(self.width); |
| 1223 | let own_down = y + side.min(self.true_height.saturating_sub(y)); |
| 1224 | let down = if reach.below_left { |
| 1225 | own_down + side.min(self.true_height.saturating_sub(own_down)) |
| 1226 | } else { |
| 1227 | own_down |
| 1228 | } |
| 1229 | .min(self.height); |
| 1230 | |
| 1231 | |
| 1232 | |
| 1233 | |
| 1234 | |
| 1235 | |
| 1236 | |
| 1237 | let across = across.min(self.tile_x1); |
| 1238 | let down = down.min(self.tile_y1); |
| 1239 | let above = (y > self.tile_y0 && across > x) |
| 1240 | .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec()); |
| 1241 | let left = (x > self.tile_x0 && down > y).then(|| { |
| 1242 | (y..down) |
| 1243 | .map(|row| self.reconstruction[row * self.width + x - 1]) |
| 1244 | .collect::<Vec<_>>() |
| 1245 | }); |
| 1246 | let corner = (x > self.tile_x0 && y > self.tile_y0) |
| 1247 | .then(|| self.reconstruction[(y - 1) * self.width + x - 1]); |
| 1248 | (above, left, corner) |
| 1249 | } |
| 1250 | |
| 1251 | |
| 1252 | |
| 1253 | |
| 1254 | fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial { |
| 1255 | self.trial_typed(at, mode, base_q_idx, deadzone, TxType::DctDct, fctx) |
| 1256 | } |
| 1257 | |
| 1258 | |
| 1259 | |
| 1260 | |
| 1261 | |
| 1262 | |
| 1263 | #[allow(clippy::too_many_arguments)] |
| 1264 | fn trial_typed( |
| 1265 | &self, |
| 1266 | at: At, |
| 1267 | mode: u8, |
| 1268 | base_q_idx: u8, |
| 1269 | deadzone: f64, |
| 1270 | tx_type: TxType, |
| 1271 | fctx: &crate::decode::FrameCtx, |
| 1272 | ) -> Trial { |
| 1273 | let At { |
| 1274 | x, y, side, reach, .. |
| 1275 | } = at; |
| 1276 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 1277 | |
| 1278 | |
| 1279 | |
| 1280 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 1281 | let prediction = &mut prediction[..side * side]; |
| 1282 | intra_predict_u8( |
| 1283 | mode, |
| 1284 | 0, |
| 1285 | above.as_deref(), |
| 1286 | left.as_deref(), |
| 1287 | corner, |
| 1288 | side, |
| 1289 | side, |
| 1290 | false, |
| 1291 | false, |
| 1292 | prediction, fctx, |
| 1293 | ); |
| 1294 | |
| 1295 | let mut residual = [0i32; BLOCK * BLOCK]; |
| 1296 | let residual = &mut residual[..side * side]; |
| 1297 | for row in 0..side { |
| 1298 | for col in 0..side { |
| 1299 | residual[row * side + col] = |
| 1300 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 1301 | - i32::from(prediction[row * side + col]); |
| 1302 | } |
| 1303 | } |
| 1304 | #[cfg(test)] |
| 1305 | let t = std::time::Instant::now(); |
| 1306 | let levels = |
| 1307 | forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type); |
| 1308 | let coded = |
| 1309 | dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type); |
| 1310 | #[cfg(test)] |
| 1311 | stage_add(2, t.elapsed()); |
| 1312 | |
| 1313 | let mut reconstruction = vec![0u8; side * side]; |
| 1314 | let mut sse = 0.0; |
| 1315 | for row in 0..side { |
| 1316 | for col in 0..side { |
| 1317 | let i = row * side + col; |
| 1318 | let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; |
| 1319 | reconstruction[i] = sample; |
| 1320 | let error = f64::from( |
| 1321 | i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), |
| 1322 | ); |
| 1323 | sse += error * error; |
| 1324 | } |
| 1325 | } |
| 1326 | |
| 1327 | |
| 1328 | |
| 1329 | #[cfg(test)] |
| 1330 | let t = std::time::Instant::now(); |
| 1331 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 1332 | |
| 1333 | |
| 1334 | |
| 1335 | |
| 1336 | levels |
| 1337 | .iter() |
| 1338 | .filter(|&&level| level != 0) |
| 1339 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 1340 | .sum() |
| 1341 | } else { |
| 1342 | crate::tile::coeff_bits(&levels, at.set, crate::decode::q_ctx_of(base_q_idx)) |
| 1343 | }; |
| 1344 | #[cfg(test)] |
| 1345 | stage_add(3, t.elapsed()); |
| 1346 | Trial { |
| 1347 | levels, |
| 1348 | reconstruction, |
| 1349 | sse, |
| 1350 | bits, |
| 1351 | } |
| 1352 | } |
| 1353 | |
| 1354 | |
| 1355 | |
| 1356 | |
| 1357 | |
| 1358 | |
| 1359 | |
| 1360 | #[allow(clippy::too_many_arguments)] |
| 1361 | fn code_from_prediction( |
| 1362 | &self, |
| 1363 | x: usize, |
| 1364 | y: usize, |
| 1365 | side: usize, |
| 1366 | prediction: &[u8], |
| 1367 | skip: bool, |
| 1368 | base_q_idx: u8, |
| 1369 | deadzone: f64, |
| 1370 | set: TxbSet, |
| 1371 | ) -> Trial { |
| 1372 | if skip { |
| 1373 | let mut sse = 0.0; |
| 1374 | for row in 0..side { |
| 1375 | for col in 0..side { |
| 1376 | let error = f64::from( |
| 1377 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 1378 | - i32::from(prediction[row * side + col]), |
| 1379 | ); |
| 1380 | sse += error * error; |
| 1381 | } |
| 1382 | } |
| 1383 | return Trial { |
| 1384 | levels: vec![0i32; side * side], |
| 1385 | reconstruction: prediction.to_vec(), |
| 1386 | sse, |
| 1387 | bits: 0.0, |
| 1388 | }; |
| 1389 | } |
| 1390 | let mut residual = [0i32; BLOCK * BLOCK]; |
| 1391 | let residual = &mut residual[..side * side]; |
| 1392 | for row in 0..side { |
| 1393 | for col in 0..side { |
| 1394 | residual[row * side + col] = |
| 1395 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 1396 | - i32::from(prediction[row * side + col]); |
| 1397 | } |
| 1398 | } |
| 1399 | #[cfg(test)] |
| 1400 | let t = std::time::Instant::now(); |
| 1401 | let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone); |
| 1402 | let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); |
| 1403 | #[cfg(test)] |
| 1404 | stage_add(2, t.elapsed()); |
| 1405 | let mut reconstruction = vec![0u8; side * side]; |
| 1406 | let mut sse = 0.0; |
| 1407 | for row in 0..side { |
| 1408 | for col in 0..side { |
| 1409 | let i = row * side + col; |
| 1410 | let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; |
| 1411 | reconstruction[i] = sample; |
| 1412 | let error = f64::from( |
| 1413 | i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), |
| 1414 | ); |
| 1415 | sse += error * error; |
| 1416 | } |
| 1417 | } |
| 1418 | #[cfg(test)] |
| 1419 | let t = std::time::Instant::now(); |
| 1420 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 1421 | levels |
| 1422 | .iter() |
| 1423 | .filter(|&&level| level != 0) |
| 1424 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 1425 | .sum() |
| 1426 | } else { |
| 1427 | crate::tile::coeff_bits(&levels, set, crate::decode::q_ctx_of(base_q_idx)) |
| 1428 | }; |
| 1429 | #[cfg(test)] |
| 1430 | stage_add(3, t.elapsed()); |
| 1431 | Trial { |
| 1432 | levels, |
| 1433 | reconstruction, |
| 1434 | sse, |
| 1435 | bits, |
| 1436 | } |
| 1437 | } |
| 1438 | |
| 1439 | |
| 1440 | |
| 1441 | |
| 1442 | |
| 1443 | |
| 1444 | |
| 1445 | |
| 1446 | |
| 1447 | fn code_tx_depth( |
| 1448 | &mut self, |
| 1449 | at: At, |
| 1450 | mode: u8, |
| 1451 | depth: usize, |
| 1452 | search: &Search, fctx: &crate::decode::FrameCtx, |
| 1453 | ) -> (Vec<i32>, f64, f64) { |
| 1454 | let At { x, y, side, reach, .. } = at; |
| 1455 | let tx = side >> depth; |
| 1456 | let n = 1usize << depth; |
| 1457 | let set = match tx { |
| 1458 | 32 => TxbSet::Luma32, |
| 1459 | 16 => TxbSet::Luma16, |
| 1460 | 8 => TxbSet::Luma8, |
| 1461 | _ => TxbSet::Luma4, |
| 1462 | }; |
| 1463 | let mut levels = vec![0i32; side * side]; |
| 1464 | census_add(4, n * n); |
| 1465 | let (mut sse, mut bits) = (0.0, 0.0); |
| 1466 | for tu_row in 0..n { |
| 1467 | for tu_col in 0..n { |
| 1468 | let (col_off, row_off) = (tu_col * tx, tu_row * tx); |
| 1469 | let tu = At { |
| 1470 | x: x + col_off, |
| 1471 | y: y + row_off, |
| 1472 | side: tx, |
| 1473 | reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach), |
| 1474 | set, |
| 1475 | }; |
| 1476 | let trial = self.trial(tu, mode, search.base_q_idx, search.deadzone, fctx); |
| 1477 | sse += trial.sse; |
| 1478 | bits += trial.bits; |
| 1479 | self.commit(tu.x, tu.y, tx, &trial); |
| 1480 | for row in 0..tx { |
| 1481 | levels[(row_off + row) * side + col_off..][..tx] |
| 1482 | .copy_from_slice(&trial.levels[row * tx..][..tx]); |
| 1483 | } |
| 1484 | } |
| 1485 | } |
| 1486 | (levels, sse, bits) |
| 1487 | } |
| 1488 | |
| 1489 | |
| 1490 | fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { |
| 1491 | for row in 0..side { |
| 1492 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 1493 | .copy_from_slice(&trial.reconstruction[row * side..][..side]); |
| 1494 | } |
| 1495 | } |
| 1496 | |
| 1497 | |
| 1498 | |
| 1499 | |
| 1500 | |
| 1501 | fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 1502 | (y..y + side) |
| 1503 | .flat_map(|row| self.source[row * self.width + x..][..side].to_vec()) |
| 1504 | .collect() |
| 1505 | } |
| 1506 | |
| 1507 | |
| 1508 | |
| 1509 | fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 1510 | (y..y + side) |
| 1511 | .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec()) |
| 1512 | .collect() |
| 1513 | } |
| 1514 | |
| 1515 | |
| 1516 | fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) { |
| 1517 | for row in 0..side { |
| 1518 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 1519 | .copy_from_slice(&samples[row * side..][..side]); |
| 1520 | } |
| 1521 | } |
| 1522 | |
| 1523 | |
| 1524 | |
| 1525 | |
| 1526 | |
| 1527 | fn intra_scores( |
| 1528 | &self, |
| 1529 | at: At, |
| 1530 | modes: &[u8], |
| 1531 | mode_bits: &[f64; 13], |
| 1532 | lambda: f64, fctx: &crate::decode::FrameCtx, |
| 1533 | ) -> Vec<(f64, u8)> { |
| 1534 | let At { |
| 1535 | x, y, side, reach, .. |
| 1536 | } = at; |
| 1537 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 1538 | modes |
| 1539 | .iter() |
| 1540 | .map(|&mode| { |
| 1541 | let mut prediction = vec![0u8; side * side]; |
| 1542 | intra_predict_u8( |
| 1543 | mode, |
| 1544 | 0, |
| 1545 | above.as_deref(), |
| 1546 | left.as_deref(), |
| 1547 | corner, |
| 1548 | side, |
| 1549 | side, |
| 1550 | false, |
| 1551 | false, |
| 1552 | &mut prediction, fctx, |
| 1553 | ); |
| 1554 | let sad: f64 = (0..side * side) |
| 1555 | .map(|i| { |
| 1556 | let (row, col) = (i / side, i % side); |
| 1557 | f64::from( |
| 1558 | (i32::from(self.source[(y + row) * self.width + x + col]) |
| 1559 | - i32::from(prediction[i])) |
| 1560 | .abs(), |
| 1561 | ) |
| 1562 | }) |
| 1563 | .sum(); |
| 1564 | (sad + lambda * mode_bits[usize::from(mode)], mode) |
| 1565 | }) |
| 1566 | .collect() |
| 1567 | } |
| 1568 | |
| 1569 | |
| 1570 | |
| 1571 | |
| 1572 | |
| 1573 | |
| 1574 | |
| 1575 | |
| 1576 | |
| 1577 | |
| 1578 | |
| 1579 | fn search_block( |
| 1580 | &mut self, |
| 1581 | at: At, |
| 1582 | search: &Search, |
| 1583 | mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx, |
| 1584 | ) -> (Vec<Coeff>, u8, f64) { |
| 1585 | let At { |
| 1586 | x, y, side, reach, .. |
| 1587 | } = at; |
| 1588 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 1589 | |
| 1590 | |
| 1591 | |
| 1592 | |
| 1593 | let want_sad = search.top_k.is_some() || census_on(); |
| 1594 | let mut scored: Vec<(f64, u8, Vec<u8>)> = search |
| 1595 | .modes |
| 1596 | .iter() |
| 1597 | .map(|&mode| { |
| 1598 | let mut prediction = vec![0u8; side * side]; |
| 1599 | intra_predict_u8( |
| 1600 | mode, |
| 1601 | 0, |
| 1602 | above.as_deref(), |
| 1603 | left.as_deref(), |
| 1604 | corner, |
| 1605 | side, |
| 1606 | side, |
| 1607 | false, |
| 1608 | false, |
| 1609 | &mut prediction, fctx, |
| 1610 | ); |
| 1611 | let sad: f64 = if want_sad { |
| 1612 | (0..side * side) |
| 1613 | .map(|i| { |
| 1614 | let (row, col) = (i / side, i % side); |
| 1615 | f64::from( |
| 1616 | (i32::from(self.source[(y + row) * self.width + x + col]) |
| 1617 | - i32::from(prediction[i])) |
| 1618 | .abs(), |
| 1619 | ) |
| 1620 | }) |
| 1621 | .sum() |
| 1622 | } else { |
| 1623 | 0.0 |
| 1624 | }; |
| 1625 | ( |
| 1626 | sad + search.lambda * mode_bits[usize::from(mode)], |
| 1627 | mode, |
| 1628 | prediction, |
| 1629 | ) |
| 1630 | }) |
| 1631 | .collect(); |
| 1632 | if let Some(k) = search.top_k { |
| 1633 | if k < scored.len() { |
| 1634 | let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED); |
| 1635 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 1636 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 1637 | scored.truncate(if dc_entry.is_some() { |
| 1638 | k.saturating_sub(1) |
| 1639 | } else { |
| 1640 | k |
| 1641 | }); |
| 1642 | if let Some(dc_entry) = dc_entry { |
| 1643 | scored.push(dc_entry); |
| 1644 | } |
| 1645 | } |
| 1646 | } |
| 1647 | let ranking: Vec<(f64, u8)> = if census_on() { |
| 1648 | scored.iter().map(|&(score, mode, _)| (score, mode)).collect() |
| 1649 | } else { |
| 1650 | Vec::new() |
| 1651 | }; |
| 1652 | census_add(0, 1); |
| 1653 | census_add(1, scored.len()); |
| 1654 | let mut best: Option<(f64, u8, Trial)> = None; |
| 1655 | for (_, mode, prediction) in scored { |
| 1656 | let trial = self.code_from_prediction( |
| 1657 | x, |
| 1658 | y, |
| 1659 | side, |
| 1660 | &prediction, |
| 1661 | false, |
| 1662 | search.base_q_idx, |
| 1663 | search.deadzone, |
| 1664 | at.set, |
| 1665 | ); |
| 1666 | let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]); |
| 1667 | if best |
| 1668 | .as_ref() |
| 1669 | .is_none_or(|(best_cost, _, _)| cost < *best_cost) |
| 1670 | { |
| 1671 | best = Some((cost, mode, trial)); |
| 1672 | } |
| 1673 | } |
| 1674 | let (cost, mode, trial) = best.expect("the search offers at least one mode"); |
| 1675 | if census_on() { |
| 1676 | LUMA_RANK[sad_rank(&ranking, mode).min(12)] |
| 1677 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 1678 | } |
| 1679 | self.commit(x, y, side, &trial); |
| 1680 | (coeffs(&trial.levels, side), mode, cost) |
| 1681 | } |
| 1682 | } |
| 1683 | |
| 1684 | |
| 1685 | |
| 1686 | #[derive(Clone, Copy)] |
| 1687 | struct At { |
| 1688 | x: usize, |
| 1689 | y: usize, |
| 1690 | side: usize, |
| 1691 | reach: Reach, |
| 1692 | |
| 1693 | |
| 1694 | set: TxbSet, |
| 1695 | } |
| 1696 | |
| 1697 | |
| 1698 | |
| 1699 | |
| 1700 | |
| 1701 | |
| 1702 | |
| 1703 | |
| 1704 | |
| 1705 | |
| 1706 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1707 | pub(crate) struct Reach { |
| 1708 | pub(crate) above_right: bool, |
| 1709 | pub(crate) below_left: bool, |
| 1710 | } |
| 1711 | |
| 1712 | |
| 1713 | |
| 1714 | |
| 1715 | |
| 1716 | |
| 1717 | |
| 1718 | const HAS_TOP_RIGHT: [&[u8]; 4] = [ |
| 1719 | &[255, 85, 119, 85, 127, 85, 119, 85], |
| 1720 | &[95, 87], |
| 1721 | |
| 1722 | |
| 1723 | &[ |
| 1724 | 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85, |
| 1725 | 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, |
| 1726 | ], |
| 1727 | |
| 1728 | |
| 1729 | |
| 1730 | |
| 1731 | |
| 1732 | |
| 1733 | |
| 1734 | |
| 1735 | &[ |
| 1736 | 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, |
| 1737 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85, |
| 1738 | 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, |
| 1739 | 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, |
| 1740 | 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, |
| 1741 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, |
| 1742 | 119, 119, 119, 119, 85, 85, 85, 85, |
| 1743 | ], |
| 1744 | ]; |
| 1745 | |
| 1746 | |
| 1747 | |
| 1748 | const HAS_BOTTOM_LEFT: [&[u8]; 4] = [ |
| 1749 | &[84, 16, 84, 0, 84, 16, 84, 0], |
| 1750 | &[4, 4], |
| 1751 | |
| 1752 | &[ |
| 1753 | 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1, |
| 1754 | 84, 85, 16, 17, 84, 85, 0, 0, |
| 1755 | ], |
| 1756 | |
| 1757 | |
| 1758 | &[ |
| 1759 | 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, |
| 1760 | 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, |
| 1761 | 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, |
| 1762 | 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, |
| 1763 | 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, |
| 1764 | 85, 85, 0, 0, 0, 0, |
| 1765 | ], |
| 1766 | ]; |
| 1767 | |
| 1768 | |
| 1769 | |
| 1770 | |
| 1771 | |
| 1772 | |
| 1773 | |
| 1774 | |
| 1775 | |
| 1776 | |
| 1777 | const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [ |
| 1778 | |
| 1779 | &[255, 0, 119, 0, 127, 0, 119, 0], |
| 1780 | |
| 1781 | &[15, 7], |
| 1782 | |
| 1783 | &[ |
| 1784 | 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119, |
| 1785 | 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, |
| 1786 | ], |
| 1787 | ]; |
| 1788 | |
| 1789 | |
| 1790 | const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [ |
| 1791 | |
| 1792 | &[254, 16, 254, 0, 254, 16, 254, 0], |
| 1793 | |
| 1794 | &[14, 14], |
| 1795 | |
| 1796 | &[ |
| 1797 | 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254, |
| 1798 | 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, |
| 1799 | ], |
| 1800 | ]; |
| 1801 | |
| 1802 | thread_local! { |
| 1803 | |
| 1804 | |
| 1805 | |
| 1806 | |
| 1807 | |
| 1808 | |
| 1809 | static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 1810 | } |
| 1811 | |
| 1812 | |
| 1813 | pub(crate) struct VertAbGuard(bool); |
| 1814 | |
| 1815 | impl Drop for VertAbGuard { |
| 1816 | fn drop(&mut self) { |
| 1817 | VERT_AB_PARTITION.with(|c| c.set(self.0)); |
| 1818 | } |
| 1819 | } |
| 1820 | |
| 1821 | |
| 1822 | |
| 1823 | |
| 1824 | |
| 1825 | |
| 1826 | |
| 1827 | |
| 1828 | |
| 1829 | |
| 1830 | |
| 1831 | |
| 1832 | |
| 1833 | |
| 1834 | |
| 1835 | 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]; |
| 1836 | |
| 1837 | 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]; |
| 1838 | |
| 1839 | 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]; |
| 1840 | |
| 1841 | 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]; |
| 1842 | |
| 1843 | const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119]; |
| 1844 | |
| 1845 | const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0]; |
| 1846 | |
| 1847 | const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0]; |
| 1848 | |
| 1849 | const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0]; |
| 1850 | |
| 1851 | const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119]; |
| 1852 | |
| 1853 | const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0]; |
| 1854 | |
| 1855 | const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5]; |
| 1856 | |
| 1857 | const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14]; |
| 1858 | |
| 1859 | const HAS_TR_32X64: [u8; 1] = [127]; |
| 1860 | |
| 1861 | const HAS_BL_32X64: [u8; 1] = [0]; |
| 1862 | |
| 1863 | const HAS_TR_64X32: [u8; 1] = [19]; |
| 1864 | |
| 1865 | const HAS_BL_64X32: [u8; 1] = [34]; |
| 1866 | |
| 1867 | 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]; |
| 1868 | |
| 1869 | 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]; |
| 1870 | |
| 1871 | 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]; |
| 1872 | |
| 1873 | 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]; |
| 1874 | |
| 1875 | const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127]; |
| 1876 | |
| 1877 | const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0]; |
| 1878 | |
| 1879 | const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0]; |
| 1880 | |
| 1881 | const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14]; |
| 1882 | |
| 1883 | const HAS_TR_16X64: [u8; 2] = [255, 127]; |
| 1884 | |
| 1885 | const HAS_BL_16X64: [u8; 2] = [0, 0]; |
| 1886 | |
| 1887 | const HAS_TR_64X16: [u8; 2] = [3, 1]; |
| 1888 | |
| 1889 | const HAS_BL_64X16: [u8; 2] = [42, 42]; |
| 1890 | |
| 1891 | |
| 1892 | fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) { |
| 1893 | match (bw, bh) { |
| 1894 | (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8), |
| 1895 | (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4), |
| 1896 | (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16), |
| 1897 | (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8), |
| 1898 | (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32), |
| 1899 | (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16), |
| 1900 | (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64), |
| 1901 | (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32), |
| 1902 | (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16), |
| 1903 | (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4), |
| 1904 | (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32), |
| 1905 | (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8), |
| 1906 | (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64), |
| 1907 | (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16), |
| 1908 | _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"), |
| 1909 | } |
| 1910 | } |
| 1911 | |
| 1912 | impl Reach { |
| 1913 | |
| 1914 | |
| 1915 | |
| 1916 | |
| 1917 | |
| 1918 | |
| 1919 | |
| 1920 | |
| 1921 | |
| 1922 | |
| 1923 | |
| 1924 | |
| 1925 | |
| 1926 | |
| 1927 | pub(crate) fn of_tu( |
| 1928 | bw: usize, |
| 1929 | bh: usize, |
| 1930 | col_off: usize, |
| 1931 | row_off: usize, |
| 1932 | |
| 1933 | |
| 1934 | |
| 1935 | tx_w: usize, |
| 1936 | tx_h: usize, |
| 1937 | block: Self, |
| 1938 | ) -> Self { |
| 1939 | |
| 1940 | |
| 1941 | |
| 1942 | |
| 1943 | let wide = bw > 64; |
| 1944 | Self { |
| 1945 | above_right: if row_off > 0 { |
| 1946 | |
| 1947 | |
| 1948 | |
| 1949 | if wide { |
| 1950 | (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64 |
| 1951 | } else { |
| 1952 | col_off + tx_w < bw |
| 1953 | } |
| 1954 | } else if col_off + tx_w < bw { |
| 1955 | true |
| 1956 | } else { |
| 1957 | block.above_right |
| 1958 | }, |
| 1959 | below_left: if wide && col_off > 0 && col_off % 64 == 0 { |
| 1960 | |
| 1961 | |
| 1962 | |
| 1963 | (row_off % 64) + tx_h < bh.min(64) |
| 1964 | } else if col_off > 0 { |
| 1965 | false |
| 1966 | } else if row_off + tx_h < bh { |
| 1967 | true |
| 1968 | } else { |
| 1969 | block.below_left |
| 1970 | }, |
| 1971 | } |
| 1972 | } |
| 1973 | |
| 1974 | |
| 1975 | |
| 1976 | pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self { |
| 1977 | Self { |
| 1978 | above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx), |
| 1979 | below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx), |
| 1980 | } |
| 1981 | } |
| 1982 | |
| 1983 | |
| 1984 | |
| 1985 | |
| 1986 | |
| 1987 | |
| 1988 | pub(crate) fn of_rect( |
| 1989 | bw: usize, |
| 1990 | bh: usize, |
| 1991 | x: usize, |
| 1992 | y: usize, |
| 1993 | width: usize, |
| 1994 | height: usize, fctx: &crate::decode::FrameCtx, |
| 1995 | ) -> Self { |
| 1996 | Self { |
| 1997 | above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx), |
| 1998 | below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx), |
| 1999 | } |
| 2000 | } |
| 2001 | |
| 2002 | |
| 2003 | |
| 2004 | |
| 2005 | |
| 2006 | |
| 2007 | |
| 2008 | |
| 2009 | |
| 2010 | |
| 2011 | |
| 2012 | |
| 2013 | |
| 2014 | |
| 2015 | |
| 2016 | fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 2017 | let sb_mi: usize = reach_sb_px(fctx) / 4; |
| 2018 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 2019 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 2020 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 2021 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 2022 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 2023 | |
| 2024 | |
| 2025 | if blk_row == 0 { |
| 2026 | return true; |
| 2027 | } |
| 2028 | |
| 2029 | if ((blk_col + 1) << bw_log2) >= sb_mi { |
| 2030 | return false; |
| 2031 | } |
| 2032 | let table = rect_reach_tables(bw, bh).0; |
| 2033 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 2034 | } |
| 2035 | |
| 2036 | |
| 2037 | |
| 2038 | |
| 2039 | |
| 2040 | |
| 2041 | |
| 2042 | |
| 2043 | |
| 2044 | fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize { |
| 2045 | (blk_row << (5 - bw_log2)) + blk_col |
| 2046 | } |
| 2047 | |
| 2048 | |
| 2049 | fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 2050 | let sb_mi: usize = reach_sb_px(fctx) / 4; |
| 2051 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 2052 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 2053 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 2054 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 2055 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 2056 | |
| 2057 | |
| 2058 | if blk_col == 0 { |
| 2059 | return (blk_row << bh_log2) + (bh / 4) < sb_mi; |
| 2060 | } |
| 2061 | |
| 2062 | |
| 2063 | if ((blk_row + 1) << bh_log2) >= sb_mi { |
| 2064 | return false; |
| 2065 | } |
| 2066 | let table = rect_reach_tables(bw, bh).1; |
| 2067 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 2068 | } |
| 2069 | |
| 2070 | |
| 2071 | |
| 2072 | |
| 2073 | |
| 2074 | |
| 2075 | |
| 2076 | |
| 2077 | |
| 2078 | pub(crate) fn in_vert_ab() -> bool { |
| 2079 | VERT_AB_PARTITION.with(std::cell::Cell::get) |
| 2080 | } |
| 2081 | |
| 2082 | pub(crate) fn vert_ab_partition() -> VertAbGuard { |
| 2083 | VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true))) |
| 2084 | } |
| 2085 | |
| 2086 | |
| 2087 | |
| 2088 | pub(crate) fn none() -> Self { |
| 2089 | Self { |
| 2090 | above_right: false, |
| 2091 | below_left: false, |
| 2092 | } |
| 2093 | } |
| 2094 | |
| 2095 | |
| 2096 | |
| 2097 | |
| 2098 | |
| 2099 | fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 2100 | let (row, col, per_side) = Self::position(side, x, y, fctx); |
| 2101 | if row == 0 { |
| 2102 | return true; |
| 2103 | } |
| 2104 | if col + 1 == per_side { |
| 2105 | return false; |
| 2106 | } |
| 2107 | |
| 2108 | |
| 2109 | |
| 2110 | |
| 2111 | |
| 2112 | |
| 2113 | |
| 2114 | |
| 2115 | |
| 2116 | |
| 2117 | |
| 2118 | let table_row = Self::table(side); |
| 2119 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() { |
| 2120 | HAS_TOP_RIGHT_VERT[table_row] |
| 2121 | } else { |
| 2122 | HAS_TOP_RIGHT[table_row] |
| 2123 | }; |
| 2124 | Self::bit( |
| 2125 | table, |
| 2126 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 2127 | ) |
| 2128 | } |
| 2129 | |
| 2130 | |
| 2131 | |
| 2132 | |
| 2133 | |
| 2134 | fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool { |
| 2135 | let (row, col, per_side) = Self::position(side, x, y, fctx); |
| 2136 | if col == 0 { |
| 2137 | return row * side + side < reach_sb_px(fctx); |
| 2138 | } |
| 2139 | if row + 1 == per_side { |
| 2140 | return false; |
| 2141 | } |
| 2142 | |
| 2143 | |
| 2144 | |
| 2145 | |
| 2146 | |
| 2147 | |
| 2148 | |
| 2149 | |
| 2150 | |
| 2151 | |
| 2152 | |
| 2153 | let table_row = Self::table(side); |
| 2154 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() { |
| 2155 | HAS_BOTTOM_LEFT_VERT[table_row] |
| 2156 | } else { |
| 2157 | HAS_BOTTOM_LEFT[table_row] |
| 2158 | }; |
| 2159 | Self::bit( |
| 2160 | table, |
| 2161 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 2162 | ) |
| 2163 | } |
| 2164 | |
| 2165 | |
| 2166 | |
| 2167 | fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) { |
| 2168 | let sb = reach_sb_px(fctx); |
| 2169 | ((y % sb) / side, (x % sb) / side, sb / side) |
| 2170 | } |
| 2171 | |
| 2172 | |
| 2173 | |
| 2174 | |
| 2175 | |
| 2176 | |
| 2177 | |
| 2178 | |
| 2179 | |
| 2180 | fn table_stride(side: usize) -> usize { |
| 2181 | 128 / side |
| 2182 | } |
| 2183 | |
| 2184 | |
| 2185 | fn table(side: usize) -> usize { |
| 2186 | if side == BLOCK { |
| 2187 | 1 |
| 2188 | } else if side == 8 { |
| 2189 | 2 |
| 2190 | } else if side == 4 { |
| 2191 | 3 |
| 2192 | } else { |
| 2193 | 0 |
| 2194 | } |
| 2195 | } |
| 2196 | |
| 2197 | |
| 2198 | fn bit(table: &[u8], index: usize) -> bool { |
| 2199 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 2200 | } |
| 2201 | } |
| 2202 | |
| 2203 | |
| 2204 | pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { |
| 2205 | let low = if symbol == 0 { 0 } else { cdf[symbol - 1] }; |
| 2206 | let width = cdf[symbol] - low; |
| 2207 | |
| 2208 | |
| 2209 | |
| 2210 | |
| 2211 | |
| 2212 | |
| 2213 | static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new(); |
| 2214 | PRICES.get_or_init(|| { |
| 2215 | (0..=32768u32) |
| 2216 | .map(|w| -(f64::from(w) / 32768.0).log2()) |
| 2217 | .collect() |
| 2218 | })[usize::from(width)] |
| 2219 | } |
| 2220 | |
| 2221 | |
| 2222 | |
| 2223 | |
| 2224 | |
| 2225 | |
| 2226 | |
| 2227 | |
| 2228 | |
| 2229 | |
| 2230 | |
| 2231 | |
| 2232 | |
| 2233 | |
| 2234 | |
| 2235 | |
| 2236 | fn max_tx_depth(side: usize) -> usize { |
| 2237 | match side { |
| 2238 | 8 => 1, |
| 2239 | 16 | 32 => 2, |
| 2240 | _ => 0, |
| 2241 | } |
| 2242 | } |
| 2243 | |
| 2244 | |
| 2245 | |
| 2246 | |
| 2247 | |
| 2248 | |
| 2249 | fn tx_depth_bits(side: usize, depth: usize) -> f64 { |
| 2250 | match side { |
| 2251 | 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth), |
| 2252 | 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth), |
| 2253 | 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth), |
| 2254 | _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth), |
| 2255 | } |
| 2256 | } |
| 2257 | |
| 2258 | |
| 2259 | |
| 2260 | static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] = |
| 2261 | [const { std::sync::atomic::AtomicUsize::new(0) }; 3]; |
| 2262 | |
| 2263 | |
| 2264 | |
| 2265 | #[cfg(test)] |
| 2266 | pub(crate) fn take_tx_depth_hits() -> [usize; 3] { |
| 2267 | std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 2268 | } |
| 2269 | |
| 2270 | |
| 2271 | |
| 2272 | |
| 2273 | static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] = |
| 2274 | [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; |
| 2275 | |
| 2276 | |
| 2277 | |
| 2278 | |
| 2279 | |
| 2280 | |
| 2281 | static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] = |
| 2282 | [const { std::sync::atomic::AtomicUsize::new(0) }; 8]; |
| 2283 | |
| 2284 | |
| 2285 | #[cfg(test)] |
| 2286 | pub(crate) fn take_ref_frame_hits() -> [usize; 8] { |
| 2287 | std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 2288 | } |
| 2289 | |
| 2290 | |
| 2291 | #[cfg(test)] |
| 2292 | pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] { |
| 2293 | std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 2294 | } |
| 2295 | |
| 2296 | |
| 2297 | |
| 2298 | |
| 2299 | |
| 2300 | |
| 2301 | fn txfm_split_bits(side: usize, depth: usize) -> f64 { |
| 2302 | let max_tx = side.min(64); |
| 2303 | let ctx = |tx: usize| { |
| 2304 | crate::decode::txfm_partition_ctx_rect( |
| 2305 | crate::decode::TXFM_CTX_INIT, |
| 2306 | crate::decode::TXFM_CTX_INIT, |
| 2307 | side, |
| 2308 | tx, |
| 2309 | tx, |
| 2310 | ) |
| 2311 | }; |
| 2312 | if depth == 0 { |
| 2313 | return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0); |
| 2314 | } |
| 2315 | symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1) |
| 2316 | + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0) |
| 2317 | } |
| 2318 | |
| 2319 | |
| 2320 | |
| 2321 | |
| 2322 | |
| 2323 | |
| 2324 | |
| 2325 | |
| 2326 | |
| 2327 | |
| 2328 | |
| 2329 | |
| 2330 | |
| 2331 | |
| 2332 | |
| 2333 | #[allow(clippy::too_many_arguments)] |
| 2334 | fn commit_inter_luma( |
| 2335 | luma: &mut Plane, |
| 2336 | (x, y): (usize, usize), |
| 2337 | side: usize, |
| 2338 | mv: (i32, i32), |
| 2339 | reference: (&[u16], usize, usize, usize), |
| 2340 | search: &Search, |
| 2341 | flat: &Trial, |
| 2342 | skip: bool, fctx: &crate::decode::FrameCtx, |
| 2343 | ) -> (Vec<i32>, u8, f64) { |
| 2344 | let eligible = tx_select() |
| 2345 | && tx_select_inter() |
| 2346 | && !skip |
| 2347 | && side >= 16 |
| 2348 | && x + side <= luma.true_width |
| 2349 | && y + side <= luma.true_height; |
| 2350 | if !eligible { |
| 2351 | luma.commit(x, y, side, flat); |
| 2352 | return (flat.levels.clone(), 0, 0.0); |
| 2353 | } |
| 2354 | let tx = side / 2; |
| 2355 | let set = if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter }; |
| 2356 | let mut levels = vec![0i32; side * side]; |
| 2357 | let (mut sse, mut bits) = (0.0, 0.0); |
| 2358 | let mut units = Vec::with_capacity(4); |
| 2359 | for tu_row in 0..2 { |
| 2360 | for tu_col in 0..2 { |
| 2361 | let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx); |
| 2362 | let trial = mc_trial( |
| 2363 | luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2, |
| 2364 | reference.3, false, search.base_q_idx, search.deadzone, set, fctx, |
| 2365 | ); |
| 2366 | sse += trial.sse; |
| 2367 | bits += trial.bits; |
| 2368 | for row in 0..tx { |
| 2369 | levels[(tu_row * tx + row) * side + tu_col * tx..][..tx] |
| 2370 | .copy_from_slice(&trial.levels[row * tx..][..tx]); |
| 2371 | } |
| 2372 | units.push((tu_x, tu_y, trial)); |
| 2373 | } |
| 2374 | } |
| 2375 | let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1)); |
| 2376 | let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0)); |
| 2377 | if split_cost < flat_cost { |
| 2378 | for (tu_x, tu_y, trial) in &units { |
| 2379 | luma.commit(*tu_x, *tu_y, tx, trial); |
| 2380 | } |
| 2381 | INTER_TX_SPLIT_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2382 | return (levels, 1, split_cost - flat_cost); |
| 2383 | } |
| 2384 | INTER_TX_SPLIT_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2385 | luma.commit(x, y, side, flat); |
| 2386 | (flat.levels.clone(), 0, 0.0) |
| 2387 | } |
| 2388 | |
| 2389 | |
| 2390 | |
| 2391 | |
| 2392 | |
| 2393 | |
| 2394 | |
| 2395 | |
| 2396 | |
| 2397 | |
| 2398 | |
| 2399 | |
| 2400 | |
| 2401 | |
| 2402 | fn palette_max_colors() -> usize { |
| 2403 | static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new(); |
| 2404 | *N.get_or_init(|| { |
| 2405 | std::env::var("EC_AV1_PAL_MAXCOLORS") |
| 2406 | .ok() |
| 2407 | .and_then(|v| v.parse().ok()) |
| 2408 | .unwrap_or(128) |
| 2409 | }) |
| 2410 | } |
| 2411 | |
| 2412 | |
| 2413 | |
| 2414 | |
| 2415 | |
| 2416 | |
| 2417 | |
| 2418 | |
| 2419 | fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> { |
| 2420 | let mut histogram = [0u32; 256]; |
| 2421 | for &v in block { |
| 2422 | histogram[usize::from(v)] += 1; |
| 2423 | } |
| 2424 | let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect(); |
| 2425 | if present.len() < 2 { |
| 2426 | return Vec::new(); |
| 2427 | } |
| 2428 | let exact = |colors: &[u16]| -> crate::tile::PaletteY { |
| 2429 | let mut base = [0u16; 8]; |
| 2430 | base[..colors.len()].copy_from_slice(colors); |
| 2431 | let map = block |
| 2432 | .iter() |
| 2433 | .map(|&v| { |
| 2434 | colors |
| 2435 | .iter() |
| 2436 | .enumerate() |
| 2437 | .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs()) |
| 2438 | .map(|(i, _)| i as u8) |
| 2439 | .expect("a palette holds at least two colours") |
| 2440 | }) |
| 2441 | .collect(); |
| 2442 | crate::tile::PaletteY { size: colors.len() as u8, colors: base, map } |
| 2443 | }; |
| 2444 | if present.len() <= 8 { |
| 2445 | return vec![exact(&present)]; |
| 2446 | } |
| 2447 | if present.len() > palette_max_colors() { |
| 2448 | return Vec::new(); |
| 2449 | } |
| 2450 | let (lo, hi) = ( |
| 2451 | i32::from(present[0]), |
| 2452 | i32::from(present[present.len() - 1]), |
| 2453 | ); |
| 2454 | let mut out = Vec::with_capacity(2); |
| 2455 | for n in [8usize, 4] { |
| 2456 | |
| 2457 | |
| 2458 | let mut centres: Vec<f64> = (0..n) |
| 2459 | .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64) |
| 2460 | .collect(); |
| 2461 | for _ in 0..4 { |
| 2462 | let mut sums = vec![0f64; n]; |
| 2463 | let mut counts = vec![0u32; n]; |
| 2464 | for (v, &count) in histogram.iter().enumerate() { |
| 2465 | if count == 0 { |
| 2466 | continue; |
| 2467 | } |
| 2468 | let k = (0..n) |
| 2469 | .min_by(|&a, &b| { |
| 2470 | (centres[a] - v as f64) |
| 2471 | .abs() |
| 2472 | .total_cmp(&(centres[b] - v as f64).abs()) |
| 2473 | }) |
| 2474 | .expect("n >= 2"); |
| 2475 | sums[k] += (v as u32 * count) as f64; |
| 2476 | counts[k] += count; |
| 2477 | } |
| 2478 | for k in 0..n { |
| 2479 | if counts[k] > 0 { |
| 2480 | centres[k] = sums[k] / f64::from(counts[k]); |
| 2481 | } |
| 2482 | } |
| 2483 | } |
| 2484 | let mut colors: Vec<u16> = centres |
| 2485 | .iter() |
| 2486 | .map(|&c| c.round().clamp(0.0, 255.0) as u16) |
| 2487 | .collect(); |
| 2488 | colors.sort_unstable(); |
| 2489 | colors.dedup(); |
| 2490 | if colors.len() >= 2 { |
| 2491 | out.push(exact(&colors)); |
| 2492 | } |
| 2493 | } |
| 2494 | out |
| 2495 | } |
| 2496 | |
| 2497 | #[allow(clippy::too_many_arguments)] |
| 2498 | fn code_square( |
| 2499 | luma: &mut Plane, |
| 2500 | chroma: &mut [Plane; 2], |
| 2501 | (x, y): (usize, usize), |
| 2502 | side: usize, |
| 2503 | search: &Search, |
| 2504 | mode_bits: &[f64; 13], |
| 2505 | |
| 2506 | |
| 2507 | |
| 2508 | tx_select: bool, fctx: &crate::decode::FrameCtx, |
| 2509 | ) -> (BlockCoeffs, f64) { |
| 2510 | let (luma_set, chroma_set) = if side == BLOCK { |
| 2511 | (TxbSet::Luma32, TxbSet::Chroma16) |
| 2512 | } else if side == 8 { |
| 2513 | |
| 2514 | |
| 2515 | |
| 2516 | |
| 2517 | |
| 2518 | |
| 2519 | |
| 2520 | (TxbSet::Luma8, TxbSet::Chroma4) |
| 2521 | } else { |
| 2522 | (TxbSet::Luma16, TxbSet::Chroma8) |
| 2523 | }; |
| 2524 | let at = At { |
| 2525 | x, |
| 2526 | y, |
| 2527 | side, |
| 2528 | reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx), |
| 2529 | set: luma_set, |
| 2530 | }; |
| 2531 | let (mut luma_coeffs, mode, mut cost) = luma.search_block(at, search, mode_bits, fctx); |
| 2532 | |
| 2533 | |
| 2534 | |
| 2535 | let mut tx_depth = 0u8; |
| 2536 | if tx_select && max_tx_depth(side) > 0 { |
| 2537 | let mut best = ( |
| 2538 | cost + search.lambda * tx_depth_bits(side, 0), |
| 2539 | 0usize, |
| 2540 | luma.snapshot(x, y, side), |
| 2541 | luma_coeffs, |
| 2542 | ); |
| 2543 | for depth in 1..=max_tx_depth(side) { |
| 2544 | let (levels, sse, bits) = luma.code_tx_depth(at, mode, depth, search, fctx); |
| 2545 | let cost_d = sse |
| 2546 | + search.lambda |
| 2547 | * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth)); |
| 2548 | if cost_d < best.0 { |
| 2549 | best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side)); |
| 2550 | } |
| 2551 | } |
| 2552 | luma.restore(x, y, side, &best.2); |
| 2553 | cost = best.0; |
| 2554 | tx_depth = best.1 as u8; |
| 2555 | luma_coeffs = best.3; |
| 2556 | TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2557 | } |
| 2558 | |
| 2559 | |
| 2560 | |
| 2561 | |
| 2562 | |
| 2563 | let mut mode = mode; |
| 2564 | let mut palette = None; |
| 2565 | if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { |
| 2566 | let source: Vec<u8> = (y..y + side) |
| 2567 | .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec()) |
| 2568 | .collect(); |
| 2569 | let kept = luma.snapshot(x, y, side); |
| 2570 | for pal in palette_candidates(&source) { |
| 2571 | let n = usize::from(pal.size); |
| 2572 | let prediction: Vec<u8> = pal |
| 2573 | .map |
| 2574 | .iter() |
| 2575 | .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8) |
| 2576 | .collect(); |
| 2577 | let trial = luma.code_from_prediction( |
| 2578 | x, |
| 2579 | y, |
| 2580 | side, |
| 2581 | &prediction, |
| 2582 | false, |
| 2583 | search.base_q_idx, |
| 2584 | search.deadzone, |
| 2585 | luma_set, |
| 2586 | ); |
| 2587 | let cost_p = trial.sse |
| 2588 | + search.lambda |
| 2589 | * (trial.bits |
| 2590 | + mode_bits[DC_PRED as usize] |
| 2591 | + crate::tile::palette_bits(&pal, side) |
| 2592 | + if tx_select { tx_depth_bits(side, 0) } else { 0.0 }); |
| 2593 | if cost_p < cost { |
| 2594 | cost = cost_p; |
| 2595 | mode = DC_PRED as u8; |
| 2596 | tx_depth = 0; |
| 2597 | luma_coeffs = coeffs(&trial.levels, side); |
| 2598 | luma.commit(x, y, side, &trial); |
| 2599 | palette = Some(pal); |
| 2600 | } |
| 2601 | } |
| 2602 | if palette.is_none() { |
| 2603 | luma.restore(x, y, side, &kept); |
| 2604 | } |
| 2605 | } |
| 2606 | |
| 2607 | |
| 2608 | |
| 2609 | let ([u, v], uv_mode, chroma_cost, palette_uv) = |
| 2610 | search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx); |
| 2611 | cost += chroma_cost; |
| 2612 | ( |
| 2613 | BlockCoeffs { |
| 2614 | u, |
| 2615 | v, |
| 2616 | luma: luma_coeffs, |
| 2617 | mode, |
| 2618 | uv_mode, |
| 2619 | tx_depth, |
| 2620 | palette, |
| 2621 | palette_uv, |
| 2622 | ..BlockCoeffs::default() |
| 2623 | }, |
| 2624 | cost, |
| 2625 | ) |
| 2626 | } |
| 2627 | |
| 2628 | |
| 2629 | |
| 2630 | |
| 2631 | |
| 2632 | |
| 2633 | |
| 2634 | const CHROMA_MODES: [u8; 7] = [ |
| 2635 | DC_PRED, |
| 2636 | V_PRED, |
| 2637 | H_PRED, |
| 2638 | SMOOTH_PRED, |
| 2639 | SMOOTH_V_PRED, |
| 2640 | SMOOTH_H_PRED, |
| 2641 | PAETH_PRED, |
| 2642 | ]; |
| 2643 | |
| 2644 | |
| 2645 | #[cfg(test)] |
| 2646 | const UV_MODE_NAMES: [&str; 13] = [ |
| 2647 | "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", |
| 2648 | "SMOOTH_H", "PAETH", |
| 2649 | ]; |
| 2650 | |
| 2651 | |
| 2652 | |
| 2653 | |
| 2654 | static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] = |
| 2655 | [const { std::sync::atomic::AtomicUsize::new(0) }; 13]; |
| 2656 | |
| 2657 | |
| 2658 | |
| 2659 | #[cfg(test)] |
| 2660 | pub(crate) fn take_uv_mode_hits() -> [usize; 13] { |
| 2661 | std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed)) |
| 2662 | } |
| 2663 | |
| 2664 | |
| 2665 | |
| 2666 | |
| 2667 | |
| 2668 | |
| 2669 | |
| 2670 | |
| 2671 | |
| 2672 | |
| 2673 | |
| 2674 | #[allow(clippy::too_many_arguments)] |
| 2675 | |
| 2676 | |
| 2677 | |
| 2678 | |
| 2679 | |
| 2680 | |
| 2681 | |
| 2682 | |
| 2683 | |
| 2684 | |
| 2685 | fn chroma_top_k() -> Option<usize> { |
| 2686 | static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new(); |
| 2687 | *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() { |
| 2688 | Some(v) => v.parse::<usize>().ok().filter(|&k| k > 0), |
| 2689 | None => CHROMA_TOP_K, |
| 2690 | }) |
| 2691 | } |
| 2692 | |
| 2693 | |
| 2694 | |
| 2695 | |
| 2696 | |
| 2697 | |
| 2698 | |
| 2699 | |
| 2700 | |
| 2701 | const CHROMA_TOP_K: Option<usize> = None; |
| 2702 | |
| 2703 | fn search_chroma( |
| 2704 | chroma: &mut [Plane; 2], |
| 2705 | (x, y): (usize, usize), |
| 2706 | side: usize, |
| 2707 | set: TxbSet, |
| 2708 | search: &Search, |
| 2709 | luma_mode: u8, |
| 2710 | fctx: &crate::decode::FrameCtx, |
| 2711 | ) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) { |
| 2712 | let at = At { |
| 2713 | x: x / 2, |
| 2714 | y: y / 2, |
| 2715 | side: side / 2, |
| 2716 | reach: Reach::none(), |
| 2717 | set, |
| 2718 | }; |
| 2719 | |
| 2720 | |
| 2721 | |
| 2722 | |
| 2723 | |
| 2724 | let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> { |
| 2725 | let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); |
| 2726 | let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx); |
| 2727 | u.iter() |
| 2728 | .zip(v.iter()) |
| 2729 | .map(|(&(us, mode), &(vs, _))| (us + vs, mode)) |
| 2730 | .collect() |
| 2731 | }; |
| 2732 | let modes: Vec<u8> = match chroma_top_k() { |
| 2733 | Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k), |
| 2734 | _ => CHROMA_MODES.to_vec(), |
| 2735 | }; |
| 2736 | let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)]; |
| 2737 | let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED)); |
| 2738 | let ranking: Vec<(f64, u8)> = if census_on() { |
| 2739 | sad_scores(chroma) |
| 2740 | } else { |
| 2741 | Vec::new() |
| 2742 | }; |
| 2743 | census_add(2, 1); |
| 2744 | census_add(3, modes.len()); |
| 2745 | let mut best: Option<(f64, u8, Trial, Trial)> = None; |
| 2746 | for mode in modes { |
| 2747 | let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits; |
| 2748 | if (V_PRED..=D67_PRED).contains(&mode) { |
| 2749 | bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3); |
| 2750 | } |
| 2751 | let tx_type = crate::decode::default_intra_tx_type(mode); |
| 2752 | let u = chroma[0].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx); |
| 2753 | let v = chroma[1].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx); |
| 2754 | let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits); |
| 2755 | if best.as_ref().is_none_or(|(b, ..)| cost < *b) { |
| 2756 | best = Some((cost, mode, u, v)); |
| 2757 | } |
| 2758 | } |
| 2759 | let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty"); |
| 2760 | |
| 2761 | |
| 2762 | |
| 2763 | |
| 2764 | |
| 2765 | |
| 2766 | |
| 2767 | |
| 2768 | let mut palette_uv = None; |
| 2769 | if search.screen && crate::decode::palette_bsize_ctx(side).is_some() { |
| 2770 | debug_assert_eq!(crate::tile::palette_uv_side(side), at.side); |
| 2771 | let plane_source = |p: &Plane| -> Vec<u8> { |
| 2772 | (at.y..at.y + at.side) |
| 2773 | .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec()) |
| 2774 | .collect() |
| 2775 | }; |
| 2776 | let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1])); |
| 2777 | for pal in palette_candidates(&u_source) { |
| 2778 | let n = usize::from(pal.size); |
| 2779 | |
| 2780 | |
| 2781 | |
| 2782 | let mut sums = [0u32; 8]; |
| 2783 | let mut counts = [0u32; 8]; |
| 2784 | for (&i, &sample) in pal.map.iter().zip(v_source.iter()) { |
| 2785 | let k = usize::from(i).min(n - 1); |
| 2786 | sums[k] += u32::from(sample); |
| 2787 | counts[k] += 1; |
| 2788 | } |
| 2789 | let mut v_colors = [0u16; 8]; |
| 2790 | for k in 0..n { |
| 2791 | v_colors[k] = if counts[k] > 0 { |
| 2792 | ((sums[k] + counts[k] / 2) / counts[k]) as u16 |
| 2793 | } else { |
| 2794 | 0 |
| 2795 | }; |
| 2796 | } |
| 2797 | let candidate = crate::tile::PaletteUv { |
| 2798 | size: pal.size, |
| 2799 | u_colors: pal.colors, |
| 2800 | v_colors, |
| 2801 | map: pal.map, |
| 2802 | }; |
| 2803 | let predict = |colors: &[u16; 8]| -> Vec<u8> { |
| 2804 | candidate |
| 2805 | .map |
| 2806 | .iter() |
| 2807 | .map(|&i| colors[usize::from(i).min(n - 1)] as u8) |
| 2808 | .collect() |
| 2809 | }; |
| 2810 | let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors)); |
| 2811 | let u_trial = chroma[0].code_from_prediction( |
| 2812 | at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set, |
| 2813 | ); |
| 2814 | let v_trial = chroma[1].code_from_prediction( |
| 2815 | at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set, |
| 2816 | ); |
| 2817 | let cost_p = u_trial.sse |
| 2818 | + v_trial.sse |
| 2819 | + search.lambda |
| 2820 | * (u_trial.bits |
| 2821 | + v_trial.bits |
| 2822 | + crate::tile::palette_uv_bits(&candidate, side)); |
| 2823 | if cost_p < cost { |
| 2824 | cost = cost_p; |
| 2825 | mode = DC_PRED; |
| 2826 | u = u_trial; |
| 2827 | v = v_trial; |
| 2828 | palette_uv = Some(candidate); |
| 2829 | } |
| 2830 | } |
| 2831 | } |
| 2832 | if census_on() { |
| 2833 | CHROMA_RANK[sad_rank(&ranking, mode).min(6)] |
| 2834 | .fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2835 | } |
| 2836 | UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 2837 | chroma[0].commit(at.x, at.y, at.side, &u); |
| 2838 | chroma[1].commit(at.x, at.y, at.side, &v); |
| 2839 | ( |
| 2840 | [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)], |
| 2841 | mode, |
| 2842 | cost, |
| 2843 | palette_uv, |
| 2844 | ) |
| 2845 | } |
| 2846 | |
| 2847 | |
| 2848 | |
| 2849 | |
| 2850 | |
| 2851 | |
| 2852 | |
| 2853 | |
| 2854 | |
| 2855 | |
| 2856 | |
| 2857 | |
| 2858 | #[allow(clippy::too_many_arguments)] |
| 2859 | fn code_square_inter( |
| 2860 | luma: &mut Plane, |
| 2861 | chroma: &mut [Plane; 2], |
| 2862 | (x, y): (usize, usize), |
| 2863 | side: usize, |
| 2864 | search: &Search, |
| 2865 | mode_bits: &[f64; 13], |
| 2866 | reference: &Picture, |
| 2867 | stack: &MvStack, |
| 2868 | |
| 2869 | |
| 2870 | |
| 2871 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], |
| 2872 | fctx: &crate::decode::FrameCtx, |
| 2873 | ) -> (BlockCoeffs, f64) { |
| 2874 | let (intra_block, intra_cost) = |
| 2875 | code_square( |
| 2876 | luma, |
| 2877 | chroma, |
| 2878 | (x, y), |
| 2879 | side, |
| 2880 | search, |
| 2881 | mode_bits, |
| 2882 | tx_select() && tx_select_inter(), |
| 2883 | fctx, |
| 2884 | ); |
| 2885 | let luma_set = if side == 8 { |
| 2886 | TxbSet::Luma8Inter |
| 2887 | } else { |
| 2888 | TxbSet::Luma16Inter |
| 2889 | }; |
| 2890 | let chroma_set = if side == 8 { |
| 2891 | TxbSet::Chroma4 |
| 2892 | } else { |
| 2893 | TxbSet::Chroma8 |
| 2894 | }; |
| 2895 | |
| 2896 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 2897 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 2898 | let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 2899 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) |
| 2900 | + symbol_bits(&cdf::SINGLE_REF[0][3], 0); |
| 2901 | let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) |
| 2902 | + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) |
| 2903 | + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); |
| 2904 | |
| 2905 | let mv = stack.nearest_mv; |
| 2906 | let ref_luma = ( |
| 2907 | &reference.y, |
| 2908 | reference.width, |
| 2909 | luma.true_width, |
| 2910 | luma.true_height, |
| 2911 | ); |
| 2912 | let ref_u = ( |
| 2913 | &reference.u, |
| 2914 | reference.width / 2, |
| 2915 | chroma[0].true_width, |
| 2916 | chroma[0].true_height, |
| 2917 | ); |
| 2918 | let ref_v = ( |
| 2919 | &reference.v, |
| 2920 | reference.width / 2, |
| 2921 | chroma[1].true_width, |
| 2922 | chroma[1].true_height, |
| 2923 | ); |
| 2924 | let luma_trial = mc_trial( |
| 2925 | luma, |
| 2926 | x, |
| 2927 | y, |
| 2928 | side, |
| 2929 | mv, |
| 2930 | true, |
| 2931 | ref_luma.0, |
| 2932 | ref_luma.1, |
| 2933 | ref_luma.2, |
| 2934 | ref_luma.3, |
| 2935 | false, |
| 2936 | search.base_q_idx, |
| 2937 | search.deadzone, |
| 2938 | luma_set, fctx, |
| 2939 | ); |
| 2940 | let u = mc_trial( |
| 2941 | &chroma[0], |
| 2942 | x / 2, |
| 2943 | y / 2, |
| 2944 | side / 2, |
| 2945 | mv, |
| 2946 | false, |
| 2947 | ref_u.0, |
| 2948 | ref_u.1, |
| 2949 | ref_u.2, |
| 2950 | ref_u.3, |
| 2951 | false, |
| 2952 | search.base_q_idx, |
| 2953 | search.deadzone, |
| 2954 | chroma_set, fctx, |
| 2955 | ); |
| 2956 | let v = mc_trial( |
| 2957 | &chroma[1], |
| 2958 | x / 2, |
| 2959 | y / 2, |
| 2960 | side / 2, |
| 2961 | mv, |
| 2962 | false, |
| 2963 | ref_v.0, |
| 2964 | ref_v.1, |
| 2965 | ref_v.2, |
| 2966 | ref_v.3, |
| 2967 | false, |
| 2968 | search.base_q_idx, |
| 2969 | search.deadzone, |
| 2970 | chroma_set, fctx, |
| 2971 | ); |
| 2972 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 2973 | && u.levels.iter().all(|&l| l == 0) |
| 2974 | && v.levels.iter().all(|&l| l == 0); |
| 2975 | let inter_cost = luma_trial.sse |
| 2976 | + u.sse |
| 2977 | + v.sse |
| 2978 | + search.lambda |
| 2979 | * (skip_bits(skip) |
| 2980 | + intra_inter_bits(true) |
| 2981 | + single_ref_bits |
| 2982 | + mode_bits_inter |
| 2983 | + if skip { |
| 2984 | 0.0 |
| 2985 | } else { |
| 2986 | luma_trial.bits + u.bits + v.bits |
| 2987 | }); |
| 2988 | |
| 2989 | |
| 2990 | |
| 2991 | |
| 2992 | |
| 2993 | |
| 2994 | |
| 2995 | |
| 2996 | |
| 2997 | |
| 2998 | |
| 2999 | |
| 3000 | |
| 3001 | |
| 3002 | |
| 3003 | |
| 3004 | |
| 3005 | |
| 3006 | |
| 3007 | |
| 3008 | |
| 3009 | let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None); |
| 3010 | |
| 3011 | |
| 3012 | |
| 3013 | |
| 3014 | let mut searched_new: Option<(i32, i32)> = None; |
| 3015 | |
| 3016 | |
| 3017 | let mut searched_new_cost: Option<f64> = None; |
| 3018 | let source_block = luma.source_block(x, y, side); |
| 3019 | if leaf_new_mv() { |
| 3020 | let (seeds, seed_n) = mv_seeds(stack); |
| 3021 | let found = motion::search( |
| 3022 | ref_luma.0, |
| 3023 | ref_luma.1, |
| 3024 | ref_luma.2, |
| 3025 | ref_luma.3, |
| 3026 | &source_block, |
| 3027 | x, |
| 3028 | y, |
| 3029 | side, |
| 3030 | side, |
| 3031 | stack.pred_mv, |
| 3032 | &seeds[..seed_n], |
| 3033 | search.lambda, fctx, |
| 3034 | 1, |
| 3035 | ); |
| 3036 | let new_mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 3037 | searched_new_cost = Some(found.cost); |
| 3038 | if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) { |
| 3039 | searched_new = Some(new_mv); |
| 3040 | |
| 3041 | |
| 3042 | let (luma_new, u_new, v_new) = if new_mv == mv { |
| 3043 | (luma_trial.clone(), u.clone(), v.clone()) |
| 3044 | } else { |
| 3045 | ( |
| 3046 | mc_trial( |
| 3047 | luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2, |
| 3048 | ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx, |
| 3049 | ), |
| 3050 | mc_trial( |
| 3051 | &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1, |
| 3052 | ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set, |
| 3053 | fctx, |
| 3054 | ), |
| 3055 | mc_trial( |
| 3056 | &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1, |
| 3057 | ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set, |
| 3058 | fctx, |
| 3059 | ), |
| 3060 | ) |
| 3061 | }; |
| 3062 | let skip_new = luma_new.levels.iter().all(|&l| l == 0) |
| 3063 | && u_new.levels.iter().all(|&l| l == 0) |
| 3064 | && v_new.levels.iter().all(|&l| l == 0); |
| 3065 | let drl_bits = if stack.entries.len() > 1 { |
| 3066 | symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0) |
| 3067 | } else { |
| 3068 | 0.0 |
| 3069 | }; |
| 3070 | let cost_new = luma_new.sse |
| 3071 | + u_new.sse |
| 3072 | + v_new.sse |
| 3073 | + search.lambda |
| 3074 | * (skip_bits(skip_new) |
| 3075 | + intra_inter_bits(true) |
| 3076 | + single_ref_bits |
| 3077 | + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) |
| 3078 | + drl_bits |
| 3079 | + mv_bits |
| 3080 | + if skip_new { |
| 3081 | 0.0 |
| 3082 | } else { |
| 3083 | luma_new.bits + u_new.bits + v_new.bits |
| 3084 | }); |
| 3085 | if cost_new < best.0 { |
| 3086 | best = ( |
| 3087 | cost_new, |
| 3088 | Some(( |
| 3089 | luma_new, |
| 3090 | u_new, |
| 3091 | v_new, |
| 3092 | skip_new, |
| 3093 | InterInfo { |
| 3094 | ref1: None, |
| 3095 | mv1: (0, 0), |
| 3096 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3097 | mode: InterMode::NewMv, |
| 3098 | mv: new_mv, |
| 3099 | ref_mv_idx: 0, |
| 3100 | }, |
| 3101 | )), |
| 3102 | ); |
| 3103 | } |
| 3104 | } |
| 3105 | } |
| 3106 | |
| 3107 | |
| 3108 | |
| 3109 | |
| 3110 | |
| 3111 | |
| 3112 | |
| 3113 | |
| 3114 | for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) { |
| 3115 | let (ref1, g) = (*ref1, *g); |
| 3116 | let uni = |
| 3117 | (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1); |
| 3118 | let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1) |
| 3119 | + if uni { |
| 3120 | symbol_bits(&cdf::COMP_REF_TYPE[0], 1) |
| 3121 | + symbol_bits(&cdf::COMP_REF[0][0], 0) |
| 3122 | + symbol_bits(&cdf::COMP_REF[0][1], 0) |
| 3123 | + symbol_bits(&cdf::COMP_BWDREF[0][0], 1) |
| 3124 | } else { |
| 3125 | symbol_bits(&cdf::COMP_REF_TYPE[0], 0) |
| 3126 | + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0) |
| 3127 | + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1) |
| 3128 | + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1) |
| 3129 | }; |
| 3130 | let mode_ctx = |
| 3131 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 3132 | let mode_bits_of = |
| 3133 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 3134 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 3135 | ( |
| 3136 | cstack.nearest_mv, |
| 3137 | mode_bits_of(0), |
| 3138 | InterInfo { |
| 3139 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3140 | mode: InterMode::NearestNearestMv, |
| 3141 | mv: cstack.nearest_mv.0, |
| 3142 | mv1: cstack.nearest_mv.1, |
| 3143 | ref1: Some(ref1), |
| 3144 | ref_mv_idx: 0, |
| 3145 | }, |
| 3146 | ), |
| 3147 | ( |
| 3148 | ((0, 0), (0, 0)), |
| 3149 | mode_bits_of(6), |
| 3150 | InterInfo { |
| 3151 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3152 | mode: InterMode::GlobalGlobalMv, |
| 3153 | mv: (0, 0), |
| 3154 | mv1: (0, 0), |
| 3155 | ref1: Some(ref1), |
| 3156 | ref_mv_idx: 0, |
| 3157 | }, |
| 3158 | ), |
| 3159 | ]; |
| 3160 | |
| 3161 | |
| 3162 | |
| 3163 | |
| 3164 | |
| 3165 | let cbase = cstack |
| 3166 | .entries |
| 3167 | .first() |
| 3168 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 3169 | |
| 3170 | |
| 3171 | |
| 3172 | |
| 3173 | |
| 3174 | |
| 3175 | |
| 3176 | |
| 3177 | let margin = leaf_second_new_margin(); |
| 3178 | let mut second_new: Option<(i32, i32)> = None; |
| 3179 | if leaf_second_new_mv() { |
| 3180 | let skip = margin > 0.0 |
| 3181 | && searched_new_cost.is_some_and(|last| { |
| 3182 | motion::cost_at( |
| 3183 | &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, |
| 3184 | side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx, |
| 3185 | ) * margin |
| 3186 | <= last |
| 3187 | }); |
| 3188 | if !skip { |
| 3189 | let mut seeds = [(0, 0); 4]; |
| 3190 | let mut seed_n = 1; |
| 3191 | for e in cstack.entries.iter().take(3) { |
| 3192 | seeds[seed_n] = e.mv1; |
| 3193 | seed_n += 1; |
| 3194 | } |
| 3195 | let found = motion::search( |
| 3196 | &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side, |
| 3197 | side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1), |
| 3198 | ); |
| 3199 | second_new = Some(round_to_valid_mv(found.mv, cbase.1)); |
| 3200 | } |
| 3201 | } |
| 3202 | if let Some(new_mv) = searched_new { |
| 3203 | if let Some(b0) = mv_residual_bits(new_mv, cbase.0) { |
| 3204 | ccands.push(( |
| 3205 | (new_mv, cstack.nearest_mv.1), |
| 3206 | mode_bits_of(3) + b0, |
| 3207 | InterInfo { |
| 3208 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3209 | mode: InterMode::NewNearestMv, |
| 3210 | mv: new_mv, |
| 3211 | mv1: cstack.nearest_mv.1, |
| 3212 | ref1: Some(ref1), |
| 3213 | ref_mv_idx: 0, |
| 3214 | }, |
| 3215 | )); |
| 3216 | } |
| 3217 | } |
| 3218 | |
| 3219 | |
| 3220 | if let Some(mv1) = second_new { |
| 3221 | if let Some(b1) = mv_residual_bits(mv1, cbase.1) { |
| 3222 | ccands.push(( |
| 3223 | (cstack.nearest_mv.0, mv1), |
| 3224 | mode_bits_of(2) + b1, |
| 3225 | InterInfo { |
| 3226 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3227 | mode: InterMode::NearestNewMv, |
| 3228 | mv: cstack.nearest_mv.0, |
| 3229 | mv1, |
| 3230 | ref1: Some(ref1), |
| 3231 | ref_mv_idx: 0, |
| 3232 | }, |
| 3233 | )); |
| 3234 | if let Some((new_mv, b0)) = |
| 3235 | searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b))) |
| 3236 | { |
| 3237 | ccands.push(( |
| 3238 | (new_mv, mv1), |
| 3239 | mode_bits_of(7) + b0 + b1, |
| 3240 | InterInfo { |
| 3241 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3242 | mode: InterMode::NewNewMv, |
| 3243 | mv: new_mv, |
| 3244 | mv1, |
| 3245 | ref1: Some(ref1), |
| 3246 | ref_mv_idx: 0, |
| 3247 | }, |
| 3248 | )); |
| 3249 | } |
| 3250 | } |
| 3251 | } |
| 3252 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 3253 | ccands.dedup_by_key(|c| c.0); |
| 3254 | let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); |
| 3255 | let g_u = ( |
| 3256 | g.u.as_slice(), |
| 3257 | g.width / 2, |
| 3258 | chroma[0].true_width, |
| 3259 | chroma[0].true_height, |
| 3260 | ); |
| 3261 | let g_v = ( |
| 3262 | g.v.as_slice(), |
| 3263 | g.width / 2, |
| 3264 | chroma[1].true_width, |
| 3265 | chroma[1].true_height, |
| 3266 | ); |
| 3267 | for (mvs, bits, info) in ccands { |
| 3268 | let luma_c = mc_trial_compound( |
| 3269 | luma, x, y, side, mvs, true, |
| 3270 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, |
| 3271 | search.base_q_idx, search.deadzone, luma_set, fctx, |
| 3272 | ); |
| 3273 | let u_c = mc_trial_compound( |
| 3274 | &chroma[0], x / 2, y / 2, side / 2, mvs, false, |
| 3275 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, |
| 3276 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 3277 | ); |
| 3278 | let v_c = mc_trial_compound( |
| 3279 | &chroma[1], x / 2, y / 2, side / 2, mvs, false, |
| 3280 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, |
| 3281 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 3282 | ); |
| 3283 | let skip_c = luma_c.levels.iter().all(|&l| l == 0) |
| 3284 | && u_c.levels.iter().all(|&l| l == 0) |
| 3285 | && v_c.levels.iter().all(|&l| l == 0); |
| 3286 | let cost_c = luma_c.sse |
| 3287 | + u_c.sse |
| 3288 | + v_c.sse |
| 3289 | + search.lambda |
| 3290 | * (skip_bits(skip_c) |
| 3291 | + intra_inter_bits(true) |
| 3292 | + bits |
| 3293 | + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits }); |
| 3294 | if cost_c < best.0 { |
| 3295 | best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info))); |
| 3296 | } |
| 3297 | } |
| 3298 | } |
| 3299 | |
| 3300 | if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best { |
| 3301 | if cost < intra_cost { |
| 3302 | |
| 3303 | |
| 3304 | |
| 3305 | |
| 3306 | |
| 3307 | |
| 3308 | |
| 3309 | |
| 3310 | |
| 3311 | |
| 3312 | |
| 3313 | |
| 3314 | |
| 3315 | let (levels, tx_depth, dcost) = if info.ref1.is_some() { |
| 3316 | luma.commit(x, y, side, &luma_new); |
| 3317 | (luma_new.levels.clone(), 0, 0.0) |
| 3318 | } else { |
| 3319 | commit_inter_luma( |
| 3320 | luma, (x, y), side, info.mv, |
| 3321 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), |
| 3322 | search, &luma_new, skip_new, fctx, |
| 3323 | ) |
| 3324 | }; |
| 3325 | chroma[0].commit(x / 2, y / 2, side / 2, &u_new); |
| 3326 | chroma[1].commit(x / 2, y / 2, side / 2, &v_new); |
| 3327 | return ( |
| 3328 | BlockCoeffs { |
| 3329 | luma: coeffs(&levels, side), |
| 3330 | u: coeffs(&u_new.levels, side / 2), |
| 3331 | v: coeffs(&v_new.levels, side / 2), |
| 3332 | mode: DC_PRED as u8, |
| 3333 | uv_mode: DC_PRED, |
| 3334 | skip: skip_new, |
| 3335 | eight: None, |
| 3336 | palette: None, |
| 3337 | palette_uv: None, |
| 3338 | tx_depth, |
| 3339 | inter: Some(info), |
| 3340 | }, |
| 3341 | cost + dcost, |
| 3342 | ); |
| 3343 | } |
| 3344 | } |
| 3345 | |
| 3346 | census_add(8, 1); |
| 3347 | if skip { |
| 3348 | census_add(10, 1); |
| 3349 | } |
| 3350 | if inter_cost >= intra_cost { |
| 3351 | census_add(9, 1); |
| 3352 | } |
| 3353 | if inter_cost < intra_cost { |
| 3354 | let (levels, tx_depth, dcost) = commit_inter_luma( |
| 3355 | luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, fctx, |
| 3356 | ); |
| 3357 | chroma[0].commit(x / 2, y / 2, side / 2, &u); |
| 3358 | chroma[1].commit(x / 2, y / 2, side / 2, &v); |
| 3359 | (BlockCoeffs { |
| 3360 | luma: coeffs(&levels, side), |
| 3361 | u: coeffs(&u.levels, side / 2), |
| 3362 | v: coeffs(&v.levels, side / 2), |
| 3363 | mode: DC_PRED as u8, |
| 3364 | uv_mode: DC_PRED, |
| 3365 | skip, |
| 3366 | eight: None, |
| 3367 | palette: None, |
| 3368 | palette_uv: None, |
| 3369 | tx_depth, |
| 3370 | inter: Some(InterInfo { |
| 3371 | ref1: None, |
| 3372 | mv1: (0, 0), |
| 3373 | ref_frame: crate::mvstack::LAST_FRAME, |
| 3374 | mode: InterMode::NearestMv, |
| 3375 | mv, |
| 3376 | ref_mv_idx: 0, |
| 3377 | }), |
| 3378 | }, inter_cost + dcost) |
| 3379 | } else { |
| 3380 | (intra_block, intra_cost) |
| 3381 | } |
| 3382 | } |
| 3383 | |
| 3384 | |
| 3385 | |
| 3386 | |
| 3387 | |
| 3388 | fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: Option<InterInfo>) { |
| 3389 | let info = match inter { |
| 3390 | Some(info) => MiInfo { |
| 3391 | is_inter: true, |
| 3392 | ref_frame: info.ref_frame, |
| 3393 | |
| 3394 | |
| 3395 | |
| 3396 | |
| 3397 | |
| 3398 | |
| 3399 | ref_frame1: info.ref1.unwrap_or(NO_REF1), |
| 3400 | mv1: mv16(info.mv1), |
| 3401 | mv: mv16(info.mv), |
| 3402 | |
| 3403 | |
| 3404 | is_new_mv: matches!( |
| 3405 | info.mode, |
| 3406 | InterMode::NewMv |
| 3407 | | InterMode::NewNewMv |
| 3408 | | InterMode::NearestNewMv |
| 3409 | | InterMode::NewNearestMv |
| 3410 | ), |
| 3411 | size, |
| 3412 | size_h: size, |
| 3413 | is_global_mv0: false, |
| 3414 | is_global_mv1: false, |
| 3415 | }, |
| 3416 | None => MiInfo { |
| 3417 | is_inter: false, |
| 3418 | ref_frame: -1, |
| 3419 | ref_frame1: NO_REF1, |
| 3420 | mv1: (0, 0), |
| 3421 | mv: (0, 0), |
| 3422 | is_new_mv: false, |
| 3423 | size, |
| 3424 | size_h: size, |
| 3425 | is_global_mv0: false, |
| 3426 | is_global_mv1: false, |
| 3427 | }, |
| 3428 | }; |
| 3429 | for dr in 0..usize::from(size) { |
| 3430 | for dc in 0..usize::from(size) { |
| 3431 | grid.set(mi_row + dr, mi_col + dc, info); |
| 3432 | } |
| 3433 | } |
| 3434 | } |
| 3435 | |
| 3436 | |
| 3437 | |
| 3438 | fn snapshot( |
| 3439 | luma: &Plane, |
| 3440 | chroma: &[Plane; 2], |
| 3441 | (x, y): (usize, usize), |
| 3442 | side: usize, |
| 3443 | ) -> [Vec<u8>; 3] { |
| 3444 | [ |
| 3445 | luma.snapshot(x, y, side), |
| 3446 | chroma[0].snapshot(x / 2, y / 2, side / 2), |
| 3447 | chroma[1].snapshot(x / 2, y / 2, side / 2), |
| 3448 | ] |
| 3449 | } |
| 3450 | |
| 3451 | |
| 3452 | fn restore( |
| 3453 | luma: &mut Plane, |
| 3454 | chroma: &mut [Plane; 2], |
| 3455 | (x, y): (usize, usize), |
| 3456 | side: usize, |
| 3457 | saved: &[Vec<u8>; 3], |
| 3458 | ) { |
| 3459 | luma.restore(x, y, side, &saved[0]); |
| 3460 | chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]); |
| 3461 | chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]); |
| 3462 | } |
| 3463 | |
| 3464 | |
| 3465 | |
| 3466 | |
| 3467 | |
| 3468 | |
| 3469 | fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> { |
| 3470 | let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED); |
| 3471 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 3472 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 3473 | scored.truncate(if dc_entry.is_some() { |
| 3474 | top_k.saturating_sub(1) |
| 3475 | } else { |
| 3476 | top_k |
| 3477 | }); |
| 3478 | if let Some(dc_entry) = dc_entry { |
| 3479 | scored.push(dc_entry); |
| 3480 | } |
| 3481 | let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect(); |
| 3482 | modes.iter().copied().filter(|m| keep.contains(m)).collect() |
| 3483 | } |
| 3484 | |
| 3485 | fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { |
| 3486 | let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]] |
| 3487 | [INTRA_MODE_CTX[usize::from(left_mode)]]; |
| 3488 | std::array::from_fn(|mode| { |
| 3489 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 3490 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 3491 | } else { |
| 3492 | 0.0 |
| 3493 | }; |
| 3494 | symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 3495 | }) |
| 3496 | } |
| 3497 | |
| 3498 | |
| 3499 | struct Search<'a> { |
| 3500 | |
| 3501 | |
| 3502 | screen: bool, |
| 3503 | base_q_idx: u8, |
| 3504 | deadzone: f64, |
| 3505 | lambda: f64, |
| 3506 | modes: &'a [u8], |
| 3507 | |
| 3508 | |
| 3509 | |
| 3510 | |
| 3511 | |
| 3512 | |
| 3513 | top_k: Option<usize>, |
| 3514 | } |
| 3515 | |
| 3516 | |
| 3517 | |
| 3518 | |
| 3519 | fn prune_top_k() -> Option<usize> { |
| 3520 | #[cfg(test)] |
| 3521 | { |
| 3522 | if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) { |
| 3523 | return k; |
| 3524 | } |
| 3525 | } |
| 3526 | let swept = std::env::var("EC_AV1_PRUNE_K") |
| 3527 | .ok() |
| 3528 | .and_then(|v| v.parse::<usize>().ok()); |
| 3529 | match swept { |
| 3530 | Some(k) if cfg!(test) => Some(k), |
| 3531 | _ => PRUNE_TOP_K, |
| 3532 | } |
| 3533 | } |
| 3534 | |
| 3535 | |
| 3536 | |
| 3537 | |
| 3538 | #[cfg(test)] |
| 3539 | thread_local! { |
| 3540 | static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> = |
| 3541 | const { std::cell::Cell::new(None) }; |
| 3542 | } |
| 3543 | |
| 3544 | #[cfg(test)] |
| 3545 | fn set_test_top_k_override(value: Option<usize>) { |
| 3546 | TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value))); |
| 3547 | } |
| 3548 | |
| 3549 | |
| 3550 | |
| 3551 | const PRUNE_TOP_K: Option<usize> = None; |
| 3552 | |
| 3553 | |
| 3554 | |
| 3555 | |
| 3556 | |
| 3557 | |
| 3558 | fn prune_top_k_inter() -> Option<usize> { |
| 3559 | #[cfg(test)] |
| 3560 | { |
| 3561 | if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) { |
| 3562 | return k; |
| 3563 | } |
| 3564 | } |
| 3565 | let swept = std::env::var("EC_AV1_PRUNE_K_INTER") |
| 3566 | .ok() |
| 3567 | .and_then(|v| v.parse::<usize>().ok()); |
| 3568 | match swept { |
| 3569 | Some(k) if cfg!(test) => Some(k), |
| 3570 | _ => INTER_PRUNE_TOP_K, |
| 3571 | } |
| 3572 | } |
| 3573 | |
| 3574 | |
| 3575 | |
| 3576 | #[cfg(test)] |
| 3577 | thread_local! { |
| 3578 | static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> = |
| 3579 | const { std::cell::Cell::new(None) }; |
| 3580 | } |
| 3581 | |
| 3582 | #[cfg(test)] |
| 3583 | fn set_test_top_k_override_inter(value: Option<usize>) { |
| 3584 | TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value))); |
| 3585 | } |
| 3586 | |
| 3587 | |
| 3588 | |
| 3589 | |
| 3590 | |
| 3591 | |
| 3592 | |
| 3593 | |
| 3594 | const INTER_PRUNE_TOP_K: Option<usize> = Some(3); |
| 3595 | |
| 3596 | |
| 3597 | |
| 3598 | |
| 3599 | |
| 3600 | |
| 3601 | |
| 3602 | |
| 3603 | |
| 3604 | #[cfg(test)] |
| 3605 | thread_local! { |
| 3606 | static STAGE_NS: [std::cell::Cell<u64>; 4] = [ |
| 3607 | std::cell::Cell::new(0), |
| 3608 | std::cell::Cell::new(0), |
| 3609 | std::cell::Cell::new(0), |
| 3610 | std::cell::Cell::new(0), |
| 3611 | ]; |
| 3612 | } |
| 3613 | |
| 3614 | #[cfg(test)] |
| 3615 | pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { |
| 3616 | STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); |
| 3617 | } |
| 3618 | |
| 3619 | #[cfg(test)] |
| 3620 | fn stage_reset() { |
| 3621 | STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0))); |
| 3622 | } |
| 3623 | |
| 3624 | #[cfg(test)] |
| 3625 | fn stage_read() -> [std::time::Duration; 4] { |
| 3626 | STAGE_NS.with(|c| { |
| 3627 | c.each_ref() |
| 3628 | .map(|cell| std::time::Duration::from_nanos(cell.get())) |
| 3629 | }) |
| 3630 | } |
| 3631 | |
| 3632 | |
| 3633 | #[derive(Clone)] |
| 3634 | struct Trial { |
| 3635 | levels: Vec<i32>, |
| 3636 | reconstruction: Vec<u8>, |
| 3637 | sse: f64, |
| 3638 | bits: f64, |
| 3639 | } |
| 3640 | |
| 3641 | |
| 3642 | fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> { |
| 3643 | levels |
| 3644 | .iter() |
| 3645 | .enumerate() |
| 3646 | .filter(|&(_, &level)| level != 0) |
| 3647 | .map(|(i, &level)| Coeff { |
| 3648 | row: (i / side) as u8, |
| 3649 | col: (i % side) as u8, |
| 3650 | level, |
| 3651 | }) |
| 3652 | .collect() |
| 3653 | } |
| 3654 | |
| 3655 | thread_local! { |
| 3656 | |
| 3657 | |
| 3658 | |
| 3659 | |
| 3660 | |
| 3661 | |
| 3662 | static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) }; |
| 3663 | } |
| 3664 | |
| 3665 | |
| 3666 | pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) { |
| 3667 | TILE_LOG2.with(|c| c.set((cols_log2, rows_log2))); |
| 3668 | } |
| 3669 | |
| 3670 | fn armed_tiles() -> (u32, u32) { |
| 3671 | let armed = TILE_LOG2.with(std::cell::Cell::get); |
| 3672 | if armed != (0, 0) { |
| 3673 | return armed; |
| 3674 | } |
| 3675 | |
| 3676 | |
| 3677 | |
| 3678 | |
| 3679 | match std::env::var("EC_AV1_TILES").ok() { |
| 3680 | Some(v) if cfg!(test) => { |
| 3681 | let mut f = v.split(':'); |
| 3682 | let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0); |
| 3683 | let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0); |
| 3684 | (cols, rows) |
| 3685 | } |
| 3686 | _ => armed, |
| 3687 | } |
| 3688 | } |
| 3689 | |
| 3690 | |
| 3691 | |
| 3692 | |
| 3693 | |
| 3694 | |
| 3695 | |
| 3696 | |
| 3697 | fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)> |
| 3698 | where |
| 3699 | F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send, |
| 3700 | { |
| 3701 | let _t = crate::par::timer(crate::par::S_TILE_WRITE); |
| 3702 | type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>; |
| 3703 | let threads = crate::par::tile_threads().min(tiles); |
| 3704 | let mut slots: Vec<Slot> = Vec::new(); |
| 3705 | if threads <= 1 { |
| 3706 | for index in 0..tiles { |
| 3707 | slots.push(Some(code(index))); |
| 3708 | } |
| 3709 | } else { |
| 3710 | let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect()); |
| 3711 | { |
| 3712 | let batch = crate::par::Batch::new("ec-av1-tile"); |
| 3713 | for (from, to) in crate::par::bands(tiles, threads) { |
| 3714 | let done = &done; |
| 3715 | let code = &code; |
| 3716 | batch.submit(move || { |
| 3717 | for index in from..to { |
| 3718 | let coded = code(index); |
| 3719 | done.lock().expect("tile slots")[index] = Some(coded); |
| 3720 | } |
| 3721 | }); |
| 3722 | } |
| 3723 | } |
| 3724 | slots = done.into_inner().expect("tile slots"); |
| 3725 | } |
| 3726 | let mut out = Vec::with_capacity(tiles); |
| 3727 | let mut stored = None; |
| 3728 | for (index, slot) in slots.into_iter().enumerate() { |
| 3729 | let (bytes, cdfs) = slot.expect("every tile was coded")?; |
| 3730 | if index == store { |
| 3731 | stored = cdfs; |
| 3732 | } |
| 3733 | out.push(bytes); |
| 3734 | } |
| 3735 | Ok((out, stored)) |
| 3736 | } |
| 3737 | |
| 3738 | |
| 3739 | |
| 3740 | |
| 3741 | |
| 3742 | |
| 3743 | |
| 3744 | |
| 3745 | |
| 3746 | |
| 3747 | |
| 3748 | |
| 3749 | |
| 3750 | |
| 3751 | |
| 3752 | fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>> |
| 3753 | where |
| 3754 | T: Send, |
| 3755 | F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync, |
| 3756 | { |
| 3757 | let _t = crate::par::timer(crate::par::S_TILE_SEARCH); |
| 3758 | let threads = crate::par::tile_threads().min(tiles); |
| 3759 | if threads <= 1 { |
| 3760 | return (0..tiles).map(|index| job(index, fctx)).collect(); |
| 3761 | } |
| 3762 | type Slot<T> = Option<Result<T>>; |
| 3763 | let done: std::sync::Mutex<Vec<Slot<T>>> = |
| 3764 | std::sync::Mutex::new((0..tiles).map(|_| None).collect()); |
| 3765 | { |
| 3766 | let batch = crate::par::Batch::new("ec-av1-tile-search"); |
| 3767 | for (from, to) in crate::par::bands(tiles, threads) { |
| 3768 | let done = &done; |
| 3769 | let job = &job; |
| 3770 | let ctx = crate::decode::filter_ctx_copy(fctx); |
| 3771 | batch.submit(move || { |
| 3772 | for index in from..to { |
| 3773 | let searched = job(index, &ctx); |
| 3774 | done.lock().expect("tile slots")[index] = Some(searched); |
| 3775 | } |
| 3776 | }); |
| 3777 | } |
| 3778 | } |
| 3779 | done.into_inner() |
| 3780 | .expect("tile slots") |
| 3781 | .into_iter() |
| 3782 | .map(|slot| slot.expect("every tile was searched")) |
| 3783 | .collect() |
| 3784 | } |
| 3785 | |
| 3786 | |
| 3787 | |
| 3788 | |
| 3789 | |
| 3790 | |
| 3791 | |
| 3792 | fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> { |
| 3793 | Plane { |
| 3794 | source, |
| 3795 | reconstruction: vec![128; source.len()], |
| 3796 | width, |
| 3797 | height, |
| 3798 | true_width, |
| 3799 | true_height, |
| 3800 | tile_x0: 0, |
| 3801 | tile_y0: 0, |
| 3802 | tile_x1: width, |
| 3803 | tile_y1: height, |
| 3804 | } |
| 3805 | } |
| 3806 | |
| 3807 | |
| 3808 | |
| 3809 | |
| 3810 | |
| 3811 | |
| 3812 | |
| 3813 | |
| 3814 | |
| 3815 | |
| 3816 | |
| 3817 | |
| 3818 | #[allow(unsafe_code)] |
| 3819 | fn copy_rect( |
| 3820 | dst: crate::par::Shared<'_, Vec<u8>>, |
| 3821 | src: &[u8], |
| 3822 | stride: usize, |
| 3823 | x0: usize, |
| 3824 | y0: usize, |
| 3825 | x1: usize, |
| 3826 | y1: usize, |
| 3827 | ) { |
| 3828 | |
| 3829 | let dst = unsafe { dst.get() }; |
| 3830 | for y in y0..y1 { |
| 3831 | let (a, b) = (y * stride + x0, y * stride + x1); |
| 3832 | dst[a..b].copy_from_slice(&src[a..b]); |
| 3833 | } |
| 3834 | } |
| 3835 | |
| 3836 | |
| 3837 | |
| 3838 | |
| 3839 | |
| 3840 | |
| 3841 | fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo { |
| 3842 | ec_av1_syntax::TileInfo { |
| 3843 | uniform_spacing: true, |
| 3844 | cols: layout.cols(), |
| 3845 | rows: layout.rows(), |
| 3846 | cols_log2: layout.cols_log2, |
| 3847 | rows_log2: layout.rows_log2, |
| 3848 | mi_col_starts: layout.mi_col_starts(), |
| 3849 | mi_row_starts: layout.mi_row_starts(), |
| 3850 | context_update_tile_id: layout.largest_tile() as u32, |
| 3851 | tile_size_bytes, |
| 3852 | } |
| 3853 | } |
| 3854 | |
| 3855 | |
| 3856 | |
| 3857 | |
| 3858 | |
| 3859 | |
| 3860 | |
| 3861 | fn clip_planes_to_tile( |
| 3862 | luma: &mut Plane<'_>, |
| 3863 | chroma: &mut [Plane<'_>; 2], |
| 3864 | rect: crate::tile::TileRect, |
| 3865 | ) { |
| 3866 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 3867 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 3868 | luma.set_tile(x0, y0, x1, y1); |
| 3869 | for plane in chroma.iter_mut() { |
| 3870 | plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2)); |
| 3871 | } |
| 3872 | } |
| 3873 | |
| 3874 | |
| 3875 | |
| 3876 | |
| 3877 | |
| 3878 | |
| 3879 | |
| 3880 | |
| 3881 | |
| 3882 | |
| 3883 | |
| 3884 | |
| 3885 | |
| 3886 | |
| 3887 | |
| 3888 | |
| 3889 | |
| 3890 | |
| 3891 | |
| 3892 | |
| 3893 | |
| 3894 | |
| 3895 | |
| 3896 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { |
| 3897 | encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::new()) |
| 3898 | } |
| 3899 | |
| 3900 | |
| 3901 | |
| 3902 | |
| 3903 | |
| 3904 | |
| 3905 | |
| 3906 | pub fn encode_key_frame_with_modes( |
| 3907 | picture: &Picture, |
| 3908 | base_q_idx: u8, |
| 3909 | deadzone: f64, |
| 3910 | modes: &[u8], |
| 3911 | ) -> Result<Encoded> { |
| 3912 | encode_key_frame_with_modes_with_ctx( |
| 3913 | picture, |
| 3914 | base_q_idx, |
| 3915 | deadzone, |
| 3916 | modes, |
| 3917 | &crate::decode::FrameCtx::new(), |
| 3918 | ) |
| 3919 | } |
| 3920 | |
| 3921 | |
| 3922 | |
| 3923 | |
| 3924 | |
| 3925 | |
| 3926 | pub fn encode_sequence( |
| 3927 | pictures: &[Picture], |
| 3928 | base_q_idx: u8, |
| 3929 | deadzone: f64, |
| 3930 | ) -> Result<EncodedSequence> { |
| 3931 | encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::new()) |
| 3932 | } |
| 3933 | |
| 3934 | pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> { |
| 3935 | encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx) |
| 3936 | } |
| 3937 | |
| 3938 | |
| 3939 | |
| 3940 | |
| 3941 | |
| 3942 | |
| 3943 | |
| 3944 | |
| 3945 | |
| 3946 | |
| 3947 | |
| 3948 | |
| 3949 | pub(crate) fn encode_key_frame_with_modes_with_ctx( |
| 3950 | picture: &Picture, |
| 3951 | base_q_idx: u8, |
| 3952 | deadzone: f64, |
| 3953 | modes: &[u8], fctx: &crate::decode::FrameCtx, |
| 3954 | ) -> Result<Encoded> { |
| 3955 | picture.check_even()?; |
| 3956 | let padded = picture.padded_to(BLOCK); |
| 3957 | let encoded = encode_key_frame_inner( |
| 3958 | &padded, |
| 3959 | base_q_idx, |
| 3960 | deadzone, |
| 3961 | modes, |
| 3962 | split_blocks(), |
| 3963 | (picture.width, picture.height), |
| 3964 | unspecified_color_config(), fctx, |
| 3965 | )?; |
| 3966 | Ok(crop_encoded(&encoded, picture.width, picture.height)) |
| 3967 | } |
| 3968 | |
| 3969 | |
| 3970 | |
| 3971 | |
| 3972 | |
| 3973 | pub(crate) fn encode_key_frame_inner( |
| 3974 | picture: &Picture, |
| 3975 | base_q_idx: u8, |
| 3976 | deadzone: f64, |
| 3977 | modes: &[u8], |
| 3978 | split_blocks: bool, |
| 3979 | render: (usize, usize), |
| 3980 | color_config: ColorConfig, fctx: &crate::decode::FrameCtx, |
| 3981 | ) -> Result<Encoded> { |
| 3982 | picture.check()?; |
| 3983 | if modes.is_empty() { |
| 3984 | return Err(Error::unsupported( |
| 3985 | "AV1 encode", |
| 3986 | "a mode search needs at least one mode to choose from", |
| 3987 | )); |
| 3988 | } |
| 3989 | if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) { |
| 3990 | return Err(Error::unsupported( |
| 3991 | "AV1 encode", |
| 3992 | format!("intra mode {bad} is not one the encoder predicts"), |
| 3993 | )); |
| 3994 | } |
| 3995 | |
| 3996 | |
| 3997 | |
| 3998 | |
| 3999 | |
| 4000 | |
| 4001 | |
| 4002 | |
| 4003 | |
| 4004 | |
| 4005 | |
| 4006 | let screen = screen_content( |
| 4007 | &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(), |
| 4008 | picture.width, |
| 4009 | (picture.width).min(render.0), |
| 4010 | (picture.height).min(render.1), |
| 4011 | ); |
| 4012 | arm_seq_screen(screen); |
| 4013 | let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; |
| 4014 | header.allow_screen_content_tools = screen; |
| 4015 | header.render_width = render.0 as u32; |
| 4016 | header.render_height = render.1 as u32; |
| 4017 | |
| 4018 | |
| 4019 | |
| 4020 | |
| 4021 | |
| 4022 | let tx_select = tx_select(); |
| 4023 | if tx_select { |
| 4024 | header.tx_mode = TxMode::Select; |
| 4025 | } |
| 4026 | let (tile_cols_log2, tile_rows_log2) = armed_tiles(); |
| 4027 | |
| 4028 | |
| 4029 | |
| 4030 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 4031 | |
| 4032 | |
| 4033 | |
| 4034 | |
| 4035 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 4036 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 4037 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 4038 | let mut luma = Plane { |
| 4039 | source: &picture_y8, |
| 4040 | reconstruction: vec![128; picture_y8.len()], |
| 4041 | width: picture.width, |
| 4042 | height: picture.height, |
| 4043 | true_width, |
| 4044 | true_height, |
| 4045 | tile_x0: 0, |
| 4046 | tile_y0: 0, |
| 4047 | tile_x1: picture.width, |
| 4048 | tile_y1: picture.height, |
| 4049 | }; |
| 4050 | let mut chroma = [ |
| 4051 | Plane { |
| 4052 | source: &picture_u8, |
| 4053 | reconstruction: vec![128; picture_u8.len()], |
| 4054 | width: picture.width / 2, |
| 4055 | height: picture.height / 2, |
| 4056 | true_width: true_width / 2, |
| 4057 | true_height: true_height / 2, |
| 4058 | tile_x0: 0, |
| 4059 | tile_y0: 0, |
| 4060 | tile_x1: picture.width / 2, |
| 4061 | tile_y1: picture.height / 2, |
| 4062 | }, |
| 4063 | Plane { |
| 4064 | source: &picture_v8, |
| 4065 | reconstruction: vec![128; picture_v8.len()], |
| 4066 | width: picture.width / 2, |
| 4067 | height: picture.height / 2, |
| 4068 | true_width: true_width / 2, |
| 4069 | true_height: true_height / 2, |
| 4070 | tile_x0: 0, |
| 4071 | tile_y0: 0, |
| 4072 | tile_x1: picture.width / 2, |
| 4073 | tile_y1: picture.height / 2, |
| 4074 | }, |
| 4075 | ]; |
| 4076 | |
| 4077 | |
| 4078 | |
| 4079 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 4080 | let search = Search { |
| 4081 | base_q_idx, |
| 4082 | deadzone, |
| 4083 | lambda: lambda_scale() * step * step, |
| 4084 | modes, |
| 4085 | top_k: prune_top_k(), |
| 4086 | screen, |
| 4087 | }; |
| 4088 | |
| 4089 | |
| 4090 | |
| 4091 | |
| 4092 | |
| 4093 | |
| 4094 | |
| 4095 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 4096 | let (cols, rows) = (cols as usize, rows as usize); |
| 4097 | |
| 4098 | |
| 4099 | |
| 4100 | |
| 4101 | |
| 4102 | |
| 4103 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 4104 | |
| 4105 | let layout = |
| 4106 | crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); |
| 4107 | header.tile_info = tile_info_of(&layout, 1); |
| 4108 | |
| 4109 | |
| 4110 | |
| 4111 | |
| 4112 | let header_tile_info = header.tile_info.clone(); |
| 4113 | |
| 4114 | |
| 4115 | |
| 4116 | |
| 4117 | |
| 4118 | |
| 4119 | |
| 4120 | let (frame_width, frame_height) = (picture.width, picture.height); |
| 4121 | let luma_out = crate::par::Shared::new(&mut luma.reconstruction); |
| 4122 | let [cb, cr] = &mut chroma; |
| 4123 | let chroma_out = [ |
| 4124 | crate::par::Shared::new(&mut cb.reconstruction), |
| 4125 | crate::par::Shared::new(&mut cr.reconstruction), |
| 4126 | ]; |
| 4127 | let search_tile = |index: usize, |
| 4128 | fctx: &crate::decode::FrameCtx| |
| 4129 | -> Result<Vec<(usize, Superblock, Vec<u8>)>> { |
| 4130 | let rect = layout.rect(index); |
| 4131 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 4132 | let mut chroma = [ |
| 4133 | fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 4134 | fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 4135 | ]; |
| 4136 | clip_planes_to_tile(&mut luma, &mut chroma, rect); |
| 4137 | let mut above_mode = vec![DC_PRED; cols * 2]; |
| 4138 | let mut left_mode = vec![DC_PRED; rows * 2]; |
| 4139 | let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new(); |
| 4140 | for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize { |
| 4141 | for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize { |
| 4142 | let mut modes = Vec::with_capacity(4); |
| 4143 | |
| 4144 | |
| 4145 | |
| 4146 | let mut blocks = Vec::with_capacity(4); |
| 4147 | for quadrant in 0..4 { |
| 4148 | let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2); |
| 4149 | if col >= cols || row >= rows { |
| 4150 | continue; |
| 4151 | } |
| 4152 | let (x, y) = (col * BLOCK, row * BLOCK); |
| 4153 | let (c0, r0) = (col * 2, row * 2); |
| 4154 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 4155 | |
| 4156 | |
| 4157 | |
| 4158 | |
| 4159 | |
| 4160 | |
| 4161 | |
| 4162 | |
| 4163 | let (has_cols32, has_rows32) = ( |
| 4164 | crate::tile::has_half( |
| 4165 | col as u32 * crate::tile::BLOCK_MI, |
| 4166 | crate::tile::BLOCK_MI, |
| 4167 | header.mi_cols, |
| 4168 | ), |
| 4169 | crate::tile::has_half( |
| 4170 | row as u32 * crate::tile::BLOCK_MI, |
| 4171 | crate::tile::BLOCK_MI, |
| 4172 | header.mi_rows, |
| 4173 | ), |
| 4174 | ); |
| 4175 | let whole_legal = has_cols32 && has_rows32; |
| 4176 | |
| 4177 | |
| 4178 | |
| 4179 | |
| 4180 | |
| 4181 | |
| 4182 | let sub_half = |sr: usize, sc: usize| { |
| 4183 | ( |
| 4184 | crate::tile::has_half( |
| 4185 | sc as u32 * crate::tile::SUB_MI, |
| 4186 | crate::tile::SUB_MI, |
| 4187 | header.mi_cols, |
| 4188 | ), |
| 4189 | crate::tile::has_half( |
| 4190 | sr as u32 * crate::tile::SUB_MI, |
| 4191 | crate::tile::SUB_MI, |
| 4192 | header.mi_rows, |
| 4193 | ), |
| 4194 | ) |
| 4195 | }; |
| 4196 | let both_axes_cut = (0..4) |
| 4197 | .map(|i| (r0 + i / 2, c0 + i % 2)) |
| 4198 | .filter(|&(sr, sc)| { |
| 4199 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 4200 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 4201 | }) |
| 4202 | .any(|(sr, sc)| { |
| 4203 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 4204 | !has_cols16 && !has_rows16 |
| 4205 | }); |
| 4206 | if !whole_legal && both_axes_cut { |
| 4207 | return Err(Error::unsupported( |
| 4208 | "AV1 encode", |
| 4209 | format!( |
| 4210 | "the 32x32 block at ({col},{row}) straddles the true frame edge \ |
| 4211 | in a way that needs a rectangular (HORZ/VERT) transform this \ |
| 4212 | encoder does not code yet" |
| 4213 | ), |
| 4214 | )); |
| 4215 | } |
| 4216 | |
| 4217 | |
| 4218 | |
| 4219 | let (whole, mut cost_whole) = code_square( |
| 4220 | &mut luma, |
| 4221 | &mut chroma, |
| 4222 | (x, y), |
| 4223 | BLOCK, |
| 4224 | &search, |
| 4225 | &mode_bits(above_mode[c0], left_mode[r0]), |
| 4226 | tx_select, fctx, |
| 4227 | ); |
| 4228 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 4229 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 4230 | |
| 4231 | |
| 4232 | |
| 4233 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); |
| 4234 | let mut split = Vec::with_capacity(4); |
| 4235 | let mut cost_split = search.lambda |
| 4236 | * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); |
| 4237 | let mut split_modes = Vec::with_capacity(4); |
| 4238 | for sub in 0..4 { |
| 4239 | let (sc, sr) = (c0 + sub % 2, r0 + sub / 2); |
| 4240 | |
| 4241 | |
| 4242 | |
| 4243 | |
| 4244 | |
| 4245 | |
| 4246 | if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows |
| 4247 | || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols |
| 4248 | { |
| 4249 | continue; |
| 4250 | } |
| 4251 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 4252 | if has_cols16 && has_rows16 { |
| 4253 | let (block, cost) = code_square( |
| 4254 | &mut luma, |
| 4255 | &mut chroma, |
| 4256 | (x + (sub % 2) * SUB, y + (sub / 2) * SUB), |
| 4257 | SUB, |
| 4258 | &search, |
| 4259 | &mode_bits(above_mode[sc], left_mode[sr]), |
| 4260 | tx_select, fctx, |
| 4261 | ); |
| 4262 | cost_split += cost; |
| 4263 | split_modes.push(block.mode); |
| 4264 | above_mode[sc] = block.mode; |
| 4265 | left_mode[sr] = block.mode; |
| 4266 | split.push(block); |
| 4267 | } else { |
| 4268 | |
| 4269 | |
| 4270 | |
| 4271 | |
| 4272 | |
| 4273 | |
| 4274 | |
| 4275 | |
| 4276 | let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]); |
| 4277 | let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB); |
| 4278 | let mut leaves = Vec::with_capacity(2); |
| 4279 | for i in 0..4 { |
| 4280 | let leaf_x = x_sub + (i % 2) * 8; |
| 4281 | let leaf_y = y_sub + (i / 2) * 8; |
| 4282 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 4283 | continue; |
| 4284 | } |
| 4285 | let (leaf, cost) = code_square( |
| 4286 | &mut luma, |
| 4287 | &mut chroma, |
| 4288 | (leaf_x, leaf_y), |
| 4289 | 8, |
| 4290 | &search, |
| 4291 | &leaf_mode_bits, |
| 4292 | tx_select, fctx, |
| 4293 | ); |
| 4294 | cost_split += cost; |
| 4295 | split_modes.push(leaf.mode); |
| 4296 | leaves.push(leaf); |
| 4297 | } |
| 4298 | split.push(BlockCoeffs { |
| 4299 | eight: Some(leaves), |
| 4300 | ..BlockCoeffs::default() |
| 4301 | }); |
| 4302 | } |
| 4303 | } |
| 4304 | |
| 4305 | |
| 4306 | |
| 4307 | |
| 4308 | |
| 4309 | |
| 4310 | |
| 4311 | |
| 4312 | |
| 4313 | if !whole_legal || (split_blocks && cost_split < cost_whole) { |
| 4314 | modes.extend_from_slice(&split_modes); |
| 4315 | blocks.push(Quadrant::Split(split)); |
| 4316 | } else { |
| 4317 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); |
| 4318 | for cell in 0..2 { |
| 4319 | above_mode[c0 + cell] = whole.mode; |
| 4320 | left_mode[r0 + cell] = whole.mode; |
| 4321 | } |
| 4322 | modes.push(whole.mode); |
| 4323 | blocks.push(Quadrant::Whole(whole)); |
| 4324 | } |
| 4325 | } |
| 4326 | coded.push((sb_row * sb_cols + sb_col, Superblock::Split(blocks), modes)); |
| 4327 | } |
| 4328 | } |
| 4329 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 4330 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 4331 | copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1); |
| 4332 | for (&out, tile) in chroma_out.iter().zip(&chroma) { |
| 4333 | copy_rect( |
| 4334 | out, |
| 4335 | &tile.reconstruction, |
| 4336 | frame_width / 2, |
| 4337 | x0 / 2, |
| 4338 | y0 / 2, |
| 4339 | x1.div_ceil(2), |
| 4340 | y1.div_ceil(2), |
| 4341 | ); |
| 4342 | } |
| 4343 | Ok(coded) |
| 4344 | }; |
| 4345 | let searched = search_tiles(layout.count(), fctx, search_tile)?; |
| 4346 | |
| 4347 | |
| 4348 | |
| 4349 | let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect(); |
| 4350 | for (at, superblock, block_modes) in searched.into_iter().flatten() { |
| 4351 | in_order[at] = Some((superblock, block_modes)); |
| 4352 | } |
| 4353 | let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); |
| 4354 | let mut modes = Vec::with_capacity(cols * rows); |
| 4355 | for slot in in_order { |
| 4356 | let (superblock, block_modes) = slot.expect("every superblock belongs to a tile"); |
| 4357 | superblocks.push(superblock); |
| 4358 | modes.extend_from_slice(&block_modes); |
| 4359 | } |
| 4360 | |
| 4361 | #[cfg(test)] |
| 4362 | record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx)); |
| 4363 | |
| 4364 | |
| 4365 | |
| 4366 | |
| 4367 | |
| 4368 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 4369 | let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)); |
| 4370 | let start_cdfs = CdfSnapshot(cdfs); |
| 4371 | |
| 4372 | |
| 4373 | |
| 4374 | |
| 4375 | let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; |
| 4376 | let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; |
| 4377 | |
| 4378 | |
| 4379 | |
| 4380 | |
| 4381 | let code_tiles = |bits: u8, |
| 4382 | sb_cols: usize, |
| 4383 | grid: &[u8], |
| 4384 | units: &[Option<crate::restoration::WienerInfo>]| |
| 4385 | -> Result<Vec<Vec<u8>>> { |
| 4386 | let (out, _) = write_tiles(layout.count(), usize::MAX, |index| { |
| 4387 | crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec()); |
| 4388 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 4389 | let mut cdfs = start_cdfs.0.clone(); |
| 4390 | crate::tile::arm_screen(screen); |
| 4391 | let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs( |
| 4392 | mi_cols, |
| 4393 | mi_rows, |
| 4394 | base_q_idx, |
| 4395 | &superblocks, |
| 4396 | tx_select, |
| 4397 | &mut cdfs, |
| 4398 | layout.rect(index), |
| 4399 | )?; |
| 4400 | Ok((bytes, None)) |
| 4401 | })?; |
| 4402 | Ok(out) |
| 4403 | }; |
| 4404 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| 4405 | |
| 4406 | |
| 4407 | |
| 4408 | |
| 4409 | |
| 4410 | pick_and_apply_filters( |
| 4411 | &mut header, |
| 4412 | &mut luma, |
| 4413 | &mut chroma, |
| 4414 | [&picture_y8, &picture_u8, &picture_v8], |
| 4415 | true, |
| 4416 | &mut tiles, |
| 4417 | search.lambda, |
| 4418 | fctx, |
| 4419 | |
| 4420 | |
| 4421 | |
| 4422 | |
| 4423 | |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |
| 4424 | |lf, cdef, h, tiles: &[Vec<u8>], lr| { |
| 4425 | let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); |
| 4426 | crate::decode::decode_key_frame_tiles_lr( |
| 4427 | &payloads, |
| 4428 | &header_tile_info, |
| 4429 | h.mi_cols, |
| 4430 | h.mi_rows, |
| 4431 | base_q_idx, |
| 4432 | h.frame_width, |
| 4433 | h.frame_height, |
| 4434 | seq.enable_filter_intra, |
| 4435 | cdef, |
| 4436 | lf, |
| 4437 | tx_select, |
| 4438 | h.reduced_tx_set, |
| 4439 | h.allow_screen_content_tools, |
| 4440 | h.allow_intrabc, |
| 4441 | lr, |
| 4442 | fctx, |
| 4443 | ) |
| 4444 | }, |
| 4445 | )?; |
| 4446 | let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); |
| 4447 | header.tile_info.tile_size_bytes = tile_size_bytes; |
| 4448 | let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); |
| 4449 | let mut stream = temporal_delimiter(); |
| 4450 | stream.extend_from_slice(&sequence_header_obu(&seq)?); |
| 4451 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 4452 | |
| 4453 | let [u, v] = chroma; |
| 4454 | Ok(Encoded { |
| 4455 | stream, |
| 4456 | modes, |
| 4457 | inter_block_share: 0.0, |
| 4458 | reconstruction: Picture { |
| 4459 | width: luma.width, |
| 4460 | height: luma.height, |
| 4461 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 4462 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 4463 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 4464 | }, |
| 4465 | tile, |
| 4466 | mi_cols: header.mi_cols, |
| 4467 | mi_rows: header.mi_rows, |
| 4468 | base_q_idx, |
| 4469 | tx_select, |
| 4470 | screen, |
| 4471 | next_cdfs: start_cdfs.clone(), |
| 4472 | start_cdfs, |
| 4473 | loop_filter: header.loop_filter, |
| 4474 | cdef: header.cdef, |
| 4475 | loop_restoration: header.loop_restoration, |
| 4476 | }) |
| 4477 | } |
| 4478 | |
| 4479 | |
| 4480 | |
| 4481 | |
| 4482 | |
| 4483 | |
| 4484 | |
| 4485 | |
| 4486 | |
| 4487 | |
| 4488 | |
| 4489 | |
| 4490 | |
| 4491 | |
| 4492 | |
| 4493 | fn pick_and_apply_filters( |
| 4494 | header: &mut FrameHeader, |
| 4495 | luma: &mut Plane<'_>, |
| 4496 | chroma: &mut [Plane<'_>; 2], |
| 4497 | source: [&[u8]; 3], |
| 4498 | search: bool, |
| 4499 | |
| 4500 | |
| 4501 | |
| 4502 | |
| 4503 | |
| 4504 | tiles: &mut Vec<Vec<u8>>, |
| 4505 | lambda: f64, |
| 4506 | fctx: &crate::decode::FrameCtx, |
| 4507 | recode: impl Fn( |
| 4508 | u8, |
| 4509 | usize, |
| 4510 | &[u8], |
| 4511 | &[Option<crate::restoration::WienerInfo>], |
| 4512 | ) -> Result<Vec<Vec<u8>>>, |
| 4513 | decode: impl Fn( |
| 4514 | &LoopFilterParams, |
| 4515 | &CdefParams, |
| 4516 | &FrameHeader, |
| 4517 | &[Vec<u8>], |
| 4518 | &LoopRestorationParams, |
| 4519 | ) -> Result<Picture>, |
| 4520 | ) -> Result<()> { |
| 4521 | if !search { |
| 4522 | return Ok(()); |
| 4523 | } |
| 4524 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 4525 | let hdr = header.clone(); |
| 4526 | |
| 4527 | |
| 4528 | let damping = 3 + (header.quantization.base_q_idx >> 6); |
| 4529 | let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 4530 | let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize); |
| 4531 | let none_lr = LoopRestorationParams::default(); |
| 4532 | |
| 4533 | |
| 4534 | |
| 4535 | |
| 4536 | |
| 4537 | crate::decode::clear_filter_replay(); |
| 4538 | |
| 4539 | |
| 4540 | |
| 4541 | |
| 4542 | let _bands = crate::par::override_filter_threads(crate::par::tile_threads()); |
| 4543 | let ft = crate::par::timer(crate::par::S_FILTER); |
| 4544 | let search_result = crate::filter_search::pick_filters( |
| 4545 | |lf, cdef| { |
| 4546 | if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) { |
| 4547 | return Ok(picture); |
| 4548 | } |
| 4549 | crate::decode::arm_filter_replay(); |
| 4550 | let _t = crate::par::timer(crate::par::S_FIRST); |
| 4551 | decode(lf, cdef, &hdr, tiles, &none_lr) |
| 4552 | }, |
| 4553 | source, |
| 4554 | luma.width, |
| 4555 | (fw, fh), |
| 4556 | damping, |
| 4557 | (sb_cols, sb_rows), |
| 4558 | lambda, |
| 4559 | ); |
| 4560 | drop(ft); |
| 4561 | crate::decode::clear_filter_replay(); |
| 4562 | let (lf, cdef, idx_grid, picture) = search_result?; |
| 4563 | header.loop_filter = lf; |
| 4564 | header.cdef = cdef; |
| 4565 | |
| 4566 | |
| 4567 | |
| 4568 | |
| 4569 | |
| 4570 | |
| 4571 | |
| 4572 | |
| 4573 | |
| 4574 | |
| 4575 | |
| 4576 | |
| 4577 | |
| 4578 | |
| 4579 | let lr_on = restoration_enabled(); |
| 4580 | fctx.capture_stages.set(lr_on); |
| 4581 | let mut filtered = if idx_grid.is_empty() { |
| 4582 | if lr_on { |
| 4583 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 4584 | decode(&lf, &cdef, &hdr, tiles, &none_lr)? |
| 4585 | } else { |
| 4586 | picture |
| 4587 | } |
| 4588 | } else { |
| 4589 | let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?; |
| 4590 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 4591 | let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?; |
| 4592 | *tiles = coded; |
| 4593 | picture |
| 4594 | }; |
| 4595 | fctx.capture_stages.set(false); |
| 4596 | let mut lr = LoopRestorationParams::default(); |
| 4597 | if lr_on { |
| 4598 | let mut want = LoopRestorationParams { |
| 4599 | loop_restoration_size: [64, 64, 64], |
| 4600 | uses_lr: true, |
| 4601 | ..LoopRestorationParams::default() |
| 4602 | }; |
| 4603 | want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener; |
| 4604 | let lrt = crate::par::timer(crate::par::S_LR); |
| 4605 | let units = match crate::decode::take_filter_stages(fctx) { |
| 4606 | Some(stages) => crate::filter_search::pick_restoration( |
| 4607 | &stages, |
| 4608 | source[0], |
| 4609 | luma.width, |
| 4610 | (fw, fh), |
| 4611 | &want, |
| 4612 | lambda, |
| 4613 | fctx, |
| 4614 | ), |
| 4615 | None => Vec::new(), |
| 4616 | }; |
| 4617 | |
| 4618 | |
| 4619 | |
| 4620 | |
| 4621 | drop(lrt); |
| 4622 | if units.iter().any(Option::is_some) { |
| 4623 | let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?; |
| 4624 | let _t = crate::par::timer(crate::par::S_CAPTURE); |
| 4625 | filtered = decode(&lf, &cdef, &hdr, &coded, &want)?; |
| 4626 | *tiles = coded; |
| 4627 | lr = want; |
| 4628 | } |
| 4629 | } |
| 4630 | header.loop_restoration = lr; |
| 4631 | let dec_cw = filtered.width.div_ceil(2); |
| 4632 | let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2)); |
| 4633 | crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh); |
| 4634 | crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch); |
| 4635 | crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch); |
| 4636 | Ok(()) |
| 4637 | } |
| 4638 | |
| 4639 | |
| 4640 | |
| 4641 | |
| 4642 | const SIZE_GROUP_32: usize = 3; |
| 4643 | |
| 4644 | |
| 4645 | |
| 4646 | |
| 4647 | const LAST_FRAME: i8 = 1; |
| 4648 | |
| 4649 | |
| 4650 | |
| 4651 | |
| 4652 | |
| 4653 | |
| 4654 | |
| 4655 | fn inter_mode_bits() -> [f64; 13] { |
| 4656 | std::array::from_fn(|mode| { |
| 4657 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 4658 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 4659 | } else { |
| 4660 | 0.0 |
| 4661 | }; |
| 4662 | symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode) |
| 4663 | + angle |
| 4664 | + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 4665 | }) |
| 4666 | } |
| 4667 | |
| 4668 | |
| 4669 | |
| 4670 | |
| 4671 | |
| 4672 | |
| 4673 | |
| 4674 | |
| 4675 | fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 { |
| 4676 | (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 } |
| 4677 | } |
| 4678 | |
| 4679 | |
| 4680 | |
| 4681 | |
| 4682 | fn mv_class_base(class: usize) -> i32 { |
| 4683 | if class == 0 { 0 } else { 2i32 << (class + 2) } |
| 4684 | } |
| 4685 | |
| 4686 | |
| 4687 | |
| 4688 | fn mv_class_of(z: i32) -> usize { |
| 4689 | let mut class = 0; |
| 4690 | while class < 10 && mv_class_base(class + 1) <= z { |
| 4691 | class += 1; |
| 4692 | } |
| 4693 | class |
| 4694 | } |
| 4695 | |
| 4696 | |
| 4697 | |
| 4698 | |
| 4699 | |
| 4700 | |
| 4701 | |
| 4702 | |
| 4703 | |
| 4704 | |
| 4705 | |
| 4706 | fn mv_component_bits(diff: i32) -> Option<f64> { |
| 4707 | let mag = diff.unsigned_abs() as i32; |
| 4708 | let z = mag - 1; |
| 4709 | if z & 1 == 0 { |
| 4710 | return None; |
| 4711 | } |
| 4712 | let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); |
| 4713 | let class = mv_class_of(z); |
| 4714 | bits += symbol_bits(&cdf::MV_CLASS, class); |
| 4715 | let local = z - mv_class_base(class); |
| 4716 | if class == 0 { |
| 4717 | let bit = (local >> 3) & 1; |
| 4718 | let fr = (local >> 1) & 3; |
| 4719 | bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize); |
| 4720 | bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize); |
| 4721 | } else { |
| 4722 | let d = local >> 3; |
| 4723 | let fr = (local >> 1) & 3; |
| 4724 | for i in 0..class { |
| 4725 | bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); |
| 4726 | } |
| 4727 | bits += symbol_bits(&cdf::MV_FR, fr as usize); |
| 4728 | } |
| 4729 | Some(bits) |
| 4730 | } |
| 4731 | |
| 4732 | |
| 4733 | |
| 4734 | |
| 4735 | |
| 4736 | fn extra_ref_new_mv() -> bool { |
| 4737 | match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() { |
| 4738 | Some(v) if cfg!(test) => v != "0", |
| 4739 | _ => EXTRA_REF_NEW_MV, |
| 4740 | } |
| 4741 | } |
| 4742 | |
| 4743 | |
| 4744 | |
| 4745 | |
| 4746 | |
| 4747 | |
| 4748 | |
| 4749 | pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] { |
| 4750 | let last = order_hint.wrapping_sub(1) & 0x7f; |
| 4751 | let alt = if has_altref { |
| 4752 | order_hint.wrapping_sub(2) & 0x7f |
| 4753 | } else { |
| 4754 | key_hint |
| 4755 | }; |
| 4756 | [last, last, last, key_hint, last, last, alt] |
| 4757 | } |
| 4758 | |
| 4759 | |
| 4760 | |
| 4761 | |
| 4762 | |
| 4763 | |
| 4764 | |
| 4765 | const REFERENCE_SELECT: bool = true; |
| 4766 | |
| 4767 | |
| 4768 | pub(crate) fn reference_select() -> bool { |
| 4769 | match std::env::var("EC_AV1_COMPOUND").ok() { |
| 4770 | Some(v) if cfg!(test) => v != "0", |
| 4771 | _ => REFERENCE_SELECT, |
| 4772 | } |
| 4773 | } |
| 4774 | |
| 4775 | |
| 4776 | |
| 4777 | fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 { |
| 4778 | let mut bits = 0.0; |
| 4779 | let mut idx = start; |
| 4780 | while idx < start + 2 && stack.entries.len() > idx + 1 { |
| 4781 | let advance = idx < target; |
| 4782 | bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance)); |
| 4783 | if !advance { |
| 4784 | break; |
| 4785 | } |
| 4786 | idx += 1; |
| 4787 | } |
| 4788 | bits |
| 4789 | } |
| 4790 | |
| 4791 | |
| 4792 | |
| 4793 | |
| 4794 | fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> { |
| 4795 | let mut best: Option<(f64, u8)> = None; |
| 4796 | for idx in 0..3usize { |
| 4797 | if idx > 0 && stack.entries.len() <= idx { |
| 4798 | break; |
| 4799 | } |
| 4800 | let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv); |
| 4801 | if let Some(b) = mv_residual_bits(mv, base) { |
| 4802 | let total = b + drl_bits_for(stack, 0, idx); |
| 4803 | if best.is_none_or(|(t, _)| total < t) { |
| 4804 | best = Some((total, idx as u8)); |
| 4805 | } |
| 4806 | } |
| 4807 | } |
| 4808 | best |
| 4809 | } |
| 4810 | |
| 4811 | |
| 4812 | |
| 4813 | |
| 4814 | |
| 4815 | |
| 4816 | fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) { |
| 4817 | let mut seeds = [(0, 0); 4]; |
| 4818 | let mut n = 1; |
| 4819 | for e in stack.entries.iter().take(3) { |
| 4820 | seeds[n] = e.mv; |
| 4821 | n += 1; |
| 4822 | } |
| 4823 | (seeds, n) |
| 4824 | } |
| 4825 | |
| 4826 | |
| 4827 | |
| 4828 | |
| 4829 | |
| 4830 | |
| 4831 | |
| 4832 | |
| 4833 | |
| 4834 | fn ref_distance(ref_frame: i8) -> u32 { |
| 4835 | let (bits, order_hint, hints) = crate::tile::order_hints(); |
| 4836 | let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize; |
| 4837 | let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i]) |
| 4838 | .unsigned_abs() |
| 4839 | .max(1); |
| 4840 | if crate::envflags::env_flag!("EC_TRACE_DIST") { |
| 4841 | eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]); |
| 4842 | } |
| 4843 | d |
| 4844 | } |
| 4845 | |
| 4846 | fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> { |
| 4847 | let diff = (mv.0 - pred.0, mv.1 - pred.1); |
| 4848 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 4849 | (false, false) => 0, |
| 4850 | (false, true) => 1, |
| 4851 | (true, false) => 2, |
| 4852 | (true, true) => 3, |
| 4853 | }; |
| 4854 | let mut bits = symbol_bits(&cdf::MV_JOINT, joint); |
| 4855 | for d in [diff.0, diff.1] { |
| 4856 | if d != 0 { |
| 4857 | bits += mv_component_bits(d)?; |
| 4858 | } |
| 4859 | } |
| 4860 | Some(bits) |
| 4861 | } |
| 4862 | |
| 4863 | |
| 4864 | |
| 4865 | |
| 4866 | |
| 4867 | |
| 4868 | |
| 4869 | |
| 4870 | |
| 4871 | |
| 4872 | fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) { |
| 4873 | let round = |m: i32, p: i32| { |
| 4874 | let diff = m - p; |
| 4875 | let mag = diff.unsigned_abs() as i32; |
| 4876 | let even = mag - mag % 2; |
| 4877 | if even == 0 { |
| 4878 | p |
| 4879 | } else { |
| 4880 | p + even * diff.signum() |
| 4881 | } |
| 4882 | }; |
| 4883 | (round(mv.0, pred.0), round(mv.1, pred.1)) |
| 4884 | } |
| 4885 | |
| 4886 | |
| 4887 | |
| 4888 | #[allow(clippy::too_many_arguments)] |
| 4889 | fn mc_trial( |
| 4890 | plane: &Plane, |
| 4891 | x: usize, |
| 4892 | y: usize, |
| 4893 | side: usize, |
| 4894 | mv: (i32, i32), |
| 4895 | luma: bool, |
| 4896 | reference: &[u16], |
| 4897 | stride: usize, |
| 4898 | ref_width: usize, |
| 4899 | ref_height: usize, |
| 4900 | skip: bool, |
| 4901 | base_q_idx: u8, |
| 4902 | deadzone: f64, |
| 4903 | set: TxbSet, fctx: &crate::decode::FrameCtx, |
| 4904 | ) -> Trial { |
| 4905 | let x_q4 = mv_to_q4(x, mv.1, luma); |
| 4906 | let y_q4 = mv_to_q4(y, mv.0, luma); |
| 4907 | |
| 4908 | |
| 4909 | |
| 4910 | |
| 4911 | |
| 4912 | |
| 4913 | |
| 4914 | let mut prediction16 = [0u16; BLOCK * BLOCK]; |
| 4915 | let prediction16 = &mut prediction16[..side * side]; |
| 4916 | mc::predict( |
| 4917 | reference, |
| 4918 | stride, |
| 4919 | ref_width, |
| 4920 | ref_height, |
| 4921 | x_q4, |
| 4922 | y_q4, |
| 4923 | side, |
| 4924 | side, |
| 4925 | prediction16, fctx, |
| 4926 | ); |
| 4927 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 4928 | let prediction = &mut prediction[..side * side]; |
| 4929 | for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) { |
| 4930 | *dst = src as u8; |
| 4931 | } |
| 4932 | plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set) |
| 4933 | } |
| 4934 | |
| 4935 | |
| 4936 | |
| 4937 | |
| 4938 | |
| 4939 | |
| 4940 | |
| 4941 | #[allow(clippy::too_many_arguments)] |
| 4942 | fn mc_trial_compound( |
| 4943 | plane: &Plane, |
| 4944 | x: usize, |
| 4945 | y: usize, |
| 4946 | side: usize, |
| 4947 | (mv0, mv1): ((i32, i32), (i32, i32)), |
| 4948 | luma: bool, |
| 4949 | ref0: (&[u16], usize, usize, usize), |
| 4950 | ref1: (&[u16], usize, usize, usize), |
| 4951 | base_q_idx: u8, |
| 4952 | deadzone: f64, |
| 4953 | set: TxbSet, fctx: &crate::decode::FrameCtx, |
| 4954 | ) -> Trial { |
| 4955 | let mut inter0 = [0i32; BLOCK * BLOCK]; |
| 4956 | let mut inter1 = [0i32; BLOCK * BLOCK]; |
| 4957 | let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]); |
| 4958 | for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] { |
| 4959 | mc::predict_compound_intermediate( |
| 4960 | r.0, |
| 4961 | r.1, |
| 4962 | r.2, |
| 4963 | r.3, |
| 4964 | mv_to_q4(x, mv.1, luma), |
| 4965 | mv_to_q4(y, mv.0, luma), |
| 4966 | mc::REF_NO_SCALE, |
| 4967 | side, |
| 4968 | side, |
| 4969 | mc::InterpFilterKind::Regular, |
| 4970 | mc::InterpFilterKind::Regular, |
| 4971 | dst, |
| 4972 | ); |
| 4973 | } |
| 4974 | let mut blended16 = [0u16; BLOCK * BLOCK]; |
| 4975 | let blended16 = &mut blended16[..side * side]; |
| 4976 | mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx); |
| 4977 | let mut prediction = [0u8; BLOCK * BLOCK]; |
| 4978 | let prediction = &mut prediction[..side * side]; |
| 4979 | for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) { |
| 4980 | *dst = src as u8; |
| 4981 | } |
| 4982 | plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set) |
| 4983 | } |
| 4984 | |
| 4985 | |
| 4986 | |
| 4987 | |
| 4988 | |
| 4989 | |
| 4990 | |
| 4991 | |
| 4992 | |
| 4993 | |
| 4994 | |
| 4995 | |
| 4996 | |
| 4997 | |
| 4998 | |
| 4999 | |
| 5000 | |
| 5001 | |
| 5002 | |
| 5003 | #[allow(clippy::too_many_arguments)] |
| 5004 | fn search_inter_block( |
| 5005 | luma: &mut Plane, |
| 5006 | chroma: &mut [Plane; 2], |
| 5007 | (x, y): (usize, usize), |
| 5008 | search: &Search, |
| 5009 | mode_bits: &[f64; 13], |
| 5010 | reference: &Picture, |
| 5011 | stack: &MvStack, |
| 5012 | |
| 5013 | |
| 5014 | |
| 5015 | |
| 5016 | |
| 5017 | extra: &[(i8, &Picture, &MvStack)], |
| 5018 | |
| 5019 | |
| 5020 | |
| 5021 | compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx, |
| 5022 | ) -> (BlockCoeffs, f64) { |
| 5023 | |
| 5024 | |
| 5025 | |
| 5026 | |
| 5027 | let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16); |
| 5028 | let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx); |
| 5029 | |
| 5030 | |
| 5031 | |
| 5032 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 5033 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 5034 | |
| 5035 | |
| 5036 | |
| 5037 | let single_ref_bits = |ref_frame: i8| { |
| 5038 | symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 5039 | + if ref_frame == crate::mvstack::GOLDEN_FRAME { |
| 5040 | symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1) |
| 5041 | } else { |
| 5042 | symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0) |
| 5043 | } |
| 5044 | }; |
| 5045 | |
| 5046 | struct Candidate { |
| 5047 | cost: f64, |
| 5048 | luma: Trial, |
| 5049 | u: Trial, |
| 5050 | v: Trial, |
| 5051 | mode: u8, |
| 5052 | skip: bool, |
| 5053 | inter: Option<InterInfo>, |
| 5054 | } |
| 5055 | let mut best: Option<Candidate> = None; |
| 5056 | let mut consider = |candidate: Candidate| { |
| 5057 | if best.as_ref().is_none_or(|b| candidate.cost < b.cost) { |
| 5058 | best = Some(candidate); |
| 5059 | } |
| 5060 | }; |
| 5061 | |
| 5062 | |
| 5063 | |
| 5064 | |
| 5065 | |
| 5066 | |
| 5067 | |
| 5068 | |
| 5069 | |
| 5070 | let u_trial = chroma[0].trial( |
| 5071 | At { |
| 5072 | x: x / 2, |
| 5073 | y: y / 2, |
| 5074 | side: BLOCK / 2, |
| 5075 | reach: Reach::none(), |
| 5076 | set: chroma_set, |
| 5077 | }, |
| 5078 | DC_PRED, |
| 5079 | search.base_q_idx, |
| 5080 | search.deadzone, fctx, |
| 5081 | ); |
| 5082 | let v_trial = chroma[1].trial( |
| 5083 | At { |
| 5084 | x: x / 2, |
| 5085 | y: y / 2, |
| 5086 | side: BLOCK / 2, |
| 5087 | reach: Reach::none(), |
| 5088 | set: chroma_set, |
| 5089 | }, |
| 5090 | DC_PRED, |
| 5091 | search.base_q_idx, |
| 5092 | search.deadzone, fctx, |
| 5093 | ); |
| 5094 | |
| 5095 | let intra_modes: Vec<u8> = match search.top_k { |
| 5096 | Some(k) if k < search.modes.len() => { |
| 5097 | let scored = luma.intra_scores( |
| 5098 | At { |
| 5099 | x, |
| 5100 | y, |
| 5101 | side: BLOCK, |
| 5102 | reach, |
| 5103 | set: luma_set, |
| 5104 | }, |
| 5105 | search.modes, |
| 5106 | mode_bits, |
| 5107 | search.lambda, fctx, |
| 5108 | ); |
| 5109 | prune_by_sad(search.modes, scored, k) |
| 5110 | } |
| 5111 | _ => search.modes.to_vec(), |
| 5112 | }; |
| 5113 | census_add(5, 1); |
| 5114 | census_add(6, intra_modes.len()); |
| 5115 | for &mode in &intra_modes { |
| 5116 | let luma_trial = luma.trial( |
| 5117 | At { |
| 5118 | x, |
| 5119 | y, |
| 5120 | side: BLOCK, |
| 5121 | reach, |
| 5122 | set: luma_set, |
| 5123 | }, |
| 5124 | mode, |
| 5125 | search.base_q_idx, |
| 5126 | search.deadzone, fctx, |
| 5127 | ); |
| 5128 | let u = u_trial.clone(); |
| 5129 | let v = v_trial.clone(); |
| 5130 | let cost = luma_trial.sse |
| 5131 | + u.sse |
| 5132 | + v.sse |
| 5133 | + search.lambda |
| 5134 | * (luma_trial.bits |
| 5135 | + u.bits |
| 5136 | + v.bits |
| 5137 | + mode_bits[usize::from(mode)] |
| 5138 | + skip_bits(false) |
| 5139 | + intra_inter_bits(false)); |
| 5140 | consider(Candidate { |
| 5141 | cost, |
| 5142 | luma: luma_trial, |
| 5143 | u, |
| 5144 | v, |
| 5145 | mode, |
| 5146 | skip: false, |
| 5147 | inter: None, |
| 5148 | }); |
| 5149 | } |
| 5150 | |
| 5151 | |
| 5152 | |
| 5153 | |
| 5154 | |
| 5155 | |
| 5156 | |
| 5157 | |
| 5158 | |
| 5159 | |
| 5160 | |
| 5161 | let ref_luma = ( |
| 5162 | &reference.y, |
| 5163 | reference.width, |
| 5164 | luma.true_width, |
| 5165 | luma.true_height, |
| 5166 | ); |
| 5167 | let ref_u = ( |
| 5168 | &reference.u, |
| 5169 | reference.width / 2, |
| 5170 | chroma[0].true_width, |
| 5171 | chroma[0].true_height, |
| 5172 | ); |
| 5173 | let ref_v = ( |
| 5174 | &reference.v, |
| 5175 | reference.width / 2, |
| 5176 | chroma[1].true_width, |
| 5177 | chroma[1].true_height, |
| 5178 | ); |
| 5179 | |
| 5180 | |
| 5181 | |
| 5182 | |
| 5183 | |
| 5184 | |
| 5185 | let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1); |
| 5186 | let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1); |
| 5187 | |
| 5188 | |
| 5189 | |
| 5190 | |
| 5191 | let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target); |
| 5192 | let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME); |
| 5193 | let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![ |
| 5194 | ( |
| 5195 | stack.nearest_mv, |
| 5196 | last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0), |
| 5197 | InterInfo { |
| 5198 | ref1: None, |
| 5199 | mv1: (0, 0), |
| 5200 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5201 | mode: InterMode::NearestMv, |
| 5202 | mv: stack.nearest_mv, |
| 5203 | ref_mv_idx: 0, |
| 5204 | }, |
| 5205 | ), |
| 5206 | |
| 5207 | |
| 5208 | |
| 5209 | ( |
| 5210 | (0, 0), |
| 5211 | last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0), |
| 5212 | InterInfo { |
| 5213 | ref1: None, |
| 5214 | mv1: (0, 0), |
| 5215 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5216 | mode: InterMode::GlobalMv, |
| 5217 | mv: (0, 0), |
| 5218 | ref_mv_idx: 0, |
| 5219 | }, |
| 5220 | ), |
| 5221 | ]; |
| 5222 | let near_bits = |
| 5223 | last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1); |
| 5224 | for idx in 1..=2usize { |
| 5225 | if let Some(e) = stack.entries.get(idx) { |
| 5226 | cands.push(( |
| 5227 | e.mv, |
| 5228 | near_bits + drl_bits(1, idx), |
| 5229 | InterInfo { |
| 5230 | ref1: None, |
| 5231 | mv1: (0, 0), |
| 5232 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5233 | mode: InterMode::NearMv, |
| 5234 | mv: e.mv, |
| 5235 | ref_mv_idx: idx as u8, |
| 5236 | }, |
| 5237 | )); |
| 5238 | } |
| 5239 | } |
| 5240 | |
| 5241 | let source_block = luma.source_block(x, y, BLOCK); |
| 5242 | let (seeds, seed_n) = mv_seeds(stack); |
| 5243 | #[cfg(test)] |
| 5244 | let t = std::time::Instant::now(); |
| 5245 | let found = motion::search( |
| 5246 | ref_luma.0, |
| 5247 | ref_luma.1, |
| 5248 | ref_luma.2, |
| 5249 | ref_luma.3, |
| 5250 | &source_block, |
| 5251 | x, |
| 5252 | y, |
| 5253 | BLOCK, |
| 5254 | BLOCK, |
| 5255 | stack.pred_mv, |
| 5256 | &seeds[..seed_n], |
| 5257 | search.lambda, fctx, |
| 5258 | 1, |
| 5259 | ); |
| 5260 | #[cfg(test)] |
| 5261 | stage_add(0, t.elapsed()); |
| 5262 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 5263 | |
| 5264 | |
| 5265 | |
| 5266 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) { |
| 5267 | cands.push(( |
| 5268 | mv, |
| 5269 | last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits, |
| 5270 | InterInfo { |
| 5271 | ref1: None, |
| 5272 | mv1: (0, 0), |
| 5273 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5274 | mode: InterMode::NewMv, |
| 5275 | mv, |
| 5276 | ref_mv_idx, |
| 5277 | }, |
| 5278 | )); |
| 5279 | } |
| 5280 | |
| 5281 | |
| 5282 | |
| 5283 | let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new(); |
| 5284 | for &(ref_frame, g, gstack) in extra { |
| 5285 | let g_ref_bits = single_ref_bits(ref_frame); |
| 5286 | let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1); |
| 5287 | cands.push(( |
| 5288 | gstack.nearest_mv, |
| 5289 | g_ref_bits |
| 5290 | + g_not_new |
| 5291 | + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1) |
| 5292 | + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0), |
| 5293 | InterInfo { |
| 5294 | ref1: None, |
| 5295 | mv1: (0, 0), |
| 5296 | ref_frame, |
| 5297 | mode: InterMode::NearestMv, |
| 5298 | mv: gstack.nearest_mv, |
| 5299 | ref_mv_idx: 0, |
| 5300 | }, |
| 5301 | )); |
| 5302 | cands.push(( |
| 5303 | (0, 0), |
| 5304 | g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0), |
| 5305 | InterInfo { |
| 5306 | ref1: None, |
| 5307 | mv1: (0, 0), |
| 5308 | ref_frame, |
| 5309 | mode: InterMode::GlobalMv, |
| 5310 | mv: (0, 0), |
| 5311 | ref_mv_idx: 0, |
| 5312 | }, |
| 5313 | )); |
| 5314 | |
| 5315 | |
| 5316 | |
| 5317 | |
| 5318 | |
| 5319 | |
| 5320 | |
| 5321 | |
| 5322 | let margin = extra_new_skip_margin(); |
| 5323 | let skip_search = extra_ref_new_mv() |
| 5324 | && margin > 0.0 |
| 5325 | && motion::cost_at( |
| 5326 | &g.y, |
| 5327 | g.width, |
| 5328 | luma.true_width, |
| 5329 | luma.true_height, |
| 5330 | &source_block, |
| 5331 | x, |
| 5332 | y, |
| 5333 | BLOCK, |
| 5334 | BLOCK, |
| 5335 | gstack.nearest_mv, |
| 5336 | gstack.pred_mv, |
| 5337 | search.lambda, |
| 5338 | fctx, |
| 5339 | ) * margin |
| 5340 | <= found.cost; |
| 5341 | if extra_ref_new_mv() && !skip_search { |
| 5342 | let (gseeds, gn) = mv_seeds(gstack); |
| 5343 | #[cfg(test)] |
| 5344 | let t = std::time::Instant::now(); |
| 5345 | let gfound = motion::search( |
| 5346 | &g.y, |
| 5347 | g.width, |
| 5348 | luma.true_width, |
| 5349 | luma.true_height, |
| 5350 | &source_block, |
| 5351 | x, |
| 5352 | y, |
| 5353 | BLOCK, |
| 5354 | BLOCK, |
| 5355 | gstack.pred_mv, |
| 5356 | &gseeds[..gn], |
| 5357 | search.lambda, fctx, |
| 5358 | ref_distance(ref_frame), |
| 5359 | ); |
| 5360 | #[cfg(test)] |
| 5361 | stage_add(0, t.elapsed()); |
| 5362 | let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv); |
| 5363 | extra_new_mvs.push((ref_frame, gmv)); |
| 5364 | if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) { |
| 5365 | cands.push(( |
| 5366 | gmv, |
| 5367 | g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits, |
| 5368 | InterInfo { |
| 5369 | ref1: None, |
| 5370 | mv1: (0, 0), |
| 5371 | ref_frame, |
| 5372 | mode: InterMode::NewMv, |
| 5373 | mv: gmv, |
| 5374 | ref_mv_idx, |
| 5375 | }, |
| 5376 | )); |
| 5377 | } |
| 5378 | } |
| 5379 | } |
| 5380 | |
| 5381 | |
| 5382 | |
| 5383 | |
| 5384 | |
| 5385 | |
| 5386 | |
| 5387 | |
| 5388 | |
| 5389 | |
| 5390 | |
| 5391 | let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR"); |
| 5392 | let half_new = true; |
| 5393 | for (ref1, g, cstack) in compound { |
| 5394 | let (ref1, g) = (*ref1, *g); |
| 5395 | let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME) |
| 5396 | .contains(&ref1); |
| 5397 | let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1) |
| 5398 | + if uni { |
| 5399 | |
| 5400 | |
| 5401 | symbol_bits(&cdf::COMP_REF_TYPE[0], 1) |
| 5402 | + symbol_bits(&cdf::COMP_REF[0][0], 0) |
| 5403 | + symbol_bits(&cdf::COMP_REF[0][1], 0) |
| 5404 | + symbol_bits(&cdf::COMP_BWDREF[0][0], 1) |
| 5405 | } else { |
| 5406 | |
| 5407 | symbol_bits(&cdf::COMP_REF_TYPE[0], 0) |
| 5408 | + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0) |
| 5409 | + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1) |
| 5410 | + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1) |
| 5411 | }; |
| 5412 | let mode_ctx = |
| 5413 | cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)]; |
| 5414 | let mode_bits_of = |
| 5415 | |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode); |
| 5416 | let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![ |
| 5417 | ( |
| 5418 | cstack.nearest_mv, |
| 5419 | mode_bits_of(0), |
| 5420 | InterInfo { |
| 5421 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5422 | mode: InterMode::NearestNearestMv, |
| 5423 | mv: cstack.nearest_mv.0, |
| 5424 | mv1: cstack.nearest_mv.1, |
| 5425 | ref1: Some(ref1), |
| 5426 | ref_mv_idx: 0, |
| 5427 | }, |
| 5428 | ), |
| 5429 | ( |
| 5430 | ((0, 0), (0, 0)), |
| 5431 | mode_bits_of(6), |
| 5432 | InterInfo { |
| 5433 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5434 | mode: InterMode::GlobalGlobalMv, |
| 5435 | mv: (0, 0), |
| 5436 | mv1: (0, 0), |
| 5437 | ref1: Some(ref1), |
| 5438 | ref_mv_idx: 0, |
| 5439 | }, |
| 5440 | ), |
| 5441 | ]; |
| 5442 | |
| 5443 | |
| 5444 | |
| 5445 | if let Some(e) = cstack.entries.get(1).filter(|_| near_near) { |
| 5446 | let drl = if cstack.entries.len() > 2 { |
| 5447 | symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0) |
| 5448 | } else { |
| 5449 | 0.0 |
| 5450 | }; |
| 5451 | ccands.push(( |
| 5452 | (e.mv0, e.mv1), |
| 5453 | mode_bits_of(1) + drl, |
| 5454 | InterInfo { |
| 5455 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5456 | mode: InterMode::NearNearMv, |
| 5457 | mv: e.mv0, |
| 5458 | mv1: e.mv1, |
| 5459 | ref1: Some(ref1), |
| 5460 | ref_mv_idx: 0, |
| 5461 | }, |
| 5462 | )); |
| 5463 | } |
| 5464 | |
| 5465 | |
| 5466 | |
| 5467 | |
| 5468 | let cbase = cstack |
| 5469 | .entries |
| 5470 | .first() |
| 5471 | .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1)); |
| 5472 | if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) { |
| 5473 | ccands.push(( |
| 5474 | (mv, cstack.nearest_mv.1), |
| 5475 | mode_bits_of(3) + b0, |
| 5476 | InterInfo { |
| 5477 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5478 | mode: InterMode::NewNearestMv, |
| 5479 | mv, |
| 5480 | mv1: cstack.nearest_mv.1, |
| 5481 | ref1: Some(ref1), |
| 5482 | ref_mv_idx: 0, |
| 5483 | }, |
| 5484 | )); |
| 5485 | } |
| 5486 | if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) { |
| 5487 | if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) { |
| 5488 | ccands.push(( |
| 5489 | (cstack.nearest_mv.0, mv1), |
| 5490 | mode_bits_of(2) + b1, |
| 5491 | InterInfo { |
| 5492 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5493 | mode: InterMode::NearestNewMv, |
| 5494 | mv: cstack.nearest_mv.0, |
| 5495 | mv1, |
| 5496 | ref1: Some(ref1), |
| 5497 | ref_mv_idx: 0, |
| 5498 | }, |
| 5499 | )); |
| 5500 | } |
| 5501 | let base = cbase; |
| 5502 | if let (Some(b0), Some(b1)) = ( |
| 5503 | mv_residual_bits(mv, base.0), |
| 5504 | mv_residual_bits(mv1, base.1), |
| 5505 | ) { |
| 5506 | ccands.push(( |
| 5507 | (mv, mv1), |
| 5508 | mode_bits_of(7) + b0 + b1, |
| 5509 | InterInfo { |
| 5510 | ref_frame: crate::mvstack::LAST_FRAME, |
| 5511 | mode: InterMode::NewNewMv, |
| 5512 | mv, |
| 5513 | mv1, |
| 5514 | ref1: Some(ref1), |
| 5515 | ref_mv_idx: 0, |
| 5516 | }, |
| 5517 | )); |
| 5518 | } |
| 5519 | } |
| 5520 | ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1))); |
| 5521 | ccands.dedup_by_key(|c| c.0); |
| 5522 | let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height); |
| 5523 | let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height); |
| 5524 | let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height); |
| 5525 | for (mvs, bits, info) in ccands { |
| 5526 | let luma_trial = mc_trial_compound( |
| 5527 | luma, x, y, BLOCK, mvs, true, |
| 5528 | (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma, |
| 5529 | search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx, |
| 5530 | ); |
| 5531 | let u = mc_trial_compound( |
| 5532 | &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false, |
| 5533 | (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u, |
| 5534 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 5535 | ); |
| 5536 | let v = mc_trial_compound( |
| 5537 | &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false, |
| 5538 | (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v, |
| 5539 | search.base_q_idx, search.deadzone, chroma_set, fctx, |
| 5540 | ); |
| 5541 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 5542 | && u.levels.iter().all(|&l| l == 0) |
| 5543 | && v.levels.iter().all(|&l| l == 0); |
| 5544 | let cost = luma_trial.sse |
| 5545 | + u.sse |
| 5546 | + v.sse |
| 5547 | + search.lambda |
| 5548 | * (skip_bits(skip) |
| 5549 | + intra_inter_bits(true) |
| 5550 | + bits |
| 5551 | + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits }); |
| 5552 | consider(Candidate { |
| 5553 | cost, |
| 5554 | luma: luma_trial, |
| 5555 | u, |
| 5556 | v, |
| 5557 | mode: DC_PRED, |
| 5558 | skip, |
| 5559 | inter: Some(info), |
| 5560 | }); |
| 5561 | } |
| 5562 | } |
| 5563 | |
| 5564 | |
| 5565 | |
| 5566 | cands.sort_by(|a, b| { |
| 5567 | (a.2.ref_frame, a.0) |
| 5568 | .cmp(&(b.2.ref_frame, b.0)) |
| 5569 | .then(a.1.total_cmp(&b.1)) |
| 5570 | }); |
| 5571 | cands.dedup_by_key(|c| (c.2.ref_frame, c.0)); |
| 5572 | census_add(7, cands.len()); |
| 5573 | { |
| 5574 | for (mv, mode_bits_inter, info) in cands { |
| 5575 | let (ref_luma, ref_u, ref_v) = match extra |
| 5576 | .iter() |
| 5577 | .find(|(r, _, _)| *r == info.ref_frame) |
| 5578 | { |
| 5579 | Some(&(_, g, _)) => ( |
| 5580 | (&g.y, g.width, luma.true_width, luma.true_height), |
| 5581 | (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height), |
| 5582 | (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height), |
| 5583 | ), |
| 5584 | None => (ref_luma, ref_u, ref_v), |
| 5585 | }; |
| 5586 | let luma_trial = mc_trial( |
| 5587 | luma, |
| 5588 | x, |
| 5589 | y, |
| 5590 | BLOCK, |
| 5591 | mv, |
| 5592 | true, |
| 5593 | ref_luma.0, |
| 5594 | ref_luma.1, |
| 5595 | ref_luma.2, |
| 5596 | ref_luma.3, |
| 5597 | false, |
| 5598 | search.base_q_idx, |
| 5599 | search.deadzone, |
| 5600 | TxbSet::Luma32Inter, fctx, |
| 5601 | ); |
| 5602 | let u = mc_trial( |
| 5603 | &chroma[0], |
| 5604 | x / 2, |
| 5605 | y / 2, |
| 5606 | BLOCK / 2, |
| 5607 | mv, |
| 5608 | false, |
| 5609 | ref_u.0, |
| 5610 | ref_u.1, |
| 5611 | ref_u.2, |
| 5612 | ref_u.3, |
| 5613 | false, |
| 5614 | search.base_q_idx, |
| 5615 | search.deadzone, |
| 5616 | chroma_set, fctx, |
| 5617 | ); |
| 5618 | let v = mc_trial( |
| 5619 | &chroma[1], |
| 5620 | x / 2, |
| 5621 | y / 2, |
| 5622 | BLOCK / 2, |
| 5623 | mv, |
| 5624 | false, |
| 5625 | ref_v.0, |
| 5626 | ref_v.1, |
| 5627 | ref_v.2, |
| 5628 | ref_v.3, |
| 5629 | false, |
| 5630 | search.base_q_idx, |
| 5631 | search.deadzone, |
| 5632 | chroma_set, fctx, |
| 5633 | ); |
| 5634 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 5635 | && u.levels.iter().all(|&l| l == 0) |
| 5636 | && v.levels.iter().all(|&l| l == 0); |
| 5637 | let cost = luma_trial.sse |
| 5638 | + u.sse |
| 5639 | + v.sse |
| 5640 | + search.lambda |
| 5641 | * (skip_bits(skip) |
| 5642 | + intra_inter_bits(true) |
| 5643 | + mode_bits_inter |
| 5644 | + if skip { |
| 5645 | 0.0 |
| 5646 | } else { |
| 5647 | luma_trial.bits + u.bits + v.bits |
| 5648 | }); |
| 5649 | consider(Candidate { |
| 5650 | cost, |
| 5651 | luma: luma_trial, |
| 5652 | u, |
| 5653 | v, |
| 5654 | mode: DC_PRED, |
| 5655 | skip, |
| 5656 | inter: Some(info), |
| 5657 | }); |
| 5658 | } |
| 5659 | } |
| 5660 | |
| 5661 | let best = best.expect("the search offers at least the intra modes"); |
| 5662 | luma.commit(x, y, BLOCK, &best.luma); |
| 5663 | chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u); |
| 5664 | chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); |
| 5665 | ( |
| 5666 | BlockCoeffs { |
| 5667 | luma: coeffs(&best.luma.levels, BLOCK), |
| 5668 | u: coeffs(&best.u.levels, BLOCK / 2), |
| 5669 | v: coeffs(&best.v.levels, BLOCK / 2), |
| 5670 | mode: best.mode, |
| 5671 | uv_mode: DC_PRED, |
| 5672 | skip: best.skip, |
| 5673 | inter: best.inter, |
| 5674 | eight: None, |
| 5675 | palette: None, |
| 5676 | palette_uv: None, |
| 5677 | tx_depth: 0, |
| 5678 | }, |
| 5679 | best.cost, |
| 5680 | ) |
| 5681 | } |
| 5682 | |
| 5683 | |
| 5684 | |
| 5685 | |
| 5686 | |
| 5687 | |
| 5688 | |
| 5689 | |
| 5690 | |
| 5691 | |
| 5692 | |
| 5693 | #[derive(Debug, Clone, Copy)] |
| 5694 | pub(crate) struct PyramidFrame { |
| 5695 | |
| 5696 | |
| 5697 | pub last_slot: u8, |
| 5698 | |
| 5699 | pub self_slot: u8, |
| 5700 | |
| 5701 | |
| 5702 | pub altref_slot: u8, |
| 5703 | |
| 5704 | |
| 5705 | pub show_frame: bool, |
| 5706 | |
| 5707 | pub sign_bias: crate::mvstack::SignBiasTable, |
| 5708 | } |
| 5709 | |
| 5710 | |
| 5711 | |
| 5712 | |
| 5713 | pub(crate) fn encode_inter_frame( |
| 5714 | picture: &Picture, |
| 5715 | reference: &Picture, |
| 5716 | base_q_idx: u8, |
| 5717 | deadzone: f64, |
| 5718 | order_hint: u32, |
| 5719 | |
| 5720 | |
| 5721 | |
| 5722 | |
| 5723 | |
| 5724 | order_hints: [u32; 7], |
| 5725 | render: (usize, usize), |
| 5726 | |
| 5727 | |
| 5728 | |
| 5729 | |
| 5730 | start_cdfs: Option<&crate::cdf_state::Cdfs>, |
| 5731 | |
| 5732 | |
| 5733 | |
| 5734 | golden: Option<&Picture>, |
| 5735 | |
| 5736 | |
| 5737 | |
| 5738 | altref: Option<&Picture>, fctx: &crate::decode::FrameCtx, |
| 5739 | |
| 5740 | |
| 5741 | pyramid: Option<PyramidFrame>, |
| 5742 | ) -> Result<Encoded> { |
| 5743 | picture.check()?; |
| 5744 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| 5745 | return Err(Error::unsupported( |
| 5746 | "AV1 encode", |
| 5747 | "an inter frame is coded only for a picture that is a whole number \ |
| 5748 | of 64x64 superblocks -- the inter tile writer never splits a \ |
| 5749 | superblock's partition below that", |
| 5750 | )); |
| 5751 | } |
| 5752 | if reference.width != picture.width || reference.height != picture.height { |
| 5753 | return Err(Error::unsupported( |
| 5754 | "AV1 encode", |
| 5755 | "the reference picture must be the same size as the one being coded", |
| 5756 | )); |
| 5757 | } |
| 5758 | |
| 5759 | |
| 5760 | |
| 5761 | |
| 5762 | |
| 5763 | const LAST_SLOT: u8 = 0; |
| 5764 | |
| 5765 | |
| 5766 | |
| 5767 | |
| 5768 | let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot); |
| 5769 | let last_slot = pyramid.map_or( |
| 5770 | if order_hint <= 1 { |
| 5771 | LAST_SLOT |
| 5772 | } else if (order_hint - 1) % 2 == 1 { |
| 5773 | 0 |
| 5774 | } else { |
| 5775 | 2 |
| 5776 | }, |
| 5777 | |p| p.last_slot, |
| 5778 | ); |
| 5779 | |
| 5780 | |
| 5781 | |
| 5782 | |
| 5783 | |
| 5784 | |
| 5785 | let (seq, mut header) = inter_frame_headers_slots( |
| 5786 | render.0, |
| 5787 | render.1, |
| 5788 | base_q_idx, |
| 5789 | order_hint, |
| 5790 | last_slot, |
| 5791 | self_slot, |
| 5792 | match pyramid { |
| 5793 | Some(p) => p.altref_slot, |
| 5794 | None if altref.is_some() => self_slot, |
| 5795 | None => GOLDEN_SLOT, |
| 5796 | }, |
| 5797 | )?; |
| 5798 | header.render_width = render.0 as u32; |
| 5799 | header.render_height = render.1 as u32; |
| 5800 | let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias); |
| 5801 | |
| 5802 | |
| 5803 | |
| 5804 | |
| 5805 | |
| 5806 | |
| 5807 | header.order_hints = order_hints; |
| 5808 | header.reference_select = reference_select(); |
| 5809 | |
| 5810 | |
| 5811 | |
| 5812 | |
| 5813 | |
| 5814 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 5815 | if let Some(p) = pyramid { |
| 5816 | header.show_frame = p.show_frame; |
| 5817 | header.showable_frame = !p.show_frame; |
| 5818 | header.ref_frame_sign_bias = p.sign_bias; |
| 5819 | } |
| 5820 | |
| 5821 | |
| 5822 | |
| 5823 | |
| 5824 | let tx_select = tx_select() && tx_select_inter(); |
| 5825 | if tx_select { |
| 5826 | header.tx_mode = TxMode::Select; |
| 5827 | } |
| 5828 | |
| 5829 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 5830 | |
| 5831 | |
| 5832 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 5833 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 5834 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 5835 | |
| 5836 | |
| 5837 | |
| 5838 | |
| 5839 | |
| 5840 | let screen = seq_screen() |
| 5841 | && screen_content(&picture_y8, picture.width, true_width, true_height); |
| 5842 | header.allow_screen_content_tools = screen; |
| 5843 | let mut luma = Plane { |
| 5844 | source: &picture_y8, |
| 5845 | reconstruction: vec![128; picture_y8.len()], |
| 5846 | width: picture.width, |
| 5847 | height: picture.height, |
| 5848 | true_width, |
| 5849 | true_height, |
| 5850 | tile_x0: 0, |
| 5851 | tile_y0: 0, |
| 5852 | tile_x1: picture.width, |
| 5853 | tile_y1: picture.height, |
| 5854 | }; |
| 5855 | let mut chroma = [ |
| 5856 | Plane { |
| 5857 | source: &picture_u8, |
| 5858 | reconstruction: vec![128; picture_u8.len()], |
| 5859 | width: picture.width / 2, |
| 5860 | height: picture.height / 2, |
| 5861 | true_width: true_width / 2, |
| 5862 | true_height: true_height / 2, |
| 5863 | tile_x0: 0, |
| 5864 | tile_y0: 0, |
| 5865 | tile_x1: picture.width / 2, |
| 5866 | tile_y1: picture.height / 2, |
| 5867 | }, |
| 5868 | Plane { |
| 5869 | source: &picture_v8, |
| 5870 | reconstruction: vec![128; picture_v8.len()], |
| 5871 | width: picture.width / 2, |
| 5872 | height: picture.height / 2, |
| 5873 | true_width: true_width / 2, |
| 5874 | true_height: true_height / 2, |
| 5875 | tile_x0: 0, |
| 5876 | tile_y0: 0, |
| 5877 | tile_x1: picture.width / 2, |
| 5878 | tile_y1: picture.height / 2, |
| 5879 | }, |
| 5880 | ]; |
| 5881 | |
| 5882 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 5883 | let search = Search { |
| 5884 | base_q_idx, |
| 5885 | deadzone, |
| 5886 | lambda: lambda_scale() * step * step, |
| 5887 | modes: &KEY_FRAME_MODES, |
| 5888 | top_k: prune_top_k_inter(), |
| 5889 | screen, |
| 5890 | }; |
| 5891 | let mode_bits_table = inter_mode_bits(); |
| 5892 | |
| 5893 | |
| 5894 | |
| 5895 | |
| 5896 | |
| 5897 | |
| 5898 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 5899 | let (cols, rows) = (cols as usize, rows as usize); |
| 5900 | let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 5901 | let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize); |
| 5902 | |
| 5903 | let (tile_cols_log2, tile_rows_log2) = armed_tiles(); |
| 5904 | let layout = |
| 5905 | crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2); |
| 5906 | header.tile_info = tile_info_of(&layout, 1); |
| 5907 | let header_tile_info = header.tile_info.clone(); |
| 5908 | |
| 5909 | |
| 5910 | |
| 5911 | |
| 5912 | let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows]; |
| 5913 | |
| 5914 | |
| 5915 | |
| 5916 | |
| 5917 | |
| 5918 | |
| 5919 | |
| 5920 | let (frame_width, frame_height) = (picture.width, picture.height); |
| 5921 | let luma_out = crate::par::Shared::new(&mut luma.reconstruction); |
| 5922 | let [cb, cr] = &mut chroma; |
| 5923 | let chroma_out = [ |
| 5924 | crate::par::Shared::new(&mut cb.reconstruction), |
| 5925 | crate::par::Shared::new(&mut cr.reconstruction), |
| 5926 | ]; |
| 5927 | let search_tile = |index: usize, |
| 5928 | fctx: &crate::decode::FrameCtx| |
| 5929 | -> Result<Vec<(usize, Quadrant)>> { |
| 5930 | |
| 5931 | |
| 5932 | |
| 5933 | |
| 5934 | crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints); |
| 5935 | let rect = layout.rect(index); |
| 5936 | let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height); |
| 5937 | let mut chroma = [ |
| 5938 | fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 5939 | fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2), |
| 5940 | ]; |
| 5941 | clip_planes_to_tile(&mut luma, &mut chroma, rect); |
| 5942 | let mut grid = MiGrid::new(mi_cols, mi_rows); |
| 5943 | grid.set_sign_bias(sign_bias); |
| 5944 | grid.set_tile_bounds( |
| 5945 | rect.mi_row0 as usize, |
| 5946 | rect.mi_col0 as usize, |
| 5947 | rect.mi_row1 as usize, |
| 5948 | rect.mi_col1 as usize, |
| 5949 | ); |
| 5950 | let mut blocks: Vec<(usize, Quadrant)> = Vec::new(); |
| 5951 | for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize { |
| 5952 | for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize { |
| 5953 | for quadrant in 0..4 { |
| 5954 | let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 5955 | |
| 5956 | |
| 5957 | if r32 >= rows || c32 >= cols { |
| 5958 | continue; |
| 5959 | } |
| 5960 | |
| 5961 | |
| 5962 | |
| 5963 | |
| 5964 | |
| 5965 | |
| 5966 | |
| 5967 | |
| 5968 | let (has_cols32, has_rows32) = ( |
| 5969 | crate::tile::has_half( |
| 5970 | c32 as u32 * crate::tile::BLOCK_MI, |
| 5971 | crate::tile::BLOCK_MI, |
| 5972 | header.mi_cols, |
| 5973 | ), |
| 5974 | crate::tile::has_half( |
| 5975 | r32 as u32 * crate::tile::BLOCK_MI, |
| 5976 | crate::tile::BLOCK_MI, |
| 5977 | header.mi_rows, |
| 5978 | ), |
| 5979 | ); |
| 5980 | if has_cols32 && has_rows32 { |
| 5981 | let (x, y) = (c32 * BLOCK, r32 * BLOCK); |
| 5982 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); |
| 5983 | let stack = |
| 5984 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); |
| 5985 | let extra_stacks: Vec<(i8, &Picture, MvStack)> = [ |
| 5986 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 5987 | (crate::mvstack::ALTREF_FRAME, altref), |
| 5988 | ] |
| 5989 | .into_iter() |
| 5990 | .filter_map(|(r, pic)| { |
| 5991 | pic.map(|p| { |
| 5992 | ( |
| 5993 | r, |
| 5994 | p, |
| 5995 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows), |
| 5996 | ) |
| 5997 | }) |
| 5998 | }) |
| 5999 | .collect(); |
| 6000 | let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks |
| 6001 | .iter() |
| 6002 | .map(|(r, p, st)| (*r, *p, st)) |
| 6003 | .collect(); |
| 6004 | |
| 6005 | |
| 6006 | |
| 6007 | |
| 6008 | let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 6009 | if header.reference_select { |
| 6010 | extra_stacks |
| 6011 | .iter() |
| 6012 | .map(|&(r, p, _)| { |
| 6013 | ( |
| 6014 | r, |
| 6015 | p, |
| 6016 | crate::mvstack::find_mv_stack_compound( |
| 6017 | &grid, |
| 6018 | mi_row, |
| 6019 | mi_col, |
| 6020 | 8, |
| 6021 | 8, |
| 6022 | (crate::mvstack::LAST_FRAME, r), |
| 6023 | mi_cols, |
| 6024 | mi_rows, |
| 6025 | grid.sign_bias_table(), |
| 6026 | &[(0, 0); 7], |
| 6027 | None, |
| 6028 | ), |
| 6029 | ) |
| 6030 | }) |
| 6031 | .collect() |
| 6032 | } else { |
| 6033 | Vec::new() |
| 6034 | }; |
| 6035 | |
| 6036 | let base = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 6037 | let (block, mut cost_whole) = search_inter_block( |
| 6038 | &mut luma, |
| 6039 | &mut chroma, |
| 6040 | (x, y), |
| 6041 | &search, |
| 6042 | &mode_bits_table, |
| 6043 | reference, |
| 6044 | &stack, |
| 6045 | &extra, |
| 6046 | &compound, fctx, |
| 6047 | ); |
| 6048 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 6049 | let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK); |
| 6050 | |
| 6051 | |
| 6052 | |
| 6053 | |
| 6054 | |
| 6055 | |
| 6056 | |
| 6057 | |
| 6058 | |
| 6059 | |
| 6060 | |
| 6061 | |
| 6062 | |
| 6063 | let leaf_positions: Vec<(usize, usize)> = (0..4) |
| 6064 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 6065 | .collect(); |
| 6066 | let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| { |
| 6067 | crate::tile::has_half( |
| 6068 | sc as u32 * crate::tile::SUB_MI, |
| 6069 | crate::tile::SUB_MI, |
| 6070 | header.mi_cols, |
| 6071 | ) && crate::tile::has_half( |
| 6072 | sr as u32 * crate::tile::SUB_MI, |
| 6073 | crate::tile::SUB_MI, |
| 6074 | header.mi_rows, |
| 6075 | ) |
| 6076 | }); |
| 6077 | |
| 6078 | |
| 6079 | let breakout = split_breakout_coeffs(); |
| 6080 | let split = (!block.skip |
| 6081 | && !split_rd_breakout(cost_whole, BLOCK, search.lambda) |
| 6082 | && (breakout == 0 || block.luma.len() > 4 * breakout) |
| 6083 | && leaves_legal |
| 6084 | && split_inter_blocks()) |
| 6085 | .then(|| { |
| 6086 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &base); |
| 6087 | let mut cost = search.lambda * partition_bits(BLOCK, true); |
| 6088 | let mut leaves = Vec::with_capacity(4); |
| 6089 | for &(sr, sc) in &leaf_positions { |
| 6090 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 6091 | let (lx, ly) = (sc * SUB, sr * SUB); |
| 6092 | let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 6093 | let stack = find_mv_stack( |
| 6094 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 6095 | ); |
| 6096 | let cstacks: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 6097 | if header.reference_select && leaf_compound() { |
| 6098 | [ |
| 6099 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 6100 | (crate::mvstack::ALTREF_FRAME, altref), |
| 6101 | ] |
| 6102 | .into_iter() |
| 6103 | .filter_map(|(r, pic)| { |
| 6104 | pic.map(|p| { |
| 6105 | ( |
| 6106 | r, |
| 6107 | p, |
| 6108 | crate::mvstack::find_mv_stack_compound( |
| 6109 | &grid, mi_row, mi_col, 4, 4, |
| 6110 | (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows, |
| 6111 | grid.sign_bias_table(), &[(0, 0); 7], None, |
| 6112 | ), |
| 6113 | ) |
| 6114 | }) |
| 6115 | }) |
| 6116 | .collect() |
| 6117 | } else { |
| 6118 | Vec::new() |
| 6119 | }; |
| 6120 | let (leaf, leaf_cost) = code_square_inter( |
| 6121 | &mut luma, |
| 6122 | &mut chroma, |
| 6123 | (lx, ly), |
| 6124 | SUB, |
| 6125 | &search, |
| 6126 | &mode_bits_table, |
| 6127 | reference, |
| 6128 | &stack, &cstacks, fctx, |
| 6129 | ); |
| 6130 | let leaf_cost = leaf_cost |
| 6131 | + search.lambda * partition_bits(SUB, false); |
| 6132 | let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB); |
| 6133 | |
| 6134 | |
| 6135 | |
| 6136 | |
| 6137 | |
| 6138 | |
| 6139 | let eight = (!leaf.skip |
| 6140 | && !split_rd_breakout(leaf_cost, SUB, search.lambda) |
| 6141 | && (breakout == 0 || leaf.luma.len() > breakout) |
| 6142 | && split_inter_8()) |
| 6143 | .then(|| { |
| 6144 | restore( |
| 6145 | &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base, |
| 6146 | ); |
| 6147 | let mut cost8 = search.lambda |
| 6148 | * (partition_bits(SUB, true) |
| 6149 | + 4.0 * partition_bits(8, false)); |
| 6150 | let mut eight = Vec::with_capacity(4); |
| 6151 | for i in 0..4 { |
| 6152 | let (mr, mc) = |
| 6153 | (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2); |
| 6154 | let stack8 = find_mv_stack( |
| 6155 | &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 6156 | ); |
| 6157 | let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = |
| 6158 | if header.reference_select && leaf_compound() { |
| 6159 | [ |
| 6160 | (crate::mvstack::GOLDEN_FRAME, golden), |
| 6161 | (crate::mvstack::ALTREF_FRAME, altref), |
| 6162 | ] |
| 6163 | .into_iter() |
| 6164 | .filter_map(|(r, pic)| { |
| 6165 | pic.map(|p| { |
| 6166 | ( |
| 6167 | r, |
| 6168 | p, |
| 6169 | crate::mvstack::find_mv_stack_compound( |
| 6170 | &grid, mr, mc, 2, 2, |
| 6171 | (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows, |
| 6172 | grid.sign_bias_table(), &[(0, 0); 7], None, |
| 6173 | ), |
| 6174 | ) |
| 6175 | }) |
| 6176 | }) |
| 6177 | .collect() |
| 6178 | } else { |
| 6179 | Vec::new() |
| 6180 | }; |
| 6181 | let (leaf8, cost) = code_square_inter( |
| 6182 | &mut luma, |
| 6183 | &mut chroma, |
| 6184 | (lx + (i % 2) * 8, ly + (i / 2) * 8), |
| 6185 | 8, |
| 6186 | &search, |
| 6187 | &mode_bits_table, |
| 6188 | reference, |
| 6189 | &stack8, &cstacks8, fctx, |
| 6190 | ); |
| 6191 | cost8 += cost; |
| 6192 | record_mi(&mut grid, mr, mc, 2, leaf8.inter); |
| 6193 | eight.push(leaf8); |
| 6194 | } |
| 6195 | (eight, cost8) |
| 6196 | }); |
| 6197 | match eight { |
| 6198 | Some((eight, cost8)) if cost8 < leaf_cost => { |
| 6199 | partition_hit(3); |
| 6200 | cost += cost8; |
| 6201 | leaves.push(BlockCoeffs { |
| 6202 | eight: Some(eight), |
| 6203 | ..BlockCoeffs::default() |
| 6204 | }); |
| 6205 | continue; |
| 6206 | } |
| 6207 | Some(_) => restore( |
| 6208 | &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf, |
| 6209 | ), |
| 6210 | None => {} |
| 6211 | } |
| 6212 | partition_hit(2); |
| 6213 | cost += leaf_cost; |
| 6214 | record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter); |
| 6215 | leaves.push(leaf); |
| 6216 | } |
| 6217 | (leaves, cost) |
| 6218 | }); |
| 6219 | if let Some((leaves, cost)) = split { |
| 6220 | if cost < cost_whole { |
| 6221 | |
| 6222 | |
| 6223 | |
| 6224 | partition_hit(1); |
| 6225 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 6226 | continue; |
| 6227 | } |
| 6228 | restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole); |
| 6229 | } |
| 6230 | partition_hit(0); |
| 6231 | record_mi(&mut grid, mi_row, mi_col, 8, block.inter); |
| 6232 | blocks.push((r32 * cols + c32, Quadrant::Whole(block))); |
| 6233 | } else { |
| 6234 | |
| 6235 | |
| 6236 | let sub_positions: Vec<(usize, usize)> = (0..4) |
| 6237 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 6238 | .filter(|&(sr, sc)| { |
| 6239 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 6240 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 6241 | }) |
| 6242 | .collect(); |
| 6243 | |
| 6244 | |
| 6245 | |
| 6246 | |
| 6247 | |
| 6248 | |
| 6249 | |
| 6250 | |
| 6251 | |
| 6252 | let mut leaves = Vec::with_capacity(sub_positions.len()); |
| 6253 | for (sr, sc) in sub_positions { |
| 6254 | let (has_cols16, has_rows16) = ( |
| 6255 | crate::tile::has_half( |
| 6256 | sc as u32 * crate::tile::SUB_MI, |
| 6257 | crate::tile::SUB_MI, |
| 6258 | header.mi_cols, |
| 6259 | ), |
| 6260 | crate::tile::has_half( |
| 6261 | sr as u32 * crate::tile::SUB_MI, |
| 6262 | crate::tile::SUB_MI, |
| 6263 | header.mi_rows, |
| 6264 | ), |
| 6265 | ); |
| 6266 | if !has_cols16 && !has_rows16 { |
| 6267 | return Err(Error::unsupported( |
| 6268 | "AV1 encode", |
| 6269 | format!( |
| 6270 | "the 16x16 block at ({sc},{sr}) straddles the true \ |
| 6271 | frame edge in a way that needs a rectangular \ |
| 6272 | (HORZ/VERT) transform this encoder does not code yet" |
| 6273 | ), |
| 6274 | )); |
| 6275 | } |
| 6276 | if has_cols16 && has_rows16 { |
| 6277 | let (x, y) = (sc * SUB, sr * SUB); |
| 6278 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 6279 | let stack = find_mv_stack( |
| 6280 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 6281 | ); |
| 6282 | let (block, _) = code_square_inter( |
| 6283 | &mut luma, |
| 6284 | &mut chroma, |
| 6285 | (x, y), |
| 6286 | SUB, |
| 6287 | &search, |
| 6288 | &mode_bits_table, |
| 6289 | reference, |
| 6290 | &stack, &[], fctx, |
| 6291 | ); |
| 6292 | |
| 6293 | |
| 6294 | |
| 6295 | |
| 6296 | |
| 6297 | |
| 6298 | record_mi(&mut grid, mi_row, mi_col, 4, block.inter); |
| 6299 | leaves.push(block); |
| 6300 | } else { |
| 6301 | let (x_sub, y_sub) = (sc * SUB, sr * SUB); |
| 6302 | let (mi_row0, mi_col0) = (sr * 4, sc * 4); |
| 6303 | let mut eight = Vec::with_capacity(2); |
| 6304 | for i in 0..4 { |
| 6305 | let leaf_x = x_sub + (i % 2) * 8; |
| 6306 | let leaf_y = y_sub + (i / 2) * 8; |
| 6307 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 6308 | continue; |
| 6309 | } |
| 6310 | let (mi_row, mi_col) = |
| 6311 | (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); |
| 6312 | let stack = find_mv_stack( |
| 6313 | &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 6314 | ); |
| 6315 | let (leaf, _) = code_square_inter( |
| 6316 | &mut luma, |
| 6317 | &mut chroma, |
| 6318 | (leaf_x, leaf_y), |
| 6319 | 8, |
| 6320 | &search, |
| 6321 | &mode_bits_table, |
| 6322 | reference, |
| 6323 | &stack, &[], fctx, |
| 6324 | ); |
| 6325 | |
| 6326 | |
| 6327 | record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter); |
| 6328 | eight.push(leaf); |
| 6329 | } |
| 6330 | leaves.push(BlockCoeffs { |
| 6331 | eight: Some(eight), |
| 6332 | ..BlockCoeffs::default() |
| 6333 | }); |
| 6334 | } |
| 6335 | } |
| 6336 | blocks.push((r32 * cols + c32, Quadrant::Split(leaves))); |
| 6337 | } |
| 6338 | } |
| 6339 | } |
| 6340 | } |
| 6341 | let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4); |
| 6342 | let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4); |
| 6343 | copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1); |
| 6344 | for (&out, tile) in chroma_out.iter().zip(&chroma) { |
| 6345 | copy_rect( |
| 6346 | out, |
| 6347 | &tile.reconstruction, |
| 6348 | frame_width / 2, |
| 6349 | x0 / 2, |
| 6350 | y0 / 2, |
| 6351 | x1.div_ceil(2), |
| 6352 | y1.div_ceil(2), |
| 6353 | ); |
| 6354 | } |
| 6355 | Ok(blocks) |
| 6356 | }; |
| 6357 | for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)? |
| 6358 | .into_iter() |
| 6359 | .flatten() |
| 6360 | { |
| 6361 | blocks[at] = quadrant; |
| 6362 | } |
| 6363 | |
| 6364 | let modes = blocks |
| 6365 | .iter() |
| 6366 | .flat_map(Quadrant::blocks) |
| 6367 | .map(|b| b.mode) |
| 6368 | .collect::<Vec<_>>(); |
| 6369 | let inter_block_share = blocks |
| 6370 | .iter() |
| 6371 | .flat_map(Quadrant::blocks) |
| 6372 | .filter(|b| b.inter.is_some()) |
| 6373 | .count() as f64 |
| 6374 | / modes.len() as f64; |
| 6375 | for block in blocks.iter().flat_map(Quadrant::blocks) { |
| 6376 | if let Some(info) = block.inter { |
| 6377 | let r = (info.ref_frame as usize).min(7); |
| 6378 | REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 6379 | } |
| 6380 | } |
| 6381 | #[cfg(test)] |
| 6382 | record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx)); |
| 6383 | |
| 6384 | |
| 6385 | |
| 6386 | |
| 6387 | let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows); |
| 6388 | let cdfs = start_cdfs |
| 6389 | .cloned() |
| 6390 | .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx))); |
| 6391 | let start_cdfs = CdfSnapshot(cdfs); |
| 6392 | let reference_select_bit = header.reference_select; |
| 6393 | let order_hint_bits = seq.order_hint_bits; |
| 6394 | let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32; |
| 6395 | let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32; |
| 6396 | |
| 6397 | |
| 6398 | |
| 6399 | let store_tile = layout.largest_tile(); |
| 6400 | let end_cdfs = std::cell::RefCell::new(None); |
| 6401 | |
| 6402 | |
| 6403 | let code_tiles = |bits: u8, |
| 6404 | sb_cols: usize, |
| 6405 | cdef_grid: &[u8], |
| 6406 | units: &[Option<crate::restoration::WienerInfo>]| |
| 6407 | -> Result<Vec<Vec<u8>>> { |
| 6408 | let (out, stored) = write_tiles(layout.count(), store_tile, |index| { |
| 6409 | crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec()); |
| 6410 | crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec()); |
| 6411 | crate::tile::arm_sign_bias(sign_bias); |
| 6412 | |
| 6413 | crate::tile::arm_reference_select(reference_select_bit); |
| 6414 | crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints); |
| 6415 | crate::tile::arm_screen(screen); |
| 6416 | let mut cdfs = start_cdfs.0.clone(); |
| 6417 | |
| 6418 | |
| 6419 | |
| 6420 | |
| 6421 | let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize); |
| 6422 | mv_grid.set_sign_bias(sign_bias); |
| 6423 | let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs( |
| 6424 | mi_cols, |
| 6425 | mi_rows, |
| 6426 | base_q_idx, |
| 6427 | &blocks, |
| 6428 | tx_select, |
| 6429 | &mut cdfs, |
| 6430 | layout.rect(index), |
| 6431 | &mut mv_grid, |
| 6432 | )?; |
| 6433 | Ok((bytes, Some(cdfs))) |
| 6434 | })?; |
| 6435 | if let Some(cdfs) = stored { |
| 6436 | *end_cdfs.borrow_mut() = Some(cdfs); |
| 6437 | } |
| 6438 | Ok(out) |
| 6439 | }; |
| 6440 | let mut tiles = code_tiles(0, sb_cols, &[], &[])?; |
| 6441 | |
| 6442 | |
| 6443 | |
| 6444 | |
| 6445 | |
| 6446 | |
| 6447 | |
| 6448 | |
| 6449 | let (fw, fh) = (header.frame_width as usize, header.frame_height as usize); |
| 6450 | let trial_ref = if (reference.width, reference.height) == (fw, fh) { |
| 6451 | reference.clone() |
| 6452 | } else { |
| 6453 | Picture { |
| 6454 | width: fw, |
| 6455 | height: fh, |
| 6456 | y: crop_plane(&reference.y, reference.width, fw, fh), |
| 6457 | u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2), |
| 6458 | v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2), |
| 6459 | } |
| 6460 | }; |
| 6461 | |
| 6462 | |
| 6463 | |
| 6464 | let trial_golden = golden.map(|g| { |
| 6465 | if (g.width, g.height) == (fw, fh) { |
| 6466 | g.clone() |
| 6467 | } else { |
| 6468 | Picture { |
| 6469 | width: fw, |
| 6470 | height: fh, |
| 6471 | y: crop_plane(&g.y, g.width, fw, fh), |
| 6472 | u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2), |
| 6473 | v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2), |
| 6474 | } |
| 6475 | } |
| 6476 | }); |
| 6477 | let trial_altref = altref.map(|a| { |
| 6478 | if (a.width, a.height) == (fw, fh) { |
| 6479 | a.clone() |
| 6480 | } else { |
| 6481 | Picture { |
| 6482 | width: fw, |
| 6483 | height: fh, |
| 6484 | y: crop_plane(&a.y, a.width, fw, fh), |
| 6485 | u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2), |
| 6486 | v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2), |
| 6487 | } |
| 6488 | } |
| 6489 | }); |
| 6490 | let mut refs: [Option<&Picture>; 8] = [None; 8]; |
| 6491 | refs[1] = Some(&trial_ref); |
| 6492 | refs[4] = trial_golden.as_ref(); |
| 6493 | refs[7] = trial_altref.as_ref(); |
| 6494 | let refpix = crate::decode::RefPix::ready(refs); |
| 6495 | pick_and_apply_filters( |
| 6496 | &mut header, |
| 6497 | &mut luma, |
| 6498 | &mut chroma, |
| 6499 | [&picture_y8, &picture_u8, &picture_v8], |
| 6500 | |
| 6501 | |
| 6502 | |
| 6503 | |
| 6504 | true, |
| 6505 | &mut tiles, |
| 6506 | search.lambda, |
| 6507 | fctx, |
| 6508 | |
| 6509 | |
| 6510 | |
| 6511 | |
| 6512 | |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units), |
| 6513 | |lf, cdef, h, tiles: &[Vec<u8>], lr| { |
| 6514 | let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect(); |
| 6515 | crate::decode::decode_inter_frame_tiles_lr( |
| 6516 | &payloads, |
| 6517 | &header_tile_info, |
| 6518 | h.mi_cols, |
| 6519 | h.mi_rows, |
| 6520 | base_q_idx, |
| 6521 | h.frame_width, |
| 6522 | h.frame_height, |
| 6523 | &refpix, |
| 6524 | cdef, |
| 6525 | lf, |
| 6526 | h.allow_high_precision_mv, |
| 6527 | h.force_integer_mv, |
| 6528 | Some(mc::InterpFilterKind::Regular), |
| 6529 | seq.enable_dual_filter, |
| 6530 | h.reference_select, |
| 6531 | tx_select, |
| 6532 | lr, |
| 6533 | |
| 6534 | |
| 6535 | |
| 6536 | Some(start_cdfs.0.clone()), |
| 6537 | sign_bias, |
| 6538 | h.allow_screen_content_tools, |
| 6539 | fctx, |
| 6540 | ) |
| 6541 | }, |
| 6542 | )?; |
| 6543 | let mut cdfs = end_cdfs |
| 6544 | .into_inner() |
| 6545 | .unwrap_or_else(|| start_cdfs.0.clone()); |
| 6546 | cdfs.reset_counts(); |
| 6547 | let next_cdfs = CdfSnapshot(cdfs); |
| 6548 | let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles); |
| 6549 | header.tile_info.tile_size_bytes = tile_size_bytes; |
| 6550 | let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes); |
| 6551 | let mut stream = temporal_delimiter(); |
| 6552 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 6553 | |
| 6554 | let [u, v] = chroma; |
| 6555 | Ok(Encoded { |
| 6556 | stream, |
| 6557 | modes, |
| 6558 | inter_block_share, |
| 6559 | reconstruction: Picture { |
| 6560 | width: luma.width, |
| 6561 | height: luma.height, |
| 6562 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 6563 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 6564 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 6565 | }, |
| 6566 | tile, |
| 6567 | mi_cols: header.mi_cols, |
| 6568 | mi_rows: header.mi_rows, |
| 6569 | base_q_idx, |
| 6570 | tx_select, |
| 6571 | screen, |
| 6572 | start_cdfs, |
| 6573 | next_cdfs, |
| 6574 | loop_filter: header.loop_filter, |
| 6575 | cdef: header.cdef, |
| 6576 | loop_restoration: header.loop_restoration, |
| 6577 | }) |
| 6578 | } |
| 6579 | |
| 6580 | |
| 6581 | |
| 6582 | |
| 6583 | |
| 6584 | #[derive(Clone, Debug)] |
| 6585 | pub struct EncodedSequence { |
| 6586 | |
| 6587 | |
| 6588 | |
| 6589 | |
| 6590 | pub stream: Vec<u8>, |
| 6591 | |
| 6592 | pub frames: Vec<Encoded>, |
| 6593 | } |
| 6594 | |
| 6595 | |
| 6596 | |
| 6597 | |
| 6598 | |
| 6599 | |
| 6600 | |
| 6601 | |
| 6602 | |
| 6603 | |
| 6604 | |
| 6605 | |
| 6606 | |
| 6607 | pub(crate) fn encode_sequence_with_ctx( |
| 6608 | pictures: &[Picture], |
| 6609 | base_q_idx: u8, |
| 6610 | deadzone: f64, fctx: &crate::decode::FrameCtx, |
| 6611 | ) -> Result<EncodedSequence> { |
| 6612 | let Some((first, rest)) = pictures.split_first() else { |
| 6613 | return Err(Error::unsupported( |
| 6614 | "AV1 encode", |
| 6615 | "a sequence needs at least one picture", |
| 6616 | )); |
| 6617 | }; |
| 6618 | first.check_even()?; |
| 6619 | let render = (first.width, first.height); |
| 6620 | |
| 6621 | |
| 6622 | |
| 6623 | |
| 6624 | |
| 6625 | let key = encode_key_frame_inner( |
| 6626 | &first.padded_to(SUPERBLOCK), |
| 6627 | base_q_idx, |
| 6628 | deadzone, |
| 6629 | &KEY_FRAME_MODES, |
| 6630 | split_blocks(), |
| 6631 | render, |
| 6632 | unspecified_color_config(), fctx, |
| 6633 | )?; |
| 6634 | let mut stream = key.stream.clone(); |
| 6635 | |
| 6636 | |
| 6637 | |
| 6638 | let golden = key.reconstruction.clone(); |
| 6639 | |
| 6640 | |
| 6641 | let mut prev2: Option<Picture> = None; |
| 6642 | let mut carried = key.next_cdfs.clone(); |
| 6643 | let mut reference = key.reconstruction.clone(); |
| 6644 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 6645 | for (i, picture) in rest.iter().enumerate() { |
| 6646 | picture.check_even()?; |
| 6647 | if (picture.width, picture.height) != render { |
| 6648 | return Err(Error::unsupported( |
| 6649 | "AV1 encode", |
| 6650 | "every picture in a sequence must be the same size as the first", |
| 6651 | )); |
| 6652 | } |
| 6653 | let order_hint = (i + 1) as u32; |
| 6654 | let inter = encode_inter_frame( |
| 6655 | &picture.padded_to(SUPERBLOCK), |
| 6656 | &reference, |
| 6657 | base_q_idx, |
| 6658 | deadzone, |
| 6659 | order_hint, |
| 6660 | flat_order_hints(order_hint, 0, prev2.is_some()), |
| 6661 | render, |
| 6662 | Some(&carried.0), |
| 6663 | Some(&golden), |
| 6664 | prev2.as_ref(), fctx, |
| 6665 | None, |
| 6666 | )?; |
| 6667 | stream.extend_from_slice(&inter.stream); |
| 6668 | carried = inter.next_cdfs.clone(); |
| 6669 | prev2 = Some(std::mem::replace( |
| 6670 | &mut reference, |
| 6671 | inter.reconstruction.clone(), |
| 6672 | )); |
| 6673 | frames.push(crop_encoded(&inter, render.0, render.1)); |
| 6674 | } |
| 6675 | Ok(EncodedSequence { stream, frames }) |
| 6676 | } |
| 6677 | |
| 6678 | #[cfg(test)] |
| 6679 | mod tests { |
| 6680 | |
| 6681 | |
| 6682 | |
| 6683 | |
| 6684 | |
| 6685 | |
| 6686 | |
| 6687 | |
| 6688 | |
| 6689 | |
| 6690 | #[test] |
| 6691 | fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { |
| 6692 | for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 6693 | let (bw_log2, bh_log2) = |
| 6694 | ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize); |
| 6695 | let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); |
| 6696 | for (name, table) in |
| 6697 | [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)] |
| 6698 | { |
| 6699 | assert_eq!( |
| 6700 | table.len() * 8, |
| 6701 | rows * cols, |
| 6702 | "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" |
| 6703 | ); |
| 6704 | let mut seen = vec![0u32; table.len() * 8]; |
| 6705 | for blk_row in 0..rows { |
| 6706 | for blk_col in 0..cols { |
| 6707 | let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); |
| 6708 | assert!( |
| 6709 | idx < seen.len(), |
| 6710 | "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" |
| 6711 | ); |
| 6712 | seen[idx] += 1; |
| 6713 | } |
| 6714 | } |
| 6715 | assert!( |
| 6716 | seen.iter().all(|&n| n == 1), |
| 6717 | "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ |
| 6718 | (row stride is not {cols})" |
| 6719 | ); |
| 6720 | } |
| 6721 | } |
| 6722 | } |
| 6723 | use super::*; |
| 6724 | use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED}; |
| 6725 | use std::io::Write; |
| 6726 | use std::process::{Command, Stdio}; |
| 6727 | |
| 6728 | |
| 6729 | |
| 6730 | |
| 6731 | |
| 6732 | |
| 6733 | |
| 6734 | |
| 6735 | |
| 6736 | |
| 6737 | |
| 6738 | |
| 6739 | |
| 6740 | |
| 6741 | |
| 6742 | |
| 6743 | |
| 6744 | |
| 6745 | |
| 6746 | |
| 6747 | |
| 6748 | #[test] |
| 6749 | fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { |
| 6750 | let fctx = &crate::decode::FrameCtx::new(); |
| 6751 | |
| 6752 | const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ |
| 6753 | (4, 8, 64, 9280, 64, 550), |
| 6754 | (8, 4, 64, 3712, 64, 9630), |
| 6755 | (8, 16, 16, 2352, 16, 134), |
| 6756 | (16, 8, 16, 960, 16, 2400), |
| 6757 | (16, 32, 4, 620, 4, 32), |
| 6758 | (32, 16, 4, 32, 4, 184), |
| 6759 | (32, 64, 1, 127, 1, 0), |
| 6760 | (64, 32, 1, 19, 1, 34), |
| 6761 | (4, 16, 32, 5472, 32, 14), |
| 6762 | (16, 4, 32, 960, 32, 6464), |
| 6763 | (8, 32, 8, 1400, 8, 2), |
| 6764 | (32, 8, 8, 32, 8, 1136), |
| 6765 | (16, 64, 2, 382, 2, 0), |
| 6766 | (64, 16, 2, 4, 2, 84), |
| 6767 | ]; |
| 6768 | |
| 6769 | |
| 6770 | |
| 6771 | |
| 6772 | fn libaom_reach( |
| 6773 | bw: usize, |
| 6774 | bh: usize, |
| 6775 | x: usize, |
| 6776 | y: usize, |
| 6777 | width: usize, |
| 6778 | height: usize, _fctx: &crate::decode::FrameCtx, |
| 6779 | ) -> (bool, bool) { |
| 6780 | let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); |
| 6781 | let (_bw_unit, bh_unit) = (bw / 4, bh / 4); |
| 6782 | let sb_mi_size = 16usize; |
| 6783 | let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; |
| 6784 | let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; |
| 6785 | let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; |
| 6786 | let (tr_table, bl_table) = rect_reach_tables(bw, bh); |
| 6787 | let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; |
| 6788 | |
| 6789 | let top_right = if y == 0 || x + bw >= width { |
| 6790 | false |
| 6791 | } else if blk_row_in_sb == 0 { |
| 6792 | |
| 6793 | |
| 6794 | true |
| 6795 | } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { |
| 6796 | false |
| 6797 | } else { |
| 6798 | bit(tr_table) |
| 6799 | }; |
| 6800 | |
| 6801 | let bottom_left = if x == 0 || y + bh >= height { |
| 6802 | false |
| 6803 | } else if blk_col_in_sb == 0 { |
| 6804 | |
| 6805 | (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size |
| 6806 | } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { |
| 6807 | false |
| 6808 | } else { |
| 6809 | bit(bl_table) |
| 6810 | }; |
| 6811 | (top_right, bottom_left) |
| 6812 | } |
| 6813 | for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { |
| 6814 | let (tr, bl) = rect_reach_tables(bw, bh); |
| 6815 | let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>(); |
| 6816 | assert_eq!( |
| 6817 | (tr.len(), sum(tr), bl.len(), sum(bl)), |
| 6818 | (tr_len, tr_sum, bl_len, bl_sum), |
| 6819 | "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" |
| 6820 | ); |
| 6821 | |
| 6822 | |
| 6823 | for sb_y in [0usize, 64] { |
| 6824 | for sb_x in [0usize, 64] { |
| 6825 | for y in (sb_y..sb_y + 64).step_by(bh) { |
| 6826 | for x in (sb_x..sb_x + 64).step_by(bw) { |
| 6827 | let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx); |
| 6828 | let want = libaom_reach(bw, bh, x, y, 256, 256, fctx); |
| 6829 | assert_eq!( |
| 6830 | (got.above_right, got.below_left), |
| 6831 | want, |
| 6832 | "{bw}x{bh} at ({x}, {y})" |
| 6833 | ); |
| 6834 | } |
| 6835 | } |
| 6836 | } |
| 6837 | } |
| 6838 | } |
| 6839 | } |
| 6840 | |
| 6841 | |
| 6842 | |
| 6843 | |
| 6844 | |
| 6845 | |
| 6846 | |
| 6847 | |
| 6848 | fn have_ffmpeg() -> bool { |
| 6849 | let present = Command::new("ffmpeg") |
| 6850 | .arg("-version") |
| 6851 | .stdout(Stdio::null()) |
| 6852 | .stderr(Stdio::null()) |
| 6853 | .status() |
| 6854 | .is_ok_and(|s| s.success()); |
| 6855 | assert!( |
| 6856 | present |
| 6857 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 6858 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 6859 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 6860 | ); |
| 6861 | present |
| 6862 | } |
| 6863 | |
| 6864 | |
| 6865 | fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { |
| 6866 | let mut child = Command::new("ffmpeg") |
| 6867 | .args([ |
| 6868 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 6869 | ]) |
| 6870 | .stdin(Stdio::piped()) |
| 6871 | .stdout(Stdio::piped()) |
| 6872 | .stderr(Stdio::piped()) |
| 6873 | .spawn() |
| 6874 | .expect("ffmpeg failed to start"); |
| 6875 | |
| 6876 | |
| 6877 | |
| 6878 | |
| 6879 | |
| 6880 | |
| 6881 | |
| 6882 | let mut stdin = child.stdin.take().expect("ffmpeg stdin"); |
| 6883 | let payload = stream.to_vec(); |
| 6884 | let writer = std::thread::spawn(move || { |
| 6885 | let _ = stdin.write_all(&payload); |
| 6886 | }); |
| 6887 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 6888 | writer.join().expect("ffmpeg stdin writer thread"); |
| 6889 | assert!( |
| 6890 | out.status.success(), |
| 6891 | "ffmpeg refused the stream: {}", |
| 6892 | String::from_utf8_lossy(&out.stderr) |
| 6893 | ); |
| 6894 | let (luma, chroma) = (width * height, width * height / 4); |
| 6895 | assert_eq!( |
| 6896 | out.stdout.len(), |
| 6897 | luma + 2 * chroma, |
| 6898 | "expected one 4:2:0 frame" |
| 6899 | ); |
| 6900 | Picture { |
| 6901 | width, |
| 6902 | height, |
| 6903 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 6904 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 6905 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 6906 | } |
| 6907 | } |
| 6908 | |
| 6909 | |
| 6910 | |
| 6911 | |
| 6912 | |
| 6913 | |
| 6914 | |
| 6915 | |
| 6916 | |
| 6917 | |
| 6918 | |
| 6919 | |
| 6920 | |
| 6921 | #[test] |
| 6922 | fn the_filter_search_picks_real_filters() { |
| 6923 | let fctx = &crate::decode::FrameCtx::new(); |
| 6924 | let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect(); |
| 6925 | let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap(); |
| 6926 | let fired = encoded |
| 6927 | .frames |
| 6928 | .iter() |
| 6929 | .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0) |
| 6930 | .count(); |
| 6931 | assert!( |
| 6932 | fired > 0, |
| 6933 | "no frame of this sequence chose any in-loop filtering: {:?}", |
| 6934 | encoded |
| 6935 | .frames |
| 6936 | .iter() |
| 6937 | .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0])) |
| 6938 | .collect::<Vec<_>>() |
| 6939 | ); |
| 6940 | |
| 6941 | |
| 6942 | |
| 6943 | let decoded = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 6944 | assert_eq!(decoded.len(), encoded.frames.len()); |
| 6945 | for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() { |
| 6946 | assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma"); |
| 6947 | assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U"); |
| 6948 | assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V"); |
| 6949 | } |
| 6950 | } |
| 6951 | |
| 6952 | fn test_card(width: usize, height: usize) -> Picture { |
| 6953 | let mut picture = Picture::grey(width, height); |
| 6954 | for y in 0..height { |
| 6955 | for x in 0..width { |
| 6956 | let gradient = x as f64 * 200.0 / width as f64; |
| 6957 | let ripple = 30.0 |
| 6958 | * (x as f64 * std::f64::consts::PI / 23.0).sin() |
| 6959 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 6960 | let edge = if x > width * 3 / 7 && y > height / 3 { |
| 6961 | 40.0 |
| 6962 | } else { |
| 6963 | 0.0 |
| 6964 | }; |
| 6965 | picture.y[y * width + x] = |
| 6966 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 6967 | } |
| 6968 | } |
| 6969 | for y in 0..height / 2 { |
| 6970 | for x in 0..width / 2 { |
| 6971 | let i = y * width / 2 + x; |
| 6972 | picture.u[i] = (100 + (x * 60 / (width / 2))) as u16; |
| 6973 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 6974 | } |
| 6975 | } |
| 6976 | picture |
| 6977 | } |
| 6978 | |
| 6979 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 6980 | let squared: f64 = a |
| 6981 | .iter() |
| 6982 | .zip(b) |
| 6983 | .map(|(&x, &y)| { |
| 6984 | let d = f64::from(x) - f64::from(y); |
| 6985 | d * d |
| 6986 | }) |
| 6987 | .sum(); |
| 6988 | if squared == 0.0 { |
| 6989 | return f64::INFINITY; |
| 6990 | } |
| 6991 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 6992 | } |
| 6993 | |
| 6994 | |
| 6995 | |
| 6996 | |
| 6997 | |
| 6998 | |
| 6999 | |
| 7000 | #[test] |
| 7001 | fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() { |
| 7002 | let fctx = &crate::decode::FrameCtx::new(); |
| 7003 | if !have_ffmpeg() { |
| 7004 | eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg"); |
| 7005 | return; |
| 7006 | } |
| 7007 | for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] { |
| 7008 | let picture = test_card(width, height); |
| 7009 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7010 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7011 | assert_eq!( |
| 7012 | decoded.y, encoded.reconstruction.y, |
| 7013 | "{width}x{height}: luma" |
| 7014 | ); |
| 7015 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 7016 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 7017 | } |
| 7018 | |
| 7019 | |
| 7020 | let (width, height) = (64usize, 64usize); |
| 7021 | let picture = test_card(width, height); |
| 7022 | let _ = take_tx_depth_hits(); |
| 7023 | for &q in &[15u8, 45, 100, 200] { |
| 7024 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 7025 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7026 | assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma"); |
| 7027 | assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); |
| 7028 | assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); |
| 7029 | } |
| 7030 | |
| 7031 | |
| 7032 | |
| 7033 | |
| 7034 | |
| 7035 | |
| 7036 | |
| 7037 | let depths = take_tx_depth_hits(); |
| 7038 | assert!( |
| 7039 | depths[1] + depths[2] > 0, |
| 7040 | "no block split its transform: depths {depths:?}" |
| 7041 | ); |
| 7042 | } |
| 7043 | |
| 7044 | |
| 7045 | |
| 7046 | |
| 7047 | #[cfg(test)] |
| 7048 | fn screen_card(width: usize, height: usize) -> Picture { |
| 7049 | const INK: [u16; 4] = [16, 90, 180, 235]; |
| 7050 | let mut picture = Picture::grey(width, height); |
| 7051 | for y in 0..height { |
| 7052 | for x in 0..width { |
| 7053 | let cell = (x / 24 + y / 24) % 2; |
| 7054 | let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20); |
| 7055 | picture.y[y * width + x] = INK[cell * 2 + bar]; |
| 7056 | } |
| 7057 | } |
| 7058 | |
| 7059 | |
| 7060 | |
| 7061 | |
| 7062 | |
| 7063 | const CHROMA_U: [u16; 4] = [96, 118, 150, 176]; |
| 7064 | const CHROMA_V: [u16; 4] = [148, 126, 104, 92]; |
| 7065 | for y in 0..height / 2 { |
| 7066 | for x in 0..width / 2 { |
| 7067 | let cell = (x / 12 + 2 * (y / 12)) % 4; |
| 7068 | picture.u[y * (width / 2) + x] = CHROMA_U[cell]; |
| 7069 | picture.v[y * (width / 2) + x] = CHROMA_V[cell]; |
| 7070 | } |
| 7071 | } |
| 7072 | picture |
| 7073 | } |
| 7074 | |
| 7075 | |
| 7076 | |
| 7077 | |
| 7078 | |
| 7079 | |
| 7080 | |
| 7081 | #[test] |
| 7082 | fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() { |
| 7083 | let fctx = &crate::decode::FrameCtx::new(); |
| 7084 | let (width, height) = (192usize, 96usize); |
| 7085 | let _ = crate::tile::take_palette_hits(); |
| 7086 | let picture = screen_card(width, height); |
| 7087 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7088 | assert!( |
| 7089 | encoded.screen, |
| 7090 | "the detector did not fire on screen content -- no palette syntax was coded at all" |
| 7091 | ); |
| 7092 | let hits = crate::tile::take_palette_hits(); |
| 7093 | assert!(hits[0] > 0, "no block took a palette: {hits:?}"); |
| 7094 | eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]); |
| 7095 | |
| 7096 | |
| 7097 | |
| 7098 | |
| 7099 | let uv_hits = crate::tile::take_palette_uv_hits(); |
| 7100 | assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}"); |
| 7101 | let uv_cached = crate::tile::take_palette_uv_cache_hits(); |
| 7102 | eprintln!( |
| 7103 | "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache", |
| 7104 | uv_hits[0], |
| 7105 | &uv_hits[2..] |
| 7106 | ); |
| 7107 | assert!( |
| 7108 | uv_cached > 0, |
| 7109 | "no chroma base colour came out of the neighbour cache -- \ |
| 7110 | `write_palette_colors_uv`'s cache half is unproven by the oracle below" |
| 7111 | ); |
| 7112 | let via_us = crate::stream::decode_stream(&encoded.stream).unwrap(); |
| 7113 | assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma"); |
| 7114 | assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U"); |
| 7115 | assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V"); |
| 7116 | if !have_ffmpeg() { |
| 7117 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 7118 | return; |
| 7119 | } |
| 7120 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7121 | assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma"); |
| 7122 | assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U"); |
| 7123 | assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V"); |
| 7124 | |
| 7125 | |
| 7126 | |
| 7127 | let moved: Vec<Picture> = (0..4) |
| 7128 | .map(|f| { |
| 7129 | let base = screen_card(width, height); |
| 7130 | let mut out = Picture::grey(width, height); |
| 7131 | for y in 0..height { |
| 7132 | for x in 0..width { |
| 7133 | let sx = (x + f * 7) % width; |
| 7134 | out.y[y * width + x] = base.y[y * width + sx]; |
| 7135 | } |
| 7136 | } |
| 7137 | for y in 0..height / 2 { |
| 7138 | for x in 0..width / 2 { |
| 7139 | let sx = (x + f * 3) % (width / 2); |
| 7140 | out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx]; |
| 7141 | out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx]; |
| 7142 | } |
| 7143 | } |
| 7144 | out |
| 7145 | }) |
| 7146 | .collect(); |
| 7147 | let _ = crate::tile::take_palette_hits(); |
| 7148 | let _ = crate::tile::take_palette_uv_hits(); |
| 7149 | let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap(); |
| 7150 | let gop_hits = crate::tile::take_palette_hits(); |
| 7151 | let gop_uv_hits = crate::tile::take_palette_uv_hits(); |
| 7152 | let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count(); |
| 7153 | eprintln!( |
| 7154 | "GOP: {} frames with screen tools after the key frame, {} palette blocks, \ |
| 7155 | {} chroma palette blocks", |
| 7156 | inter_screen, gop_hits[0], gop_uv_hits[0] |
| 7157 | ); |
| 7158 | assert!( |
| 7159 | gop_uv_hits[0] > 0, |
| 7160 | "no block of the GOP took a chroma palette: {gop_uv_hits:?}" |
| 7161 | ); |
| 7162 | assert!( |
| 7163 | inter_screen > 0, |
| 7164 | "no inter frame set allow_screen_content_tools" |
| 7165 | ); |
| 7166 | let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap(); |
| 7167 | for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() { |
| 7168 | assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma"); |
| 7169 | } |
| 7170 | if have_ffmpeg() { |
| 7171 | let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len()); |
| 7172 | for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() { |
| 7173 | assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma"); |
| 7174 | assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U"); |
| 7175 | assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V"); |
| 7176 | } |
| 7177 | } |
| 7178 | |
| 7179 | |
| 7180 | |
| 7181 | let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap(); |
| 7182 | assert!(!film.screen, "the detector fired on the film-shaped test card"); |
| 7183 | } |
| 7184 | |
| 7185 | |
| 7186 | |
| 7187 | |
| 7188 | |
| 7189 | |
| 7190 | |
| 7191 | |
| 7192 | |
| 7193 | #[test] |
| 7194 | fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() { |
| 7195 | let fctx = &crate::decode::FrameCtx::new(); |
| 7196 | if !have_ffmpeg() { |
| 7197 | eprintln!( |
| 7198 | "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg" |
| 7199 | ); |
| 7200 | return; |
| 7201 | } |
| 7202 | let (width, height) = (64usize, 64usize); |
| 7203 | let picture = Picture::grey(width, height); |
| 7204 | let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7205 | |
| 7206 | let (seq, _) = key_frame_headers(width, height, 100).unwrap(); |
| 7207 | let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); |
| 7208 | |
| 7209 | let residual_block = BlockCoeffs { |
| 7210 | luma: vec![Coeff { |
| 7211 | row: 0, |
| 7212 | col: 0, |
| 7213 | level: 4, |
| 7214 | }], |
| 7215 | u: Vec::new(), |
| 7216 | v: Vec::new(), |
| 7217 | mode: 0, |
| 7218 | uv_mode: 0, |
| 7219 | skip: false, |
| 7220 | eight: None, |
| 7221 | palette: None, |
| 7222 | palette_uv: None, |
| 7223 | tx_depth: 0, |
| 7224 | inter: Some(InterInfo { |
| 7225 | ref1: None, |
| 7226 | mv1: (0, 0), |
| 7227 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7228 | mode: InterMode::NearestMv, |
| 7229 | mv: (0, 0), |
| 7230 | ref_mv_idx: 0, |
| 7231 | }), |
| 7232 | }; |
| 7233 | let skipped_block = BlockCoeffs { |
| 7234 | skip: true, |
| 7235 | inter: Some(InterInfo { |
| 7236 | ref1: None, |
| 7237 | mv1: (0, 0), |
| 7238 | ref_frame: crate::mvstack::LAST_FRAME, |
| 7239 | mode: InterMode::NearestMv, |
| 7240 | mv: (0, 0), |
| 7241 | ref_mv_idx: 0, |
| 7242 | }), |
| 7243 | ..BlockCoeffs::default() |
| 7244 | }; |
| 7245 | let blocks = vec![ |
| 7246 | Quadrant::Whole(residual_block), |
| 7247 | Quadrant::Whole(skipped_block.clone()), |
| 7248 | Quadrant::Whole(skipped_block.clone()), |
| 7249 | Quadrant::Whole(skipped_block), |
| 7250 | ]; |
| 7251 | let tile = |
| 7252 | crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks) |
| 7253 | .unwrap(); |
| 7254 | |
| 7255 | |
| 7256 | |
| 7257 | |
| 7258 | |
| 7259 | |
| 7260 | let mut stream = key.stream.clone(); |
| 7261 | stream.extend_from_slice(&temporal_delimiter()); |
| 7262 | stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap()); |
| 7263 | |
| 7264 | ffmpeg_decode_sequence(&stream, width, height, 2); |
| 7265 | } |
| 7266 | |
| 7267 | |
| 7268 | |
| 7269 | |
| 7270 | fn ffprobe_size(stream: &[u8]) -> (u32, u32) { |
| 7271 | |
| 7272 | |
| 7273 | |
| 7274 | static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 7275 | let path = std::env::temp_dir().join(format!( |
| 7276 | "ec-av1-probe-{}-{}.obu", |
| 7277 | std::process::id(), |
| 7278 | PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) |
| 7279 | )); |
| 7280 | let _ = std::fs::remove_file(&path); |
| 7281 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 7282 | let out = Command::new("ffprobe") |
| 7283 | .args([ |
| 7284 | "-v", |
| 7285 | "error", |
| 7286 | "-f", |
| 7287 | "obu", |
| 7288 | "-select_streams", |
| 7289 | "v:0", |
| 7290 | "-show_entries", |
| 7291 | "stream=width,height", |
| 7292 | "-of", |
| 7293 | "csv=p=0", |
| 7294 | ]) |
| 7295 | .arg(&path) |
| 7296 | .output() |
| 7297 | .expect("ffprobe failed to run"); |
| 7298 | let _ = std::fs::remove_file(&path); |
| 7299 | assert!( |
| 7300 | out.status.success(), |
| 7301 | "ffprobe refused the stream: {}", |
| 7302 | String::from_utf8_lossy(&out.stderr) |
| 7303 | ); |
| 7304 | let text = String::from_utf8_lossy(&out.stdout); |
| 7305 | let mut fields = text.trim().split(','); |
| 7306 | let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); |
| 7307 | let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); |
| 7308 | (width, height) |
| 7309 | } |
| 7310 | |
| 7311 | |
| 7312 | |
| 7313 | |
| 7314 | |
| 7315 | |
| 7316 | |
| 7317 | |
| 7318 | |
| 7319 | |
| 7320 | |
| 7321 | |
| 7322 | |
| 7323 | |
| 7324 | |
| 7325 | #[test] |
| 7326 | fn a_frame_round_trips_at_its_own_size() { |
| 7327 | let fctx = &crate::decode::FrameCtx::new(); |
| 7328 | if !have_ffmpeg() { |
| 7329 | eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg"); |
| 7330 | return; |
| 7331 | } |
| 7332 | |
| 7333 | |
| 7334 | |
| 7335 | for &(width, height) in &[ |
| 7336 | (1920usize, 1080usize), |
| 7337 | (640, 352), |
| 7338 | (1280, 720), |
| 7339 | (64, 56), |
| 7340 | (854, 480), |
| 7341 | (216, 96), |
| 7342 | (192, 120), |
| 7343 | ] { |
| 7344 | let picture = test_card(width, height); |
| 7345 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7346 | assert_eq!( |
| 7347 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 7348 | (width, height), |
| 7349 | "{width}x{height}: reconstruction is cropped to the picture's own size" |
| 7350 | ); |
| 7351 | assert_eq!( |
| 7352 | ffprobe_size(&encoded.stream), |
| 7353 | (width as u32, height as u32), |
| 7354 | "{width}x{height}: ffprobe reports the true (display) size, not the padded one" |
| 7355 | ); |
| 7356 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7357 | assert_eq!( |
| 7358 | decoded.y, encoded.reconstruction.y, |
| 7359 | "{width}x{height}: luma" |
| 7360 | ); |
| 7361 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 7362 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 7363 | } |
| 7364 | } |
| 7365 | |
| 7366 | |
| 7367 | |
| 7368 | |
| 7369 | |
| 7370 | |
| 7371 | |
| 7372 | |
| 7373 | |
| 7374 | |
| 7375 | |
| 7376 | |
| 7377 | |
| 7378 | |
| 7379 | |
| 7380 | |
| 7381 | |
| 7382 | |
| 7383 | |
| 7384 | |
| 7385 | |
| 7386 | |
| 7387 | |
| 7388 | |
| 7389 | |
| 7390 | |
| 7391 | #[test] |
| 7392 | fn an_854x480_picture_round_trips_through_its_padding() { |
| 7393 | let fctx = &crate::decode::FrameCtx::new(); |
| 7394 | if !have_ffmpeg() { |
| 7395 | return; |
| 7396 | } |
| 7397 | let (width, height) = (854usize, 480usize); |
| 7398 | let picture = test_card(width, height); |
| 7399 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7400 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7401 | assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); |
| 7402 | assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); |
| 7403 | assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); |
| 7404 | } |
| 7405 | |
| 7406 | |
| 7407 | |
| 7408 | |
| 7409 | |
| 7410 | |
| 7411 | |
| 7412 | |
| 7413 | |
| 7414 | |
| 7415 | |
| 7416 | |
| 7417 | |
| 7418 | |
| 7419 | |
| 7420 | |
| 7421 | |
| 7422 | #[test] |
| 7423 | fn of_tu_follows_the_block_row_including_under_vert_ab() { |
| 7424 | let fctx = &crate::decode::FrameCtx::new(); |
| 7425 | |
| 7426 | |
| 7427 | |
| 7428 | |
| 7429 | |
| 7430 | let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); |
| 7431 | assert_eq!( |
| 7432 | Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right, |
| 7433 | plain.above_right, |
| 7434 | "ordinary table: the top-right TX4 unit takes the block's row" |
| 7435 | ); |
| 7436 | let guard = Reach::vert_ab_partition(); |
| 7437 | let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx); |
| 7438 | assert_eq!( |
| 7439 | Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right, |
| 7440 | vert.above_right, |
| 7441 | "vert AB: the unit follows the vert row the block just picked" |
| 7442 | ); |
| 7443 | assert_ne!( |
| 7444 | plain.above_right, vert.above_right, |
| 7445 | "this position is the cell where the vert tables disagree; pick another if libaom's tables change" |
| 7446 | ); |
| 7447 | drop(guard); |
| 7448 | } |
| 7449 | |
| 7450 | |
| 7451 | |
| 7452 | |
| 7453 | |
| 7454 | |
| 7455 | |
| 7456 | |
| 7457 | #[test] |
| 7458 | fn reach_matches_libaom_has_top_right_and_has_bottom_left() { |
| 7459 | let fctx = &crate::decode::FrameCtx::new(); |
| 7460 | |
| 7461 | |
| 7462 | |
| 7463 | |
| 7464 | fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool { |
| 7465 | if y == 0 || x + side >= width { |
| 7466 | return false; |
| 7467 | } |
| 7468 | let (row, col, per_side) = ( |
| 7469 | (y % SUPERBLOCK) / side, |
| 7470 | (x % SUPERBLOCK) / side, |
| 7471 | SUPERBLOCK / side, |
| 7472 | ); |
| 7473 | if row == 0 { |
| 7474 | return true; |
| 7475 | } |
| 7476 | if col + 1 == per_side { |
| 7477 | return false; |
| 7478 | } |
| 7479 | let stride = 128 / side; |
| 7480 | let index = row * stride + col; |
| 7481 | let table = if side == BLOCK { |
| 7482 | [95u8, 87].to_vec() |
| 7483 | } else { |
| 7484 | vec![255, 85, 119, 85, 127, 85, 119, 85] |
| 7485 | }; |
| 7486 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 7487 | } |
| 7488 | |
| 7489 | fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool { |
| 7490 | if x == 0 || y + side >= height { |
| 7491 | return false; |
| 7492 | } |
| 7493 | let (row, col, per_side) = ( |
| 7494 | (y % SUPERBLOCK) / side, |
| 7495 | (x % SUPERBLOCK) / side, |
| 7496 | SUPERBLOCK / side, |
| 7497 | ); |
| 7498 | if col == 0 { |
| 7499 | return row * side + side < SUPERBLOCK; |
| 7500 | } |
| 7501 | if row + 1 == per_side { |
| 7502 | return false; |
| 7503 | } |
| 7504 | let stride = 128 / side; |
| 7505 | let index = row * stride + col; |
| 7506 | let table = if side == BLOCK { |
| 7507 | [4u8, 4].to_vec() |
| 7508 | } else { |
| 7509 | vec![84, 16, 84, 0, 84, 16, 84, 0] |
| 7510 | }; |
| 7511 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 7512 | } |
| 7513 | |
| 7514 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 7515 | for side in [16usize, BLOCK] { |
| 7516 | for y in (0..height).step_by(side) { |
| 7517 | for x in (0..width).step_by(side) { |
| 7518 | let reach = Reach::of(side, x, y, width, height, fctx); |
| 7519 | assert_eq!( |
| 7520 | reach.above_right, |
| 7521 | libaom_top_right(side, x, y, width, height), |
| 7522 | "side={side} x={x} y={y}: above_right" |
| 7523 | ); |
| 7524 | assert_eq!( |
| 7525 | reach.below_left, |
| 7526 | libaom_bottom_left(side, x, y, height, fctx), |
| 7527 | "side={side} x={x} y={y}: below_left" |
| 7528 | ); |
| 7529 | } |
| 7530 | } |
| 7531 | } |
| 7532 | } |
| 7533 | |
| 7534 | |
| 7535 | |
| 7536 | |
| 7537 | |
| 7538 | |
| 7539 | |
| 7540 | |
| 7541 | |
| 7542 | |
| 7543 | |
| 7544 | |
| 7545 | |
| 7546 | |
| 7547 | |
| 7548 | #[test] |
| 7549 | fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { |
| 7550 | |
| 7551 | |
| 7552 | fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 7553 | let (plane_bw_unit, count) = (bw / 4, tx / 4); |
| 7554 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 7555 | let _ = bh; |
| 7556 | if row_off_u > 0 { |
| 7557 | col_off_u + count < plane_bw_unit |
| 7558 | } else if col_off_u + count < plane_bw_unit { |
| 7559 | true |
| 7560 | } else { |
| 7561 | blk |
| 7562 | } |
| 7563 | } |
| 7564 | fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 7565 | let (plane_bh_unit, count) = (bh / 4, tx / 4); |
| 7566 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 7567 | let _ = bw; |
| 7568 | if col_off_u > 0 { |
| 7569 | false |
| 7570 | } else if row_off_u + count < plane_bh_unit { |
| 7571 | true |
| 7572 | } else { |
| 7573 | blk |
| 7574 | } |
| 7575 | } |
| 7576 | for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 7577 | for &tx in &[4usize, 8, 16, 32] { |
| 7578 | if tx > bw.min(bh) { |
| 7579 | continue; |
| 7580 | } |
| 7581 | for row_off in (0..bh).step_by(tx) { |
| 7582 | for col_off in (0..bw).step_by(tx) { |
| 7583 | for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] { |
| 7584 | let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk); |
| 7585 | assert_eq!( |
| 7586 | got.above_right, |
| 7587 | libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), |
| 7588 | "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 7589 | ); |
| 7590 | assert_eq!( |
| 7591 | got.below_left, |
| 7592 | libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), |
| 7593 | "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 7594 | ); |
| 7595 | } |
| 7596 | } |
| 7597 | } |
| 7598 | } |
| 7599 | } |
| 7600 | } |
| 7601 | |
| 7602 | #[test] |
| 7603 | fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { |
| 7604 | let fctx = &crate::decode::FrameCtx::new(); |
| 7605 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 7606 | |
| 7607 | |
| 7608 | let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK); |
| 7609 | let mut flipped = 0; |
| 7610 | for row in 0..8 { |
| 7611 | for col in 1..8 { |
| 7612 | let (x, y) = (sb_x + col * 8, sb_y + row * 8); |
| 7613 | let raster = Reach::of(8, x, y, width, height, fctx).below_left; |
| 7614 | let vert = { |
| 7615 | let _guard = Reach::vert_ab_partition(); |
| 7616 | Reach::of(8, x, y, width, height, fctx).below_left |
| 7617 | }; |
| 7618 | |
| 7619 | |
| 7620 | if row % 2 == 0 && col % 2 == 1 { |
| 7621 | assert!(!raster, "raster below_left at row={row} col={col}"); |
| 7622 | assert!(vert, "vert below_left at row={row} col={col}"); |
| 7623 | flipped += 1; |
| 7624 | } else { |
| 7625 | assert_eq!(raster, vert, "guard moved row={row} col={col}"); |
| 7626 | } |
| 7627 | } |
| 7628 | } |
| 7629 | assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip"); |
| 7630 | |
| 7631 | assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left); |
| 7632 | } |
| 7633 | |
| 7634 | |
| 7635 | |
| 7636 | #[test] |
| 7637 | fn odd_dimensions_are_refused() { |
| 7638 | let fctx = &crate::decode::FrameCtx::new(); |
| 7639 | for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { |
| 7640 | let picture = Picture::grey(width, height); |
| 7641 | let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx) |
| 7642 | .expect_err(&format!("{width}x{height} is odd and must be refused")); |
| 7643 | assert!( |
| 7644 | err.to_string().contains("even"), |
| 7645 | "{width}x{height}: error was {err}" |
| 7646 | ); |
| 7647 | } |
| 7648 | } |
| 7649 | |
| 7650 | |
| 7651 | |
| 7652 | |
| 7653 | |
| 7654 | #[test] |
| 7655 | fn sequence_round_trips_at_a_non_multiple_size() { |
| 7656 | let fctx = &crate::decode::FrameCtx::new(); |
| 7657 | if !have_ffmpeg() { |
| 7658 | eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg"); |
| 7659 | return; |
| 7660 | } |
| 7661 | let (width, height) = (160usize, 96usize); |
| 7662 | let pictures: Vec<Picture> = (0..3) |
| 7663 | .map(|i| panned_test_card(width, height, i * 3)) |
| 7664 | .collect(); |
| 7665 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 7666 | assert_eq!(encoded.frames.len(), 3); |
| 7667 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 7668 | assert_eq!( |
| 7669 | (frame.reconstruction.width, frame.reconstruction.height), |
| 7670 | (width, height), |
| 7671 | "frame {i}: reconstruction size" |
| 7672 | ); |
| 7673 | } |
| 7674 | |
| 7675 | |
| 7676 | assert_eq!( |
| 7677 | ffprobe_size(&encoded.stream), |
| 7678 | (width as u32, height as u32), |
| 7679 | "sequence: ffprobe reports the true (display) size" |
| 7680 | ); |
| 7681 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 7682 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 7683 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 7684 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 7685 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 7686 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 7687 | } |
| 7688 | } |
| 7689 | |
| 7690 | |
| 7691 | |
| 7692 | |
| 7693 | |
| 7694 | |
| 7695 | |
| 7696 | |
| 7697 | #[test] |
| 7698 | fn a_sequence_round_trips_at_the_exactly_half_straddle_size() { |
| 7699 | let fctx = &crate::decode::FrameCtx::new(); |
| 7700 | if !have_ffmpeg() { |
| 7701 | eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg"); |
| 7702 | return; |
| 7703 | } |
| 7704 | let (width, height) = (1280usize, 720usize); |
| 7705 | let pictures: Vec<Picture> = (0..3) |
| 7706 | .map(|i| panned_test_card(width, height, i * 3)) |
| 7707 | .collect(); |
| 7708 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 7709 | assert_eq!(encoded.frames.len(), 3); |
| 7710 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 7711 | assert_eq!( |
| 7712 | (frame.reconstruction.width, frame.reconstruction.height), |
| 7713 | (width, height), |
| 7714 | "frame {i}: reconstruction size" |
| 7715 | ); |
| 7716 | } |
| 7717 | assert_eq!( |
| 7718 | ffprobe_size(&encoded.stream), |
| 7719 | (width as u32, height as u32), |
| 7720 | "ffprobe reports the true (display) 1280x720 size" |
| 7721 | ); |
| 7722 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 7723 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 7724 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 7725 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 7726 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 7727 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 7728 | } |
| 7729 | } |
| 7730 | |
| 7731 | |
| 7732 | |
| 7733 | |
| 7734 | |
| 7735 | |
| 7736 | |
| 7737 | |
| 7738 | |
| 7739 | |
| 7740 | |
| 7741 | |
| 7742 | #[test] |
| 7743 | fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { |
| 7744 | let fctx = &crate::decode::FrameCtx::new(); |
| 7745 | let (width, height) = (640usize, 360usize); |
| 7746 | let picture = Picture::grey(width, height); |
| 7747 | encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle"); |
| 7748 | |
| 7749 | |
| 7750 | |
| 7751 | let pictures = vec![picture.clone(), picture]; |
| 7752 | encode_sequence_with_ctx(&pictures, 100, 0.5, fctx) |
| 7753 | .expect("inter frame now codes the mod-32==8 straddle too"); |
| 7754 | } |
| 7755 | |
| 7756 | |
| 7757 | |
| 7758 | |
| 7759 | |
| 7760 | |
| 7761 | #[test] |
| 7762 | fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() { |
| 7763 | let fctx = &crate::decode::FrameCtx::new(); |
| 7764 | if !have_ffmpeg() { |
| 7765 | eprintln!( |
| 7766 | "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \ |
| 7767 | no ffmpeg" |
| 7768 | ); |
| 7769 | return; |
| 7770 | } |
| 7771 | let (width, height) = (640usize, 360usize); |
| 7772 | for shift in [0i64, 7, 19] { |
| 7773 | let picture = panned_test_card(width, height, shift); |
| 7774 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 7775 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7776 | assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma"); |
| 7777 | assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U"); |
| 7778 | assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V"); |
| 7779 | } |
| 7780 | } |
| 7781 | |
| 7782 | |
| 7783 | |
| 7784 | |
| 7785 | |
| 7786 | #[test] |
| 7787 | fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { |
| 7788 | let fctx = &crate::decode::FrameCtx::new(); |
| 7789 | if !have_ffmpeg() { |
| 7790 | eprintln!( |
| 7791 | "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg" |
| 7792 | ); |
| 7793 | return; |
| 7794 | } |
| 7795 | let (width, height) = (640usize, 360usize); |
| 7796 | let pictures: Vec<Picture> = (0..4) |
| 7797 | .map(|i| panned_test_card(width, height, i * 3)) |
| 7798 | .collect(); |
| 7799 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 7800 | assert_eq!(encoded.frames.len(), 4); |
| 7801 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 7802 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 7803 | } |
| 7804 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); |
| 7805 | assert_eq!(decoded.len(), 4, "decoded frame count"); |
| 7806 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 7807 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 7808 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 7809 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 7810 | } |
| 7811 | } |
| 7812 | |
| 7813 | |
| 7814 | fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { |
| 7815 | let out = Command::new("ffmpeg") |
| 7816 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"]) |
| 7817 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 7818 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 7819 | .output() |
| 7820 | .expect("ffmpeg failed to run"); |
| 7821 | assert!( |
| 7822 | out.status.success(), |
| 7823 | "ffmpeg: {}", |
| 7824 | String::from_utf8_lossy(&out.stderr) |
| 7825 | ); |
| 7826 | let (luma, chroma) = (width * height, width * height / 4); |
| 7827 | assert_eq!( |
| 7828 | out.stdout.len(), |
| 7829 | luma + 2 * chroma, |
| 7830 | "expected one 4:2:0 frame" |
| 7831 | ); |
| 7832 | Picture { |
| 7833 | width, |
| 7834 | height, |
| 7835 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 7836 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 7837 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 7838 | } |
| 7839 | } |
| 7840 | |
| 7841 | |
| 7842 | |
| 7843 | |
| 7844 | #[test] |
| 7845 | #[ignore = "a sweep, not a gate"] |
| 7846 | fn probe_lambda() { |
| 7847 | let fctx = &crate::decode::FrameCtx::new(); |
| 7848 | let mut pictures = vec![ |
| 7849 | ("test card".to_string(), test_card(160, 96)), |
| 7850 | ("stripes".to_string(), stripes(160, 96, true)), |
| 7851 | ]; |
| 7852 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 7853 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 7854 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 7855 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 7856 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 7857 | } |
| 7858 | } |
| 7859 | for (name, picture) in pictures { |
| 7860 | let dc = ladder(&picture, &[DC_PRED], fctx); |
| 7861 | let searched = ladder(&picture, &NON_DIRECTIONAL, fctx); |
| 7862 | println!( |
| 7863 | "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point", |
| 7864 | bd_rate(&dc, &searched) * 100.0, |
| 7865 | 10f64.powf(searched[1].1), |
| 7866 | searched[1].0, |
| 7867 | 10f64.powf(dc[1].1), |
| 7868 | dc[1].0, |
| 7869 | ); |
| 7870 | } |
| 7871 | } |
| 7872 | |
| 7873 | |
| 7874 | |
| 7875 | #[test] |
| 7876 | #[ignore = "a sweep, not a gate"] |
| 7877 | fn probe_ladder() { |
| 7878 | let fctx = &crate::decode::FrameCtx::new(); |
| 7879 | for (name, picture) in sweep_pictures() { |
| 7880 | let all = ladder(&picture, &KEY_FRAME_MODES, fctx); |
| 7881 | let points = all |
| 7882 | .iter() |
| 7883 | .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes))) |
| 7884 | .collect::<Vec<_>>() |
| 7885 | .join(" "); |
| 7886 | println!("ladder {name}: {points}"); |
| 7887 | } |
| 7888 | } |
| 7889 | |
| 7890 | |
| 7891 | |
| 7892 | |
| 7893 | #[test] |
| 7894 | #[ignore = "a sweep, not a gate"] |
| 7895 | fn probe_split() { |
| 7896 | let fctx = &crate::decode::FrameCtx::new(); |
| 7897 | for (name, picture) in sweep_pictures() { |
| 7898 | let ladder = |split: bool| { |
| 7899 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 7900 | .iter() |
| 7901 | .map(|&q| { |
| 7902 | let encoded = encode_key_frame_inner( |
| 7903 | &picture, |
| 7904 | q, |
| 7905 | 0.5, |
| 7906 | &KEY_FRAME_MODES, |
| 7907 | split, |
| 7908 | (picture.width, picture.height), |
| 7909 | unspecified_color_config(), fctx, |
| 7910 | ) |
| 7911 | .unwrap(); |
| 7912 | ( |
| 7913 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 7914 | (encoded.stream.len() as f64).log10(), |
| 7915 | ) |
| 7916 | }) |
| 7917 | .collect(); |
| 7918 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 7919 | points |
| 7920 | }; |
| 7921 | let (whole, split) = (ladder(false), ladder(true)); |
| 7922 | let blocks = encode_key_frame_inner( |
| 7923 | &picture, |
| 7924 | 90, |
| 7925 | 0.5, |
| 7926 | &KEY_FRAME_MODES, |
| 7927 | true, |
| 7928 | (picture.width, picture.height), |
| 7929 | unspecified_color_config(), fctx, |
| 7930 | ) |
| 7931 | .unwrap() |
| 7932 | .modes |
| 7933 | .len(); |
| 7934 | let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK); |
| 7935 | println!( |
| 7936 | "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90", |
| 7937 | bd_rate(&whole, &split) * 100.0 |
| 7938 | ); |
| 7939 | } |
| 7940 | } |
| 7941 | |
| 7942 | |
| 7943 | |
| 7944 | |
| 7945 | |
| 7946 | fn stripes(width: usize, height: usize, vertical: bool) -> Picture { |
| 7947 | let mut picture = Picture::grey(width, height); |
| 7948 | for y in 0..height { |
| 7949 | for x in 0..width { |
| 7950 | let along = if vertical { x } else { y }; |
| 7951 | picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 }; |
| 7952 | } |
| 7953 | } |
| 7954 | picture |
| 7955 | } |
| 7956 | |
| 7957 | |
| 7958 | |
| 7959 | |
| 7960 | fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> { |
| 7961 | let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?; |
| 7962 | let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count(); |
| 7963 | Some(format!( |
| 7964 | "{differ} samples differ, first at ({}, {}): ours {} theirs {}", |
| 7965 | i % width, |
| 7966 | i / width, |
| 7967 | ours[i], |
| 7968 | theirs[i] |
| 7969 | )) |
| 7970 | } |
| 7971 | |
| 7972 | |
| 7973 | |
| 7974 | |
| 7975 | #[test] |
| 7976 | fn every_mode_decodes_to_what_the_encoder_predicted() { |
| 7977 | let fctx = &crate::decode::FrameCtx::new(); |
| 7978 | if !have_ffmpeg() { |
| 7979 | eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg"); |
| 7980 | return; |
| 7981 | } |
| 7982 | |
| 7983 | |
| 7984 | |
| 7985 | for (width, height) in [(128, 96), (160, 96)] { |
| 7986 | let picture = test_card(width, height); |
| 7987 | for mode in KEY_FRAME_MODES { |
| 7988 | let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap(); |
| 7989 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 7990 | for (plane, ours, theirs, stride) in [ |
| 7991 | ("luma", &encoded.reconstruction.y, &decoded.y, width), |
| 7992 | ("U", &encoded.reconstruction.u, &decoded.u, width / 2), |
| 7993 | ("V", &encoded.reconstruction.v, &decoded.v, width / 2), |
| 7994 | ] { |
| 7995 | assert!( |
| 7996 | first_difference(ours, theirs, stride).is_none(), |
| 7997 | "{width}x{height} mode {mode}, {plane}: {}", |
| 7998 | first_difference(ours, theirs, stride).unwrap() |
| 7999 | ); |
| 8000 | } |
| 8001 | assert!( |
| 8002 | encoded.modes.iter().all(|&m| m == mode), |
| 8003 | "mode {mode}: the encoder coded something else" |
| 8004 | ); |
| 8005 | } |
| 8006 | } |
| 8007 | } |
| 8008 | |
| 8009 | |
| 8010 | |
| 8011 | |
| 8012 | |
| 8013 | #[test] |
| 8014 | fn the_search_picks_the_direction_the_picture_runs() { |
| 8015 | let fctx = &crate::decode::FrameCtx::new(); |
| 8016 | for (vertical, want) in [(true, V_PRED), (false, H_PRED)] { |
| 8017 | let picture = stripes(128, 96, vertical); |
| 8018 | |
| 8019 | |
| 8020 | |
| 8021 | |
| 8022 | |
| 8023 | let encoded = |
| 8024 | encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap(); |
| 8025 | |
| 8026 | |
| 8027 | let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count(); |
| 8028 | assert!( |
| 8029 | picked * 2 > encoded.modes.len() - 1, |
| 8030 | "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}", |
| 8031 | encoded.modes.len() - 1, |
| 8032 | encoded.modes |
| 8033 | ); |
| 8034 | } |
| 8035 | } |
| 8036 | |
| 8037 | |
| 8038 | |
| 8039 | |
| 8040 | |
| 8041 | |
| 8042 | |
| 8043 | fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 { |
| 8044 | let low = reference[0].0.max(other[0].0); |
| 8045 | let high = reference[reference.len() - 1] |
| 8046 | .0 |
| 8047 | .min(other[other.len() - 1].0); |
| 8048 | |
| 8049 | |
| 8050 | |
| 8051 | |
| 8052 | |
| 8053 | |
| 8054 | |
| 8055 | |
| 8056 | if high <= low { |
| 8057 | let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min); |
| 8058 | let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max); |
| 8059 | let dominates = other[0].0 > reference[reference.len() - 1].0 |
| 8060 | && other_hi_rate <= ref_lo_rate; |
| 8061 | assert!( |
| 8062 | dominates, |
| 8063 | "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}" |
| 8064 | ); |
| 8065 | return -1.0; |
| 8066 | } |
| 8067 | let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { |
| 8068 | let i = curve |
| 8069 | .windows(2) |
| 8070 | .position(|w| psnr >= w[0].0 && psnr <= w[1].0) |
| 8071 | .unwrap_or(0); |
| 8072 | let (x0, y0) = curve[i]; |
| 8073 | let (x1, y1) = curve[i + 1]; |
| 8074 | y0 + (y1 - y0) * (psnr - x0) / (x1 - x0) |
| 8075 | }; |
| 8076 | let steps = 64; |
| 8077 | let mut area = 0.0; |
| 8078 | for step in 0..steps { |
| 8079 | let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps); |
| 8080 | area += log_rate_at(other, psnr) - log_rate_at(reference, psnr); |
| 8081 | } |
| 8082 | 10f64.powf(area / f64::from(steps)) - 1.0 |
| 8083 | } |
| 8084 | |
| 8085 | |
| 8086 | |
| 8087 | fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> { |
| 8088 | |
| 8089 | |
| 8090 | |
| 8091 | force_screen(Some(false)); |
| 8092 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 8093 | .iter() |
| 8094 | .map(|&q| { |
| 8095 | let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap(); |
| 8096 | ( |
| 8097 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 8098 | (encoded.stream.len() as f64).log10(), |
| 8099 | ) |
| 8100 | }) |
| 8101 | .collect(); |
| 8102 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 8103 | points |
| 8104 | } |
| 8105 | |
| 8106 | |
| 8107 | |
| 8108 | |
| 8109 | |
| 8110 | #[test] |
| 8111 | fn the_search_beats_dc_alone() { |
| 8112 | let fctx = &crate::decode::FrameCtx::new(); |
| 8113 | for (name, picture, want) in [ |
| 8114 | ("test card", test_card(160, 96), -0.05), |
| 8115 | ("stripes", stripes(160, 96, true), -0.40), |
| 8116 | ] { |
| 8117 | let saved = bd_rate( |
| 8118 | &ladder(&picture, &[DC_PRED], fctx), |
| 8119 | &ladder(&picture, &NON_DIRECTIONAL, fctx), |
| 8120 | ); |
| 8121 | assert!( |
| 8122 | saved < want, |
| 8123 | "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%", |
| 8124 | saved * 100.0, |
| 8125 | -want * 100.0 |
| 8126 | ); |
| 8127 | } |
| 8128 | } |
| 8129 | |
| 8130 | |
| 8131 | |
| 8132 | fn sweep_pictures() -> Vec<(String, Picture)> { |
| 8133 | let mut pictures = vec![ |
| 8134 | ("test card".to_string(), test_card(160, 96)), |
| 8135 | ("stripes".to_string(), stripes(160, 96, true)), |
| 8136 | ("diagonal".to_string(), diagonal(160, 96, true)), |
| 8137 | ]; |
| 8138 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 8139 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 8140 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 8141 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 8142 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 8143 | } |
| 8144 | } |
| 8145 | pictures |
| 8146 | } |
| 8147 | |
| 8148 | |
| 8149 | |
| 8150 | |
| 8151 | #[test] |
| 8152 | #[ignore = "a sweep, not a gate"] |
| 8153 | fn probe_directional() { |
| 8154 | let fctx = &crate::decode::FrameCtx::new(); |
| 8155 | for (name, picture) in sweep_pictures() { |
| 8156 | let dc = ladder(&picture, &[DC_PRED], fctx); |
| 8157 | let flat = ladder(&picture, &NON_DIRECTIONAL, fctx); |
| 8158 | let all = ladder(&picture, &KEY_FRAME_MODES, fctx); |
| 8159 | let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap(); |
| 8160 | let directional = encoded |
| 8161 | .modes |
| 8162 | .iter() |
| 8163 | .filter(|&&m| (3..=8).contains(&m)) |
| 8164 | .count(); |
| 8165 | |
| 8166 | |
| 8167 | let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 8168 | a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0) |
| 8169 | }; |
| 8170 | let against = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 8171 | if overlap(a, b) { |
| 8172 | format!("{:+.2}%", bd_rate(a, b) * 100.0) |
| 8173 | } else { |
| 8174 | "no overlap".to_string() |
| 8175 | } |
| 8176 | }; |
| 8177 | println!( |
| 8178 | "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional", |
| 8179 | against(&flat, &all), |
| 8180 | against(&dc, &all), |
| 8181 | encoded.modes.len(), |
| 8182 | ); |
| 8183 | } |
| 8184 | } |
| 8185 | |
| 8186 | |
| 8187 | |
| 8188 | |
| 8189 | |
| 8190 | fn diagonal(width: usize, height: usize, down_right: bool) -> Picture { |
| 8191 | let mut picture = Picture::grey(width, height); |
| 8192 | for y in 0..height { |
| 8193 | for x in 0..width { |
| 8194 | let along = if down_right { x + height - y } else { x + y }; |
| 8195 | picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 }; |
| 8196 | } |
| 8197 | } |
| 8198 | picture |
| 8199 | } |
| 8200 | |
| 8201 | |
| 8202 | |
| 8203 | fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) { |
| 8204 | |
| 8205 | |
| 8206 | |
| 8207 | force_screen(Some(false)); |
| 8208 | let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap(); |
| 8209 | let blocks = &encoded.modes[1..]; |
| 8210 | let mut counts = [0usize; 13]; |
| 8211 | for &mode in blocks { |
| 8212 | counts[usize::from(mode)] += 1; |
| 8213 | } |
| 8214 | let (mode, count) = counts |
| 8215 | .iter() |
| 8216 | .enumerate() |
| 8217 | .max_by_key(|&(_, count)| *count) |
| 8218 | .expect("thirteen modes"); |
| 8219 | (mode as u8, *count, blocks.len()) |
| 8220 | } |
| 8221 | |
| 8222 | |
| 8223 | |
| 8224 | |
| 8225 | |
| 8226 | #[test] |
| 8227 | fn the_search_picks_the_diagonal_the_picture_runs() { |
| 8228 | let fctx = &crate::decode::FrameCtx::new(); |
| 8229 | for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] { |
| 8230 | let picture = diagonal(160, 96, down_right); |
| 8231 | let (mode, count, blocks) = favourite_mode(&picture, fctx); |
| 8232 | assert_eq!( |
| 8233 | mode, want, |
| 8234 | "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}" |
| 8235 | ); |
| 8236 | } |
| 8237 | } |
| 8238 | |
| 8239 | |
| 8240 | |
| 8241 | |
| 8242 | |
| 8243 | |
| 8244 | |
| 8245 | #[test] |
| 8246 | fn the_diagonals_beat_the_modes_that_read_no_further() { |
| 8247 | let fctx = &crate::decode::FrameCtx::new(); |
| 8248 | for (name, picture, want) in [ |
| 8249 | ("down-right", diagonal(160, 96, true), -0.20), |
| 8250 | ("down-left", diagonal(160, 96, false), -0.20), |
| 8251 | ("test card", test_card(160, 96), 0.01), |
| 8252 | ] { |
| 8253 | let saved = bd_rate( |
| 8254 | &ladder(&picture, &NON_DIRECTIONAL, fctx), |
| 8255 | &ladder(&picture, &KEY_FRAME_MODES, fctx), |
| 8256 | ); |
| 8257 | assert!( |
| 8258 | saved < want, |
| 8259 | "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%", |
| 8260 | saved * 100.0, |
| 8261 | -want * 100.0 |
| 8262 | ); |
| 8263 | } |
| 8264 | } |
| 8265 | |
| 8266 | |
| 8267 | |
| 8268 | #[test] |
| 8269 | fn a_mode_the_encoder_cannot_predict_is_refused() { |
| 8270 | let fctx = &crate::decode::FrameCtx::new(); |
| 8271 | let picture = test_card(64, 64); |
| 8272 | let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx) |
| 8273 | .unwrap_err() |
| 8274 | .to_string(); |
| 8275 | assert!( |
| 8276 | message.contains("intra mode 13"), |
| 8277 | "the refusal must name the mode, got {message}" |
| 8278 | ); |
| 8279 | assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err()); |
| 8280 | } |
| 8281 | |
| 8282 | |
| 8283 | |
| 8284 | |
| 8285 | |
| 8286 | |
| 8287 | #[test] |
| 8288 | fn the_encoded_picture_is_the_one_that_went_in() { |
| 8289 | let fctx = &crate::decode::FrameCtx::new(); |
| 8290 | let picture = test_card(160, 96); |
| 8291 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 8292 | let luma = psnr(&encoded.reconstruction.y, &picture.y); |
| 8293 | assert!(luma > 36.0, "luma PSNR {luma} at q 100"); |
| 8294 | for (plane, (got, want)) in [ |
| 8295 | (encoded.reconstruction.u.as_slice(), picture.u.as_slice()), |
| 8296 | (encoded.reconstruction.v.as_slice(), picture.v.as_slice()), |
| 8297 | ] |
| 8298 | .iter() |
| 8299 | .enumerate() |
| 8300 | { |
| 8301 | let chroma = psnr(got, want); |
| 8302 | assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100"); |
| 8303 | } |
| 8304 | } |
| 8305 | |
| 8306 | |
| 8307 | |
| 8308 | |
| 8309 | #[test] |
| 8310 | fn fidelity_and_rate_move_with_the_quantizer() { |
| 8311 | let fctx = &crate::decode::FrameCtx::new(); |
| 8312 | let picture = test_card(128, 128); |
| 8313 | let mut previous: Option<(usize, f64)> = None; |
| 8314 | for &q in &[70u8, 90, 110] { |
| 8315 | let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 8316 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 8317 | if let Some((bytes, better)) = previous { |
| 8318 | assert!( |
| 8319 | encoded.stream.len() < bytes, |
| 8320 | "q {q}: {} bytes", |
| 8321 | encoded.stream.len() |
| 8322 | ); |
| 8323 | assert!(quality < better, "q {q}: PSNR {quality}"); |
| 8324 | } |
| 8325 | previous = Some((encoded.stream.len(), quality)); |
| 8326 | } |
| 8327 | |
| 8328 | let mut previous = None; |
| 8329 | for &deadzone in &[0.5f64, 0.3, 0.15] { |
| 8330 | let encoded = encode_key_frame_with_ctx(&picture, 100, deadzone, fctx).unwrap(); |
| 8331 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 8332 | if let Some((bytes, better)) = previous { |
| 8333 | assert!( |
| 8334 | encoded.stream.len() < bytes, |
| 8335 | "deadzone {deadzone}: {} bytes", |
| 8336 | encoded.stream.len() |
| 8337 | ); |
| 8338 | assert!(quality < better, "deadzone {deadzone}: PSNR {quality}"); |
| 8339 | } |
| 8340 | previous = Some((encoded.stream.len(), quality)); |
| 8341 | } |
| 8342 | |
| 8343 | |
| 8344 | |
| 8345 | |
| 8346 | |
| 8347 | |
| 8348 | |
| 8349 | |
| 8350 | |
| 8351 | |
| 8352 | |
| 8353 | |
| 8354 | |
| 8355 | |
| 8356 | |
| 8357 | |
| 8358 | |
| 8359 | |
| 8360 | |
| 8361 | |
| 8362 | |
| 8363 | |
| 8364 | for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { |
| 8365 | let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len(); |
| 8366 | let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len(); |
| 8367 | assert!( |
| 8368 | hi_bytes as f64 <= lo_bytes as f64 * 1.10, |
| 8369 | "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" |
| 8370 | ); |
| 8371 | } |
| 8372 | } |
| 8373 | |
| 8374 | |
| 8375 | |
| 8376 | #[test] |
| 8377 | fn a_flat_picture_costs_almost_nothing() { |
| 8378 | let fctx = &crate::decode::FrameCtx::new(); |
| 8379 | let mut picture = Picture::grey(128, 128); |
| 8380 | picture.y.fill(97); |
| 8381 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 8382 | |
| 8383 | |
| 8384 | assert!( |
| 8385 | encoded.stream.len() < 100, |
| 8386 | "{} bytes for a flat picture", |
| 8387 | encoded.stream.len() |
| 8388 | ); |
| 8389 | for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) { |
| 8390 | assert_eq!(s, 97, "sample {i} of a flat picture"); |
| 8391 | } |
| 8392 | } |
| 8393 | |
| 8394 | |
| 8395 | |
| 8396 | |
| 8397 | |
| 8398 | |
| 8399 | |
| 8400 | |
| 8401 | |
| 8402 | |
| 8403 | |
| 8404 | |
| 8405 | |
| 8406 | #[test] |
| 8407 | fn a_picture_off_the_block_grid_is_refused() { |
| 8408 | let fctx = &crate::decode::FrameCtx::new(); |
| 8409 | let msg = encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx) |
| 8410 | .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform") |
| 8411 | .to_string(); |
| 8412 | assert!(msg.contains("rectangular"), "refusal: {msg}"); |
| 8413 | |
| 8414 | let mut short = Picture::grey(64, 64); |
| 8415 | short.u.truncate(10); |
| 8416 | assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err()); |
| 8417 | } |
| 8418 | |
| 8419 | |
| 8420 | |
| 8421 | |
| 8422 | |
| 8423 | |
| 8424 | |
| 8425 | |
| 8426 | |
| 8427 | |
| 8428 | |
| 8429 | |
| 8430 | |
| 8431 | |
| 8432 | |
| 8433 | |
| 8434 | |
| 8435 | |
| 8436 | |
| 8437 | |
| 8438 | |
| 8439 | |
| 8440 | |
| 8441 | |
| 8442 | |
| 8443 | |
| 8444 | |
| 8445 | |
| 8446 | |
| 8447 | |
| 8448 | |
| 8449 | |
| 8450 | |
| 8451 | |
| 8452 | |
| 8453 | |
| 8454 | |
| 8455 | |
| 8456 | |
| 8457 | |
| 8458 | |
| 8459 | |
| 8460 | |
| 8461 | |
| 8462 | |
| 8463 | |
| 8464 | |
| 8465 | |
| 8466 | |
| 8467 | |
| 8468 | |
| 8469 | |
| 8470 | |
| 8471 | |
| 8472 | |
| 8473 | |
| 8474 | |
| 8475 | |
| 8476 | |
| 8477 | |
| 8478 | |
| 8479 | |
| 8480 | |
| 8481 | |
| 8482 | |
| 8483 | |
| 8484 | |
| 8485 | |
| 8486 | |
| 8487 | |
| 8488 | |
| 8489 | #[test] |
| 8490 | fn a_single_axis_straddle_round_trips_through_ffmpeg() { |
| 8491 | let fctx = &crate::decode::FrameCtx::new(); |
| 8492 | if !have_ffmpeg() { |
| 8493 | eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg"); |
| 8494 | return; |
| 8495 | } |
| 8496 | let (width, height) = (40usize, 32usize); |
| 8497 | let picture = test_card(width, height); |
| 8498 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 8499 | assert_eq!( |
| 8500 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 8501 | (width, height) |
| 8502 | ); |
| 8503 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 8504 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 8505 | } |
| 8506 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 8507 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 8508 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 8509 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 8510 | } |
| 8511 | |
| 8512 | |
| 8513 | |
| 8514 | |
| 8515 | |
| 8516 | |
| 8517 | |
| 8518 | #[test] |
| 8519 | fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() { |
| 8520 | let fctx = &crate::decode::FrameCtx::new(); |
| 8521 | let Ok(clip) = std::env::var("EC_AV1_CLIP") else { |
| 8522 | eprintln!( |
| 8523 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \ |
| 8524 | set EC_AV1_CLIP to a clip" |
| 8525 | ); |
| 8526 | return; |
| 8527 | }; |
| 8528 | if !have_ffmpeg() { |
| 8529 | eprintln!( |
| 8530 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 8531 | ); |
| 8532 | return; |
| 8533 | } |
| 8534 | let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into()); |
| 8535 | |
| 8536 | |
| 8537 | let (width, height) = (640usize, 352usize); |
| 8538 | let picture = clip_frame(&clip, &skip, width, height); |
| 8539 | |
| 8540 | let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 8541 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 8542 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 8543 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 8544 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 8545 | eprintln!( |
| 8546 | "{} bytes, luma PSNR {:.2} dB", |
| 8547 | encoded.stream.len(), |
| 8548 | psnr(&decoded.y, &picture.y) |
| 8549 | ); |
| 8550 | } |
| 8551 | |
| 8552 | |
| 8553 | |
| 8554 | |
| 8555 | |
| 8556 | |
| 8557 | fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture { |
| 8558 | let mut picture = Picture::grey(width, height); |
| 8559 | for y in 0..height { |
| 8560 | for x in 0..width { |
| 8561 | let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; |
| 8562 | let gradient = sx * 200.0 / width as f64; |
| 8563 | let ripple = 30.0 |
| 8564 | * (sx * std::f64::consts::PI / 23.0).sin() |
| 8565 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 8566 | let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 { |
| 8567 | 40.0 |
| 8568 | } else { |
| 8569 | 0.0 |
| 8570 | }; |
| 8571 | picture.y[y * width + x] = |
| 8572 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 8573 | } |
| 8574 | } |
| 8575 | for y in 0..height / 2 { |
| 8576 | for x in 0..width / 2 { |
| 8577 | let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; |
| 8578 | let i = y * width / 2 + x; |
| 8579 | picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; |
| 8580 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 8581 | } |
| 8582 | } |
| 8583 | picture |
| 8584 | } |
| 8585 | |
| 8586 | |
| 8587 | fn ffmpeg_decode_sequence( |
| 8588 | stream: &[u8], |
| 8589 | width: usize, |
| 8590 | height: usize, |
| 8591 | frames: usize, |
| 8592 | ) -> Vec<Picture> { |
| 8593 | let mut child = Command::new("ffmpeg") |
| 8594 | .args([ |
| 8595 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 8596 | ]) |
| 8597 | .stdin(Stdio::piped()) |
| 8598 | .stdout(Stdio::piped()) |
| 8599 | .stderr(Stdio::piped()) |
| 8600 | .spawn() |
| 8601 | .expect("ffmpeg failed to start"); |
| 8602 | |
| 8603 | |
| 8604 | |
| 8605 | |
| 8606 | |
| 8607 | |
| 8608 | |
| 8609 | let mut stdin = child.stdin.take().expect("ffmpeg stdin"); |
| 8610 | let payload = stream.to_vec(); |
| 8611 | let writer = std::thread::spawn(move || { |
| 8612 | let _ = stdin.write_all(&payload); |
| 8613 | }); |
| 8614 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 8615 | writer.join().expect("ffmpeg stdin writer thread"); |
| 8616 | assert!( |
| 8617 | out.status.success(), |
| 8618 | "ffmpeg refused the stream: {}", |
| 8619 | String::from_utf8_lossy(&out.stderr) |
| 8620 | ); |
| 8621 | let (luma, chroma) = (width * height, width * height / 4); |
| 8622 | let frame_bytes = luma + 2 * chroma; |
| 8623 | assert_eq!( |
| 8624 | out.stdout.len(), |
| 8625 | frame_bytes * frames, |
| 8626 | "expected {frames} 4:2:0 frames, ffmpeg said: {}", |
| 8627 | String::from_utf8_lossy(&out.stderr) |
| 8628 | ); |
| 8629 | (0..frames) |
| 8630 | .map(|i| { |
| 8631 | let base = i * frame_bytes; |
| 8632 | Picture { |
| 8633 | width, |
| 8634 | height, |
| 8635 | y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(), |
| 8636 | u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 8637 | v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(), |
| 8638 | } |
| 8639 | }) |
| 8640 | .collect() |
| 8641 | } |
| 8642 | |
| 8643 | |
| 8644 | |
| 8645 | |
| 8646 | |
| 8647 | |
| 8648 | |
| 8649 | #[test] |
| 8650 | fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() { |
| 8651 | let fctx = &crate::decode::FrameCtx::new(); |
| 8652 | if !have_ffmpeg() { |
| 8653 | eprintln!( |
| 8654 | "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 8655 | ); |
| 8656 | return; |
| 8657 | } |
| 8658 | let (width, height) = (128usize, 64usize); |
| 8659 | let pictures: Vec<Picture> = (0..5) |
| 8660 | .map(|i| panned_test_card(width, height, i * 3)) |
| 8661 | .collect(); |
| 8662 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 8663 | assert_eq!(encoded.frames.len(), 5); |
| 8664 | |
| 8665 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5); |
| 8666 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 8667 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma"); |
| 8668 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U"); |
| 8669 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V"); |
| 8670 | } |
| 8671 | |
| 8672 | eprintln!("frame bytes luma PSNR (dB) inter share"); |
| 8673 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 8674 | eprintln!( |
| 8675 | "{i:5} {:5} {:14.2} {:11.2}", |
| 8676 | frame.stream.len(), |
| 8677 | psnr(&frame.reconstruction.y, &pictures[i].y), |
| 8678 | frame.inter_block_share |
| 8679 | ); |
| 8680 | } |
| 8681 | } |
| 8682 | |
| 8683 | |
| 8684 | |
| 8685 | |
| 8686 | |
| 8687 | |
| 8688 | |
| 8689 | |
| 8690 | #[test] |
| 8691 | fn every_frame_of_a_sequence_decodes_through_our_own_decoder() { |
| 8692 | let fctx = &crate::decode::FrameCtx::new(); |
| 8693 | let (width, height) = (128usize, 64usize); |
| 8694 | let pictures: Vec<Picture> = |
| 8695 | (0..5).map(|i| panned_test_card(width, height, i * 3)).collect(); |
| 8696 | let _ = take_inter_tx_split_hits(); |
| 8697 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 8698 | let split = take_inter_tx_split_hits(); |
| 8699 | eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]); |
| 8700 | |
| 8701 | |
| 8702 | |
| 8703 | if tx_select() && tx_select_inter() { |
| 8704 | assert!(split[1] > 0, "the inter var-tx split never fired"); |
| 8705 | } |
| 8706 | let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 8707 | assert_eq!(decoded.len(), encoded.frames.len(), "frame count"); |
| 8708 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 8709 | let recon = &frame.reconstruction; |
| 8710 | for (plane, got, want, stride) in [ |
| 8711 | ("luma", &dec.y, &recon.y, width), |
| 8712 | ("U", &dec.u, &recon.u, width / 2), |
| 8713 | ("V", &dec.v, &recon.v, width / 2), |
| 8714 | ] { |
| 8715 | assert_eq!(got.len(), want.len(), "frame {i}: {plane} size"); |
| 8716 | if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) { |
| 8717 | panic!( |
| 8718 | "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \ |
| 8719 | reconstruction {} ({} of {} samples differ)", |
| 8720 | at % stride, |
| 8721 | at / stride, |
| 8722 | got[at], |
| 8723 | want[at], |
| 8724 | got.iter().zip(want).filter(|(a, b)| a != b).count(), |
| 8725 | got.len(), |
| 8726 | ); |
| 8727 | } |
| 8728 | } |
| 8729 | } |
| 8730 | } |
| 8731 | |
| 8732 | |
| 8733 | |
| 8734 | |
| 8735 | |
| 8736 | |
| 8737 | |
| 8738 | |
| 8739 | |
| 8740 | |
| 8741 | |
| 8742 | |
| 8743 | #[test] |
| 8744 | fn predicted_coeff_bits_track_the_tile_the_writer_wrote() { |
| 8745 | let fctx = &crate::decode::FrameCtx::new(); |
| 8746 | let (width, height) = (256usize, 128usize); |
| 8747 | let pictures: Vec<Picture> = (0..5) |
| 8748 | .map(|i| panned_test_card(width, height, i * 2)) |
| 8749 | .collect(); |
| 8750 | let _ = take_predicted_bits(); |
| 8751 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 8752 | let predicted = take_predicted_bits(); |
| 8753 | assert_eq!(predicted.len(), encoded.frames.len()); |
| 8754 | |
| 8755 | eprintln!("frame predicted bits written bits drift"); |
| 8756 | |
| 8757 | |
| 8758 | |
| 8759 | |
| 8760 | |
| 8761 | let mut worst_over: f64 = 0.0; |
| 8762 | let mut worst_under: f64 = 0.0; |
| 8763 | for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() { |
| 8764 | let written = frame.tile.len() as f64 * 8.0; |
| 8765 | let drift = (written - bits) / written; |
| 8766 | worst_over = worst_over.max(-drift); |
| 8767 | worst_under = worst_under.max(drift); |
| 8768 | eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0); |
| 8769 | } |
| 8770 | |
| 8771 | |
| 8772 | |
| 8773 | |
| 8774 | |
| 8775 | |
| 8776 | |
| 8777 | |
| 8778 | assert!( |
| 8779 | worst_over <= 0.16, |
| 8780 | "the search's rate term OVER-priced by {:.2}% against the bits the writer spent", |
| 8781 | worst_over * 100.0 |
| 8782 | ); |
| 8783 | |
| 8784 | |
| 8785 | |
| 8786 | |
| 8787 | |
| 8788 | |
| 8789 | |
| 8790 | assert!( |
| 8791 | worst_under <= 0.32, |
| 8792 | "the writer spent {:.2}% more than the search priced -- more than \ |
| 8793 | the mode/mv syntax outside the coefficient sum explains", |
| 8794 | worst_under * 100.0 |
| 8795 | ); |
| 8796 | } |
| 8797 | |
| 8798 | |
| 8799 | |
| 8800 | |
| 8801 | |
| 8802 | |
| 8803 | |
| 8804 | |
| 8805 | #[test] |
| 8806 | fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() { |
| 8807 | let fctx = &crate::decode::FrameCtx::new(); |
| 8808 | let (width, height) = (256usize, 128usize); |
| 8809 | let pictures: Vec<Picture> = (0..5) |
| 8810 | .map(|i| panned_test_card(width, height, i * 2)) |
| 8811 | .collect(); |
| 8812 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 8813 | |
| 8814 | let key_bytes = encoded.frames[0].stream.len(); |
| 8815 | eprintln!("frame bytes inter share"); |
| 8816 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 8817 | eprintln!( |
| 8818 | "{i:5} {:5} {:11.2}", |
| 8819 | frame.stream.len(), |
| 8820 | frame.inter_block_share |
| 8821 | ); |
| 8822 | } |
| 8823 | assert!( |
| 8824 | encoded.frames[1..] |
| 8825 | .iter() |
| 8826 | .any(|f| f.stream.len() < key_bytes), |
| 8827 | "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes" |
| 8828 | ); |
| 8829 | assert!( |
| 8830 | encoded.frames[1..] |
| 8831 | .iter() |
| 8832 | .any(|f| f.inter_block_share > 0.0), |
| 8833 | "no inter frame coded a single inter block -- the search never fired" |
| 8834 | ); |
| 8835 | } |
| 8836 | |
| 8837 | |
| 8838 | |
| 8839 | |
| 8840 | |
| 8841 | #[test] |
| 8842 | #[ignore = "a perf probe, not a gate"] |
| 8843 | fn stage_timing_breakdown() { |
| 8844 | let fctx = &crate::decode::FrameCtx::new(); |
| 8845 | use std::time::Instant; |
| 8846 | |
| 8847 | for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] { |
| 8848 | let picture = test_card(width, height); |
| 8849 | |
| 8850 | let t = Instant::now(); |
| 8851 | let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap(); |
| 8852 | let dc_only_t = t.elapsed(); |
| 8853 | |
| 8854 | let t = Instant::now(); |
| 8855 | let non_directional = |
| 8856 | encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap(); |
| 8857 | let non_directional_t = t.elapsed(); |
| 8858 | |
| 8859 | let t = Instant::now(); |
| 8860 | let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 8861 | let all_modes_t = t.elapsed(); |
| 8862 | |
| 8863 | eprintln!( |
| 8864 | "\n=== key frame {width}x{height} ===\n\ |
| 8865 | 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\ |
| 8866 | 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\ |
| 8867 | 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)", |
| 8868 | dc_only.stream.len(), |
| 8869 | non_directional.stream.len(), |
| 8870 | all_modes.stream.len(), |
| 8871 | ); |
| 8872 | |
| 8873 | |
| 8874 | |
| 8875 | |
| 8876 | let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK); |
| 8877 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 8878 | let t = Instant::now(); |
| 8879 | let inter = |
| 8880 | 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(); |
| 8881 | let inter_t = t.elapsed(); |
| 8882 | eprintln!( |
| 8883 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| 8884 | {:.2})", |
| 8885 | inter.stream.len(), |
| 8886 | inter.inter_block_share |
| 8887 | ); |
| 8888 | } |
| 8889 | |
| 8890 | |
| 8891 | |
| 8892 | |
| 8893 | for side in [16usize, 32] { |
| 8894 | const N: u32 = 20_000; |
| 8895 | let residual: Vec<i32> = (0..side * side) |
| 8896 | .map(|i| ((i * 37 % 61) as i32) - 30) |
| 8897 | .collect(); |
| 8898 | |
| 8899 | let t = Instant::now(); |
| 8900 | let mut levels = Vec::new(); |
| 8901 | for _ in 0..N { |
| 8902 | levels = forward_and_quantize(&residual, side, 8, 100, 0.5); |
| 8903 | } |
| 8904 | let forward_t = t.elapsed() / N; |
| 8905 | |
| 8906 | let t = Instant::now(); |
| 8907 | for _ in 0..N { |
| 8908 | std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100)); |
| 8909 | } |
| 8910 | let inverse_t = t.elapsed() / N; |
| 8911 | |
| 8912 | let set = if side == 32 { |
| 8913 | crate::cdf_state::TxbSet::Luma32 |
| 8914 | } else { |
| 8915 | crate::cdf_state::TxbSet::Luma16 |
| 8916 | }; |
| 8917 | let t = Instant::now(); |
| 8918 | for _ in 0..N { |
| 8919 | std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2)); |
| 8920 | } |
| 8921 | let entropy_t = t.elapsed() / N; |
| 8922 | |
| 8923 | let above = vec![128u8; side * 2]; |
| 8924 | let left = vec![128u8; side * 2]; |
| 8925 | let mut prediction = vec![0u8; side * side]; |
| 8926 | let t = Instant::now(); |
| 8927 | for _ in 0..N { |
| 8928 | intra_predict_u8( |
| 8929 | D45_PRED, |
| 8930 | 0, |
| 8931 | Some(&above), |
| 8932 | Some(&left), |
| 8933 | Some(128), |
| 8934 | side, |
| 8935 | side, |
| 8936 | false, |
| 8937 | false, |
| 8938 | &mut prediction, fctx, |
| 8939 | ); |
| 8940 | } |
| 8941 | let predict_t = t.elapsed() / N; |
| 8942 | |
| 8943 | eprintln!( |
| 8944 | "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ |
| 8945 | predict (1 directional mode): {predict_t:>9.2?}\n\ |
| 8946 | forward_and_quantize: {forward_t:>9.2?}\n\ |
| 8947 | dequant_and_inverse: {inverse_t:>9.2?}\n\ |
| 8948 | coeff_bits: {entropy_t:>9.2?}" |
| 8949 | ); |
| 8950 | } |
| 8951 | } |
| 8952 | |
| 8953 | |
| 8954 | |
| 8955 | |
| 8956 | |
| 8957 | |
| 8958 | |
| 8959 | |
| 8960 | |
| 8961 | |
| 8962 | |
| 8963 | #[test] |
| 8964 | #[ignore = "a perf probe, not a gate"] |
| 8965 | fn stage_timing_breakdown_inter() { |
| 8966 | let fctx = &crate::decode::FrameCtx::new(); |
| 8967 | use std::time::Instant; |
| 8968 | |
| 8969 | let (width, height) = (1280usize, 720); |
| 8970 | let picture = test_card(width, height); |
| 8971 | let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); |
| 8972 | let padded_ref = key.reconstruction.padded_to(SUPERBLOCK); |
| 8973 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 8974 | |
| 8975 | stage_reset(); |
| 8976 | let t = Instant::now(); |
| 8977 | let inter = |
| 8978 | 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(); |
| 8979 | let total_t = t.elapsed(); |
| 8980 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 8981 | let accounted = motion_search + transform_quant + entropy; |
| 8982 | |
| 8983 | |
| 8984 | |
| 8985 | |
| 8986 | let other = total_t.saturating_sub(accounted); |
| 8987 | |
| 8988 | eprintln!( |
| 8989 | "\n=== inter frame {width}x{height}, one frame ===\n\ |
| 8990 | total: {total_t:>9.2?} ({} bytes)\n\ |
| 8991 | motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \ |
| 8992 | {interpolation:>9.2?})\n\ |
| 8993 | transform + quantize: {transform_quant:>9.2?}\n\ |
| 8994 | coeff_bits (entropy pricing): {entropy:>9.2?}\n\ |
| 8995 | everything else (13-mode intra {other:>9.2?}\n\ |
| 8996 | candidate loop's own predict/bookkeeping, NEARESTMV's own \ |
| 8997 | predict, RD glue):", |
| 8998 | inter.stream.len(), |
| 8999 | ); |
| 9000 | } |
| 9001 | |
| 9002 | |
| 9003 | |
| 9004 | |
| 9005 | |
| 9006 | |
| 9007 | |
| 9008 | |
| 9009 | |
| 9010 | |
| 9011 | #[test] |
| 9012 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 9013 | fn prune_k_quality_sweep() { |
| 9014 | let fctx = &crate::decode::FrameCtx::new(); |
| 9015 | if !have_ffmpeg() { |
| 9016 | eprintln!("SKIP prune_k_quality_sweep: no ffmpeg"); |
| 9017 | return; |
| 9018 | } |
| 9019 | let (width, height) = (640usize, 352usize); |
| 9020 | let frames: &[(&str, &str, &str)] = &[ |
| 9021 | |
| 9022 | |
| 9023 | ( |
| 9024 | "dark/flat", |
| 9025 | "/home/user/Videos/reela.mp4", |
| 9026 | "3", |
| 9027 | ), |
| 9028 | ( |
| 9029 | "detailed", |
| 9030 | "/home/user/Downloads/reelb.mkv", |
| 9031 | "1200", |
| 9032 | ), |
| 9033 | ( |
| 9034 | "film", |
| 9035 | "/home/user/Videos/Films/reelc.mkv", |
| 9036 | "600", |
| 9037 | ), |
| 9038 | ]; |
| 9039 | for &(label, clip, skip) in frames { |
| 9040 | if !std::path::Path::new(clip).exists() { |
| 9041 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 9042 | continue; |
| 9043 | } |
| 9044 | let picture = clip_frame(clip, skip, width, height); |
| 9045 | for &q in &[60u8, 150] { |
| 9046 | |
| 9047 | |
| 9048 | |
| 9049 | set_test_top_k_override(None); |
| 9050 | let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 9051 | let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y); |
| 9052 | eprint!( |
| 9053 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 9054 | baseline.stream.len(), |
| 9055 | baseline_psnr |
| 9056 | ); |
| 9057 | for &k in &[3usize, 4, 6] { |
| 9058 | set_test_top_k_override(Some(k)); |
| 9059 | let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap(); |
| 9060 | let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y); |
| 9061 | eprint!( |
| 9062 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 9063 | pruned.stream.len(), |
| 9064 | pruned_psnr, |
| 9065 | pruned_psnr - baseline_psnr |
| 9066 | ); |
| 9067 | } |
| 9068 | eprintln!(); |
| 9069 | } |
| 9070 | } |
| 9071 | set_test_top_k_override(None); |
| 9072 | } |
| 9073 | |
| 9074 | |
| 9075 | |
| 9076 | fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] { |
| 9077 | let out = Command::new("ffmpeg") |
| 9078 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"]) |
| 9079 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 9080 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 9081 | .output() |
| 9082 | .expect("ffmpeg failed to run"); |
| 9083 | assert!( |
| 9084 | out.status.success(), |
| 9085 | "ffmpeg: {}", |
| 9086 | String::from_utf8_lossy(&out.stderr) |
| 9087 | ); |
| 9088 | let (luma, chroma) = (width * height, width * height / 4); |
| 9089 | let frame_len = luma + 2 * chroma; |
| 9090 | assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames"); |
| 9091 | std::array::from_fn(|i| { |
| 9092 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 9093 | Picture { |
| 9094 | width, |
| 9095 | height, |
| 9096 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 9097 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 9098 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 9099 | } |
| 9100 | }) |
| 9101 | } |
| 9102 | |
| 9103 | |
| 9104 | |
| 9105 | |
| 9106 | |
| 9107 | |
| 9108 | |
| 9109 | |
| 9110 | |
| 9111 | #[test] |
| 9112 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 9113 | fn prune_k_quality_sweep_inter() { |
| 9114 | let fctx = &crate::decode::FrameCtx::new(); |
| 9115 | if !have_ffmpeg() { |
| 9116 | eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg"); |
| 9117 | return; |
| 9118 | } |
| 9119 | let (width, height) = (1280usize, 704usize); |
| 9120 | let frames: &[(&str, &str, &str)] = &[ |
| 9121 | ( |
| 9122 | "dark/flat", |
| 9123 | "/home/user/Videos/reela.mp4", |
| 9124 | "3", |
| 9125 | ), |
| 9126 | ( |
| 9127 | "detailed", |
| 9128 | "/home/user/Downloads/reelb.mkv", |
| 9129 | "1200", |
| 9130 | ), |
| 9131 | ( |
| 9132 | "film", |
| 9133 | "/home/user/Videos/Films/reelc.mkv", |
| 9134 | "600", |
| 9135 | ), |
| 9136 | ]; |
| 9137 | for &(label, clip, skip) in frames { |
| 9138 | if !std::path::Path::new(clip).exists() { |
| 9139 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 9140 | continue; |
| 9141 | } |
| 9142 | let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height); |
| 9143 | for &q in &[60u8, 150] { |
| 9144 | |
| 9145 | |
| 9146 | |
| 9147 | set_test_top_k_override_inter(None); |
| 9148 | let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap(); |
| 9149 | let baseline = encode_inter_frame( |
| 9150 | &inter_source, |
| 9151 | &key.reconstruction, |
| 9152 | q, |
| 9153 | 0.5, |
| 9154 | 1, |
| 9155 | flat_order_hints(1, 0, false), |
| 9156 | (width, height), None, None, None, fctx, None, |
| 9157 | ) |
| 9158 | .unwrap(); |
| 9159 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| 9160 | eprint!( |
| 9161 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 9162 | baseline.stream.len(), |
| 9163 | baseline_psnr |
| 9164 | ); |
| 9165 | for &k in &[3usize, 4, 6] { |
| 9166 | set_test_top_k_override_inter(Some(k)); |
| 9167 | let pruned = encode_inter_frame( |
| 9168 | &inter_source, |
| 9169 | &key.reconstruction, |
| 9170 | q, |
| 9171 | 0.5, |
| 9172 | 1, |
| 9173 | flat_order_hints(1, 0, false), |
| 9174 | (width, height), None, None, None, fctx, None, |
| 9175 | ) |
| 9176 | .unwrap(); |
| 9177 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
| 9178 | eprint!( |
| 9179 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 9180 | pruned.stream.len(), |
| 9181 | pruned_psnr, |
| 9182 | pruned_psnr - baseline_psnr |
| 9183 | ); |
| 9184 | } |
| 9185 | eprintln!(); |
| 9186 | } |
| 9187 | } |
| 9188 | set_test_top_k_override_inter(None); |
| 9189 | } |
| 9190 | |
| 9191 | |
| 9192 | |
| 9193 | |
| 9194 | fn clip_frames( |
| 9195 | clip: &str, |
| 9196 | skip: &str, |
| 9197 | width: usize, |
| 9198 | height: usize, |
| 9199 | frames: usize, |
| 9200 | ) -> Vec<Picture> { |
| 9201 | let out = Command::new("ffmpeg") |
| 9202 | .args(["-v", "error", "-ss", skip, "-i", clip]) |
| 9203 | .args(["-frames:v", &frames.to_string()]) |
| 9204 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 9205 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 9206 | .output() |
| 9207 | .expect("ffmpeg failed to run"); |
| 9208 | assert!( |
| 9209 | out.status.success(), |
| 9210 | "ffmpeg: {}", |
| 9211 | String::from_utf8_lossy(&out.stderr) |
| 9212 | ); |
| 9213 | let (luma, chroma) = (width * height, width * height / 4); |
| 9214 | let frame_len = luma + 2 * chroma; |
| 9215 | assert_eq!( |
| 9216 | out.stdout.len(), |
| 9217 | frame_len * frames, |
| 9218 | "expected {frames} 4:2:0 frames" |
| 9219 | ); |
| 9220 | (0..frames) |
| 9221 | .map(|i| { |
| 9222 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 9223 | Picture { |
| 9224 | width, |
| 9225 | height, |
| 9226 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 9227 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 9228 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 9229 | } |
| 9230 | }) |
| 9231 | .collect() |
| 9232 | } |
| 9233 | |
| 9234 | |
| 9235 | |
| 9236 | |
| 9237 | |
| 9238 | |
| 9239 | |
| 9240 | |
| 9241 | |
| 9242 | |
| 9243 | |
| 9244 | |
| 9245 | |
| 9246 | |
| 9247 | |
| 9248 | |
| 9249 | |
| 9250 | |
| 9251 | |
| 9252 | #[test] |
| 9253 | fn real_clip_encodes_within_its_quality_and_size_budget() { |
| 9254 | let fctx = &crate::decode::FrameCtx::new(); |
| 9255 | if !have_ffmpeg() { |
| 9256 | eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg"); |
| 9257 | return; |
| 9258 | } |
| 9259 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 9260 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 9261 | if !clip.exists() { |
| 9262 | eprintln!( |
| 9263 | "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing", |
| 9264 | clip.display() |
| 9265 | ); |
| 9266 | return; |
| 9267 | } |
| 9268 | let (width, height, frame_count) = (640usize, 384usize, 12usize); |
| 9269 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 9270 | let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 9271 | assert_eq!(encoded.frames.len(), frame_count); |
| 9272 | |
| 9273 | |
| 9274 | |
| 9275 | |
| 9276 | |
| 9277 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 9278 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 9279 | |
| 9280 | |
| 9281 | let mean_psnr: f64 = decoded |
| 9282 | .iter() |
| 9283 | .zip(&source) |
| 9284 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 9285 | .sum::<f64>() |
| 9286 | / frame_count as f64; |
| 9287 | assert!( |
| 9288 | mean_psnr >= 44.91, |
| 9289 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor" |
| 9290 | ); |
| 9291 | |
| 9292 | |
| 9293 | assert!( |
| 9294 | encoded.stream.len() <= 80_340, |
| 9295 | "stream grew to {} bytes, over the 80340-byte ceiling", |
| 9296 | encoded.stream.len() |
| 9297 | ); |
| 9298 | } |
| 9299 | |
| 9300 | |
| 9301 | |
| 9302 | |
| 9303 | |
| 9304 | |
| 9305 | |
| 9306 | |
| 9307 | |
| 9308 | |
| 9309 | |
| 9310 | |
| 9311 | |
| 9312 | |
| 9313 | #[test] |
| 9314 | fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() { |
| 9315 | let fctx = &crate::decode::FrameCtx::new(); |
| 9316 | if !have_ffmpeg() { |
| 9317 | eprintln!( |
| 9318 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 9319 | no ffmpeg" |
| 9320 | ); |
| 9321 | return; |
| 9322 | } |
| 9323 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 9324 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 9325 | if !clip.exists() { |
| 9326 | eprintln!( |
| 9327 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 9328 | {} missing", |
| 9329 | clip.display() |
| 9330 | ); |
| 9331 | return; |
| 9332 | } |
| 9333 | let (width, height, frame_count) = (704usize, 400usize, 8usize); |
| 9334 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 9335 | let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap(); |
| 9336 | assert_eq!(encoded.frames.len(), frame_count); |
| 9337 | |
| 9338 | |
| 9339 | |
| 9340 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 9341 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 9342 | |
| 9343 | |
| 9344 | let mean_psnr: f64 = decoded |
| 9345 | .iter() |
| 9346 | .zip(&source) |
| 9347 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 9348 | .sum::<f64>() |
| 9349 | / frame_count as f64; |
| 9350 | assert!( |
| 9351 | mean_psnr >= 44.98, |
| 9352 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor" |
| 9353 | ); |
| 9354 | |
| 9355 | |
| 9356 | assert!( |
| 9357 | encoded.stream.len() <= 62_703, |
| 9358 | "stream grew to {} bytes, over the 62703-byte ceiling", |
| 9359 | encoded.stream.len() |
| 9360 | ); |
| 9361 | } |
| 9362 | |
| 9363 | |
| 9364 | |
| 9365 | |
| 9366 | |
| 9367 | |
| 9368 | |
| 9369 | #[test] |
| 9370 | #[ignore = "a perf probe, not a gate"] |
| 9371 | fn sequence_bench_sanity() { |
| 9372 | let fctx = &crate::decode::FrameCtx::new(); |
| 9373 | use std::time::Instant; |
| 9374 | let (width, height) = (1280usize, 720usize); |
| 9375 | let pictures: Vec<Picture> = (0..24) |
| 9376 | .map(|i| panned_test_card(width, height, i * 3)) |
| 9377 | .collect(); |
| 9378 | let t = Instant::now(); |
| 9379 | let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap(); |
| 9380 | let elapsed = t.elapsed(); |
| 9381 | let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum(); |
| 9382 | eprintln!( |
| 9383 | "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes", |
| 9384 | elapsed / 24 |
| 9385 | ); |
| 9386 | } |
| 9387 | |
| 9388 | |
| 9389 | |
| 9390 | |
| 9391 | |
| 9392 | #[test] |
| 9393 | #[ignore = "a calibration probe, not a gate"] |
| 9394 | fn calibration_sweep_base_q_idx() { |
| 9395 | let fctx = &crate::decode::FrameCtx::new(); |
| 9396 | if !have_ffmpeg() { |
| 9397 | eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg"); |
| 9398 | return; |
| 9399 | } |
| 9400 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 9401 | for clip in [ |
| 9402 | "h264-1080p-23.976-8bit.mp4", |
| 9403 | "h264-1080p-60-8bit.mp4", |
| 9404 | ] { |
| 9405 | let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 9406 | .join("../../fixtures/video") |
| 9407 | .join(clip); |
| 9408 | if !path.exists() { |
| 9409 | eprintln!("SKIP {clip}: fixture missing"); |
| 9410 | continue; |
| 9411 | } |
| 9412 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 9413 | eprintln!("--- {clip} ---"); |
| 9414 | for q in [40u8, 70, 100, 130, 160, 190, 220, 240] { |
| 9415 | let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap(); |
| 9416 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames); |
| 9417 | let mean_psnr: f64 = decoded |
| 9418 | .iter() |
| 9419 | .zip(&source) |
| 9420 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 9421 | .sum::<f64>() |
| 9422 | / frames as f64; |
| 9423 | let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64; |
| 9424 | eprintln!( |
| 9425 | "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB", |
| 9426 | encoded.stream.len() |
| 9427 | ); |
| 9428 | } |
| 9429 | } |
| 9430 | } |
| 9431 | |
| 9432 | |
| 9433 | |
| 9434 | |
| 9435 | |
| 9436 | |
| 9437 | |
| 9438 | |
| 9439 | |
| 9440 | |
| 9441 | fn psnr_all(decoded: &Picture, source: &Picture) -> f64 { |
| 9442 | let cat = |p: &Picture| { |
| 9443 | let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len()); |
| 9444 | v.extend_from_slice(&p.y); |
| 9445 | v.extend_from_slice(&p.u); |
| 9446 | v.extend_from_slice(&p.v); |
| 9447 | v |
| 9448 | }; |
| 9449 | psnr(&cat(decoded), &cat(source)) |
| 9450 | } |
| 9451 | |
| 9452 | |
| 9453 | fn raw_yuv420p(source: &[Picture]) -> Vec<u8> { |
| 9454 | let mut raw = Vec::new(); |
| 9455 | for p in source { |
| 9456 | for plane in [&p.y, &p.u, &p.v] { |
| 9457 | raw.extend(plane.iter().map(|&s| s as u8)); |
| 9458 | } |
| 9459 | } |
| 9460 | raw |
| 9461 | } |
| 9462 | |
| 9463 | |
| 9464 | |
| 9465 | |
| 9466 | |
| 9467 | |
| 9468 | fn external_ladder( |
| 9469 | source: &[Picture], |
| 9470 | width: usize, |
| 9471 | height: usize, |
| 9472 | encoder: &str, |
| 9473 | points: &[Vec<String>], |
| 9474 | ) -> (Vec<(f64, f64)>, f64) { |
| 9475 | |
| 9476 | let dir = std::env::temp_dir(); |
| 9477 | let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id())); |
| 9478 | std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source"); |
| 9479 | let mut ladder = Vec::new(); |
| 9480 | let mut wall = 0.0; |
| 9481 | for (i, params) in points.iter().enumerate() { |
| 9482 | let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id())); |
| 9483 | let start = std::time::Instant::now(); |
| 9484 | let out = Command::new("ffmpeg") |
| 9485 | .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) |
| 9486 | .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"]) |
| 9487 | .arg(&raw_path) |
| 9488 | .args(["-an", "-threads", "1"]) |
| 9489 | .args(["-g", &source.len().to_string(), "-c:v", encoder]) |
| 9490 | .args(params) |
| 9491 | .args(["-f", "obu"]) |
| 9492 | .arg(&obu) |
| 9493 | .output() |
| 9494 | .expect("ffmpeg failed to run"); |
| 9495 | wall += start.elapsed().as_secs_f64(); |
| 9496 | assert!( |
| 9497 | out.status.success(), |
| 9498 | "{encoder} {params:?}: {}", |
| 9499 | String::from_utf8_lossy(&out.stderr) |
| 9500 | ); |
| 9501 | let stream = std::fs::read(&obu).expect("reference stream"); |
| 9502 | let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); |
| 9503 | let mean: f64 = decoded |
| 9504 | .iter() |
| 9505 | .zip(source) |
| 9506 | .map(|(d, s)| psnr_all(d, s)) |
| 9507 | .sum::<f64>() |
| 9508 | / source.len() as f64; |
| 9509 | ladder.push((mean, (stream.len() as f64).log10())); |
| 9510 | let _ = std::fs::remove_file(&obu); |
| 9511 | } |
| 9512 | let _ = std::fs::remove_file(&raw_path); |
| 9513 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 9514 | (ladder, wall) |
| 9515 | } |
| 9516 | |
| 9517 | |
| 9518 | |
| 9519 | |
| 9520 | |
| 9521 | fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> { |
| 9522 | for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] { |
| 9523 | if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) { |
| 9524 | return Some((plane, i, i64::from(l[i]), i64::from(r[i]))); |
| 9525 | } |
| 9526 | if l.len() != r.len() { |
| 9527 | return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64)); |
| 9528 | } |
| 9529 | } |
| 9530 | None |
| 9531 | } |
| 9532 | |
| 9533 | |
| 9534 | |
| 9535 | |
| 9536 | |
| 9537 | |
| 9538 | |
| 9539 | |
| 9540 | |
| 9541 | fn our_ladder( |
| 9542 | name: &str, |
| 9543 | source: &[Picture], |
| 9544 | width: usize, |
| 9545 | height: usize, |
| 9546 | fctx: &crate::decode::FrameCtx, |
| 9547 | ) -> (Vec<(f64, f64)>, f64) { |
| 9548 | let mut ladder = Vec::new(); |
| 9549 | let mut wall = 0.0; |
| 9550 | for &q in &[150u8, 120, 90, 60] { |
| 9551 | let start = std::time::Instant::now(); |
| 9552 | let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap(); |
| 9553 | wall += start.elapsed().as_secs_f64(); |
| 9554 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len()); |
| 9555 | let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder"); |
| 9556 | assert_eq!( |
| 9557 | ours.len(), |
| 9558 | source.len(), |
| 9559 | "{name} q={q}: our decoder's display-order frame count" |
| 9560 | ); |
| 9561 | for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() { |
| 9562 | if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) { |
| 9563 | panic!( |
| 9564 | "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \ |
| 9565 | {got}, the encoder reconstructed {want}" |
| 9566 | ); |
| 9567 | } |
| 9568 | } |
| 9569 | for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() { |
| 9570 | if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) { |
| 9571 | panic!( |
| 9572 | "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \ |
| 9573 | {got}, the encoder reconstructed {want}" |
| 9574 | ); |
| 9575 | } |
| 9576 | } |
| 9577 | let mean: f64 = decoded |
| 9578 | .iter() |
| 9579 | .zip(source) |
| 9580 | .map(|(d, s)| psnr_all(d, s)) |
| 9581 | .sum::<f64>() |
| 9582 | / source.len() as f64; |
| 9583 | ladder.push((mean, (encoded.stream.len() as f64).log10())); |
| 9584 | } |
| 9585 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 9586 | (ladder, wall) |
| 9587 | } |
| 9588 | |
| 9589 | |
| 9590 | |
| 9591 | |
| 9592 | |
| 9593 | fn pyramid_from_env() -> Option<crate::encoder::Pyramid> { |
| 9594 | let spec = std::env::var("EC_AV1_PYRAMID").ok()?; |
| 9595 | let mut f = spec.split(':'); |
| 9596 | let mini_gop = f.next()?.parse().ok()?; |
| 9597 | let d = crate::encoder::Pyramid::default(); |
| 9598 | Some(crate::encoder::Pyramid { |
| 9599 | mini_gop, |
| 9600 | arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), |
| 9601 | leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), |
| 9602 | }) |
| 9603 | } |
| 9604 | |
| 9605 | |
| 9606 | |
| 9607 | |
| 9608 | |
| 9609 | |
| 9610 | |
| 9611 | fn our_ladder_pyramid( |
| 9612 | name: &str, |
| 9613 | source: &[Picture], |
| 9614 | width: usize, |
| 9615 | height: usize, |
| 9616 | pyramid: crate::encoder::Pyramid, |
| 9617 | ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4]) { |
| 9618 | use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level}; |
| 9619 | let slot = |l: Level| match l { |
| 9620 | Level::Key => 0, |
| 9621 | Level::Arf => 1, |
| 9622 | Level::Leaf => 2, |
| 9623 | Level::ShowExisting => 3, |
| 9624 | }; |
| 9625 | let mut ladder = Vec::new(); |
| 9626 | let mut wall = 0.0; |
| 9627 | let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]); |
| 9628 | for &q in &[150u8, 120, 90, 60] { |
| 9629 | let config = EncoderConfig { |
| 9630 | width, |
| 9631 | height, |
| 9632 | base_q_idx: q, |
| 9633 | gop: source.len(), |
| 9634 | colour: Colour::Unspecified, |
| 9635 | tile_cols_log2: 0, |
| 9636 | tile_rows_log2: 0, |
| 9637 | }; |
| 9638 | let start = std::time::Instant::now(); |
| 9639 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 9640 | let mut packets = Vec::new(); |
| 9641 | for picture in source { |
| 9642 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 9643 | } |
| 9644 | packets.extend(enc.flush().unwrap()); |
| 9645 | wall += start.elapsed().as_secs_f64(); |
| 9646 | let mut stream = Vec::new(); |
| 9647 | for p in &packets { |
| 9648 | counts[slot(p.level)] += 1; |
| 9649 | bytes[slot(p.level)] += p.data.len(); |
| 9650 | stream.extend_from_slice(&p.data); |
| 9651 | } |
| 9652 | |
| 9653 | |
| 9654 | |
| 9655 | |
| 9656 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 9657 | assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count"); |
| 9658 | let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len()); |
| 9659 | for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() { |
| 9660 | if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) { |
| 9661 | panic!( |
| 9662 | "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \ |
| 9663 | decoded {got}, our decoder decoded {want}" |
| 9664 | ); |
| 9665 | } |
| 9666 | } |
| 9667 | let mean: f64 = decoded |
| 9668 | .iter() |
| 9669 | .zip(source) |
| 9670 | .map(|(d, s)| psnr_all(d, s)) |
| 9671 | .sum::<f64>() |
| 9672 | / source.len() as f64; |
| 9673 | ladder.push((mean, (stream.len() as f64).log10())); |
| 9674 | } |
| 9675 | ladder.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 9676 | (ladder, wall, counts, bytes) |
| 9677 | } |
| 9678 | |
| 9679 | |
| 9680 | |
| 9681 | |
| 9682 | |
| 9683 | |
| 9684 | |
| 9685 | |
| 9686 | |
| 9687 | |
| 9688 | |
| 9689 | #[test] |
| 9690 | fn the_encoders_own_streams_are_byte_identical_to_their_pins() { |
| 9691 | if !have_ffmpeg() { |
| 9692 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg"); |
| 9693 | return; |
| 9694 | } |
| 9695 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 9696 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 9697 | if !clip.exists() { |
| 9698 | eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip"); |
| 9699 | return; |
| 9700 | } |
| 9701 | let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4); |
| 9702 | |
| 9703 | |
| 9704 | let fnv = |b: &[u8]| { |
| 9705 | b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| { |
| 9706 | (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3) |
| 9707 | }) |
| 9708 | }; |
| 9709 | let pins: [(u8, usize, u64); 2] = |
| 9710 | [(150, 7084, 0xe6a9_2f62_3855_0eee), (60, 26116, 0xa831_9866_b799_80fc)]; |
| 9711 | for (q, bytes, hash) in pins { |
| 9712 | let encoded = encode_sequence(&source, q, 0.5).unwrap(); |
| 9713 | assert_eq!( |
| 9714 | (encoded.stream.len(), fnv(&encoded.stream)), |
| 9715 | (bytes, hash), |
| 9716 | "q={q}: the encoder's stream moved" |
| 9717 | ); |
| 9718 | } |
| 9719 | } |
| 9720 | |
| 9721 | |
| 9722 | fn assert_monotone(name: &str, ladder: &[(f64, f64)]) { |
| 9723 | assert_eq!(ladder.len(), 4, "{name}: wanted four quality points"); |
| 9724 | for w in ladder.windows(2) { |
| 9725 | assert!( |
| 9726 | w[1].0 > w[0].0 && w[1].1 > w[0].1, |
| 9727 | "{name}: not monotone, {ladder:?}" |
| 9728 | ); |
| 9729 | } |
| 9730 | } |
| 9731 | |
| 9732 | |
| 9733 | |
| 9734 | |
| 9735 | |
| 9736 | #[test] |
| 9737 | #[ignore = "reads the real library"] |
| 9738 | fn probe_screen_detect() { |
| 9739 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 9740 | let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); |
| 9741 | for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] { |
| 9742 | let path = fixtures.join("video").join(name); |
| 9743 | if path.exists() { |
| 9744 | clips.push((name.to_string(), path)); |
| 9745 | } |
| 9746 | } |
| 9747 | if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) |
| 9748 | && let Some(p) = manifest |
| 9749 | .lines() |
| 9750 | .skip(1) |
| 9751 | .filter_map(|l| l.split('\t').next()) |
| 9752 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()) |
| 9753 | { |
| 9754 | clips.push(("screen".to_string(), std::path::PathBuf::from(p))); |
| 9755 | } |
| 9756 | let (width, height) = (640usize, 384usize); |
| 9757 | for (name, path) in &clips { |
| 9758 | let frames = clip_frames(path.to_str().unwrap(), "0", width, height, 4); |
| 9759 | for (f, picture) in frames.iter().enumerate() { |
| 9760 | let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 9761 | let mut hist = [0usize; 257]; |
| 9762 | let mut blocks = 0usize; |
| 9763 | for by in (0..height).step_by(16) { |
| 9764 | for bx in (0..width).step_by(16) { |
| 9765 | let mut seen = [false; 256]; |
| 9766 | let mut colors = 0usize; |
| 9767 | for row in 0..16 { |
| 9768 | for col in 0..16 { |
| 9769 | let v = usize::from(y[(by + row) * width + bx + col]); |
| 9770 | if !seen[v] { |
| 9771 | seen[v] = true; |
| 9772 | colors += 1; |
| 9773 | } |
| 9774 | } |
| 9775 | } |
| 9776 | hist[colors] += 1; |
| 9777 | blocks += 1; |
| 9778 | } |
| 9779 | } |
| 9780 | let share = |limit: usize| { |
| 9781 | 100.0 * hist[2..=limit.min(256)].iter().sum::<usize>() as f64 |
| 9782 | / blocks.max(1) as f64 |
| 9783 | }; |
| 9784 | eprintln!( |
| 9785 | "{name} frame {f}: <=4 {:.1}% <=8 {:.1}% <=16 {:.1}% <=32 {:.1}% <=64 {:.1}% <=128 {:.1}%", |
| 9786 | share(4), |
| 9787 | share(8), |
| 9788 | share(16), |
| 9789 | share(32), |
| 9790 | share(64), |
| 9791 | share(128), |
| 9792 | ); |
| 9793 | } |
| 9794 | } |
| 9795 | } |
| 9796 | |
| 9797 | |
| 9798 | |
| 9799 | |
| 9800 | |
| 9801 | |
| 9802 | |
| 9803 | |
| 9804 | |
| 9805 | |
| 9806 | |
| 9807 | |
| 9808 | |
| 9809 | |
| 9810 | |
| 9811 | |
| 9812 | |
| 9813 | |
| 9814 | |
| 9815 | |
| 9816 | |
| 9817 | |
| 9818 | |
| 9819 | |
| 9820 | |
| 9821 | |
| 9822 | |
| 9823 | |
| 9824 | |
| 9825 | |
| 9826 | |
| 9827 | |
| 9828 | |
| 9829 | |
| 9830 | |
| 9831 | |
| 9832 | |
| 9833 | |
| 9834 | |
| 9835 | |
| 9836 | |
| 9837 | |
| 9838 | |
| 9839 | |
| 9840 | |
| 9841 | |
| 9842 | |
| 9843 | |
| 9844 | |
| 9845 | |
| 9846 | |
| 9847 | |
| 9848 | |
| 9849 | |
| 9850 | |
| 9851 | |
| 9852 | |
| 9853 | |
| 9854 | |
| 9855 | |
| 9856 | |
| 9857 | |
| 9858 | |
| 9859 | |
| 9860 | |
| 9861 | |
| 9862 | |
| 9863 | |
| 9864 | |
| 9865 | |
| 9866 | |
| 9867 | |
| 9868 | |
| 9869 | |
| 9870 | |
| 9871 | |
| 9872 | |
| 9873 | |
| 9874 | |
| 9875 | |
| 9876 | |
| 9877 | #[test] |
| 9878 | #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"] |
| 9879 | fn bd_rate_vs_libaom_and_rav1e() { |
| 9880 | if !have_ffmpeg() { |
| 9881 | eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg"); |
| 9882 | return; |
| 9883 | } |
| 9884 | let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures"); |
| 9885 | let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new(); |
| 9886 | for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] { |
| 9887 | let path = fixtures.join("video").join(name); |
| 9888 | if path.exists() { |
| 9889 | clips.push((name.to_string(), path)); |
| 9890 | } else { |
| 9891 | eprintln!("SKIP clip {name}: missing"); |
| 9892 | } |
| 9893 | } |
| 9894 | |
| 9895 | |
| 9896 | match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) { |
| 9897 | Ok(manifest) => { |
| 9898 | let screen = manifest |
| 9899 | .lines() |
| 9900 | .skip(1) |
| 9901 | .filter_map(|l| l.split('\t').next()) |
| 9902 | .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists()); |
| 9903 | match screen { |
| 9904 | Some(p) => clips.push(( |
| 9905 | format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)), |
| 9906 | std::path::PathBuf::from(p), |
| 9907 | )), |
| 9908 | None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"), |
| 9909 | } |
| 9910 | } |
| 9911 | Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"), |
| 9912 | } |
| 9913 | assert!(!clips.is_empty(), "no source clip available"); |
| 9914 | |
| 9915 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 9916 | let aom_points: Vec<Vec<String>> = [5, 20, 35, 45] |
| 9917 | .iter() |
| 9918 | .map(|q| { |
| 9919 | ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()] |
| 9920 | .map(String::from) |
| 9921 | .to_vec() |
| 9922 | }) |
| 9923 | .collect(); |
| 9924 | let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200] |
| 9925 | .iter() |
| 9926 | .map(|q| { |
| 9927 | vec![ |
| 9928 | "-rav1e-params".to_string(), |
| 9929 | format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"), |
| 9930 | ] |
| 9931 | }) |
| 9932 | .collect(); |
| 9933 | println!( |
| 9934 | "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread" |
| 9935 | ); |
| 9936 | println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |"); |
| 9937 | println!("|---|---|---|---|---|"); |
| 9938 | for (name, path) in &clips { |
| 9939 | let fctx = &crate::decode::FrameCtx::new(); |
| 9940 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 9941 | let _ = take_partition_hits(); |
| 9942 | let _ = crate::tile::take_palette_hits(); |
| 9943 | SCREEN_FRAMES.iter().for_each(|c| { |
| 9944 | c.store(0, std::sync::atomic::Ordering::Relaxed); |
| 9945 | }); |
| 9946 | let _ = take_uv_mode_hits(); |
| 9947 | let _ = crate::tile::take_inter_mode_hits(); |
| 9948 | let _ = crate::tile::take_drl_hits(); |
| 9949 | let _ = crate::tile::take_ref_hits(); |
| 9950 | let _ = crate::tile::take_compound_mode_hits(); |
| 9951 | let _ = crate::tile::take_compound_pair_hits(); |
| 9952 | let _ = crate::tile::take_compound_size_hits(); |
| 9953 | let _ = crate::motion::take_census(); |
| 9954 | let (ours, ours_wall) = match pyramid_from_env() { |
| 9955 | None => our_ladder(name, &source, width, height, fctx), |
| 9956 | Some(pyramid) => { |
| 9957 | let (ladder, wall, counts, bytes) = |
| 9958 | our_ladder_pyramid(name, &source, width, height, pyramid); |
| 9959 | eprintln!( |
| 9960 | "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \ |
| 9961 | show_existing {}; bytes key {} arf {} leaf {} show_existing {}", |
| 9962 | counts[0], counts[1], counts[2], counts[3], |
| 9963 | bytes[0], bytes[1], bytes[2], bytes[3], |
| 9964 | ); |
| 9965 | (ladder, wall) |
| 9966 | } |
| 9967 | }; |
| 9968 | |
| 9969 | |
| 9970 | |
| 9971 | let [whole32, split32, whole16, split16] = take_partition_hits(); |
| 9972 | |
| 9973 | |
| 9974 | |
| 9975 | let [nearest, near, global, new] = crate::tile::take_inter_mode_hits(); |
| 9976 | let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits(); |
| 9977 | let refs = crate::tile::take_ref_hits(); |
| 9978 | let modes_total = (nearest + near + global + new).max(1); |
| 9979 | eprintln!( |
| 9980 | "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \ |
| 9981 | GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \ |
| 9982 | {drl0}/{drl1}/{drl2}/{drl3}", |
| 9983 | 100.0 * nearest as f64 / modes_total as f64, |
| 9984 | 100.0 * near as f64 / modes_total as f64, |
| 9985 | 100.0 * global as f64 / modes_total as f64, |
| 9986 | 100.0 * new as f64 / modes_total as f64, |
| 9987 | ); |
| 9988 | |
| 9989 | |
| 9990 | |
| 9991 | |
| 9992 | let comp_modes = crate::tile::take_compound_mode_hits(); |
| 9993 | let comp_pairs = crate::tile::take_compound_pair_hits(); |
| 9994 | let comp_sizes = crate::tile::take_compound_size_hits(); |
| 9995 | let comp_total: usize = comp_modes.iter().sum(); |
| 9996 | eprintln!( |
| 9997 | "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \ |
| 9998 | NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \ |
| 9999 | GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}", |
| 10000 | modes_total + comp_total, |
| 10001 | 100.0 * comp_total as f64 / (modes_total + comp_total) as f64, |
| 10002 | comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3], |
| 10003 | comp_modes[6], comp_modes[7], |
| 10004 | comp_pairs[3], comp_pairs[6], |
| 10005 | ); |
| 10006 | eprintln!( |
| 10007 | "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}", |
| 10008 | comp_sizes[1], comp_sizes[2], comp_sizes[3], |
| 10009 | ); |
| 10010 | |
| 10011 | |
| 10012 | |
| 10013 | |
| 10014 | let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census(); |
| 10015 | let per = |n: u64| n as f64 / calls.max(1) as f64; |
| 10016 | eprintln!( |
| 10017 | "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \ |
| 10018 | {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \ |
| 10019 | +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%", |
| 10020 | per(evals), |
| 10021 | 100.0 * subpel as f64 / evals.max(1) as f64, |
| 10022 | per(rounds), |
| 10023 | 100.0 * near_pred as f64 / calls.max(1) as f64, |
| 10024 | 100.0 * unmoved as f64 / calls.max(1) as f64, |
| 10025 | ); |
| 10026 | eprintln!( |
| 10027 | "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})", |
| 10028 | refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6] |
| 10029 | ); |
| 10030 | eprintln!( |
| 10031 | "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \ |
| 10032 | 16x16 leaves split into 8s {split16} of {} ({:.1}%)", |
| 10033 | whole32 + split32, |
| 10034 | 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64, |
| 10035 | whole16 + split16, |
| 10036 | 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64 |
| 10037 | ); |
| 10038 | |
| 10039 | |
| 10040 | let levels = crate::filter_search::take_chosen_levels(); |
| 10041 | type Chosen = ((u8, u8), (u8, u8), (u8, u8)); |
| 10042 | let mean = |f: fn(&Chosen) -> u8| { |
| 10043 | levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64 |
| 10044 | }; |
| 10045 | eprintln!( |
| 10046 | "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \ |
| 10047 | cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}", |
| 10048 | levels.len(), |
| 10049 | mean(|l| l.0.0), |
| 10050 | mean(|l| l.0.1), |
| 10051 | mean(|l| l.1.0), |
| 10052 | mean(|l| l.1.1), |
| 10053 | mean(|l| l.2.0), |
| 10054 | mean(|l| l.2.1), |
| 10055 | ); |
| 10056 | |
| 10057 | |
| 10058 | |
| 10059 | let presets = crate::filter_search::take_cdef_presets(); |
| 10060 | let mut by_bits = [0usize; 4]; |
| 10061 | for (b, _) in &presets { |
| 10062 | by_bits[usize::from(*b)] += 1; |
| 10063 | } |
| 10064 | let units: usize = presets.iter().flat_map(|(_, c)| c).sum(); |
| 10065 | let on_extra: usize = presets |
| 10066 | .iter() |
| 10067 | .flat_map(|(_, c)| c.iter().skip(1)) |
| 10068 | .sum(); |
| 10069 | eprintln!( |
| 10070 | "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \ |
| 10071 | on a non-default preset ({:.1}%)", |
| 10072 | by_bits[0], |
| 10073 | by_bits[1], |
| 10074 | by_bits[2], |
| 10075 | by_bits[3], |
| 10076 | on_extra, |
| 10077 | units, |
| 10078 | 100.0 * on_extra as f64 / units.max(1) as f64 |
| 10079 | ); |
| 10080 | |
| 10081 | |
| 10082 | let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram(); |
| 10083 | eprintln!( |
| 10084 | "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)", |
| 10085 | 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64 |
| 10086 | ); |
| 10087 | |
| 10088 | |
| 10089 | |
| 10090 | |
| 10091 | |
| 10092 | |
| 10093 | |
| 10094 | let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed); |
| 10095 | let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed); |
| 10096 | let palette = crate::tile::take_palette_hits(); |
| 10097 | eprintln!( |
| 10098 | "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}", |
| 10099 | palette[0], |
| 10100 | (2..=8) |
| 10101 | .filter(|&n| palette[n] > 0) |
| 10102 | .map(|n| format!("{n}={}", palette[n])) |
| 10103 | .collect::<Vec<_>>() |
| 10104 | .join(" ") |
| 10105 | ); |
| 10106 | let palette_uv = crate::tile::take_palette_uv_hits(); |
| 10107 | eprintln!( |
| 10108 | "{name}: chroma palette blocks {} sizes {}", |
| 10109 | palette_uv[0], |
| 10110 | (2..=8) |
| 10111 | .filter(|&n| palette_uv[n] > 0) |
| 10112 | .map(|n| format!("{n}={}", palette_uv[n])) |
| 10113 | .collect::<Vec<_>>() |
| 10114 | .join(" ") |
| 10115 | ); |
| 10116 | let uv = take_uv_mode_hits(); |
| 10117 | let uv_total: usize = uv.iter().sum(); |
| 10118 | eprintln!( |
| 10119 | "{name}: uv modes {}", |
| 10120 | uv.iter() |
| 10121 | .enumerate() |
| 10122 | .filter(|&(_, &n)| n > 0) |
| 10123 | .map(|(m, &n)| format!( |
| 10124 | "{}={n} ({:.1}%)", |
| 10125 | UV_MODE_NAMES[m], |
| 10126 | 100.0 * n as f64 / uv_total.max(1) as f64 |
| 10127 | )) |
| 10128 | .collect::<Vec<_>>() |
| 10129 | .join(" ") |
| 10130 | ); |
| 10131 | |
| 10132 | |
| 10133 | |
| 10134 | let depths = take_tx_depth_hits(); |
| 10135 | let depth_total: usize = depths.iter().sum(); |
| 10136 | eprintln!( |
| 10137 | "{name}: intra tx depths {}", |
| 10138 | depths |
| 10139 | .iter() |
| 10140 | .enumerate() |
| 10141 | .map(|(d, &n)| format!( |
| 10142 | "{d}={n} ({:.1}%)", |
| 10143 | 100.0 * n as f64 / depth_total.max(1) as f64 |
| 10144 | )) |
| 10145 | .collect::<Vec<_>>() |
| 10146 | .join(" ") |
| 10147 | ); |
| 10148 | |
| 10149 | |
| 10150 | |
| 10151 | let splits = take_inter_tx_split_hits(); |
| 10152 | let split_total: usize = splits.iter().sum(); |
| 10153 | eprintln!( |
| 10154 | "{name}: inter var-tx depths {}", |
| 10155 | splits |
| 10156 | .iter() |
| 10157 | .enumerate() |
| 10158 | .map(|(d, &n)| format!( |
| 10159 | "{d}={n} ({:.1}%)", |
| 10160 | 100.0 * n as f64 / split_total.max(1) as f64 |
| 10161 | )) |
| 10162 | .collect::<Vec<_>>() |
| 10163 | .join(" ") |
| 10164 | ); |
| 10165 | let (aom, aom_wall) = |
| 10166 | external_ladder(&source, width, height, "libaom-av1", &aom_points); |
| 10167 | let (rav1e, rav1e_wall) = |
| 10168 | external_ladder(&source, width, height, "librav1e", &rav1e_points); |
| 10169 | assert_monotone(&format!("{name}: ours"), &ours); |
| 10170 | assert_monotone(&format!("{name}: libaom"), &aom); |
| 10171 | assert_monotone(&format!("{name}: rav1e"), &rav1e); |
| 10172 | let points = ours |
| 10173 | .iter() |
| 10174 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 10175 | .collect::<Vec<_>>() |
| 10176 | .join(", "); |
| 10177 | println!( |
| 10178 | "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |", |
| 10179 | bd_rate(&aom, &ours) * 100.0, |
| 10180 | bd_rate(&rav1e, &ours) * 100.0, |
| 10181 | ); |
| 10182 | println!( |
| 10183 | "| references | libaom {} | rav1e {} | | |", |
| 10184 | aom.iter() |
| 10185 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 10186 | .collect::<Vec<_>>() |
| 10187 | .join(", "), |
| 10188 | rav1e |
| 10189 | .iter() |
| 10190 | .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b))) |
| 10191 | .collect::<Vec<_>>() |
| 10192 | .join(", "), |
| 10193 | ); |
| 10194 | } |
| 10195 | } |
| 10196 | } |