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