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