| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig}; |
| 21 | use ec_core::{Error, Result}; |
| 22 | |
| 23 | use crate::encode::{ |
| 24 | Encoded, GOLDEN_SLOT, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, |
| 25 | encode_key_frame_inner, split_blocks, |
| 26 | }; |
| 27 | use crate::intra::KEY_FRAME_MODES; |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | const DEADZONE: f64 = 0.5; |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 42 | pub enum Colour { |
| 43 | |
| 44 | |
| 45 | |
| 46 | #[default] |
| 47 | Bt709Limited, |
| 48 | |
| 49 | |
| 50 | Bt601Limited, |
| 51 | |
| 52 | |
| 53 | Unspecified, |
| 54 | } |
| 55 | |
| 56 | impl Colour { |
| 57 | fn color_config(self) -> ColorConfig { |
| 58 | let (color_primaries, transfer_characteristics, matrix_coefficients) = match self { |
| 59 | Colour::Bt709Limited => (1, 1, 1), |
| 60 | Colour::Bt601Limited => (6, 6, 6), |
| 61 | Colour::Unspecified => (2, 2, 2), |
| 62 | }; |
| 63 | ColorConfig { |
| 64 | bit_depth: 8, |
| 65 | mono_chrome: false, |
| 66 | num_planes: 3, |
| 67 | color_primaries, |
| 68 | transfer_characteristics, |
| 69 | matrix_coefficients, |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | color_range: false, |
| 75 | subsampling_x: 1, |
| 76 | subsampling_y: 1, |
| 77 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 78 | separate_uv_delta_q: false, |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 91 | pub enum RateTarget { |
| 92 | |
| 93 | |
| 94 | QIndex(u8), |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | Quality(u8), |
| 103 | |
| 104 | |
| 105 | |
| 106 | BytesPerFrame(u32), |
| 107 | |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | Bitrate { |
| 114 | |
| 115 | bits_per_second: u32, |
| 116 | |
| 117 | frames_per_second: f64, |
| 118 | }, |
| 119 | } |
| 120 | |
| 121 | impl RateTarget { |
| 122 | |
| 123 | |
| 124 | |
| 125 | fn into_loop(self, config: &mut EncoderConfig, mini_gop: Option<usize>) -> Option<RateLoop> { |
| 126 | let target_bytes = match self { |
| 127 | RateTarget::QIndex(q) => { |
| 128 | config.base_q_idx = q; |
| 129 | return None; |
| 130 | } |
| 131 | RateTarget::Quality(quality) => { |
| 132 | config.base_q_idx = quality_to_q_idx(quality); |
| 133 | return None; |
| 134 | } |
| 135 | RateTarget::BytesPerFrame(target_bytes) => f64::from(target_bytes), |
| 136 | RateTarget::Bitrate { |
| 137 | bits_per_second, |
| 138 | frames_per_second, |
| 139 | } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0), |
| 140 | }; |
| 141 | Some(RateLoop::new( |
| 142 | target_bytes, |
| 143 | f64::from(config.base_q_idx), |
| 144 | mini_gop, |
| 145 | )) |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | fn quality_to_q_idx(quality: u8) -> u8 { |
| 155 | let quality = f64::from(quality.min(100)); |
| 156 | (240.0 - quality * 2.0).round() as u8 |
| 157 | } |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | const ARF_WEIGHT: f64 = 2.0; |
| 164 | |
| 165 | |
| 166 | const KEY_WEIGHT: f64 = 3.0; |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | #[derive(Debug, Clone, Copy)] |
| 183 | struct RateLoop { |
| 184 | |
| 185 | target: [f64; 3], |
| 186 | |
| 187 | q: [f64; 3], |
| 188 | |
| 189 | |
| 190 | |
| 191 | per_level: bool, |
| 192 | } |
| 193 | |
| 194 | impl RateLoop { |
| 195 | |
| 196 | |
| 197 | |
| 198 | |
| 199 | const STEP_CLAMP: f64 = 12.0; |
| 200 | |
| 201 | |
| 202 | const GAIN: f64 = 1.0 / 0.0154; |
| 203 | |
| 204 | fn new(target_bytes: f64, start_q: f64, mini_gop: Option<usize>) -> Self { |
| 205 | let Some(m) = mini_gop.map(|m| m as f64) else { |
| 206 | return Self { |
| 207 | target: [target_bytes; 3], |
| 208 | q: [start_q; 3], |
| 209 | per_level: false, |
| 210 | }; |
| 211 | }; |
| 212 | |
| 213 | |
| 214 | |
| 215 | let share = target_bytes * m / (m - 1.0 + ARF_WEIGHT); |
| 216 | Self { |
| 217 | target: [target_bytes * KEY_WEIGHT, share * ARF_WEIGHT, share], |
| 218 | q: [start_q; 3], |
| 219 | per_level: true, |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | |
| 224 | |
| 225 | fn slot(&self, level: Level) -> usize { |
| 226 | if !self.per_level { |
| 227 | return 0; |
| 228 | } |
| 229 | match level { |
| 230 | Level::Key => 0, |
| 231 | Level::Arf => 1, |
| 232 | |
| 233 | |
| 234 | Level::Leaf | Level::ShowExisting => 2, |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | fn q_idx(&self, level: Level) -> u8 { |
| 239 | self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8 |
| 240 | } |
| 241 | |
| 242 | |
| 243 | |
| 244 | fn update(&mut self, level: Level, actual_bytes: usize) { |
| 245 | let slot = self.slot(level); |
| 246 | if self.target[slot] <= 0.0 || actual_bytes == 0 { |
| 247 | return; |
| 248 | } |
| 249 | let ratio = actual_bytes as f64 / self.target[slot]; |
| 250 | let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP); |
| 251 | self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | #[derive(Debug, Clone, Copy)] |
| 266 | pub struct EncoderConfig { |
| 267 | |
| 268 | pub width: usize, |
| 269 | |
| 270 | pub height: usize, |
| 271 | |
| 272 | pub base_q_idx: u8, |
| 273 | |
| 274 | |
| 275 | |
| 276 | pub gop: usize, |
| 277 | |
| 278 | pub colour: Colour, |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | pub tile_cols_log2: u32, |
| 284 | |
| 285 | pub tile_rows_log2: u32, |
| 286 | } |
| 287 | |
| 288 | impl EncoderConfig { |
| 289 | |
| 290 | |
| 291 | |
| 292 | |
| 293 | #[must_use] |
| 294 | pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self { |
| 295 | Self { |
| 296 | width, |
| 297 | height, |
| 298 | base_q_idx, |
| 299 | gop, |
| 300 | colour, |
| 301 | tile_cols_log2: 0, |
| 302 | tile_rows_log2: 0, |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | |
| 308 | |
| 309 | |
| 310 | #[derive(Debug, Clone)] |
| 311 | pub struct Packet { |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | pub data: Vec<u8>, |
| 319 | |
| 320 | pub key: bool, |
| 321 | |
| 322 | |
| 323 | |
| 324 | pub order: u64, |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | pub dts: u64, |
| 332 | |
| 333 | pub level: Level, |
| 334 | } |
| 335 | |
| 336 | |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 344 | pub struct Pyramid { |
| 345 | |
| 346 | |
| 347 | |
| 348 | pub mini_gop: usize, |
| 349 | |
| 350 | |
| 351 | pub arf_q_offset: i16, |
| 352 | |
| 353 | |
| 354 | pub leaf_q_offset: i16, |
| 355 | } |
| 356 | |
| 357 | impl Default for Pyramid { |
| 358 | |
| 359 | |
| 360 | |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 384 | |
| 385 | |
| 386 | |
| 387 | |
| 388 | |
| 389 | |
| 390 | |
| 391 | |
| 392 | |
| 393 | |
| 394 | |
| 395 | |
| 396 | |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | |
| 408 | |
| 409 | |
| 410 | |
| 411 | |
| 412 | |
| 413 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | |
| 418 | |
| 419 | fn default() -> Self { |
| 420 | Self { |
| 421 | mini_gop: 4, |
| 422 | arf_q_offset: -16, |
| 423 | leaf_q_offset: 8, |
| 424 | } |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | |
| 429 | |
| 430 | |
| 431 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 432 | pub enum Level { |
| 433 | |
| 434 | Key, |
| 435 | |
| 436 | Arf, |
| 437 | |
| 438 | Leaf, |
| 439 | |
| 440 | |
| 441 | ShowExisting, |
| 442 | } |
| 443 | |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | const ANCHOR_SLOTS: [u8; 2] = [3, 4]; |
| 451 | |
| 452 | |
| 453 | const LEAF_SLOT: u8 = 0; |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | #[derive(Debug)] |
| 460 | pub struct Av1Encoder { |
| 461 | config: EncoderConfig, |
| 462 | color_config: ColorConfig, |
| 463 | |
| 464 | |
| 465 | |
| 466 | |
| 467 | reference: Option<Picture>, |
| 468 | next_index: u64, |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | rate_loop: Option<RateLoop>, |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | fctx: crate::decode::FrameCtx, |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | carried_cdfs: Option<crate::encode::CdfSnapshot>, |
| 484 | |
| 485 | |
| 486 | golden: Option<Picture>, |
| 487 | |
| 488 | |
| 489 | prev2: Option<Picture>, |
| 490 | |
| 491 | |
| 492 | |
| 493 | pyramid: Option<Pyramid>, |
| 494 | |
| 495 | |
| 496 | |
| 497 | |
| 498 | dpb: [Option<DpbSlot>; 8], |
| 499 | |
| 500 | pending: Vec<(u64, Picture)>, |
| 501 | |
| 502 | |
| 503 | anchor: usize, |
| 504 | |
| 505 | next_dts: u64, |
| 506 | } |
| 507 | |
| 508 | |
| 509 | |
| 510 | #[derive(Debug, Clone)] |
| 511 | struct DpbSlot { |
| 512 | picture: Picture, |
| 513 | order_hint: u32, |
| 514 | cdfs: crate::encode::CdfSnapshot, |
| 515 | } |
| 516 | |
| 517 | |
| 518 | |
| 519 | |
| 520 | const _: fn() = || { |
| 521 | fn assert_send<T: Send>() {} |
| 522 | assert_send::<Av1Encoder>(); |
| 523 | }; |
| 524 | |
| 525 | impl Av1Encoder { |
| 526 | |
| 527 | |
| 528 | |
| 529 | |
| 530 | |
| 531 | pub fn new(config: EncoderConfig) -> Result<Self> { |
| 532 | if config.gop == 0 { |
| 533 | return Err(Error::unsupported("AV1 encode", "gop must be at least 1")); |
| 534 | } |
| 535 | |
| 536 | |
| 537 | |
| 538 | Picture::grey(config.width, config.height).check_even()?; |
| 539 | |
| 540 | |
| 541 | |
| 542 | |
| 543 | let sb_cols = config.width.div_ceil(64) as u32; |
| 544 | let sb_rows = config.height.div_ceil(64) as u32; |
| 545 | if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows { |
| 546 | return Err(Error::unsupported( |
| 547 | "AV1 encode", |
| 548 | format!( |
| 549 | "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has", |
| 550 | 1 << config.tile_cols_log2, |
| 551 | 1 << config.tile_rows_log2 |
| 552 | ), |
| 553 | )); |
| 554 | } |
| 555 | Ok(Self { |
| 556 | carried_cdfs: None, |
| 557 | golden: None, |
| 558 | prev2: None, |
| 559 | color_config: config.colour.color_config(), |
| 560 | config, |
| 561 | reference: None, |
| 562 | next_index: 0, |
| 563 | rate_loop: None, |
| 564 | fctx: crate::decode::FrameCtx::new(), |
| 565 | pyramid: None, |
| 566 | dpb: [const { None }; 8], |
| 567 | pending: Vec::new(), |
| 568 | anchor: 0, |
| 569 | next_dts: 0, |
| 570 | }) |
| 571 | } |
| 572 | |
| 573 | |
| 574 | |
| 575 | |
| 576 | |
| 577 | |
| 578 | |
| 579 | |
| 580 | |
| 581 | |
| 582 | |
| 583 | |
| 584 | pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> { |
| 585 | if pyramid.mini_gop < 2 { |
| 586 | return Err(Error::unsupported( |
| 587 | "AV1 encode", |
| 588 | "a pyramid mini-GOP is at least 2 pictures", |
| 589 | )); |
| 590 | } |
| 591 | let mut encoder = Self::new(config)?; |
| 592 | encoder.pyramid = Some(pyramid); |
| 593 | Ok(encoder) |
| 594 | } |
| 595 | |
| 596 | |
| 597 | |
| 598 | |
| 599 | |
| 600 | |
| 601 | |
| 602 | pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> { |
| 603 | let rate_loop = rate.into_loop(&mut config, None); |
| 604 | let mut encoder = Self::new(config)?; |
| 605 | encoder.rate_loop = rate_loop; |
| 606 | Ok(encoder) |
| 607 | } |
| 608 | |
| 609 | |
| 610 | |
| 611 | |
| 612 | |
| 613 | |
| 614 | |
| 615 | |
| 616 | |
| 617 | pub fn with_pyramid_and_rate_target( |
| 618 | mut config: EncoderConfig, |
| 619 | pyramid: Pyramid, |
| 620 | rate: RateTarget, |
| 621 | ) -> Result<Self> { |
| 622 | let rate_loop = rate.into_loop(&mut config, Some(pyramid.mini_gop)); |
| 623 | let mut encoder = Self::with_pyramid(config, pyramid)?; |
| 624 | encoder.rate_loop = rate_loop; |
| 625 | Ok(encoder) |
| 626 | } |
| 627 | |
| 628 | |
| 629 | |
| 630 | #[must_use] |
| 631 | pub fn coded_size(&self) -> (usize, usize) { |
| 632 | ( |
| 633 | self.config.width.next_multiple_of(SUPERBLOCK), |
| 634 | self.config.height.next_multiple_of(SUPERBLOCK), |
| 635 | ) |
| 636 | } |
| 637 | |
| 638 | |
| 639 | |
| 640 | #[must_use] |
| 641 | pub fn display_size(&self) -> (usize, usize) { |
| 642 | (self.config.width, self.config.height) |
| 643 | } |
| 644 | |
| 645 | |
| 646 | |
| 647 | |
| 648 | |
| 649 | |
| 650 | |
| 651 | |
| 652 | |
| 653 | |
| 654 | |
| 655 | |
| 656 | pub fn encode(&mut self, picture: &Picture) -> Result<Packet> { |
| 657 | if self.pyramid.is_some() { |
| 658 | return Err(Error::unsupported( |
| 659 | "AV1 encode", |
| 660 | "a pyramid stream reorders pictures -- use encode_frames()/flush()", |
| 661 | )); |
| 662 | } |
| 663 | let mut packets = self.encode_frames(picture)?; |
| 664 | Ok(packets.pop().expect("the flat path emits exactly one packet")) |
| 665 | } |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | |
| 675 | |
| 676 | pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> { |
| 677 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 678 | if (picture.width, picture.height) != (self.config.width, self.config.height) { |
| 679 | return Err(Error::unsupported( |
| 680 | "AV1 encode", |
| 681 | format!( |
| 682 | "picture is {}x{}, encoder is {}x{}", |
| 683 | picture.width, picture.height, self.config.width, self.config.height |
| 684 | ), |
| 685 | )); |
| 686 | } |
| 687 | let Some(pyramid) = self.pyramid else { |
| 688 | return Ok(vec![self.encode_flat(picture)?]); |
| 689 | }; |
| 690 | let order = self.next_index; |
| 691 | self.next_index += 1; |
| 692 | if order.is_multiple_of(self.config.gop as u64) { |
| 693 | |
| 694 | |
| 695 | |
| 696 | let mut packets = self.drain_pending()?; |
| 697 | packets.push(self.encode_key(order, picture)?); |
| 698 | return Ok(packets); |
| 699 | } |
| 700 | self.pending.push((order, picture.clone())); |
| 701 | |
| 702 | |
| 703 | let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64); |
| 704 | if self.pending.len() >= pyramid.mini_gop || next_is_key { |
| 705 | return self.drain_pending(); |
| 706 | } |
| 707 | Ok(Vec::new()) |
| 708 | } |
| 709 | |
| 710 | |
| 711 | |
| 712 | |
| 713 | |
| 714 | |
| 715 | |
| 716 | pub fn flush(&mut self) -> Result<Vec<Packet>> { |
| 717 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 718 | self.drain_pending() |
| 719 | } |
| 720 | |
| 721 | |
| 722 | fn encode_flat(&mut self, picture: &Picture) -> Result<Packet> { |
| 723 | let render = (self.config.width, self.config.height); |
| 724 | let padded = picture.padded_to(SUPERBLOCK); |
| 725 | let is_key = self.next_index.is_multiple_of(self.config.gop as u64); |
| 726 | let order = self.next_index; |
| 727 | let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| { |
| 728 | r.q_idx(if is_key { Level::Key } else { Level::Leaf }) |
| 729 | }); |
| 730 | |
| 731 | let encoded: Encoded = if is_key { |
| 732 | encode_key_frame_inner( |
| 733 | &padded, |
| 734 | base_q_idx, |
| 735 | DEADZONE, |
| 736 | &KEY_FRAME_MODES, |
| 737 | split_blocks(), |
| 738 | render, |
| 739 | self.color_config, |
| 740 | &self.fctx, |
| 741 | )? |
| 742 | } else { |
| 743 | let reference = self.reference.as_ref().ok_or_else(|| { |
| 744 | Error::unsupported( |
| 745 | "AV1 encode", |
| 746 | "an inter frame needs a previous reconstruction", |
| 747 | ) |
| 748 | })?; |
| 749 | encode_inter_frame( |
| 750 | &padded, |
| 751 | reference, |
| 752 | base_q_idx, |
| 753 | DEADZONE, |
| 754 | order as u32, |
| 755 | |
| 756 | |
| 757 | |
| 758 | |
| 759 | crate::encode::flat_order_hints( |
| 760 | order as u32 & 0x7f, |
| 761 | (order - order % self.config.gop as u64) as u32 & 0x7f, |
| 762 | self.prev2.is_some(), |
| 763 | ), |
| 764 | render, |
| 765 | self.carried_cdfs.as_ref().map(|c| &c.0), |
| 766 | self.golden.as_ref(), |
| 767 | self.prev2.as_ref(), |
| 768 | &self.fctx, |
| 769 | None, |
| 770 | )? |
| 771 | }; |
| 772 | |
| 773 | self.carried_cdfs = Some(encoded.next_cdfs.clone()); |
| 774 | if is_key { |
| 775 | self.golden = Some(encoded.reconstruction.clone()); |
| 776 | self.prev2 = None; |
| 777 | } else { |
| 778 | self.prev2 = self.reference.take(); |
| 779 | } |
| 780 | self.reference = Some(encoded.reconstruction.clone()); |
| 781 | self.next_index += 1; |
| 782 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 783 | let level = if is_key { Level::Key } else { Level::Leaf }; |
| 784 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 785 | rate_loop.update(level, cropped.stream.len()); |
| 786 | } |
| 787 | Ok(self.packet(cropped.stream, is_key, order, level)) |
| 788 | } |
| 789 | |
| 790 | |
| 791 | |
| 792 | fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet { |
| 793 | let dts = self.next_dts; |
| 794 | self.next_dts += 1; |
| 795 | Packet { |
| 796 | data, |
| 797 | key, |
| 798 | order, |
| 799 | dts, |
| 800 | level, |
| 801 | } |
| 802 | } |
| 803 | |
| 804 | |
| 805 | |
| 806 | fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) { |
| 807 | let slot = DpbSlot { |
| 808 | picture: encoded.reconstruction.clone(), |
| 809 | order_hint, |
| 810 | cdfs: encoded.next_cdfs.clone(), |
| 811 | }; |
| 812 | for &s in slots { |
| 813 | self.dpb[s as usize] = Some(slot.clone()); |
| 814 | } |
| 815 | } |
| 816 | |
| 817 | |
| 818 | |
| 819 | |
| 820 | fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> { |
| 821 | let render = (self.config.width, self.config.height); |
| 822 | let base_q_idx = self |
| 823 | .rate_loop |
| 824 | .as_ref() |
| 825 | .map_or(self.config.base_q_idx, |r| r.q_idx(Level::Key)); |
| 826 | let encoded = encode_key_frame_inner( |
| 827 | &picture.padded_to(SUPERBLOCK), |
| 828 | base_q_idx, |
| 829 | DEADZONE, |
| 830 | &KEY_FRAME_MODES, |
| 831 | split_blocks(), |
| 832 | render, |
| 833 | self.color_config, |
| 834 | &self.fctx, |
| 835 | )?; |
| 836 | self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0); |
| 837 | self.anchor = 0; |
| 838 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 839 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 840 | rate_loop.update(Level::Key, cropped.stream.len()); |
| 841 | } |
| 842 | Ok(self.packet(cropped.stream, true, order, Level::Key)) |
| 843 | } |
| 844 | |
| 845 | |
| 846 | #[allow(clippy::too_many_arguments)] |
| 847 | fn encode_pyramid_inter( |
| 848 | &mut self, |
| 849 | order: u64, |
| 850 | picture: &Picture, |
| 851 | last_slot: u8, |
| 852 | self_slot: u8, |
| 853 | altref_slot: u8, |
| 854 | show_frame: bool, |
| 855 | level: Level, |
| 856 | ) -> Result<Packet> { |
| 857 | let render = (self.config.width, self.config.height); |
| 858 | let order_hint = (order & 0x7f) as u32; |
| 859 | let pyramid = self.pyramid.expect("pyramid mode"); |
| 860 | let offset = match level { |
| 861 | Level::Arf => pyramid.arf_q_offset, |
| 862 | _ => pyramid.leaf_q_offset, |
| 863 | }; |
| 864 | let base = self |
| 865 | .rate_loop |
| 866 | .as_ref() |
| 867 | .map_or(i16::from(self.config.base_q_idx), |r| { |
| 868 | i16::from(r.q_idx(level)) |
| 869 | }); |
| 870 | let base_q_idx = (base + offset).clamp(1, 255) as u8; |
| 871 | |
| 872 | |
| 873 | |
| 874 | |
| 875 | |
| 876 | |
| 877 | let mut sign_bias = crate::mvstack::NO_SIGN_BIAS; |
| 878 | let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| { |
| 879 | dpb[slot as usize] |
| 880 | .as_ref() |
| 881 | .is_some_and(|s| s.order_hint > order_hint) |
| 882 | }; |
| 883 | let slots = [ |
| 884 | last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot, |
| 885 | ]; |
| 886 | for (i, slot) in slots.into_iter().enumerate() { |
| 887 | sign_bias[i] = ahead(slot, &self.dpb); |
| 888 | } |
| 889 | |
| 890 | |
| 891 | let order_hints: [u32; 7] = slots.map(|slot| { |
| 892 | self.dpb[slot as usize] |
| 893 | .as_ref() |
| 894 | .map_or(0, |s| (s.order_hint & 0x7f) as u32) |
| 895 | }); |
| 896 | let reference = self.dpb[last_slot as usize] |
| 897 | .as_ref() |
| 898 | .map(|s| s.picture.clone()) |
| 899 | .ok_or_else(|| { |
| 900 | Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction") |
| 901 | })?; |
| 902 | let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone()); |
| 903 | let altref = (altref_slot != GOLDEN_SLOT) |
| 904 | .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) |
| 905 | .flatten(); |
| 906 | let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone()); |
| 907 | let encoded = || -> Result<Encoded> { encode_inter_frame( |
| 908 | &picture.padded_to(SUPERBLOCK), |
| 909 | &reference, |
| 910 | base_q_idx, |
| 911 | DEADZONE, |
| 912 | order_hint, |
| 913 | order_hints, |
| 914 | render, |
| 915 | start_cdfs.as_ref(), |
| 916 | golden.as_ref(), |
| 917 | altref.as_ref(), |
| 918 | &self.fctx, |
| 919 | Some(crate::encode::PyramidFrame { |
| 920 | last_slot, |
| 921 | self_slot, |
| 922 | altref_slot, |
| 923 | show_frame, |
| 924 | sign_bias, |
| 925 | }), |
| 926 | ) }(); |
| 927 | |
| 928 | |
| 929 | |
| 930 | let encoded = encoded.map_err(|e| { |
| 931 | Error::unsupported( |
| 932 | "AV1 encode", |
| 933 | format!( |
| 934 | "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \ |
| 935 | altref {altref_slot}, shown {show_frame}, golden {}, altref pic {}): {e}", |
| 936 | golden.is_some(), |
| 937 | altref.is_some(), |
| 938 | ), |
| 939 | ) |
| 940 | })?; |
| 941 | self.refresh(&[self_slot], &encoded, order_hint); |
| 942 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 943 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 944 | rate_loop.update(level, cropped.stream.len()); |
| 945 | } |
| 946 | Ok(self.packet(cropped.stream, false, order, level)) |
| 947 | } |
| 948 | |
| 949 | |
| 950 | |
| 951 | |
| 952 | fn drain_pending(&mut self) -> Result<Vec<Packet>> { |
| 953 | if self.pending.is_empty() { |
| 954 | return Ok(Vec::new()); |
| 955 | } |
| 956 | let group: Vec<(u64, Picture)> = std::mem::take(&mut self.pending); |
| 957 | let mut packets = Vec::with_capacity(group.len() + 1); |
| 958 | let anchor_slot = ANCHOR_SLOTS[self.anchor]; |
| 959 | let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor]; |
| 960 | let (arf_order, arf_picture) = group.last().cloned().expect("non-empty"); |
| 961 | if group.len() == 1 { |
| 962 | |
| 963 | |
| 964 | packets.push(self.encode_pyramid_inter( |
| 965 | arf_order, |
| 966 | &arf_picture, |
| 967 | anchor_slot, |
| 968 | next_anchor_slot, |
| 969 | GOLDEN_SLOT, |
| 970 | true, |
| 971 | Level::Leaf, |
| 972 | )?); |
| 973 | self.anchor = 1 - self.anchor; |
| 974 | return Ok(packets); |
| 975 | } |
| 976 | packets.push(self.encode_pyramid_inter( |
| 977 | arf_order, |
| 978 | &arf_picture, |
| 979 | anchor_slot, |
| 980 | next_anchor_slot, |
| 981 | GOLDEN_SLOT, |
| 982 | false, |
| 983 | Level::Arf, |
| 984 | )?); |
| 985 | for (i, (order, picture)) in group[..group.len() - 1].iter().enumerate() { |
| 986 | let last_slot = if i == 0 { anchor_slot } else { LEAF_SLOT }; |
| 987 | packets.push(self.encode_pyramid_inter( |
| 988 | *order, |
| 989 | picture, |
| 990 | last_slot, |
| 991 | LEAF_SLOT, |
| 992 | next_anchor_slot, |
| 993 | true, |
| 994 | Level::Leaf, |
| 995 | )?); |
| 996 | } |
| 997 | let (seq, _) = crate::encode::key_frame_headers( |
| 998 | self.config.width, |
| 999 | self.config.height, |
| 1000 | self.config.base_q_idx, |
| 1001 | )?; |
| 1002 | let mut data = crate::obu::temporal_delimiter(); |
| 1003 | data.extend_from_slice(&crate::frame::show_existing_frame_obu( |
| 1004 | &seq, |
| 1005 | next_anchor_slot, |
| 1006 | )?); |
| 1007 | packets.push(self.packet(data, false, arf_order, Level::ShowExisting)); |
| 1008 | self.anchor = 1 - self.anchor; |
| 1009 | Ok(packets) |
| 1010 | } |
| 1011 | } |
| 1012 | |
| 1013 | #[cfg(test)] |
| 1014 | mod tests { |
| 1015 | use super::*; |
| 1016 | use std::process::{Command, Stdio}; |
| 1017 | |
| 1018 | |
| 1019 | |
| 1020 | |
| 1021 | |
| 1022 | |
| 1023 | |
| 1024 | |
| 1025 | fn have_ffmpeg() -> bool { |
| 1026 | let present = Command::new("ffmpeg") |
| 1027 | .arg("-version") |
| 1028 | .stdout(Stdio::null()) |
| 1029 | .stderr(Stdio::null()) |
| 1030 | .status() |
| 1031 | .is_ok_and(|s| s.success()); |
| 1032 | assert!( |
| 1033 | present |
| 1034 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 1035 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 1036 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 1037 | ); |
| 1038 | present |
| 1039 | } |
| 1040 | |
| 1041 | fn test_card(width: usize, height: usize, shift: usize) -> Picture { |
| 1042 | let mut picture = Picture::grey(width, height); |
| 1043 | for y in 0..height { |
| 1044 | for x in 0..width { |
| 1045 | let sx = (x + shift) % width; |
| 1046 | picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16; |
| 1047 | } |
| 1048 | } |
| 1049 | for y in 0..height / 2 { |
| 1050 | for x in 0..width / 2 { |
| 1051 | let i = y * (width / 2) + x; |
| 1052 | picture.u[i] = ((100 + shift * 4) % 256) as u16; |
| 1053 | picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16; |
| 1054 | } |
| 1055 | } |
| 1056 | picture |
| 1057 | } |
| 1058 | |
| 1059 | |
| 1060 | |
| 1061 | fn concat(packets: &[Packet]) -> Vec<u8> { |
| 1062 | packets.iter().flat_map(|p| p.data.clone()).collect() |
| 1063 | } |
| 1064 | |
| 1065 | |
| 1066 | |
| 1067 | |
| 1068 | #[test] |
| 1069 | fn one_in_one_out() { |
| 1070 | let config = EncoderConfig { |
| 1071 | width: 64, |
| 1072 | height: 64, |
| 1073 | base_q_idx: 100, |
| 1074 | gop: 2, |
| 1075 | colour: Colour::Bt709Limited, |
| 1076 | tile_cols_log2: 0, |
| 1077 | tile_rows_log2: 0, |
| 1078 | }; |
| 1079 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1080 | for t in 0..5u64 { |
| 1081 | let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); |
| 1082 | assert!(!packet.data.is_empty(), "picture {t}: empty packet"); |
| 1083 | assert_eq!(packet.order, t, "picture {t}: order"); |
| 1084 | } |
| 1085 | } |
| 1086 | |
| 1087 | |
| 1088 | |
| 1089 | |
| 1090 | #[test] |
| 1091 | fn gop_cadence_is_honored() { |
| 1092 | let config = EncoderConfig { |
| 1093 | width: 64, |
| 1094 | height: 64, |
| 1095 | base_q_idx: 100, |
| 1096 | gop: 3, |
| 1097 | colour: Colour::Unspecified, |
| 1098 | tile_cols_log2: 0, |
| 1099 | tile_rows_log2: 0, |
| 1100 | }; |
| 1101 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1102 | let keys: Vec<bool> = (0..7) |
| 1103 | .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key) |
| 1104 | .collect(); |
| 1105 | assert_eq!(keys, vec![true, false, false, true, false, false, true]); |
| 1106 | } |
| 1107 | |
| 1108 | fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { |
| 1109 | let path = std::env::temp_dir().join(format!( |
| 1110 | "ec-av1-facade-probe-{}-{}.obu", |
| 1111 | std::process::id(), |
| 1112 | std::ptr::addr_of!(stream) as usize |
| 1113 | )); |
| 1114 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 1115 | let out = Command::new("ffprobe") |
| 1116 | .args([ |
| 1117 | "-v", |
| 1118 | "error", |
| 1119 | "-f", |
| 1120 | "obu", |
| 1121 | "-select_streams", |
| 1122 | "v:0", |
| 1123 | "-show_entries", |
| 1124 | "frame=key_frame,width,height", |
| 1125 | "-of", |
| 1126 | "csv=p=0", |
| 1127 | ]) |
| 1128 | .arg(&path) |
| 1129 | .output() |
| 1130 | .expect("ffprobe failed to run"); |
| 1131 | let _ = std::fs::remove_file(&path); |
| 1132 | assert!( |
| 1133 | out.status.success(), |
| 1134 | "ffprobe refused the stream: {}", |
| 1135 | String::from_utf8_lossy(&out.stderr) |
| 1136 | ); |
| 1137 | String::from_utf8_lossy(&out.stdout) |
| 1138 | .lines() |
| 1139 | .map(|line| { |
| 1140 | let mut f = line.trim().split(','); |
| 1141 | let key: u32 = f.next().unwrap().parse().unwrap(); |
| 1142 | let width: u32 = f.next().unwrap().parse().unwrap(); |
| 1143 | let height: u32 = f.next().unwrap().parse().unwrap(); |
| 1144 | (key == 1, width, height) |
| 1145 | }) |
| 1146 | .collect() |
| 1147 | } |
| 1148 | |
| 1149 | fn ffprobe_colour(stream: &[u8]) -> String { |
| 1150 | let path = std::env::temp_dir().join(format!( |
| 1151 | "ec-av1-facade-colour-probe-{}-{}.obu", |
| 1152 | std::process::id(), |
| 1153 | std::ptr::addr_of!(stream) as usize |
| 1154 | )); |
| 1155 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 1156 | let out = Command::new("ffprobe") |
| 1157 | .args([ |
| 1158 | "-v", |
| 1159 | "error", |
| 1160 | "-f", |
| 1161 | "obu", |
| 1162 | "-select_streams", |
| 1163 | "v:0", |
| 1164 | "-show_entries", |
| 1165 | "stream=color_primaries,color_transfer,color_space,color_range", |
| 1166 | "-of", |
| 1167 | "csv=p=0", |
| 1168 | ]) |
| 1169 | .arg(&path) |
| 1170 | .output() |
| 1171 | .expect("ffprobe failed to run"); |
| 1172 | let _ = std::fs::remove_file(&path); |
| 1173 | assert!( |
| 1174 | out.status.success(), |
| 1175 | "ffprobe refused the stream: {}", |
| 1176 | String::from_utf8_lossy(&out.stderr) |
| 1177 | ); |
| 1178 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 1179 | } |
| 1180 | |
| 1181 | |
| 1182 | |
| 1183 | |
| 1184 | |
| 1185 | #[test] |
| 1186 | fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { |
| 1187 | if !have_ffmpeg() { |
| 1188 | eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg"); |
| 1189 | return; |
| 1190 | } |
| 1191 | let (width, height) = (96usize, 96usize); |
| 1192 | let config = EncoderConfig { |
| 1193 | width, |
| 1194 | height, |
| 1195 | base_q_idx: 120, |
| 1196 | gop: 15, |
| 1197 | colour: Colour::Bt709Limited, |
| 1198 | tile_cols_log2: 0, |
| 1199 | tile_rows_log2: 0, |
| 1200 | }; |
| 1201 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1202 | assert_eq!(enc.display_size(), (width, height)); |
| 1203 | let (coded_w, coded_h) = enc.coded_size(); |
| 1204 | assert_eq!( |
| 1205 | (coded_w, coded_h), |
| 1206 | ( |
| 1207 | width.next_multiple_of(SUPERBLOCK), |
| 1208 | height.next_multiple_of(SUPERBLOCK) |
| 1209 | ) |
| 1210 | ); |
| 1211 | |
| 1212 | let packets: Vec<Packet> = (0..30) |
| 1213 | .map(|t| enc.encode(&test_card(width, height, t)).unwrap()) |
| 1214 | .collect(); |
| 1215 | let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect(); |
| 1216 | assert_eq!( |
| 1217 | packets.iter().map(|p| p.key).collect::<Vec<_>>(), |
| 1218 | expect_key, |
| 1219 | "facade's own key/inter flags" |
| 1220 | ); |
| 1221 | |
| 1222 | let stream = concat(&packets); |
| 1223 | let frames = ffprobe_frames(&stream); |
| 1224 | assert_eq!(frames.len(), 30, "ffprobe frame count"); |
| 1225 | for (t, (key, w, h)) in frames.iter().enumerate() { |
| 1226 | assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); |
| 1227 | assert_eq!( |
| 1228 | (*w, *h), |
| 1229 | (width as u32, height as u32), |
| 1230 | "picture {t}: ffprobe reports the true (display) size, not the padded coded one" |
| 1231 | ); |
| 1232 | } |
| 1233 | } |
| 1234 | |
| 1235 | |
| 1236 | |
| 1237 | |
| 1238 | |
| 1239 | |
| 1240 | |
| 1241 | #[test] |
| 1242 | fn bt709_limited_colour_is_reported_by_ffprobe() { |
| 1243 | if !have_ffmpeg() { |
| 1244 | eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 1245 | return; |
| 1246 | } |
| 1247 | let config = EncoderConfig { |
| 1248 | width: 64, |
| 1249 | height: 64, |
| 1250 | base_q_idx: 100, |
| 1251 | gop: 4, |
| 1252 | colour: Colour::Bt709Limited, |
| 1253 | tile_cols_log2: 0, |
| 1254 | tile_rows_log2: 0, |
| 1255 | }; |
| 1256 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1257 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 1258 | let colour = ffprobe_colour(&packet.data); |
| 1259 | assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); |
| 1260 | } |
| 1261 | |
| 1262 | |
| 1263 | |
| 1264 | |
| 1265 | #[test] |
| 1266 | fn bt601_limited_colour_is_reported_by_ffprobe() { |
| 1267 | if !have_ffmpeg() { |
| 1268 | eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 1269 | return; |
| 1270 | } |
| 1271 | let config = EncoderConfig { |
| 1272 | width: 64, |
| 1273 | height: 64, |
| 1274 | base_q_idx: 100, |
| 1275 | gop: 4, |
| 1276 | colour: Colour::Bt601Limited, |
| 1277 | tile_cols_log2: 0, |
| 1278 | tile_rows_log2: 0, |
| 1279 | }; |
| 1280 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1281 | let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); |
| 1282 | let colour = ffprobe_colour(&packet.data); |
| 1283 | assert_eq!( |
| 1284 | colour, "tv,smpte170m,smpte170m,smpte170m", |
| 1285 | "ffprobe colour fields" |
| 1286 | ); |
| 1287 | } |
| 1288 | |
| 1289 | |
| 1290 | |
| 1291 | #[test] |
| 1292 | fn geometry_mismatch_is_refused() { |
| 1293 | let config = EncoderConfig { |
| 1294 | width: 64, |
| 1295 | height: 64, |
| 1296 | base_q_idx: 100, |
| 1297 | gop: 4, |
| 1298 | colour: Colour::Bt709Limited, |
| 1299 | tile_cols_log2: 0, |
| 1300 | tile_rows_log2: 0, |
| 1301 | }; |
| 1302 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1303 | let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); |
| 1304 | assert!(err.to_string().contains("64x64"), "{err}"); |
| 1305 | } |
| 1306 | |
| 1307 | |
| 1308 | #[test] |
| 1309 | fn zero_gop_is_refused() { |
| 1310 | let config = EncoderConfig { |
| 1311 | width: 64, |
| 1312 | height: 64, |
| 1313 | base_q_idx: 100, |
| 1314 | gop: 0, |
| 1315 | colour: Colour::Bt709Limited, |
| 1316 | tile_cols_log2: 0, |
| 1317 | tile_rows_log2: 0, |
| 1318 | }; |
| 1319 | let err = Av1Encoder::new(config).unwrap_err(); |
| 1320 | assert!(err.to_string().contains("gop"), "{err}"); |
| 1321 | } |
| 1322 | |
| 1323 | |
| 1324 | |
| 1325 | |
| 1326 | |
| 1327 | |
| 1328 | fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> { |
| 1329 | if !have_ffmpeg() { |
| 1330 | return None; |
| 1331 | } |
| 1332 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 1333 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 1334 | if !clip.exists() { |
| 1335 | return None; |
| 1336 | } |
| 1337 | let out = Command::new("ffmpeg") |
| 1338 | .args(["-v", "error", "-i", clip.to_str().unwrap()]) |
| 1339 | .args(["-frames:v", &frames.to_string()]) |
| 1340 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 1341 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 1342 | .output() |
| 1343 | .expect("ffmpeg failed to run"); |
| 1344 | assert!( |
| 1345 | out.status.success(), |
| 1346 | "{}", |
| 1347 | String::from_utf8_lossy(&out.stderr) |
| 1348 | ); |
| 1349 | let (luma, chroma) = (width * height, width * height / 4); |
| 1350 | let frame_len = luma + 2 * chroma; |
| 1351 | assert_eq!( |
| 1352 | out.stdout.len(), |
| 1353 | frame_len * frames, |
| 1354 | "expected {frames} 4:2:0 frames" |
| 1355 | ); |
| 1356 | Some( |
| 1357 | (0..frames) |
| 1358 | .map(|i| { |
| 1359 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 1360 | Picture { |
| 1361 | width, |
| 1362 | height, |
| 1363 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 1364 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 1365 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 1366 | } |
| 1367 | }) |
| 1368 | .collect(), |
| 1369 | ) |
| 1370 | } |
| 1371 | |
| 1372 | |
| 1373 | |
| 1374 | |
| 1375 | |
| 1376 | #[test] |
| 1377 | fn bytes_per_frame_target_settles_within_20_percent() { |
| 1378 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 1379 | eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture"); |
| 1380 | return; |
| 1381 | }; |
| 1382 | let target_bytes = 4_000u32; |
| 1383 | let config = EncoderConfig { |
| 1384 | width: 640, |
| 1385 | height: 384, |
| 1386 | base_q_idx: 100, |
| 1387 | gop: 24, |
| 1388 | colour: Colour::Bt709Limited, |
| 1389 | tile_cols_log2: 0, |
| 1390 | tile_rows_log2: 0, |
| 1391 | }; |
| 1392 | let mut enc = |
| 1393 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); |
| 1394 | let sizes: Vec<usize> = pictures |
| 1395 | .iter() |
| 1396 | .map(|p| enc.encode(p).unwrap().data.len()) |
| 1397 | .collect(); |
| 1398 | |
| 1399 | |
| 1400 | let settled = &sizes[5..]; |
| 1401 | let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64; |
| 1402 | let low = f64::from(target_bytes) * 0.8; |
| 1403 | let high = f64::from(target_bytes) * 1.2; |
| 1404 | assert!( |
| 1405 | mean >= low && mean <= high, |
| 1406 | "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" |
| 1407 | ); |
| 1408 | } |
| 1409 | |
| 1410 | |
| 1411 | |
| 1412 | |
| 1413 | |
| 1414 | |
| 1415 | #[test] |
| 1416 | fn bitrate_target_lands_within_10_percent_over_48_frames() { |
| 1417 | let (width, height, frames) = (640usize, 384usize, 48usize); |
| 1418 | let Some(pictures) = h264_clip_frames(width, height, frames) else { |
| 1419 | eprintln!("SKIP bitrate_target_lands_within_10_percent_over_48_frames: no ffmpeg/fixture"); |
| 1420 | return; |
| 1421 | }; |
| 1422 | let fps = 24.0; |
| 1423 | for bits_per_second in [768_000u32, 1_536_000] { |
| 1424 | let config = EncoderConfig { |
| 1425 | width, |
| 1426 | height, |
| 1427 | base_q_idx: 100, |
| 1428 | gop: frames, |
| 1429 | colour: Colour::Bt709Limited, |
| 1430 | tile_cols_log2: 0, |
| 1431 | tile_rows_log2: 0, |
| 1432 | }; |
| 1433 | let rate = RateTarget::Bitrate { |
| 1434 | bits_per_second, |
| 1435 | frames_per_second: fps, |
| 1436 | }; |
| 1437 | for pyramid in [None, Some(Pyramid::default())] { |
| 1438 | let mut enc = match pyramid { |
| 1439 | None => Av1Encoder::with_rate_target(config, rate).unwrap(), |
| 1440 | Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(), |
| 1441 | }; |
| 1442 | let mut coded = 0usize; |
| 1443 | for picture in &pictures { |
| 1444 | for packet in enc.encode_frames(picture).unwrap() { |
| 1445 | coded += packet.data.len(); |
| 1446 | } |
| 1447 | } |
| 1448 | for packet in enc.flush().unwrap() { |
| 1449 | coded += packet.data.len(); |
| 1450 | } |
| 1451 | let seconds = frames as f64 / fps; |
| 1452 | let achieved = coded as f64 * 8.0 / seconds; |
| 1453 | let error = achieved / f64::from(bits_per_second) - 1.0; |
| 1454 | eprintln!( |
| 1455 | "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \ |
| 1456 | = {achieved:.0} bps ({:+.1}%)", |
| 1457 | pyramid.is_some(), |
| 1458 | 100.0 * error, |
| 1459 | ); |
| 1460 | assert!( |
| 1461 | error.abs() <= 0.10, |
| 1462 | "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \ |
| 1463 | (pyramid {})", |
| 1464 | 100.0 * error, |
| 1465 | pyramid.is_some(), |
| 1466 | ); |
| 1467 | } |
| 1468 | } |
| 1469 | } |
| 1470 | |
| 1471 | |
| 1472 | |
| 1473 | |
| 1474 | |
| 1475 | #[test] |
| 1476 | fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { |
| 1477 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 1478 | eprintln!( |
| 1479 | "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture" |
| 1480 | ); |
| 1481 | return; |
| 1482 | }; |
| 1483 | let config = EncoderConfig { |
| 1484 | width: 640, |
| 1485 | height: 384, |
| 1486 | base_q_idx: 100, |
| 1487 | gop: 24, |
| 1488 | colour: Colour::Bt709Limited, |
| 1489 | tile_cols_log2: 0, |
| 1490 | tile_rows_log2: 0, |
| 1491 | }; |
| 1492 | let mut enc = |
| 1493 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); |
| 1494 | let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 1495 | for picture in &pictures { |
| 1496 | enc.encode(picture).unwrap(); |
| 1497 | let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 1498 | let step = (i32::from(q) - i32::from(prev_q)).abs(); |
| 1499 | assert!( |
| 1500 | f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, |
| 1501 | "q stepped from {prev_q} to {q}, past the {} clamp", |
| 1502 | RateLoop::STEP_CLAMP |
| 1503 | ); |
| 1504 | prev_q = q; |
| 1505 | } |
| 1506 | } |
| 1507 | |
| 1508 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 1509 | let squared: f64 = a |
| 1510 | .iter() |
| 1511 | .zip(b) |
| 1512 | .map(|(&x, &y)| { |
| 1513 | let d = f64::from(x) - f64::from(y); |
| 1514 | d * d |
| 1515 | }) |
| 1516 | .sum(); |
| 1517 | if squared == 0.0 { |
| 1518 | return f64::INFINITY; |
| 1519 | } |
| 1520 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 1521 | } |
| 1522 | |
| 1523 | |
| 1524 | |
| 1525 | |
| 1526 | |
| 1527 | fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> { |
| 1528 | let path = std::env::temp_dir().join(format!( |
| 1529 | "ec-av1-facade-rate-decode-{}-{}.obu", |
| 1530 | std::process::id(), |
| 1531 | std::ptr::addr_of!(stream) as usize |
| 1532 | )); |
| 1533 | std::fs::write(&path, stream).expect("writing the decode probe stream"); |
| 1534 | let out = Command::new("ffmpeg") |
| 1535 | .args(["-v", "error", "-f", "obu", "-i"]) |
| 1536 | .arg(&path) |
| 1537 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 1538 | .output() |
| 1539 | .expect("ffmpeg failed to run"); |
| 1540 | let _ = std::fs::remove_file(&path); |
| 1541 | assert!( |
| 1542 | out.status.success(), |
| 1543 | "{}", |
| 1544 | String::from_utf8_lossy(&out.stderr) |
| 1545 | ); |
| 1546 | let (luma, chroma) = (width * height, width * height / 4); |
| 1547 | let frame_len = luma + 2 * chroma; |
| 1548 | out.stdout |
| 1549 | .chunks_exact(frame_len) |
| 1550 | .map(|f| f[..luma].to_vec()) |
| 1551 | .collect() |
| 1552 | } |
| 1553 | |
| 1554 | |
| 1555 | |
| 1556 | |
| 1557 | |
| 1558 | |
| 1559 | |
| 1560 | |
| 1561 | |
| 1562 | |
| 1563 | |
| 1564 | #[test] |
| 1565 | fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { |
| 1566 | let (width, height) = (128usize, 128usize); |
| 1567 | let config = EncoderConfig { |
| 1568 | width, |
| 1569 | height, |
| 1570 | base_q_idx: 120, |
| 1571 | gop: 32, |
| 1572 | colour: Colour::Bt709Limited, |
| 1573 | tile_cols_log2: 0, |
| 1574 | tile_rows_log2: 0, |
| 1575 | }; |
| 1576 | let pyramid = Pyramid { |
| 1577 | mini_gop: 4, |
| 1578 | ..Pyramid::default() |
| 1579 | }; |
| 1580 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 1581 | let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect(); |
| 1582 | let _ = crate::encode::take_ref_frame_hits(); |
| 1583 | let mut packets = Vec::new(); |
| 1584 | for picture in &sources { |
| 1585 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 1586 | } |
| 1587 | packets.extend(enc.flush().unwrap()); |
| 1588 | |
| 1589 | |
| 1590 | |
| 1591 | let coded: Vec<u64> = packets |
| 1592 | .iter() |
| 1593 | .filter(|p| p.level != Level::ShowExisting) |
| 1594 | .map(|p| p.order) |
| 1595 | .collect(); |
| 1596 | let mut sorted = coded.clone(); |
| 1597 | sorted.sort_unstable(); |
| 1598 | assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture"); |
| 1599 | assert_ne!(coded, sorted, "the pyramid never reordered anything"); |
| 1600 | let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); |
| 1601 | assert_eq!(shown, 2, "one show_existing_frame per closed mini-GOP"); |
| 1602 | for (i, p) in packets.iter().enumerate() { |
| 1603 | assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); |
| 1604 | } |
| 1605 | let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); |
| 1606 | eprintln!( |
| 1607 | "pyramid levels: key {} arf {} leaf {} show_existing {}", |
| 1608 | hist(Level::Key), |
| 1609 | hist(Level::Arf), |
| 1610 | hist(Level::Leaf), |
| 1611 | hist(Level::ShowExisting), |
| 1612 | ); |
| 1613 | assert_eq!(hist(Level::Arf), 2, "two hidden frames"); |
| 1614 | let refs = crate::encode::take_ref_frame_hits(); |
| 1615 | eprintln!( |
| 1616 | "blocks per reference: LAST {} GOLDEN {} ALTREF {}", |
| 1617 | refs[crate::mvstack::LAST_FRAME as usize], |
| 1618 | refs[crate::mvstack::GOLDEN_FRAME as usize], |
| 1619 | refs[crate::mvstack::ALTREF_FRAME as usize], |
| 1620 | ); |
| 1621 | |
| 1622 | |
| 1623 | |
| 1624 | |
| 1625 | |
| 1626 | assert!( |
| 1627 | refs[crate::mvstack::ALTREF_FRAME as usize] > 0, |
| 1628 | "no block predicted off the hidden ALTREF" |
| 1629 | ); |
| 1630 | |
| 1631 | let stream = concat(&packets); |
| 1632 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 1633 | assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); |
| 1634 | if !have_ffmpeg() { |
| 1635 | eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg"); |
| 1636 | return; |
| 1637 | } |
| 1638 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 1639 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); |
| 1640 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 1641 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 1642 | assert_eq!(got.len(), b.len(), "frame {i}: luma size"); |
| 1643 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 1644 | panic!( |
| 1645 | "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 1646 | at % width, |
| 1647 | at / width, |
| 1648 | got[at], |
| 1649 | b[at], |
| 1650 | ); |
| 1651 | } |
| 1652 | } |
| 1653 | } |
| 1654 | |
| 1655 | |
| 1656 | |
| 1657 | |
| 1658 | |
| 1659 | |
| 1660 | |
| 1661 | |
| 1662 | |
| 1663 | |
| 1664 | |
| 1665 | |
| 1666 | #[test] |
| 1667 | fn every_tile_layout_decodes_sample_exact_through_both_decoders() { |
| 1668 | let (width, height) = (640usize, 384usize); |
| 1669 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 1670 | let mut sizes = Vec::new(); |
| 1671 | for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] { |
| 1672 | let config = EncoderConfig { |
| 1673 | width, |
| 1674 | height, |
| 1675 | base_q_idx: 120, |
| 1676 | gop: 4, |
| 1677 | colour: Colour::Bt709Limited, |
| 1678 | tile_cols_log2: cols_log2, |
| 1679 | tile_rows_log2: rows_log2, |
| 1680 | }; |
| 1681 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 1682 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1683 | let mut stream = Vec::new(); |
| 1684 | for (i, picture) in sources.iter().enumerate() { |
| 1685 | let packet = enc |
| 1686 | .encode(picture) |
| 1687 | .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}")); |
| 1688 | stream.extend_from_slice(&packet.data); |
| 1689 | } |
| 1690 | sizes.push((layout.clone(), stream.len())); |
| 1691 | |
| 1692 | |
| 1693 | let mut parser = ec_av1_syntax::Av1Parser::new(); |
| 1694 | let mut frames = 0usize; |
| 1695 | let mut offset = 0usize; |
| 1696 | while offset < stream.len() { |
| 1697 | let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); |
| 1698 | let unit: usize = obus.iter().map(|o| o.total_size).sum(); |
| 1699 | for obu in &obus { |
| 1700 | if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { |
| 1701 | assert_eq!( |
| 1702 | (parsed.tile_info.cols, parsed.tile_info.rows), |
| 1703 | (1 << cols_log2, 1 << rows_log2), |
| 1704 | "{layout}: the header's own tile grid" |
| 1705 | ); |
| 1706 | assert_eq!( |
| 1707 | tiles.len(), |
| 1708 | 1 << (cols_log2 + rows_log2), |
| 1709 | "{layout}: tile payloads located in the tile group" |
| 1710 | ); |
| 1711 | frames += 1; |
| 1712 | } |
| 1713 | } |
| 1714 | offset += unit; |
| 1715 | } |
| 1716 | assert_eq!(frames, sources.len(), "{layout}: coded frames"); |
| 1717 | |
| 1718 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 1719 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 1720 | if !have_ffmpeg() { |
| 1721 | eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg"); |
| 1722 | continue; |
| 1723 | } |
| 1724 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 1725 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 1726 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 1727 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 1728 | assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); |
| 1729 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 1730 | panic!( |
| 1731 | "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 1732 | at % width, |
| 1733 | at / width, |
| 1734 | got[at], |
| 1735 | b[at], |
| 1736 | ); |
| 1737 | } |
| 1738 | } |
| 1739 | } |
| 1740 | let base = sizes[0].1 as f64; |
| 1741 | for (layout, bytes) in &sizes { |
| 1742 | eprintln!( |
| 1743 | "{layout}: {bytes} bytes ({:+.2}% vs one tile)", |
| 1744 | (*bytes as f64 / base - 1.0) * 100.0 |
| 1745 | ); |
| 1746 | } |
| 1747 | } |
| 1748 | |
| 1749 | |
| 1750 | |
| 1751 | |
| 1752 | #[test] |
| 1753 | #[ignore = "1080p wall table: minutes, run it with --ignored"] |
| 1754 | fn tile_wall_table_at_1080p() { |
| 1755 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 1756 | let (width, height) = (1920usize, 1080usize); |
| 1757 | let Some(sources) = h264_clip_frames(width, height, 8) else { |
| 1758 | eprintln!("SKIP tile_wall_table_at_1080p: no fixture"); |
| 1759 | return; |
| 1760 | }; |
| 1761 | let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)]; |
| 1762 | let threadings = [1usize, 2, 4, 8]; |
| 1763 | let mut table: Vec<(String, usize, f64, usize)> = Vec::new(); |
| 1764 | for pass in 0..2 { |
| 1765 | for &(cols_log2, rows_log2) in &layouts { |
| 1766 | for &threads in &threadings { |
| 1767 | crate::par::set_tile_threads(threads); |
| 1768 | let config = EncoderConfig { |
| 1769 | width, |
| 1770 | height, |
| 1771 | base_q_idx: 120, |
| 1772 | gop: 8, |
| 1773 | colour: Colour::Bt709Limited, |
| 1774 | tile_cols_log2: cols_log2, |
| 1775 | tile_rows_log2: rows_log2, |
| 1776 | }; |
| 1777 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1778 | let start = std::time::Instant::now(); |
| 1779 | let mut bytes = 0usize; |
| 1780 | for picture in &sources { |
| 1781 | bytes += enc.encode(picture).unwrap().data.len(); |
| 1782 | } |
| 1783 | let wall = start.elapsed().as_secs_f64(); |
| 1784 | let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2); |
| 1785 | match table.iter_mut().find(|r| r.0 == name && r.1 == threads) { |
| 1786 | Some(row) => row.2 = row.2.min(wall), |
| 1787 | None => table.push((name, threads, wall, bytes)), |
| 1788 | } |
| 1789 | let _ = pass; |
| 1790 | } |
| 1791 | } |
| 1792 | } |
| 1793 | crate::par::set_tile_threads(1); |
| 1794 | eprintln!("| tiles | threads | wall (s, best of 2) | bytes |"); |
| 1795 | for (name, threads, wall, bytes) in &table { |
| 1796 | eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |"); |
| 1797 | } |
| 1798 | } |
| 1799 | |
| 1800 | |
| 1801 | |
| 1802 | |
| 1803 | #[test] |
| 1804 | fn tile_bytes_do_not_depend_on_the_thread_count() { |
| 1805 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 1806 | let (width, height) = (320usize, 192usize); |
| 1807 | let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect(); |
| 1808 | let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { |
| 1809 | crate::par::set_tile_threads(threads); |
| 1810 | let config = EncoderConfig { |
| 1811 | width, |
| 1812 | height, |
| 1813 | base_q_idx: 120, |
| 1814 | gop: 3, |
| 1815 | colour: Colour::Bt709Limited, |
| 1816 | tile_cols_log2: cols_log2, |
| 1817 | tile_rows_log2: rows_log2, |
| 1818 | }; |
| 1819 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1820 | let mut stream = Vec::new(); |
| 1821 | for picture in &sources { |
| 1822 | stream.extend_from_slice(&enc.encode(picture).unwrap().data); |
| 1823 | } |
| 1824 | stream |
| 1825 | }; |
| 1826 | for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { |
| 1827 | let one = coded(1, cols_log2, rows_log2); |
| 1828 | let four = coded(4, cols_log2, rows_log2); |
| 1829 | assert_eq!( |
| 1830 | one, |
| 1831 | four, |
| 1832 | "{}x{} tiles: {} bytes at one thread, {} at four", |
| 1833 | 1 << cols_log2, |
| 1834 | 1 << rows_log2, |
| 1835 | one.len(), |
| 1836 | four.len() |
| 1837 | ); |
| 1838 | } |
| 1839 | crate::par::set_tile_threads(1); |
| 1840 | } |
| 1841 | |
| 1842 | |
| 1843 | |
| 1844 | |
| 1845 | |
| 1846 | |
| 1847 | |
| 1848 | |
| 1849 | |
| 1850 | |
| 1851 | #[test] |
| 1852 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 1853 | fn tile_search_wall_1080p() { |
| 1854 | tile_search_wall(1920, 1080, 12, &[(0, 0), (1, 0), (1, 1), (2, 1)], &[1, 2, 4, 8]); |
| 1855 | } |
| 1856 | |
| 1857 | |
| 1858 | |
| 1859 | #[test] |
| 1860 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 1861 | fn tile_search_wall_4k() { |
| 1862 | tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]); |
| 1863 | } |
| 1864 | |
| 1865 | |
| 1866 | |
| 1867 | |
| 1868 | |
| 1869 | |
| 1870 | |
| 1871 | #[test] |
| 1872 | fn filter_stage_bytes_do_not_depend_on_the_thread_count() { |
| 1873 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 1874 | let (width, height) = (384usize, 288usize); |
| 1875 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 1876 | let coded = |threads: usize| { |
| 1877 | crate::par::set_tile_threads(threads); |
| 1878 | let config = EncoderConfig { |
| 1879 | width, |
| 1880 | height, |
| 1881 | base_q_idx: 120, |
| 1882 | gop: 2, |
| 1883 | colour: Colour::Bt709Limited, |
| 1884 | tile_cols_log2: 0, |
| 1885 | tile_rows_log2: 0, |
| 1886 | }; |
| 1887 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1888 | let mut stream = Vec::new(); |
| 1889 | for picture in &sources { |
| 1890 | stream.extend_from_slice(&enc.encode(picture).unwrap().data); |
| 1891 | } |
| 1892 | stream |
| 1893 | }; |
| 1894 | |
| 1895 | let one = coded(1); |
| 1896 | for threads in [2usize, 4, 8] { |
| 1897 | assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads"); |
| 1898 | } |
| 1899 | crate::par::set_tile_threads(1); |
| 1900 | } |
| 1901 | |
| 1902 | |
| 1903 | |
| 1904 | |
| 1905 | |
| 1906 | |
| 1907 | |
| 1908 | #[test] |
| 1909 | fn filter_replay_codes_the_same_stream_as_a_full_decode() { |
| 1910 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 1911 | let run = |width: usize, height: usize, off: bool| { |
| 1912 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 1913 | crate::decode::set_filter_replay_disabled(off); |
| 1914 | let config = EncoderConfig { |
| 1915 | width, |
| 1916 | height, |
| 1917 | base_q_idx: 120, |
| 1918 | gop: 2, |
| 1919 | colour: Colour::Bt709Limited, |
| 1920 | tile_cols_log2: 0, |
| 1921 | tile_rows_log2: 0, |
| 1922 | }; |
| 1923 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1924 | let mut stream = Vec::new(); |
| 1925 | for picture in &sources { |
| 1926 | stream.extend_from_slice(&enc.encode(picture).unwrap().data); |
| 1927 | } |
| 1928 | crate::decode::set_filter_replay_disabled(false); |
| 1929 | stream |
| 1930 | }; |
| 1931 | |
| 1932 | |
| 1933 | |
| 1934 | for (width, height) in [(320usize, 160usize), (320, 192)] { |
| 1935 | let replayed = run(width, height, false); |
| 1936 | let decoded = run(width, height, true); |
| 1937 | assert_eq!( |
| 1938 | replayed, |
| 1939 | decoded, |
| 1940 | "{width}x{height}: the filter replay is not the decode it stands in for \ |
| 1941 | ({} bytes replayed, {} decoded)", |
| 1942 | replayed.len(), |
| 1943 | decoded.len(), |
| 1944 | ); |
| 1945 | } |
| 1946 | } |
| 1947 | |
| 1948 | |
| 1949 | |
| 1950 | |
| 1951 | |
| 1952 | |
| 1953 | #[test] |
| 1954 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 1955 | fn filter_stage_wall_1080p() { |
| 1956 | filter_stage_wall(1920, 1080, 8, (2, 1), &[8]); |
| 1957 | } |
| 1958 | |
| 1959 | #[test] |
| 1960 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 1961 | fn filter_stage_wall_4k() { |
| 1962 | filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]); |
| 1963 | } |
| 1964 | |
| 1965 | fn filter_stage_wall( |
| 1966 | width: usize, |
| 1967 | height: usize, |
| 1968 | frames: usize, |
| 1969 | (cols_log2, rows_log2): (u32, u32), |
| 1970 | threads: &[usize], |
| 1971 | ) { |
| 1972 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 1973 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 1974 | eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg"); |
| 1975 | return; |
| 1976 | }; |
| 1977 | crate::par::set_stage_times(true); |
| 1978 | for &t in threads { |
| 1979 | crate::par::set_tile_threads(t); |
| 1980 | let config = EncoderConfig { |
| 1981 | width, |
| 1982 | height, |
| 1983 | base_q_idx: 120, |
| 1984 | gop: frames, |
| 1985 | colour: Colour::Bt709Limited, |
| 1986 | tile_cols_log2: cols_log2, |
| 1987 | tile_rows_log2: rows_log2, |
| 1988 | }; |
| 1989 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 1990 | let _ = crate::par::take_stage_ns(); |
| 1991 | let start = std::time::Instant::now(); |
| 1992 | for picture in &sources { |
| 1993 | assert!(!enc.encode(picture).unwrap().data.is_empty()); |
| 1994 | } |
| 1995 | let wall = start.elapsed().as_secs_f64(); |
| 1996 | let ns = crate::par::take_stage_ns(); |
| 1997 | let ms = |i: usize| ns[i] as f64 / 1e6; |
| 1998 | eprintln!( |
| 1999 | "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \ |
| 2000 | {wall:.2}s wall, {:.2} fps", |
| 2001 | 1 << cols_log2, |
| 2002 | 1 << rows_log2, |
| 2003 | frames as f64 / wall, |
| 2004 | ); |
| 2005 | eprintln!("| stage | ms | ms/frame | % of wall |"); |
| 2006 | for (i, name) in crate::par::STAGES.iter().enumerate() { |
| 2007 | eprintln!( |
| 2008 | "| {name} | {:.0} | {:.1} | {:.1}% |", |
| 2009 | ms(i), |
| 2010 | ms(i) / frames as f64, |
| 2011 | 100.0 * ms(i) / (wall * 1e3), |
| 2012 | ); |
| 2013 | } |
| 2014 | |
| 2015 | |
| 2016 | |
| 2017 | let top: f64 = [ |
| 2018 | crate::par::S_TILE_SEARCH, |
| 2019 | crate::par::S_TILE_WRITE, |
| 2020 | crate::par::S_FILTER, |
| 2021 | crate::par::S_CAPTURE, |
| 2022 | crate::par::S_LR, |
| 2023 | ] |
| 2024 | .iter() |
| 2025 | .map(|&i| ms(i)) |
| 2026 | .sum(); |
| 2027 | eprintln!( |
| 2028 | "accounted {:.1}% of wall; outside the tile search {:.1}%", |
| 2029 | 100.0 * top / (wall * 1e3), |
| 2030 | 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)), |
| 2031 | ); |
| 2032 | } |
| 2033 | crate::par::set_stage_times(false); |
| 2034 | crate::par::set_tile_threads(1); |
| 2035 | } |
| 2036 | |
| 2037 | fn tile_search_wall( |
| 2038 | width: usize, |
| 2039 | height: usize, |
| 2040 | frames: usize, |
| 2041 | layouts: &[(u32, u32)], |
| 2042 | threads: &[usize], |
| 2043 | ) { |
| 2044 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 2045 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 2046 | eprintln!("SKIP the tile-search wall table: no fixture or no ffmpeg"); |
| 2047 | return; |
| 2048 | }; |
| 2049 | let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) { |
| 2050 | crate::par::set_tile_threads(t); |
| 2051 | let config = EncoderConfig { |
| 2052 | width, |
| 2053 | height, |
| 2054 | base_q_idx: 120, |
| 2055 | gop: frames, |
| 2056 | colour: Colour::Bt709Limited, |
| 2057 | tile_cols_log2: cols_log2, |
| 2058 | tile_rows_log2: rows_log2, |
| 2059 | }; |
| 2060 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2061 | let start = std::time::Instant::now(); |
| 2062 | let mut bytes = 0usize; |
| 2063 | for picture in &sources { |
| 2064 | bytes += enc.encode(picture).unwrap().data.len(); |
| 2065 | } |
| 2066 | (start.elapsed(), bytes) |
| 2067 | }; |
| 2068 | let cells: Vec<((u32, u32), usize)> = layouts |
| 2069 | .iter() |
| 2070 | .flat_map(|&l| threads.iter().map(move |&t| (l, t))) |
| 2071 | .collect(); |
| 2072 | let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()]; |
| 2073 | for _pass in 0..2 { |
| 2074 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 2075 | let got = run(c, r, t); |
| 2076 | assert!(got.1 > 0, "{}x{} tiles at {t} threads: empty stream", 1 << c, 1 << r); |
| 2077 | if best[i].is_none_or(|(w, _)| got.0 < w) { |
| 2078 | best[i] = Some(got); |
| 2079 | } |
| 2080 | } |
| 2081 | } |
| 2082 | crate::par::set_tile_threads(1); |
| 2083 | eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes"); |
| 2084 | eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |"); |
| 2085 | let base = best[0].expect("the first cell ran").0.as_secs_f64(); |
| 2086 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 2087 | let (wall, bytes) = best[i].expect("every cell ran"); |
| 2088 | let secs = wall.as_secs_f64(); |
| 2089 | eprintln!( |
| 2090 | "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |", |
| 2091 | 1 << c, |
| 2092 | 1 << r, |
| 2093 | 1 << (c + r), |
| 2094 | frames as f64 / secs, |
| 2095 | base / secs, |
| 2096 | ); |
| 2097 | } |
| 2098 | |
| 2099 | |
| 2100 | |
| 2101 | for &(c, r) in layouts { |
| 2102 | let one = cells |
| 2103 | .iter() |
| 2104 | .position(|&(l, t)| l == (c, r) && t == threads[0]) |
| 2105 | .map(|i| best[i].expect("cell").0.as_secs_f64()); |
| 2106 | let Some(one) = one else { continue }; |
| 2107 | for &t in &threads[1..] { |
| 2108 | let i = cells.iter().position(|&(l, tt)| l == (c, r) && tt == t).expect("cell"); |
| 2109 | let secs = best[i].expect("cell").0.as_secs_f64(); |
| 2110 | let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64; |
| 2111 | let speedup = one / secs; |
| 2112 | eprintln!( |
| 2113 | "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \ |
| 2114 | idle share {:.0}%", |
| 2115 | 1 << c, |
| 2116 | 1 << r, |
| 2117 | threads[0], |
| 2118 | 100.0 * (1.0 - speedup / workers).max(0.0), |
| 2119 | ); |
| 2120 | } |
| 2121 | } |
| 2122 | rav1e_wall_reference(width, height, frames, layouts, threads); |
| 2123 | } |
| 2124 | |
| 2125 | |
| 2126 | |
| 2127 | fn rav1e_wall_reference( |
| 2128 | width: usize, |
| 2129 | height: usize, |
| 2130 | frames: usize, |
| 2131 | layouts: &[(u32, u32)], |
| 2132 | threads: &[usize], |
| 2133 | ) { |
| 2134 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 2135 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 2136 | let listed = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output(); |
| 2137 | let has_rav1e = listed |
| 2138 | .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e")) |
| 2139 | .unwrap_or(false); |
| 2140 | if !has_rav1e || !clip.exists() { |
| 2141 | eprintln!("SKIP the rav1e reference: no librav1e or no fixture"); |
| 2142 | return; |
| 2143 | } |
| 2144 | eprintln!("| rav1e layout | threads | wall | fps | bytes |"); |
| 2145 | for &(c, r) in layouts { |
| 2146 | for &t in threads { |
| 2147 | let out = std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id())); |
| 2148 | let params = format!( |
| 2149 | "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}", |
| 2150 | 1 << c, |
| 2151 | 1 << r |
| 2152 | ); |
| 2153 | let start = std::time::Instant::now(); |
| 2154 | let status = Command::new("ffmpeg") |
| 2155 | .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()]) |
| 2156 | .args(["-frames:v", &frames.to_string()]) |
| 2157 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 2158 | .args(["-c:v", "librav1e", "-rav1e-params", ¶ms]) |
| 2159 | .arg(out.to_str().unwrap()) |
| 2160 | .output() |
| 2161 | .expect("ffmpeg failed to run"); |
| 2162 | let secs = start.elapsed().as_secs_f64(); |
| 2163 | if !status.status.success() { |
| 2164 | eprintln!("| {}x{} | {t} | FAILED: {} |", 1 << c, 1 << r, String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or("")); |
| 2165 | continue; |
| 2166 | } |
| 2167 | let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); |
| 2168 | let _ = std::fs::remove_file(&out); |
| 2169 | eprintln!( |
| 2170 | "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |", |
| 2171 | 1 << c, |
| 2172 | 1 << r, |
| 2173 | frames as f64 / secs |
| 2174 | ); |
| 2175 | } |
| 2176 | } |
| 2177 | } |
| 2178 | |
| 2179 | |
| 2180 | |
| 2181 | |
| 2182 | |
| 2183 | #[test] |
| 2184 | #[ignore = "1080p encode: minutes, run it with --ignored"] |
| 2185 | fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() { |
| 2186 | let (width, height) = (1920usize, 1080usize); |
| 2187 | let Some(sources) = h264_clip_frames(width, height, 3) else { |
| 2188 | eprintln!("SKIP the 1080p tile round trip: no fixture"); |
| 2189 | return; |
| 2190 | }; |
| 2191 | for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] { |
| 2192 | let config = EncoderConfig { |
| 2193 | width, |
| 2194 | height, |
| 2195 | base_q_idx: 120, |
| 2196 | gop: 3, |
| 2197 | colour: Colour::Bt709Limited, |
| 2198 | tile_cols_log2: cols_log2, |
| 2199 | tile_rows_log2: rows_log2, |
| 2200 | }; |
| 2201 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 2202 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2203 | let mut stream = Vec::new(); |
| 2204 | for (i, picture) in sources.iter().enumerate() { |
| 2205 | let packet = enc |
| 2206 | .encode(picture) |
| 2207 | .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}")); |
| 2208 | stream.extend_from_slice(&packet.data); |
| 2209 | } |
| 2210 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 2211 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 2212 | if !have_ffmpeg() { |
| 2213 | eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg"); |
| 2214 | continue; |
| 2215 | } |
| 2216 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 2217 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 2218 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 2219 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 2220 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 2221 | panic!( |
| 2222 | "1080p {layout} frame {i}: luma differs first at ({}, {})", |
| 2223 | at % width, |
| 2224 | at / width |
| 2225 | ); |
| 2226 | } |
| 2227 | } |
| 2228 | eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len()); |
| 2229 | } |
| 2230 | } |
| 2231 | |
| 2232 | |
| 2233 | |
| 2234 | |
| 2235 | #[test] |
| 2236 | fn quality_target_is_monotone_in_bytes_and_psnr() { |
| 2237 | if !have_ffmpeg() { |
| 2238 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg"); |
| 2239 | return; |
| 2240 | } |
| 2241 | let (width, height) = (640, 384); |
| 2242 | let Some(pictures) = h264_clip_frames(width, height, 8) else { |
| 2243 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture"); |
| 2244 | return; |
| 2245 | }; |
| 2246 | let mut prev_bytes = 0usize; |
| 2247 | let mut prev_psnr = 0.0f64; |
| 2248 | for quality in [20u8, 50, 80] { |
| 2249 | let config = EncoderConfig { |
| 2250 | width, |
| 2251 | height, |
| 2252 | base_q_idx: 100, |
| 2253 | gop: 8, |
| 2254 | colour: Colour::Bt709Limited, |
| 2255 | tile_cols_log2: 0, |
| 2256 | tile_rows_log2: 0, |
| 2257 | }; |
| 2258 | let mut enc = |
| 2259 | Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); |
| 2260 | let mut stream = Vec::new(); |
| 2261 | let mut total_bytes = 0usize; |
| 2262 | for picture in &pictures { |
| 2263 | let packet = enc.encode(picture).unwrap(); |
| 2264 | total_bytes += packet.data.len(); |
| 2265 | stream.extend_from_slice(&packet.data); |
| 2266 | } |
| 2267 | let decoded = ffmpeg_decode_luma(&stream, width, height); |
| 2268 | assert_eq!( |
| 2269 | decoded.len(), |
| 2270 | pictures.len(), |
| 2271 | "quality {quality}: dav1d frame count" |
| 2272 | ); |
| 2273 | let mean_psnr: f64 = decoded |
| 2274 | .iter() |
| 2275 | .zip(&pictures) |
| 2276 | .map(|(d, p)| { |
| 2277 | let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect(); |
| 2278 | psnr(&d16, &p.y) |
| 2279 | }) |
| 2280 | .sum::<f64>() |
| 2281 | / decoded.len() as f64; |
| 2282 | assert!( |
| 2283 | total_bytes >= prev_bytes, |
| 2284 | "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" |
| 2285 | ); |
| 2286 | assert!( |
| 2287 | mean_psnr >= prev_psnr - 0.01, |
| 2288 | "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" |
| 2289 | ); |
| 2290 | prev_bytes = total_bytes; |
| 2291 | prev_psnr = mean_psnr; |
| 2292 | } |
| 2293 | } |
| 2294 | } |