| 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 | |
| 1265 | |
| 1266 | |
| 1267 | |
| 1268 | let wide = bw > 64; |
| 1269 | Self { |
| 1270 | above_right: if row_off > 0 { |
| 1271 | |
| 1272 | |
| 1273 | |
| 1274 | if wide { |
| 1275 | (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64 |
| 1276 | } else { |
| 1277 | col_off + tx_w < bw |
| 1278 | } |
| 1279 | } else if col_off + tx_w < bw { |
| 1280 | true |
| 1281 | } else { |
| 1282 | block.above_right |
| 1283 | }, |
| 1284 | below_left: if wide && col_off > 0 && col_off % 64 == 0 { |
| 1285 | |
| 1286 | |
| 1287 | |
| 1288 | (row_off % 64) + tx_h < bh.min(64) |
| 1289 | } else if col_off > 0 { |
| 1290 | false |
| 1291 | } else if row_off + tx_h < bh { |
| 1292 | true |
| 1293 | } else { |
| 1294 | block.below_left |
| 1295 | }, |
| 1296 | } |
| 1297 | } |
| 1298 | |
| 1299 | |
| 1300 | |
| 1301 | pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self { |
| 1302 | Self { |
| 1303 | above_right: y > 0 && x + side < width && Self::top_right(side, x, y), |
| 1304 | below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y), |
| 1305 | } |
| 1306 | } |
| 1307 | |
| 1308 | |
| 1309 | |
| 1310 | |
| 1311 | |
| 1312 | |
| 1313 | pub(crate) fn of_rect( |
| 1314 | bw: usize, |
| 1315 | bh: usize, |
| 1316 | x: usize, |
| 1317 | y: usize, |
| 1318 | width: usize, |
| 1319 | height: usize, |
| 1320 | ) -> Self { |
| 1321 | Self { |
| 1322 | above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y), |
| 1323 | below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y), |
| 1324 | } |
| 1325 | } |
| 1326 | |
| 1327 | |
| 1328 | |
| 1329 | |
| 1330 | |
| 1331 | |
| 1332 | |
| 1333 | |
| 1334 | |
| 1335 | |
| 1336 | |
| 1337 | |
| 1338 | |
| 1339 | |
| 1340 | |
| 1341 | fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool { |
| 1342 | let sb_mi: usize = reach_sb_px() / 4; |
| 1343 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 1344 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 1345 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 1346 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 1347 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 1348 | |
| 1349 | |
| 1350 | if blk_row == 0 { |
| 1351 | return true; |
| 1352 | } |
| 1353 | |
| 1354 | if ((blk_col + 1) << bw_log2) >= sb_mi { |
| 1355 | return false; |
| 1356 | } |
| 1357 | let table = rect_reach_tables(bw, bh).0; |
| 1358 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 1359 | } |
| 1360 | |
| 1361 | |
| 1362 | |
| 1363 | |
| 1364 | |
| 1365 | |
| 1366 | |
| 1367 | |
| 1368 | |
| 1369 | fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize { |
| 1370 | (blk_row << (5 - bw_log2)) + blk_col |
| 1371 | } |
| 1372 | |
| 1373 | |
| 1374 | fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize) -> bool { |
| 1375 | let sb_mi: usize = reach_sb_px() / 4; |
| 1376 | let (mi_row, mi_col) = (y / 4, x / 4); |
| 1377 | let bw_log2 = (bw / 4).trailing_zeros() as usize; |
| 1378 | let bh_log2 = (bh / 4).trailing_zeros() as usize; |
| 1379 | let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2; |
| 1380 | let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2; |
| 1381 | |
| 1382 | |
| 1383 | if blk_col == 0 { |
| 1384 | return (blk_row << bh_log2) + (bh / 4) < sb_mi; |
| 1385 | } |
| 1386 | |
| 1387 | |
| 1388 | if ((blk_row + 1) << bh_log2) >= sb_mi { |
| 1389 | return false; |
| 1390 | } |
| 1391 | let table = rect_reach_tables(bw, bh).1; |
| 1392 | Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col)) |
| 1393 | } |
| 1394 | |
| 1395 | |
| 1396 | |
| 1397 | |
| 1398 | |
| 1399 | |
| 1400 | |
| 1401 | |
| 1402 | |
| 1403 | pub(crate) fn in_vert_ab() -> bool { |
| 1404 | VERT_AB_PARTITION.with(std::cell::Cell::get) |
| 1405 | } |
| 1406 | |
| 1407 | pub(crate) fn vert_ab_partition() -> VertAbGuard { |
| 1408 | VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true))) |
| 1409 | } |
| 1410 | |
| 1411 | |
| 1412 | |
| 1413 | pub(crate) fn none() -> Self { |
| 1414 | Self { |
| 1415 | above_right: false, |
| 1416 | below_left: false, |
| 1417 | } |
| 1418 | } |
| 1419 | |
| 1420 | |
| 1421 | |
| 1422 | |
| 1423 | |
| 1424 | fn top_right(side: usize, x: usize, y: usize) -> bool { |
| 1425 | let (row, col, per_side) = Self::position(side, x, y); |
| 1426 | if row == 0 { |
| 1427 | return true; |
| 1428 | } |
| 1429 | if col + 1 == per_side { |
| 1430 | return false; |
| 1431 | } |
| 1432 | |
| 1433 | |
| 1434 | |
| 1435 | |
| 1436 | |
| 1437 | |
| 1438 | |
| 1439 | |
| 1440 | |
| 1441 | |
| 1442 | |
| 1443 | let table_row = Self::table(side); |
| 1444 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() { |
| 1445 | HAS_TOP_RIGHT_VERT[table_row] |
| 1446 | } else { |
| 1447 | HAS_TOP_RIGHT[table_row] |
| 1448 | }; |
| 1449 | Self::bit( |
| 1450 | table, |
| 1451 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 1452 | ) |
| 1453 | } |
| 1454 | |
| 1455 | |
| 1456 | |
| 1457 | |
| 1458 | |
| 1459 | fn bottom_left(side: usize, x: usize, y: usize) -> bool { |
| 1460 | let (row, col, per_side) = Self::position(side, x, y); |
| 1461 | if col == 0 { |
| 1462 | return row * side + side < reach_sb_px(); |
| 1463 | } |
| 1464 | if row + 1 == per_side { |
| 1465 | return false; |
| 1466 | } |
| 1467 | |
| 1468 | |
| 1469 | |
| 1470 | |
| 1471 | |
| 1472 | |
| 1473 | |
| 1474 | |
| 1475 | |
| 1476 | |
| 1477 | |
| 1478 | let table_row = Self::table(side); |
| 1479 | let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() { |
| 1480 | HAS_BOTTOM_LEFT_VERT[table_row] |
| 1481 | } else { |
| 1482 | HAS_BOTTOM_LEFT[table_row] |
| 1483 | }; |
| 1484 | Self::bit( |
| 1485 | table, |
| 1486 | (row * Self::table_stride(side) + col) % (table.len() * 8), |
| 1487 | ) |
| 1488 | } |
| 1489 | |
| 1490 | |
| 1491 | |
| 1492 | fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) { |
| 1493 | let sb = reach_sb_px(); |
| 1494 | ((y % sb) / side, (x % sb) / side, sb / side) |
| 1495 | } |
| 1496 | |
| 1497 | |
| 1498 | |
| 1499 | |
| 1500 | |
| 1501 | |
| 1502 | |
| 1503 | |
| 1504 | |
| 1505 | fn table_stride(side: usize) -> usize { |
| 1506 | 128 / side |
| 1507 | } |
| 1508 | |
| 1509 | |
| 1510 | fn table(side: usize) -> usize { |
| 1511 | if side == BLOCK { |
| 1512 | 1 |
| 1513 | } else if side == 8 { |
| 1514 | 2 |
| 1515 | } else if side == 4 { |
| 1516 | 3 |
| 1517 | } else { |
| 1518 | 0 |
| 1519 | } |
| 1520 | } |
| 1521 | |
| 1522 | |
| 1523 | fn bit(table: &[u8], index: usize) -> bool { |
| 1524 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 1525 | } |
| 1526 | } |
| 1527 | |
| 1528 | |
| 1529 | pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 { |
| 1530 | let low = if symbol == 0 { 0 } else { cdf[symbol - 1] }; |
| 1531 | let probability = f64::from(cdf[symbol] - low) / 32768.0; |
| 1532 | -probability.log2() |
| 1533 | } |
| 1534 | |
| 1535 | |
| 1536 | |
| 1537 | |
| 1538 | |
| 1539 | |
| 1540 | |
| 1541 | |
| 1542 | |
| 1543 | |
| 1544 | |
| 1545 | |
| 1546 | |
| 1547 | fn code_square( |
| 1548 | luma: &mut Plane, |
| 1549 | chroma: &mut [Plane; 2], |
| 1550 | (x, y): (usize, usize), |
| 1551 | side: usize, |
| 1552 | search: &Search, |
| 1553 | mode_bits: &[f64; 13], |
| 1554 | ) -> (BlockCoeffs, f64) { |
| 1555 | let (luma_set, chroma_set) = if side == BLOCK { |
| 1556 | (TxbSet::Luma32, TxbSet::Chroma16) |
| 1557 | } else if side == 8 { |
| 1558 | |
| 1559 | |
| 1560 | |
| 1561 | |
| 1562 | |
| 1563 | |
| 1564 | |
| 1565 | (TxbSet::Luma8, TxbSet::Chroma4) |
| 1566 | } else { |
| 1567 | (TxbSet::Luma16, TxbSet::Chroma8) |
| 1568 | }; |
| 1569 | let (luma_coeffs, mode, mut cost) = luma.search_block( |
| 1570 | At { |
| 1571 | x, |
| 1572 | y, |
| 1573 | side, |
| 1574 | reach: Reach::of(side, x, y, luma.true_width, luma.true_height), |
| 1575 | set: luma_set, |
| 1576 | }, |
| 1577 | search, |
| 1578 | mode_bits, |
| 1579 | ); |
| 1580 | |
| 1581 | |
| 1582 | let mut planes = [Vec::new(), Vec::new()]; |
| 1583 | for (plane, coeffs) in chroma.iter_mut().zip(&mut planes) { |
| 1584 | let (levels, sse, bits) = plane.code_block( |
| 1585 | At { |
| 1586 | x: x / 2, |
| 1587 | y: y / 2, |
| 1588 | side: side / 2, |
| 1589 | reach: Reach::none(), |
| 1590 | set: chroma_set, |
| 1591 | }, |
| 1592 | DC_PRED, |
| 1593 | search.base_q_idx, |
| 1594 | search.deadzone, |
| 1595 | ); |
| 1596 | *coeffs = levels; |
| 1597 | cost += sse + search.lambda * bits; |
| 1598 | } |
| 1599 | let [u, v] = planes; |
| 1600 | ( |
| 1601 | BlockCoeffs { |
| 1602 | u, |
| 1603 | v, |
| 1604 | luma: luma_coeffs, |
| 1605 | mode, |
| 1606 | ..BlockCoeffs::default() |
| 1607 | }, |
| 1608 | cost, |
| 1609 | ) |
| 1610 | } |
| 1611 | |
| 1612 | |
| 1613 | |
| 1614 | |
| 1615 | |
| 1616 | |
| 1617 | |
| 1618 | |
| 1619 | |
| 1620 | |
| 1621 | |
| 1622 | |
| 1623 | #[allow(clippy::too_many_arguments)] |
| 1624 | fn code_square_inter( |
| 1625 | luma: &mut Plane, |
| 1626 | chroma: &mut [Plane; 2], |
| 1627 | (x, y): (usize, usize), |
| 1628 | side: usize, |
| 1629 | search: &Search, |
| 1630 | mode_bits: &[f64; 13], |
| 1631 | reference: &Picture, |
| 1632 | stack: &MvStack, |
| 1633 | ) -> BlockCoeffs { |
| 1634 | let (intra_block, intra_cost) = code_square(luma, chroma, (x, y), side, search, mode_bits); |
| 1635 | let luma_set = if side == 8 { |
| 1636 | TxbSet::Luma8Inter |
| 1637 | } else { |
| 1638 | TxbSet::Luma16Inter |
| 1639 | }; |
| 1640 | let chroma_set = if side == 8 { |
| 1641 | TxbSet::Chroma4 |
| 1642 | } else { |
| 1643 | TxbSet::Chroma8 |
| 1644 | }; |
| 1645 | |
| 1646 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 1647 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 1648 | let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 1649 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) |
| 1650 | + symbol_bits(&cdf::SINGLE_REF[0][3], 0); |
| 1651 | let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) |
| 1652 | + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) |
| 1653 | + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); |
| 1654 | |
| 1655 | let mv = stack.nearest_mv; |
| 1656 | let ref_luma = ( |
| 1657 | &reference.y, |
| 1658 | reference.width, |
| 1659 | luma.true_width, |
| 1660 | luma.true_height, |
| 1661 | ); |
| 1662 | let ref_u = ( |
| 1663 | &reference.u, |
| 1664 | reference.width / 2, |
| 1665 | chroma[0].true_width, |
| 1666 | chroma[0].true_height, |
| 1667 | ); |
| 1668 | let ref_v = ( |
| 1669 | &reference.v, |
| 1670 | reference.width / 2, |
| 1671 | chroma[1].true_width, |
| 1672 | chroma[1].true_height, |
| 1673 | ); |
| 1674 | let luma_trial = mc_trial( |
| 1675 | luma, |
| 1676 | x, |
| 1677 | y, |
| 1678 | side, |
| 1679 | mv, |
| 1680 | true, |
| 1681 | ref_luma.0, |
| 1682 | ref_luma.1, |
| 1683 | ref_luma.2, |
| 1684 | ref_luma.3, |
| 1685 | false, |
| 1686 | search.base_q_idx, |
| 1687 | search.deadzone, |
| 1688 | luma_set, |
| 1689 | ); |
| 1690 | let u = mc_trial( |
| 1691 | &chroma[0], |
| 1692 | x / 2, |
| 1693 | y / 2, |
| 1694 | side / 2, |
| 1695 | mv, |
| 1696 | false, |
| 1697 | ref_u.0, |
| 1698 | ref_u.1, |
| 1699 | ref_u.2, |
| 1700 | ref_u.3, |
| 1701 | false, |
| 1702 | search.base_q_idx, |
| 1703 | search.deadzone, |
| 1704 | chroma_set, |
| 1705 | ); |
| 1706 | let v = mc_trial( |
| 1707 | &chroma[1], |
| 1708 | x / 2, |
| 1709 | y / 2, |
| 1710 | side / 2, |
| 1711 | mv, |
| 1712 | false, |
| 1713 | ref_v.0, |
| 1714 | ref_v.1, |
| 1715 | ref_v.2, |
| 1716 | ref_v.3, |
| 1717 | false, |
| 1718 | search.base_q_idx, |
| 1719 | search.deadzone, |
| 1720 | chroma_set, |
| 1721 | ); |
| 1722 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 1723 | && u.levels.iter().all(|&l| l == 0) |
| 1724 | && v.levels.iter().all(|&l| l == 0); |
| 1725 | let inter_cost = luma_trial.sse |
| 1726 | + u.sse |
| 1727 | + v.sse |
| 1728 | + search.lambda |
| 1729 | * (skip_bits(skip) |
| 1730 | + intra_inter_bits(true) |
| 1731 | + single_ref_bits |
| 1732 | + mode_bits_inter |
| 1733 | + if skip { |
| 1734 | 0.0 |
| 1735 | } else { |
| 1736 | luma_trial.bits + u.bits + v.bits |
| 1737 | }); |
| 1738 | |
| 1739 | |
| 1740 | |
| 1741 | |
| 1742 | |
| 1743 | |
| 1744 | |
| 1745 | |
| 1746 | |
| 1747 | |
| 1748 | |
| 1749 | |
| 1750 | |
| 1751 | |
| 1752 | |
| 1753 | if inter_cost < intra_cost { |
| 1754 | luma.commit(x, y, side, &luma_trial); |
| 1755 | chroma[0].commit(x / 2, y / 2, side / 2, &u); |
| 1756 | chroma[1].commit(x / 2, y / 2, side / 2, &v); |
| 1757 | BlockCoeffs { |
| 1758 | luma: coeffs(&luma_trial.levels, side), |
| 1759 | u: coeffs(&u.levels, side / 2), |
| 1760 | v: coeffs(&v.levels, side / 2), |
| 1761 | mode: DC_PRED as u8, |
| 1762 | skip, |
| 1763 | eight: None, |
| 1764 | inter: Some(InterInfo { |
| 1765 | mode: InterMode::NearestMv, |
| 1766 | mv, |
| 1767 | }), |
| 1768 | } |
| 1769 | } else { |
| 1770 | intra_block |
| 1771 | } |
| 1772 | } |
| 1773 | |
| 1774 | |
| 1775 | |
| 1776 | fn snapshot(luma: &Plane, chroma: &[Plane; 2], (x, y): (usize, usize)) -> [Vec<u8>; 3] { |
| 1777 | [ |
| 1778 | luma.snapshot(x, y, BLOCK), |
| 1779 | chroma[0].snapshot(x / 2, y / 2, BLOCK / 2), |
| 1780 | chroma[1].snapshot(x / 2, y / 2, BLOCK / 2), |
| 1781 | ] |
| 1782 | } |
| 1783 | |
| 1784 | |
| 1785 | fn restore( |
| 1786 | luma: &mut Plane, |
| 1787 | chroma: &mut [Plane; 2], |
| 1788 | (x, y): (usize, usize), |
| 1789 | saved: &[Vec<u8>; 3], |
| 1790 | ) { |
| 1791 | luma.restore(x, y, BLOCK, &saved[0]); |
| 1792 | chroma[0].restore(x / 2, y / 2, BLOCK / 2, &saved[1]); |
| 1793 | chroma[1].restore(x / 2, y / 2, BLOCK / 2, &saved[2]); |
| 1794 | } |
| 1795 | |
| 1796 | |
| 1797 | |
| 1798 | |
| 1799 | |
| 1800 | |
| 1801 | fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> { |
| 1802 | let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED); |
| 1803 | let dc_entry = dc_pos.map(|i| scored.remove(i)); |
| 1804 | scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite")); |
| 1805 | scored.truncate(if dc_entry.is_some() { |
| 1806 | top_k.saturating_sub(1) |
| 1807 | } else { |
| 1808 | top_k |
| 1809 | }); |
| 1810 | if let Some(dc_entry) = dc_entry { |
| 1811 | scored.push(dc_entry); |
| 1812 | } |
| 1813 | let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect(); |
| 1814 | modes.iter().copied().filter(|m| keep.contains(m)).collect() |
| 1815 | } |
| 1816 | |
| 1817 | fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] { |
| 1818 | let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]] |
| 1819 | [INTRA_MODE_CTX[usize::from(left_mode)]]; |
| 1820 | std::array::from_fn(|mode| { |
| 1821 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 1822 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 1823 | } else { |
| 1824 | 0.0 |
| 1825 | }; |
| 1826 | symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 1827 | }) |
| 1828 | } |
| 1829 | |
| 1830 | |
| 1831 | struct Search<'a> { |
| 1832 | base_q_idx: u8, |
| 1833 | deadzone: f64, |
| 1834 | lambda: f64, |
| 1835 | modes: &'a [u8], |
| 1836 | |
| 1837 | |
| 1838 | |
| 1839 | |
| 1840 | |
| 1841 | |
| 1842 | top_k: Option<usize>, |
| 1843 | } |
| 1844 | |
| 1845 | |
| 1846 | |
| 1847 | |
| 1848 | fn prune_top_k() -> Option<usize> { |
| 1849 | #[cfg(test)] |
| 1850 | { |
| 1851 | if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) { |
| 1852 | return k; |
| 1853 | } |
| 1854 | } |
| 1855 | let swept = std::env::var("EC_AV1_PRUNE_K") |
| 1856 | .ok() |
| 1857 | .and_then(|v| v.parse::<usize>().ok()); |
| 1858 | match swept { |
| 1859 | Some(k) if cfg!(test) => Some(k), |
| 1860 | _ => PRUNE_TOP_K, |
| 1861 | } |
| 1862 | } |
| 1863 | |
| 1864 | |
| 1865 | |
| 1866 | |
| 1867 | #[cfg(test)] |
| 1868 | thread_local! { |
| 1869 | static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> = |
| 1870 | const { std::cell::Cell::new(None) }; |
| 1871 | } |
| 1872 | |
| 1873 | #[cfg(test)] |
| 1874 | fn set_test_top_k_override(value: Option<usize>) { |
| 1875 | TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value))); |
| 1876 | } |
| 1877 | |
| 1878 | |
| 1879 | |
| 1880 | const PRUNE_TOP_K: Option<usize> = None; |
| 1881 | |
| 1882 | |
| 1883 | |
| 1884 | |
| 1885 | |
| 1886 | |
| 1887 | fn prune_top_k_inter() -> Option<usize> { |
| 1888 | #[cfg(test)] |
| 1889 | { |
| 1890 | if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) { |
| 1891 | return k; |
| 1892 | } |
| 1893 | } |
| 1894 | let swept = std::env::var("EC_AV1_PRUNE_K_INTER") |
| 1895 | .ok() |
| 1896 | .and_then(|v| v.parse::<usize>().ok()); |
| 1897 | match swept { |
| 1898 | Some(k) if cfg!(test) => Some(k), |
| 1899 | _ => INTER_PRUNE_TOP_K, |
| 1900 | } |
| 1901 | } |
| 1902 | |
| 1903 | |
| 1904 | |
| 1905 | #[cfg(test)] |
| 1906 | thread_local! { |
| 1907 | static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> = |
| 1908 | const { std::cell::Cell::new(None) }; |
| 1909 | } |
| 1910 | |
| 1911 | #[cfg(test)] |
| 1912 | fn set_test_top_k_override_inter(value: Option<usize>) { |
| 1913 | TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value))); |
| 1914 | } |
| 1915 | |
| 1916 | |
| 1917 | |
| 1918 | |
| 1919 | |
| 1920 | |
| 1921 | |
| 1922 | |
| 1923 | const INTER_PRUNE_TOP_K: Option<usize> = Some(3); |
| 1924 | |
| 1925 | |
| 1926 | |
| 1927 | |
| 1928 | |
| 1929 | |
| 1930 | |
| 1931 | |
| 1932 | |
| 1933 | #[cfg(test)] |
| 1934 | thread_local! { |
| 1935 | static STAGE_NS: [std::cell::Cell<u64>; 4] = [ |
| 1936 | std::cell::Cell::new(0), |
| 1937 | std::cell::Cell::new(0), |
| 1938 | std::cell::Cell::new(0), |
| 1939 | std::cell::Cell::new(0), |
| 1940 | ]; |
| 1941 | } |
| 1942 | |
| 1943 | #[cfg(test)] |
| 1944 | pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) { |
| 1945 | STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64)); |
| 1946 | } |
| 1947 | |
| 1948 | #[cfg(test)] |
| 1949 | fn stage_reset() { |
| 1950 | STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0))); |
| 1951 | } |
| 1952 | |
| 1953 | #[cfg(test)] |
| 1954 | fn stage_read() -> [std::time::Duration; 4] { |
| 1955 | STAGE_NS.with(|c| { |
| 1956 | c.each_ref() |
| 1957 | .map(|cell| std::time::Duration::from_nanos(cell.get())) |
| 1958 | }) |
| 1959 | } |
| 1960 | |
| 1961 | |
| 1962 | #[derive(Clone)] |
| 1963 | struct Trial { |
| 1964 | levels: Vec<i32>, |
| 1965 | reconstruction: Vec<u8>, |
| 1966 | sse: f64, |
| 1967 | bits: f64, |
| 1968 | } |
| 1969 | |
| 1970 | |
| 1971 | fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> { |
| 1972 | levels |
| 1973 | .iter() |
| 1974 | .enumerate() |
| 1975 | .filter(|&(_, &level)| level != 0) |
| 1976 | .map(|(i, &level)| Coeff { |
| 1977 | row: (i / side) as u8, |
| 1978 | col: (i % side) as u8, |
| 1979 | level, |
| 1980 | }) |
| 1981 | .collect() |
| 1982 | } |
| 1983 | |
| 1984 | |
| 1985 | |
| 1986 | |
| 1987 | |
| 1988 | |
| 1989 | |
| 1990 | |
| 1991 | |
| 1992 | |
| 1993 | |
| 1994 | |
| 1995 | |
| 1996 | |
| 1997 | |
| 1998 | |
| 1999 | |
| 2000 | pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> { |
| 2001 | encode_key_frame_with_modes(picture, base_q_idx, deadzone, &KEY_FRAME_MODES) |
| 2002 | } |
| 2003 | |
| 2004 | |
| 2005 | |
| 2006 | |
| 2007 | |
| 2008 | |
| 2009 | |
| 2010 | |
| 2011 | |
| 2012 | |
| 2013 | |
| 2014 | |
| 2015 | pub fn encode_key_frame_with_modes( |
| 2016 | picture: &Picture, |
| 2017 | base_q_idx: u8, |
| 2018 | deadzone: f64, |
| 2019 | modes: &[u8], |
| 2020 | ) -> Result<Encoded> { |
| 2021 | picture.check_even()?; |
| 2022 | let padded = picture.padded_to(BLOCK); |
| 2023 | let encoded = encode_key_frame_inner( |
| 2024 | &padded, |
| 2025 | base_q_idx, |
| 2026 | deadzone, |
| 2027 | modes, |
| 2028 | split_blocks(), |
| 2029 | (picture.width, picture.height), |
| 2030 | unspecified_color_config(), |
| 2031 | )?; |
| 2032 | Ok(crop_encoded(&encoded, picture.width, picture.height)) |
| 2033 | } |
| 2034 | |
| 2035 | |
| 2036 | |
| 2037 | |
| 2038 | |
| 2039 | pub(crate) fn encode_key_frame_inner( |
| 2040 | picture: &Picture, |
| 2041 | base_q_idx: u8, |
| 2042 | deadzone: f64, |
| 2043 | modes: &[u8], |
| 2044 | split_blocks: bool, |
| 2045 | render: (usize, usize), |
| 2046 | color_config: ColorConfig, |
| 2047 | ) -> Result<Encoded> { |
| 2048 | picture.check()?; |
| 2049 | if modes.is_empty() { |
| 2050 | return Err(Error::unsupported( |
| 2051 | "AV1 encode", |
| 2052 | "a mode search needs at least one mode to choose from", |
| 2053 | )); |
| 2054 | } |
| 2055 | if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) { |
| 2056 | return Err(Error::unsupported( |
| 2057 | "AV1 encode", |
| 2058 | format!("intra mode {bad} is not one the encoder predicts"), |
| 2059 | )); |
| 2060 | } |
| 2061 | |
| 2062 | |
| 2063 | |
| 2064 | |
| 2065 | |
| 2066 | |
| 2067 | |
| 2068 | let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?; |
| 2069 | header.render_width = render.0 as u32; |
| 2070 | header.render_height = render.1 as u32; |
| 2071 | |
| 2072 | |
| 2073 | |
| 2074 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 2075 | |
| 2076 | |
| 2077 | |
| 2078 | |
| 2079 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 2080 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 2081 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 2082 | let mut luma = Plane { |
| 2083 | source: &picture_y8, |
| 2084 | reconstruction: vec![128; picture_y8.len()], |
| 2085 | width: picture.width, |
| 2086 | height: picture.height, |
| 2087 | true_width, |
| 2088 | true_height, |
| 2089 | }; |
| 2090 | let mut chroma = [ |
| 2091 | Plane { |
| 2092 | source: &picture_u8, |
| 2093 | reconstruction: vec![128; picture_u8.len()], |
| 2094 | width: picture.width / 2, |
| 2095 | height: picture.height / 2, |
| 2096 | true_width: true_width / 2, |
| 2097 | true_height: true_height / 2, |
| 2098 | }, |
| 2099 | Plane { |
| 2100 | source: &picture_v8, |
| 2101 | reconstruction: vec![128; picture_v8.len()], |
| 2102 | width: picture.width / 2, |
| 2103 | height: picture.height / 2, |
| 2104 | true_width: true_width / 2, |
| 2105 | true_height: true_height / 2, |
| 2106 | }, |
| 2107 | ]; |
| 2108 | |
| 2109 | |
| 2110 | |
| 2111 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 2112 | let search = Search { |
| 2113 | base_q_idx, |
| 2114 | deadzone, |
| 2115 | lambda: lambda_scale() * step * step, |
| 2116 | modes, |
| 2117 | top_k: prune_top_k(), |
| 2118 | }; |
| 2119 | |
| 2120 | |
| 2121 | |
| 2122 | |
| 2123 | |
| 2124 | |
| 2125 | |
| 2126 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 2127 | let (cols, rows) = (cols as usize, rows as usize); |
| 2128 | |
| 2129 | |
| 2130 | |
| 2131 | |
| 2132 | |
| 2133 | |
| 2134 | let mut above_mode = vec![DC_PRED; cols * 2]; |
| 2135 | let mut left_mode = vec![DC_PRED; rows * 2]; |
| 2136 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 2137 | let mut superblocks = Vec::with_capacity(sb_cols * sb_rows); |
| 2138 | let mut modes = Vec::with_capacity(cols * rows); |
| 2139 | for sb_row in 0..sb_rows { |
| 2140 | for sb_col in 0..sb_cols { |
| 2141 | |
| 2142 | |
| 2143 | |
| 2144 | let mut blocks = Vec::with_capacity(4); |
| 2145 | for quadrant in 0..4 { |
| 2146 | let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2); |
| 2147 | if col >= cols || row >= rows { |
| 2148 | continue; |
| 2149 | } |
| 2150 | let (x, y) = (col * BLOCK, row * BLOCK); |
| 2151 | let (c0, r0) = (col * 2, row * 2); |
| 2152 | let base = snapshot(&luma, &chroma, (x, y)); |
| 2153 | |
| 2154 | |
| 2155 | |
| 2156 | |
| 2157 | |
| 2158 | |
| 2159 | |
| 2160 | |
| 2161 | let (has_cols32, has_rows32) = ( |
| 2162 | crate::tile::has_half( |
| 2163 | col as u32 * crate::tile::BLOCK_MI, |
| 2164 | crate::tile::BLOCK_MI, |
| 2165 | header.mi_cols, |
| 2166 | ), |
| 2167 | crate::tile::has_half( |
| 2168 | row as u32 * crate::tile::BLOCK_MI, |
| 2169 | crate::tile::BLOCK_MI, |
| 2170 | header.mi_rows, |
| 2171 | ), |
| 2172 | ); |
| 2173 | let whole_legal = has_cols32 && has_rows32; |
| 2174 | |
| 2175 | |
| 2176 | |
| 2177 | |
| 2178 | |
| 2179 | |
| 2180 | let sub_half = |sr: usize, sc: usize| { |
| 2181 | ( |
| 2182 | crate::tile::has_half( |
| 2183 | sc as u32 * crate::tile::SUB_MI, |
| 2184 | crate::tile::SUB_MI, |
| 2185 | header.mi_cols, |
| 2186 | ), |
| 2187 | crate::tile::has_half( |
| 2188 | sr as u32 * crate::tile::SUB_MI, |
| 2189 | crate::tile::SUB_MI, |
| 2190 | header.mi_rows, |
| 2191 | ), |
| 2192 | ) |
| 2193 | }; |
| 2194 | let both_axes_cut = (0..4) |
| 2195 | .map(|i| (r0 + i / 2, c0 + i % 2)) |
| 2196 | .filter(|&(sr, sc)| { |
| 2197 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 2198 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 2199 | }) |
| 2200 | .any(|(sr, sc)| { |
| 2201 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 2202 | !has_cols16 && !has_rows16 |
| 2203 | }); |
| 2204 | if !whole_legal && both_axes_cut { |
| 2205 | return Err(Error::unsupported( |
| 2206 | "AV1 encode", |
| 2207 | format!( |
| 2208 | "the 32x32 block at ({col},{row}) straddles the true frame edge \ |
| 2209 | in a way that needs a rectangular (HORZ/VERT) transform this \ |
| 2210 | encoder does not code yet" |
| 2211 | ), |
| 2212 | )); |
| 2213 | } |
| 2214 | |
| 2215 | |
| 2216 | |
| 2217 | let (whole, mut cost_whole) = code_square( |
| 2218 | &mut luma, |
| 2219 | &mut chroma, |
| 2220 | (x, y), |
| 2221 | BLOCK, |
| 2222 | &search, |
| 2223 | &mode_bits(above_mode[c0], left_mode[r0]), |
| 2224 | ); |
| 2225 | cost_whole += search.lambda * partition_bits(BLOCK, false); |
| 2226 | let after_whole = snapshot(&luma, &chroma, (x, y)); |
| 2227 | |
| 2228 | |
| 2229 | |
| 2230 | restore(&mut luma, &mut chroma, (x, y), &base); |
| 2231 | let mut split = Vec::with_capacity(4); |
| 2232 | let mut cost_split = search.lambda |
| 2233 | * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false)); |
| 2234 | let mut split_modes = Vec::with_capacity(4); |
| 2235 | for sub in 0..4 { |
| 2236 | let (sc, sr) = (c0 + sub % 2, r0 + sub / 2); |
| 2237 | |
| 2238 | |
| 2239 | |
| 2240 | |
| 2241 | |
| 2242 | |
| 2243 | if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows |
| 2244 | || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols |
| 2245 | { |
| 2246 | continue; |
| 2247 | } |
| 2248 | let (has_cols16, has_rows16) = sub_half(sr, sc); |
| 2249 | if has_cols16 && has_rows16 { |
| 2250 | let (block, cost) = code_square( |
| 2251 | &mut luma, |
| 2252 | &mut chroma, |
| 2253 | (x + (sub % 2) * SUB, y + (sub / 2) * SUB), |
| 2254 | SUB, |
| 2255 | &search, |
| 2256 | &mode_bits(above_mode[sc], left_mode[sr]), |
| 2257 | ); |
| 2258 | cost_split += cost; |
| 2259 | split_modes.push(block.mode); |
| 2260 | above_mode[sc] = block.mode; |
| 2261 | left_mode[sr] = block.mode; |
| 2262 | split.push(block); |
| 2263 | } else { |
| 2264 | |
| 2265 | |
| 2266 | |
| 2267 | |
| 2268 | |
| 2269 | |
| 2270 | |
| 2271 | |
| 2272 | let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]); |
| 2273 | let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB); |
| 2274 | let mut leaves = Vec::with_capacity(2); |
| 2275 | for i in 0..4 { |
| 2276 | let leaf_x = x_sub + (i % 2) * 8; |
| 2277 | let leaf_y = y_sub + (i / 2) * 8; |
| 2278 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 2279 | continue; |
| 2280 | } |
| 2281 | let (leaf, cost) = code_square( |
| 2282 | &mut luma, |
| 2283 | &mut chroma, |
| 2284 | (leaf_x, leaf_y), |
| 2285 | 8, |
| 2286 | &search, |
| 2287 | &leaf_mode_bits, |
| 2288 | ); |
| 2289 | cost_split += cost; |
| 2290 | split_modes.push(leaf.mode); |
| 2291 | leaves.push(leaf); |
| 2292 | } |
| 2293 | split.push(BlockCoeffs { |
| 2294 | eight: Some(leaves), |
| 2295 | ..BlockCoeffs::default() |
| 2296 | }); |
| 2297 | } |
| 2298 | } |
| 2299 | |
| 2300 | |
| 2301 | |
| 2302 | |
| 2303 | |
| 2304 | |
| 2305 | |
| 2306 | |
| 2307 | |
| 2308 | if !whole_legal || (split_blocks && cost_split < cost_whole) { |
| 2309 | modes.extend_from_slice(&split_modes); |
| 2310 | blocks.push(Quadrant::Split(split)); |
| 2311 | } else { |
| 2312 | restore(&mut luma, &mut chroma, (x, y), &after_whole); |
| 2313 | for cell in 0..2 { |
| 2314 | above_mode[c0 + cell] = whole.mode; |
| 2315 | left_mode[r0 + cell] = whole.mode; |
| 2316 | } |
| 2317 | modes.push(whole.mode); |
| 2318 | blocks.push(Quadrant::Whole(whole)); |
| 2319 | } |
| 2320 | } |
| 2321 | superblocks.push(Superblock::Split(blocks)); |
| 2322 | } |
| 2323 | } |
| 2324 | |
| 2325 | let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &superblocks)?; |
| 2326 | let mut stream = temporal_delimiter(); |
| 2327 | stream.extend_from_slice(&sequence_header_obu(&seq)?); |
| 2328 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 2329 | |
| 2330 | let [u, v] = chroma; |
| 2331 | Ok(Encoded { |
| 2332 | stream, |
| 2333 | modes, |
| 2334 | inter_block_share: 0.0, |
| 2335 | reconstruction: Picture { |
| 2336 | width: luma.width, |
| 2337 | height: luma.height, |
| 2338 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 2339 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 2340 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 2341 | }, |
| 2342 | tile, |
| 2343 | mi_cols: header.mi_cols, |
| 2344 | mi_rows: header.mi_rows, |
| 2345 | base_q_idx, |
| 2346 | }) |
| 2347 | } |
| 2348 | |
| 2349 | |
| 2350 | |
| 2351 | |
| 2352 | const SIZE_GROUP_32: usize = 3; |
| 2353 | |
| 2354 | |
| 2355 | |
| 2356 | |
| 2357 | const LAST_FRAME: i8 = 1; |
| 2358 | |
| 2359 | |
| 2360 | |
| 2361 | |
| 2362 | |
| 2363 | |
| 2364 | |
| 2365 | fn inter_mode_bits() -> [f64; 13] { |
| 2366 | std::array::from_fn(|mode| { |
| 2367 | let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) { |
| 2368 | symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3) |
| 2369 | } else { |
| 2370 | 0.0 |
| 2371 | }; |
| 2372 | symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode) |
| 2373 | + angle |
| 2374 | + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED)) |
| 2375 | }) |
| 2376 | } |
| 2377 | |
| 2378 | |
| 2379 | |
| 2380 | |
| 2381 | |
| 2382 | |
| 2383 | |
| 2384 | |
| 2385 | fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 { |
| 2386 | (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 } |
| 2387 | } |
| 2388 | |
| 2389 | |
| 2390 | |
| 2391 | |
| 2392 | fn mv_class_base(class: usize) -> i32 { |
| 2393 | if class == 0 { 0 } else { 2i32 << (class + 2) } |
| 2394 | } |
| 2395 | |
| 2396 | |
| 2397 | |
| 2398 | fn mv_class_of(z: i32) -> usize { |
| 2399 | let mut class = 0; |
| 2400 | while class < 10 && mv_class_base(class + 1) <= z { |
| 2401 | class += 1; |
| 2402 | } |
| 2403 | class |
| 2404 | } |
| 2405 | |
| 2406 | |
| 2407 | |
| 2408 | |
| 2409 | |
| 2410 | |
| 2411 | |
| 2412 | |
| 2413 | |
| 2414 | |
| 2415 | |
| 2416 | fn mv_component_bits(diff: i32) -> Option<f64> { |
| 2417 | let mag = diff.unsigned_abs() as i32; |
| 2418 | let z = mag - 1; |
| 2419 | if z & 1 == 0 { |
| 2420 | return None; |
| 2421 | } |
| 2422 | let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0)); |
| 2423 | let class = mv_class_of(z); |
| 2424 | bits += symbol_bits(&cdf::MV_CLASS, class); |
| 2425 | let local = z - mv_class_base(class); |
| 2426 | if class == 0 { |
| 2427 | let bit = (local >> 3) & 1; |
| 2428 | let fr = (local >> 1) & 3; |
| 2429 | bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize); |
| 2430 | bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize); |
| 2431 | } else { |
| 2432 | let d = local >> 3; |
| 2433 | let fr = (local >> 1) & 3; |
| 2434 | for i in 0..class { |
| 2435 | bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize); |
| 2436 | } |
| 2437 | bits += symbol_bits(&cdf::MV_FR, fr as usize); |
| 2438 | } |
| 2439 | Some(bits) |
| 2440 | } |
| 2441 | |
| 2442 | |
| 2443 | |
| 2444 | |
| 2445 | |
| 2446 | fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> { |
| 2447 | let diff = (mv.0 - pred.0, mv.1 - pred.1); |
| 2448 | let joint = match (diff.0 != 0, diff.1 != 0) { |
| 2449 | (false, false) => 0, |
| 2450 | (false, true) => 1, |
| 2451 | (true, false) => 2, |
| 2452 | (true, true) => 3, |
| 2453 | }; |
| 2454 | let mut bits = symbol_bits(&cdf::MV_JOINT, joint); |
| 2455 | for d in [diff.0, diff.1] { |
| 2456 | if d != 0 { |
| 2457 | bits += mv_component_bits(d)?; |
| 2458 | } |
| 2459 | } |
| 2460 | Some(bits) |
| 2461 | } |
| 2462 | |
| 2463 | |
| 2464 | |
| 2465 | |
| 2466 | |
| 2467 | |
| 2468 | |
| 2469 | |
| 2470 | |
| 2471 | |
| 2472 | fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) { |
| 2473 | let round = |m: i32, p: i32| { |
| 2474 | let diff = m - p; |
| 2475 | let mag = diff.unsigned_abs() as i32; |
| 2476 | let even = mag - mag % 2; |
| 2477 | if even == 0 { |
| 2478 | p |
| 2479 | } else { |
| 2480 | p + even * diff.signum() |
| 2481 | } |
| 2482 | }; |
| 2483 | (round(mv.0, pred.0), round(mv.1, pred.1)) |
| 2484 | } |
| 2485 | |
| 2486 | |
| 2487 | |
| 2488 | #[allow(clippy::too_many_arguments)] |
| 2489 | fn mc_trial( |
| 2490 | plane: &Plane, |
| 2491 | x: usize, |
| 2492 | y: usize, |
| 2493 | side: usize, |
| 2494 | mv: (i32, i32), |
| 2495 | luma: bool, |
| 2496 | reference: &[u16], |
| 2497 | stride: usize, |
| 2498 | ref_width: usize, |
| 2499 | ref_height: usize, |
| 2500 | skip: bool, |
| 2501 | base_q_idx: u8, |
| 2502 | deadzone: f64, |
| 2503 | set: TxbSet, |
| 2504 | ) -> Trial { |
| 2505 | let x_q4 = mv_to_q4(x, mv.1, luma); |
| 2506 | let y_q4 = mv_to_q4(y, mv.0, luma); |
| 2507 | |
| 2508 | |
| 2509 | |
| 2510 | let mut prediction16 = vec![0u16; side * side]; |
| 2511 | mc::predict( |
| 2512 | reference, |
| 2513 | stride, |
| 2514 | ref_width, |
| 2515 | ref_height, |
| 2516 | x_q4, |
| 2517 | y_q4, |
| 2518 | side, |
| 2519 | side, |
| 2520 | &mut prediction16, |
| 2521 | ); |
| 2522 | let prediction: Vec<u8> = prediction16.iter().map(|&v| v as u8).collect(); |
| 2523 | plane.code_from_prediction(x, y, side, &prediction, skip, base_q_idx, deadzone, set) |
| 2524 | } |
| 2525 | |
| 2526 | |
| 2527 | |
| 2528 | |
| 2529 | |
| 2530 | |
| 2531 | |
| 2532 | |
| 2533 | |
| 2534 | |
| 2535 | |
| 2536 | |
| 2537 | |
| 2538 | |
| 2539 | |
| 2540 | |
| 2541 | |
| 2542 | |
| 2543 | |
| 2544 | #[allow(clippy::too_many_arguments)] |
| 2545 | fn search_inter_block( |
| 2546 | luma: &mut Plane, |
| 2547 | chroma: &mut [Plane; 2], |
| 2548 | (x, y): (usize, usize), |
| 2549 | search: &Search, |
| 2550 | mode_bits: &[f64; 13], |
| 2551 | reference: &Picture, |
| 2552 | stack: &MvStack, |
| 2553 | ) -> BlockCoeffs { |
| 2554 | let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16); |
| 2555 | let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height); |
| 2556 | |
| 2557 | |
| 2558 | |
| 2559 | let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip)); |
| 2560 | let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter)); |
| 2561 | let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0) |
| 2562 | + symbol_bits(&cdf::SINGLE_REF[0][2], 0) |
| 2563 | + symbol_bits(&cdf::SINGLE_REF[0][3], 0); |
| 2564 | |
| 2565 | struct Candidate { |
| 2566 | cost: f64, |
| 2567 | luma: Trial, |
| 2568 | u: Trial, |
| 2569 | v: Trial, |
| 2570 | mode: u8, |
| 2571 | skip: bool, |
| 2572 | inter: Option<InterInfo>, |
| 2573 | } |
| 2574 | let mut best: Option<Candidate> = None; |
| 2575 | let mut consider = |candidate: Candidate| { |
| 2576 | if best.as_ref().is_none_or(|b| candidate.cost < b.cost) { |
| 2577 | best = Some(candidate); |
| 2578 | } |
| 2579 | }; |
| 2580 | |
| 2581 | |
| 2582 | |
| 2583 | |
| 2584 | |
| 2585 | |
| 2586 | |
| 2587 | |
| 2588 | |
| 2589 | let u_trial = chroma[0].trial( |
| 2590 | At { |
| 2591 | x: x / 2, |
| 2592 | y: y / 2, |
| 2593 | side: BLOCK / 2, |
| 2594 | reach: Reach::none(), |
| 2595 | set: chroma_set, |
| 2596 | }, |
| 2597 | DC_PRED, |
| 2598 | search.base_q_idx, |
| 2599 | search.deadzone, |
| 2600 | ); |
| 2601 | let v_trial = chroma[1].trial( |
| 2602 | At { |
| 2603 | x: x / 2, |
| 2604 | y: y / 2, |
| 2605 | side: BLOCK / 2, |
| 2606 | reach: Reach::none(), |
| 2607 | set: chroma_set, |
| 2608 | }, |
| 2609 | DC_PRED, |
| 2610 | search.base_q_idx, |
| 2611 | search.deadzone, |
| 2612 | ); |
| 2613 | |
| 2614 | let intra_modes: Vec<u8> = match search.top_k { |
| 2615 | Some(k) if k < search.modes.len() => { |
| 2616 | let scored = luma.intra_scores( |
| 2617 | At { |
| 2618 | x, |
| 2619 | y, |
| 2620 | side: BLOCK, |
| 2621 | reach, |
| 2622 | set: luma_set, |
| 2623 | }, |
| 2624 | search.modes, |
| 2625 | mode_bits, |
| 2626 | search.lambda, |
| 2627 | ); |
| 2628 | prune_by_sad(search.modes, scored, k) |
| 2629 | } |
| 2630 | _ => search.modes.to_vec(), |
| 2631 | }; |
| 2632 | for &mode in &intra_modes { |
| 2633 | let luma_trial = luma.trial( |
| 2634 | At { |
| 2635 | x, |
| 2636 | y, |
| 2637 | side: BLOCK, |
| 2638 | reach, |
| 2639 | set: luma_set, |
| 2640 | }, |
| 2641 | mode, |
| 2642 | search.base_q_idx, |
| 2643 | search.deadzone, |
| 2644 | ); |
| 2645 | let u = u_trial.clone(); |
| 2646 | let v = v_trial.clone(); |
| 2647 | let cost = luma_trial.sse |
| 2648 | + u.sse |
| 2649 | + v.sse |
| 2650 | + search.lambda |
| 2651 | * (luma_trial.bits |
| 2652 | + u.bits |
| 2653 | + v.bits |
| 2654 | + mode_bits[usize::from(mode)] |
| 2655 | + skip_bits(false) |
| 2656 | + intra_inter_bits(false)); |
| 2657 | consider(Candidate { |
| 2658 | cost, |
| 2659 | luma: luma_trial, |
| 2660 | u, |
| 2661 | v, |
| 2662 | mode, |
| 2663 | skip: false, |
| 2664 | inter: None, |
| 2665 | }); |
| 2666 | } |
| 2667 | |
| 2668 | |
| 2669 | |
| 2670 | |
| 2671 | |
| 2672 | |
| 2673 | |
| 2674 | |
| 2675 | |
| 2676 | |
| 2677 | |
| 2678 | let ref_luma = ( |
| 2679 | &reference.y, |
| 2680 | reference.width, |
| 2681 | luma.true_width, |
| 2682 | luma.true_height, |
| 2683 | ); |
| 2684 | let ref_u = ( |
| 2685 | &reference.u, |
| 2686 | reference.width / 2, |
| 2687 | chroma[0].true_width, |
| 2688 | chroma[0].true_height, |
| 2689 | ); |
| 2690 | let ref_v = ( |
| 2691 | &reference.v, |
| 2692 | reference.width / 2, |
| 2693 | chroma[1].true_width, |
| 2694 | chroma[1].true_height, |
| 2695 | ); |
| 2696 | let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) |
| 2697 | + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) |
| 2698 | + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); |
| 2699 | |
| 2700 | |
| 2701 | |
| 2702 | |
| 2703 | { |
| 2704 | let mv = stack.nearest_mv; |
| 2705 | let luma_trial = mc_trial( |
| 2706 | luma, |
| 2707 | x, |
| 2708 | y, |
| 2709 | BLOCK, |
| 2710 | mv, |
| 2711 | true, |
| 2712 | ref_luma.0, |
| 2713 | ref_luma.1, |
| 2714 | ref_luma.2, |
| 2715 | ref_luma.3, |
| 2716 | false, |
| 2717 | search.base_q_idx, |
| 2718 | search.deadzone, |
| 2719 | luma_set, |
| 2720 | ); |
| 2721 | let u = mc_trial( |
| 2722 | &chroma[0], |
| 2723 | x / 2, |
| 2724 | y / 2, |
| 2725 | BLOCK / 2, |
| 2726 | mv, |
| 2727 | false, |
| 2728 | ref_u.0, |
| 2729 | ref_u.1, |
| 2730 | ref_u.2, |
| 2731 | ref_u.3, |
| 2732 | false, |
| 2733 | search.base_q_idx, |
| 2734 | search.deadzone, |
| 2735 | chroma_set, |
| 2736 | ); |
| 2737 | let v = mc_trial( |
| 2738 | &chroma[1], |
| 2739 | x / 2, |
| 2740 | y / 2, |
| 2741 | BLOCK / 2, |
| 2742 | mv, |
| 2743 | false, |
| 2744 | ref_v.0, |
| 2745 | ref_v.1, |
| 2746 | ref_v.2, |
| 2747 | ref_v.3, |
| 2748 | false, |
| 2749 | search.base_q_idx, |
| 2750 | search.deadzone, |
| 2751 | chroma_set, |
| 2752 | ); |
| 2753 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 2754 | && u.levels.iter().all(|&l| l == 0) |
| 2755 | && v.levels.iter().all(|&l| l == 0); |
| 2756 | let cost = luma_trial.sse |
| 2757 | + u.sse |
| 2758 | + v.sse |
| 2759 | + search.lambda |
| 2760 | * (skip_bits(skip) |
| 2761 | + intra_inter_bits(true) |
| 2762 | + single_ref_bits |
| 2763 | + mode_bits_inter |
| 2764 | + if skip { |
| 2765 | 0.0 |
| 2766 | } else { |
| 2767 | luma_trial.bits + u.bits + v.bits |
| 2768 | }); |
| 2769 | consider(Candidate { |
| 2770 | cost, |
| 2771 | luma: luma_trial, |
| 2772 | u, |
| 2773 | v, |
| 2774 | mode: DC_PRED, |
| 2775 | skip, |
| 2776 | inter: Some(InterInfo { |
| 2777 | mode: InterMode::NearestMv, |
| 2778 | mv, |
| 2779 | }), |
| 2780 | }); |
| 2781 | } |
| 2782 | |
| 2783 | let source_block = luma.source_block(x, y, BLOCK); |
| 2784 | |
| 2785 | |
| 2786 | let ref_luma_8: Vec<u8> = ref_luma.0.iter().map(|&v| v as u8).collect(); |
| 2787 | #[cfg(test)] |
| 2788 | let t = std::time::Instant::now(); |
| 2789 | let found = motion::search( |
| 2790 | &ref_luma_8, |
| 2791 | ref_luma.1, |
| 2792 | ref_luma.2, |
| 2793 | ref_luma.3, |
| 2794 | &source_block, |
| 2795 | x, |
| 2796 | y, |
| 2797 | BLOCK, |
| 2798 | BLOCK, |
| 2799 | stack.pred_mv, |
| 2800 | search.lambda, |
| 2801 | ); |
| 2802 | #[cfg(test)] |
| 2803 | stage_add(0, t.elapsed()); |
| 2804 | let mv = round_to_valid_mv(found.mv, stack.pred_mv); |
| 2805 | if let Some(mv_bits) = mv_residual_bits(mv, stack.pred_mv) { |
| 2806 | let luma_trial = mc_trial( |
| 2807 | luma, |
| 2808 | x, |
| 2809 | y, |
| 2810 | BLOCK, |
| 2811 | mv, |
| 2812 | true, |
| 2813 | ref_luma.0, |
| 2814 | ref_luma.1, |
| 2815 | ref_luma.2, |
| 2816 | ref_luma.3, |
| 2817 | false, |
| 2818 | search.base_q_idx, |
| 2819 | search.deadzone, |
| 2820 | luma_set, |
| 2821 | ); |
| 2822 | let u = mc_trial( |
| 2823 | &chroma[0], |
| 2824 | x / 2, |
| 2825 | y / 2, |
| 2826 | BLOCK / 2, |
| 2827 | mv, |
| 2828 | false, |
| 2829 | ref_u.0, |
| 2830 | ref_u.1, |
| 2831 | ref_u.2, |
| 2832 | ref_u.3, |
| 2833 | false, |
| 2834 | search.base_q_idx, |
| 2835 | search.deadzone, |
| 2836 | chroma_set, |
| 2837 | ); |
| 2838 | let v = mc_trial( |
| 2839 | &chroma[1], |
| 2840 | x / 2, |
| 2841 | y / 2, |
| 2842 | BLOCK / 2, |
| 2843 | mv, |
| 2844 | false, |
| 2845 | ref_v.0, |
| 2846 | ref_v.1, |
| 2847 | ref_v.2, |
| 2848 | ref_v.3, |
| 2849 | false, |
| 2850 | search.base_q_idx, |
| 2851 | search.deadzone, |
| 2852 | chroma_set, |
| 2853 | ); |
| 2854 | let drl_bits = if stack.entries.len() > 1 { |
| 2855 | symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0) |
| 2856 | } else { |
| 2857 | 0.0 |
| 2858 | }; |
| 2859 | let skip = luma_trial.levels.iter().all(|&l| l == 0) |
| 2860 | && u.levels.iter().all(|&l| l == 0) |
| 2861 | && v.levels.iter().all(|&l| l == 0); |
| 2862 | let cost = luma_trial.sse |
| 2863 | + u.sse |
| 2864 | + v.sse |
| 2865 | + search.lambda |
| 2866 | * (skip_bits(skip) |
| 2867 | + intra_inter_bits(true) |
| 2868 | + single_ref_bits |
| 2869 | + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) |
| 2870 | + drl_bits |
| 2871 | + mv_bits |
| 2872 | + if skip { |
| 2873 | 0.0 |
| 2874 | } else { |
| 2875 | luma_trial.bits + u.bits + v.bits |
| 2876 | }); |
| 2877 | consider(Candidate { |
| 2878 | cost, |
| 2879 | luma: luma_trial, |
| 2880 | u, |
| 2881 | v, |
| 2882 | mode: DC_PRED, |
| 2883 | skip, |
| 2884 | inter: Some(InterInfo { |
| 2885 | mode: InterMode::NewMv, |
| 2886 | mv, |
| 2887 | }), |
| 2888 | }); |
| 2889 | } |
| 2890 | |
| 2891 | let best = best.expect("the search offers at least the intra modes"); |
| 2892 | luma.commit(x, y, BLOCK, &best.luma); |
| 2893 | chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u); |
| 2894 | chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v); |
| 2895 | BlockCoeffs { |
| 2896 | luma: coeffs(&best.luma.levels, BLOCK), |
| 2897 | u: coeffs(&best.u.levels, BLOCK / 2), |
| 2898 | v: coeffs(&best.v.levels, BLOCK / 2), |
| 2899 | mode: best.mode, |
| 2900 | skip: best.skip, |
| 2901 | inter: best.inter, |
| 2902 | eight: None, |
| 2903 | } |
| 2904 | } |
| 2905 | |
| 2906 | |
| 2907 | |
| 2908 | |
| 2909 | pub(crate) fn encode_inter_frame( |
| 2910 | picture: &Picture, |
| 2911 | reference: &Picture, |
| 2912 | base_q_idx: u8, |
| 2913 | deadzone: f64, |
| 2914 | order_hint: u32, |
| 2915 | render: (usize, usize), |
| 2916 | ) -> Result<Encoded> { |
| 2917 | picture.check()?; |
| 2918 | if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) { |
| 2919 | return Err(Error::unsupported( |
| 2920 | "AV1 encode", |
| 2921 | "an inter frame is coded only for a picture that is a whole number \ |
| 2922 | of 64x64 superblocks -- the inter tile writer never splits a \ |
| 2923 | superblock's partition below that", |
| 2924 | )); |
| 2925 | } |
| 2926 | if reference.width != picture.width || reference.height != picture.height { |
| 2927 | return Err(Error::unsupported( |
| 2928 | "AV1 encode", |
| 2929 | "the reference picture must be the same size as the one being coded", |
| 2930 | )); |
| 2931 | } |
| 2932 | |
| 2933 | |
| 2934 | |
| 2935 | |
| 2936 | |
| 2937 | const LAST_SLOT: u8 = 0; |
| 2938 | |
| 2939 | |
| 2940 | |
| 2941 | |
| 2942 | |
| 2943 | |
| 2944 | let (seq, mut header) = |
| 2945 | inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?; |
| 2946 | header.render_width = render.0 as u32; |
| 2947 | header.render_height = render.1 as u32; |
| 2948 | |
| 2949 | let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4); |
| 2950 | |
| 2951 | |
| 2952 | let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect(); |
| 2953 | let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect(); |
| 2954 | let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect(); |
| 2955 | let mut luma = Plane { |
| 2956 | source: &picture_y8, |
| 2957 | reconstruction: vec![128; picture_y8.len()], |
| 2958 | width: picture.width, |
| 2959 | height: picture.height, |
| 2960 | true_width, |
| 2961 | true_height, |
| 2962 | }; |
| 2963 | let mut chroma = [ |
| 2964 | Plane { |
| 2965 | source: &picture_u8, |
| 2966 | reconstruction: vec![128; picture_u8.len()], |
| 2967 | width: picture.width / 2, |
| 2968 | height: picture.height / 2, |
| 2969 | true_width: true_width / 2, |
| 2970 | true_height: true_height / 2, |
| 2971 | }, |
| 2972 | Plane { |
| 2973 | source: &picture_v8, |
| 2974 | reconstruction: vec![128; picture_v8.len()], |
| 2975 | width: picture.width / 2, |
| 2976 | height: picture.height / 2, |
| 2977 | true_width: true_width / 2, |
| 2978 | true_height: true_height / 2, |
| 2979 | }, |
| 2980 | ]; |
| 2981 | |
| 2982 | let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0; |
| 2983 | let search = Search { |
| 2984 | base_q_idx, |
| 2985 | deadzone, |
| 2986 | lambda: lambda_scale() * step * step, |
| 2987 | modes: &KEY_FRAME_MODES, |
| 2988 | top_k: prune_top_k_inter(), |
| 2989 | }; |
| 2990 | let mode_bits_table = inter_mode_bits(); |
| 2991 | |
| 2992 | |
| 2993 | |
| 2994 | |
| 2995 | |
| 2996 | |
| 2997 | let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows); |
| 2998 | let (cols, rows) = (cols as usize, rows as usize); |
| 2999 | let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2)); |
| 3000 | let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize); |
| 3001 | let mut grid = MiGrid::new(mi_cols, mi_rows); |
| 3002 | let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows]; |
| 3003 | |
| 3004 | for sb_r in 0..sb_rows { |
| 3005 | for sb_c in 0..sb_cols { |
| 3006 | for quadrant in 0..4 { |
| 3007 | let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2); |
| 3008 | |
| 3009 | |
| 3010 | if r32 >= rows || c32 >= cols { |
| 3011 | continue; |
| 3012 | } |
| 3013 | |
| 3014 | |
| 3015 | |
| 3016 | |
| 3017 | |
| 3018 | |
| 3019 | |
| 3020 | |
| 3021 | let (has_cols32, has_rows32) = ( |
| 3022 | crate::tile::has_half( |
| 3023 | c32 as u32 * crate::tile::BLOCK_MI, |
| 3024 | crate::tile::BLOCK_MI, |
| 3025 | header.mi_cols, |
| 3026 | ), |
| 3027 | crate::tile::has_half( |
| 3028 | r32 as u32 * crate::tile::BLOCK_MI, |
| 3029 | crate::tile::BLOCK_MI, |
| 3030 | header.mi_rows, |
| 3031 | ), |
| 3032 | ); |
| 3033 | if has_cols32 && has_rows32 { |
| 3034 | let (x, y) = (c32 * BLOCK, r32 * BLOCK); |
| 3035 | let (mi_row, mi_col) = (r32 * 8, c32 * 8); |
| 3036 | let stack = |
| 3037 | find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows); |
| 3038 | |
| 3039 | let block = search_inter_block( |
| 3040 | &mut luma, |
| 3041 | &mut chroma, |
| 3042 | (x, y), |
| 3043 | &search, |
| 3044 | &mode_bits_table, |
| 3045 | reference, |
| 3046 | &stack, |
| 3047 | ); |
| 3048 | |
| 3049 | for dr in 0..8 { |
| 3050 | for dc in 0..8 { |
| 3051 | grid.set( |
| 3052 | mi_row + dr, |
| 3053 | mi_col + dc, |
| 3054 | match block.inter { |
| 3055 | Some(info) => MiInfo { |
| 3056 | is_inter: true, |
| 3057 | ref_frame: LAST_FRAME, |
| 3058 | ref_frame1: None, |
| 3059 | mv1: None, |
| 3060 | mv: info.mv, |
| 3061 | is_new_mv: matches!(info.mode, InterMode::NewMv), |
| 3062 | size: 8, |
| 3063 | size_h: 8, |
| 3064 | is_global_mv0: false, |
| 3065 | is_global_mv1: false, |
| 3066 | }, |
| 3067 | |
| 3068 | |
| 3069 | |
| 3070 | |
| 3071 | None => MiInfo { |
| 3072 | is_inter: false, |
| 3073 | ref_frame: -1, |
| 3074 | ref_frame1: None, |
| 3075 | mv1: None, |
| 3076 | mv: (0, 0), |
| 3077 | is_new_mv: false, |
| 3078 | size: 8, |
| 3079 | size_h: 8, |
| 3080 | is_global_mv0: false, |
| 3081 | is_global_mv1: false, |
| 3082 | }, |
| 3083 | }, |
| 3084 | ); |
| 3085 | } |
| 3086 | } |
| 3087 | blocks[r32 * cols + c32] = Quadrant::Whole(block); |
| 3088 | } else { |
| 3089 | |
| 3090 | |
| 3091 | let sub_positions: Vec<(usize, usize)> = (0..4) |
| 3092 | .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2)) |
| 3093 | .filter(|&(sr, sc)| { |
| 3094 | (sr as u32) * crate::tile::SUB_MI < header.mi_rows |
| 3095 | && (sc as u32) * crate::tile::SUB_MI < header.mi_cols |
| 3096 | }) |
| 3097 | .collect(); |
| 3098 | |
| 3099 | |
| 3100 | |
| 3101 | |
| 3102 | |
| 3103 | |
| 3104 | |
| 3105 | |
| 3106 | |
| 3107 | let mut leaves = Vec::with_capacity(sub_positions.len()); |
| 3108 | for (sr, sc) in sub_positions { |
| 3109 | let (has_cols16, has_rows16) = ( |
| 3110 | crate::tile::has_half( |
| 3111 | sc as u32 * crate::tile::SUB_MI, |
| 3112 | crate::tile::SUB_MI, |
| 3113 | header.mi_cols, |
| 3114 | ), |
| 3115 | crate::tile::has_half( |
| 3116 | sr as u32 * crate::tile::SUB_MI, |
| 3117 | crate::tile::SUB_MI, |
| 3118 | header.mi_rows, |
| 3119 | ), |
| 3120 | ); |
| 3121 | if !has_cols16 && !has_rows16 { |
| 3122 | return Err(Error::unsupported( |
| 3123 | "AV1 encode", |
| 3124 | format!( |
| 3125 | "the 16x16 block at ({sc},{sr}) straddles the true \ |
| 3126 | frame edge in a way that needs a rectangular \ |
| 3127 | (HORZ/VERT) transform this encoder does not code yet" |
| 3128 | ), |
| 3129 | )); |
| 3130 | } |
| 3131 | if has_cols16 && has_rows16 { |
| 3132 | let (x, y) = (sc * SUB, sr * SUB); |
| 3133 | let (mi_row, mi_col) = (sr * 4, sc * 4); |
| 3134 | let stack = find_mv_stack( |
| 3135 | &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows, |
| 3136 | ); |
| 3137 | let block = code_square_inter( |
| 3138 | &mut luma, |
| 3139 | &mut chroma, |
| 3140 | (x, y), |
| 3141 | SUB, |
| 3142 | &search, |
| 3143 | &mode_bits_table, |
| 3144 | reference, |
| 3145 | &stack, |
| 3146 | ); |
| 3147 | for dr in 0..4 { |
| 3148 | for dc in 0..4 { |
| 3149 | grid.set( |
| 3150 | mi_row + dr, |
| 3151 | mi_col + dc, |
| 3152 | match block.inter { |
| 3153 | Some(info) => MiInfo { |
| 3154 | is_inter: true, |
| 3155 | ref_frame: LAST_FRAME, |
| 3156 | ref_frame1: None, |
| 3157 | mv1: None, |
| 3158 | mv: info.mv, |
| 3159 | is_new_mv: matches!(info.mode, InterMode::NewMv), |
| 3160 | size: 4, |
| 3161 | size_h: 4, |
| 3162 | is_global_mv0: false, |
| 3163 | is_global_mv1: false, |
| 3164 | }, |
| 3165 | None => MiInfo { |
| 3166 | is_inter: false, |
| 3167 | ref_frame: -1, |
| 3168 | ref_frame1: None, |
| 3169 | mv1: None, |
| 3170 | mv: (0, 0), |
| 3171 | is_new_mv: false, |
| 3172 | size: 4, |
| 3173 | size_h: 4, |
| 3174 | is_global_mv0: false, |
| 3175 | is_global_mv1: false, |
| 3176 | }, |
| 3177 | }, |
| 3178 | ); |
| 3179 | } |
| 3180 | } |
| 3181 | leaves.push(block); |
| 3182 | } else { |
| 3183 | let (x_sub, y_sub) = (sc * SUB, sr * SUB); |
| 3184 | let (mi_row0, mi_col0) = (sr * 4, sc * 4); |
| 3185 | let mut eight = Vec::with_capacity(2); |
| 3186 | for i in 0..4 { |
| 3187 | let leaf_x = x_sub + (i % 2) * 8; |
| 3188 | let leaf_y = y_sub + (i / 2) * 8; |
| 3189 | if leaf_x >= luma.true_width || leaf_y >= luma.true_height { |
| 3190 | continue; |
| 3191 | } |
| 3192 | let (mi_row, mi_col) = |
| 3193 | (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2); |
| 3194 | let stack = find_mv_stack( |
| 3195 | &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows, |
| 3196 | ); |
| 3197 | let leaf = code_square_inter( |
| 3198 | &mut luma, |
| 3199 | &mut chroma, |
| 3200 | (leaf_x, leaf_y), |
| 3201 | 8, |
| 3202 | &search, |
| 3203 | &mode_bits_table, |
| 3204 | reference, |
| 3205 | &stack, |
| 3206 | ); |
| 3207 | for dr in 0..2 { |
| 3208 | for dc in 0..2 { |
| 3209 | grid.set( |
| 3210 | mi_row + dr, |
| 3211 | mi_col + dc, |
| 3212 | match leaf.inter { |
| 3213 | Some(info) => MiInfo { |
| 3214 | is_inter: true, |
| 3215 | ref_frame: LAST_FRAME, |
| 3216 | ref_frame1: None, |
| 3217 | mv1: None, |
| 3218 | mv: info.mv, |
| 3219 | is_new_mv: matches!( |
| 3220 | info.mode, |
| 3221 | InterMode::NewMv |
| 3222 | ), |
| 3223 | size: 2, |
| 3224 | size_h: 2, |
| 3225 | is_global_mv0: false, |
| 3226 | is_global_mv1: false, |
| 3227 | }, |
| 3228 | None => MiInfo { |
| 3229 | is_inter: false, |
| 3230 | ref_frame: -1, |
| 3231 | ref_frame1: None, |
| 3232 | mv1: None, |
| 3233 | mv: (0, 0), |
| 3234 | is_new_mv: false, |
| 3235 | size: 2, |
| 3236 | size_h: 2, |
| 3237 | is_global_mv0: false, |
| 3238 | is_global_mv1: false, |
| 3239 | }, |
| 3240 | }, |
| 3241 | ); |
| 3242 | } |
| 3243 | } |
| 3244 | eight.push(leaf); |
| 3245 | } |
| 3246 | leaves.push(BlockCoeffs { |
| 3247 | eight: Some(eight), |
| 3248 | ..BlockCoeffs::default() |
| 3249 | }); |
| 3250 | } |
| 3251 | } |
| 3252 | blocks[r32 * cols + c32] = Quadrant::Split(leaves); |
| 3253 | } |
| 3254 | } |
| 3255 | } |
| 3256 | } |
| 3257 | |
| 3258 | let modes = blocks |
| 3259 | .iter() |
| 3260 | .flat_map(Quadrant::blocks) |
| 3261 | .map(|b| b.mode) |
| 3262 | .collect::<Vec<_>>(); |
| 3263 | let inter_block_share = blocks |
| 3264 | .iter() |
| 3265 | .flat_map(Quadrant::blocks) |
| 3266 | .filter(|b| b.inter.is_some()) |
| 3267 | .count() as f64 |
| 3268 | / modes.len() as f64; |
| 3269 | let tile = sb_coeff_inter_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &blocks)?; |
| 3270 | let mut stream = temporal_delimiter(); |
| 3271 | stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?); |
| 3272 | |
| 3273 | let [u, v] = chroma; |
| 3274 | Ok(Encoded { |
| 3275 | stream, |
| 3276 | modes, |
| 3277 | inter_block_share, |
| 3278 | reconstruction: Picture { |
| 3279 | width: luma.width, |
| 3280 | height: luma.height, |
| 3281 | y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 3282 | u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 3283 | v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(), |
| 3284 | }, |
| 3285 | tile, |
| 3286 | mi_cols: header.mi_cols, |
| 3287 | mi_rows: header.mi_rows, |
| 3288 | base_q_idx, |
| 3289 | }) |
| 3290 | } |
| 3291 | |
| 3292 | |
| 3293 | |
| 3294 | |
| 3295 | |
| 3296 | #[derive(Clone, Debug)] |
| 3297 | pub struct EncodedSequence { |
| 3298 | |
| 3299 | |
| 3300 | |
| 3301 | |
| 3302 | pub stream: Vec<u8>, |
| 3303 | |
| 3304 | pub frames: Vec<Encoded>, |
| 3305 | } |
| 3306 | |
| 3307 | |
| 3308 | |
| 3309 | |
| 3310 | |
| 3311 | |
| 3312 | |
| 3313 | |
| 3314 | |
| 3315 | |
| 3316 | |
| 3317 | |
| 3318 | |
| 3319 | pub fn encode_sequence( |
| 3320 | pictures: &[Picture], |
| 3321 | base_q_idx: u8, |
| 3322 | deadzone: f64, |
| 3323 | ) -> Result<EncodedSequence> { |
| 3324 | let Some((first, rest)) = pictures.split_first() else { |
| 3325 | return Err(Error::unsupported( |
| 3326 | "AV1 encode", |
| 3327 | "a sequence needs at least one picture", |
| 3328 | )); |
| 3329 | }; |
| 3330 | first.check_even()?; |
| 3331 | let render = (first.width, first.height); |
| 3332 | |
| 3333 | |
| 3334 | |
| 3335 | |
| 3336 | |
| 3337 | let key = encode_key_frame_inner( |
| 3338 | &first.padded_to(SUPERBLOCK), |
| 3339 | base_q_idx, |
| 3340 | deadzone, |
| 3341 | &KEY_FRAME_MODES, |
| 3342 | split_blocks(), |
| 3343 | render, |
| 3344 | unspecified_color_config(), |
| 3345 | )?; |
| 3346 | let mut stream = key.stream.clone(); |
| 3347 | let mut reference = key.reconstruction.clone(); |
| 3348 | let mut frames = vec![crop_encoded(&key, render.0, render.1)]; |
| 3349 | for (i, picture) in rest.iter().enumerate() { |
| 3350 | picture.check_even()?; |
| 3351 | if (picture.width, picture.height) != render { |
| 3352 | return Err(Error::unsupported( |
| 3353 | "AV1 encode", |
| 3354 | "every picture in a sequence must be the same size as the first", |
| 3355 | )); |
| 3356 | } |
| 3357 | let order_hint = (i + 1) as u32; |
| 3358 | let inter = encode_inter_frame( |
| 3359 | &picture.padded_to(SUPERBLOCK), |
| 3360 | &reference, |
| 3361 | base_q_idx, |
| 3362 | deadzone, |
| 3363 | order_hint, |
| 3364 | render, |
| 3365 | )?; |
| 3366 | stream.extend_from_slice(&inter.stream); |
| 3367 | reference = inter.reconstruction.clone(); |
| 3368 | frames.push(crop_encoded(&inter, render.0, render.1)); |
| 3369 | } |
| 3370 | Ok(EncodedSequence { stream, frames }) |
| 3371 | } |
| 3372 | |
| 3373 | #[cfg(test)] |
| 3374 | mod tests { |
| 3375 | |
| 3376 | |
| 3377 | |
| 3378 | |
| 3379 | |
| 3380 | |
| 3381 | |
| 3382 | |
| 3383 | |
| 3384 | |
| 3385 | #[test] |
| 3386 | fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() { |
| 3387 | for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 3388 | let (bw_log2, bh_log2) = |
| 3389 | ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize); |
| 3390 | let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2); |
| 3391 | for (name, table) in |
| 3392 | [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)] |
| 3393 | { |
| 3394 | assert_eq!( |
| 3395 | table.len() * 8, |
| 3396 | rows * cols, |
| 3397 | "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits" |
| 3398 | ); |
| 3399 | let mut seen = vec![0u32; table.len() * 8]; |
| 3400 | for blk_row in 0..rows { |
| 3401 | for blk_col in 0..cols { |
| 3402 | let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col); |
| 3403 | assert!( |
| 3404 | idx < seen.len(), |
| 3405 | "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})" |
| 3406 | ); |
| 3407 | seen[idx] += 1; |
| 3408 | } |
| 3409 | } |
| 3410 | assert!( |
| 3411 | seen.iter().all(|&n| n == 1), |
| 3412 | "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \ |
| 3413 | (row stride is not {cols})" |
| 3414 | ); |
| 3415 | } |
| 3416 | } |
| 3417 | } |
| 3418 | use super::*; |
| 3419 | use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED}; |
| 3420 | use std::io::Write; |
| 3421 | use std::process::{Command, Stdio}; |
| 3422 | |
| 3423 | |
| 3424 | |
| 3425 | |
| 3426 | |
| 3427 | |
| 3428 | |
| 3429 | |
| 3430 | |
| 3431 | |
| 3432 | |
| 3433 | |
| 3434 | |
| 3435 | |
| 3436 | |
| 3437 | |
| 3438 | |
| 3439 | |
| 3440 | |
| 3441 | |
| 3442 | |
| 3443 | #[test] |
| 3444 | fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() { |
| 3445 | |
| 3446 | const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [ |
| 3447 | (4, 8, 64, 9280, 64, 550), |
| 3448 | (8, 4, 64, 3712, 64, 9630), |
| 3449 | (8, 16, 16, 2352, 16, 134), |
| 3450 | (16, 8, 16, 960, 16, 2400), |
| 3451 | (16, 32, 4, 620, 4, 32), |
| 3452 | (32, 16, 4, 32, 4, 184), |
| 3453 | (32, 64, 1, 127, 1, 0), |
| 3454 | (64, 32, 1, 19, 1, 34), |
| 3455 | (4, 16, 32, 5472, 32, 14), |
| 3456 | (16, 4, 32, 960, 32, 6464), |
| 3457 | (8, 32, 8, 1400, 8, 2), |
| 3458 | (32, 8, 8, 32, 8, 1136), |
| 3459 | (16, 64, 2, 382, 2, 0), |
| 3460 | (64, 16, 2, 4, 2, 84), |
| 3461 | ]; |
| 3462 | |
| 3463 | |
| 3464 | |
| 3465 | |
| 3466 | fn libaom_reach( |
| 3467 | bw: usize, |
| 3468 | bh: usize, |
| 3469 | x: usize, |
| 3470 | y: usize, |
| 3471 | width: usize, |
| 3472 | height: usize, |
| 3473 | ) -> (bool, bool) { |
| 3474 | let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize); |
| 3475 | let (_bw_unit, bh_unit) = (bw / 4, bh / 4); |
| 3476 | let sb_mi_size = 16usize; |
| 3477 | let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2; |
| 3478 | let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2; |
| 3479 | let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb; |
| 3480 | let (tr_table, bl_table) = rect_reach_tables(bw, bh); |
| 3481 | let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0; |
| 3482 | |
| 3483 | let top_right = if y == 0 || x + bw >= width { |
| 3484 | false |
| 3485 | } else if blk_row_in_sb == 0 { |
| 3486 | |
| 3487 | |
| 3488 | true |
| 3489 | } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size { |
| 3490 | false |
| 3491 | } else { |
| 3492 | bit(tr_table) |
| 3493 | }; |
| 3494 | |
| 3495 | let bottom_left = if x == 0 || y + bh >= height { |
| 3496 | false |
| 3497 | } else if blk_col_in_sb == 0 { |
| 3498 | |
| 3499 | (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size |
| 3500 | } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size { |
| 3501 | false |
| 3502 | } else { |
| 3503 | bit(bl_table) |
| 3504 | }; |
| 3505 | (top_right, bottom_left) |
| 3506 | } |
| 3507 | for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES { |
| 3508 | let (tr, bl) = rect_reach_tables(bw, bh); |
| 3509 | let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>(); |
| 3510 | assert_eq!( |
| 3511 | (tr.len(), sum(tr), bl.len(), sum(bl)), |
| 3512 | (tr_len, tr_sum, bl_len, bl_sum), |
| 3513 | "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}" |
| 3514 | ); |
| 3515 | |
| 3516 | |
| 3517 | for sb_y in [0usize, 64] { |
| 3518 | for sb_x in [0usize, 64] { |
| 3519 | for y in (sb_y..sb_y + 64).step_by(bh) { |
| 3520 | for x in (sb_x..sb_x + 64).step_by(bw) { |
| 3521 | let got = Reach::of_rect(bw, bh, x, y, 256, 256); |
| 3522 | let want = libaom_reach(bw, bh, x, y, 256, 256); |
| 3523 | assert_eq!( |
| 3524 | (got.above_right, got.below_left), |
| 3525 | want, |
| 3526 | "{bw}x{bh} at ({x}, {y})" |
| 3527 | ); |
| 3528 | } |
| 3529 | } |
| 3530 | } |
| 3531 | } |
| 3532 | } |
| 3533 | } |
| 3534 | |
| 3535 | |
| 3536 | |
| 3537 | |
| 3538 | |
| 3539 | |
| 3540 | |
| 3541 | |
| 3542 | fn have_ffmpeg() -> bool { |
| 3543 | let present = Command::new("ffmpeg") |
| 3544 | .arg("-version") |
| 3545 | .stdout(Stdio::null()) |
| 3546 | .stderr(Stdio::null()) |
| 3547 | .status() |
| 3548 | .is_ok_and(|s| s.success()); |
| 3549 | assert!( |
| 3550 | present |
| 3551 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 3552 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 3553 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 3554 | ); |
| 3555 | present |
| 3556 | } |
| 3557 | |
| 3558 | |
| 3559 | fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture { |
| 3560 | let mut child = Command::new("ffmpeg") |
| 3561 | .args([ |
| 3562 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 3563 | ]) |
| 3564 | .stdin(Stdio::piped()) |
| 3565 | .stdout(Stdio::piped()) |
| 3566 | .stderr(Stdio::piped()) |
| 3567 | .spawn() |
| 3568 | .expect("ffmpeg failed to start"); |
| 3569 | |
| 3570 | |
| 3571 | |
| 3572 | |
| 3573 | |
| 3574 | |
| 3575 | |
| 3576 | let mut stdin = child.stdin.take().expect("ffmpeg stdin"); |
| 3577 | let payload = stream.to_vec(); |
| 3578 | let writer = std::thread::spawn(move || { |
| 3579 | let _ = stdin.write_all(&payload); |
| 3580 | }); |
| 3581 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 3582 | writer.join().expect("ffmpeg stdin writer thread"); |
| 3583 | assert!( |
| 3584 | out.status.success(), |
| 3585 | "ffmpeg refused the stream: {}", |
| 3586 | String::from_utf8_lossy(&out.stderr) |
| 3587 | ); |
| 3588 | let (luma, chroma) = (width * height, width * height / 4); |
| 3589 | assert_eq!( |
| 3590 | out.stdout.len(), |
| 3591 | luma + 2 * chroma, |
| 3592 | "expected one 4:2:0 frame" |
| 3593 | ); |
| 3594 | Picture { |
| 3595 | width, |
| 3596 | height, |
| 3597 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 3598 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 3599 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 3600 | } |
| 3601 | } |
| 3602 | |
| 3603 | |
| 3604 | |
| 3605 | |
| 3606 | fn test_card(width: usize, height: usize) -> Picture { |
| 3607 | let mut picture = Picture::grey(width, height); |
| 3608 | for y in 0..height { |
| 3609 | for x in 0..width { |
| 3610 | let gradient = x as f64 * 200.0 / width as f64; |
| 3611 | let ripple = 30.0 |
| 3612 | * (x as f64 * std::f64::consts::PI / 23.0).sin() |
| 3613 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 3614 | let edge = if x > width * 3 / 7 && y > height / 3 { |
| 3615 | 40.0 |
| 3616 | } else { |
| 3617 | 0.0 |
| 3618 | }; |
| 3619 | picture.y[y * width + x] = |
| 3620 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 3621 | } |
| 3622 | } |
| 3623 | for y in 0..height / 2 { |
| 3624 | for x in 0..width / 2 { |
| 3625 | let i = y * width / 2 + x; |
| 3626 | picture.u[i] = (100 + (x * 60 / (width / 2))) as u16; |
| 3627 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 3628 | } |
| 3629 | } |
| 3630 | picture |
| 3631 | } |
| 3632 | |
| 3633 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 3634 | let squared: f64 = a |
| 3635 | .iter() |
| 3636 | .zip(b) |
| 3637 | .map(|(&x, &y)| { |
| 3638 | let d = f64::from(x) - f64::from(y); |
| 3639 | d * d |
| 3640 | }) |
| 3641 | .sum(); |
| 3642 | if squared == 0.0 { |
| 3643 | return f64::INFINITY; |
| 3644 | } |
| 3645 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 3646 | } |
| 3647 | |
| 3648 | |
| 3649 | |
| 3650 | |
| 3651 | |
| 3652 | |
| 3653 | |
| 3654 | #[test] |
| 3655 | fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() { |
| 3656 | if !have_ffmpeg() { |
| 3657 | eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg"); |
| 3658 | return; |
| 3659 | } |
| 3660 | for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] { |
| 3661 | let picture = test_card(width, height); |
| 3662 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 3663 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 3664 | assert_eq!( |
| 3665 | decoded.y, encoded.reconstruction.y, |
| 3666 | "{width}x{height}: luma" |
| 3667 | ); |
| 3668 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 3669 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 3670 | } |
| 3671 | |
| 3672 | |
| 3673 | let (width, height) = (64usize, 64usize); |
| 3674 | let picture = test_card(width, height); |
| 3675 | for &q in &[15u8, 45, 100, 200] { |
| 3676 | let encoded = encode_key_frame(&picture, q, 0.5).unwrap(); |
| 3677 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 3678 | assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma"); |
| 3679 | assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U"); |
| 3680 | assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V"); |
| 3681 | } |
| 3682 | } |
| 3683 | |
| 3684 | |
| 3685 | |
| 3686 | |
| 3687 | |
| 3688 | |
| 3689 | |
| 3690 | |
| 3691 | |
| 3692 | #[test] |
| 3693 | fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() { |
| 3694 | if !have_ffmpeg() { |
| 3695 | eprintln!( |
| 3696 | "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg" |
| 3697 | ); |
| 3698 | return; |
| 3699 | } |
| 3700 | let (width, height) = (64usize, 64usize); |
| 3701 | let picture = Picture::grey(width, height); |
| 3702 | let key = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 3703 | |
| 3704 | let (seq, _) = key_frame_headers(width, height, 100).unwrap(); |
| 3705 | let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap(); |
| 3706 | |
| 3707 | let residual_block = BlockCoeffs { |
| 3708 | luma: vec![Coeff { |
| 3709 | row: 0, |
| 3710 | col: 0, |
| 3711 | level: 4, |
| 3712 | }], |
| 3713 | u: Vec::new(), |
| 3714 | v: Vec::new(), |
| 3715 | mode: 0, |
| 3716 | skip: false, |
| 3717 | eight: None, |
| 3718 | inter: Some(InterInfo { |
| 3719 | mode: InterMode::NearestMv, |
| 3720 | mv: (0, 0), |
| 3721 | }), |
| 3722 | }; |
| 3723 | let skipped_block = BlockCoeffs { |
| 3724 | skip: true, |
| 3725 | inter: Some(InterInfo { |
| 3726 | mode: InterMode::NearestMv, |
| 3727 | mv: (0, 0), |
| 3728 | }), |
| 3729 | ..BlockCoeffs::default() |
| 3730 | }; |
| 3731 | let blocks = vec![ |
| 3732 | Quadrant::Whole(residual_block), |
| 3733 | Quadrant::Whole(skipped_block.clone()), |
| 3734 | Quadrant::Whole(skipped_block.clone()), |
| 3735 | Quadrant::Whole(skipped_block), |
| 3736 | ]; |
| 3737 | let tile = |
| 3738 | sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks) |
| 3739 | .unwrap(); |
| 3740 | |
| 3741 | |
| 3742 | |
| 3743 | |
| 3744 | |
| 3745 | |
| 3746 | let mut stream = key.stream.clone(); |
| 3747 | stream.extend_from_slice(&temporal_delimiter()); |
| 3748 | stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap()); |
| 3749 | |
| 3750 | ffmpeg_decode_sequence(&stream, width, height, 2); |
| 3751 | } |
| 3752 | |
| 3753 | |
| 3754 | |
| 3755 | |
| 3756 | fn ffprobe_size(stream: &[u8]) -> (u32, u32) { |
| 3757 | |
| 3758 | |
| 3759 | |
| 3760 | static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); |
| 3761 | let path = std::env::temp_dir().join(format!( |
| 3762 | "ec-av1-probe-{}-{}.obu", |
| 3763 | std::process::id(), |
| 3764 | PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) |
| 3765 | )); |
| 3766 | let _ = std::fs::remove_file(&path); |
| 3767 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 3768 | let out = Command::new("ffprobe") |
| 3769 | .args([ |
| 3770 | "-v", |
| 3771 | "error", |
| 3772 | "-f", |
| 3773 | "obu", |
| 3774 | "-select_streams", |
| 3775 | "v:0", |
| 3776 | "-show_entries", |
| 3777 | "stream=width,height", |
| 3778 | "-of", |
| 3779 | "csv=p=0", |
| 3780 | ]) |
| 3781 | .arg(&path) |
| 3782 | .output() |
| 3783 | .expect("ffprobe failed to run"); |
| 3784 | let _ = std::fs::remove_file(&path); |
| 3785 | assert!( |
| 3786 | out.status.success(), |
| 3787 | "ffprobe refused the stream: {}", |
| 3788 | String::from_utf8_lossy(&out.stderr) |
| 3789 | ); |
| 3790 | let text = String::from_utf8_lossy(&out.stdout); |
| 3791 | let mut fields = text.trim().split(','); |
| 3792 | let width: u32 = fields.next().expect("ffprobe width").parse().unwrap(); |
| 3793 | let height: u32 = fields.next().expect("ffprobe height").parse().unwrap(); |
| 3794 | (width, height) |
| 3795 | } |
| 3796 | |
| 3797 | |
| 3798 | |
| 3799 | |
| 3800 | |
| 3801 | |
| 3802 | |
| 3803 | |
| 3804 | |
| 3805 | |
| 3806 | |
| 3807 | |
| 3808 | |
| 3809 | |
| 3810 | |
| 3811 | #[test] |
| 3812 | fn a_frame_round_trips_at_its_own_size() { |
| 3813 | if !have_ffmpeg() { |
| 3814 | eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg"); |
| 3815 | return; |
| 3816 | } |
| 3817 | |
| 3818 | |
| 3819 | |
| 3820 | for &(width, height) in &[ |
| 3821 | (1920usize, 1080usize), |
| 3822 | (640, 352), |
| 3823 | (1280, 720), |
| 3824 | (64, 56), |
| 3825 | (854, 480), |
| 3826 | (216, 96), |
| 3827 | (192, 120), |
| 3828 | ] { |
| 3829 | let picture = test_card(width, height); |
| 3830 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 3831 | assert_eq!( |
| 3832 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 3833 | (width, height), |
| 3834 | "{width}x{height}: reconstruction is cropped to the picture's own size" |
| 3835 | ); |
| 3836 | assert_eq!( |
| 3837 | ffprobe_size(&encoded.stream), |
| 3838 | (width as u32, height as u32), |
| 3839 | "{width}x{height}: ffprobe reports the true (display) size, not the padded one" |
| 3840 | ); |
| 3841 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 3842 | assert_eq!( |
| 3843 | decoded.y, encoded.reconstruction.y, |
| 3844 | "{width}x{height}: luma" |
| 3845 | ); |
| 3846 | assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U"); |
| 3847 | assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V"); |
| 3848 | } |
| 3849 | } |
| 3850 | |
| 3851 | |
| 3852 | |
| 3853 | |
| 3854 | |
| 3855 | |
| 3856 | |
| 3857 | |
| 3858 | |
| 3859 | |
| 3860 | |
| 3861 | |
| 3862 | |
| 3863 | |
| 3864 | |
| 3865 | |
| 3866 | |
| 3867 | |
| 3868 | |
| 3869 | |
| 3870 | |
| 3871 | |
| 3872 | |
| 3873 | |
| 3874 | |
| 3875 | |
| 3876 | #[test] |
| 3877 | fn an_854x480_picture_round_trips_through_its_padding() { |
| 3878 | if !have_ffmpeg() { |
| 3879 | return; |
| 3880 | } |
| 3881 | let (width, height) = (854usize, 480usize); |
| 3882 | let picture = test_card(width, height); |
| 3883 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 3884 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 3885 | assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma"); |
| 3886 | assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U"); |
| 3887 | assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V"); |
| 3888 | } |
| 3889 | |
| 3890 | |
| 3891 | |
| 3892 | |
| 3893 | |
| 3894 | |
| 3895 | |
| 3896 | |
| 3897 | |
| 3898 | |
| 3899 | |
| 3900 | |
| 3901 | |
| 3902 | |
| 3903 | |
| 3904 | |
| 3905 | |
| 3906 | #[test] |
| 3907 | fn of_tu_follows_the_block_row_including_under_vert_ab() { |
| 3908 | |
| 3909 | |
| 3910 | |
| 3911 | |
| 3912 | |
| 3913 | let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK); |
| 3914 | assert_eq!( |
| 3915 | Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right, |
| 3916 | plain.above_right, |
| 3917 | "ordinary table: the top-right TX4 unit takes the block's row" |
| 3918 | ); |
| 3919 | let guard = Reach::vert_ab_partition(); |
| 3920 | let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK); |
| 3921 | assert_eq!( |
| 3922 | Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right, |
| 3923 | vert.above_right, |
| 3924 | "vert AB: the unit follows the vert row the block just picked" |
| 3925 | ); |
| 3926 | assert_ne!( |
| 3927 | plain.above_right, vert.above_right, |
| 3928 | "this position is the cell where the vert tables disagree; pick another if libaom's tables change" |
| 3929 | ); |
| 3930 | drop(guard); |
| 3931 | } |
| 3932 | |
| 3933 | |
| 3934 | |
| 3935 | |
| 3936 | |
| 3937 | |
| 3938 | |
| 3939 | |
| 3940 | #[test] |
| 3941 | fn reach_matches_libaom_has_top_right_and_has_bottom_left() { |
| 3942 | |
| 3943 | |
| 3944 | |
| 3945 | |
| 3946 | fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, height: usize) -> bool { |
| 3947 | if y == 0 || x + side >= width { |
| 3948 | return false; |
| 3949 | } |
| 3950 | let (row, col, per_side) = ( |
| 3951 | (y % SUPERBLOCK) / side, |
| 3952 | (x % SUPERBLOCK) / side, |
| 3953 | SUPERBLOCK / side, |
| 3954 | ); |
| 3955 | if row == 0 { |
| 3956 | return true; |
| 3957 | } |
| 3958 | if col + 1 == per_side { |
| 3959 | return false; |
| 3960 | } |
| 3961 | let stride = 128 / side; |
| 3962 | let index = row * stride + col; |
| 3963 | let table = if side == BLOCK { |
| 3964 | [95u8, 87].to_vec() |
| 3965 | } else { |
| 3966 | vec![255, 85, 119, 85, 127, 85, 119, 85] |
| 3967 | }; |
| 3968 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 3969 | } |
| 3970 | |
| 3971 | fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize) -> bool { |
| 3972 | if x == 0 || y + side >= height { |
| 3973 | return false; |
| 3974 | } |
| 3975 | let (row, col, per_side) = ( |
| 3976 | (y % SUPERBLOCK) / side, |
| 3977 | (x % SUPERBLOCK) / side, |
| 3978 | SUPERBLOCK / side, |
| 3979 | ); |
| 3980 | if col == 0 { |
| 3981 | return row * side + side < SUPERBLOCK; |
| 3982 | } |
| 3983 | if row + 1 == per_side { |
| 3984 | return false; |
| 3985 | } |
| 3986 | let stride = 128 / side; |
| 3987 | let index = row * stride + col; |
| 3988 | let table = if side == BLOCK { |
| 3989 | [4u8, 4].to_vec() |
| 3990 | } else { |
| 3991 | vec![84, 16, 84, 0, 84, 16, 84, 0] |
| 3992 | }; |
| 3993 | (table[index / 8] >> (index % 8)) & 1 != 0 |
| 3994 | } |
| 3995 | |
| 3996 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 3997 | for side in [16usize, BLOCK] { |
| 3998 | for y in (0..height).step_by(side) { |
| 3999 | for x in (0..width).step_by(side) { |
| 4000 | let reach = Reach::of(side, x, y, width, height); |
| 4001 | assert_eq!( |
| 4002 | reach.above_right, |
| 4003 | libaom_top_right(side, x, y, width, height), |
| 4004 | "side={side} x={x} y={y}: above_right" |
| 4005 | ); |
| 4006 | assert_eq!( |
| 4007 | reach.below_left, |
| 4008 | libaom_bottom_left(side, x, y, height), |
| 4009 | "side={side} x={x} y={y}: below_left" |
| 4010 | ); |
| 4011 | } |
| 4012 | } |
| 4013 | } |
| 4014 | } |
| 4015 | |
| 4016 | |
| 4017 | |
| 4018 | |
| 4019 | |
| 4020 | |
| 4021 | |
| 4022 | |
| 4023 | |
| 4024 | |
| 4025 | |
| 4026 | |
| 4027 | |
| 4028 | |
| 4029 | |
| 4030 | #[test] |
| 4031 | fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() { |
| 4032 | |
| 4033 | |
| 4034 | fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 4035 | let (plane_bw_unit, count) = (bw / 4, tx / 4); |
| 4036 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 4037 | let _ = bh; |
| 4038 | if row_off_u > 0 { |
| 4039 | col_off_u + count < plane_bw_unit |
| 4040 | } else if col_off_u + count < plane_bw_unit { |
| 4041 | true |
| 4042 | } else { |
| 4043 | blk |
| 4044 | } |
| 4045 | } |
| 4046 | fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool { |
| 4047 | let (plane_bh_unit, count) = (bh / 4, tx / 4); |
| 4048 | let (col_off_u, row_off_u) = (col_off / 4, row_off / 4); |
| 4049 | let _ = bw; |
| 4050 | if col_off_u > 0 { |
| 4051 | false |
| 4052 | } else if row_off_u + count < plane_bh_unit { |
| 4053 | true |
| 4054 | } else { |
| 4055 | blk |
| 4056 | } |
| 4057 | } |
| 4058 | for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] { |
| 4059 | for &tx in &[4usize, 8, 16, 32] { |
| 4060 | if tx > bw.min(bh) { |
| 4061 | continue; |
| 4062 | } |
| 4063 | for row_off in (0..bh).step_by(tx) { |
| 4064 | for col_off in (0..bw).step_by(tx) { |
| 4065 | for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] { |
| 4066 | let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk); |
| 4067 | assert_eq!( |
| 4068 | got.above_right, |
| 4069 | libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right), |
| 4070 | "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 4071 | ); |
| 4072 | assert_eq!( |
| 4073 | got.below_left, |
| 4074 | libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left), |
| 4075 | "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}" |
| 4076 | ); |
| 4077 | } |
| 4078 | } |
| 4079 | } |
| 4080 | } |
| 4081 | } |
| 4082 | } |
| 4083 | |
| 4084 | #[test] |
| 4085 | fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() { |
| 4086 | let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3); |
| 4087 | |
| 4088 | |
| 4089 | let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK); |
| 4090 | let mut flipped = 0; |
| 4091 | for row in 0..8 { |
| 4092 | for col in 1..8 { |
| 4093 | let (x, y) = (sb_x + col * 8, sb_y + row * 8); |
| 4094 | let raster = Reach::of(8, x, y, width, height).below_left; |
| 4095 | let vert = { |
| 4096 | let _guard = Reach::vert_ab_partition(); |
| 4097 | Reach::of(8, x, y, width, height).below_left |
| 4098 | }; |
| 4099 | |
| 4100 | |
| 4101 | if row % 2 == 0 && col % 2 == 1 { |
| 4102 | assert!(!raster, "raster below_left at row={row} col={col}"); |
| 4103 | assert!(vert, "vert below_left at row={row} col={col}"); |
| 4104 | flipped += 1; |
| 4105 | } else { |
| 4106 | assert_eq!(raster, vert, "guard moved row={row} col={col}"); |
| 4107 | } |
| 4108 | } |
| 4109 | } |
| 4110 | assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip"); |
| 4111 | |
| 4112 | assert!(!Reach::of(8, sb_x + 8, sb_y, width, height).below_left); |
| 4113 | } |
| 4114 | |
| 4115 | |
| 4116 | |
| 4117 | #[test] |
| 4118 | fn odd_dimensions_are_refused() { |
| 4119 | for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] { |
| 4120 | let picture = Picture::grey(width, height); |
| 4121 | let err = encode_key_frame(&picture, 100, 0.5) |
| 4122 | .expect_err(&format!("{width}x{height} is odd and must be refused")); |
| 4123 | assert!( |
| 4124 | err.to_string().contains("even"), |
| 4125 | "{width}x{height}: error was {err}" |
| 4126 | ); |
| 4127 | } |
| 4128 | } |
| 4129 | |
| 4130 | |
| 4131 | |
| 4132 | |
| 4133 | |
| 4134 | #[test] |
| 4135 | fn sequence_round_trips_at_a_non_multiple_size() { |
| 4136 | if !have_ffmpeg() { |
| 4137 | eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg"); |
| 4138 | return; |
| 4139 | } |
| 4140 | let (width, height) = (160usize, 96usize); |
| 4141 | let pictures: Vec<Picture> = (0..3) |
| 4142 | .map(|i| panned_test_card(width, height, i * 3)) |
| 4143 | .collect(); |
| 4144 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 4145 | assert_eq!(encoded.frames.len(), 3); |
| 4146 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 4147 | assert_eq!( |
| 4148 | (frame.reconstruction.width, frame.reconstruction.height), |
| 4149 | (width, height), |
| 4150 | "frame {i}: reconstruction size" |
| 4151 | ); |
| 4152 | } |
| 4153 | |
| 4154 | |
| 4155 | assert_eq!( |
| 4156 | ffprobe_size(&encoded.stream), |
| 4157 | (width as u32, height as u32), |
| 4158 | "sequence: ffprobe reports the true (display) size" |
| 4159 | ); |
| 4160 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 4161 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 4162 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 4163 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 4164 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 4165 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 4166 | } |
| 4167 | } |
| 4168 | |
| 4169 | |
| 4170 | |
| 4171 | |
| 4172 | |
| 4173 | |
| 4174 | |
| 4175 | |
| 4176 | #[test] |
| 4177 | fn a_sequence_round_trips_at_the_exactly_half_straddle_size() { |
| 4178 | if !have_ffmpeg() { |
| 4179 | eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg"); |
| 4180 | return; |
| 4181 | } |
| 4182 | let (width, height) = (1280usize, 720usize); |
| 4183 | let pictures: Vec<Picture> = (0..3) |
| 4184 | .map(|i| panned_test_card(width, height, i * 3)) |
| 4185 | .collect(); |
| 4186 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 4187 | assert_eq!(encoded.frames.len(), 3); |
| 4188 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 4189 | assert_eq!( |
| 4190 | (frame.reconstruction.width, frame.reconstruction.height), |
| 4191 | (width, height), |
| 4192 | "frame {i}: reconstruction size" |
| 4193 | ); |
| 4194 | } |
| 4195 | assert_eq!( |
| 4196 | ffprobe_size(&encoded.stream), |
| 4197 | (width as u32, height as u32), |
| 4198 | "ffprobe reports the true (display) 1280x720 size" |
| 4199 | ); |
| 4200 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3); |
| 4201 | assert_eq!(decoded.len(), 3, "decoded frame count"); |
| 4202 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 4203 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 4204 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 4205 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 4206 | } |
| 4207 | } |
| 4208 | |
| 4209 | |
| 4210 | |
| 4211 | |
| 4212 | |
| 4213 | |
| 4214 | |
| 4215 | |
| 4216 | |
| 4217 | |
| 4218 | |
| 4219 | |
| 4220 | #[test] |
| 4221 | fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() { |
| 4222 | let (width, height) = (640usize, 360usize); |
| 4223 | let picture = Picture::grey(width, height); |
| 4224 | encode_key_frame(&picture, 100, 0.5).expect("key frame now codes the mod-32==8 straddle"); |
| 4225 | |
| 4226 | |
| 4227 | |
| 4228 | let pictures = vec![picture.clone(), picture]; |
| 4229 | encode_sequence(&pictures, 100, 0.5) |
| 4230 | .expect("inter frame now codes the mod-32==8 straddle too"); |
| 4231 | } |
| 4232 | |
| 4233 | |
| 4234 | |
| 4235 | |
| 4236 | |
| 4237 | |
| 4238 | #[test] |
| 4239 | fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() { |
| 4240 | if !have_ffmpeg() { |
| 4241 | eprintln!( |
| 4242 | "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \ |
| 4243 | no ffmpeg" |
| 4244 | ); |
| 4245 | return; |
| 4246 | } |
| 4247 | let (width, height) = (640usize, 360usize); |
| 4248 | for shift in [0i64, 7, 19] { |
| 4249 | let picture = panned_test_card(width, height, shift); |
| 4250 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4251 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 4252 | assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma"); |
| 4253 | assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U"); |
| 4254 | assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V"); |
| 4255 | } |
| 4256 | } |
| 4257 | |
| 4258 | |
| 4259 | |
| 4260 | |
| 4261 | |
| 4262 | #[test] |
| 4263 | fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() { |
| 4264 | if !have_ffmpeg() { |
| 4265 | eprintln!( |
| 4266 | "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg" |
| 4267 | ); |
| 4268 | return; |
| 4269 | } |
| 4270 | let (width, height) = (640usize, 360usize); |
| 4271 | let pictures: Vec<Picture> = (0..4) |
| 4272 | .map(|i| panned_test_card(width, height, i * 3)) |
| 4273 | .collect(); |
| 4274 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 4275 | assert_eq!(encoded.frames.len(), 4); |
| 4276 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 4277 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 4278 | } |
| 4279 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4); |
| 4280 | assert_eq!(decoded.len(), 4, "decoded frame count"); |
| 4281 | for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 4282 | assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma"); |
| 4283 | assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U"); |
| 4284 | assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V"); |
| 4285 | } |
| 4286 | } |
| 4287 | |
| 4288 | |
| 4289 | fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture { |
| 4290 | let out = Command::new("ffmpeg") |
| 4291 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"]) |
| 4292 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 4293 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 4294 | .output() |
| 4295 | .expect("ffmpeg failed to run"); |
| 4296 | assert!( |
| 4297 | out.status.success(), |
| 4298 | "ffmpeg: {}", |
| 4299 | String::from_utf8_lossy(&out.stderr) |
| 4300 | ); |
| 4301 | let (luma, chroma) = (width * height, width * height / 4); |
| 4302 | assert_eq!( |
| 4303 | out.stdout.len(), |
| 4304 | luma + 2 * chroma, |
| 4305 | "expected one 4:2:0 frame" |
| 4306 | ); |
| 4307 | Picture { |
| 4308 | width, |
| 4309 | height, |
| 4310 | y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 4311 | u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 4312 | v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 4313 | } |
| 4314 | } |
| 4315 | |
| 4316 | |
| 4317 | |
| 4318 | |
| 4319 | #[test] |
| 4320 | #[ignore = "a sweep, not a gate"] |
| 4321 | fn probe_lambda() { |
| 4322 | let mut pictures = vec![ |
| 4323 | ("test card".to_string(), test_card(160, 96)), |
| 4324 | ("stripes".to_string(), stripes(160, 96, true)), |
| 4325 | ]; |
| 4326 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 4327 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 4328 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 4329 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 4330 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 4331 | } |
| 4332 | } |
| 4333 | for (name, picture) in pictures { |
| 4334 | let dc = ladder(&picture, &[DC_PRED]); |
| 4335 | let searched = ladder(&picture, &NON_DIRECTIONAL); |
| 4336 | println!( |
| 4337 | "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point", |
| 4338 | bd_rate(&dc, &searched) * 100.0, |
| 4339 | 10f64.powf(searched[1].1), |
| 4340 | searched[1].0, |
| 4341 | 10f64.powf(dc[1].1), |
| 4342 | dc[1].0, |
| 4343 | ); |
| 4344 | } |
| 4345 | } |
| 4346 | |
| 4347 | |
| 4348 | |
| 4349 | #[test] |
| 4350 | #[ignore = "a sweep, not a gate"] |
| 4351 | fn probe_ladder() { |
| 4352 | for (name, picture) in sweep_pictures() { |
| 4353 | let all = ladder(&picture, &KEY_FRAME_MODES); |
| 4354 | let points = all |
| 4355 | .iter() |
| 4356 | .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes))) |
| 4357 | .collect::<Vec<_>>() |
| 4358 | .join(" "); |
| 4359 | println!("ladder {name}: {points}"); |
| 4360 | } |
| 4361 | } |
| 4362 | |
| 4363 | |
| 4364 | |
| 4365 | |
| 4366 | #[test] |
| 4367 | #[ignore = "a sweep, not a gate"] |
| 4368 | fn probe_split() { |
| 4369 | for (name, picture) in sweep_pictures() { |
| 4370 | let ladder = |split: bool| { |
| 4371 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 4372 | .iter() |
| 4373 | .map(|&q| { |
| 4374 | let encoded = encode_key_frame_inner( |
| 4375 | &picture, |
| 4376 | q, |
| 4377 | 0.5, |
| 4378 | &KEY_FRAME_MODES, |
| 4379 | split, |
| 4380 | (picture.width, picture.height), |
| 4381 | unspecified_color_config(), |
| 4382 | ) |
| 4383 | .unwrap(); |
| 4384 | ( |
| 4385 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 4386 | (encoded.stream.len() as f64).log10(), |
| 4387 | ) |
| 4388 | }) |
| 4389 | .collect(); |
| 4390 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 4391 | points |
| 4392 | }; |
| 4393 | let (whole, split) = (ladder(false), ladder(true)); |
| 4394 | let blocks = encode_key_frame_inner( |
| 4395 | &picture, |
| 4396 | 90, |
| 4397 | 0.5, |
| 4398 | &KEY_FRAME_MODES, |
| 4399 | true, |
| 4400 | (picture.width, picture.height), |
| 4401 | unspecified_color_config(), |
| 4402 | ) |
| 4403 | .unwrap() |
| 4404 | .modes |
| 4405 | .len(); |
| 4406 | let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK); |
| 4407 | println!( |
| 4408 | "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90", |
| 4409 | bd_rate(&whole, &split) * 100.0 |
| 4410 | ); |
| 4411 | } |
| 4412 | } |
| 4413 | |
| 4414 | |
| 4415 | |
| 4416 | |
| 4417 | |
| 4418 | fn stripes(width: usize, height: usize, vertical: bool) -> Picture { |
| 4419 | let mut picture = Picture::grey(width, height); |
| 4420 | for y in 0..height { |
| 4421 | for x in 0..width { |
| 4422 | let along = if vertical { x } else { y }; |
| 4423 | picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 }; |
| 4424 | } |
| 4425 | } |
| 4426 | picture |
| 4427 | } |
| 4428 | |
| 4429 | |
| 4430 | |
| 4431 | |
| 4432 | fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> { |
| 4433 | let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?; |
| 4434 | let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count(); |
| 4435 | Some(format!( |
| 4436 | "{differ} samples differ, first at ({}, {}): ours {} theirs {}", |
| 4437 | i % width, |
| 4438 | i / width, |
| 4439 | ours[i], |
| 4440 | theirs[i] |
| 4441 | )) |
| 4442 | } |
| 4443 | |
| 4444 | |
| 4445 | |
| 4446 | |
| 4447 | #[test] |
| 4448 | fn every_mode_decodes_to_what_the_encoder_predicted() { |
| 4449 | if !have_ffmpeg() { |
| 4450 | eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg"); |
| 4451 | return; |
| 4452 | } |
| 4453 | |
| 4454 | |
| 4455 | |
| 4456 | for (width, height) in [(128, 96), (160, 96)] { |
| 4457 | let picture = test_card(width, height); |
| 4458 | for mode in KEY_FRAME_MODES { |
| 4459 | let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap(); |
| 4460 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 4461 | for (plane, ours, theirs, stride) in [ |
| 4462 | ("luma", &encoded.reconstruction.y, &decoded.y, width), |
| 4463 | ("U", &encoded.reconstruction.u, &decoded.u, width / 2), |
| 4464 | ("V", &encoded.reconstruction.v, &decoded.v, width / 2), |
| 4465 | ] { |
| 4466 | assert!( |
| 4467 | first_difference(ours, theirs, stride).is_none(), |
| 4468 | "{width}x{height} mode {mode}, {plane}: {}", |
| 4469 | first_difference(ours, theirs, stride).unwrap() |
| 4470 | ); |
| 4471 | } |
| 4472 | assert!( |
| 4473 | encoded.modes.iter().all(|&m| m == mode), |
| 4474 | "mode {mode}: the encoder coded something else" |
| 4475 | ); |
| 4476 | } |
| 4477 | } |
| 4478 | } |
| 4479 | |
| 4480 | |
| 4481 | |
| 4482 | |
| 4483 | |
| 4484 | #[test] |
| 4485 | fn the_search_picks_the_direction_the_picture_runs() { |
| 4486 | for (vertical, want) in [(true, V_PRED), (false, H_PRED)] { |
| 4487 | let picture = stripes(128, 96, vertical); |
| 4488 | |
| 4489 | |
| 4490 | |
| 4491 | |
| 4492 | |
| 4493 | let encoded = |
| 4494 | encode_key_frame_with_modes(&picture, 100, 0.5, &[V_PRED, H_PRED]).unwrap(); |
| 4495 | |
| 4496 | |
| 4497 | let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count(); |
| 4498 | assert!( |
| 4499 | picked * 2 > encoded.modes.len() - 1, |
| 4500 | "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}", |
| 4501 | encoded.modes.len() - 1, |
| 4502 | encoded.modes |
| 4503 | ); |
| 4504 | } |
| 4505 | } |
| 4506 | |
| 4507 | |
| 4508 | |
| 4509 | |
| 4510 | |
| 4511 | |
| 4512 | |
| 4513 | fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 { |
| 4514 | let low = reference[0].0.max(other[0].0); |
| 4515 | let high = reference[reference.len() - 1] |
| 4516 | .0 |
| 4517 | .min(other[other.len() - 1].0); |
| 4518 | assert!(high > low, "the two ladders have to overlap in PSNR"); |
| 4519 | let log_rate_at = |curve: &[(f64, f64)], psnr: f64| { |
| 4520 | let i = curve |
| 4521 | .windows(2) |
| 4522 | .position(|w| psnr >= w[0].0 && psnr <= w[1].0) |
| 4523 | .unwrap_or(0); |
| 4524 | let (x0, y0) = curve[i]; |
| 4525 | let (x1, y1) = curve[i + 1]; |
| 4526 | y0 + (y1 - y0) * (psnr - x0) / (x1 - x0) |
| 4527 | }; |
| 4528 | let steps = 64; |
| 4529 | let mut area = 0.0; |
| 4530 | for step in 0..steps { |
| 4531 | let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps); |
| 4532 | area += log_rate_at(other, psnr) - log_rate_at(reference, psnr); |
| 4533 | } |
| 4534 | 10f64.powf(area / f64::from(steps)) - 1.0 |
| 4535 | } |
| 4536 | |
| 4537 | |
| 4538 | |
| 4539 | fn ladder(picture: &Picture, modes: &[u8]) -> Vec<(f64, f64)> { |
| 4540 | let mut points: Vec<(f64, f64)> = [110u8, 90, 70] |
| 4541 | .iter() |
| 4542 | .map(|&q| { |
| 4543 | let encoded = encode_key_frame_with_modes(picture, q, 0.5, modes).unwrap(); |
| 4544 | ( |
| 4545 | psnr(&encoded.reconstruction.y, picture.y.as_slice()), |
| 4546 | (encoded.stream.len() as f64).log10(), |
| 4547 | ) |
| 4548 | }) |
| 4549 | .collect(); |
| 4550 | points.sort_by(|a, b| a.0.total_cmp(&b.0)); |
| 4551 | points |
| 4552 | } |
| 4553 | |
| 4554 | |
| 4555 | |
| 4556 | |
| 4557 | |
| 4558 | #[test] |
| 4559 | fn the_search_beats_dc_alone() { |
| 4560 | for (name, picture, want) in [ |
| 4561 | ("test card", test_card(160, 96), -0.05), |
| 4562 | ("stripes", stripes(160, 96, true), -0.40), |
| 4563 | ] { |
| 4564 | let saved = bd_rate( |
| 4565 | &ladder(&picture, &[DC_PRED]), |
| 4566 | &ladder(&picture, &NON_DIRECTIONAL), |
| 4567 | ); |
| 4568 | assert!( |
| 4569 | saved < want, |
| 4570 | "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%", |
| 4571 | saved * 100.0, |
| 4572 | -want * 100.0 |
| 4573 | ); |
| 4574 | } |
| 4575 | } |
| 4576 | |
| 4577 | |
| 4578 | |
| 4579 | fn sweep_pictures() -> Vec<(String, Picture)> { |
| 4580 | let mut pictures = vec![ |
| 4581 | ("test card".to_string(), test_card(160, 96)), |
| 4582 | ("stripes".to_string(), stripes(160, 96, true)), |
| 4583 | ("diagonal".to_string(), diagonal(160, 96, true)), |
| 4584 | ]; |
| 4585 | if let Ok(clips) = std::env::var("EC_AV1_CLIPS") { |
| 4586 | for entry in clips.split(':').filter(|e| !e.is_empty()) { |
| 4587 | let (path, skip) = entry.split_once('@').unwrap_or((entry, "0")); |
| 4588 | let name = path.rsplit('/').next().unwrap_or(path).to_string(); |
| 4589 | pictures.push((name, clip_frame(path, skip, 640, 352))); |
| 4590 | } |
| 4591 | } |
| 4592 | pictures |
| 4593 | } |
| 4594 | |
| 4595 | |
| 4596 | |
| 4597 | |
| 4598 | #[test] |
| 4599 | #[ignore = "a sweep, not a gate"] |
| 4600 | fn probe_directional() { |
| 4601 | for (name, picture) in sweep_pictures() { |
| 4602 | let dc = ladder(&picture, &[DC_PRED]); |
| 4603 | let flat = ladder(&picture, &NON_DIRECTIONAL); |
| 4604 | let all = ladder(&picture, &KEY_FRAME_MODES); |
| 4605 | let encoded = encode_key_frame(&picture, 90, 0.5).unwrap(); |
| 4606 | let directional = encoded |
| 4607 | .modes |
| 4608 | .iter() |
| 4609 | .filter(|&&m| (3..=8).contains(&m)) |
| 4610 | .count(); |
| 4611 | |
| 4612 | |
| 4613 | let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 4614 | a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0) |
| 4615 | }; |
| 4616 | let against = |a: &[(f64, f64)], b: &[(f64, f64)]| { |
| 4617 | if overlap(a, b) { |
| 4618 | format!("{:+.2}%", bd_rate(a, b) * 100.0) |
| 4619 | } else { |
| 4620 | "no overlap".to_string() |
| 4621 | } |
| 4622 | }; |
| 4623 | println!( |
| 4624 | "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional", |
| 4625 | against(&flat, &all), |
| 4626 | against(&dc, &all), |
| 4627 | encoded.modes.len(), |
| 4628 | ); |
| 4629 | } |
| 4630 | } |
| 4631 | |
| 4632 | |
| 4633 | |
| 4634 | |
| 4635 | |
| 4636 | fn diagonal(width: usize, height: usize, down_right: bool) -> Picture { |
| 4637 | let mut picture = Picture::grey(width, height); |
| 4638 | for y in 0..height { |
| 4639 | for x in 0..width { |
| 4640 | let along = if down_right { x + height - y } else { x + y }; |
| 4641 | picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 }; |
| 4642 | } |
| 4643 | } |
| 4644 | picture |
| 4645 | } |
| 4646 | |
| 4647 | |
| 4648 | |
| 4649 | fn favourite_mode(picture: &Picture) -> (u8, usize, usize) { |
| 4650 | let encoded = encode_key_frame(picture, 100, 0.5).unwrap(); |
| 4651 | let blocks = &encoded.modes[1..]; |
| 4652 | let mut counts = [0usize; 13]; |
| 4653 | for &mode in blocks { |
| 4654 | counts[usize::from(mode)] += 1; |
| 4655 | } |
| 4656 | let (mode, count) = counts |
| 4657 | .iter() |
| 4658 | .enumerate() |
| 4659 | .max_by_key(|&(_, count)| *count) |
| 4660 | .expect("thirteen modes"); |
| 4661 | (mode as u8, *count, blocks.len()) |
| 4662 | } |
| 4663 | |
| 4664 | |
| 4665 | |
| 4666 | |
| 4667 | |
| 4668 | #[test] |
| 4669 | fn the_search_picks_the_diagonal_the_picture_runs() { |
| 4670 | for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] { |
| 4671 | let picture = diagonal(160, 96, down_right); |
| 4672 | let (mode, count, blocks) = favourite_mode(&picture); |
| 4673 | assert_eq!( |
| 4674 | mode, want, |
| 4675 | "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}" |
| 4676 | ); |
| 4677 | } |
| 4678 | } |
| 4679 | |
| 4680 | |
| 4681 | |
| 4682 | |
| 4683 | |
| 4684 | |
| 4685 | |
| 4686 | #[test] |
| 4687 | fn the_diagonals_beat_the_modes_that_read_no_further() { |
| 4688 | for (name, picture, want) in [ |
| 4689 | ("down-right", diagonal(160, 96, true), -0.20), |
| 4690 | ("down-left", diagonal(160, 96, false), -0.20), |
| 4691 | ("test card", test_card(160, 96), 0.01), |
| 4692 | ] { |
| 4693 | let saved = bd_rate( |
| 4694 | &ladder(&picture, &NON_DIRECTIONAL), |
| 4695 | &ladder(&picture, &KEY_FRAME_MODES), |
| 4696 | ); |
| 4697 | assert!( |
| 4698 | saved < want, |
| 4699 | "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%", |
| 4700 | saved * 100.0, |
| 4701 | -want * 100.0 |
| 4702 | ); |
| 4703 | } |
| 4704 | } |
| 4705 | |
| 4706 | |
| 4707 | |
| 4708 | #[test] |
| 4709 | fn a_mode_the_encoder_cannot_predict_is_refused() { |
| 4710 | let picture = test_card(64, 64); |
| 4711 | let message = encode_key_frame_with_modes(&picture, 100, 0.5, &[13]) |
| 4712 | .unwrap_err() |
| 4713 | .to_string(); |
| 4714 | assert!( |
| 4715 | message.contains("intra mode 13"), |
| 4716 | "the refusal must name the mode, got {message}" |
| 4717 | ); |
| 4718 | assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[]).is_err()); |
| 4719 | } |
| 4720 | |
| 4721 | |
| 4722 | |
| 4723 | |
| 4724 | |
| 4725 | |
| 4726 | #[test] |
| 4727 | fn the_encoded_picture_is_the_one_that_went_in() { |
| 4728 | let picture = test_card(160, 96); |
| 4729 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4730 | let luma = psnr(&encoded.reconstruction.y, &picture.y); |
| 4731 | assert!(luma > 36.0, "luma PSNR {luma} at q 100"); |
| 4732 | for (plane, (got, want)) in [ |
| 4733 | (encoded.reconstruction.u.as_slice(), picture.u.as_slice()), |
| 4734 | (encoded.reconstruction.v.as_slice(), picture.v.as_slice()), |
| 4735 | ] |
| 4736 | .iter() |
| 4737 | .enumerate() |
| 4738 | { |
| 4739 | let chroma = psnr(got, want); |
| 4740 | assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100"); |
| 4741 | } |
| 4742 | } |
| 4743 | |
| 4744 | |
| 4745 | |
| 4746 | |
| 4747 | #[test] |
| 4748 | fn fidelity_and_rate_move_with_the_quantizer() { |
| 4749 | let picture = test_card(128, 128); |
| 4750 | let mut previous: Option<(usize, f64)> = None; |
| 4751 | for &q in &[70u8, 90, 110] { |
| 4752 | let encoded = encode_key_frame(&picture, q, 0.5).unwrap(); |
| 4753 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 4754 | if let Some((bytes, better)) = previous { |
| 4755 | assert!( |
| 4756 | encoded.stream.len() < bytes, |
| 4757 | "q {q}: {} bytes", |
| 4758 | encoded.stream.len() |
| 4759 | ); |
| 4760 | assert!(quality < better, "q {q}: PSNR {quality}"); |
| 4761 | } |
| 4762 | previous = Some((encoded.stream.len(), quality)); |
| 4763 | } |
| 4764 | |
| 4765 | let mut previous = None; |
| 4766 | for &deadzone in &[0.5f64, 0.3, 0.15] { |
| 4767 | let encoded = encode_key_frame(&picture, 100, deadzone).unwrap(); |
| 4768 | let quality = psnr(&encoded.reconstruction.y, &picture.y); |
| 4769 | if let Some((bytes, better)) = previous { |
| 4770 | assert!( |
| 4771 | encoded.stream.len() < bytes, |
| 4772 | "deadzone {deadzone}: {} bytes", |
| 4773 | encoded.stream.len() |
| 4774 | ); |
| 4775 | assert!(quality < better, "deadzone {deadzone}: PSNR {quality}"); |
| 4776 | } |
| 4777 | previous = Some((encoded.stream.len(), quality)); |
| 4778 | } |
| 4779 | |
| 4780 | |
| 4781 | |
| 4782 | |
| 4783 | |
| 4784 | for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] { |
| 4785 | let lo_bytes = encode_key_frame(&picture, lo, 0.5).unwrap().stream.len(); |
| 4786 | let hi_bytes = encode_key_frame(&picture, hi, 0.5).unwrap().stream.len(); |
| 4787 | assert!( |
| 4788 | hi_bytes <= lo_bytes, |
| 4789 | "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes" |
| 4790 | ); |
| 4791 | } |
| 4792 | } |
| 4793 | |
| 4794 | |
| 4795 | |
| 4796 | #[test] |
| 4797 | fn a_flat_picture_costs_almost_nothing() { |
| 4798 | let mut picture = Picture::grey(128, 128); |
| 4799 | picture.y.fill(97); |
| 4800 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4801 | |
| 4802 | |
| 4803 | assert!( |
| 4804 | encoded.stream.len() < 100, |
| 4805 | "{} bytes for a flat picture", |
| 4806 | encoded.stream.len() |
| 4807 | ); |
| 4808 | for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) { |
| 4809 | assert_eq!(s, 97, "sample {i} of a flat picture"); |
| 4810 | } |
| 4811 | } |
| 4812 | |
| 4813 | |
| 4814 | |
| 4815 | |
| 4816 | |
| 4817 | |
| 4818 | |
| 4819 | |
| 4820 | |
| 4821 | |
| 4822 | |
| 4823 | |
| 4824 | |
| 4825 | #[test] |
| 4826 | fn a_picture_off_the_block_grid_is_refused() { |
| 4827 | let msg = encode_key_frame(&Picture::grey(40, 40), 100, 0.5) |
| 4828 | .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform") |
| 4829 | .to_string(); |
| 4830 | assert!(msg.contains("rectangular"), "refusal: {msg}"); |
| 4831 | |
| 4832 | let mut short = Picture::grey(64, 64); |
| 4833 | short.u.truncate(10); |
| 4834 | assert!(encode_key_frame(&short, 100, 0.5).is_err()); |
| 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 | |
| 4882 | |
| 4883 | |
| 4884 | |
| 4885 | |
| 4886 | |
| 4887 | |
| 4888 | |
| 4889 | |
| 4890 | |
| 4891 | |
| 4892 | |
| 4893 | |
| 4894 | |
| 4895 | |
| 4896 | |
| 4897 | |
| 4898 | |
| 4899 | |
| 4900 | |
| 4901 | |
| 4902 | |
| 4903 | |
| 4904 | |
| 4905 | |
| 4906 | |
| 4907 | #[test] |
| 4908 | fn a_single_axis_straddle_round_trips_through_ffmpeg() { |
| 4909 | if !have_ffmpeg() { |
| 4910 | eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg"); |
| 4911 | return; |
| 4912 | } |
| 4913 | let (width, height) = (40usize, 32usize); |
| 4914 | let picture = test_card(width, height); |
| 4915 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4916 | assert_eq!( |
| 4917 | (encoded.reconstruction.width, encoded.reconstruction.height), |
| 4918 | (width, height) |
| 4919 | ); |
| 4920 | if let Ok(path) = std::env::var("EC_AV1_DUMP") { |
| 4921 | std::fs::write(&path, &encoded.stream).expect("dump the raw stream"); |
| 4922 | } |
| 4923 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 4924 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 4925 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 4926 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 4927 | } |
| 4928 | |
| 4929 | |
| 4930 | |
| 4931 | |
| 4932 | |
| 4933 | |
| 4934 | |
| 4935 | #[test] |
| 4936 | fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() { |
| 4937 | let Ok(clip) = std::env::var("EC_AV1_CLIP") else { |
| 4938 | eprintln!( |
| 4939 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \ |
| 4940 | set EC_AV1_CLIP to a clip" |
| 4941 | ); |
| 4942 | return; |
| 4943 | }; |
| 4944 | if !have_ffmpeg() { |
| 4945 | eprintln!( |
| 4946 | "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 4947 | ); |
| 4948 | return; |
| 4949 | } |
| 4950 | let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into()); |
| 4951 | |
| 4952 | |
| 4953 | let (width, height) = (640usize, 352usize); |
| 4954 | let picture = clip_frame(&clip, &skip, width, height); |
| 4955 | |
| 4956 | let encoded = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 4957 | let decoded = ffmpeg_decode(&encoded.stream, width, height); |
| 4958 | assert_eq!(decoded.y, encoded.reconstruction.y, "luma"); |
| 4959 | assert_eq!(decoded.u, encoded.reconstruction.u, "U"); |
| 4960 | assert_eq!(decoded.v, encoded.reconstruction.v, "V"); |
| 4961 | eprintln!( |
| 4962 | "{} bytes, luma PSNR {:.2} dB", |
| 4963 | encoded.stream.len(), |
| 4964 | psnr(&decoded.y, &picture.y) |
| 4965 | ); |
| 4966 | } |
| 4967 | |
| 4968 | |
| 4969 | |
| 4970 | |
| 4971 | |
| 4972 | |
| 4973 | fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture { |
| 4974 | let mut picture = Picture::grey(width, height); |
| 4975 | for y in 0..height { |
| 4976 | for x in 0..width { |
| 4977 | let sx = (x as i64 - shift).rem_euclid(width as i64) as f64; |
| 4978 | let gradient = sx * 200.0 / width as f64; |
| 4979 | let ripple = 30.0 |
| 4980 | * (sx * std::f64::consts::PI / 23.0).sin() |
| 4981 | * (y as f64 * std::f64::consts::PI / 37.0).cos(); |
| 4982 | let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 { |
| 4983 | 40.0 |
| 4984 | } else { |
| 4985 | 0.0 |
| 4986 | }; |
| 4987 | picture.y[y * width + x] = |
| 4988 | (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16; |
| 4989 | } |
| 4990 | } |
| 4991 | for y in 0..height / 2 { |
| 4992 | for x in 0..width / 2 { |
| 4993 | let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize; |
| 4994 | let i = y * width / 2 + x; |
| 4995 | picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16; |
| 4996 | picture.v[i] = (200 - (y * 80 / (height / 2))) as u16; |
| 4997 | } |
| 4998 | } |
| 4999 | picture |
| 5000 | } |
| 5001 | |
| 5002 | |
| 5003 | fn ffmpeg_decode_sequence( |
| 5004 | stream: &[u8], |
| 5005 | width: usize, |
| 5006 | height: usize, |
| 5007 | frames: usize, |
| 5008 | ) -> Vec<Picture> { |
| 5009 | let mut child = Command::new("ffmpeg") |
| 5010 | .args([ |
| 5011 | "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-", |
| 5012 | ]) |
| 5013 | .stdin(Stdio::piped()) |
| 5014 | .stdout(Stdio::piped()) |
| 5015 | .stderr(Stdio::piped()) |
| 5016 | .spawn() |
| 5017 | .expect("ffmpeg failed to start"); |
| 5018 | |
| 5019 | |
| 5020 | |
| 5021 | |
| 5022 | |
| 5023 | |
| 5024 | |
| 5025 | let mut stdin = child.stdin.take().expect("ffmpeg stdin"); |
| 5026 | let payload = stream.to_vec(); |
| 5027 | let writer = std::thread::spawn(move || { |
| 5028 | let _ = stdin.write_all(&payload); |
| 5029 | }); |
| 5030 | let out = child.wait_with_output().expect("ffmpeg failed to run"); |
| 5031 | writer.join().expect("ffmpeg stdin writer thread"); |
| 5032 | assert!( |
| 5033 | out.status.success(), |
| 5034 | "ffmpeg refused the stream: {}", |
| 5035 | String::from_utf8_lossy(&out.stderr) |
| 5036 | ); |
| 5037 | let (luma, chroma) = (width * height, width * height / 4); |
| 5038 | let frame_bytes = luma + 2 * chroma; |
| 5039 | assert_eq!( |
| 5040 | out.stdout.len(), |
| 5041 | frame_bytes * frames, |
| 5042 | "expected {frames} 4:2:0 frames, ffmpeg said: {}", |
| 5043 | String::from_utf8_lossy(&out.stderr) |
| 5044 | ); |
| 5045 | (0..frames) |
| 5046 | .map(|i| { |
| 5047 | let base = i * frame_bytes; |
| 5048 | Picture { |
| 5049 | width, |
| 5050 | height, |
| 5051 | y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(), |
| 5052 | u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 5053 | v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(), |
| 5054 | } |
| 5055 | }) |
| 5056 | .collect() |
| 5057 | } |
| 5058 | |
| 5059 | |
| 5060 | |
| 5061 | |
| 5062 | |
| 5063 | |
| 5064 | |
| 5065 | #[test] |
| 5066 | fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() { |
| 5067 | if !have_ffmpeg() { |
| 5068 | eprintln!( |
| 5069 | "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg" |
| 5070 | ); |
| 5071 | return; |
| 5072 | } |
| 5073 | let (width, height) = (128usize, 64usize); |
| 5074 | let pictures: Vec<Picture> = (0..5) |
| 5075 | .map(|i| panned_test_card(width, height, i * 3)) |
| 5076 | .collect(); |
| 5077 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 5078 | assert_eq!(encoded.frames.len(), 5); |
| 5079 | |
| 5080 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5); |
| 5081 | for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() { |
| 5082 | assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma"); |
| 5083 | assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U"); |
| 5084 | assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V"); |
| 5085 | } |
| 5086 | |
| 5087 | eprintln!("frame bytes luma PSNR (dB) inter share"); |
| 5088 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 5089 | eprintln!( |
| 5090 | "{i:5} {:5} {:14.2} {:11.2}", |
| 5091 | frame.stream.len(), |
| 5092 | psnr(&frame.reconstruction.y, &pictures[i].y), |
| 5093 | frame.inter_block_share |
| 5094 | ); |
| 5095 | } |
| 5096 | } |
| 5097 | |
| 5098 | |
| 5099 | |
| 5100 | |
| 5101 | |
| 5102 | |
| 5103 | |
| 5104 | |
| 5105 | #[test] |
| 5106 | fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() { |
| 5107 | let (width, height) = (256usize, 128usize); |
| 5108 | let pictures: Vec<Picture> = (0..5) |
| 5109 | .map(|i| panned_test_card(width, height, i * 2)) |
| 5110 | .collect(); |
| 5111 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 5112 | |
| 5113 | let key_bytes = encoded.frames[0].stream.len(); |
| 5114 | eprintln!("frame bytes inter share"); |
| 5115 | for (i, frame) in encoded.frames.iter().enumerate() { |
| 5116 | eprintln!( |
| 5117 | "{i:5} {:5} {:11.2}", |
| 5118 | frame.stream.len(), |
| 5119 | frame.inter_block_share |
| 5120 | ); |
| 5121 | } |
| 5122 | assert!( |
| 5123 | encoded.frames[1..] |
| 5124 | .iter() |
| 5125 | .any(|f| f.stream.len() < key_bytes), |
| 5126 | "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes" |
| 5127 | ); |
| 5128 | assert!( |
| 5129 | encoded.frames[1..] |
| 5130 | .iter() |
| 5131 | .any(|f| f.inter_block_share > 0.0), |
| 5132 | "no inter frame coded a single inter block -- the search never fired" |
| 5133 | ); |
| 5134 | } |
| 5135 | |
| 5136 | |
| 5137 | |
| 5138 | |
| 5139 | |
| 5140 | #[test] |
| 5141 | #[ignore = "a perf probe, not a gate"] |
| 5142 | fn stage_timing_breakdown() { |
| 5143 | use std::time::Instant; |
| 5144 | |
| 5145 | for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] { |
| 5146 | let picture = test_card(width, height); |
| 5147 | |
| 5148 | let t = Instant::now(); |
| 5149 | let dc_only = encode_key_frame_with_modes(&picture, 100, 0.5, &[DC_PRED]).unwrap(); |
| 5150 | let dc_only_t = t.elapsed(); |
| 5151 | |
| 5152 | let t = Instant::now(); |
| 5153 | let non_directional = |
| 5154 | encode_key_frame_with_modes(&picture, 100, 0.5, &NON_DIRECTIONAL).unwrap(); |
| 5155 | let non_directional_t = t.elapsed(); |
| 5156 | |
| 5157 | let t = Instant::now(); |
| 5158 | let all_modes = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 5159 | let all_modes_t = t.elapsed(); |
| 5160 | |
| 5161 | eprintln!( |
| 5162 | "\n=== key frame {width}x{height} ===\n\ |
| 5163 | 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\ |
| 5164 | 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\ |
| 5165 | 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)", |
| 5166 | dc_only.stream.len(), |
| 5167 | non_directional.stream.len(), |
| 5168 | all_modes.stream.len(), |
| 5169 | ); |
| 5170 | |
| 5171 | |
| 5172 | |
| 5173 | |
| 5174 | let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK); |
| 5175 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 5176 | let t = Instant::now(); |
| 5177 | let inter = |
| 5178 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap(); |
| 5179 | let inter_t = t.elapsed(); |
| 5180 | eprintln!( |
| 5181 | "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \ |
| 5182 | {:.2})", |
| 5183 | inter.stream.len(), |
| 5184 | inter.inter_block_share |
| 5185 | ); |
| 5186 | } |
| 5187 | |
| 5188 | |
| 5189 | |
| 5190 | |
| 5191 | for side in [16usize, 32] { |
| 5192 | const N: u32 = 20_000; |
| 5193 | let residual: Vec<i32> = (0..side * side) |
| 5194 | .map(|i| ((i * 37 % 61) as i32) - 30) |
| 5195 | .collect(); |
| 5196 | |
| 5197 | let t = Instant::now(); |
| 5198 | let mut levels = Vec::new(); |
| 5199 | for _ in 0..N { |
| 5200 | levels = forward_and_quantize(&residual, side, 8, 100, 0.5); |
| 5201 | } |
| 5202 | let forward_t = t.elapsed() / N; |
| 5203 | |
| 5204 | let t = Instant::now(); |
| 5205 | for _ in 0..N { |
| 5206 | std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100)); |
| 5207 | } |
| 5208 | let inverse_t = t.elapsed() / N; |
| 5209 | |
| 5210 | let set = if side == 32 { |
| 5211 | crate::cdf_state::TxbSet::Luma32 |
| 5212 | } else { |
| 5213 | crate::cdf_state::TxbSet::Luma16 |
| 5214 | }; |
| 5215 | let t = Instant::now(); |
| 5216 | for _ in 0..N { |
| 5217 | std::hint::black_box(crate::tile::coeff_bits(&levels, set)); |
| 5218 | } |
| 5219 | let entropy_t = t.elapsed() / N; |
| 5220 | |
| 5221 | let above = vec![128u8; side * 2]; |
| 5222 | let left = vec![128u8; side * 2]; |
| 5223 | let mut prediction = vec![0u8; side * side]; |
| 5224 | let t = Instant::now(); |
| 5225 | for _ in 0..N { |
| 5226 | intra_predict_u8( |
| 5227 | D45_PRED, |
| 5228 | 0, |
| 5229 | Some(&above), |
| 5230 | Some(&left), |
| 5231 | Some(128), |
| 5232 | side, |
| 5233 | side, |
| 5234 | false, |
| 5235 | false, |
| 5236 | &mut prediction, |
| 5237 | ); |
| 5238 | } |
| 5239 | let predict_t = t.elapsed() / N; |
| 5240 | |
| 5241 | eprintln!( |
| 5242 | "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\ |
| 5243 | predict (1 directional mode): {predict_t:>9.2?}\n\ |
| 5244 | forward_and_quantize: {forward_t:>9.2?}\n\ |
| 5245 | dequant_and_inverse: {inverse_t:>9.2?}\n\ |
| 5246 | coeff_bits: {entropy_t:>9.2?}" |
| 5247 | ); |
| 5248 | } |
| 5249 | } |
| 5250 | |
| 5251 | |
| 5252 | |
| 5253 | |
| 5254 | |
| 5255 | |
| 5256 | |
| 5257 | |
| 5258 | |
| 5259 | |
| 5260 | |
| 5261 | #[test] |
| 5262 | #[ignore = "a perf probe, not a gate"] |
| 5263 | fn stage_timing_breakdown_inter() { |
| 5264 | use std::time::Instant; |
| 5265 | |
| 5266 | let (width, height) = (1280usize, 720); |
| 5267 | let picture = test_card(width, height); |
| 5268 | let key = encode_key_frame(&picture, 100, 0.5).unwrap(); |
| 5269 | let padded_ref = key.reconstruction.padded_to(SUPERBLOCK); |
| 5270 | let padded_pic = picture.padded_to(SUPERBLOCK); |
| 5271 | |
| 5272 | stage_reset(); |
| 5273 | let t = Instant::now(); |
| 5274 | let inter = |
| 5275 | encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap(); |
| 5276 | let total_t = t.elapsed(); |
| 5277 | let [motion_search, interpolation, transform_quant, entropy] = stage_read(); |
| 5278 | let accounted = motion_search + transform_quant + entropy; |
| 5279 | |
| 5280 | |
| 5281 | |
| 5282 | |
| 5283 | let other = total_t.saturating_sub(accounted); |
| 5284 | |
| 5285 | eprintln!( |
| 5286 | "\n=== inter frame {width}x{height}, one frame ===\n\ |
| 5287 | total: {total_t:>9.2?} ({} bytes)\n\ |
| 5288 | motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \ |
| 5289 | {interpolation:>9.2?})\n\ |
| 5290 | transform + quantize: {transform_quant:>9.2?}\n\ |
| 5291 | coeff_bits (entropy pricing): {entropy:>9.2?}\n\ |
| 5292 | everything else (13-mode intra {other:>9.2?}\n\ |
| 5293 | candidate loop's own predict/bookkeeping, NEARESTMV's own \ |
| 5294 | predict, RD glue):", |
| 5295 | inter.stream.len(), |
| 5296 | ); |
| 5297 | } |
| 5298 | |
| 5299 | |
| 5300 | |
| 5301 | |
| 5302 | |
| 5303 | |
| 5304 | |
| 5305 | |
| 5306 | |
| 5307 | |
| 5308 | #[test] |
| 5309 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 5310 | fn prune_k_quality_sweep() { |
| 5311 | if !have_ffmpeg() { |
| 5312 | eprintln!("SKIP prune_k_quality_sweep: no ffmpeg"); |
| 5313 | return; |
| 5314 | } |
| 5315 | let (width, height) = (640usize, 352usize); |
| 5316 | let frames: &[(&str, &str, &str)] = &[ |
| 5317 | |
| 5318 | |
| 5319 | ( |
| 5320 | "dark/flat", |
| 5321 | "/home/user/Videos/reela.mp4", |
| 5322 | "3", |
| 5323 | ), |
| 5324 | ( |
| 5325 | "detailed", |
| 5326 | "/home/user/Downloads/reelb.mkv", |
| 5327 | "1200", |
| 5328 | ), |
| 5329 | ( |
| 5330 | "film", |
| 5331 | "/home/user/Videos/Films/reelc.mkv", |
| 5332 | "600", |
| 5333 | ), |
| 5334 | ]; |
| 5335 | for &(label, clip, skip) in frames { |
| 5336 | if !std::path::Path::new(clip).exists() { |
| 5337 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 5338 | continue; |
| 5339 | } |
| 5340 | let picture = clip_frame(clip, skip, width, height); |
| 5341 | for &q in &[60u8, 150] { |
| 5342 | |
| 5343 | |
| 5344 | |
| 5345 | set_test_top_k_override(None); |
| 5346 | let baseline = encode_key_frame(&picture, q, 0.5).unwrap(); |
| 5347 | let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y); |
| 5348 | eprint!( |
| 5349 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 5350 | baseline.stream.len(), |
| 5351 | baseline_psnr |
| 5352 | ); |
| 5353 | for &k in &[3usize, 4, 6] { |
| 5354 | set_test_top_k_override(Some(k)); |
| 5355 | let pruned = encode_key_frame(&picture, q, 0.5).unwrap(); |
| 5356 | let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y); |
| 5357 | eprint!( |
| 5358 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 5359 | pruned.stream.len(), |
| 5360 | pruned_psnr, |
| 5361 | pruned_psnr - baseline_psnr |
| 5362 | ); |
| 5363 | } |
| 5364 | eprintln!(); |
| 5365 | } |
| 5366 | } |
| 5367 | set_test_top_k_override(None); |
| 5368 | } |
| 5369 | |
| 5370 | |
| 5371 | |
| 5372 | fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] { |
| 5373 | let out = Command::new("ffmpeg") |
| 5374 | .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"]) |
| 5375 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 5376 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 5377 | .output() |
| 5378 | .expect("ffmpeg failed to run"); |
| 5379 | assert!( |
| 5380 | out.status.success(), |
| 5381 | "ffmpeg: {}", |
| 5382 | String::from_utf8_lossy(&out.stderr) |
| 5383 | ); |
| 5384 | let (luma, chroma) = (width * height, width * height / 4); |
| 5385 | let frame_len = luma + 2 * chroma; |
| 5386 | assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames"); |
| 5387 | std::array::from_fn(|i| { |
| 5388 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 5389 | Picture { |
| 5390 | width, |
| 5391 | height, |
| 5392 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 5393 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 5394 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 5395 | } |
| 5396 | }) |
| 5397 | } |
| 5398 | |
| 5399 | |
| 5400 | |
| 5401 | |
| 5402 | |
| 5403 | |
| 5404 | |
| 5405 | |
| 5406 | |
| 5407 | #[test] |
| 5408 | #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"] |
| 5409 | fn prune_k_quality_sweep_inter() { |
| 5410 | if !have_ffmpeg() { |
| 5411 | eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg"); |
| 5412 | return; |
| 5413 | } |
| 5414 | let (width, height) = (1280usize, 704usize); |
| 5415 | let frames: &[(&str, &str, &str)] = &[ |
| 5416 | ( |
| 5417 | "dark/flat", |
| 5418 | "/home/user/Videos/reela.mp4", |
| 5419 | "3", |
| 5420 | ), |
| 5421 | ( |
| 5422 | "detailed", |
| 5423 | "/home/user/Downloads/reelb.mkv", |
| 5424 | "1200", |
| 5425 | ), |
| 5426 | ( |
| 5427 | "film", |
| 5428 | "/home/user/Videos/Films/reelc.mkv", |
| 5429 | "600", |
| 5430 | ), |
| 5431 | ]; |
| 5432 | for &(label, clip, skip) in frames { |
| 5433 | if !std::path::Path::new(clip).exists() { |
| 5434 | eprintln!("SKIP {label}: {clip} not present on this machine"); |
| 5435 | continue; |
| 5436 | } |
| 5437 | let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height); |
| 5438 | for &q in &[60u8, 150] { |
| 5439 | |
| 5440 | |
| 5441 | |
| 5442 | set_test_top_k_override_inter(None); |
| 5443 | let key = encode_key_frame(&key_source, q, 0.5).unwrap(); |
| 5444 | let baseline = encode_inter_frame( |
| 5445 | &inter_source, |
| 5446 | &key.reconstruction, |
| 5447 | q, |
| 5448 | 0.5, |
| 5449 | 1, |
| 5450 | (width, height), |
| 5451 | ) |
| 5452 | .unwrap(); |
| 5453 | let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y); |
| 5454 | eprint!( |
| 5455 | "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB", |
| 5456 | baseline.stream.len(), |
| 5457 | baseline_psnr |
| 5458 | ); |
| 5459 | for &k in &[3usize, 4, 6] { |
| 5460 | set_test_top_k_override_inter(Some(k)); |
| 5461 | let pruned = encode_inter_frame( |
| 5462 | &inter_source, |
| 5463 | &key.reconstruction, |
| 5464 | q, |
| 5465 | 0.5, |
| 5466 | 1, |
| 5467 | (width, height), |
| 5468 | ) |
| 5469 | .unwrap(); |
| 5470 | let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y); |
| 5471 | eprint!( |
| 5472 | " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)", |
| 5473 | pruned.stream.len(), |
| 5474 | pruned_psnr, |
| 5475 | pruned_psnr - baseline_psnr |
| 5476 | ); |
| 5477 | } |
| 5478 | eprintln!(); |
| 5479 | } |
| 5480 | } |
| 5481 | set_test_top_k_override_inter(None); |
| 5482 | } |
| 5483 | |
| 5484 | |
| 5485 | |
| 5486 | |
| 5487 | fn clip_frames( |
| 5488 | clip: &str, |
| 5489 | skip: &str, |
| 5490 | width: usize, |
| 5491 | height: usize, |
| 5492 | frames: usize, |
| 5493 | ) -> Vec<Picture> { |
| 5494 | let out = Command::new("ffmpeg") |
| 5495 | .args(["-v", "error", "-ss", skip, "-i", clip]) |
| 5496 | .args(["-frames:v", &frames.to_string()]) |
| 5497 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 5498 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 5499 | .output() |
| 5500 | .expect("ffmpeg failed to run"); |
| 5501 | assert!( |
| 5502 | out.status.success(), |
| 5503 | "ffmpeg: {}", |
| 5504 | String::from_utf8_lossy(&out.stderr) |
| 5505 | ); |
| 5506 | let (luma, chroma) = (width * height, width * height / 4); |
| 5507 | let frame_len = luma + 2 * chroma; |
| 5508 | assert_eq!( |
| 5509 | out.stdout.len(), |
| 5510 | frame_len * frames, |
| 5511 | "expected {frames} 4:2:0 frames" |
| 5512 | ); |
| 5513 | (0..frames) |
| 5514 | .map(|i| { |
| 5515 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 5516 | Picture { |
| 5517 | width, |
| 5518 | height, |
| 5519 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 5520 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 5521 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 5522 | } |
| 5523 | }) |
| 5524 | .collect() |
| 5525 | } |
| 5526 | |
| 5527 | |
| 5528 | |
| 5529 | |
| 5530 | |
| 5531 | |
| 5532 | |
| 5533 | |
| 5534 | |
| 5535 | |
| 5536 | |
| 5537 | |
| 5538 | |
| 5539 | |
| 5540 | |
| 5541 | |
| 5542 | |
| 5543 | |
| 5544 | |
| 5545 | #[test] |
| 5546 | fn real_clip_encodes_within_its_quality_and_size_budget() { |
| 5547 | if !have_ffmpeg() { |
| 5548 | eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg"); |
| 5549 | return; |
| 5550 | } |
| 5551 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 5552 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 5553 | if !clip.exists() { |
| 5554 | eprintln!( |
| 5555 | "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing", |
| 5556 | clip.display() |
| 5557 | ); |
| 5558 | return; |
| 5559 | } |
| 5560 | let (width, height, frame_count) = (640usize, 384usize, 12usize); |
| 5561 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 5562 | let encoded = encode_sequence(&source, 100, 0.5).unwrap(); |
| 5563 | assert_eq!(encoded.frames.len(), frame_count); |
| 5564 | |
| 5565 | |
| 5566 | |
| 5567 | |
| 5568 | |
| 5569 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 5570 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 5571 | |
| 5572 | |
| 5573 | let mean_psnr: f64 = decoded |
| 5574 | .iter() |
| 5575 | .zip(&source) |
| 5576 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 5577 | .sum::<f64>() |
| 5578 | / frame_count as f64; |
| 5579 | assert!( |
| 5580 | mean_psnr >= 44.91, |
| 5581 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor" |
| 5582 | ); |
| 5583 | |
| 5584 | |
| 5585 | assert!( |
| 5586 | encoded.stream.len() <= 80_340, |
| 5587 | "stream grew to {} bytes, over the 80340-byte ceiling", |
| 5588 | encoded.stream.len() |
| 5589 | ); |
| 5590 | } |
| 5591 | |
| 5592 | |
| 5593 | |
| 5594 | |
| 5595 | |
| 5596 | |
| 5597 | |
| 5598 | |
| 5599 | |
| 5600 | |
| 5601 | |
| 5602 | |
| 5603 | |
| 5604 | |
| 5605 | #[test] |
| 5606 | fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() { |
| 5607 | if !have_ffmpeg() { |
| 5608 | eprintln!( |
| 5609 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 5610 | no ffmpeg" |
| 5611 | ); |
| 5612 | return; |
| 5613 | } |
| 5614 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 5615 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 5616 | if !clip.exists() { |
| 5617 | eprintln!( |
| 5618 | "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \ |
| 5619 | {} missing", |
| 5620 | clip.display() |
| 5621 | ); |
| 5622 | return; |
| 5623 | } |
| 5624 | let (width, height, frame_count) = (704usize, 400usize, 8usize); |
| 5625 | let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count); |
| 5626 | let encoded = encode_sequence(&source, 100, 0.5).unwrap(); |
| 5627 | assert_eq!(encoded.frames.len(), frame_count); |
| 5628 | |
| 5629 | |
| 5630 | |
| 5631 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count); |
| 5632 | assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame"); |
| 5633 | |
| 5634 | |
| 5635 | let mean_psnr: f64 = decoded |
| 5636 | .iter() |
| 5637 | .zip(&source) |
| 5638 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 5639 | .sum::<f64>() |
| 5640 | / frame_count as f64; |
| 5641 | assert!( |
| 5642 | mean_psnr >= 44.98, |
| 5643 | "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor" |
| 5644 | ); |
| 5645 | |
| 5646 | |
| 5647 | assert!( |
| 5648 | encoded.stream.len() <= 62_703, |
| 5649 | "stream grew to {} bytes, over the 62703-byte ceiling", |
| 5650 | encoded.stream.len() |
| 5651 | ); |
| 5652 | } |
| 5653 | |
| 5654 | |
| 5655 | |
| 5656 | |
| 5657 | |
| 5658 | |
| 5659 | |
| 5660 | #[test] |
| 5661 | #[ignore = "a perf probe, not a gate"] |
| 5662 | fn sequence_bench_sanity() { |
| 5663 | use std::time::Instant; |
| 5664 | let (width, height) = (1280usize, 720usize); |
| 5665 | let pictures: Vec<Picture> = (0..24) |
| 5666 | .map(|i| panned_test_card(width, height, i * 3)) |
| 5667 | .collect(); |
| 5668 | let t = Instant::now(); |
| 5669 | let encoded = encode_sequence(&pictures, 100, 0.5).unwrap(); |
| 5670 | let elapsed = t.elapsed(); |
| 5671 | let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum(); |
| 5672 | eprintln!( |
| 5673 | "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes", |
| 5674 | elapsed / 24 |
| 5675 | ); |
| 5676 | } |
| 5677 | |
| 5678 | |
| 5679 | |
| 5680 | |
| 5681 | |
| 5682 | #[test] |
| 5683 | #[ignore = "a calibration probe, not a gate"] |
| 5684 | fn calibration_sweep_base_q_idx() { |
| 5685 | if !have_ffmpeg() { |
| 5686 | eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg"); |
| 5687 | return; |
| 5688 | } |
| 5689 | let (width, height, frames) = (640usize, 384usize, 12usize); |
| 5690 | for clip in [ |
| 5691 | "h264-1080p-23.976-8bit.mp4", |
| 5692 | "h264-1080p-60-8bit.mp4", |
| 5693 | ] { |
| 5694 | let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 5695 | .join("../../fixtures/video") |
| 5696 | .join(clip); |
| 5697 | if !path.exists() { |
| 5698 | eprintln!("SKIP {clip}: fixture missing"); |
| 5699 | continue; |
| 5700 | } |
| 5701 | let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames); |
| 5702 | eprintln!("--- {clip} ---"); |
| 5703 | for q in [40u8, 70, 100, 130, 160, 190, 220, 240] { |
| 5704 | let encoded = encode_sequence(&source, q, 0.5).unwrap(); |
| 5705 | let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames); |
| 5706 | let mean_psnr: f64 = decoded |
| 5707 | .iter() |
| 5708 | .zip(&source) |
| 5709 | .map(|(d, s)| psnr(&d.y, &s.y)) |
| 5710 | .sum::<f64>() |
| 5711 | / frames as f64; |
| 5712 | let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64; |
| 5713 | eprintln!( |
| 5714 | "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB", |
| 5715 | encoded.stream.len() |
| 5716 | ); |
| 5717 | } |
| 5718 | } |
| 5719 | } |
| 5720 | } |