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