| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader}; |
| 18 | use ec_av1_syntax::{ |
| 19 | ChromaSamplePosition, FrameHeader, FrameType, PRIMARY_REF_NONE, QuantizationParams, TileInfo, |
| 20 | TxMode, |
| 21 | }; |
| 22 | use ec_core::{Error, Result}; |
| 23 | |
| 24 | use crate::cdf; |
| 25 | use crate::cdf_state::TxbSet; |
| 26 | use crate::frame::frame_obu; |
| 27 | use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED}; |
| 28 | use crate::mc; |
| 29 | use crate::motion; |
| 30 | use crate::mvstack::{MiGrid, MiInfo, MvStack, find_mv_stack}; |
| 31 | use crate::obu::temporal_delimiter; |
| 32 | use crate::quant::ac_q; |
| 33 | use crate::sequence::sequence_header_obu; |
| 34 | use crate::tile::{ |
| 35 | BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits, |
| 36 | sb_coeff_inter_frame_tile, sb_coeff_key_frame_tile, |
| 37 | }; |
| 38 | use crate::transform::{dequant_and_inverse, forward_and_quantize}; |
| 39 | |
| 40 | |
| 41 | |
| 42 | const BLOCK: usize = 32; |
| 43 | |
| 44 | |
| 45 | const SUB: usize = 16; |
| 46 | |
| 47 | |
| 48 | pub(crate) const SUPERBLOCK: usize = 64; |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | thread_local! { |
| 58 | static REACH_SB_PX: std::cell::Cell<usize> = const { std::cell::Cell::new(SUPERBLOCK) }; |
| 59 | } |
| 60 | |
| 61 | |
| 62 | pub(crate) fn set_reach_superblock_px(px: usize) { |
| 63 | REACH_SB_PX.with(|c| c.set(px)); |
| 64 | } |
| 65 | |
| 66 | fn reach_sb_px() -> usize { |
| 67 | REACH_SB_PX.with(|c| c.get()) |
| 68 | } |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | const LAMBDA_SCALE: f64 = 0.1; |
| 81 | |
| 82 | |
| 83 | |
| 84 | fn lambda_scale() -> f64 { |
| 85 | let swept = std::env::var("EC_AV1_LAMBDA") |
| 86 | .ok() |
| 87 | .and_then(|v| v.parse::<f64>().ok()); |
| 88 | match swept { |
| 89 | Some(scale) if cfg!(test) => scale, |
| 90 | _ => LAMBDA_SCALE, |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | |
| 95 | |
| 96 | const SPLIT_BLOCKS: bool = true; |
| 97 | |
| 98 | |
| 99 | |
| 100 | pub(crate) fn split_blocks() -> bool { |
| 101 | SPLIT_BLOCKS |
| 102 | } |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 114 | pub struct Picture { |
| 115 | |
| 116 | pub width: usize, |
| 117 | |
| 118 | pub height: usize, |
| 119 | |
| 120 | pub y: Vec<u16>, |
| 121 | |
| 122 | pub u: Vec<u16>, |
| 123 | |
| 124 | pub v: Vec<u16>, |
| 125 | } |
| 126 | |
| 127 | impl Picture { |
| 128 | |
| 129 | #[must_use] |
| 130 | pub fn grey(width: usize, height: usize) -> Self { |
| 131 | Self { |
| 132 | width, |
| 133 | height, |
| 134 | y: vec![128; width * height], |
| 135 | u: vec![128; width * height / 4], |
| 136 | v: vec![128; width * height / 4], |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | pub(crate) fn check(&self) -> Result<()> { |
| 141 | if self.width == 0 |
| 142 | || !self.width.is_multiple_of(BLOCK) |
| 143 | || !self.height.is_multiple_of(BLOCK) |
| 144 | || !self.height.is_multiple_of(BLOCK) |
| 145 | { |
| 146 | return Err(Error::unsupported( |
| 147 | "AV1 encode", |
| 148 | "the picture must be a whole number of 32x32 blocks in each direction", |
| 149 | )); |
| 150 | } |
| 151 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 152 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 153 | return Err(Error::unsupported( |
| 154 | "AV1 encode", |
| 155 | "each plane must carry one sample per position at 4:2:0", |
| 156 | )); |
| 157 | } |
| 158 | Ok(()) |
| 159 | } |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | pub(crate) fn check_even(&self) -> Result<()> { |
| 166 | if self.width == 0 |
| 167 | || self.height == 0 |
| 168 | || !self.width.is_multiple_of(2) |
| 169 | || !self.height.is_multiple_of(2) |
| 170 | { |
| 171 | return Err(Error::unsupported( |
| 172 | "AV1 encode", |
| 173 | "the picture's width and height must each be even and nonzero", |
| 174 | )); |
| 175 | } |
| 176 | let (luma, chroma) = (self.width * self.height, self.width * self.height / 4); |
| 177 | if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma { |
| 178 | return Err(Error::unsupported( |
| 179 | "AV1 encode", |
| 180 | "each plane must carry one sample per position at 4:2:0", |
| 181 | )); |
| 182 | } |
| 183 | Ok(()) |
| 184 | } |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | pub(crate) fn padded_to(&self, align: usize) -> Picture { |
| 194 | let padded_width = self.width.next_multiple_of(align); |
| 195 | let padded_height = self.height.next_multiple_of(align); |
| 196 | if padded_width == self.width && padded_height == self.height { |
| 197 | return self.clone(); |
| 198 | } |
| 199 | Picture { |
| 200 | width: padded_width, |
| 201 | height: padded_height, |
| 202 | y: pad_plane( |
| 203 | &self.y, |
| 204 | self.width, |
| 205 | self.height, |
| 206 | padded_width, |
| 207 | padded_height, |
| 208 | ), |
| 209 | u: pad_plane( |
| 210 | &self.u, |
| 211 | self.width / 2, |
| 212 | self.height / 2, |
| 213 | padded_width / 2, |
| 214 | padded_height / 2, |
| 215 | ), |
| 216 | v: pad_plane( |
| 217 | &self.v, |
| 218 | self.width / 2, |
| 219 | self.height / 2, |
| 220 | padded_width / 2, |
| 221 | padded_height / 2, |
| 222 | ), |
| 223 | } |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | #[allow(clippy::too_many_arguments)] |
| 234 | fn intra_predict_u8( |
| 235 | mode: u8, |
| 236 | angle_delta: i32, |
| 237 | above: Option<&[u8]>, |
| 238 | left: Option<&[u8]>, |
| 239 | corner: Option<u8>, |
| 240 | bw: usize, |
| 241 | bh: usize, |
| 242 | enable_edge_filter: bool, |
| 243 | smooth_neighbor: bool, |
| 244 | dst: &mut [u8], |
| 245 | ) { |
| 246 | let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect()); |
| 247 | let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect()); |
| 248 | let mut dst16 = vec![0u16; dst.len()]; |
| 249 | crate::intra::predict( |
| 250 | mode, |
| 251 | angle_delta, |
| 252 | above16.as_deref(), |
| 253 | left16.as_deref(), |
| 254 | corner.map(u16::from), |
| 255 | bw, |
| 256 | bh, |
| 257 | enable_edge_filter, |
| 258 | smooth_neighbor, |
| 259 | &mut dst16, |
| 260 | ); |
| 261 | for (d, &s) in dst.iter_mut().zip(dst16.iter()) { |
| 262 | *d = s as u8; |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | |
| 267 | |
| 268 | |
| 269 | fn pad_plane<T: Copy + Default>( |
| 270 | source: &[T], |
| 271 | width: usize, |
| 272 | height: usize, |
| 273 | padded_width: usize, |
| 274 | padded_height: usize, |
| 275 | ) -> Vec<T> { |
| 276 | let mut out = vec![T::default(); padded_width * padded_height]; |
| 277 | for row in 0..padded_height { |
| 278 | let src = source[row.min(height - 1) * width..][..width].as_ref(); |
| 279 | let dst = &mut out[row * padded_width..][..padded_width]; |
| 280 | dst[..width].copy_from_slice(src); |
| 281 | dst[width..].fill(src[width - 1]); |
| 282 | } |
| 283 | out |
| 284 | } |
| 285 | |
| 286 | |
| 287 | |
| 288 | |
| 289 | fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> { |
| 290 | let mut out = Vec::with_capacity(width * height); |
| 291 | for row in 0..height { |
| 292 | out.extend_from_slice(&source[row * padded_width..][..width]); |
| 293 | } |
| 294 | out |
| 295 | } |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded { |
| 302 | let reconstruction = &encoded.reconstruction; |
| 303 | let cropped = if reconstruction.width == width && reconstruction.height == height { |
| 304 | reconstruction.clone() |
| 305 | } else { |
| 306 | Picture { |
| 307 | width, |
| 308 | height, |
| 309 | y: crop_plane(&reconstruction.y, reconstruction.width, width, height), |
| 310 | u: crop_plane( |
| 311 | &reconstruction.u, |
| 312 | reconstruction.width / 2, |
| 313 | width / 2, |
| 314 | height / 2, |
| 315 | ), |
| 316 | v: crop_plane( |
| 317 | &reconstruction.v, |
| 318 | reconstruction.width / 2, |
| 319 | width / 2, |
| 320 | height / 2, |
| 321 | ), |
| 322 | } |
| 323 | }; |
| 324 | Encoded { |
| 325 | stream: encoded.stream.clone(), |
| 326 | modes: encoded.modes.clone(), |
| 327 | inter_block_share: encoded.inter_block_share, |
| 328 | reconstruction: cropped, |
| 329 | tile: encoded.tile.clone(), |
| 330 | mi_cols: encoded.mi_cols, |
| 331 | mi_rows: encoded.mi_rows, |
| 332 | base_q_idx: encoded.base_q_idx, |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | |
| 337 | #[derive(Clone, Debug)] |
| 338 | pub struct Encoded { |
| 339 | |
| 340 | |
| 341 | pub stream: Vec<u8>, |
| 342 | |
| 343 | |
| 344 | pub reconstruction: Picture, |
| 345 | |
| 346 | |
| 347 | |
| 348 | pub modes: Vec<u8>, |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | pub inter_block_share: f64, |
| 354 | |
| 355 | |
| 356 | |
| 357 | |
| 358 | pub(crate) tile: Vec<u8>, |
| 359 | pub(crate) mi_cols: u32, |
| 360 | pub(crate) mi_rows: u32, |
| 361 | pub(crate) base_q_idx: u8, |
| 362 | } |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | pub fn key_frame_headers( |
| 372 | width: usize, |
| 373 | height: usize, |
| 374 | base_q_idx: u8, |
| 375 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 376 | key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config()) |
| 377 | } |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | fn unspecified_color_config() -> ColorConfig { |
| 384 | ColorConfig { |
| 385 | bit_depth: 8, |
| 386 | mono_chrome: false, |
| 387 | num_planes: 3, |
| 388 | color_primaries: 2, |
| 389 | transfer_characteristics: 2, |
| 390 | matrix_coefficients: 2, |
| 391 | color_range: false, |
| 392 | subsampling_x: 1, |
| 393 | subsampling_y: 1, |
| 394 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 395 | separate_uv_delta_q: false, |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | pub(crate) fn key_frame_headers_colour( |
| 408 | width: usize, |
| 409 | height: usize, |
| 410 | base_q_idx: u8, |
| 411 | color_config: ColorConfig, |
| 412 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 413 | let bits = |n: usize| -> Result<u32> { |
| 414 | let n = u32::try_from(n).map_err(|_| too_large())?; |
| 415 | if n == 0 || n > 1 << 16 { |
| 416 | return Err(too_large()); |
| 417 | } |
| 418 | Ok((32 - (n - 1).leading_zeros()).max(1)) |
| 419 | }; |
| 420 | let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?); |
| 421 | let (w, h) = (width as u32, height as u32); |
| 422 | let seq = SequenceHeader { |
| 423 | seq_profile: 0, |
| 424 | operating_points: vec![OperatingPoint { |
| 425 | seq_level_idx: 8, |
| 426 | ..OperatingPoint::default() |
| 427 | }], |
| 428 | frame_width_bits, |
| 429 | frame_height_bits, |
| 430 | max_frame_width: w, |
| 431 | max_frame_height: h, |
| 432 | use_128x128_superblock: false, |
| 433 | enable_filter_intra: false, |
| 434 | enable_intra_edge_filter: false, |
| 435 | enable_order_hint: true, |
| 436 | order_hint_bits: 7, |
| 437 | enable_superres: false, |
| 438 | enable_cdef: false, |
| 439 | enable_restoration: false, |
| 440 | seq_force_screen_content_tools: 0, |
| 441 | seq_force_integer_mv: 0, |
| 442 | color_config, |
| 443 | still_picture: false, |
| 444 | reduced_still_picture_header: false, |
| 445 | timing_info: None, |
| 446 | decoder_model_info: None, |
| 447 | initial_display_delay_present_flag: false, |
| 448 | operating_point: 0, |
| 449 | operating_point_idc: 0, |
| 450 | frame_id_numbers_present_flag: false, |
| 451 | delta_frame_id_length: 0, |
| 452 | additional_frame_id_length: 0, |
| 453 | enable_interintra_compound: false, |
| 454 | enable_masked_compound: false, |
| 455 | enable_warped_motion: false, |
| 456 | enable_dual_filter: false, |
| 457 | enable_jnt_comp: false, |
| 458 | enable_ref_frame_mvs: false, |
| 459 | film_grain_params_present: false, |
| 460 | }; |
| 461 | |
| 462 | |
| 463 | |
| 464 | |
| 465 | let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3)); |
| 466 | let header = FrameHeader { |
| 467 | frame_type: FrameType::Key, |
| 468 | frame_is_intra: true, |
| 469 | show_frame: true, |
| 470 | error_resilient_mode: true, |
| 471 | |
| 472 | |
| 473 | disable_cdf_update: false, |
| 474 | |
| 475 | |
| 476 | disable_frame_end_update_cdf: true, |
| 477 | force_integer_mv: true, |
| 478 | refresh_frame_flags: 0xFF, |
| 479 | primary_ref_frame: PRIMARY_REF_NONE, |
| 480 | frame_width: w, |
| 481 | frame_height: h, |
| 482 | upscaled_width: w, |
| 483 | render_width: w, |
| 484 | render_height: h, |
| 485 | mi_cols, |
| 486 | mi_rows, |
| 487 | tile_info: TileInfo { |
| 488 | uniform_spacing: true, |
| 489 | cols: 1, |
| 490 | rows: 1, |
| 491 | mi_col_starts: vec![0, mi_cols], |
| 492 | mi_row_starts: vec![0, mi_rows], |
| 493 | tile_size_bytes: 1, |
| 494 | ..TileInfo::default() |
| 495 | }, |
| 496 | quantization: QuantizationParams { |
| 497 | base_q_idx, |
| 498 | ..QuantizationParams::default() |
| 499 | }, |
| 500 | tx_mode: TxMode::Largest, |
| 501 | |
| 502 | |
| 503 | |
| 504 | |
| 505 | |
| 506 | |
| 507 | |
| 508 | |
| 509 | |
| 510 | |
| 511 | |
| 512 | |
| 513 | reduced_tx_set: true, |
| 514 | ..FrameHeader::default() |
| 515 | }; |
| 516 | Ok((seq, header)) |
| 517 | } |
| 518 | |
| 519 | |
| 520 | |
| 521 | |
| 522 | |
| 523 | |
| 524 | |
| 525 | |
| 526 | pub fn inter_frame_headers( |
| 527 | width: usize, |
| 528 | height: usize, |
| 529 | base_q_idx: u8, |
| 530 | order_hint: u32, |
| 531 | last_slot: u8, |
| 532 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 533 | let (seq, key) = key_frame_headers(width, height, base_q_idx)?; |
| 534 | let header = FrameHeader { |
| 535 | frame_type: FrameType::Inter, |
| 536 | frame_is_intra: false, |
| 537 | show_frame: true, |
| 538 | error_resilient_mode: false, |
| 539 | disable_cdf_update: false, |
| 540 | disable_frame_end_update_cdf: true, |
| 541 | force_integer_mv: false, |
| 542 | order_hint, |
| 543 | primary_ref_frame: 0, |
| 544 | refresh_frame_flags: 1 << last_slot, |
| 545 | ref_frame_idx: [last_slot; ec_av1_syntax::REFS_PER_FRAME], |
| 546 | allow_high_precision_mv: false, |
| 547 | interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap, |
| 548 | is_motion_mode_switchable: false, |
| 549 | use_ref_frame_mvs: false, |
| 550 | |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | |
| 561 | reduced_tx_set: true, |
| 562 | ..key |
| 563 | }; |
| 564 | Ok((seq, header)) |
| 565 | } |
| 566 | |
| 567 | fn too_large() -> Error { |
| 568 | Error::unsupported( |
| 569 | "AV1 encode", |
| 570 | "the picture is larger than a frame size can carry", |
| 571 | ) |
| 572 | } |
| 573 | |
| 574 | |
| 575 | |
| 576 | struct Plane<'a> { |
| 577 | source: &'a [u8], |
| 578 | reconstruction: Vec<u8>, |
| 579 | width: usize, |
| 580 | height: usize, |
| 581 | |
| 582 | |
| 583 | |
| 584 | |
| 585 | |
| 586 | |
| 587 | |
| 588 | |
| 589 | |
| 590 | |
| 591 | true_width: usize, |
| 592 | true_height: usize, |
| 593 | } |
| 594 | |
| 595 | impl Plane<'_> { |
| 596 | |
| 597 | |
| 598 | |
| 599 | |
| 600 | |
| 601 | |
| 602 | |
| 603 | |
| 604 | |
| 605 | fn edges( |
| 606 | &self, |
| 607 | x: usize, |
| 608 | y: usize, |
| 609 | side: usize, |
| 610 | reach: Reach, |
| 611 | ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) { |
| 612 | |
| 613 | |
| 614 | |
| 615 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | |
| 620 | |
| 621 | |
| 622 | |
| 623 | |
| 624 | |
| 625 | |
| 626 | let own_across = x + side.min(self.true_width.saturating_sub(x)); |
| 627 | let across = if reach.above_right { |
| 628 | own_across + side.min(self.true_width.saturating_sub(own_across)) |
| 629 | } else { |
| 630 | own_across |
| 631 | } |
| 632 | .min(self.width); |
| 633 | let own_down = y + side.min(self.true_height.saturating_sub(y)); |
| 634 | let down = if reach.below_left { |
| 635 | own_down + side.min(self.true_height.saturating_sub(own_down)) |
| 636 | } else { |
| 637 | own_down |
| 638 | } |
| 639 | .min(self.height); |
| 640 | |
| 641 | |
| 642 | |
| 643 | |
| 644 | |
| 645 | |
| 646 | |
| 647 | let above = (y > 0 && across > x) |
| 648 | .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec()); |
| 649 | let left = (x > 0 && down > y).then(|| { |
| 650 | (y..down) |
| 651 | .map(|row| self.reconstruction[row * self.width + x - 1]) |
| 652 | .collect::<Vec<_>>() |
| 653 | }); |
| 654 | let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]); |
| 655 | (above, left, corner) |
| 656 | } |
| 657 | |
| 658 | |
| 659 | |
| 660 | |
| 661 | fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Trial { |
| 662 | let At { |
| 663 | x, y, side, reach, .. |
| 664 | } = at; |
| 665 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 666 | let mut prediction = vec![0u8; side * side]; |
| 667 | intra_predict_u8( |
| 668 | mode, |
| 669 | 0, |
| 670 | above.as_deref(), |
| 671 | left.as_deref(), |
| 672 | corner, |
| 673 | side, |
| 674 | side, |
| 675 | false, |
| 676 | false, |
| 677 | &mut prediction, |
| 678 | ); |
| 679 | |
| 680 | let mut residual = vec![0i32; side * side]; |
| 681 | for row in 0..side { |
| 682 | for col in 0..side { |
| 683 | residual[row * side + col] = |
| 684 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 685 | - i32::from(prediction[row * side + col]); |
| 686 | } |
| 687 | } |
| 688 | #[cfg(test)] |
| 689 | let t = std::time::Instant::now(); |
| 690 | let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone); |
| 691 | let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); |
| 692 | #[cfg(test)] |
| 693 | stage_add(2, t.elapsed()); |
| 694 | |
| 695 | let mut reconstruction = vec![0u8; side * side]; |
| 696 | let mut sse = 0.0; |
| 697 | for row in 0..side { |
| 698 | for col in 0..side { |
| 699 | let i = row * side + col; |
| 700 | let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; |
| 701 | reconstruction[i] = sample; |
| 702 | let error = f64::from( |
| 703 | i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), |
| 704 | ); |
| 705 | sse += error * error; |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | |
| 710 | |
| 711 | #[cfg(test)] |
| 712 | let t = std::time::Instant::now(); |
| 713 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 714 | |
| 715 | |
| 716 | |
| 717 | |
| 718 | levels |
| 719 | .iter() |
| 720 | .filter(|&&level| level != 0) |
| 721 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 722 | .sum() |
| 723 | } else { |
| 724 | crate::tile::coeff_bits(&levels, at.set) |
| 725 | }; |
| 726 | #[cfg(test)] |
| 727 | stage_add(3, t.elapsed()); |
| 728 | Trial { |
| 729 | levels, |
| 730 | reconstruction, |
| 731 | sse, |
| 732 | bits, |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | |
| 737 | |
| 738 | |
| 739 | |
| 740 | |
| 741 | |
| 742 | #[allow(clippy::too_many_arguments)] |
| 743 | fn code_from_prediction( |
| 744 | &self, |
| 745 | x: usize, |
| 746 | y: usize, |
| 747 | side: usize, |
| 748 | prediction: &[u8], |
| 749 | skip: bool, |
| 750 | base_q_idx: u8, |
| 751 | deadzone: f64, |
| 752 | set: TxbSet, |
| 753 | ) -> Trial { |
| 754 | if skip { |
| 755 | let mut sse = 0.0; |
| 756 | for row in 0..side { |
| 757 | for col in 0..side { |
| 758 | let error = f64::from( |
| 759 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 760 | - i32::from(prediction[row * side + col]), |
| 761 | ); |
| 762 | sse += error * error; |
| 763 | } |
| 764 | } |
| 765 | return Trial { |
| 766 | levels: vec![0i32; side * side], |
| 767 | reconstruction: prediction.to_vec(), |
| 768 | sse, |
| 769 | bits: 0.0, |
| 770 | }; |
| 771 | } |
| 772 | let mut residual = vec![0i32; side * side]; |
| 773 | for row in 0..side { |
| 774 | for col in 0..side { |
| 775 | residual[row * side + col] = |
| 776 | i32::from(self.source[(y + row) * self.width + x + col]) |
| 777 | - i32::from(prediction[row * side + col]); |
| 778 | } |
| 779 | } |
| 780 | #[cfg(test)] |
| 781 | let t = std::time::Instant::now(); |
| 782 | let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone); |
| 783 | let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx)); |
| 784 | #[cfg(test)] |
| 785 | stage_add(2, t.elapsed()); |
| 786 | let mut reconstruction = vec![0u8; side * side]; |
| 787 | let mut sse = 0.0; |
| 788 | for row in 0..side { |
| 789 | for col in 0..side { |
| 790 | let i = row * side + col; |
| 791 | let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8; |
| 792 | reconstruction[i] = sample; |
| 793 | let error = f64::from( |
| 794 | i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample), |
| 795 | ); |
| 796 | sse += error * error; |
| 797 | } |
| 798 | } |
| 799 | #[cfg(test)] |
| 800 | let t = std::time::Instant::now(); |
| 801 | let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() { |
| 802 | levels |
| 803 | .iter() |
| 804 | .filter(|&&level| level != 0) |
| 805 | .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2()) |
| 806 | .sum() |
| 807 | } else { |
| 808 | crate::tile::coeff_bits(&levels, set) |
| 809 | }; |
| 810 | #[cfg(test)] |
| 811 | stage_add(3, t.elapsed()); |
| 812 | Trial { |
| 813 | levels, |
| 814 | reconstruction, |
| 815 | sse, |
| 816 | bits, |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | |
| 821 | fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) { |
| 822 | for row in 0..side { |
| 823 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 824 | .copy_from_slice(&trial.reconstruction[row * side..][..side]); |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | |
| 829 | |
| 830 | fn code_block( |
| 831 | &mut self, |
| 832 | at: At, |
| 833 | mode: u8, |
| 834 | base_q_idx: u8, |
| 835 | deadzone: f64, |
| 836 | ) -> (Vec<Coeff>, f64, f64) { |
| 837 | let trial = self.trial(at, mode, base_q_idx, deadzone); |
| 838 | self.commit(at.x, at.y, at.side, &trial); |
| 839 | (coeffs(&trial.levels, at.side), trial.sse, trial.bits) |
| 840 | } |
| 841 | |
| 842 | |
| 843 | |
| 844 | |
| 845 | |
| 846 | fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 847 | (y..y + side) |
| 848 | .flat_map(|row| self.source[row * self.width + x..][..side].to_vec()) |
| 849 | .collect() |
| 850 | } |
| 851 | |
| 852 | |
| 853 | |
| 854 | fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> { |
| 855 | (y..y + side) |
| 856 | .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec()) |
| 857 | .collect() |
| 858 | } |
| 859 | |
| 860 | |
| 861 | fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) { |
| 862 | for row in 0..side { |
| 863 | self.reconstruction[(y + row) * self.width + x..][..side] |
| 864 | .copy_from_slice(&samples[row * side..][..side]); |
| 865 | } |
| 866 | } |
| 867 | |
| 868 | |
| 869 | |
| 870 | |
| 871 | |
| 872 | fn intra_scores( |
| 873 | &self, |
| 874 | at: At, |
| 875 | modes: &[u8], |
| 876 | mode_bits: &[f64; 13], |
| 877 | lambda: f64, |
| 878 | ) -> Vec<(f64, u8)> { |
| 879 | let At { |
| 880 | x, y, side, reach, .. |
| 881 | } = at; |
| 882 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 883 | modes |
| 884 | .iter() |
| 885 | .map(|&mode| { |
| 886 | let mut prediction = vec![0u8; side * side]; |
| 887 | intra_predict_u8( |
| 888 | mode, |
| 889 | 0, |
| 890 | above.as_deref(), |
| 891 | left.as_deref(), |
| 892 | corner, |
| 893 | side, |
| 894 | side, |
| 895 | false, |
| 896 | false, |
| 897 | &mut prediction, |
| 898 | ); |
| 899 | let sad: f64 = (0..side * side) |
| 900 | .map(|i| { |
| 901 | let (row, col) = (i / side, i % side); |
| 902 | f64::from( |
| 903 | (i32::from(self.source[(y + row) * self.width + x + col]) |
| 904 | - i32::from(prediction[i])) |
| 905 | .abs(), |
| 906 | ) |
| 907 | }) |
| 908 | .sum(); |
| 909 | (sad + lambda * mode_bits[usize::from(mode)], mode) |
| 910 | }) |
| 911 | .collect() |
| 912 | } |
| 913 | |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 918 | |
| 919 | |
| 920 | |
| 921 | |
| 922 | |
| 923 | |
| 924 | fn search_block( |
| 925 | &mut self, |
| 926 | at: At, |
| 927 | search: &Search, |
| 928 | mode_bits: &[f64; 13], |
| 929 | ) -> (Vec<Coeff>, u8, f64) { |
| 930 | let At { |
| 931 | x, y, side, reach, .. |
| 932 | } = at; |
| 933 | let (above, left, corner) = self.edges(x, y, side, reach); |
| 934 | let mut scored: Vec<(f64, u8, Vec<u8>)> = search |
| 935 | .modes |
| 936 | .iter() |
| 937 | .map(|&mode| { |
| 938 | let mut prediction = vec![0u8; side * side]; |
| 939 | intra_predict_u8( |
| 940 | mode, |
| 941 | 0, |
| 942 | above.as_deref(), |
| 943 | left.as_deref(), |
| 944 | corner, |
| 945 | side, |
| 946 | side, |
| 947 | false, |
| 948 | false, |
| 949 | &mut prediction, |
| 950 | ); |
| 951 | let sad: f64 = (0..side * side) |
| 952 | .map(|i| { |
| 953 | let (row, col) = (i / side, i % side); |
| 954 | f64::from( |
| 955 | (i32::from(self.source[(y + row) * self.width + x + col]) |
| 956 | - i32::from(prediction[i])) |
| 957 | .abs(), |
| 958 | ) |
| 959 | }) |
| 960 | .sum(); |
| 961 | ( |
| 962 | sad + search.lambda * mode_bits[usize::from(mode)], |
| 963 | mode, |
| 964 | prediction, |
| 965 | ) |
| 966 | }) |
| 967 | .collect(); |
| 968 | if let Some(k) = search.top_k { |
| 969 | if k < scored.len() { |
| 970 | let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED); |
| 971 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 972 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 973 | scored.truncate(if dc_entry.is_some() { |
| 974 | k.saturating_sub(1) |
| 975 | } else { |
| 976 | k |
| 977 | }); |
| 978 | if let Some(dc_entry) = dc_entry { |
| 979 | scored.push(dc_entry); |
| 980 | } |
| 981 | } |
| 982 | } |
| 983 | let mut best: Option<(f64, u8, Trial)> = None; |
| 984 | for (_, mode, prediction) in scored { |
| 985 | let trial = self.code_from_prediction( |
| 986 | x, |
| 987 | y, |
| 988 | side, |
| 989 | &prediction, |
| 990 | false, |
| 991 | search.base_q_idx, |
| 992 | search.deadzone, |
| 993 | at.set, |
| 994 | ); |
| 995 | let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]); |
| 996 | if best |
| 997 | .as_ref() |
| 998 | .is_none_or(|(best_cost, _, _)| cost < *best_cost) |
| 999 | { |
| 1000 | best = Some((cost, mode, trial)); |
| 1001 | } |
| 1002 | } |
| 1003 | let (cost, mode, trial) = best.expect("the search offers at least one mode"); |
| 1004 | self.commit(x, y, side, &trial); |
| 1005 | (coeffs(&trial.levels, side), mode, cost) |
| 1006 | } |
| 1007 | } |
| 1008 | |
| 1009 | |
| 1010 | |
| 1011 | #[derive(Clone, Copy)] |
| 1012 | struct At { |
| 1013 | x: usize, |
| 1014 | y: usize, |
| 1015 | side: usize, |
| 1016 | reach: Reach, |
| 1017 | |
| 1018 | |
| 1019 | set: TxbSet, |
| 1020 | } |
| 1021 | |
| 1022 | |
| 1023 | |
| 1024 | |
| 1025 | |
| 1026 | |
| 1027 | |
| 1028 | |
| 1029 | |
| 1030 | |
| 1031 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 1032 | pub(crate) struct Reach { |
| 1033 | pub(crate) above_right: bool, |
| 1034 | pub(crate) below_left: bool, |
| 1035 | } |
| 1036 | |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | |
| 1042 | |
| 1043 | const HAS_TOP_RIGHT: [&[u8]; 4] = [ |
| 1044 | &[255, 85, 119, 85, 127, 85, 119, 85], |
| 1045 | &[95, 87], |
| 1046 | |
| 1047 | |
| 1048 | &[ |
| 1049 | 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85, |
| 1050 | 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, |
| 1051 | ], |
| 1052 | |
| 1053 | |
| 1054 | |
| 1055 | |
| 1056 | |
| 1057 | |
| 1058 | |
| 1059 | |
| 1060 | &[ |
| 1061 | 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, |
| 1062 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85, |
| 1063 | 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, |
| 1064 | 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, |
| 1065 | 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, |
| 1066 | 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, |
| 1067 | 119, 119, 119, 119, 85, 85, 85, 85, |
| 1068 | ], |
| 1069 | ]; |
| 1070 | |
| 1071 | |
| 1072 | |
| 1073 | const HAS_BOTTOM_LEFT: [&[u8]; 4] = [ |
| 1074 | &[84, 16, 84, 0, 84, 16, 84, 0], |
| 1075 | &[4, 4], |
| 1076 | |
| 1077 | &[ |
| 1078 | 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1, |
| 1079 | 84, 85, 16, 17, 84, 85, 0, 0, |
| 1080 | ], |
| 1081 | |
| 1082 | |
| 1083 | &[ |
| 1084 | 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, |
| 1085 | 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, |
| 1086 | 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, |
| 1087 | 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, |
| 1088 | 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, |
| 1089 | 85, 85, 0, 0, 0, 0, |
| 1090 | ], |
| 1091 | ]; |
| 1092 | |
| 1093 | |
| 1094 | |
| 1095 | |
| 1096 | |
| 1097 | |
| 1098 | |
| 1099 | |
| 1100 | |
| 1101 | |
| 1102 | const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [ |
| 1103 | |
| 1104 | &[255, 0, 119, 0, 127, 0, 119, 0], |
| 1105 | |
| 1106 | &[15, 7], |
| 1107 | |
| 1108 | &[ |
| 1109 | 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119, |
| 1110 | 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, |
| 1111 | ], |
| 1112 | ]; |
| 1113 | |
| 1114 | |
| 1115 | const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [ |
| 1116 | |
| 1117 | &[254, 16, 254, 0, 254, 16, 254, 0], |
| 1118 | |
| 1119 | &[14, 14], |
| 1120 | |
| 1121 | &[ |
| 1122 | 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254, |
| 1123 | 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, |
| 1124 | ], |
| 1125 | ]; |
| 1126 | |
| 1127 | thread_local! { |
| 1128 | |
| 1129 | |
| 1130 | |
| 1131 | |
| 1132 | |
| 1133 | |
| 1134 | static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; |
| 1135 | } |
| 1136 | |
| 1137 | |
| 1138 | pub(crate) struct VertAbGuard(bool); |
| 1139 | |
| 1140 | impl Drop for VertAbGuard { |
| 1141 | fn drop(&mut self) { |
| 1142 | VERT_AB_PARTITION.with(|c| c.set(self.0)); |
| 1143 | } |
| 1144 | } |
| 1145 | |
| 1146 | |
| 1147 | |
| 1148 | |
| 1149 | |
| 1150 | |
| 1151 | |
| 1152 | |
| 1153 | |
| 1154 | |
| 1155 | |
| 1156 | |
| 1157 | |
| 1158 | |
| 1159 | |
| 1160 | 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]; |
| 1161 | |
| 1162 | 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]; |
| 1163 | |
| 1164 | 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]; |
| 1165 | |
| 1166 | 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]; |
| 1167 | |
| 1168 | const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119]; |
| 1169 | |
| 1170 | const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0]; |
| 1171 | |
| 1172 | const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0]; |
| 1173 | |
| 1174 | const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0]; |
| 1175 | |
| 1176 | const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119]; |
| 1177 | |
| 1178 | const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0]; |
| 1179 | |
| 1180 | const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5]; |
| 1181 | |
| 1182 | const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14]; |
| 1183 | |
| 1184 | const HAS_TR_32X64: [u8; 1] = [127]; |
| 1185 | |
| 1186 | const HAS_BL_32X64: [u8; 1] = [0]; |
| 1187 | |
| 1188 | const HAS_TR_64X32: [u8; 1] = [19]; |
| 1189 | |
| 1190 | const HAS_BL_64X32: [u8; 1] = [34]; |
| 1191 | |
| 1192 | 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]; |
| 1193 | |
| 1194 | 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]; |
| 1195 | |
| 1196 | 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]; |
| 1197 | |
| 1198 | 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]; |
| 1199 | |
| 1200 | const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127]; |
| 1201 | |
| 1202 | const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0]; |
| 1203 | |
| 1204 | const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0]; |
| 1205 | |
| 1206 | const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14]; |
| 1207 | |
| 1208 | const HAS_TR_16X64: [u8; 2] = [255, 127]; |
| 1209 | |
| 1210 | const HAS_BL_16X64: [u8; 2] = [0, 0]; |
| 1211 | |
| 1212 | const HAS_TR_64X16: [u8; 2] = [3, 1]; |
| 1213 | |
| 1214 | const HAS_BL_64X16: [u8; 2] = [42, 42]; |
| 1215 | |
| 1216 | |
| 1217 | fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) { |
| 1218 | match (bw, bh) { |
| 1219 | (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8), |
| 1220 | (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4), |
| 1221 | (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16), |
| 1222 | (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8), |
| 1223 | (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32), |
| 1224 | (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16), |
| 1225 | (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64), |
| 1226 | (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32), |
| 1227 | (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16), |
| 1228 | (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4), |
| 1229 | (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32), |
| 1230 | (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8), |
| 1231 | (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64), |
| 1232 | (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16), |
| 1233 | _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"), |
| 1234 | } |
| 1235 | } |
| 1236 | |
| 1237 | impl Reach { |
| 1238 | |
| 1239 | |
| 1240 | |
| 1241 | |
| 1242 | |
| 1243 | |
| 1244 | |
| 1245 | |
| 1246 | |
| 1247 | |
| 1248 | |
| 1249 | |
| 1250 | |
| 1251 | |
| 1252 | pub(crate) fn of_tu( |
| 1253 | bw: usize, |
| 1254 | bh: usize, |
| 1255 | col_off: usize, |
| 1256 | row_off: usize, |
| 1257 | |
| 1258 | |
| 1259 | |
| 1260 | tx_w: usize, |
| 1261 | tx_h: usize, |
| 1262 | block: Self, |
| 1263 | ) -> Self { |
| 1264 | Self { |
| 1265 | above_right: if col_off + tx_w < bw { |
| 1266 | true |
| 1267 | } else { |
| 1268 | row_off == 0 && block.above_right |
| 1269 | }, |
| 1270 | below_left: if col_off > 0 { |
| 1271 | false |
| 1272 | } else if row_off + tx_h < bh { |
| 1273 | true |
| 1274 | } else { |
| 1275 | block.below_left |
| 1276 | }, |
| 1277 | } |
| 1278 | } |
| 1279 | |
| 1280 | |
| 1281 | |
| 1282 | pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self { |
| 1283 | Self { |
| 1284 | above_right: y > 0 && x + side < width && Self::top_right(side, x, y), |
| 1285 | below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y), |
| 1286 | } |
| 1287 | } |
| 1288 | |
| 1289 | |
| 1290 | |
| 1291 | |
| 1292 | |
| 1293 | |
| 1294 | pub(crate) fn of_rect( |
| 1295 | bw: usize, |
| 1296 | bh: usize, |
| 1297 | x: usize, |
| 1298 | y: usize, |
| 1299 | width: usize, |
| 1300 | height: usize, |
| 1301 | ) -> Self { |
| 1302 | Self { |
| 1303 | above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y), |
| 1304 | below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y), |
| 1305 | } |
| 1306 | } |
| 1307 | |
| 1308 | |
| 1309 | |
| 1310 | |
| 1311 | |
| 1312 | |
| 1313 | |
| 1314 | |
| 1315 | |
| 1316 | |
| 1317 | |
| 1318 | |
| 1319 | |
| 1320 | |
| 1321 | |
| 1322 | fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool { |
| 1323 | let sb_mi: usize = reach_sb_px() / 4; |
| 1324 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 1325 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 1326 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 1327 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 1328 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 1329 | |
| 1330 | |
| 1331 | if blk_row == 0 { |
| 1332 | return true; |
| 1333 | } |
| 1334 | |
| 1335 | if ((blk_col + 1) << bw_log2) >= sb_mi { |
| 1336 | return false; |
| 1337 | } |
| 1338 | let table = rect_reach_tables(bw, bh).0; |
| 1339 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 1340 | } |
| 1341 | |
| 1342 | |
| 1343 | |
| 1344 | |
| 1345 | |
| 1346 | |
| 1347 | |
| 1348 | |
| 1349 | |
| 1350 | fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize { |
| 1351 | (blk_row << (5 - bw_log2)) + blk_col |
| 1352 | } |
| 1353 | |
| 1354 | |
| 1355 | fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool { |
| 1356 | let sb_mi: usize = reach_sb_px() / 4; |
| 1357 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 1358 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 1359 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 1360 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 1361 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 1362 | |
| 1363 | |
| 1364 | if blk_col == 0 { |
| 1365 | return (blk_row << bh_log2) + (bh / 4) < sb_mi; |
| 1366 | } |
| 1367 | |
| 1368 | |
| 1369 | if ((blk_row + 1) << bh_log2) >= sb_mi { |
| 1370 | return false; |
| 1371 | } |
| 1372 | let table = rect_reach_tables(bw, bh).1; |
| 1373 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 1374 | } |
| 1375 | |
| 1376 | |
| 1377 | |
| 1378 | |
| 1379 | |
| 1380 | |
| 1381 | |
| 1382 | |
| 1383 | |
| 1384 | pub(crate) fn in_vert_ab() -> bool { |
| 1385 | VERT_AB_PARTITION.with(std::cell::Cell::get) |
| 1386 | } |
| 1387 | |
| 1388 | pub(crate) fn vert_ab_partition() -> VertAbGuard { |
| 1389 | VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true))) |
| 1390 | } |
| 1391 | |
| 1392 | |
| 1393 | |
| 1394 | pub(crate) fn none() -> Self { |
| 1395 | Self { |
| 1396 | above_right: false, |
| 1397 | below_left: false, |
| 1398 | } |
| 1399 | } |
| 1400 | |
| 1401 | |
| 1402 | |
| 1403 | |
| 1404 | |
| 1405 | fn top_right(side: usize, x: usize, y: usize) -> bool { |
| 1406 | let (row, col, per_side) = Self::position(side, x, y); |
| 1407 | if row == 0 { |
| 1408 | return true; |
| 1409 | } |
| 1410 | if col + 1 == per_side { |
| 1411 | return false; |
| 1412 | } |
| 1413 | |
| 1414 | |
| 1415 | |
| 1416 | |
| 1417 | |
| 1418 | |
| 1419 | |
| 1420 | |
| 1421 | |
| 1422 | |
| 1423 | |
| 1424 | let table_row = Self::table(side); |
| 1425 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() { |
| 1426 | HAS_TOP_RIGHT_VERT[table_row] |
| 1427 | } else { |
| 1428 | HAS_TOP_RIGHT[table_row] |
| 1429 | }; |
| 1430 | Self::bit( |
| 1431 | table, |
| 1432 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 1433 | ) |
| 1434 | } |
| 1435 | |
| 1436 | |
| 1437 | |
| 1438 | |
| 1439 | |
| 1440 | fn bottom_left(side: usize, x: usize, y: usize) -> bool { |
| 1441 | let (row, col, per_side) = Self::position(side, x, y); |
| 1442 | if col == 0 { |
| 1443 | return row * side + side < reach_sb_px(); |
| 1444 | } |
| 1445 | if row + 1 == per_side { |
| 1446 | return false; |
| 1447 | } |
| 1448 | |
| 1449 | |
| 1450 | |
| 1451 | |
| 1452 | |
| 1453 | |
| 1454 | |
| 1455 | |
| 1456 | |
| 1457 | |
| 1458 | |
| 1459 | let table_row = Self::table(side); |
| 1460 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() { |
| 1461 | HAS_BOTTOM_LEFT_VERT[table_row] |
| 1462 | } else { |
| 1463 | HAS_BOTTOM_LEFT[table_row] |
| 1464 | }; |
| 1465 | Self::bit( |
| 1466 | table, |
| 1467 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 1468 | ) |
| 1469 | } |
| 1470 | |
| 1471 | |
| 1472 | |
| 1473 | fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) { |
| 1474 | let sb = reach_sb_px(); |
| 1475 | ((y % sb) / side, (x % sb) / side, sb / side) |
| 1476 | } |
| 1477 | |
| 1478 | |
| 1479 | |
| 1480 | |
| 1481 | |
| 1482 | |
| 1483 | |
| 1484 | |
| 1485 | |
| 1486 | fn table_stride(side: usize) -> usize { |
| 1487 | 128 / side |
| 1488 | } |
| 1489 | |
| 1490 | |
| 1491 | fn table(side: usize) -> usize { |
| 1492 | if side == BLOCK { |
| 1493 | 1 |
| 1494 | } else if side == 8 { |
| 1495 | 2 |
| 1496 | } else if side == 4 { |
| 1497 | 3 |
| 1498 | } else { |
| 1499 | 0 |
| 1500 | } |
| 1501 | } |
| 1502 | |
| 1503 | |
| 1504 | fn bit(table: &[u8], index: usize) -> bool { |
| 1505 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 1506 | } |
| 1507 | } |
| 1508 | |
| 1509 | |
| 1510 | pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { |
| 1511 | let low = if symbol == 0 { 0 } else { cdf[symbol - 1] }; |
| 1512 | let probability = f64::from(cdf[symbol] - low) / 32768.0; |
| 1513 | -probability.log2() |
| 1514 | } |
| 1515 | |
| 1516 | |
| 1517 | |
| 1518 | |
| 1519 | |
| 1520 | |
| 1521 | |
| 1522 | |
| 1523 | |
| 1524 | |
| 1525 | |
| 1526 | |
| 1527 | |
| 1528 | fn code_square( |
| 1529 | luma: &mut Plane, |
| 1530 | chroma: &mut [Plane; 2], |
| 1531 | (x, y): (usize, usize), |
| 1532 | side: usize, |
| 1533 | search: &Search, |
| 1534 | mode_bits: &[f64; 13], |
| 1535 | ) -> (BlockCoeffs, f64) { |
| 1536 | let (luma_set, chroma_set) = if side == BLOCK { |
| 1537 | (TxbSet::Luma32, TxbSet::Chroma16) |
| 1538 | } else if side == 8 { |
| 1539 | |
| 1540 | |
| 1541 | |
| 1542 | |
| 1543 | |
| 1544 | |
| 1545 | |
| 1546 | (TxbSet::Luma8, TxbSet::Chroma4) |
| 1547 | } else { |
| 1548 | (TxbSet::Luma16, TxbSet::Chroma8) |
| 1549 | }; |
| 1550 | let (luma_coeffs, mode, mut cost) = luma.search_block( |
| 1551 | At { |
| 1552 | x, |
| 1553 | y, |
| 1554 | side, |
| 1555 | reach: Reach::of(side, x, y, luma.true_width, luma.true_height), |
| 1556 | set: luma_set, |
| 1557 | }, |
| 1558 | search, |
| 1559 | mode_bits, |
| 1560 | ); |
| 1561 | |
| 1562 | |
| 1563 | let mut planes = [Vec::new(), Vec::new()]; |
| 1564 | for (plane, coeffs) in chroma.iter_mut().zip(&mut planes) { |
| 1565 | let (levels, sse, bits) = plane.code_block( |
| 1566 | At { |
| 1567 | x: x / 2, |
| 1568 | y: y / 2, |
| 1569 | side: side / 2, |
| 1570 | reach: Reach::none(), |
| 1571 | set: chroma_set, |
| 1572 | }, |
| 1573 | DC_PRED, |
| 1574 | search.base_q_idx, |
| 1575 | search.deadzone, |
| 1576 | ); |
| 1577 | *coeffs = levels; |
| 1578 | cost += sse + search.lambda * bits; |
| 1579 | } |
| 1580 | let [u, v] = planes; |
| 1581 | ( |
| 1582 | BlockCoeffs { |
| 1583 | u, |
| 1584 | v, |
| 1585 | luma: luma_coeffs, |
| 1586 | mode, |
| 1587 | ..BlockCoeffs::default() |
| 1588 | }, |
| 1589 | cost, |
| 1590 | ) |
| 1591 | } |
| 1592 | |
| 1593 | |
| 1594 | |
| 1595 | |
| 1596 | |
| 1597 | |
| 1598 | |
| 1599 | |
| 1600 | |
| 1601 | |
| 1602 | |
| 1603 | |
| 1604 | #[allow(clippy::too_many_arguments)] |
| 1605 | fn code_square_inter( |
| 1606 | luma: &mut Plane, |
| 1607 | chroma: &mut [Plane; 2], |
| 1608 | (x, y): (usize, usize), |
| 1609 | side: usize, |
| 1610 | search: &Search, |
| 1611 | mode_bits: &[f64; 13], |
| 1612 | reference: &Picture, |
| 1613 | stack: &MvStack, |
| 1614 | ) -> BlockCoeffs { |
| 1615 | let (intra_block, intra_cost) = code_square(luma, chroma, (x, y), side, search, mode_bits); |
| 1616 | let luma_set = if side == 8 { |
| 1617 | TxbSet::Luma8Inter |
| 1618 | } else { |
| 1619 | TxbSet::Luma16Inter |
| 1620 | }; |
| 1621 | let chroma_set = if side == 8 { |
| 1622 | TxbSet::Chroma4 |
| 1623 | } else { |
| 1624 | TxbSet::Chroma8 |
| 1625 | }; |
| 1626 | |
| 1627 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 1628 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 1629 | let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 1630 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) |
| 1631 | + symbol_bits(&cdf::SINGLE_REF[0][3], 0); |
| 1632 | let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) |
| 1633 | + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) |
| 1634 | + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); |
| 1635 | |
| 1636 | let mv = stack.nearest_mv; |
| 1637 | let ref_luma = ( |
| 1638 | &reference.y, |
| 1639 | reference.width, |
| 1640 | luma.true_width, |
| 1641 | luma.true_height, |
| 1642 | ); |
| 1643 | let ref_u = ( |
| 1644 | &reference.u, |
| 1645 | reference.width / 2, |
| 1646 | chroma[0].true_width, |
| 1647 | chroma[0].true_height, |
| 1648 | ); |
| 1649 | let ref_v = ( |
| 1650 | &reference.v, |
| 1651 | reference.width / 2, |
| 1652 | chroma[1].true_width, |
| 1653 | chroma[1].true_height, |
| 1654 | ); |
| 1655 | let luma_trial = mc_trial( |
| 1656 | luma, |
| 1657 | x, |
| 1658 | y, |
| 1659 | side, |
| 1660 | mv, |
| 1661 | true, |
| 1662 | ref_luma.0, |
| 1663 | ref_luma.1, |
| 1664 | ref_luma.2, |
| 1665 | ref_luma.3, |
| 1666 | false, |
| 1667 | search.base_q_idx, |
| 1668 | search.deadzone, |
| 1669 | luma_set, |
| 1670 | ); |
| 1671 | let u = mc_trial( |
| 1672 | &chroma[0], |
| 1673 | x / 2, |
| 1674 | y / 2, |
| 1675 | side / 2, |
| 1676 | mv, |
| 1677 | false, |
| 1678 | ref_u.0, |
| 1679 | ref_u.1, |
| 1680 | ref_u.2, |
| 1681 | ref_u.3, |
| 1682 | false, |
| 1683 | search.base_q_idx, |
| 1684 | search.deadzone, |
| 1685 | chroma_set, |
| 1686 | ); |
| 1687 | let v = mc_trial( |
| 1688 | &chroma[1], |
| 1689 | x / 2, |
| 1690 | y / 2, |
| 1691 | side / 2, |
| 1692 | mv, |
| 1693 | false, |
| 1694 | ref_v.0, |
| 1695 | ref_v.1, |
| 1696 | ref_v.2, |
| 1697 | ref_v.3, |
| 1698 | false, |
| 1699 | search.base_q_idx, |
| 1700 | search.deadzone, |
| 1701 | chroma_set, |
| 1702 | ); |
| 1703 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 1704 | && u.levels.iter().all(|&l| l == 0) |
| 1705 | && v.levels.iter().all(|&l| l == 0); |
| 1706 | let inter_cost = luma_trial.sse |
| 1707 | + u.sse |
| 1708 | + v.sse |
| 1709 | + search.lambda |
| 1710 | * (skip_bits(skip) |
| 1711 | + intra_inter_bits(true) |
| 1712 | + single_ref_bits |
| 1713 | + mode_bits_inter |
| 1714 | + if skip { |
| 1715 | 0.0 |
| 1716 | } else { |
| 1717 | luma_trial.bits + u.bits + v.bits |
| 1718 | }); |
| 1719 | |
| 1720 | |
| 1721 | |
| 1722 | |
| 1723 | |
| 1724 | |
| 1725 | |
| 1726 | |
| 1727 | |
| 1728 | |
| 1729 | |
| 1730 | |
| 1731 | |
| 1732 | |
| 1733 | |
| 1734 | if inter_cost < intra_cost { |
| 1735 | luma.commit(x, y, side, &luma_trial); |
| 1736 | chroma[0].commit(x / 2, y / 2, side / 2, &u); |
| 1737 | chroma[1].commit(x / 2, y / 2, side / 2, &v); |
| 1738 | BlockCoeffs { |
| 1739 | luma: coeffs(&luma_trial.levels, side), |
| 1740 | u: coeffs(&u.levels, side / 2), |
| 1741 | v: coeffs(&v.levels, side / 2), |
| 1742 | mode: DC_PRED as u8, |
| 1743 | skip, |
| 1744 | eight: None, |
| 1745 | inter: Some(InterInfo { |
| 1746 | mode: InterMode::NearestMv, |
| 1747 | mv, |
| 1748 | }), |
| 1749 | } |
| 1750 | } else { |
| 1751 | intra_block |
| 1752 | } |
| 1753 | } |
| 1754 | |
| 1755 | |
| 1756 | |
| 1757 | fn snapshot(luma: &Plane, chroma: &[Plane; 2], (x, y): (usize, usize)) -> [Vec<u8>; 3] { |
| 1758 | [ |
| 1759 | luma.snapshot(x, y, BLOCK), |
| 1760 | chroma[0].snapshot(x / 2, y / 2, BLOCK / 2), |
| 1761 | chroma[1].snapshot(x / 2, y / 2, BLOCK / 2), |
| 1762 | ] |
| 1763 | } |
| 1764 | |
| 1765 | |
| 1766 | fn restore( |
| 1767 | luma: &mut Plane, |
| 1768 | chroma: &mut [Plane; 2], |
| 1769 | (x, y): (usize, usize), |
| 1770 | saved: &[Vec<u8>; 3], |
| 1771 | ) { |
| 1772 | luma.restore(x, y, BLOCK, &saved[0]); |
| 1773 | chroma[0].restore(x / 2, y / 2, BLOCK / 2, &saved[1]); |
| 1774 | chroma[1].restore(x / 2, y / 2, BLOCK / 2, &saved[2]); |
| 1775 | } |
| 1776 | |
| 1777 | |
| 1778 | |
| 1779 | |
| 1780 | |
| 1781 | |
| 1782 | fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> { |
| 1783 | let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED); |
| 1784 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 1785 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 1786 | scored.truncate(if dc_entry.is_some() { |
| 1787 | top_k.saturating_sub(1) |
| 1788 | } else { |
| 1789 | top_k |
| 1790 | }); |
| 1791 | if let Some(dc_entry) = dc_entry { |
| 1792 | scored.push(dc_entry); |
| 1793 | } |
| 1794 | let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect(); |
| 1795 | modes.iter().copied().filter(|m| keep.contains(m)).collect() |
| 1796 | } |
| 1797 | |
| 1798 | fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { |
| 1799 | let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]] |
| 1800 | [INTRA_MODE_CTX[usize::from(left_mode)]]; |
| 1801 | std::array::from_fn(|mode| { |
| 1802 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 1803 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 1804 | } else { |
| 1805 | 0.0 |
| 1806 | }; |
| 1807 | symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 1808 | }) |
| 1809 | } |
| 1810 | |
| 1811 | |
| 1812 | struct Search<'a> { |
| 1813 | base_q_idx: u8, |
| 1814 | deadzone: f64, |
| 1815 | lambda: f64, |
| 1816 | modes: &'a [u8], |
| 1817 | |
| 1818 | |
| 1819 | |
| 1820 | |
| 1821 | |
| 1822 | |
| 1823 | top_k: Option<usize>, |
| 1824 | } |
| 1825 | |
| 1826 | |
| 1827 | |
| 1828 | |
| 1829 | fn prune_top_k() -> Option<usize> { |
| 1830 | #[cfg(test)] |
| 1831 | { |
| 1832 | if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) { |
| 1833 | return k; |
| 1834 | } |
| 1835 | } |
| 1836 | let swept = std::env::var("EC_AV1_PRUNE_K") |
| 1837 | .ok() |
| 1838 | .and_then(|v| v.parse::<usize>().ok()); |
| 1839 | match swept { |
| 1840 | Some(k) if cfg!(test) => Some(k), |
| 1841 | _ => PRUNE_TOP_K, |
| 1842 | } |
| 1843 | } |
| 1844 | |
| 1845 | |
| 1846 | |
| 1847 | |
| 1848 | #[cfg(test)] |
| 1849 | thread_local! { |
| 1850 | static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> = |
| 1851 | const { std::cell::Cell::new(None) }; |
| 1852 | } |
| 1853 | |
| 1854 | #[cfg(test)] |
| 1855 | fn set_test_top_k_override(value: Option<usize>) { |
| 1856 | TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value))); |
| 1857 | } |
| 1858 | |
| 1859 | |
| 1860 | |
| 1861 | const PRUNE_TOP_K: Option<usize> = None; |
| 1862 | |
| 1863 | |
| 1864 | |
| 1865 | |
| 1866 | |
| 1867 | |
| 1868 | fn prune_top_k_inter() -> Option<usize> { |
| 1869 | #[cfg(test)] |
| 1870 | { |
| 1871 | if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) { |
| 1872 | return k; |
| 1873 | } |
| 1874 | } |
| 1875 | let swept = std::env::var("EC_AV1_PRUNE_K_INTER") |
| 1876 | .ok() |
| 1877 | .and_then(|v| v.parse::<usize>().ok()); |
| 1878 | match swept { |
| 1879 | Some(k) if cfg!(test) => Some(k), |
| 1880 | _ => INTER_PRUNE_TOP_K, |
| 1881 | } |
| 1882 | } |
| 1883 | |
| 1884 | |
| 1885 | |
| 1886 | #[cfg(test)] |
| 1887 | thread_local! { |
| 1888 | static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> = |
| 1889 | const { std::cell::Cell::new(None) }; |
| 1890 | } |
| 1891 | |
| 1892 | #[cfg(test)] |
| 1893 | fn set_test_top_k_override_inter(value: Option<usize>) { |
| 1894 | TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value))); |
| 1895 | } |
| 1896 | |
| 1897 | |
| 1898 | |
| 1899 | |
| 1900 | |
| 1901 | |
| 1902 | |
| 1903 | |
| 1904 | const INTER_PRUNE_TOP_K: Option<usize> = Some(3); |
| 1905 | |
| 1906 | |
| 1907 | |
| 1908 | |
| 1909 | |
| 1910 | |
| 1911 | |
| 1912 | |
| 1913 | |
| 1914 | #[cfg(test)] |
| 1915 | thread_local! { |
| 1916 | static STAGE_NS: [std::cell::Cell<u64>; 4] = [ |
| 1917 | std::cell::Cell::new(0), |
| 1918 | std::cell::Cell::new(0), |
| 1919 | std::cell::Cell::new(0), |
| 1920 | std::cell::Cell::new(0), |
| 1921 | ]; |
| 1922 | } |
| 1923 | |
| 1924 | #[cfg(test)] |
| 1925 | pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { |
| 1926 | STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); |
| 1927 | } |
| 1928 | |
| 1929 | #[cfg(test)] |
| 1930 | fn stage_reset() { |
| 1931 | STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0))); |
| 1932 | } |
| 1933 | |
| 1934 | #[cfg(test)] |
| 1935 | fn stage_read() -> [std::time::Duration; 4] { |
| 1936 | STAGE_NS.with(|c| { |
| 1937 | c.each_ref() |
| 1938 | .map(|cell| std::time::Duration::from_nanos(cell.get())) |
| 1939 | }) |
| 1940 | } |
| 1941 | |
| 1942 | |
| 1943 | #[derive(Clone)] |
| 1944 | struct Trial { |
| 1945 | levels: Vec<i32>, |
| 1946 | reconstruction: Vec<u8>, |
| 1947 | sse: f64, |
| 1948 | bits: f64, |
| 1949 | } |
| 1950 | |
| 1951 | |
| 1952 | fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> { |
| 1953 | levels |
| 1954 | .iter() |
| 1955 | .enumerate() |
| 1956 | .filter(|&(_, &level)| level != 0) |
| 1957 | .map(|(i, &level)| Coeff { |
| 1958 | row: (i / side) as u8, |
| 1959 | col: (i % side) as u8, |
| 1960 | level, |
| 1961 | }) |
| 1962 | .collect() |
| 1963 | } |
| 1964 | |
| 1965 | |
| 1966 | |
| 1967 | |
| 1968 | |
| 1969 | |
| 1970 | |
| 1971 | |
| 1972 | |
| 1973 | |
| 1974 | |
| 1975 | |
| 1976 | |
| 1977 | |
| 1978 | |
| 1979 | |
| 1980 | |
| 1981 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { |
| 1982 | encode_key_frame_with_modes(picture, base_q_idx, deadzone, &KEY_FRAME_MODES) |
| 1983 | } |
| 1984 | |
| 1985 | |
| 1986 | |
| 1987 | |
| 1988 | |
| 1989 | |
| 1990 | |
| 1991 | |
| 1992 | |
| 1993 | |
| 1994 | |
| 1995 | |
| 1996 | pub fn encode_key_frame_with_modes( |
| 1997 | picture: &Picture, |
| 1998 | base_q_idx: u8, |
| 1999 | deadzone: f64, |
| 2000 | modes: &[u8], |
| 2001 | ) -> Result<Encoded> { |
| 2002 | picture.check_even()?; |
| 2003 | let padded = picture.padded_to(BLOCK); |
| 2004 | let encoded = encode_key_frame_inner( |
| 2005 | &padded, |
| 2006 | base_q_idx, |
| 2007 | deadzone, |
| 2008 | modes, |
| 2009 | split_blocks(), |
| 2010 | (picture.width, picture.height), |
| 2011 | unspecified_color_config(), |
| 2012 | )?; |
| 2013 | Ok(crop_encoded(&encoded, picture.width, picture.height)) |
| 2014 | } |
| 2015 | |
| 2016 | |
| 2017 | |
| 2018 | |
| 2019 | |
| 2020 | pub(crate) fn encode_key_frame_inner( |
| 2021 | picture: &Picture, |
| 2022 | base_q_idx: u8, |
| 2023 | deadzone: f64, |
| 2024 | modes: &[u8], |
| 2025 | split_blocks: bool, |
| 2026 | render: (usize, usize), |
| 2027 | color_config: ColorConfig, |
| 2028 | ) -> Result<Encoded> { |
| 2029 | picture.check()?; |
| 2030 | if modes.is_empty() { |
| 2031 | return Err(Error::unsupported( |
| 2032 | "AV1 encode", |
| 2033 | "a mode search needs at least one mode to choose from", |
| 2034 | )); |
| 2035 | } |
| 2036 | if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) { |
| 2037 | return Err(Error::unsupported( |
| 2038 | "AV1 encode", |
| 2039 | format!("intra mode {bad} is not one the encoder predicts"), |
| 2040 | )); |
| 2041 | } |
| 2042 | |
| 2043 | |
| 2044 | |
| 2045 | |
| 2046 | |
| 2047 | |
| 2048 | |
| 2049 | let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; |
| 2050 | header.render_width = render.0 as u32; |
| 2051 | header.render_height = render.1 as u32; |
| 2052 | |
| 2053 | |
| 2054 | |
| 2055 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 2056 | |
| 2057 | |
| 2058 | |
| 2059 | |
| 2060 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 2061 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 2062 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 2063 | let mut luma = Plane { |
| 2064 | source: &picture_y8, |
| 2065 | reconstruction: vec![128; picture_y8.len()], |
| 2066 | width: picture.width, |
| 2067 | height: picture.height, |
| 2068 | true_width, |
| 2069 | true_height, |
| 2070 | }; |
| 2071 | let mut chroma = [ |
| 2072 | Plane { |
| 2073 | source: &picture_u8, |
| 2074 | reconstruction: vec![128; picture_u8.len()], |
| 2075 | width: picture.width / 2, |
| 2076 | height: picture.height / 2, |
| 2077 | true_width: true_width / 2, |
| 2078 | true_height: true_height / 2, |
| 2079 | }, |
| 2080 | Plane { |
| 2081 | source: &picture_v8, |
| 2082 | reconstruction: vec![128; picture_v8.len()], |
| 2083 | width: picture.width / 2, |
| 2084 | height: picture.height / 2, |
| 2085 | true_width: true_width / 2, |
| 2086 | true_height: true_height / 2, |
| 2087 | }, |
| 2088 | ]; |
| 2089 | |
| 2090 | |
| 2091 | |
| 2092 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 2093 | let search = Search { |
| 2094 | base_q_idx, |
| 2095 | deadzone, |
| 2096 | lambda: lambda_scale() * step * step, |
| 2097 | modes, |
| 2098 | top_k: prune_top_k(), |
| 2099 | }; |
| 2100 | |
| 2101 | |
| 2102 | |
| 2103 | |
| 2104 | |
| 2105 | |
| 2106 | |
| 2107 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 2108 | let (cols, rows) = (cols as usize, rows as usize); |
| 2109 | |
| 2110 | |
| 2111 | |
| 2112 | |
| 2113 | |
| 2114 | |
| 2115 | let mut above_mode = vec![DC_PRED; cols * 2]; |
| 2116 | let mut left_mode = vec![DC_PRED; rows * 2]; |
| 2117 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 2118 | let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); |
| 2119 | let mut modes = Vec::with_capacity(cols * rows); |
| 2120 | for sb_row in 0..sb_rows { |
| 2121 | for sb_col in 0..sb_cols { |
| 2122 | |
| 2123 | |
| 2124 | |
| 2125 | let mut blocks = Vec::with_capacity(4); |
| 2126 | for quadrant in 0..4 { |
| 2127 | let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2); |
| 2128 | if col >= cols || row >= rows { |
| 2129 | continue; |
| 2130 | } |
| 2131 | let (x, y) = (col * BLOCK, row * BLOCK); |
| 2132 | let (c0, r0) = (col * 2, row * 2); |
| 2133 | let base = snapshot(&luma, &chroma, (x, y)); |
| 2134 | |
| 2135 | |
| 2136 | |
| 2137 | |
| 2138 | |
| 2139 | |
| 2140 | |
| 2141 | |
| 2142 | let (has_cols32, has_rows32) = ( |
| 2143 | crate::tile::has_half( |
| 2144 | col as u32 * crate::tile::BLOCK_MI, |
| 2145 | crate::tile::BLOCK_MI, |
| 2146 | header.mi_cols, |
| 2147 | ), |
| 2148 | crate::tile::has_half( |
| 2149 | row as u32 * crate::tile::BLOCK_MI, |
| 2150 | crate::tile::BLOCK_MI, |
| 2151 | header.mi_rows, |
| 2152 | ), |
| 2153 | ); |
| 2154 | let whole_legal = has_cols32 && has_rows32; |
| 2155 | |
| 2156 | |
| 2157 | |
| 2158 | |
| 2159 | |
| 2160 | |
| 2161 | let sub_half = |sr: usize, sc: usize| { |
| 2162 | ( |
| 2163 | crate::tile::has_half( |
| 2164 | sc as u32 * crate::tile::SUB_MI, |
| 2165 | crate::tile::SUB_MI, |
| 2166 | header.mi_cols, |
| 2167 | ), |
| 2168 | crate::tile::has_half( |
| 2169 | sr as u32 * crate::tile::SUB_MI, |
| 2170 | crate::tile::SUB_MI, |
| 2171 | header.mi_rows, |
| 2172 | ), |
| 2173 | ) |
| 2174 | }; |
| 2175 | let both_axes_cut = (0..4) |
| 2176 | .map(|i| (r0 + i / 2, c0 + i % 2)) |
| 2177 | .filter(|&(sr, sc)| { |
| 2178 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 2179 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 2180 | }) |
| 2181 | .any(|(sr, sc)| { |
| 2182 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 2183 | !has_cols16 && !has_rows16 |
| 2184 | }); |
| 2185 | if !whole_legal && both_axes_cut { |
| 2186 | return Err(Error::unsupported( |
| 2187 | "AV1 encode", |
| 2188 | format!( |
| 2189 | "the 32x32 block at ({col},{row}) straddles the true frame edge \ |
| 2190 | in a way that needs a rectangular (HORZ/VERT) transform this \ |
| 2191 | encoder does not code yet" |
| 2192 | ), |
| 2193 | )); |
| 2194 | } |
| 2195 | |
| 2196 | |
| 2197 | |
| 2198 | let (whole, mut cost_whole) = code_square( |
| 2199 | &mut luma, |
| 2200 | &mut chroma, |
| 2201 | (x, y), |
| 2202 | BLOCK, |
| 2203 | &search, |
| 2204 | &mode_bits(above_mode[c0], left_mode[r0]), |
| 2205 | ); |
| 2206 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 2207 | let after_whole = snapshot(&luma, &chroma, (x, y)); |
| 2208 | |
| 2209 | |
| 2210 | |
| 2211 | restore(&mut luma, &mut chroma, (x, y), &base); |
| 2212 | let mut split = Vec::with_capacity(4); |
| 2213 | let mut cost_split = search.lambda |
| 2214 | * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); |
| 2215 | let mut split_modes = Vec::with_capacity(4); |
| 2216 | for sub in 0..4 { |
| 2217 | let (sc, sr) = (c0 + sub % 2, r0 + sub / 2); |
| 2218 | |
| 2219 | |
| 2220 | |
| 2221 | |
| 2222 | |
| 2223 | |
| 2224 | if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows |
| 2225 | || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols |
| 2226 | { |
| 2227 | continue; |
| 2228 | } |
| 2229 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 2230 | if has_cols16 && has_rows16 { |
| 2231 | let (block, cost) = code_square( |
| 2232 | &mut luma, |
| 2233 | &mut chroma, |
| 2234 | (x + (sub % 2) * SUB, y + (sub / 2) * SUB), |
| 2235 | SUB, |
| 2236 | &search, |
| 2237 | &mode_bits(above_mode[sc], left_mode[sr]), |
| 2238 | ); |
| 2239 | cost_split += cost; |
| 2240 | split_modes.push(block.mode); |
| 2241 | above_mode[sc] = block.mode; |
| 2242 | left_mode[sr] = block.mode; |
| 2243 | split.push(block); |
| 2244 | } else { |
| 2245 | |
| 2246 | |
| 2247 | |
| 2248 | |
| 2249 | |
| 2250 | |
| 2251 | |
| 2252 | |
| 2253 | let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]); |
| 2254 | let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB); |
| 2255 | let mut leaves = Vec::with_capacity(2); |
| 2256 | for i in 0..4 { |
| 2257 | let leaf_x = x_sub + (i % 2) * 8; |
| 2258 | let leaf_y = y_sub + (i / 2) * 8; |
| 2259 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 2260 | continue; |
| 2261 | } |
| 2262 | let (leaf, cost) = code_square( |
| 2263 | &mut luma, |
| 2264 | &mut chroma, |
| 2265 | (leaf_x, leaf_y), |
| 2266 | 8, |
| 2267 | &search, |
| 2268 | &leaf_mode_bits, |
| 2269 | ); |
| 2270 | cost_split += cost; |
| 2271 | split_modes.push(leaf.mode); |
| 2272 | leaves.push(leaf); |
| 2273 | } |
| 2274 | split.push(BlockCoeffs { |
| 2275 | eight: Some(leaves), |
| 2276 | ..BlockCoeffs::default() |
| 2277 | }); |
| 2278 | } |
| 2279 | } |
| 2280 | |
| 2281 | |
| 2282 | |
| 2283 | |
| 2284 | |
| 2285 | |
| 2286 | |
| 2287 | |
| 2288 | |
| 2289 | if !whole_legal || (split_blocks && cost_split < cost_whole) { |
| 2290 | modes.extend_from_slice(&split_modes); |
| 2291 | blocks.push(Quadrant::Split(split)); |
| 2292 | } else { |
| 2293 | restore(&mut luma, &mut chroma, (x, y), &after_whole); |
| 2294 | for cell in 0..2 { |
| 2295 | above_mode[c0 + cell] = whole.mode; |
| 2296 | left_mode[r0 + cell] = whole.mode; |
| 2297 | } |
| 2298 | modes.push(whole.mode); |
| 2299 | blocks.push(Quadrant::Whole(whole)); |
| 2300 | } |
| 2301 | } |
| 2302 | superblocks.push(Superblock::Split(blocks)); |
| 2303 | } |
| 2304 | } |
| 2305 | |
| 2306 | let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &superblocks)?; |
| 2307 | let mut stream = temporal_delimiter(); |
| 2308 | stream.extend_from_slice(&sequence_header_obu(&seq)?); |
| 2309 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 2310 | |
| 2311 | let [u, v] = chroma; |
| 2312 | Ok(Encoded { |
| 2313 | stream, |
| 2314 | modes, |
| 2315 | inter_block_share: 0.0, |
| 2316 | reconstruction: Picture { |
| 2317 | width: luma.width, |
| 2318 | height: luma.height, |
| 2319 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 2320 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 2321 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 2322 | }, |
| 2323 | tile, |
| 2324 | mi_cols: header.mi_cols, |
| 2325 | mi_rows: header.mi_rows, |
| 2326 | base_q_idx, |
| 2327 | }) |
| 2328 | } |
| 2329 | |
| 2330 | |
| 2331 | |
| 2332 | |
| 2333 | const SIZE_GROUP_32: usize = 3; |
| 2334 | |
| 2335 | |
| 2336 | |
| 2337 | |
| 2338 | const LAST_FRAME: i8 = 1; |
| 2339 | |
| 2340 | |
| 2341 | |
| 2342 | |
| 2343 | |
| 2344 | |
| 2345 | |
| 2346 | fn inter_mode_bits() -> [f64; 13] { |
| 2347 | std::array::from_fn(|mode| { |
| 2348 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 2349 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 2350 | } else { |
| 2351 | 0.0 |
| 2352 | }; |
| 2353 | symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode) |
| 2354 | + angle |
| 2355 | + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 2356 | }) |
| 2357 | } |
| 2358 | |
| 2359 | |
| 2360 | |
| 2361 | |
| 2362 | |
| 2363 | |
| 2364 | |
| 2365 | |
| 2366 | fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 { |
| 2367 | (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 } |
| 2368 | } |
| 2369 | |
| 2370 | |
| 2371 | |
| 2372 | |
| 2373 | fn mv_class_base(class: usize) -> i32 { |
| 2374 | if class == 0 { 0 } else { 2i32 << (class + 2) } |
| 2375 | } |
| 2376 | |
| 2377 | |
| 2378 | |
| 2379 | fn mv_class_of(z: i32) -> usize { |
| 2380 | let mut class = 0; |
| 2381 | while class < 10 && mv_class_base(class + 1) <= z { |
| 2382 | class += 1; |
| 2383 | } |
| 2384 | class |
| 2385 | } |
| 2386 | |
| 2387 | |
| 2388 | |
| 2389 | |
| 2390 | |
| 2391 | |
| 2392 | |
| 2393 | |
| 2394 | |
| 2395 | |
| 2396 | |
| 2397 | fn mv_component_bits(diff: i32) -> Option<f64> { |
| 2398 | let mag = diff.unsigned_abs() as i32; |
| 2399 | let z = mag - 1; |
| 2400 | if z & 1 == 0 { |
| 2401 | return None; |
| 2402 | } |
| 2403 | let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); |
| 2404 | let class = mv_class_of(z); |
| 2405 | bits += symbol_bits(&cdf::MV_CLASS, class); |
| 2406 | let local = z - mv_class_base(class); |
| 2407 | if class == 0 { |
| 2408 | let bit = (local >> 3) & 1; |
| 2409 | let fr = (local >> 1) & 3; |
| 2410 | bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize); |
| 2411 | bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize); |
| 2412 | } else { |
| 2413 | let d = local >> 3; |
| 2414 | let fr = (local >> 1) & 3; |
| 2415 | for i in 0..class { |
| 2416 | bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); |
| 2417 | } |
| 2418 | bits += symbol_bits(&cdf::MV_FR, fr as usize); |
| 2419 | } |
| 2420 | Some(bits) |
| 2421 | } |
| 2422 | |
| 2423 | |
| 2424 | |
| 2425 | |
| 2426 | |
| 2427 | fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> { |
| 2428 | let diff = (mv.0 - pred.0, mv.1 - pred.1); |
| 2429 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 2430 | (false, false) => 0, |
| 2431 | (false, true) => 1, |
| 2432 | (true, false) => 2, |
| 2433 | (true, true) => 3, |
| 2434 | }; |
| 2435 | let mut bits = symbol_bits(&cdf::MV_JOINT, joint); |
| 2436 | for d in [diff.0, diff.1] { |
| 2437 | if d != 0 { |
| 2438 | bits += mv_component_bits(d)?; |
| 2439 | } |
| 2440 | } |
| 2441 | Some(bits) |
| 2442 | } |
| 2443 | |
| 2444 | |
| 2445 | |
| 2446 | |
| 2447 | |
| 2448 | |
| 2449 | |
| 2450 | |
| 2451 | |
| 2452 | |
| 2453 | fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) { |
| 2454 | let round = |m: i32, p: i32| { |
| 2455 | let diff = m - p; |
| 2456 | let mag = diff.unsigned_abs() as i32; |
| 2457 | let even = mag - mag % 2; |
| 2458 | if even == 0 { |
| 2459 | p |
| 2460 | } else { |
| 2461 | p + even * diff.signum() |
| 2462 | } |
| 2463 | }; |
| 2464 | (round(mv.0, pred.0), round(mv.1, pred.1)) |
| 2465 | } |
| 2466 | |
| 2467 | |
| 2468 | |
| 2469 | #[allow(clippy::too_many_arguments)] |
| 2470 | fn mc_trial( |
| 2471 | plane: &Plane, |
| 2472 | x: usize, |
| 2473 | y: usize, |
| 2474 | side: usize, |
| 2475 | mv: (i32, i32), |
| 2476 | luma: bool, |
| 2477 | reference: &[u16], |
| 2478 | stride: usize, |
| 2479 | ref_width: usize, |
| 2480 | ref_height: usize, |
| 2481 | skip: bool, |
| 2482 | base_q_idx: u8, |
| 2483 | deadzone: f64, |
| 2484 | set: TxbSet, |
| 2485 | ) -> Trial { |
| 2486 | let x_q4 = mv_to_q4(x, mv.1, luma); |
| 2487 | let y_q4 = mv_to_q4(y, mv.0, luma); |
| 2488 | |
| 2489 | |
| 2490 | |
| 2491 | let mut prediction16 = vec![0u16; side * side]; |
| 2492 | mc::predict( |
| 2493 | reference, |
| 2494 | stride, |
| 2495 | ref_width, |
| 2496 | ref_height, |
| 2497 | x_q4, |
| 2498 | y_q4, |
| 2499 | side, |
| 2500 | side, |
| 2501 | &mut prediction16, |
| 2502 | ); |
| 2503 | let prediction: Vec<u8> = prediction16.iter().map(|&v| v as u8).collect(); |
| 2504 | plane.code_from_prediction(x, y, side, &prediction, skip, base_q_idx, deadzone, set) |
| 2505 | } |
| 2506 | |
| 2507 | |
| 2508 | |
| 2509 | |
| 2510 | |
| 2511 | |
| 2512 | |
| 2513 | |
| 2514 | |
| 2515 | |
| 2516 | |
| 2517 | |
| 2518 | |
| 2519 | |
| 2520 | |
| 2521 | |
| 2522 | |
| 2523 | |
| 2524 | |
| 2525 | #[allow(clippy::too_many_arguments)] |
| 2526 | fn search_inter_block( |
| 2527 | luma: &mut Plane, |
| 2528 | chroma: &mut [Plane; 2], |
| 2529 | (x, y): (usize, usize), |
| 2530 | search: &Search, |
| 2531 | mode_bits: &[f64; 13], |
| 2532 | reference: &Picture, |
| 2533 | stack: &MvStack, |
| 2534 | ) -> BlockCoeffs { |
| 2535 | let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16); |
| 2536 | let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height); |
| 2537 | |
| 2538 | |
| 2539 | |
| 2540 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 2541 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 2542 | let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 2543 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) |
| 2544 | + symbol_bits(&cdf::SINGLE_REF[0][3], 0); |
| 2545 | |
| 2546 | struct Candidate { |
| 2547 | cost: f64, |
| 2548 | luma: Trial, |
| 2549 | u: Trial, |
| 2550 | v: Trial, |
| 2551 | mode: u8, |
| 2552 | skip: bool, |
| 2553 | inter: Option<InterInfo>, |
| 2554 | } |
| 2555 | let mut best: Option<Candidate> = None; |
| 2556 | let mut consider = |candidate: Candidate| { |
| 2557 | if best.as_ref().is_none_or(|b| candidate.cost < b.cost) { |
| 2558 | best = Some(candidate); |
| 2559 | } |
| 2560 | }; |
| 2561 | |
| 2562 | |
| 2563 | |
| 2564 | |
| 2565 | |
| 2566 | |
| 2567 | |
| 2568 | |
| 2569 | |
| 2570 | let u_trial = chroma[0].trial( |
| 2571 | At { |
| 2572 | x: x / 2, |
| 2573 | y: y / 2, |
| 2574 | side: BLOCK / 2, |
| 2575 | reach: Reach::none(), |
| 2576 | set: chroma_set, |
| 2577 | }, |
| 2578 | DC_PRED, |
| 2579 | search.base_q_idx, |
| 2580 | search.deadzone, |
| 2581 | ); |
| 2582 | let v_trial = chroma[1].trial( |
| 2583 | At { |
| 2584 | x: x / 2, |
| 2585 | y: y / 2, |
| 2586 | side: BLOCK / 2, |
| 2587 | reach: Reach::none(), |
| 2588 | set: chroma_set, |
| 2589 | }, |
| 2590 | DC_PRED, |
| 2591 | search.base_q_idx, |
| 2592 | search.deadzone, |
| 2593 | ); |
| 2594 | |
| 2595 | let intra_modes: Vec<u8> = match search.top_k { |
| 2596 | Some(k) if k < search.modes.len() => { |
| 2597 | let scored = luma.intra_scores( |
| 2598 | At { |
| 2599 | x, |
| 2600 | y, |
| 2601 | side: BLOCK, |
| 2602 | reach, |
| 2603 | set: luma_set, |
| 2604 | }, |
| 2605 | search.modes, |
| 2606 | mode_bits, |
| 2607 | search.lambda, |
| 2608 | ); |
| 2609 | prune_by_sad(search.modes, scored, k) |
| 2610 | } |
| 2611 | _ => search.modes.to_vec(), |
| 2612 | }; |
| 2613 | for &mode in &intra_modes { |
| 2614 | let luma_trial = luma.trial( |
| 2615 | At { |
| 2616 | x, |
| 2617 | y, |
| 2618 | side: BLOCK, |
| 2619 | reach, |
| 2620 | set: luma_set, |
| 2621 | }, |
| 2622 | mode, |
| 2623 | search.base_q_idx, |
| 2624 | search.deadzone, |
| 2625 | ); |
| 2626 | let u = u_trial.clone(); |
| 2627 | let v = v_trial.clone(); |
| 2628 | let cost = luma_trial.sse |
| 2629 | + u.sse |
| 2630 | + v.sse |
| 2631 | + search.lambda |
| 2632 | * (luma_trial.bits |
| 2633 | + u.bits |
| 2634 | + v.bits |
| 2635 | + mode_bits[usize::from(mode)] |
| 2636 | + skip_bits(false) |
| 2637 | + intra_inter_bits(false)); |
| 2638 | consider(Candidate { |
| 2639 | cost, |
| 2640 | luma: luma_trial, |
| 2641 | u, |
| 2642 | v, |
| 2643 | mode, |
| 2644 | skip: false, |
| 2645 | inter: None, |
| 2646 | }); |
| 2647 | } |
| 2648 | |
| 2649 | |
| 2650 | |
| 2651 | |
| 2652 | |
| 2653 | |
| 2654 | |
| 2655 | |
| 2656 | |
| 2657 | |
| 2658 | |
| 2659 | let ref_luma = ( |
| 2660 | &reference.y, |
| 2661 | reference.width, |
| 2662 | luma.true_width, |
| 2663 | luma.true_height, |
| 2664 | ); |
| 2665 | let ref_u = ( |
| 2666 | &reference.u, |
| 2667 | reference.width / 2, |
| 2668 | chroma[0].true_width, |
| 2669 | chroma[0].true_height, |
| 2670 | ); |
| 2671 | let ref_v = ( |
| 2672 | &reference.v, |
| 2673 | reference.width / 2, |
| 2674 | chroma[1].true_width, |
| 2675 | chroma[1].true_height, |
| 2676 | ); |
| 2677 | let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) |
| 2678 | + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) |
| 2679 | + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); |
| 2680 | |
| 2681 | |
| 2682 | |
| 2683 | |
| 2684 | { |
| 2685 | let mv = stack.nearest_mv; |
| 2686 | let luma_trial = mc_trial( |
| 2687 | luma, |
| 2688 | x, |
| 2689 | y, |
| 2690 | BLOCK, |
| 2691 | mv, |
| 2692 | true, |
| 2693 | ref_luma.0, |
| 2694 | ref_luma.1, |
| 2695 | ref_luma.2, |
| 2696 | ref_luma.3, |
| 2697 | false, |
| 2698 | search.base_q_idx, |
| 2699 | search.deadzone, |
| 2700 | luma_set, |
| 2701 | ); |
| 2702 | let u = mc_trial( |
| 2703 | &chroma[0], |
| 2704 | x / 2, |
| 2705 | y / 2, |
| 2706 | BLOCK / 2, |
| 2707 | mv, |
| 2708 | false, |
| 2709 | ref_u.0, |
| 2710 | ref_u.1, |
| 2711 | ref_u.2, |
| 2712 | ref_u.3, |
| 2713 | false, |
| 2714 | search.base_q_idx, |
| 2715 | search.deadzone, |
| 2716 | chroma_set, |
| 2717 | ); |
| 2718 | let v = mc_trial( |
| 2719 | &chroma[1], |
| 2720 | x / 2, |
| 2721 | y / 2, |
| 2722 | BLOCK / 2, |
| 2723 | mv, |
| 2724 | false, |
| 2725 | ref_v.0, |
| 2726 | ref_v.1, |
| 2727 | ref_v.2, |
| 2728 | ref_v.3, |
| 2729 | false, |
| 2730 | search.base_q_idx, |
| 2731 | search.deadzone, |
| 2732 | chroma_set, |
| 2733 | ); |
| 2734 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 2735 | && u.levels.iter().all(|&l| l == 0) |
| 2736 | && v.levels.iter().all(|&l| l == 0); |
| 2737 | let cost = luma_trial.sse |
| 2738 | + u.sse |
| 2739 | + v.sse |
| 2740 | + search.lambda |
| 2741 | * (skip_bits(skip) |
| 2742 | + intra_inter_bits(true) |
| 2743 | + single_ref_bits |
| 2744 | + mode_bits_inter |
| 2745 | + if skip { |
| 2746 | 0.0 |
| 2747 | } else { |
| 2748 | luma_trial.bits + u.bits + v.bits |
| 2749 | }); |
| 2750 | consider(Candidate { |
| 2751 | cost, |
| 2752 | luma: luma_trial, |
| 2753 | u, |
| 2754 | v, |
| 2755 | mode: DC_PRED, |
| 2756 | skip, |
| 2757 | inter: Some(InterInfo { |
| 2758 | mode: InterMode::NearestMv, |
| 2759 | mv, |
| 2760 | }), |
| 2761 | }); |
| 2762 | } |
| 2763 | |
| 2764 | let source_block = luma.source_block(x, y, BLOCK); |
| 2765 | |
| 2766 | |
| 2767 | let ref_luma_8: Vec<u8> = ref_luma.0.iter().map(|&v| v as u8).collect(); |
| 2768 | #[cfg(test)] |
| 2769 | let t = std::time::Instant::now(); |
| 2770 | let found = motion::search( |
| 2771 | &ref_luma_8, |
| 2772 | ref_luma.1, |
| 2773 | ref_luma.2, |
| 2774 | ref_luma.3, |
| 2775 | &source_block, |
| 2776 | x, |
| 2777 | y, |
| 2778 | BLOCK, |
| 2779 | BLOCK, |
| 2780 | stack.pred_mv, |
| 2781 | search.lambda, |
| 2782 | ); |
| 2783 | #[cfg(test)] |
| 2784 | stage_add(0, t.elapsed()); |
| 2785 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 2786 | if let Some(mv_bits) = mv_residual_bits(mv, stack.pred_mv) { |
| 2787 | let luma_trial = mc_trial( |
| 2788 | luma, |
| 2789 | x, |
| 2790 | y, |
| 2791 | BLOCK, |
| 2792 | mv, |
| 2793 | true, |
| 2794 | ref_luma.0, |
| 2795 | ref_luma.1, |
| 2796 | ref_luma.2, |
| 2797 | ref_luma.3, |
| 2798 | false, |
| 2799 | search.base_q_idx, |
| 2800 | search.deadzone, |
| 2801 | luma_set, |
| 2802 | ); |
| 2803 | let u = mc_trial( |
| 2804 | &chroma[0], |
| 2805 | x / 2, |
| 2806 | y / 2, |
| 2807 | BLOCK / 2, |
| 2808 | mv, |
| 2809 | false, |
| 2810 | ref_u.0, |
| 2811 | ref_u.1, |
| 2812 | ref_u.2, |
| 2813 | ref_u.3, |
| 2814 | false, |
| 2815 | search.base_q_idx, |
| 2816 | search.deadzone, |
| 2817 | chroma_set, |
| 2818 | ); |
| 2819 | let v = mc_trial( |
| 2820 | &chroma[1], |
| 2821 | x / 2, |
| 2822 | y / 2, |
| 2823 | BLOCK / 2, |
| 2824 | mv, |
| 2825 | false, |
| 2826 | ref_v.0, |
| 2827 | ref_v.1, |
| 2828 | ref_v.2, |
| 2829 | ref_v.3, |
| 2830 | false, |
| 2831 | search.base_q_idx, |
| 2832 | search.deadzone, |
| 2833 | chroma_set, |
| 2834 | ); |
| 2835 | let drl_bits = if stack.entries.len() > 1 { |
| 2836 | symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0) |
| 2837 | } else { |
| 2838 | 0.0 |
| 2839 | }; |
| 2840 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 2841 | && u.levels.iter().all(|&l| l == 0) |
| 2842 | && v.levels.iter().all(|&l| l == 0); |
| 2843 | let cost = luma_trial.sse |
| 2844 | + u.sse |
| 2845 | + v.sse |
| 2846 | + search.lambda |
| 2847 | * (skip_bits(skip) |
| 2848 | + intra_inter_bits(true) |
| 2849 | + single_ref_bits |
| 2850 | + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) |
| 2851 | + drl_bits |
| 2852 | + mv_bits |
| 2853 | + if skip { |
| 2854 | 0.0 |
| 2855 | } else { |
| 2856 | luma_trial.bits + u.bits + v.bits |
| 2857 | }); |
| 2858 | consider(Candidate { |
| 2859 | cost, |
| 2860 | luma: luma_trial, |
| 2861 | u, |
| 2862 | v, |
| 2863 | mode: DC_PRED, |
| 2864 | skip, |
| 2865 | inter: Some(InterInfo { |
| 2866 | mode: InterMode::NewMv, |
| 2867 | mv, |
| 2868 | }), |
| 2869 | }); |
| 2870 | } |
| 2871 | |
| 2872 | let best = best.expect("the search offers at least the intra modes"); |
| 2873 | luma.commit(x, y, BLOCK, &best.luma); |
| 2874 | chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u); |
| 2875 | chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); |
| 2876 | BlockCoeffs { |
| 2877 | luma: coeffs(&best.luma.levels, BLOCK), |
| 2878 | u: coeffs(&best.u.levels, BLOCK / 2), |
| 2879 | v: coeffs(&best.v.levels, BLOCK / 2), |
| 2880 | mode: best.mode, |
| 2881 | skip: best.skip, |
| 2882 | inter: best.inter, |
| 2883 | eight: None, |
| 2884 | } |
| 2885 | } |
| 2886 | |
| 2887 | |
| 2888 | |
| 2889 | |
| 2890 | pub(crate) fn encode_inter_frame( |
| 2891 | picture: &Picture, |
| 2892 | reference: &Picture, |
| 2893 | base_q_idx: u8, |
| 2894 | deadzone: f64, |
| 2895 | order_hint: u32, |
| 2896 | render: (usize, usize), |
| 2897 | ) -> Result<Encoded> { |
| 2898 | picture.check()?; |
| 2899 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| 2900 | return Err(Error::unsupported( |
| 2901 | "AV1 encode", |
| 2902 | "an inter frame is coded only for a picture that is a whole number \ |
| 2903 | of 64x64 superblocks -- the inter tile writer never splits a \ |
| 2904 | superblock's partition below that", |
| 2905 | )); |
| 2906 | } |
| 2907 | if reference.width != picture.width || reference.height != picture.height { |
| 2908 | return Err(Error::unsupported( |
| 2909 | "AV1 encode", |
| 2910 | "the reference picture must be the same size as the one being coded", |
| 2911 | )); |
| 2912 | } |
| 2913 | |
| 2914 | |
| 2915 | |
| 2916 | |
| 2917 | |
| 2918 | const LAST_SLOT: u8 = 0; |
| 2919 | |
| 2920 | |
| 2921 | |
| 2922 | |
| 2923 | |
| 2924 | |
| 2925 | let (seq, mut header) = |
| 2926 | inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?; |
| 2927 | header.render_width = render.0 as u32; |
| 2928 | header.render_height = render.1 as u32; |
| 2929 | |
| 2930 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 2931 | |
| 2932 | |
| 2933 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 2934 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 2935 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 2936 | let mut luma = Plane { |
| 2937 | source: &picture_y8, |
| 2938 | reconstruction: vec![128; picture_y8.len()], |
| 2939 | width: picture.width, |
| 2940 | height: picture.height, |
| 2941 | true_width, |
| 2942 | true_height, |
| 2943 | }; |
| 2944 | let mut chroma = [ |
| 2945 | Plane { |
| 2946 | source: &picture_u8, |
| 2947 | reconstruction: vec![128; picture_u8.len()], |
| 2948 | width: picture.width / 2, |
| 2949 | height: picture.height / 2, |
| 2950 | true_width: true_width / 2, |
| 2951 | true_height: true_height / 2, |
| 2952 | }, |
| 2953 | Plane { |
| 2954 | source: &picture_v8, |
| 2955 | reconstruction: vec![128; picture_v8.len()], |
| 2956 | width: picture.width / 2, |
| 2957 | height: picture.height / 2, |
| 2958 | true_width: true_width / 2, |
| 2959 | true_height: true_height / 2, |
| 2960 | }, |
| 2961 | ]; |
| 2962 | |
| 2963 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 2964 | let search = Search { |
| 2965 | base_q_idx, |
| 2966 | deadzone, |
| 2967 | lambda: lambda_scale() * step * step, |
| 2968 | modes: &KEY_FRAME_MODES, |
| 2969 | top_k: prune_top_k_inter(), |
| 2970 | }; |
| 2971 | let mode_bits_table = inter_mode_bits(); |
| 2972 | |
| 2973 | |
| 2974 | |
| 2975 | |
| 2976 | |
| 2977 | |
| 2978 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 2979 | let (cols, rows) = (cols as usize, rows as usize); |
| 2980 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 2981 | let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize); |
| 2982 | let mut grid = MiGrid::new(mi_cols, mi_rows); |
| 2983 | let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows]; |
| 2984 | |
| 2985 | for sb_r in 0..sb_rows { |
| 2986 | for sb_c in 0..sb_cols { |
| 2987 | for quadrant in 0..4 { |
| 2988 | let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 2989 | |
| 2990 | |
| 2991 | if r32 >= rows || c32 >= cols { |
| 2992 | continue; |
| 2993 | } |
| 2994 | |
| 2995 | |
| 2996 | |
| 2997 | |
| 2998 | |
| 2999 | |
| 3000 | |
| 3001 | |
| 3002 | let (has_cols32, has_rows32) = ( |
| 3003 | crate::tile::has_half( |
| 3004 | c32 as u32 * crate::tile::BLOCK_MI, |
| 3005 | crate::tile::BLOCK_MI, |
| 3006 | header.mi_cols, |
| 3007 | ), |
| 3008 | crate::tile::has_half( |
| 3009 | r32 as u32 * crate::tile::BLOCK_MI, |
| 3010 | crate::tile::BLOCK_MI, |
| 3011 | header.mi_rows, |
| 3012 | ), |
| 3013 | ); |
| 3014 | if has_cols32 && has_rows32 { |
| 3015 | let (x, y) = (c32 * BLOCK, r32 * BLOCK); |
| 3016 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); |
| 3017 | let stack = |
| 3018 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); |
| 3019 | |
| 3020 | let block = search_inter_block( |
| 3021 | &mut luma, |
| 3022 | &mut chroma, |
| 3023 | (x, y), |
| 3024 | &search, |
| 3025 | &mode_bits_table, |
| 3026 | reference, |
| 3027 | &stack, |
| 3028 | ); |
| 3029 | |
| 3030 | for dr in 0..8 { |
| 3031 | for dc in 0..8 { |
| 3032 | grid.set( |
| 3033 | mi_row + dr, |
| 3034 | mi_col + dc, |
| 3035 | match block.inter { |
| 3036 | Some(info) => MiInfo { |
| 3037 | is_inter: true, |
| 3038 | ref_frame: LAST_FRAME, |
| 3039 | ref_frame1: None, |
| 3040 | mv1: None, |
| 3041 | mv: info.mv, |
| 3042 | is_new_mv: matches!(info.mode, InterMode::NewMv), |
| 3043 | size: 8, |
| 3044 | size_h: 8, |
| 3045 | is_global_mv0: false, |
| 3046 | is_global_mv1: false, |
| 3047 | }, |
| 3048 | |
| 3049 | |
| 3050 | |
| 3051 | |
| 3052 | None => MiInfo { |
| 3053 | is_inter: false, |
| 3054 | ref_frame: -1, |
| 3055 | ref_frame1: None, |
| 3056 | mv1: None, |
| 3057 | mv: (0, 0), |
| 3058 | is_new_mv: false, |
| 3059 | size: 8, |
| 3060 | size_h: 8, |
| 3061 | is_global_mv0: false, |
| 3062 | is_global_mv1: false, |
| 3063 | }, |
| 3064 | }, |
| 3065 | ); |
| 3066 | } |
| 3067 | } |
| 3068 | blocks[r32 * cols + c32] = Quadrant::Whole(block); |
| 3069 | } else { |
| 3070 | |
| 3071 | |
| 3072 | let sub_positions: Vec<(usize, usize)> = (0..4) |
| 3073 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 3074 | .filter(|&(sr, sc)| { |
| 3075 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 3076 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 3077 | }) |
| 3078 | .collect(); |
| 3079 | |
| 3080 | |
| 3081 | |
| 3082 | |
| 3083 | |
| 3084 | |
| 3085 | |
| 3086 | |
| 3087 | |
| 3088 | let mut leaves = Vec::with_capacity(sub_positions.len()); |
| 3089 | for (sr, sc) in sub_positions { |
| 3090 | let (has_cols16, has_rows16) = ( |
| 3091 | crate::tile::has_half( |
| 3092 | sc as u32 * crate::tile::SUB_MI, |
| 3093 | crate::tile::SUB_MI, |
| 3094 | header.mi_cols, |
| 3095 | ), |
| 3096 | crate::tile::has_half( |
| 3097 | sr as u32 * crate::tile::SUB_MI, |
| 3098 | crate::tile::SUB_MI, |
| 3099 | header.mi_rows, |
| 3100 | ), |
| 3101 | ); |
| 3102 | if !has_cols16 && !has_rows16 { |
| 3103 | return Err(Error::unsupported( |
| 3104 | "AV1 encode", |
| 3105 | format!( |
| 3106 | "the 16x16 block at ({sc},{sr}) straddles the true \ |
| 3107 | frame edge in a way that needs a rectangular \ |
| 3108 | (HORZ/VERT) transform this encoder does not code yet" |
| 3109 | ), |
| 3110 | )); |
| 3111 | } |
| 3112 | if has_cols16 && has_rows16 { |
| 3113 | let (x, y) = (sc * SUB, sr * SUB); |
| 3114 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 3115 | let stack = find_mv_stack( |
| 3116 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 3117 | ); |
| 3118 | let block = code_square_inter( |
| 3119 | &mut luma, |
| 3120 | &mut chroma, |
| 3121 | (x, y), |
| 3122 | SUB, |
| 3123 | &search, |
| 3124 | &mode_bits_table, |
| 3125 | reference, |
| 3126 | &stack, |
| 3127 | ); |
| 3128 | for dr in 0..4 { |
| 3129 | for dc in 0..4 { |
| 3130 | grid.set( |
| 3131 | mi_row + dr, |
| 3132 | mi_col + dc, |
| 3133 | match block.inter { |
| 3134 | Some(info) => MiInfo { |
| 3135 | is_inter: true, |
| 3136 | ref_frame: LAST_FRAME, |
| 3137 | ref_frame1: None, |
| 3138 | mv1: None, |
| 3139 | mv: info.mv, |
| 3140 | is_new_mv: matches!(info.mode, InterMode::NewMv), |
| 3141 | size: 4, |
| 3142 | size_h: 4, |
| 3143 | is_global_mv0: false, |
| 3144 | is_global_mv1: false, |
| 3145 | }, |
| 3146 | None => MiInfo { |
| 3147 | is_inter: false, |
| 3148 | ref_frame: -1, |
| 3149 | ref_frame1: None, |
| 3150 | mv1: None, |
| 3151 | mv: (0, 0), |
| 3152 | is_new_mv: false, |
| 3153 | size: 4, |
| 3154 | size_h: 4, |
| 3155 | is_global_mv0: false, |
| 3156 | is_global_mv1: false, |
| 3157 | }, |
| 3158 | }, |
| 3159 | ); |
| 3160 | } |
| 3161 | } |
| 3162 | leaves.push(block); |
| 3163 | } else { |
| 3164 | let (x_sub, y_sub) = (sc * SUB, sr * SUB); |
| 3165 | let (mi_row0, mi_col0) = (sr * 4, sc * 4); |
| 3166 | let mut eight = Vec::with_capacity(2); |
| 3167 | for i in 0..4 { |
| 3168 | let leaf_x = x_sub + (i % 2) * 8; |
| 3169 | let leaf_y = y_sub + (i / 2) * 8; |
| 3170 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 3171 | continue; |
| 3172 | } |
| 3173 | let (mi_row, mi_col) = |
| 3174 | (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); |
| 3175 | let stack = find_mv_stack( |
| 3176 | &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 3177 | ); |
| 3178 | let leaf = code_square_inter( |
| 3179 | &mut luma, |
| 3180 | &mut chroma, |
| 3181 | (leaf_x, leaf_y), |
| 3182 | 8, |
| 3183 | &search, |
| 3184 | &mode_bits_table, |
| 3185 | reference, |
| 3186 | &stack, |
| 3187 | ); |
| 3188 | for dr in 0..2 { |
| 3189 | for dc in 0..2 { |
| 3190 | grid.set( |
| 3191 | mi_row + dr, |
| 3192 | mi_col + dc, |
| 3193 | match leaf.inter { |
| 3194 | Some(info) => MiInfo { |
| 3195 | is_inter: true, |
| 3196 | ref_frame: LAST_FRAME, |
| 3197 | ref_frame1: None, |
| 3198 | mv1: None, |
| 3199 | mv: info.mv, |
| 3200 | is_new_mv: matches!( |
| 3201 | info.mode, |
| 3202 | InterMode::NewMv |
| 3203 | ), |
| 3204 | size: 2, |
| 3205 | size_h: 2, |
| 3206 | is_global_mv0: false, |
| 3207 | is_global_mv1: false, |
| 3208 | }, |
| 3209 | None => MiInfo { |
| 3210 | is_inter: false, |
| 3211 | ref_frame: -1, |
| 3212 | ref_frame1: None, |
| 3213 | mv1: None, |
| 3214 | mv: (0, 0), |
| 3215 | is_new_mv: false, |
| 3216 | size: 2, |
| 3217 | size_h: 2, |
| 3218 | is_global_mv0: false, |
| 3219 | is_global_mv1: false, |
| 3220 | }, |
| 3221 | }, |
| 3222 | ); |
| 3223 | } |
| 3224 | } |
| 3225 | eight.push(leaf); |
| 3226 | } |
| 3227 | leaves.push(BlockCoeffs { |
| 3228 | eight: Some(eight), |
| 3229 | ..BlockCoeffs::default() |
| 3230 | }); |
| 3231 | } |
| 3232 | } |
| 3233 | blocks[r32 * cols + c32] = Quadrant::Split(leaves); |
| 3234 | } |
| 3235 | } |
| 3236 | } |
| 3237 | } |
| 3238 | |
| 3239 | let modes = blocks |
| 3240 | .iter() |
| 3241 | .flat_map(Quadrant::blocks) |
| 3242 | .map(|b| b.mode) |
| 3243 | .collect::<Vec<_>>(); |
| 3244 | let inter_block_share = blocks |
| 3245 | .iter() |
| 3246 | .flat_map(Quadrant::blocks) |
| 3247 | .filter(|b| b.inter.is_some()) |
| 3248 | .count() as f64 |
| 3249 | / modes.len() as f64; |
| 3250 | let tile = sb_coeff_inter_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &blocks)?; |
| 3251 | let mut stream = temporal_delimiter(); |
| 3252 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 3253 | |
| 3254 | let [u, v] = chroma; |
| 3255 | Ok(Encoded { |
| 3256 | stream, |
| 3257 | modes, |
| 3258 | inter_block_share, |
| 3259 | reconstruction: Picture { |
| 3260 | width: luma.width, |
| 3261 | height: luma.height, |
| 3262 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 3263 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 3264 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 3265 | }, |
| 3266 | tile, |
| 3267 | mi_cols: header.mi_cols, |
| 3268 | mi_rows: header.mi_rows, |
| 3269 | base_q_idx, |
| 3270 | }) |
| 3271 | } |
| 3272 | |
| 3273 | |
| 3274 | |
| 3275 | |
| 3276 | |
| 3277 | #[derive(Clone, Debug)] |
| 3278 | pub struct EncodedSequence { |
| 3279 | |
| 3280 | |
| 3281 | |
| 3282 | |
| 3283 | pub stream: Vec<u8>, |
| 3284 | |
| 3285 | pub frames: Vec<Encoded>, |
| 3286 | } |
| 3287 | |
| 3288 | |
| 3289 | |
| 3290 | |
| 3291 | |
| 3292 | |
| 3293 | |
| 3294 | |
| 3295 | |
| 3296 | |
| 3297 | |
| 3298 | |
| 3299 | |
| 3300 | pub fn encode_sequence( |
| 3301 | pictures: &[Picture], |
| 3302 | base_q_idx: u8, |
| 3303 | deadzone: f64, |
| 3304 | ) -> Result<EncodedSequence> { |
| 3305 | let Some((first, rest)) = pictures.split_first() else { |
| 3306 | return Err(Error::unsupported( |
| 3307 | "AV1 encode", |
| 3308 | "a sequence needs at least one picture", |
| 3309 | )); |
| 3310 | }; |
| 3311 | first.check_even()?; |
| 3312 | let render = (first.width, first.height); |
| 3313 | |
| 3314 | |
| 3315 | |
| 3316 | |
| 3317 | |
| 3318 | let key = encode_key_frame_inner( |
| 3319 | &first.padded_to(SUPERBLOCK), |
| 3320 | base_q_idx, |
| 3321 | deadzone, |
| 3322 | &KEY_FRAME_MODES, |
| 3323 | split_blocks(), |
| 3324 | render, |
| 3325 | unspecified_color_config(), |
| 3326 | )?; |
| 3327 | let mut stream = key.stream.clone(); |
| 3328 | let mut reference = key.reconstruction.clone(); |
| 3329 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 3330 | for (i, picture) in rest.iter().enumerate() { |
| 3331 | picture.check_even()?; |
| 3332 | if (picture.width, picture.height) != render { |
| 3333 | return Err(Error::unsupported( |
| 3334 | "AV1 encode", |
| 3335 | "every picture in a sequence must be the same size as the first", |
| 3336 | )); |
| 3337 | } |
| 3338 | let order_hint = (i + 1) as u32; |
| 3339 | let inter = encode_inter_frame( |
| 3340 | &picture.padded_to(SUPERBLOCK), |
| 3341 | &reference, |
| 3342 | base_q_idx, |
| 3343 | deadzone, |
| 3344 | order_hint, |
| 3345 | render, |
| 3346 | )?; |
| 3347 | stream.extend_from_slice(&inter.stream); |
| 3348 | reference = inter.reconstruction.clone(); |
| 3349 | frames.push(crop_encoded(&inter, render.0, render.1)); |
| 3350 | } |
| 3351 | Ok(EncodedSequence { stream, frames }) |
| 3352 | } |
| 3353 | |
| 3354 | #[cfg(test)] |
| 3355 | mod tests { |
| 3356 | |
| 3357 | |
| 3358 | |
| 3359 | |
| 3360 | |
| 3361 | |
| 3362 | |
| 3363 | |
| 3364 | |
| 3365 | |
| 3366 | #[test] |
| 3367 | fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { |
| 3368 | for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 3369 | let (bw_log2, bh_log2) = |
| 3370 | ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize); |
| 3371 | let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); |
| 3372 | for (name, table) in |
| 3373 | [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)] |
| 3374 | { |
| 3375 | assert_eq!( |
| 3376 | table.len() * 8, |
| 3377 | rows * cols, |
| 3378 | "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" |
| 3379 | ); |
| 3380 | let mut seen = vec![0u32; table.len() * 8]; |
| 3381 | for blk_row in 0..rows { |
| 3382 | for blk_col in 0..cols { |
| 3383 | let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); |
| 3384 | assert!( |
| 3385 | idx < seen.len(), |
| 3386 | "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" |
| 3387 | ); |
| 3388 | seen[idx] += 1; |
| 3389 | } |
| 3390 | } |
| 3391 | assert!( |
| 3392 | seen.iter().all(|&n| n == 1), |
| 3393 | "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ |
| 3394 | (row stride is not {cols})" |
| 3395 | ); |
| 3396 | } |
| 3397 | } |
| 3398 | } |
| 3399 | use super::*; |
| 3400 | use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED}; |
| 3401 | use std::io::Write; |
| 3402 | use std::process::{Command, Stdio}; |
| 3403 | |
| 3404 | |
| 3405 | |
| 3406 | |
| 3407 | |
| 3408 | |
| 3409 | |
| 3410 | |
| 3411 | |
| 3412 | |
| 3413 | |
| 3414 | |
| 3415 | |
| 3416 | |
| 3417 | |
| 3418 | |
| 3419 | |
| 3420 | |
| 3421 | |
| 3422 | |
| 3423 | |
| 3424 | #[test] |
| 3425 | fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { |
| 3426 | |
| 3427 | const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ |
| 3428 | (4, 8, 64, 9280, 64, 550), |
| 3429 | (8, 4, 64, 3712, 64, 9630), |
| 3430 | (8, 16, 16, 2352, 16, 134), |
| 3431 | (16, 8, 16, 960, 16, 2400), |
| 3432 | (16, 32, 4, 620, 4, 32), |
| 3433 | (32, 16, 4, 32, 4, 184), |
| 3434 | (32, 64, 1, 127, 1, 0), |
| 3435 | (64, 32, 1, 19, 1, 34), |
| 3436 | (4, 16, 32, 5472, 32, 14), |
| 3437 | (16, 4, 32, 960, 32, 6464), |
| 3438 | (8, 32, 8, 1400, 8, 2), |
| 3439 | (32, 8, 8, 32, 8, 1136), |
| 3440 | (16, 64, 2, 382, 2, 0), |
| 3441 | (64, 16, 2, 4, 2, 84), |
| 3442 | ]; |
| 3443 | |
| 3444 | |
| 3445 | |
| 3446 | |
| 3447 | fn libaom_reach( |
| 3448 | bw: usize, |
| 3449 | bh: usize, |
| 3450 | x: usize, |
| 3451 | y: usize, |
| 3452 | width: usize, |
| 3453 | height: usize, |
| 3454 | ) -> (bool, bool) { |
| 3455 | let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); |
| 3456 | let (_bw_unit, bh_unit) = (bw / 4, bh / 4); |
| 3457 | let sb_mi_size = 16usize; |
| 3458 | let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; |
| 3459 | let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; |
| 3460 | let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; |
| 3461 | let (tr_table, bl_table) = rect_reach_tables(bw, bh); |
| 3462 | let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; |
| 3463 | |
| 3464 | let top_right = if y == 0 || x + bw >= width { |
| 3465 | false |
| 3466 | } else if blk_row_in_sb == 0 { |
| 3467 | |
| 3468 | |
| 3469 | true |
| 3470 | } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { |
| 3471 | false |
| 3472 | } else { |
| 3473 | bit(tr_table) |
| 3474 | }; |
| 3475 | |
| 3476 | let bottom_left = if x == 0 || y + bh >= height { |
| 3477 | false |
| 3478 | } else if blk_col_in_sb == 0 { |
| 3479 | |
| 3480 | (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size |
| 3481 | } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { |
| 3482 | false |
| 3483 | } else { |
| 3484 | bit(bl_table) |
| 3485 | }; |
| 3486 | (top_right, bottom_left) |
| 3487 | } |
| 3488 | for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { |
| 3489 | let (tr, bl) = rect_reach_tables(bw, bh); |
| 3490 | let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>(); |
| 3491 | assert_eq!( |
| 3492 | (tr.len(), sum(tr), bl.len(), sum(bl)), |
| 3493 | (tr_len, tr_sum, bl_len, bl_sum), |
| 3494 | "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" |
| 3495 | ); |
| 3496 | |
| 3497 | |
| 3498 | for sb_y in [0usize, 64] { |
| 3499 | for sb_x in [0usize, 64] { |
| 3500 | for y in (sb_y..sb_y + 64).step_by(bh) { |
| 3501 | for x in (sb_x..sb_x + 64).step_by(bw) { |
| 3502 | let got = Reach::of_rect(bw, bh, x, y, 256, 256); |
| 3503 | let want = libaom_reach(bw, bh, x, y, 256, 256); |
| 3504 | assert_eq!( |
| 3505 | (got.above_right, got.below_left), |
| 3506 | want, |
| 3507 | "{bw}x{bh} at ({x}, {y})" |
| 3508 | ); |
| 3509 | } |
| 3510 | } |
| 3511 | } |
| 3512 | } |
| 3513 | } |
| 3514 | } |
| 3515 | |
| 3516 | |
| 3517 | |
| 3518 | |
| 3519 | |
| 3520 | |
| 3521 | |
| 3522 | |
| 3523 | fn have_ffmpeg() -> bool { |
| 3524 | let present = Command::new("ffmpeg") |
| 3525 | .arg("-version") |
| 3526 | .stdout(Stdio::null()) |
| 3527 | .stderr(Stdio::null()) |
| 3528 | .status() |
| 3529 | .is_ok_and(|s| s.success()); |
| 3530 | assert!( |
| 3531 | present |
| 3532 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 3533 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 3534 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 3535 | ); |
| 3536 | present |
| 3537 | } |
| 3538 | |
| 3539 | |
| 3540 | fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { |
| 3541 | let mut child = Command::new("ffmpeg") |
| 3542 | .args([ |
| 3543 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 3544 | ]) |
| 3545 | .stdin(Stdio::piped()) |
| 3546 | .stdout(Stdio::piped()) |
| 3547 | .stderr(Stdio::piped()) |
| 3548 | .spawn() |
| 3549 | .expect("ffmpeg failed to start"); |
| 3550 | child |
| 3551 | .stdin |
| 3552 | .take() |
| 3553 | .expect("ffmpeg stdin") |
| 3554 | .write_all(stream) |
| 3555 | .expect("writing the stream to ffmpeg"); |
| 3556 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 3557 | assert!( |
| 3558 | out.status.success(), |
| 3559 | "ffmpeg refused the stream: {}", |
| 3560 | String::from_utf8_lossy(&out.stderr) |
| 3561 | ); |
| 3562 | let (luma, chroma) = (width * height, width * height / 4); |
| 3563 | assert_eq!( |
| 3564 | out.stdout.len(), |
| 3565 | luma + 2 * chroma, |
| 3566 | "expected one 4:2:0 frame" |
| 3567 | ); |
| 3568 | Picture { |
| 3569 | width, |
| 3570 | height, |
| 3571 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 3572 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 3573 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 3574 | } |
| 3575 | } |
| 3576 | |
| 3577 | |
| 3578 | |
| 3579 | |
| 3580 | fn test_card(width: usize, height: usize) -> Picture { |
| 3581 | let mut picture = Picture::grey(width, height); |
| 3582 | for y in 0..height { |
| 3583 | for x in 0..width { |
| 3584 | let gradient = x as f64 * 200.0 / width as f64; |
| 3585 | let ripple = 30.0 |
| 3586 | * (x as f64 * std::f64::consts::PI / 23.0).sin() |
| 3587 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 3588 | let edge = if x > width * 3 / 7 && y > height / 3 { |
| 3589 | 40.0 |
| 3590 | } else { |
| 3591 | 0.0 |
| 3592 | }; |
| 3593 | picture.y[y * width + x] = |
| 3594 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 3595 | } |
| 3596 | } |
| 3597 | for y in 0..height / 2 { |
| 3598 | for x in 0..width / 2 { |
| 3599 | let i = y * width / 2 + x; |
| 3600 | picture.u[i] = (100 + (x * 60 / (width / 2))) as u16; |
| 3601 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 3602 | } |
| 3603 | } |
| 3604 | picture |
| 3605 | } |
| 3606 | |
| 3607 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 3608 | let squared: f64 = a |
| 3609 | .iter() |
| 3610 | .zip(b) |
| 3611 | .map(|(&x, &y)| { |
| 3612 | let d = f64::from(x) - f64::from(y); |
| 3613 | d * d |
| 3614 | }) |
| 3615 | .sum(); |
| 3616 | if squared == 0.0 { |
| 3617 | return f64::INFINITY; |
| 3618 | } |
| 3619 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 3620 | } |
| 3621 | |
| 3622 | |
| 3623 | |
| 3624 | |
| 3625 | |
| 3626 | |
| 3627 | |
| 3628 | #[test] |
| 3629 | fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() { |
| 3630 | if !have_ffmpeg() { |
| 3631 | eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg"); |
| 3632 | return; |
| 3633 | } |
| 3634 | for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] { |
| 3635 | let picture = test_card(width, height); |
| 3636 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 3637 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 3638 | assert_eq!( |
| 3639 | decoded.y, encoded.reconstruction.y, |
| 3640 | "{width}x{height}: luma" |
| 3641 | ); |
| 3642 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 3643 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 3644 | } |
| 3645 | |
| 3646 | |
| 3647 | let (width, height) = (64usize, 64usize); |
| 3648 | let picture = test_card(width, height); |
| 3649 | for &q in &[15u8, 45, 100, 200] { |
| 3650 | let encoded = encode_key_frame(&picture, q, 0.5).unwrap(); |
| 3651 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 3652 | assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma"); |
| 3653 | assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); |
| 3654 | assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); |
| 3655 | } |
| 3656 | } |
| 3657 | |
| 3658 | |
| 3659 | |
| 3660 | |
| 3661 | |
| 3662 | |
| 3663 | |
| 3664 | |
| 3665 | |
| 3666 | #[test] |
| 3667 | fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() { |
| 3668 | if !have_ffmpeg() { |
| 3669 | eprintln!( |
| 3670 | "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg" |
| 3671 | ); |
| 3672 | return; |
| 3673 | } |
| 3674 | let (width, height) = (64usize, 64usize); |
| 3675 | let picture = Picture::grey(width, height); |
| 3676 | let key = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 3677 | |
| 3678 | let (seq, _) = key_frame_headers(width, height, 100).unwrap(); |
| 3679 | let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); |
| 3680 | |
| 3681 | let residual_block = BlockCoeffs { |
| 3682 | luma: vec![Coeff { |
| 3683 | row: 0, |
| 3684 | col: 0, |
| 3685 | level: 4, |
| 3686 | }], |
| 3687 | u: Vec::new(), |
| 3688 | v: Vec::new(), |
| 3689 | mode: 0, |
| 3690 | skip: false, |
| 3691 | eight: None, |
| 3692 | inter: Some(InterInfo { |
| 3693 | mode: InterMode::NearestMv, |
| 3694 | mv: (0, 0), |
| 3695 | }), |
| 3696 | }; |
| 3697 | let skipped_block = BlockCoeffs { |
| 3698 | skip: true, |
| 3699 | inter: Some(InterInfo { |
| 3700 | mode: InterMode::NearestMv, |
| 3701 | mv: (0, 0), |
| 3702 | }), |
| 3703 | ..BlockCoeffs::default() |
| 3704 | }; |
| 3705 | let blocks = vec![ |
| 3706 | Quadrant::Whole(residual_block), |
| 3707 | Quadrant::Whole(skipped_block.clone()), |
| 3708 | Quadrant::Whole(skipped_block.clone()), |
| 3709 | Quadrant::Whole(skipped_block), |
| 3710 | ]; |
| 3711 | let tile = |
| 3712 | sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks) |
| 3713 | .unwrap(); |
| 3714 | |
| 3715 | |
| 3716 | |
| 3717 | |
| 3718 | |
| 3719 | |
| 3720 | let mut stream = key.stream.clone(); |
| 3721 | stream.extend_from_slice(&temporal_delimiter()); |
| 3722 | stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap()); |
| 3723 | |
| 3724 | ffmpeg_decode_sequence(&stream, width, height, 2); |
| 3725 | } |
| 3726 | |
| 3727 | |
| 3728 | |
| 3729 | |
| 3730 | fn ffprobe_size(stream: &[u8]) -> (u32, u32) { |
| 3731 | |
| 3732 | |
| 3733 | |
| 3734 | static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 3735 | let path = std::env::temp_dir().join(format!( |
| 3736 | "ec-av1-probe-{}-{}.obu", |
| 3737 | std::process::id(), |
| 3738 | PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) |
| 3739 | )); |
| 3740 | let _ = std::fs::remove_file(&path); |
| 3741 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 3742 | let out = Command::new("ffprobe") |
| 3743 | .args([ |
| 3744 | "-v", |
| 3745 | "error", |
| 3746 | "-f", |
| 3747 | "obu", |
| 3748 | "-select_streams", |
| 3749 | "v:0", |
| 3750 | "-show_entries", |
| 3751 | "stream=width,height", |
| 3752 | "-of", |
| 3753 | "csv=p=0", |
| 3754 | ]) |
| 3755 | .arg(&path) |
| 3756 | .output() |
| 3757 | .expect("ffprobe failed to run"); |
| 3758 | let _ = std::fs::remove_file(&path); |
| 3759 | assert!( |
| 3760 | out.status.success(), |
| 3761 | "ffprobe refused the stream: {}", |
| 3762 | String::from_utf8_lossy(&out.stderr) |
| 3763 | ); |
| 3764 | let text = String::from_utf8_lossy(&out.stdout); |
| 3765 | let mut fields = text.trim().split(','); |
| 3766 | let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); |
| 3767 | let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); |
| 3768 | (width, height) |
| 3769 | } |
| 3770 | |
| 3771 | |
| 3772 | |
| 3773 | |
| 3774 | |
| 3775 | |
| 3776 | |
| 3777 | |
| 3778 | |
| 3779 | |
| 3780 | |
| 3781 | |
| 3782 | |
| 3783 | |
| 3784 | |
| 3785 | #[test] |
| 3786 | fn a_frame_round_trips_at_its_own_size() { |
| 3787 | if !have_ffmpeg() { |
| 3788 | eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg"); |
| 3789 | return; |
| 3790 | } |
| 3791 | |
| 3792 | |
| 3793 | |
| 3794 | for &(width, height) in &[ |
| 3795 | (1920usize, 1080usize), |
| 3796 | (640, 352), |
| 3797 | (1280, 720), |
| 3798 | (64, 56), |
| 3799 | (854, 480), |
| 3800 | (216, 96), |
| 3801 | (192, 120), |
| 3802 | ] { |
| 3803 | let picture = test_card(width, height); |
| 3804 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 3805 | assert_eq!( |
| 3806 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 3807 | (width, height), |
| 3808 | "{width}x{height}: reconstruction is cropped to the picture's own size" |
| 3809 | ); |
| 3810 | assert_eq!( |
| 3811 | ffprobe_size(&encoded.stream), |
| 3812 | (width as u32, height as u32), |
| 3813 | "{width}x{height}: ffprobe reports the true (display) size, not the padded one" |
| 3814 | ); |
| 3815 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 3816 | assert_eq!( |
| 3817 | decoded.y, encoded.reconstruction.y, |
| 3818 | "{width}x{height}: luma" |
| 3819 | ); |
| 3820 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 3821 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 3822 | } |
| 3823 | } |
| 3824 | |
| 3825 | |
| 3826 | |
| 3827 | |
| 3828 | |
| 3829 | |
| 3830 | |
| 3831 | |
| 3832 | |
| 3833 | |
| 3834 | |
| 3835 | |
| 3836 | |
| 3837 | |
| 3838 | |
| 3839 | |
| 3840 | |
| 3841 | |
| 3842 | |
| 3843 | |
| 3844 | |
| 3845 | |
| 3846 | |
| 3847 | |
| 3848 | |
| 3849 | |
| 3850 | #[test] |
| 3851 | fn an_854x480_picture_round_trips_through_its_padding() { |
| 3852 | if !have_ffmpeg() { |
| 3853 | return; |
| 3854 | } |
| 3855 | let (width, height) = (854usize, 480usize); |
| 3856 | let picture = test_card(width, height); |
| 3857 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 3858 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 3859 | assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); |
| 3860 | assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); |
| 3861 | assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); |
| 3862 | } |
| 3863 | |
| 3864 | |
| 3865 | |
| 3866 | |
| 3867 | |
| 3868 | |
| 3869 | |
| 3870 | |
| 3871 | |
| 3872 | |
| 3873 | |
| 3874 | |
| 3875 | |
| 3876 | |
| 3877 | |
| 3878 | |
| 3879 | |
| 3880 | #[test] |
| 3881 | fn of_tu_follows_the_block_row_including_under_vert_ab() { |
| 3882 | |
| 3883 | |
| 3884 | |
| 3885 | |
| 3886 | |
| 3887 | let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK); |
| 3888 | assert_eq!( |
| 3889 | Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right, |
| 3890 | plain.above_right, |
| 3891 | "ordinary table: the top-right TX4 unit takes the block's row" |
| 3892 | ); |
| 3893 | let guard = Reach::vert_ab_partition(); |
| 3894 | let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK); |
| 3895 | assert_eq!( |
| 3896 | Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right, |
| 3897 | vert.above_right, |
| 3898 | "vert AB: the unit follows the vert row the block just picked" |
| 3899 | ); |
| 3900 | assert_ne!( |
| 3901 | plain.above_right, vert.above_right, |
| 3902 | "this position is the cell where the vert tables disagree; pick another if libaom's tables change" |
| 3903 | ); |
| 3904 | drop(guard); |
| 3905 | } |
| 3906 | |
| 3907 | |
| 3908 | |
| 3909 | |
| 3910 | |
| 3911 | |
| 3912 | |
| 3913 | |
| 3914 | #[test] |
| 3915 | fn reach_matches_libaom_has_top_right_and_has_bottom_left() { |
| 3916 | |
| 3917 | |
| 3918 | |
| 3919 | |
| 3920 | fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, height: usize) -> bool { |
| 3921 | if y == 0 || x + side >= width { |
| 3922 | return false; |
| 3923 | } |
| 3924 | let (row, col, per_side) = ( |
| 3925 | (y % SUPERBLOCK) / side, |
| 3926 | (x % SUPERBLOCK) / side, |
| 3927 | SUPERBLOCK / side, |
| 3928 | ); |
| 3929 | if row == 0 { |
| 3930 | return true; |
| 3931 | } |
| 3932 | if col + 1 == per_side { |
| 3933 | return false; |
| 3934 | } |
| 3935 | let stride = 128 / side; |
| 3936 | let index = row * stride + col; |
| 3937 | let table = if side == BLOCK { |
| 3938 | [95u8, 87].to_vec() |
| 3939 | } else { |
| 3940 | vec![255, 85, 119, 85, 127, 85, 119, 85] |
| 3941 | }; |
| 3942 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 3943 | } |
| 3944 | |
| 3945 | fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize) -> bool { |
| 3946 | if x == 0 || y + side >= height { |
| 3947 | return false; |
| 3948 | } |
| 3949 | let (row, col, per_side) = ( |
| 3950 | (y % SUPERBLOCK) / side, |
| 3951 | (x % SUPERBLOCK) / side, |
| 3952 | SUPERBLOCK / side, |
| 3953 | ); |
| 3954 | if col == 0 { |
| 3955 | return row * side + side < SUPERBLOCK; |
| 3956 | } |
| 3957 | if row + 1 == per_side { |
| 3958 | return false; |
| 3959 | } |
| 3960 | let stride = 128 / side; |
| 3961 | let index = row * stride + col; |
| 3962 | let table = if side == BLOCK { |
| 3963 | [4u8, 4].to_vec() |
| 3964 | } else { |
| 3965 | vec![84, 16, 84, 0, 84, 16, 84, 0] |
| 3966 | }; |
| 3967 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 3968 | } |
| 3969 | |
| 3970 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 3971 | for side in [16usize, BLOCK] { |
| 3972 | for y in (0..height).step_by(side) { |
| 3973 | for x in (0..width).step_by(side) { |
| 3974 | let reach = Reach::of(side, x, y, width, height); |
| 3975 | assert_eq!( |
| 3976 | reach.above_right, |
| 3977 | libaom_top_right(side, x, y, width, height), |
| 3978 | "side={side} x={x} y={y}: above_right" |
| 3979 | ); |
| 3980 | assert_eq!( |
| 3981 | reach.below_left, |
| 3982 | libaom_bottom_left(side, x, y, height), |
| 3983 | "side={side} x={x} y={y}: below_left" |
| 3984 | ); |
| 3985 | } |
| 3986 | } |
| 3987 | } |
| 3988 | } |
| 3989 | |
| 3990 | |
| 3991 | |
| 3992 | |
| 3993 | |
| 3994 | |
| 3995 | |
| 3996 | |
| 3997 | |
| 3998 | |
| 3999 | |
| 4000 | |
| 4001 | |
| 4002 | |
| 4003 | |
| 4004 | #[test] |
| 4005 | fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { |
| 4006 | |
| 4007 | |
| 4008 | fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 4009 | let (plane_bw_unit, count) = (bw / 4, tx / 4); |
| 4010 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 4011 | let _ = bh; |
| 4012 | if row_off_u > 0 { |
| 4013 | col_off_u + count < plane_bw_unit |
| 4014 | } else if col_off_u + count < plane_bw_unit { |
| 4015 | true |
| 4016 | } else { |
| 4017 | blk |
| 4018 | } |
| 4019 | } |
| 4020 | fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 4021 | let (plane_bh_unit, count) = (bh / 4, tx / 4); |
| 4022 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 4023 | let _ = bw; |
| 4024 | if col_off_u > 0 { |
| 4025 | false |
| 4026 | } else if row_off_u + count < plane_bh_unit { |
| 4027 | true |
| 4028 | } else { |
| 4029 | blk |
| 4030 | } |
| 4031 | } |
| 4032 | for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 4033 | for &tx in &[4usize, 8, 16, 32] { |
| 4034 | if tx > bw.min(bh) { |
| 4035 | continue; |
| 4036 | } |
| 4037 | for row_off in (0..bh).step_by(tx) { |
| 4038 | for col_off in (0..bw).step_by(tx) { |
| 4039 | for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] { |
| 4040 | let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk); |
| 4041 | assert_eq!( |
| 4042 | got.above_right, |
| 4043 | libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), |
| 4044 | "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 4045 | ); |
| 4046 | assert_eq!( |
| 4047 | got.below_left, |
| 4048 | libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), |
| 4049 | "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 4050 | ); |
| 4051 | } |
| 4052 | } |
| 4053 | } |
| 4054 | } |
| 4055 | } |
| 4056 | } |
| 4057 | |
| 4058 | #[test] |
| 4059 | fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { |
| 4060 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 4061 | |
| 4062 | |
| 4063 | let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK); |
| 4064 | let mut flipped = 0; |
| 4065 | for row in 0..8 { |
| 4066 | for col in 1..8 { |
| 4067 | let (x, y) = (sb_x + col * 8, sb_y + row * 8); |
| 4068 | let raster = Reach::of(8, x, y, width, height).below_left; |
| 4069 | let vert = { |
| 4070 | let _guard = Reach::vert_ab_partition(); |
| 4071 | Reach::of(8, x, y, width, height).below_left |
| 4072 | }; |
| 4073 | |
| 4074 | |
| 4075 | if row % 2 == 0 && col % 2 == 1 { |
| 4076 | assert!(!raster, "raster below_left at row={row} col={col}"); |
| 4077 | assert!(vert, "vert below_left at row={row} col={col}"); |
| 4078 | flipped += 1; |
| 4079 | } else { |
| 4080 | assert_eq!(raster, vert, "guard moved row={row} col={col}"); |
| 4081 | } |
| 4082 | } |
| 4083 | } |
| 4084 | assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip"); |
| 4085 | |
| 4086 | assert!(!Reach::of(8, sb_x + 8, sb_y, width, height).below_left); |
| 4087 | } |
| 4088 | |
| 4089 | |
| 4090 | |
| 4091 | #[test] |
| 4092 | fn odd_dimensions_are_refused() { |
| 4093 | for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { |
| 4094 | let picture = Picture::grey(width, height); |
| 4095 | let err = encode_key_frame(&picture, 100, 0.5) |
| 4096 | .expect_err(&format!("{width}x{height} is odd and must be refused")); |
| 4097 | assert!( |
| 4098 | err.to_string().contains("even"), |
| 4099 | "{width}x{height}: error was {err}" |
| 4100 | ); |
| 4101 | } |
| 4102 | } |
| 4103 | |
| 4104 | |
| 4105 | |
| 4106 | |
| 4107 | |
| 4108 | #[test] |
| 4109 | fn sequence_round_trips_at_a_non_multiple_size() { |
| 4110 | if !have_ffmpeg() { |
| 4111 | eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg"); |
| 4112 | return; |
| 4113 | } |
| 4114 | let (width, height) = (160usize, 96usize); |
| 4115 | let pictures: Vec<Picture> = (0..3) |
| 4116 | .map(|i| panned_test_card(width, height, i * 3)) |
| 4117 | .collect(); |
| 4118 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 4119 | assert_eq!(encoded.frames.len(), 3); |
| 4120 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 4121 | assert_eq!( |
| 4122 | (frame.reconstruction.width, frame.reconstruction.height), |
| 4123 | (width, height), |
| 4124 | "frame {i}: reconstruction size" |
| 4125 | ); |
| 4126 | } |
| 4127 | |
| 4128 | |
| 4129 | assert_eq!( |
| 4130 | ffprobe_size(&encoded.stream), |
| 4131 | (width as u32, height as u32), |
| 4132 | "sequence: ffprobe reports the true (display) size" |
| 4133 | ); |
| 4134 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 4135 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 4136 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 4137 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 4138 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 4139 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 4140 | } |
| 4141 | } |
| 4142 | |
| 4143 | |
| 4144 | |
| 4145 | |
| 4146 | |
| 4147 | |
| 4148 | |
| 4149 | |
| 4150 | #[test] |
| 4151 | fn a_sequence_round_trips_at_the_exactly_half_straddle_size() { |
| 4152 | if !have_ffmpeg() { |
| 4153 | eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg"); |
| 4154 | return; |
| 4155 | } |
| 4156 | let (width, height) = (1280usize, 720usize); |
| 4157 | let pictures: Vec<Picture> = (0..3) |
| 4158 | .map(|i| panned_test_card(width, height, i * 3)) |
| 4159 | .collect(); |
| 4160 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 4161 | assert_eq!(encoded.frames.len(), 3); |
| 4162 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 4163 | assert_eq!( |
| 4164 | (frame.reconstruction.width, frame.reconstruction.height), |
| 4165 | (width, height), |
| 4166 | "frame {i}: reconstruction size" |
| 4167 | ); |
| 4168 | } |
| 4169 | assert_eq!( |
| 4170 | ffprobe_size(&encoded.stream), |
| 4171 | (width as u32, height as u32), |
| 4172 | "ffprobe reports the true (display) 1280x720 size" |
| 4173 | ); |
| 4174 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 4175 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 4176 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 4177 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 4178 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 4179 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 4180 | } |
| 4181 | } |
| 4182 | |
| 4183 | |
| 4184 | |
| 4185 | |
| 4186 | |
| 4187 | |
| 4188 | |
| 4189 | |
| 4190 | |
| 4191 | |
| 4192 | |
| 4193 | |
| 4194 | #[test] |
| 4195 | fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { |
| 4196 | let (width, height) = (640usize, 360usize); |
| 4197 | let picture = Picture::grey(width, height); |
| 4198 | encode_key_frame(&picture, 100, 0.5).expect("key frame now codes the mod-32==8 straddle"); |
| 4199 | |
| 4200 | |
| 4201 | |
| 4202 | let pictures = vec![picture.clone(), picture]; |
| 4203 | encode_sequence(&pictures, 100, 0.5) |
| 4204 | .expect("inter frame now codes the mod-32==8 straddle too"); |
| 4205 | } |
| 4206 | |
| 4207 | |
| 4208 | |
| 4209 | |
| 4210 | |
| 4211 | |
| 4212 | #[test] |
| 4213 | fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() { |
| 4214 | if !have_ffmpeg() { |
| 4215 | eprintln!( |
| 4216 | "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \ |
| 4217 | no ffmpeg" |
| 4218 | ); |
| 4219 | return; |
| 4220 | } |
| 4221 | let (width, height) = (640usize, 360usize); |
| 4222 | for shift in [0i64, 7, 19] { |
| 4223 | let picture = panned_test_card(width, height, shift); |
| 4224 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4225 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 4226 | assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma"); |
| 4227 | assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U"); |
| 4228 | assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V"); |
| 4229 | } |
| 4230 | } |
| 4231 | |
| 4232 | |
| 4233 | |
| 4234 | |
| 4235 | |
| 4236 | #[test] |
| 4237 | fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { |
| 4238 | if !have_ffmpeg() { |
| 4239 | eprintln!( |
| 4240 | "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg" |
| 4241 | ); |
| 4242 | return; |
| 4243 | } |
| 4244 | let (width, height) = (640usize, 360usize); |
| 4245 | let pictures: Vec<Picture> = (0..4) |
| 4246 | .map(|i| panned_test_card(width, height, i * 3)) |
| 4247 | .collect(); |
| 4248 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 4249 | assert_eq!(encoded.frames.len(), 4); |
| 4250 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 4251 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 4252 | } |
| 4253 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); |
| 4254 | assert_eq!(decoded.len(), 4, "decoded frame count"); |
| 4255 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 4256 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 4257 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 4258 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 4259 | } |
| 4260 | } |
| 4261 | |
| 4262 | |
| 4263 | fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { |
| 4264 | let out = Command::new("ffmpeg") |
| 4265 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"]) |
| 4266 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 4267 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 4268 | .output() |
| 4269 | .expect("ffmpeg failed to run"); |
| 4270 | assert!( |
| 4271 | out.status.success(), |
| 4272 | "ffmpeg: {}", |
| 4273 | String::from_utf8_lossy(&out.stderr) |
| 4274 | ); |
| 4275 | let (luma, chroma) = (width * height, width * height / 4); |
| 4276 | assert_eq!( |
| 4277 | out.stdout.len(), |
| 4278 | luma + 2 * chroma, |
| 4279 | "expected one 4:2:0 frame" |
| 4280 | ); |
| 4281 | Picture { |
| 4282 | width, |
| 4283 | height, |
| 4284 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 4285 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 4286 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 4287 | } |
| 4288 | } |
| 4289 | |
| 4290 | |
| 4291 | |
| 4292 | |
| 4293 | #[test] |
| 4294 | #[ignore = "a sweep, not a gate"] |
| 4295 | fn probe_lambda() { |
| 4296 | let mut pictures = vec![ |
| 4297 | ("test card".to_string(), test_card(160, 96)), |
| 4298 | ("stripes".to_string(), stripes(160, 96, true)), |
| 4299 | ]; |
| 4300 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 4301 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 4302 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 4303 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 4304 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 4305 | } |
| 4306 | } |
| 4307 | for (name, picture) in pictures { |
| 4308 | let dc = ladder(&picture, &[DC_PRED]); |
| 4309 | let searched = ladder(&picture, &NON_DIRECTIONAL); |
| 4310 | println!( |
| 4311 | "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point", |
| 4312 | bd_rate(&dc, &searched) * 100.0, |
| 4313 | 10f64.powf(searched[1].1), |
| 4314 | searched[1].0, |
| 4315 | 10f64.powf(dc[1].1), |
| 4316 | dc[1].0, |
| 4317 | ); |
| 4318 | } |
| 4319 | } |
| 4320 | |
| 4321 | |
| 4322 | |
| 4323 | #[test] |
| 4324 | #[ignore = "a sweep, not a gate"] |
| 4325 | fn probe_ladder() { |
| 4326 | for (name, picture) in sweep_pictures() { |
| 4327 | let all = ladder(&picture, &KEY_FRAME_MODES); |
| 4328 | let points = all |
| 4329 | .iter() |
| 4330 | .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes))) |
| 4331 | .collect::<Vec<_>>() |
| 4332 | .join(" "); |
| 4333 | println!("ladder {name}: {points}"); |
| 4334 | } |
| 4335 | } |
| 4336 | |
| 4337 | |
| 4338 | |
| 4339 | |
| 4340 | #[test] |
| 4341 | #[ignore = "a sweep, not a gate"] |
| 4342 | fn probe_split() { |
| 4343 | for (name, picture) in sweep_pictures() { |
| 4344 | let ladder = |split: bool| { |
| 4345 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 4346 | .iter() |
| 4347 | .map(|&q| { |
| 4348 | let encoded = encode_key_frame_inner( |
| 4349 | &picture, |
| 4350 | q, |
| 4351 | 0.5, |
| 4352 | &KEY_FRAME_MODES, |
| 4353 | split, |
| 4354 | (picture.width, picture.height), |
| 4355 | unspecified_color_config(), |
| 4356 | ) |
| 4357 | .unwrap(); |
| 4358 | ( |
| 4359 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 4360 | (encoded.stream.len() as f64).log10(), |
| 4361 | ) |
| 4362 | }) |
| 4363 | .collect(); |
| 4364 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 4365 | points |
| 4366 | }; |
| 4367 | let (whole, split) = (ladder(false), ladder(true)); |
| 4368 | let blocks = encode_key_frame_inner( |
| 4369 | &picture, |
| 4370 | 90, |
| 4371 | 0.5, |
| 4372 | &KEY_FRAME_MODES, |
| 4373 | true, |
| 4374 | (picture.width, picture.height), |
| 4375 | unspecified_color_config(), |
| 4376 | ) |
| 4377 | .unwrap() |
| 4378 | .modes |
| 4379 | .len(); |
| 4380 | let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK); |
| 4381 | println!( |
| 4382 | "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90", |
| 4383 | bd_rate(&whole, &split) * 100.0 |
| 4384 | ); |
| 4385 | } |
| 4386 | } |
| 4387 | |
| 4388 | |
| 4389 | |
| 4390 | |
| 4391 | |
| 4392 | fn stripes(width: usize, height: usize, vertical: bool) -> Picture { |
| 4393 | let mut picture = Picture::grey(width, height); |
| 4394 | for y in 0..height { |
| 4395 | for x in 0..width { |
| 4396 | let along = if vertical { x } else { y }; |
| 4397 | picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 }; |
| 4398 | } |
| 4399 | } |
| 4400 | picture |
| 4401 | } |
| 4402 | |
| 4403 | |
| 4404 | |
| 4405 | |
| 4406 | fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> { |
| 4407 | let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?; |
| 4408 | let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count(); |
| 4409 | Some(format!( |
| 4410 | "{differ} samples differ, first at ({}, {}): ours {} theirs {}", |
| 4411 | i % width, |
| 4412 | i / width, |
| 4413 | ours[i], |
| 4414 | theirs[i] |
| 4415 | )) |
| 4416 | } |
| 4417 | |
| 4418 | |
| 4419 | |
| 4420 | |
| 4421 | #[test] |
| 4422 | fn every_mode_decodes_to_what_the_encoder_predicted() { |
| 4423 | if !have_ffmpeg() { |
| 4424 | eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg"); |
| 4425 | return; |
| 4426 | } |
| 4427 | |
| 4428 | |
| 4429 | |
| 4430 | for (width, height) in [(128, 96), (160, 96)] { |
| 4431 | let picture = test_card(width, height); |
| 4432 | for mode in KEY_FRAME_MODES { |
| 4433 | let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap(); |
| 4434 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 4435 | for (plane, ours, theirs, stride) in [ |
| 4436 | ("luma", &encoded.reconstruction.y, &decoded.y, width), |
| 4437 | ("U", &encoded.reconstruction.u, &decoded.u, width / 2), |
| 4438 | ("V", &encoded.reconstruction.v, &decoded.v, width / 2), |
| 4439 | ] { |
| 4440 | assert!( |
| 4441 | first_difference(ours, theirs, stride).is_none(), |
| 4442 | "{width}x{height} mode {mode}, {plane}: {}", |
| 4443 | first_difference(ours, theirs, stride).unwrap() |
| 4444 | ); |
| 4445 | } |
| 4446 | assert!( |
| 4447 | encoded.modes.iter().all(|&m| m == mode), |
| 4448 | "mode {mode}: the encoder coded something else" |
| 4449 | ); |
| 4450 | } |
| 4451 | } |
| 4452 | } |
| 4453 | |
| 4454 | |
| 4455 | |
| 4456 | |
| 4457 | |
| 4458 | #[test] |
| 4459 | fn the_search_picks_the_direction_the_picture_runs() { |
| 4460 | for (vertical, want) in [(true, V_PRED), (false, H_PRED)] { |
| 4461 | let picture = stripes(128, 96, vertical); |
| 4462 | |
| 4463 | |
| 4464 | |
| 4465 | |
| 4466 | |
| 4467 | let encoded = |
| 4468 | encode_key_frame_with_modes(&picture, 100, 0.5, &[V_PRED, H_PRED]).unwrap(); |
| 4469 | |
| 4470 | |
| 4471 | let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count(); |
| 4472 | assert!( |
| 4473 | picked * 2 > encoded.modes.len() - 1, |
| 4474 | "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}", |
| 4475 | encoded.modes.len() - 1, |
| 4476 | encoded.modes |
| 4477 | ); |
| 4478 | } |
| 4479 | } |
| 4480 | |
| 4481 | |
| 4482 | |
| 4483 | |
| 4484 | |
| 4485 | |
| 4486 | |
| 4487 | fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 { |
| 4488 | let low = reference[0].0.max(other[0].0); |
| 4489 | let high = reference[reference.len() - 1] |
| 4490 | .0 |
| 4491 | .min(other[other.len() - 1].0); |
| 4492 | assert!(high > low, "the two ladders have to overlap in PSNR"); |
| 4493 | let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { |
| 4494 | let i = curve |
| 4495 | .windows(2) |
| 4496 | .position(|w| psnr >= w[0].0 && psnr <= w[1].0) |
| 4497 | .unwrap_or(0); |
| 4498 | let (x0, y0) = curve[i]; |
| 4499 | let (x1, y1) = curve[i + 1]; |
| 4500 | y0 + (y1 - y0) * (psnr - x0) / (x1 - x0) |
| 4501 | }; |
| 4502 | let steps = 64; |
| 4503 | let mut area = 0.0; |
| 4504 | for step in 0..steps { |
| 4505 | let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps); |
| 4506 | area += log_rate_at(other, psnr) - log_rate_at(reference, psnr); |
| 4507 | } |
| 4508 | 10f64.powf(area / f64::from(steps)) - 1.0 |
| 4509 | } |
| 4510 | |
| 4511 | |
| 4512 | |
| 4513 | fn ladder(picture: &Picture, modes: &[u8]) -> Vec<(f64, f64)> { |
| 4514 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 4515 | .iter() |
| 4516 | .map(|&q| { |
| 4517 | let encoded = encode_key_frame_with_modes(picture, q, 0.5, modes).unwrap(); |
| 4518 | ( |
| 4519 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 4520 | (encoded.stream.len() as f64).log10(), |
| 4521 | ) |
| 4522 | }) |
| 4523 | .collect(); |
| 4524 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 4525 | points |
| 4526 | } |
| 4527 | |
| 4528 | |
| 4529 | |
| 4530 | |
| 4531 | |
| 4532 | #[test] |
| 4533 | fn the_search_beats_dc_alone() { |
| 4534 | for (name, picture, want) in [ |
| 4535 | ("test card", test_card(160, 96), -0.05), |
| 4536 | ("stripes", stripes(160, 96, true), -0.40), |
| 4537 | ] { |
| 4538 | let saved = bd_rate( |
| 4539 | &ladder(&picture, &[DC_PRED]), |
| 4540 | &ladder(&picture, &NON_DIRECTIONAL), |
| 4541 | ); |
| 4542 | assert!( |
| 4543 | saved < want, |
| 4544 | "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%", |
| 4545 | saved * 100.0, |
| 4546 | -want * 100.0 |
| 4547 | ); |
| 4548 | } |
| 4549 | } |
| 4550 | |
| 4551 | |
| 4552 | |
| 4553 | fn sweep_pictures() -> Vec<(String, Picture)> { |
| 4554 | let mut pictures = vec![ |
| 4555 | ("test card".to_string(), test_card(160, 96)), |
| 4556 | ("stripes".to_string(), stripes(160, 96, true)), |
| 4557 | ("diagonal".to_string(), diagonal(160, 96, true)), |
| 4558 | ]; |
| 4559 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 4560 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 4561 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 4562 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 4563 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 4564 | } |
| 4565 | } |
| 4566 | pictures |
| 4567 | } |
| 4568 | |
| 4569 | |
| 4570 | |
| 4571 | |
| 4572 | #[test] |
| 4573 | #[ignore = "a sweep, not a gate"] |
| 4574 | fn probe_directional() { |
| 4575 | for (name, picture) in sweep_pictures() { |
| 4576 | let dc = ladder(&picture, &[DC_PRED]); |
| 4577 | let flat = ladder(&picture, &NON_DIRECTIONAL); |
| 4578 | let all = ladder(&picture, &KEY_FRAME_MODES); |
| 4579 | let encoded = encode_key_frame(&picture, 90, 0.5).unwrap(); |
| 4580 | let directional = encoded |
| 4581 | .modes |
| 4582 | .iter() |
| 4583 | .filter(|&&m| (3..=8).contains(&m)) |
| 4584 | .count(); |
| 4585 | |
| 4586 | |
| 4587 | let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 4588 | a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0) |
| 4589 | }; |
| 4590 | let against = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 4591 | if overlap(a, b) { |
| 4592 | format!("{:+.2}%", bd_rate(a, b) * 100.0) |
| 4593 | } else { |
| 4594 | "no overlap".to_string() |
| 4595 | } |
| 4596 | }; |
| 4597 | println!( |
| 4598 | "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional", |
| 4599 | against(&flat, &all), |
| 4600 | against(&dc, &all), |
| 4601 | encoded.modes.len(), |
| 4602 | ); |
| 4603 | } |
| 4604 | } |
| 4605 | |
| 4606 | |
| 4607 | |
| 4608 | |
| 4609 | |
| 4610 | fn diagonal(width: usize, height: usize, down_right: bool) -> Picture { |
| 4611 | let mut picture = Picture::grey(width, height); |
| 4612 | for y in 0..height { |
| 4613 | for x in 0..width { |
| 4614 | let along = if down_right { x + height - y } else { x + y }; |
| 4615 | picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 }; |
| 4616 | } |
| 4617 | } |
| 4618 | picture |
| 4619 | } |
| 4620 | |
| 4621 | |
| 4622 | |
| 4623 | fn favourite_mode(picture: &Picture) -> (u8, usize, usize) { |
| 4624 | let encoded = encode_key_frame(picture, 100, 0.5).unwrap(); |
| 4625 | let blocks = &encoded.modes[1..]; |
| 4626 | let mut counts = [0usize; 13]; |
| 4627 | for &mode in blocks { |
| 4628 | counts[usize::from(mode)] += 1; |
| 4629 | } |
| 4630 | let (mode, count) = counts |
| 4631 | .iter() |
| 4632 | .enumerate() |
| 4633 | .max_by_key(|&(_, count)| *count) |
| 4634 | .expect("thirteen modes"); |
| 4635 | (mode as u8, *count, blocks.len()) |
| 4636 | } |
| 4637 | |
| 4638 | |
| 4639 | |
| 4640 | |
| 4641 | |
| 4642 | #[test] |
| 4643 | fn the_search_picks_the_diagonal_the_picture_runs() { |
| 4644 | for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] { |
| 4645 | let picture = diagonal(160, 96, down_right); |
| 4646 | let (mode, count, blocks) = favourite_mode(&picture); |
| 4647 | assert_eq!( |
| 4648 | mode, want, |
| 4649 | "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}" |
| 4650 | ); |
| 4651 | } |
| 4652 | } |
| 4653 | |
| 4654 | |
| 4655 | |
| 4656 | |
| 4657 | |
| 4658 | |
| 4659 | |
| 4660 | #[test] |
| 4661 | fn the_diagonals_beat_the_modes_that_read_no_further() { |
| 4662 | for (name, picture, want) in [ |
| 4663 | ("down-right", diagonal(160, 96, true), -0.20), |
| 4664 | ("down-left", diagonal(160, 96, false), -0.20), |
| 4665 | ("test card", test_card(160, 96), 0.01), |
| 4666 | ] { |
| 4667 | let saved = bd_rate( |
| 4668 | &ladder(&picture, &NON_DIRECTIONAL), |
| 4669 | &ladder(&picture, &KEY_FRAME_MODES), |
| 4670 | ); |
| 4671 | assert!( |
| 4672 | saved < want, |
| 4673 | "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%", |
| 4674 | saved * 100.0, |
| 4675 | -want * 100.0 |
| 4676 | ); |
| 4677 | } |
| 4678 | } |
| 4679 | |
| 4680 | |
| 4681 | |
| 4682 | #[test] |
| 4683 | fn a_mode_the_encoder_cannot_predict_is_refused() { |
| 4684 | let picture = test_card(64, 64); |
| 4685 | let message = encode_key_frame_with_modes(&picture, 100, 0.5, &[13]) |
| 4686 | .unwrap_err() |
| 4687 | .to_string(); |
| 4688 | assert!( |
| 4689 | message.contains("intra mode 13"), |
| 4690 | "the refusal must name the mode, got {message}" |
| 4691 | ); |
| 4692 | assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[]).is_err()); |
| 4693 | } |
| 4694 | |
| 4695 | |
| 4696 | |
| 4697 | |
| 4698 | |
| 4699 | |
| 4700 | #[test] |
| 4701 | fn the_encoded_picture_is_the_one_that_went_in() { |
| 4702 | let picture = test_card(160, 96); |
| 4703 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4704 | let luma = psnr(&encoded.reconstruction.y, &picture.y); |
| 4705 | assert!(luma > 36.0, "luma PSNR {luma} at q 100"); |
| 4706 | for (plane, (got, want)) in [ |
| 4707 | (encoded.reconstruction.u.as_slice(), picture.u.as_slice()), |
| 4708 | (encoded.reconstruction.v.as_slice(), picture.v.as_slice()), |
| 4709 | ] |
| 4710 | .iter() |
| 4711 | .enumerate() |
| 4712 | { |
| 4713 | let chroma = psnr(got, want); |
| 4714 | assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100"); |
| 4715 | } |
| 4716 | } |
| 4717 | |
| 4718 | |
| 4719 | |
| 4720 | |
| 4721 | #[test] |
| 4722 | fn fidelity_and_rate_move_with_the_quantizer() { |
| 4723 | let picture = test_card(128, 128); |
| 4724 | let mut previous: Option<(usize, f64)> = None; |
| 4725 | for &q in &[70u8, 90, 110] { |
| 4726 | let encoded = encode_key_frame(&picture, q, 0.5).unwrap(); |
| 4727 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 4728 | if let Some((bytes, better)) = previous { |
| 4729 | assert!( |
| 4730 | encoded.stream.len() < bytes, |
| 4731 | "q {q}: {} bytes", |
| 4732 | encoded.stream.len() |
| 4733 | ); |
| 4734 | assert!(quality < better, "q {q}: PSNR {quality}"); |
| 4735 | } |
| 4736 | previous = Some((encoded.stream.len(), quality)); |
| 4737 | } |
| 4738 | |
| 4739 | let mut previous = None; |
| 4740 | for &deadzone in &[0.5f64, 0.3, 0.15] { |
| 4741 | let encoded = encode_key_frame(&picture, 100, deadzone).unwrap(); |
| 4742 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 4743 | if let Some((bytes, better)) = previous { |
| 4744 | assert!( |
| 4745 | encoded.stream.len() < bytes, |
| 4746 | "deadzone {deadzone}: {} bytes", |
| 4747 | encoded.stream.len() |
| 4748 | ); |
| 4749 | assert!(quality < better, "deadzone {deadzone}: PSNR {quality}"); |
| 4750 | } |
| 4751 | previous = Some((encoded.stream.len(), quality)); |
| 4752 | } |
| 4753 | |
| 4754 | |
| 4755 | |
| 4756 | |
| 4757 | |
| 4758 | for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { |
| 4759 | let lo_bytes = encode_key_frame(&picture, lo, 0.5).unwrap().stream.len(); |
| 4760 | let hi_bytes = encode_key_frame(&picture, hi, 0.5).unwrap().stream.len(); |
| 4761 | assert!( |
| 4762 | hi_bytes <= lo_bytes, |
| 4763 | "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" |
| 4764 | ); |
| 4765 | } |
| 4766 | } |
| 4767 | |
| 4768 | |
| 4769 | |
| 4770 | #[test] |
| 4771 | fn a_flat_picture_costs_almost_nothing() { |
| 4772 | let mut picture = Picture::grey(128, 128); |
| 4773 | picture.y.fill(97); |
| 4774 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4775 | |
| 4776 | |
| 4777 | assert!( |
| 4778 | encoded.stream.len() < 100, |
| 4779 | "{} bytes for a flat picture", |
| 4780 | encoded.stream.len() |
| 4781 | ); |
| 4782 | for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) { |
| 4783 | assert_eq!(s, 97, "sample {i} of a flat picture"); |
| 4784 | } |
| 4785 | } |
| 4786 | |
| 4787 | |
| 4788 | |
| 4789 | |
| 4790 | |
| 4791 | |
| 4792 | |
| 4793 | |
| 4794 | |
| 4795 | |
| 4796 | |
| 4797 | |
| 4798 | |
| 4799 | #[test] |
| 4800 | fn a_picture_off_the_block_grid_is_refused() { |
| 4801 | let msg = encode_key_frame(&Picture::grey(40, 40), 100, 0.5) |
| 4802 | .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform") |
| 4803 | .to_string(); |
| 4804 | assert!(msg.contains("rectangular"), "refusal: {msg}"); |
| 4805 | |
| 4806 | let mut short = Picture::grey(64, 64); |
| 4807 | short.u.truncate(10); |
| 4808 | assert!(encode_key_frame(&short, 100, 0.5).is_err()); |
| 4809 | } |
| 4810 | |
| 4811 | |
| 4812 | |
| 4813 | |
| 4814 | |
| 4815 | |
| 4816 | |
| 4817 | |
| 4818 | |
| 4819 | |
| 4820 | |
| 4821 | |
| 4822 | |
| 4823 | |
| 4824 | |
| 4825 | |
| 4826 | |
| 4827 | |
| 4828 | |
| 4829 | |
| 4830 | |
| 4831 | |
| 4832 | |
| 4833 | |
| 4834 | |
| 4835 | |
| 4836 | |
| 4837 | |
| 4838 | |
| 4839 | |
| 4840 | |
| 4841 | |
| 4842 | |
| 4843 | |
| 4844 | |
| 4845 | |
| 4846 | |
| 4847 | |
| 4848 | |
| 4849 | |
| 4850 | |
| 4851 | |
| 4852 | |
| 4853 | |
| 4854 | |
| 4855 | |
| 4856 | |
| 4857 | |
| 4858 | |
| 4859 | |
| 4860 | |
| 4861 | |
| 4862 | |
| 4863 | |
| 4864 | |
| 4865 | |
| 4866 | |
| 4867 | |
| 4868 | |
| 4869 | |
| 4870 | |
| 4871 | |
| 4872 | |
| 4873 | |
| 4874 | |
| 4875 | |
| 4876 | |
| 4877 | |
| 4878 | |
| 4879 | |
| 4880 | |
| 4881 | #[test] |
| 4882 | fn a_single_axis_straddle_round_trips_through_ffmpeg() { |
| 4883 | if !have_ffmpeg() { |
| 4884 | eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg"); |
| 4885 | return; |
| 4886 | } |
| 4887 | let (width, height) = (40usize, 32usize); |
| 4888 | let picture = test_card(width, height); |
| 4889 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4890 | assert_eq!( |
| 4891 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 4892 | (width, height) |
| 4893 | ); |
| 4894 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 4895 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 4896 | } |
| 4897 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 4898 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 4899 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 4900 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 4901 | } |
| 4902 | |
| 4903 | |
| 4904 | |
| 4905 | |
| 4906 | |
| 4907 | |
| 4908 | |
| 4909 | #[test] |
| 4910 | fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() { |
| 4911 | let Ok(clip) = std::env::var("EC_AV1_CLIP") else { |
| 4912 | eprintln!( |
| 4913 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \ |
| 4914 | set EC_AV1_CLIP to a clip" |
| 4915 | ); |
| 4916 | return; |
| 4917 | }; |
| 4918 | if !have_ffmpeg() { |
| 4919 | eprintln!( |
| 4920 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 4921 | ); |
| 4922 | return; |
| 4923 | } |
| 4924 | let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into()); |
| 4925 | |
| 4926 | |
| 4927 | let (width, height) = (640usize, 352usize); |
| 4928 | let picture = clip_frame(&clip, &skip, width, height); |
| 4929 | |
| 4930 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4931 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 4932 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 4933 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 4934 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 4935 | eprintln!( |
| 4936 | "{} bytes, luma PSNR {:.2} dB", |
| 4937 | encoded.stream.len(), |
| 4938 | psnr(&decoded.y, &picture.y) |
| 4939 | ); |
| 4940 | } |
| 4941 | |
| 4942 | |
| 4943 | |
| 4944 | |
| 4945 | |
| 4946 | |
| 4947 | fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture { |
| 4948 | let mut picture = Picture::grey(width, height); |
| 4949 | for y in 0..height { |
| 4950 | for x in 0..width { |
| 4951 | let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; |
| 4952 | let gradient = sx * 200.0 / width as f64; |
| 4953 | let ripple = 30.0 |
| 4954 | * (sx * std::f64::consts::PI / 23.0).sin() |
| 4955 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 4956 | let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 { |
| 4957 | 40.0 |
| 4958 | } else { |
| 4959 | 0.0 |
| 4960 | }; |
| 4961 | picture.y[y * width + x] = |
| 4962 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 4963 | } |
| 4964 | } |
| 4965 | for y in 0..height / 2 { |
| 4966 | for x in 0..width / 2 { |
| 4967 | let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; |
| 4968 | let i = y * width / 2 + x; |
| 4969 | picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; |
| 4970 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 4971 | } |
| 4972 | } |
| 4973 | picture |
| 4974 | } |
| 4975 | |
| 4976 | |
| 4977 | fn ffmpeg_decode_sequence( |
| 4978 | stream: &[u8], |
| 4979 | width: usize, |
| 4980 | height: usize, |
| 4981 | frames: usize, |
| 4982 | ) -> Vec<Picture> { |
| 4983 | let mut child = Command::new("ffmpeg") |
| 4984 | .args([ |
| 4985 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 4986 | ]) |
| 4987 | .stdin(Stdio::piped()) |
| 4988 | .stdout(Stdio::piped()) |
| 4989 | .stderr(Stdio::piped()) |
| 4990 | .spawn() |
| 4991 | .expect("ffmpeg failed to start"); |
| 4992 | child |
| 4993 | .stdin |
| 4994 | .take() |
| 4995 | .expect("ffmpeg stdin") |
| 4996 | .write_all(stream) |
| 4997 | .expect("writing the stream to ffmpeg"); |
| 4998 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 4999 | assert!( |
| 5000 | out.status.success(), |
| 5001 | "ffmpeg refused the stream: {}", |
| 5002 | String::from_utf8_lossy(&out.stderr) |
| 5003 | ); |
| 5004 | let (luma, chroma) = (width * height, width * height / 4); |
| 5005 | let frame_bytes = luma + 2 * chroma; |
| 5006 | assert_eq!( |
| 5007 | out.stdout.len(), |
| 5008 | frame_bytes * frames, |
| 5009 | "expected {frames} 4:2:0 frames, ffmpeg said: {}", |
| 5010 | String::from_utf8_lossy(&out.stderr) |
| 5011 | ); |
| 5012 | (0..frames) |
| 5013 | .map(|i| { |
| 5014 | let base = i * frame_bytes; |
| 5015 | Picture { |
| 5016 | width, |
| 5017 | height, |
| 5018 | y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(), |
| 5019 | u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 5020 | v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(), |
| 5021 | } |
| 5022 | }) |
| 5023 | .collect() |
| 5024 | } |
| 5025 | |
| 5026 | |
| 5027 | |
| 5028 | |
| 5029 | |
| 5030 | |
| 5031 | |
| 5032 | #[test] |
| 5033 | fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() { |
| 5034 | if !have_ffmpeg() { |
| 5035 | eprintln!( |
| 5036 | "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 5037 | ); |
| 5038 | return; |
| 5039 | } |
| 5040 | let (width, height) = (128usize, 64usize); |
| 5041 | let pictures: Vec<Picture> = (0..5) |
| 5042 | .map(|i| panned_test_card(width, height, i * 3)) |
| 5043 | .collect(); |
| 5044 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 5045 | assert_eq!(encoded.frames.len(), 5); |
| 5046 | |
| 5047 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5); |
| 5048 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 5049 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma"); |
| 5050 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U"); |
| 5051 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V"); |
| 5052 | } |
| 5053 | |
| 5054 | eprintln!("frame bytes luma PSNR (dB) inter share"); |
| 5055 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 5056 | eprintln!( |
| 5057 | "{i:5} {:5} {:14.2} {:11.2}", |
| 5058 | frame.stream.len(), |
| 5059 | psnr(&frame.reconstruction.y, &pictures[i].y), |
| 5060 | frame.inter_block_share |
| 5061 | ); |
| 5062 | } |
| 5063 | } |
| 5064 | |
| 5065 | |
| 5066 | |
| 5067 | |
| 5068 | |
| 5069 | |
| 5070 | |
| 5071 | |
| 5072 | #[test] |
| 5073 | fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() { |
| 5074 | let (width, height) = (256usize, 128usize); |
| 5075 | let pictures: Vec<Picture> = (0..5) |
| 5076 | .map(|i| panned_test_card(width, height, i * 2)) |
| 5077 | .collect(); |
| 5078 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 5079 | |
| 5080 | let key_bytes = encoded.frames[0].stream.len(); |
| 5081 | eprintln!("frame bytes inter share"); |
| 5082 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 5083 | eprintln!( |
| 5084 | "{i:5} {:5} {:11.2}", |
| 5085 | frame.stream.len(), |
| 5086 | frame.inter_block_share |
| 5087 | ); |
| 5088 | } |
| 5089 | assert!( |
| 5090 | encoded.frames[1..] |
| 5091 | .iter() |
| 5092 | .any(|f| f.stream.len() < key_bytes), |
| 5093 | "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes" |
| 5094 | ); |
| 5095 | assert!( |
| 5096 | encoded.frames[1..] |
| 5097 | .iter() |
| 5098 | .any(|f| f.inter_block_share > 0.0), |
| 5099 | "no inter frame coded a single inter block -- the search never fired" |
| 5100 | ); |
| 5101 | } |
| 5102 | |
| 5103 | |
| 5104 | |
| 5105 | |
| 5106 | |
| 5107 | #[test] |
| 5108 | #[ignore = "a perf probe, not a gate"] |
| 5109 | fn stage_timing_breakdown() { |
| 5110 | use std::time::Instant; |
| 5111 | |
| 5112 | for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] { |
| 5113 | let picture = test_card(width, height); |
| 5114 | |
| 5115 | let t = Instant::now(); |
| 5116 | let dc_only = encode_key_frame_with_modes(&picture, 100, 0.5, &[DC_PRED]).unwrap(); |
| 5117 | let dc_only_t = t.elapsed(); |
| 5118 | |
| 5119 | let t = Instant::now(); |
| 5120 | let non_directional = |
| 5121 | encode_key_frame_with_modes(&picture, 100, 0.5, &NON_DIRECTIONAL).unwrap(); |
| 5122 | let non_directional_t = t.elapsed(); |
| 5123 | |
| 5124 | let t = Instant::now(); |
| 5125 | let all_modes = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 5126 | let all_modes_t = t.elapsed(); |
| 5127 | |
| 5128 | eprintln!( |
| 5129 | "\n=== key frame {width}x{height} ===\n\ |
| 5130 | 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\ |
| 5131 | 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\ |
| 5132 | 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)", |
| 5133 | dc_only.stream.len(), |
| 5134 | non_directional.stream.len(), |
| 5135 | all_modes.stream.len(), |
| 5136 | ); |
| 5137 | |
| 5138 | |
| 5139 | |
| 5140 | |
| 5141 | let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK); |
| 5142 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 5143 | let t = Instant::now(); |
| 5144 | let inter = |
| 5145 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap(); |
| 5146 | let inter_t = t.elapsed(); |
| 5147 | eprintln!( |
| 5148 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| 5149 | {:.2})", |
| 5150 | inter.stream.len(), |
| 5151 | inter.inter_block_share |
| 5152 | ); |
| 5153 | } |
| 5154 | |
| 5155 | |
| 5156 | |
| 5157 | |
| 5158 | for side in [16usize, 32] { |
| 5159 | const N: u32 = 20_000; |
| 5160 | let residual: Vec<i32> = (0..side * side) |
| 5161 | .map(|i| ((i * 37 % 61) as i32) - 30) |
| 5162 | .collect(); |
| 5163 | |
| 5164 | let t = Instant::now(); |
| 5165 | let mut levels = Vec::new(); |
| 5166 | for _ in 0..N { |
| 5167 | levels = forward_and_quantize(&residual, side, 8, 100, 0.5); |
| 5168 | } |
| 5169 | let forward_t = t.elapsed() / N; |
| 5170 | |
| 5171 | let t = Instant::now(); |
| 5172 | for _ in 0..N { |
| 5173 | std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100)); |
| 5174 | } |
| 5175 | let inverse_t = t.elapsed() / N; |
| 5176 | |
| 5177 | let set = if side == 32 { |
| 5178 | crate::cdf_state::TxbSet::Luma32 |
| 5179 | } else { |
| 5180 | crate::cdf_state::TxbSet::Luma16 |
| 5181 | }; |
| 5182 | let t = Instant::now(); |
| 5183 | for _ in 0..N { |
| 5184 | std::hint::black_box(crate::tile::coeff_bits(&levels, set)); |
| 5185 | } |
| 5186 | let entropy_t = t.elapsed() / N; |
| 5187 | |
| 5188 | let above = vec![128u8; side * 2]; |
| 5189 | let left = vec![128u8; side * 2]; |
| 5190 | let mut prediction = vec![0u8; side * side]; |
| 5191 | let t = Instant::now(); |
| 5192 | for _ in 0..N { |
| 5193 | intra_predict_u8( |
| 5194 | D45_PRED, |
| 5195 | 0, |
| 5196 | Some(&above), |
| 5197 | Some(&left), |
| 5198 | Some(128), |
| 5199 | side, |
| 5200 | side, |
| 5201 | false, |
| 5202 | false, |
| 5203 | &mut prediction, |
| 5204 | ); |
| 5205 | } |
| 5206 | let predict_t = t.elapsed() / N; |
| 5207 | |
| 5208 | eprintln!( |
| 5209 | "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ |
| 5210 | predict (1 directional mode): {predict_t:>9.2?}\n\ |
| 5211 | forward_and_quantize: {forward_t:>9.2?}\n\ |
| 5212 | dequant_and_inverse: {inverse_t:>9.2?}\n\ |
| 5213 | coeff_bits: {entropy_t:>9.2?}" |
| 5214 | ); |
| 5215 | } |
| 5216 | } |
| 5217 | |
| 5218 | |
| 5219 | |
| 5220 | |
| 5221 | |
| 5222 | |
| 5223 | |
| 5224 | |
| 5225 | |
| 5226 | |
| 5227 | |
| 5228 | #[test] |
| 5229 | #[ignore = "a perf probe, not a gate"] |
| 5230 | fn stage_timing_breakdown_inter() { |
| 5231 | use std::time::Instant; |
| 5232 | |
| 5233 | let (width, height) = (1280usize, 720); |
| 5234 | let picture = test_card(width, height); |
| 5235 | let key = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 5236 | let padded_ref = key.reconstruction.padded_to(SUPERBLOCK); |
| 5237 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 5238 | |
| 5239 | stage_reset(); |
| 5240 | let t = Instant::now(); |
| 5241 | let inter = |
| 5242 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap(); |
| 5243 | let total_t = t.elapsed(); |
| 5244 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 5245 | let accounted = motion_search + transform_quant + entropy; |
| 5246 | |
| 5247 | |
| 5248 | |
| 5249 | |
| 5250 | let other = total_t.saturating_sub(accounted); |
| 5251 | |
| 5252 | eprintln!( |
| 5253 | "\n=== inter frame {width}x{height}, one frame ===\n\ |
| 5254 | total: {total_t:>9.2?} ({} bytes)\n\ |
| 5255 | motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \ |
| 5256 | {interpolation:>9.2?})\n\ |
| 5257 | transform + quantize: {transform_quant:>9.2?}\n\ |
| 5258 | coeff_bits (entropy pricing): {entropy:>9.2?}\n\ |
| 5259 | everything else (13-mode intra {other:>9.2?}\n\ |
| 5260 | candidate loop's own predict/bookkeeping, NEARESTMV's own \ |
| 5261 | predict, RD glue):", |
| 5262 | inter.stream.len(), |
| 5263 | ); |
| 5264 | } |
| 5265 | |
| 5266 | |
| 5267 | |
| 5268 | |
| 5269 | |
| 5270 | |
| 5271 | |
| 5272 | |
| 5273 | |
| 5274 | |
| 5275 | #[test] |
| 5276 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 5277 | fn prune_k_quality_sweep() { |
| 5278 | if !have_ffmpeg() { |
| 5279 | eprintln!("SKIP prune_k_quality_sweep: no ffmpeg"); |
| 5280 | return; |
| 5281 | } |
| 5282 | let (width, height) = (640usize, 352usize); |
| 5283 | let frames: &[(&str, &str, &str)] = &[ |
| 5284 | |
| 5285 | |
| 5286 | ( |
| 5287 | "dark/flat", |
| 5288 | "/home/user/Videos/reela.mp4", |
| 5289 | "3", |
| 5290 | ), |
| 5291 | ( |
| 5292 | "detailed", |
| 5293 | "/home/user/Downloads/reelb.mkv", |
| 5294 | "1200", |
| 5295 | ), |
| 5296 | ( |
| 5297 | "film", |
| 5298 | "/home/user/Videos/Films/reelc.mkv", |
| 5299 | "600", |
| 5300 | ), |
| 5301 | ]; |
| 5302 | for &(label, clip, skip) in frames { |
| 5303 | if !std::path::Path::new(clip).exists() { |
| 5304 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 5305 | continue; |
| 5306 | } |
| 5307 | let picture = clip_frame(clip, skip, width, height); |
| 5308 | for &q in &[60u8, 150] { |
| 5309 | |
| 5310 | |
| 5311 | |
| 5312 | set_test_top_k_override(None); |
| 5313 | let baseline = encode_key_frame(&picture, q, 0.5).unwrap(); |
| 5314 | let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y); |
| 5315 | eprint!( |
| 5316 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 5317 | baseline.stream.len(), |
| 5318 | baseline_psnr |
| 5319 | ); |
| 5320 | for &k in &[3usize, 4, 6] { |
| 5321 | set_test_top_k_override(Some(k)); |
| 5322 | let pruned = encode_key_frame(&picture, q, 0.5).unwrap(); |
| 5323 | let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y); |
| 5324 | eprint!( |
| 5325 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 5326 | pruned.stream.len(), |
| 5327 | pruned_psnr, |
| 5328 | pruned_psnr - baseline_psnr |
| 5329 | ); |
| 5330 | } |
| 5331 | eprintln!(); |
| 5332 | } |
| 5333 | } |
| 5334 | set_test_top_k_override(None); |
| 5335 | } |
| 5336 | |
| 5337 | |
| 5338 | |
| 5339 | fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] { |
| 5340 | let out = Command::new("ffmpeg") |
| 5341 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"]) |
| 5342 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 5343 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 5344 | .output() |
| 5345 | .expect("ffmpeg failed to run"); |
| 5346 | assert!( |
| 5347 | out.status.success(), |
| 5348 | "ffmpeg: {}", |
| 5349 | String::from_utf8_lossy(&out.stderr) |
| 5350 | ); |
| 5351 | let (luma, chroma) = (width * height, width * height / 4); |
| 5352 | let frame_len = luma + 2 * chroma; |
| 5353 | assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames"); |
| 5354 | std::array::from_fn(|i| { |
| 5355 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 5356 | Picture { |
| 5357 | width, |
| 5358 | height, |
| 5359 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 5360 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 5361 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 5362 | } |
| 5363 | }) |
| 5364 | } |
| 5365 | |
| 5366 | |
| 5367 | |
| 5368 | |
| 5369 | |
| 5370 | |
| 5371 | |
| 5372 | |
| 5373 | |
| 5374 | #[test] |
| 5375 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 5376 | fn prune_k_quality_sweep_inter() { |
| 5377 | if !have_ffmpeg() { |
| 5378 | eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg"); |
| 5379 | return; |
| 5380 | } |
| 5381 | let (width, height) = (1280usize, 704usize); |
| 5382 | let frames: &[(&str, &str, &str)] = &[ |
| 5383 | ( |
| 5384 | "dark/flat", |
| 5385 | "/home/user/Videos/reela.mp4", |
| 5386 | "3", |
| 5387 | ), |
| 5388 | ( |
| 5389 | "detailed", |
| 5390 | "/home/user/Downloads/reelb.mkv", |
| 5391 | "1200", |
| 5392 | ), |
| 5393 | ( |
| 5394 | "film", |
| 5395 | "/home/user/Videos/Films/reelc.mkv", |
| 5396 | "600", |
| 5397 | ), |
| 5398 | ]; |
| 5399 | for &(label, clip, skip) in frames { |
| 5400 | if !std::path::Path::new(clip).exists() { |
| 5401 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 5402 | continue; |
| 5403 | } |
| 5404 | let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height); |
| 5405 | for &q in &[60u8, 150] { |
| 5406 | |
| 5407 | |
| 5408 | |
| 5409 | set_test_top_k_override_inter(None); |
| 5410 | let key = encode_key_frame(&key_source, q, 0.5).unwrap(); |
| 5411 | let baseline = encode_inter_frame( |
| 5412 | &inter_source, |
| 5413 | &key.reconstruction, |
| 5414 | q, |
| 5415 | 0.5, |
| 5416 | 1, |
| 5417 | (width, height), |
| 5418 | ) |
| 5419 | .unwrap(); |
| 5420 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| 5421 | eprint!( |
| 5422 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 5423 | baseline.stream.len(), |
| 5424 | baseline_psnr |
| 5425 | ); |
| 5426 | for &k in &[3usize, 4, 6] { |
| 5427 | set_test_top_k_override_inter(Some(k)); |
| 5428 | let pruned = encode_inter_frame( |
| 5429 | &inter_source, |
| 5430 | &key.reconstruction, |
| 5431 | q, |
| 5432 | 0.5, |
| 5433 | 1, |
| 5434 | (width, height), |
| 5435 | ) |
| 5436 | .unwrap(); |
| 5437 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
| 5438 | eprint!( |
| 5439 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 5440 | pruned.stream.len(), |
| 5441 | pruned_psnr, |
| 5442 | pruned_psnr - baseline_psnr |
| 5443 | ); |
| 5444 | } |
| 5445 | eprintln!(); |
| 5446 | } |
| 5447 | } |
| 5448 | set_test_top_k_override_inter(None); |
| 5449 | } |
| 5450 | |
| 5451 | |
| 5452 | |
| 5453 | |
| 5454 | fn clip_frames( |
| 5455 | clip: &str, |
| 5456 | skip: &str, |
| 5457 | width: usize, |
| 5458 | height: usize, |
| 5459 | frames: usize, |
| 5460 | ) -> Vec<Picture> { |
| 5461 | let out = Command::new("ffmpeg") |
| 5462 | .args(["-v", "error", "-ss", skip, "-i", clip]) |
| 5463 | .args(["-frames:v", &frames.to_string()]) |
| 5464 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 5465 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 5466 | .output() |
| 5467 | .expect("ffmpeg failed to run"); |
| 5468 | assert!( |
| 5469 | out.status.success(), |
| 5470 | "ffmpeg: {}", |
| 5471 | String::from_utf8_lossy(&out.stderr) |
| 5472 | ); |
| 5473 | let (luma, chroma) = (width * height, width * height / 4); |
| 5474 | let frame_len = luma + 2 * chroma; |
| 5475 | assert_eq!( |
| 5476 | out.stdout.len(), |
| 5477 | frame_len * frames, |
| 5478 | "expected {frames} 4:2:0 frames" |
| 5479 | ); |
| 5480 | (0..frames) |
| 5481 | .map(|i| { |
| 5482 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 5483 | Picture { |
| 5484 | width, |
| 5485 | height, |
| 5486 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 5487 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 5488 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 5489 | } |
| 5490 | }) |
| 5491 | .collect() |
| 5492 | } |
| 5493 | |
| 5494 | |
| 5495 | |
| 5496 | |
| 5497 | |
| 5498 | |
| 5499 | |
| 5500 | |
| 5501 | |
| 5502 | |
| 5503 | |
| 5504 | |
| 5505 | |
| 5506 | |
| 5507 | |
| 5508 | |
| 5509 | |
| 5510 | |
| 5511 | |
| 5512 | #[test] |
| 5513 | fn real_clip_encodes_within_its_quality_and_size_budget() { |
| 5514 | if !have_ffmpeg() { |
| 5515 | eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg"); |
| 5516 | return; |
| 5517 | } |
| 5518 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 5519 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 5520 | if !clip.exists() { |
| 5521 | eprintln!( |
| 5522 | "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing", |
| 5523 | clip.display() |
| 5524 | ); |
| 5525 | return; |
| 5526 | } |
| 5527 | let (width, height, frame_count) = (640usize, 384usize, 12usize); |
| 5528 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 5529 | let encoded = encode_sequence(&source, 100, 0.5).unwrap(); |
| 5530 | assert_eq!(encoded.frames.len(), frame_count); |
| 5531 | |
| 5532 | |
| 5533 | |
| 5534 | |
| 5535 | |
| 5536 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 5537 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 5538 | |
| 5539 | |
| 5540 | let mean_psnr: f64 = decoded |
| 5541 | .iter() |
| 5542 | .zip(&source) |
| 5543 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 5544 | .sum::<f64>() |
| 5545 | / frame_count as f64; |
| 5546 | assert!( |
| 5547 | mean_psnr >= 44.91, |
| 5548 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor" |
| 5549 | ); |
| 5550 | |
| 5551 | |
| 5552 | assert!( |
| 5553 | encoded.stream.len() <= 80_340, |
| 5554 | "stream grew to {} bytes, over the 80340-byte ceiling", |
| 5555 | encoded.stream.len() |
| 5556 | ); |
| 5557 | } |
| 5558 | |
| 5559 | |
| 5560 | |
| 5561 | |
| 5562 | |
| 5563 | |
| 5564 | |
| 5565 | |
| 5566 | |
| 5567 | |
| 5568 | |
| 5569 | |
| 5570 | |
| 5571 | |
| 5572 | #[test] |
| 5573 | fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() { |
| 5574 | if !have_ffmpeg() { |
| 5575 | eprintln!( |
| 5576 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 5577 | no ffmpeg" |
| 5578 | ); |
| 5579 | return; |
| 5580 | } |
| 5581 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 5582 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 5583 | if !clip.exists() { |
| 5584 | eprintln!( |
| 5585 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 5586 | {} missing", |
| 5587 | clip.display() |
| 5588 | ); |
| 5589 | return; |
| 5590 | } |
| 5591 | let (width, height, frame_count) = (704usize, 400usize, 8usize); |
| 5592 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 5593 | let encoded = encode_sequence(&source, 100, 0.5).unwrap(); |
| 5594 | assert_eq!(encoded.frames.len(), frame_count); |
| 5595 | |
| 5596 | |
| 5597 | |
| 5598 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 5599 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 5600 | |
| 5601 | |
| 5602 | let mean_psnr: f64 = decoded |
| 5603 | .iter() |
| 5604 | .zip(&source) |
| 5605 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 5606 | .sum::<f64>() |
| 5607 | / frame_count as f64; |
| 5608 | assert!( |
| 5609 | mean_psnr >= 44.98, |
| 5610 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor" |
| 5611 | ); |
| 5612 | |
| 5613 | |
| 5614 | assert!( |
| 5615 | encoded.stream.len() <= 62_703, |
| 5616 | "stream grew to {} bytes, over the 62703-byte ceiling", |
| 5617 | encoded.stream.len() |
| 5618 | ); |
| 5619 | } |
| 5620 | |
| 5621 | |
| 5622 | |
| 5623 | |
| 5624 | |
| 5625 | |
| 5626 | |
| 5627 | #[test] |
| 5628 | #[ignore = "a perf probe, not a gate"] |
| 5629 | fn sequence_bench_sanity() { |
| 5630 | use std::time::Instant; |
| 5631 | let (width, height) = (1280usize, 720usize); |
| 5632 | let pictures: Vec<Picture> = (0..24) |
| 5633 | .map(|i| panned_test_card(width, height, i * 3)) |
| 5634 | .collect(); |
| 5635 | let t = Instant::now(); |
| 5636 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 5637 | let elapsed = t.elapsed(); |
| 5638 | let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum(); |
| 5639 | eprintln!( |
| 5640 | "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes", |
| 5641 | elapsed / 24 |
| 5642 | ); |
| 5643 | } |
| 5644 | |
| 5645 | |
| 5646 | |
| 5647 | |
| 5648 | |
| 5649 | #[test] |
| 5650 | #[ignore = "a calibration probe, not a gate"] |
| 5651 | fn calibration_sweep_base_q_idx() { |
| 5652 | if !have_ffmpeg() { |
| 5653 | eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg"); |
| 5654 | return; |
| 5655 | } |
| 5656 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 5657 | for clip in [ |
| 5658 | "h264-1080p-23.976-8bit.mp4", |
| 5659 | "h264-1080p-60-8bit.mp4", |
| 5660 | ] { |
| 5661 | let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 5662 | .join("../../fixtures/video") |
| 5663 | .join(clip); |
| 5664 | if !path.exists() { |
| 5665 | eprintln!("SKIP {clip}: fixture missing"); |
| 5666 | continue; |
| 5667 | } |
| 5668 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 5669 | eprintln!("--- {clip} ---"); |
| 5670 | for q in [40u8, 70, 100, 130, 160, 190, 220, 240] { |
| 5671 | let encoded = encode_sequence(&source, q, 0.5).unwrap(); |
| 5672 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames); |
| 5673 | let mean_psnr: f64 = decoded |
| 5674 | .iter() |
| 5675 | .zip(&source) |
| 5676 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 5677 | .sum::<f64>() |
| 5678 | / frames as f64; |
| 5679 | let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64; |
| 5680 | eprintln!( |
| 5681 | "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB", |
| 5682 | encoded.stream.len() |
| 5683 | ); |
| 5684 | } |
| 5685 | } |
| 5686 | } |
| 5687 | } |