| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig}; |
| 23 | use ec_core::{Error, Result}; |
| 24 | |
| 25 | use crate::encode::{ |
| 26 | Encoded, GOLDEN_SLOT, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, |
| 27 | encode_key_frame_inner, split_blocks, |
| 28 | }; |
| 29 | use crate::intra::KEY_FRAME_MODES; |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | const DEADZONE: f64 = 0.5; |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 44 | pub enum Colour { |
| 45 | |
| 46 | |
| 47 | |
| 48 | #[default] |
| 49 | Bt709Limited, |
| 50 | |
| 51 | |
| 52 | Bt601Limited, |
| 53 | |
| 54 | |
| 55 | Unspecified, |
| 56 | } |
| 57 | |
| 58 | impl Colour { |
| 59 | fn color_config(self) -> ColorConfig { |
| 60 | let (color_primaries, transfer_characteristics, matrix_coefficients) = match self { |
| 61 | Colour::Bt709Limited => (1, 1, 1), |
| 62 | Colour::Bt601Limited => (6, 6, 6), |
| 63 | Colour::Unspecified => (2, 2, 2), |
| 64 | }; |
| 65 | ColorConfig { |
| 66 | bit_depth: 8, |
| 67 | mono_chrome: false, |
| 68 | num_planes: 3, |
| 69 | color_primaries, |
| 70 | transfer_characteristics, |
| 71 | matrix_coefficients, |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | color_range: false, |
| 77 | subsampling_x: 1, |
| 78 | subsampling_y: 1, |
| 79 | chroma_sample_position: ChromaSamplePosition::Unknown, |
| 80 | separate_uv_delta_q: false, |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | |
| 90 | |
| 91 | |
| 92 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 93 | pub enum RateTarget { |
| 94 | |
| 95 | |
| 96 | QIndex(u8), |
| 97 | |
| 98 | |
| 99 | |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | Quality(u8), |
| 105 | |
| 106 | |
| 107 | |
| 108 | BytesPerFrame(u32), |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | |
| 115 | Bitrate { |
| 116 | |
| 117 | bits_per_second: u32, |
| 118 | |
| 119 | frames_per_second: f64, |
| 120 | }, |
| 121 | } |
| 122 | |
| 123 | impl RateTarget { |
| 124 | |
| 125 | |
| 126 | |
| 127 | fn into_loop(self, config: &mut EncoderConfig, pyramid: Option<Pyramid>) -> Option<RateLoop> { |
| 128 | let target_bytes = match self { |
| 129 | RateTarget::QIndex(q) => { |
| 130 | config.base_q_idx = q; |
| 131 | return None; |
| 132 | } |
| 133 | RateTarget::Quality(quality) => { |
| 134 | config.base_q_idx = quality_to_q_idx(quality); |
| 135 | return None; |
| 136 | } |
| 137 | RateTarget::BytesPerFrame(target_bytes) => f64::from(target_bytes), |
| 138 | RateTarget::Bitrate { |
| 139 | bits_per_second, |
| 140 | frames_per_second, |
| 141 | } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0), |
| 142 | }; |
| 143 | Some(RateLoop::new( |
| 144 | target_bytes, |
| 145 | f64::from(config.base_q_idx), |
| 146 | pyramid, |
| 147 | config.gop, |
| 148 | )) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | fn quality_to_q_idx(quality: u8) -> u8 { |
| 158 | let quality = f64::from(quality.min(100)); |
| 159 | (240.0 - quality * 2.0).round() as u8 |
| 160 | } |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | |
| 175 | const WEIGHT_LEVEL_GAIN: f64 = 0.0557; |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | const KEY_WEIGHT: f64 = 1.08; |
| 183 | |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | #[derive(Debug, Clone, Copy)] |
| 199 | struct RateLoop { |
| 200 | |
| 201 | target: [f64; 3], |
| 202 | |
| 203 | q: [f64; 3], |
| 204 | |
| 205 | |
| 206 | |
| 207 | per_level: bool, |
| 208 | |
| 209 | |
| 210 | |
| 211 | seeded: [bool; 3], |
| 212 | |
| 213 | |
| 214 | |
| 215 | leaf_q_offset: i16, |
| 216 | |
| 217 | key_weight: f64, |
| 218 | |
| 219 | |
| 220 | |
| 221 | run_weight: f64, |
| 222 | run_bytes: f64, |
| 223 | |
| 224 | left_weight: f64, |
| 225 | left_bytes: f64, |
| 226 | } |
| 227 | |
| 228 | impl RateLoop { |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | const STEP_CLAMP: f64 = 12.0; |
| 234 | |
| 235 | |
| 236 | const GAIN: f64 = 1.0 / 0.0154; |
| 237 | |
| 238 | fn new(target_bytes: f64, start_q: f64, pyramid: Option<Pyramid>, gop: usize) -> Self { |
| 239 | let Some(p) = pyramid else { |
| 240 | return Self { |
| 241 | target: [target_bytes; 3], |
| 242 | q: [start_q; 3], |
| 243 | per_level: false, |
| 244 | seeded: [false; 3], |
| 245 | leaf_q_offset: 0, |
| 246 | key_weight: 1.0, |
| 247 | run_weight: 0.0, |
| 248 | run_bytes: 0.0, |
| 249 | left_weight: 0.0, |
| 250 | left_bytes: 0.0, |
| 251 | }; |
| 252 | }; |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | let w = |offset: i16| { |
| 264 | ((f64::from(p.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp() |
| 265 | }; |
| 266 | let (hidden, leaves) = gop_shape(p, gop); |
| 267 | let key = KEY_WEIGHT * w(p.key_q_offset); |
| 268 | let total: f64 = key |
| 269 | + leaves as f64 |
| 270 | + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>(); |
| 271 | |
| 272 | |
| 273 | let scale = target_bytes * gop.max(1) as f64 / total.max(f64::EPSILON); |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | Self { |
| 282 | target: [scale * key, scale, scale], |
| 283 | q: [start_q; 3], |
| 284 | per_level: true, |
| 285 | seeded: [false; 3], |
| 286 | leaf_q_offset: p.leaf_q_offset, |
| 287 | key_weight: key, |
| 288 | run_weight: total, |
| 289 | run_bytes: target_bytes * gop.max(1) as f64, |
| 290 | left_weight: total, |
| 291 | left_bytes: target_bytes * gop.max(1) as f64, |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | |
| 296 | |
| 297 | fn weight(&self, offset: i16) -> f64 { |
| 298 | ((f64::from(self.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp() |
| 299 | } |
| 300 | |
| 301 | |
| 302 | |
| 303 | fn slot(&self, level: Level) -> usize { |
| 304 | if !self.per_level { |
| 305 | return 0; |
| 306 | } |
| 307 | match level { |
| 308 | Level::Key => 0, |
| 309 | Level::Arf => 1, |
| 310 | |
| 311 | |
| 312 | Level::Leaf | Level::ShowExisting => 2, |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | fn q_idx(&self, level: Level) -> u8 { |
| 317 | self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8 |
| 318 | } |
| 319 | |
| 320 | |
| 321 | |
| 322 | fn update(&mut self, level: Level, offset: i16, actual_bytes: usize) { |
| 323 | let slot = self.slot(level); |
| 324 | if self.target[slot] <= 0.0 || actual_bytes == 0 { |
| 325 | return; |
| 326 | } |
| 327 | |
| 328 | |
| 329 | let frame_weight = match slot { |
| 330 | 0 => self.key_weight, |
| 331 | 1 => self.weight(offset), |
| 332 | _ => 1.0, |
| 333 | }; |
| 334 | let target = match self.per_level && slot == 1 { |
| 335 | true => self.target[slot] * frame_weight, |
| 336 | false => self.target[slot], |
| 337 | }; |
| 338 | let ratio = actual_bytes as f64 / target; |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | |
| 345 | |
| 346 | |
| 347 | |
| 348 | |
| 349 | |
| 350 | let raw = ratio.ln() * Self::GAIN; |
| 351 | let step = if std::mem::replace(&mut self.seeded[slot], true) { |
| 352 | raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP) |
| 353 | } else { |
| 354 | raw |
| 355 | }; |
| 356 | self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0); |
| 357 | self.replan(level, frame_weight, actual_bytes as f64); |
| 358 | } |
| 359 | |
| 360 | |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | fn replan(&mut self, level: Level, frame_weight: f64, actual_bytes: f64) { |
| 378 | if !self.per_level { |
| 379 | return; |
| 380 | } |
| 381 | if level == Level::Key { |
| 382 | self.left_weight = self.run_weight; |
| 383 | self.left_bytes = self.run_bytes; |
| 384 | } |
| 385 | self.left_weight -= frame_weight; |
| 386 | self.left_bytes -= actual_bytes; |
| 387 | |
| 388 | |
| 389 | if self.left_weight <= 1.0 { |
| 390 | return; |
| 391 | } |
| 392 | let scale = (self.left_bytes / self.left_weight).max(0.0); |
| 393 | self.target = [scale * self.key_weight, scale, scale]; |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | |
| 398 | |
| 399 | |
| 400 | |
| 401 | |
| 402 | |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | #[derive(Debug, Clone, Copy)] |
| 408 | pub struct EncoderConfig { |
| 409 | |
| 410 | pub width: usize, |
| 411 | |
| 412 | pub height: usize, |
| 413 | |
| 414 | pub base_q_idx: u8, |
| 415 | |
| 416 | |
| 417 | |
| 418 | pub gop: usize, |
| 419 | |
| 420 | pub colour: Colour, |
| 421 | |
| 422 | |
| 423 | |
| 424 | |
| 425 | pub tile_cols_log2: u32, |
| 426 | |
| 427 | pub tile_rows_log2: u32, |
| 428 | } |
| 429 | |
| 430 | impl EncoderConfig { |
| 431 | |
| 432 | |
| 433 | |
| 434 | |
| 435 | #[must_use] |
| 436 | pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self { |
| 437 | Self { |
| 438 | width, |
| 439 | height, |
| 440 | base_q_idx, |
| 441 | gop, |
| 442 | colour, |
| 443 | tile_cols_log2: 0, |
| 444 | tile_rows_log2: 0, |
| 445 | } |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | |
| 450 | |
| 451 | |
| 452 | #[derive(Debug, Clone)] |
| 453 | pub struct Packet { |
| 454 | |
| 455 | |
| 456 | |
| 457 | |
| 458 | |
| 459 | |
| 460 | pub data: Vec<u8>, |
| 461 | |
| 462 | pub key: bool, |
| 463 | |
| 464 | |
| 465 | |
| 466 | pub order: u64, |
| 467 | |
| 468 | |
| 469 | |
| 470 | |
| 471 | |
| 472 | |
| 473 | pub dts: u64, |
| 474 | |
| 475 | pub level: Level, |
| 476 | } |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | |
| 482 | |
| 483 | |
| 484 | |
| 485 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 486 | pub struct Pyramid { |
| 487 | |
| 488 | |
| 489 | |
| 490 | |
| 491 | |
| 492 | |
| 493 | pub mini_gop: usize, |
| 494 | |
| 495 | |
| 496 | pub arf_q_offset: i16, |
| 497 | |
| 498 | |
| 499 | pub leaf_q_offset: i16, |
| 500 | |
| 501 | |
| 502 | |
| 503 | |
| 504 | |
| 505 | |
| 506 | |
| 507 | |
| 508 | pub mid_q_offset: Option<i16>, |
| 509 | |
| 510 | |
| 511 | |
| 512 | |
| 513 | |
| 514 | |
| 515 | |
| 516 | |
| 517 | |
| 518 | pub quarter_q_offset: Option<i16>, |
| 519 | |
| 520 | |
| 521 | |
| 522 | |
| 523 | |
| 524 | |
| 525 | pub key_q_offset: i16, |
| 526 | } |
| 527 | |
| 528 | |
| 529 | |
| 530 | |
| 531 | |
| 532 | |
| 533 | |
| 534 | |
| 535 | |
| 536 | |
| 537 | |
| 538 | |
| 539 | |
| 540 | |
| 541 | |
| 542 | |
| 543 | |
| 544 | |
| 545 | fn group_target(remaining: usize, mini_gop: usize, absorb_tail: bool) -> usize { |
| 546 | match absorb_tail && remaining <= mini_gop + mini_gop / 2 { |
| 547 | true => remaining.max(1), |
| 548 | false => mini_gop, |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | |
| 553 | |
| 554 | |
| 555 | |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | |
| 561 | |
| 562 | |
| 563 | fn gop_shape(p: Pyramid, gop: usize) -> (Vec<(i16, usize)>, usize) { |
| 564 | let (mut hidden, mut leaves) = (Vec::<(i16, usize)>::new(), 0usize); |
| 565 | let mut add = |offset: i16, n: usize| match hidden.iter_mut().find(|(o, _)| *o == offset) { |
| 566 | Some((_, c)) => *c += n, |
| 567 | None => hidden.push((offset, n)), |
| 568 | }; |
| 569 | let long_run = gop > p.mini_gop + p.mini_gop / 2; |
| 570 | let mut left = gop.saturating_sub(1); |
| 571 | while left > 0 { |
| 572 | let g = group_target(left, p.mini_gop, absorb_tail()).min(left); |
| 573 | left -= g; |
| 574 | if g == 1 { |
| 575 | leaves += 1; |
| 576 | continue; |
| 577 | } |
| 578 | let inner = g - 1; |
| 579 | add(p.arf_q_offset, 1); |
| 580 | let mid = p.mid_q_offset.filter(|_| inner >= 3 && long_run); |
| 581 | let quarters = mid.and(p.quarter_q_offset).filter(|_| inner >= 7); |
| 582 | if let Some(o) = mid { |
| 583 | add(o, 1); |
| 584 | } |
| 585 | if let Some(o) = quarters { |
| 586 | add(o, 2); |
| 587 | } |
| 588 | leaves += inner - usize::from(mid.is_some()) - 2 * usize::from(quarters.is_some()); |
| 589 | } |
| 590 | (hidden, leaves) |
| 591 | } |
| 592 | |
| 593 | |
| 594 | |
| 595 | fn absorb_tail() -> bool { |
| 596 | static ABSORB: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| { |
| 597 | std::env::var("EC_AV1_GOP_LAYOUT").ok().as_deref() != Some("fixed") |
| 598 | }); |
| 599 | *ABSORB |
| 600 | } |
| 601 | |
| 602 | impl Pyramid { |
| 603 | |
| 604 | |
| 605 | |
| 606 | |
| 607 | |
| 608 | |
| 609 | |
| 610 | |
| 611 | #[must_use] |
| 612 | pub fn from_env() -> Option<Self> { |
| 613 | let d = Self::default(); |
| 614 | let Some(spec) = std::env::var("EC_AV1_PYRAMID").ok() else { |
| 615 | return Some(d); |
| 616 | }; |
| 617 | let mut f = spec.split(':'); |
| 618 | let mini_gop: usize = f.next().and_then(|v| v.parse().ok()).unwrap_or(0); |
| 619 | if mini_gop < 2 { |
| 620 | return None; |
| 621 | } |
| 622 | Some(Self { |
| 623 | mini_gop, |
| 624 | arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset), |
| 625 | leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset), |
| 626 | |
| 627 | |
| 628 | |
| 629 | mid_q_offset: match f.next() { |
| 630 | None => d.mid_q_offset, |
| 631 | Some("off") => None, |
| 632 | Some(v) => v.parse().ok().or(d.mid_q_offset), |
| 633 | }, |
| 634 | |
| 635 | key_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.key_q_offset), |
| 636 | |
| 637 | quarter_q_offset: match f.next() { |
| 638 | None => d.quarter_q_offset, |
| 639 | Some("off") => None, |
| 640 | Some(v) => v.parse().ok().or(d.quarter_q_offset), |
| 641 | }, |
| 642 | }) |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | impl Default for Pyramid { |
| 647 | |
| 648 | |
| 649 | |
| 650 | |
| 651 | |
| 652 | |
| 653 | |
| 654 | |
| 655 | |
| 656 | |
| 657 | |
| 658 | |
| 659 | |
| 660 | |
| 661 | |
| 662 | |
| 663 | |
| 664 | |
| 665 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | |
| 675 | |
| 676 | |
| 677 | |
| 678 | |
| 679 | |
| 680 | |
| 681 | |
| 682 | |
| 683 | |
| 684 | |
| 685 | |
| 686 | |
| 687 | |
| 688 | |
| 689 | |
| 690 | |
| 691 | |
| 692 | |
| 693 | |
| 694 | |
| 695 | |
| 696 | |
| 697 | |
| 698 | |
| 699 | |
| 700 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | |
| 705 | |
| 706 | |
| 707 | |
| 708 | |
| 709 | |
| 710 | |
| 711 | |
| 712 | |
| 713 | |
| 714 | |
| 715 | |
| 716 | |
| 717 | |
| 718 | |
| 719 | |
| 720 | |
| 721 | |
| 722 | |
| 723 | |
| 724 | |
| 725 | |
| 726 | |
| 727 | |
| 728 | |
| 729 | |
| 730 | |
| 731 | |
| 732 | |
| 733 | |
| 734 | |
| 735 | |
| 736 | |
| 737 | |
| 738 | |
| 739 | |
| 740 | |
| 741 | |
| 742 | |
| 743 | |
| 744 | |
| 745 | |
| 746 | |
| 747 | |
| 748 | |
| 749 | |
| 750 | |
| 751 | |
| 752 | |
| 753 | |
| 754 | |
| 755 | |
| 756 | |
| 757 | |
| 758 | |
| 759 | |
| 760 | |
| 761 | |
| 762 | |
| 763 | |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | |
| 774 | |
| 775 | |
| 776 | |
| 777 | |
| 778 | |
| 779 | |
| 780 | |
| 781 | |
| 782 | |
| 783 | |
| 784 | |
| 785 | |
| 786 | |
| 787 | |
| 788 | |
| 789 | |
| 790 | |
| 791 | |
| 792 | |
| 793 | |
| 794 | |
| 795 | |
| 796 | |
| 797 | |
| 798 | |
| 799 | |
| 800 | |
| 801 | |
| 802 | |
| 803 | |
| 804 | |
| 805 | |
| 806 | |
| 807 | |
| 808 | |
| 809 | |
| 810 | |
| 811 | |
| 812 | |
| 813 | |
| 814 | |
| 815 | |
| 816 | |
| 817 | |
| 818 | |
| 819 | |
| 820 | |
| 821 | |
| 822 | |
| 823 | |
| 824 | |
| 825 | |
| 826 | |
| 827 | |
| 828 | |
| 829 | |
| 830 | |
| 831 | |
| 832 | |
| 833 | |
| 834 | |
| 835 | |
| 836 | |
| 837 | |
| 838 | |
| 839 | |
| 840 | |
| 841 | |
| 842 | |
| 843 | |
| 844 | |
| 845 | |
| 846 | |
| 847 | |
| 848 | |
| 849 | |
| 850 | |
| 851 | |
| 852 | |
| 853 | |
| 854 | |
| 855 | |
| 856 | |
| 857 | |
| 858 | |
| 859 | |
| 860 | |
| 861 | |
| 862 | |
| 863 | |
| 864 | |
| 865 | |
| 866 | |
| 867 | |
| 868 | |
| 869 | |
| 870 | |
| 871 | |
| 872 | |
| 873 | |
| 874 | |
| 875 | |
| 876 | |
| 877 | |
| 878 | |
| 879 | |
| 880 | |
| 881 | |
| 882 | |
| 883 | |
| 884 | |
| 885 | |
| 886 | |
| 887 | |
| 888 | |
| 889 | |
| 890 | |
| 891 | |
| 892 | |
| 893 | |
| 894 | |
| 895 | |
| 896 | |
| 897 | |
| 898 | |
| 899 | |
| 900 | |
| 901 | |
| 902 | |
| 903 | |
| 904 | |
| 905 | |
| 906 | |
| 907 | |
| 908 | |
| 909 | |
| 910 | |
| 911 | |
| 912 | |
| 913 | |
| 914 | |
| 915 | |
| 916 | |
| 917 | |
| 918 | |
| 919 | |
| 920 | |
| 921 | |
| 922 | |
| 923 | |
| 924 | |
| 925 | fn default() -> Self { |
| 926 | Self { |
| 927 | mini_gop: 8, |
| 928 | arf_q_offset: -32, |
| 929 | leaf_q_offset: 12, |
| 930 | mid_q_offset: MID_DEFAULT, |
| 931 | key_q_offset: KEY_DEFAULT, |
| 932 | quarter_q_offset: QUARTER_DEFAULT, |
| 933 | } |
| 934 | } |
| 935 | } |
| 936 | |
| 937 | |
| 938 | |
| 939 | |
| 940 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 941 | pub enum Level { |
| 942 | |
| 943 | Key, |
| 944 | |
| 945 | Arf, |
| 946 | |
| 947 | Leaf, |
| 948 | |
| 949 | |
| 950 | ShowExisting, |
| 951 | } |
| 952 | |
| 953 | |
| 954 | |
| 955 | |
| 956 | |
| 957 | |
| 958 | |
| 959 | const ANCHOR_SLOTS: [u8; 2] = [3, 4]; |
| 960 | |
| 961 | |
| 962 | const LEAF_SLOT: u8 = 0; |
| 963 | |
| 964 | |
| 965 | |
| 966 | |
| 967 | const MID_SLOT: u8 = 2; |
| 968 | |
| 969 | |
| 970 | |
| 971 | |
| 972 | |
| 973 | |
| 974 | |
| 975 | |
| 976 | |
| 977 | |
| 978 | |
| 979 | |
| 980 | |
| 981 | |
| 982 | |
| 983 | |
| 984 | |
| 985 | |
| 986 | |
| 987 | const QUARTER_SLOTS: [u8; 2] = [5, 6]; |
| 988 | |
| 989 | |
| 990 | |
| 991 | const QUARTER_DEFAULT: Option<i16> = None; |
| 992 | |
| 993 | |
| 994 | |
| 995 | |
| 996 | |
| 997 | const MID_DEFAULT: Option<i16> = Some(-8); |
| 998 | |
| 999 | |
| 1000 | |
| 1001 | |
| 1002 | |
| 1003 | |
| 1004 | |
| 1005 | |
| 1006 | |
| 1007 | |
| 1008 | |
| 1009 | |
| 1010 | |
| 1011 | |
| 1012 | |
| 1013 | |
| 1014 | |
| 1015 | |
| 1016 | |
| 1017 | const KEY_DEFAULT: i16 = -48; |
| 1018 | |
| 1019 | |
| 1020 | |
| 1021 | |
| 1022 | |
| 1023 | |
| 1024 | |
| 1025 | |
| 1026 | fn tpl_pyramid() -> bool { |
| 1027 | match std::env::var("EC_AV1_TPL_PYRAMID").ok() { |
| 1028 | Some(v) => v != "0", |
| 1029 | None => TPL_PYRAMID, |
| 1030 | } |
| 1031 | } |
| 1032 | |
| 1033 | |
| 1034 | const TPL_PYRAMID: bool = true; |
| 1035 | |
| 1036 | |
| 1037 | |
| 1038 | |
| 1039 | |
| 1040 | |
| 1041 | |
| 1042 | |
| 1043 | |
| 1044 | fn arf_altref() -> bool { |
| 1045 | match std::env::var("EC_AV1_ARF_ALTREF").ok() { |
| 1046 | Some(v) => v != "0", |
| 1047 | None => ARF_ALTREF, |
| 1048 | } |
| 1049 | } |
| 1050 | |
| 1051 | |
| 1052 | |
| 1053 | |
| 1054 | |
| 1055 | const ARF_ALTREF: bool = true; |
| 1056 | |
| 1057 | |
| 1058 | |
| 1059 | |
| 1060 | |
| 1061 | #[derive(Debug)] |
| 1062 | pub struct Av1Encoder { |
| 1063 | config: EncoderConfig, |
| 1064 | color_config: ColorConfig, |
| 1065 | |
| 1066 | |
| 1067 | |
| 1068 | |
| 1069 | reference: Option<Picture>, |
| 1070 | next_index: u64, |
| 1071 | |
| 1072 | |
| 1073 | |
| 1074 | |
| 1075 | rate_loop: Option<RateLoop>, |
| 1076 | |
| 1077 | |
| 1078 | |
| 1079 | |
| 1080 | fctx: crate::decode::FrameCtx, |
| 1081 | |
| 1082 | |
| 1083 | |
| 1084 | |
| 1085 | carried_cdfs: Option<crate::encode::CdfSnapshot>, |
| 1086 | |
| 1087 | |
| 1088 | golden: Option<Picture>, |
| 1089 | |
| 1090 | |
| 1091 | prev2: Option<Picture>, |
| 1092 | |
| 1093 | |
| 1094 | |
| 1095 | pyramid: Option<Pyramid>, |
| 1096 | |
| 1097 | |
| 1098 | |
| 1099 | |
| 1100 | dpb: [Option<DpbSlot>; 8], |
| 1101 | |
| 1102 | pending: Vec<(u64, Picture)>, |
| 1103 | |
| 1104 | |
| 1105 | |
| 1106 | |
| 1107 | held: std::collections::VecDeque<Picture>, |
| 1108 | |
| 1109 | |
| 1110 | anchor: usize, |
| 1111 | |
| 1112 | next_dts: u64, |
| 1113 | |
| 1114 | |
| 1115 | |
| 1116 | |
| 1117 | collected: Option<Vec<(u64, Encoded)>>, |
| 1118 | } |
| 1119 | |
| 1120 | |
| 1121 | |
| 1122 | #[derive(Debug, Clone)] |
| 1123 | struct DpbSlot { |
| 1124 | picture: Picture, |
| 1125 | order_hint: u32, |
| 1126 | cdfs: crate::encode::CdfSnapshot, |
| 1127 | } |
| 1128 | |
| 1129 | |
| 1130 | |
| 1131 | |
| 1132 | const _: fn() = || { |
| 1133 | fn assert_send<T: Send>() {} |
| 1134 | assert_send::<Av1Encoder>(); |
| 1135 | }; |
| 1136 | |
| 1137 | impl Av1Encoder { |
| 1138 | |
| 1139 | |
| 1140 | |
| 1141 | |
| 1142 | |
| 1143 | |
| 1144 | |
| 1145 | |
| 1146 | |
| 1147 | |
| 1148 | |
| 1149 | |
| 1150 | |
| 1151 | pub fn with_speed(config: EncoderConfig, speed: u8) -> Result<Self> { |
| 1152 | crate::speed::set_speed(speed); |
| 1153 | Self::new(config) |
| 1154 | } |
| 1155 | |
| 1156 | |
| 1157 | |
| 1158 | |
| 1159 | |
| 1160 | |
| 1161 | pub fn new(config: EncoderConfig) -> Result<Self> { |
| 1162 | if config.gop == 0 { |
| 1163 | return Err(Error::unsupported("AV1 encode", "gop must be at least 1")); |
| 1164 | } |
| 1165 | |
| 1166 | |
| 1167 | |
| 1168 | Picture::grey(config.width, config.height).check_even()?; |
| 1169 | |
| 1170 | |
| 1171 | |
| 1172 | |
| 1173 | let sb_cols = config.width.div_ceil(64) as u32; |
| 1174 | let sb_rows = config.height.div_ceil(64) as u32; |
| 1175 | if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows { |
| 1176 | return Err(Error::unsupported( |
| 1177 | "AV1 encode", |
| 1178 | format!( |
| 1179 | "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has", |
| 1180 | 1 << config.tile_cols_log2, |
| 1181 | 1 << config.tile_rows_log2 |
| 1182 | ), |
| 1183 | )); |
| 1184 | } |
| 1185 | Ok(Self { |
| 1186 | carried_cdfs: None, |
| 1187 | golden: None, |
| 1188 | prev2: None, |
| 1189 | color_config: config.colour.color_config(), |
| 1190 | config, |
| 1191 | reference: None, |
| 1192 | next_index: 0, |
| 1193 | rate_loop: None, |
| 1194 | fctx: crate::decode::FrameCtx::new(), |
| 1195 | pyramid: None, |
| 1196 | dpb: [const { None }; 8], |
| 1197 | pending: Vec::new(), |
| 1198 | held: std::collections::VecDeque::new(), |
| 1199 | anchor: 0, |
| 1200 | next_dts: 0, |
| 1201 | collected: None, |
| 1202 | }) |
| 1203 | } |
| 1204 | |
| 1205 | |
| 1206 | |
| 1207 | |
| 1208 | |
| 1209 | |
| 1210 | |
| 1211 | |
| 1212 | |
| 1213 | |
| 1214 | |
| 1215 | |
| 1216 | pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> { |
| 1217 | if pyramid.mini_gop < 2 { |
| 1218 | return Err(Error::unsupported( |
| 1219 | "AV1 encode", |
| 1220 | "a pyramid mini-GOP is at least 2 pictures", |
| 1221 | )); |
| 1222 | } |
| 1223 | let mut encoder = Self::new(config)?; |
| 1224 | encoder.pyramid = Some(pyramid); |
| 1225 | Ok(encoder) |
| 1226 | } |
| 1227 | |
| 1228 | |
| 1229 | |
| 1230 | |
| 1231 | |
| 1232 | |
| 1233 | |
| 1234 | pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> { |
| 1235 | let rate_loop = rate.into_loop(&mut config, None); |
| 1236 | let mut encoder = Self::new(config)?; |
| 1237 | encoder.rate_loop = rate_loop; |
| 1238 | Ok(encoder) |
| 1239 | } |
| 1240 | |
| 1241 | |
| 1242 | |
| 1243 | |
| 1244 | |
| 1245 | |
| 1246 | |
| 1247 | |
| 1248 | |
| 1249 | pub fn with_pyramid_and_rate_target( |
| 1250 | mut config: EncoderConfig, |
| 1251 | pyramid: Pyramid, |
| 1252 | rate: RateTarget, |
| 1253 | ) -> Result<Self> { |
| 1254 | let rate_loop = rate.into_loop(&mut config, Some(pyramid)); |
| 1255 | let mut encoder = Self::with_pyramid(config, pyramid)?; |
| 1256 | encoder.rate_loop = rate_loop; |
| 1257 | Ok(encoder) |
| 1258 | } |
| 1259 | |
| 1260 | |
| 1261 | |
| 1262 | |
| 1263 | |
| 1264 | |
| 1265 | #[must_use] |
| 1266 | pub fn pyramid(&self) -> Option<Pyramid> { |
| 1267 | self.pyramid |
| 1268 | } |
| 1269 | |
| 1270 | |
| 1271 | |
| 1272 | #[must_use] |
| 1273 | pub fn coded_size(&self) -> (usize, usize) { |
| 1274 | ( |
| 1275 | self.config.width.next_multiple_of(SUPERBLOCK), |
| 1276 | self.config.height.next_multiple_of(SUPERBLOCK), |
| 1277 | ) |
| 1278 | } |
| 1279 | |
| 1280 | |
| 1281 | |
| 1282 | #[must_use] |
| 1283 | pub fn display_size(&self) -> (usize, usize) { |
| 1284 | (self.config.width, self.config.height) |
| 1285 | } |
| 1286 | |
| 1287 | |
| 1288 | |
| 1289 | |
| 1290 | |
| 1291 | |
| 1292 | |
| 1293 | |
| 1294 | |
| 1295 | |
| 1296 | |
| 1297 | |
| 1298 | |
| 1299 | |
| 1300 | |
| 1301 | |
| 1302 | |
| 1303 | |
| 1304 | pub fn encode(&mut self, picture: &Picture) -> Result<Packet> { |
| 1305 | if self.pyramid.is_some() { |
| 1306 | return Err(Error::unsupported( |
| 1307 | "AV1 encode", |
| 1308 | "a pyramid stream reorders pictures -- use encode_frames()/flush()", |
| 1309 | )); |
| 1310 | } |
| 1311 | let mut packets = self.encode_frames(picture)?; |
| 1312 | Ok(packets.pop().unwrap_or(Packet { |
| 1313 | data: Vec::new(), |
| 1314 | key: false, |
| 1315 | order: 0, |
| 1316 | dts: 0, |
| 1317 | level: Level::Leaf, |
| 1318 | })) |
| 1319 | } |
| 1320 | |
| 1321 | |
| 1322 | |
| 1323 | |
| 1324 | |
| 1325 | |
| 1326 | |
| 1327 | |
| 1328 | |
| 1329 | |
| 1330 | |
| 1331 | pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> { |
| 1332 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 1333 | if (picture.width, picture.height) != (self.config.width, self.config.height) { |
| 1334 | return Err(Error::unsupported( |
| 1335 | "AV1 encode", |
| 1336 | format!( |
| 1337 | "picture is {}x{}, encoder is {}x{}", |
| 1338 | picture.width, picture.height, self.config.width, self.config.height |
| 1339 | ), |
| 1340 | )); |
| 1341 | } |
| 1342 | |
| 1343 | |
| 1344 | |
| 1345 | |
| 1346 | |
| 1347 | |
| 1348 | |
| 1349 | |
| 1350 | |
| 1351 | |
| 1352 | |
| 1353 | |
| 1354 | |
| 1355 | |
| 1356 | if self.pyramid.is_some() |
| 1357 | && self.next_index == 0 |
| 1358 | && crate::encode::picture_is_screen(picture) |
| 1359 | { |
| 1360 | self.pyramid = None; |
| 1361 | } |
| 1362 | let Some(pyramid) = self.pyramid else { |
| 1363 | |
| 1364 | |
| 1365 | |
| 1366 | |
| 1367 | self.held.push_back(picture.clone()); |
| 1368 | if self.held.len() <= crate::encode::tpl_depth() - 1 { |
| 1369 | return Ok(Vec::new()); |
| 1370 | } |
| 1371 | let previous = self.held.pop_front().expect("queue is over depth"); |
| 1372 | let window: Vec<Picture> = self.held.iter().cloned().collect(); |
| 1373 | return Ok(vec![self.encode_flat(&previous, &window)?]); |
| 1374 | }; |
| 1375 | let order = self.next_index; |
| 1376 | self.next_index += 1; |
| 1377 | if order.is_multiple_of(self.config.gop as u64) { |
| 1378 | |
| 1379 | |
| 1380 | |
| 1381 | let mut packets = self.drain_pending()?; |
| 1382 | packets.push(self.encode_key(order, picture)?); |
| 1383 | return Ok(packets); |
| 1384 | } |
| 1385 | self.pending.push((order, picture.clone())); |
| 1386 | |
| 1387 | |
| 1388 | |
| 1389 | |
| 1390 | let run_start = self.pending[0].0; |
| 1391 | let remaining = self.config.gop - (run_start % self.config.gop as u64) as usize; |
| 1392 | let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64); |
| 1393 | if self.pending.len() >= group_target(remaining, pyramid.mini_gop, absorb_tail()) |
| 1394 | || next_is_key |
| 1395 | { |
| 1396 | return self.drain_pending(); |
| 1397 | } |
| 1398 | Ok(Vec::new()) |
| 1399 | } |
| 1400 | |
| 1401 | |
| 1402 | |
| 1403 | |
| 1404 | |
| 1405 | |
| 1406 | |
| 1407 | |
| 1408 | pub fn flush(&mut self) -> Result<Vec<Packet>> { |
| 1409 | crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2); |
| 1410 | if !self.held.is_empty() { |
| 1411 | let mut packets = Vec::with_capacity(self.held.len()); |
| 1412 | while let Some(previous) = self.held.pop_front() { |
| 1413 | let window: Vec<Picture> = self.held.iter().cloned().collect(); |
| 1414 | packets.push(self.encode_flat(&previous, &window)?); |
| 1415 | } |
| 1416 | return Ok(packets); |
| 1417 | } |
| 1418 | self.drain_pending() |
| 1419 | } |
| 1420 | |
| 1421 | |
| 1422 | |
| 1423 | |
| 1424 | |
| 1425 | fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result<Packet> { |
| 1426 | let render = (self.config.width, self.config.height); |
| 1427 | let padded = picture.padded_to(SUPERBLOCK); |
| 1428 | let is_key = self.next_index.is_multiple_of(self.config.gop as u64); |
| 1429 | let order = self.next_index; |
| 1430 | let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| { |
| 1431 | r.q_idx(if is_key { Level::Key } else { Level::Leaf }) |
| 1432 | }); |
| 1433 | |
| 1434 | let encoded: Encoded = if is_key { |
| 1435 | encode_key_frame_inner( |
| 1436 | &padded, |
| 1437 | base_q_idx, |
| 1438 | DEADZONE, |
| 1439 | &KEY_FRAME_MODES, |
| 1440 | split_blocks(), |
| 1441 | render, |
| 1442 | self.color_config, |
| 1443 | &self.fctx, |
| 1444 | )? |
| 1445 | } else { |
| 1446 | let reference = self.reference.as_ref().ok_or_else(|| { |
| 1447 | Error::unsupported( |
| 1448 | "AV1 encode", |
| 1449 | "an inter frame needs a previous reconstruction", |
| 1450 | ) |
| 1451 | })?; |
| 1452 | encode_inter_frame( |
| 1453 | &padded, |
| 1454 | reference, |
| 1455 | base_q_idx, |
| 1456 | DEADZONE, |
| 1457 | order as u32, |
| 1458 | |
| 1459 | |
| 1460 | |
| 1461 | |
| 1462 | crate::encode::flat_order_hints( |
| 1463 | order as u32 & 0x7f, |
| 1464 | (order - order % self.config.gop as u64) as u32 & 0x7f, |
| 1465 | self.prev2.is_some(), |
| 1466 | ), |
| 1467 | render, |
| 1468 | self.carried_cdfs.as_ref().map(|c| &c.0), |
| 1469 | self.golden.as_ref(), |
| 1470 | self.prev2.as_ref(), |
| 1471 | &self.fctx, |
| 1472 | None, |
| 1473 | &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::<Vec<_>>(), |
| 1474 | )? |
| 1475 | }; |
| 1476 | |
| 1477 | self.carried_cdfs = Some(encoded.next_cdfs.clone()); |
| 1478 | if is_key { |
| 1479 | self.golden = Some(encoded.reconstruction.clone()); |
| 1480 | self.prev2 = None; |
| 1481 | } else { |
| 1482 | self.prev2 = self.reference.take(); |
| 1483 | } |
| 1484 | self.reference = Some(encoded.reconstruction.clone()); |
| 1485 | self.next_index += 1; |
| 1486 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1487 | let level = if is_key { Level::Key } else { Level::Leaf }; |
| 1488 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1489 | |
| 1490 | rate_loop.update(level, 0, cropped.stream.len()); |
| 1491 | } |
| 1492 | Ok(self.packet(cropped.stream, is_key, order, level)) |
| 1493 | } |
| 1494 | |
| 1495 | |
| 1496 | |
| 1497 | |
| 1498 | |
| 1499 | |
| 1500 | |
| 1501 | |
| 1502 | |
| 1503 | |
| 1504 | |
| 1505 | |
| 1506 | |
| 1507 | |
| 1508 | |
| 1509 | |
| 1510 | |
| 1511 | |
| 1512 | |
| 1513 | |
| 1514 | |
| 1515 | pub(crate) fn encode_sequence_pyramid( |
| 1516 | pictures: &[Picture], |
| 1517 | base_q_idx: u8, |
| 1518 | pyramid: Pyramid, |
| 1519 | tiles: (u32, u32), |
| 1520 | ) -> Result<crate::encode::EncodedSequence> { |
| 1521 | let first = pictures.first().ok_or_else(|| { |
| 1522 | Error::unsupported("AV1 encode", "a sequence needs at least one picture") |
| 1523 | })?; |
| 1524 | let config = EncoderConfig { |
| 1525 | width: first.width, |
| 1526 | height: first.height, |
| 1527 | base_q_idx, |
| 1528 | |
| 1529 | gop: pictures.len().max(1), |
| 1530 | |
| 1531 | colour: Colour::Unspecified, |
| 1532 | tile_cols_log2: tiles.0, |
| 1533 | tile_rows_log2: tiles.1, |
| 1534 | }; |
| 1535 | let mut encoder = Self::with_pyramid(config, pyramid)?; |
| 1536 | encoder.collected = Some(Vec::with_capacity(pictures.len())); |
| 1537 | let mut stream = Vec::new(); |
| 1538 | for picture in pictures { |
| 1539 | for packet in encoder.encode_frames(picture)? { |
| 1540 | stream.extend_from_slice(&packet.data); |
| 1541 | } |
| 1542 | } |
| 1543 | for packet in encoder.flush()? { |
| 1544 | stream.extend_from_slice(&packet.data); |
| 1545 | } |
| 1546 | let mut collected = encoder.collected.take().expect("collecting"); |
| 1547 | |
| 1548 | |
| 1549 | let coding_order: Vec<usize> = |
| 1550 | collected.iter().map(|(order, _)| *order as usize).collect(); |
| 1551 | collected.sort_by_key(|(order, _)| *order); |
| 1552 | let frames: Vec<Encoded> = collected.into_iter().map(|(_, encoded)| encoded).collect(); |
| 1553 | assert!( |
| 1554 | coding_order.iter().all(|&i| i < frames.len()), |
| 1555 | "a coded frame's display position is outside the sequence" |
| 1556 | ); |
| 1557 | Ok(crate::encode::EncodedSequence { stream, frames, coding_order }) |
| 1558 | } |
| 1559 | |
| 1560 | |
| 1561 | |
| 1562 | fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet { |
| 1563 | let dts = self.next_dts; |
| 1564 | self.next_dts += 1; |
| 1565 | Packet { |
| 1566 | data, |
| 1567 | key, |
| 1568 | order, |
| 1569 | dts, |
| 1570 | level, |
| 1571 | } |
| 1572 | } |
| 1573 | |
| 1574 | |
| 1575 | |
| 1576 | fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) { |
| 1577 | let slot = DpbSlot { |
| 1578 | picture: encoded.reconstruction.clone(), |
| 1579 | order_hint, |
| 1580 | cdfs: encoded.next_cdfs.clone(), |
| 1581 | }; |
| 1582 | for &s in slots { |
| 1583 | self.dpb[s as usize] = Some(slot.clone()); |
| 1584 | } |
| 1585 | } |
| 1586 | |
| 1587 | |
| 1588 | |
| 1589 | |
| 1590 | fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> { |
| 1591 | let render = (self.config.width, self.config.height); |
| 1592 | let base = self |
| 1593 | .rate_loop |
| 1594 | .as_ref() |
| 1595 | .map_or(i16::from(self.config.base_q_idx), |r| i16::from(r.q_idx(Level::Key))); |
| 1596 | let offset = self.pyramid.map_or(0, |p| p.key_q_offset); |
| 1597 | let base_q_idx = (base + offset).clamp(1, 255) as u8; |
| 1598 | let encoded = encode_key_frame_inner( |
| 1599 | &picture.padded_to(SUPERBLOCK), |
| 1600 | base_q_idx, |
| 1601 | DEADZONE, |
| 1602 | &KEY_FRAME_MODES, |
| 1603 | split_blocks(), |
| 1604 | render, |
| 1605 | self.color_config, |
| 1606 | &self.fctx, |
| 1607 | )?; |
| 1608 | self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0); |
| 1609 | self.anchor = 0; |
| 1610 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1611 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1612 | rate_loop.update(Level::Key, 0, cropped.stream.len()); |
| 1613 | } |
| 1614 | if let Some(collected) = self.collected.as_mut() { |
| 1615 | collected.push((order, cropped.clone())); |
| 1616 | } |
| 1617 | Ok(self.packet(cropped.stream, true, order, Level::Key)) |
| 1618 | } |
| 1619 | |
| 1620 | |
| 1621 | #[allow(clippy::too_many_arguments)] |
| 1622 | fn encode_pyramid_inter( |
| 1623 | &mut self, |
| 1624 | order: u64, |
| 1625 | picture: &Picture, |
| 1626 | last_slot: u8, |
| 1627 | self_slot: u8, |
| 1628 | altref_slot: u8, |
| 1629 | show_frame: bool, |
| 1630 | level: Level, |
| 1631 | |
| 1632 | |
| 1633 | |
| 1634 | |
| 1635 | offset: i16, |
| 1636 | |
| 1637 | |
| 1638 | |
| 1639 | lookahead: &[Picture], |
| 1640 | ) -> Result<Packet> { |
| 1641 | let render = (self.config.width, self.config.height); |
| 1642 | let order_hint = (order & 0x7f) as u32; |
| 1643 | let base = self |
| 1644 | .rate_loop |
| 1645 | .as_ref() |
| 1646 | .map_or(i16::from(self.config.base_q_idx), |r| { |
| 1647 | i16::from(r.q_idx(level)) |
| 1648 | }); |
| 1649 | let base_q_idx = (base + offset).clamp(1, 255) as u8; |
| 1650 | |
| 1651 | |
| 1652 | |
| 1653 | |
| 1654 | |
| 1655 | |
| 1656 | let mut sign_bias = crate::mvstack::NO_SIGN_BIAS; |
| 1657 | let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| { |
| 1658 | dpb[slot as usize] |
| 1659 | .as_ref() |
| 1660 | .is_some_and(|s| s.order_hint > order_hint) |
| 1661 | }; |
| 1662 | let slots = [ |
| 1663 | last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot, |
| 1664 | ]; |
| 1665 | for (i, slot) in slots.into_iter().enumerate() { |
| 1666 | sign_bias[i] = ahead(slot, &self.dpb); |
| 1667 | } |
| 1668 | |
| 1669 | |
| 1670 | let order_hints: [u32; 7] = slots.map(|slot| { |
| 1671 | self.dpb[slot as usize] |
| 1672 | .as_ref() |
| 1673 | .map_or(0, |s| (s.order_hint & 0x7f) as u32) |
| 1674 | }); |
| 1675 | let reference = self.dpb[last_slot as usize] |
| 1676 | .as_ref() |
| 1677 | .map(|s| s.picture.clone()) |
| 1678 | .ok_or_else(|| { |
| 1679 | Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction") |
| 1680 | })?; |
| 1681 | let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone()); |
| 1682 | let altref = (altref_slot != GOLDEN_SLOT) |
| 1683 | .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone())) |
| 1684 | .flatten(); |
| 1685 | let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone()); |
| 1686 | let encoded = || -> Result<Encoded> { encode_inter_frame( |
| 1687 | &picture.padded_to(SUPERBLOCK), |
| 1688 | &reference, |
| 1689 | base_q_idx, |
| 1690 | DEADZONE, |
| 1691 | order_hint, |
| 1692 | order_hints, |
| 1693 | render, |
| 1694 | start_cdfs.as_ref(), |
| 1695 | golden.as_ref(), |
| 1696 | altref.as_ref(), |
| 1697 | &self.fctx, |
| 1698 | Some(crate::encode::PyramidFrame { |
| 1699 | last_slot, |
| 1700 | self_slot, |
| 1701 | altref_slot, |
| 1702 | show_frame, |
| 1703 | sign_bias, |
| 1704 | }), |
| 1705 | |
| 1706 | |
| 1707 | |
| 1708 | lookahead, |
| 1709 | ) }(); |
| 1710 | |
| 1711 | |
| 1712 | |
| 1713 | let encoded = encoded.map_err(|e| { |
| 1714 | Error::unsupported( |
| 1715 | "AV1 encode", |
| 1716 | format!( |
| 1717 | "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \ |
| 1718 | altref {altref_slot}, shown {show_frame}, golden {}, altref pic {}): {e}", |
| 1719 | golden.is_some(), |
| 1720 | altref.is_some(), |
| 1721 | ), |
| 1722 | ) |
| 1723 | })?; |
| 1724 | self.refresh(&[self_slot], &encoded, order_hint); |
| 1725 | let cropped = crop_encoded(&encoded, render.0, render.1); |
| 1726 | if let Some(rate_loop) = self.rate_loop.as_mut() { |
| 1727 | rate_loop.update(level, offset, cropped.stream.len()); |
| 1728 | } |
| 1729 | if let Some(collected) = self.collected.as_mut() { |
| 1730 | collected.push((order, cropped.clone())); |
| 1731 | } |
| 1732 | Ok(self.packet(cropped.stream, false, order, level)) |
| 1733 | } |
| 1734 | |
| 1735 | |
| 1736 | |
| 1737 | |
| 1738 | fn drain_pending(&mut self) -> Result<Vec<Packet>> { |
| 1739 | if self.pending.is_empty() { |
| 1740 | return Ok(Vec::new()); |
| 1741 | } |
| 1742 | let group: Vec<(u64, Picture)> = std::mem::take(&mut self.pending); |
| 1743 | let mut packets = Vec::with_capacity(group.len() + 1); |
| 1744 | |
| 1745 | |
| 1746 | |
| 1747 | |
| 1748 | |
| 1749 | |
| 1750 | let tpl_window = |pos: usize, back: bool| -> Vec<Picture> { |
| 1751 | let depth = crate::encode::tpl_depth(); |
| 1752 | if !tpl_pyramid() || depth < 2 { |
| 1753 | return Vec::new(); |
| 1754 | } |
| 1755 | let window: Vec<&Picture> = match back { |
| 1756 | false => group[pos + 1..].iter().map(|(_, p)| p).collect(), |
| 1757 | true => group[..pos].iter().rev().map(|(_, p)| p).collect(), |
| 1758 | }; |
| 1759 | window.into_iter().take(depth - 1).map(|p| p.padded_to(SUPERBLOCK)).collect() |
| 1760 | }; |
| 1761 | let anchor_slot = ANCHOR_SLOTS[self.anchor]; |
| 1762 | let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor]; |
| 1763 | let (arf_order, arf_picture) = group.last().cloned().expect("non-empty"); |
| 1764 | let pyramid = self.pyramid.expect("pyramid mode"); |
| 1765 | if group.len() == 1 { |
| 1766 | |
| 1767 | |
| 1768 | packets.push(self.encode_pyramid_inter( |
| 1769 | arf_order, |
| 1770 | &arf_picture, |
| 1771 | anchor_slot, |
| 1772 | next_anchor_slot, |
| 1773 | GOLDEN_SLOT, |
| 1774 | true, |
| 1775 | Level::Leaf, |
| 1776 | pyramid.leaf_q_offset, |
| 1777 | &tpl_window(0, false), |
| 1778 | )?); |
| 1779 | self.anchor = 1 - self.anchor; |
| 1780 | return Ok(packets); |
| 1781 | } |
| 1782 | |
| 1783 | packets.push(self.encode_pyramid_inter( |
| 1784 | arf_order, |
| 1785 | &arf_picture, |
| 1786 | anchor_slot, |
| 1787 | next_anchor_slot, |
| 1788 | |
| 1789 | |
| 1790 | |
| 1791 | |
| 1792 | match arf_altref() { |
| 1793 | true => next_anchor_slot, |
| 1794 | false => GOLDEN_SLOT, |
| 1795 | }, |
| 1796 | false, |
| 1797 | Level::Arf, |
| 1798 | pyramid.arf_q_offset, |
| 1799 | &tpl_window(group.len() - 1, true), |
| 1800 | )?); |
| 1801 | let leaves = group.len() - 1; |
| 1802 | |
| 1803 | |
| 1804 | |
| 1805 | |
| 1806 | |
| 1807 | |
| 1808 | |
| 1809 | |
| 1810 | |
| 1811 | |
| 1812 | |
| 1813 | |
| 1814 | |
| 1815 | |
| 1816 | let long_run = self.config.gop > pyramid.mini_gop + pyramid.mini_gop / 2; |
| 1817 | let mid = pyramid.mid_q_offset.filter(|_| leaves >= 3 && long_run).map(|offset| { |
| 1818 | let at = (leaves - 1) / 2; |
| 1819 | (at, offset) |
| 1820 | }); |
| 1821 | if let Some((at, offset)) = mid { |
| 1822 | let (order, picture) = group[at].clone(); |
| 1823 | packets.push(self.encode_pyramid_inter( |
| 1824 | order, |
| 1825 | &picture, |
| 1826 | anchor_slot, |
| 1827 | MID_SLOT, |
| 1828 | next_anchor_slot, |
| 1829 | false, |
| 1830 | Level::Arf, |
| 1831 | offset, |
| 1832 | &tpl_window(at, false), |
| 1833 | )?); |
| 1834 | } |
| 1835 | |
| 1836 | |
| 1837 | |
| 1838 | |
| 1839 | |
| 1840 | |
| 1841 | |
| 1842 | |
| 1843 | let quarters = match (mid, pyramid.quarter_q_offset) { |
| 1844 | (Some((at, _)), Some(offset)) if leaves >= 7 => { |
| 1845 | Some(([(at - 1) / 2, (at + leaves) / 2], offset)) |
| 1846 | } |
| 1847 | _ => None, |
| 1848 | }; |
| 1849 | if let Some((at, offset)) = quarters { |
| 1850 | |
| 1851 | |
| 1852 | |
| 1853 | for (i, &pos) in at.iter().enumerate() { |
| 1854 | let (order, picture) = group[pos].clone(); |
| 1855 | let (last_slot, altref_slot) = match i { |
| 1856 | 0 => (anchor_slot, MID_SLOT), |
| 1857 | _ => (MID_SLOT, next_anchor_slot), |
| 1858 | }; |
| 1859 | packets.push(self.encode_pyramid_inter( |
| 1860 | order, |
| 1861 | &picture, |
| 1862 | last_slot, |
| 1863 | QUARTER_SLOTS[i], |
| 1864 | altref_slot, |
| 1865 | false, |
| 1866 | Level::Arf, |
| 1867 | offset, |
| 1868 | &tpl_window(pos, false), |
| 1869 | )?); |
| 1870 | } |
| 1871 | } |
| 1872 | |
| 1873 | |
| 1874 | |
| 1875 | |
| 1876 | let mut inner: Vec<(usize, u8)> = Vec::new(); |
| 1877 | if let Some((at, _)) = mid { |
| 1878 | inner.push((at, MID_SLOT)); |
| 1879 | } |
| 1880 | if let Some((at, _)) = quarters { |
| 1881 | inner.extend(at.iter().zip(QUARTER_SLOTS).map(|(&at, slot)| (at, slot))); |
| 1882 | } |
| 1883 | inner.sort_unstable(); |
| 1884 | let (seq, _) = crate::encode::key_frame_headers( |
| 1885 | self.config.width, |
| 1886 | self.config.height, |
| 1887 | self.config.base_q_idx, |
| 1888 | )?; |
| 1889 | let show_existing = |encoder: &mut Self, slot: u8, order: u64| -> Result<Packet> { |
| 1890 | let mut data = crate::obu::temporal_delimiter(); |
| 1891 | data.extend_from_slice(&crate::frame::show_existing_frame_obu(&seq, slot)?); |
| 1892 | Ok(encoder.packet(data, false, order, Level::ShowExisting)) |
| 1893 | }; |
| 1894 | |
| 1895 | |
| 1896 | |
| 1897 | |
| 1898 | |
| 1899 | for (i, (order, picture)) in group[..leaves].iter().enumerate() { |
| 1900 | if let Some(&(_, slot)) = inner.iter().find(|(at, _)| *at == i) { |
| 1901 | let packet = show_existing(self, slot, *order)?; |
| 1902 | packets.push(packet); |
| 1903 | continue; |
| 1904 | } |
| 1905 | let last_slot = match i { |
| 1906 | 0 => anchor_slot, |
| 1907 | i => inner |
| 1908 | .iter() |
| 1909 | .find(|(at, _)| at + 1 == i) |
| 1910 | .map_or(LEAF_SLOT, |&(_, slot)| slot), |
| 1911 | }; |
| 1912 | let altref_slot = inner |
| 1913 | .iter() |
| 1914 | .find(|(at, _)| *at > i) |
| 1915 | .map_or(next_anchor_slot, |&(_, slot)| slot); |
| 1916 | packets.push(self.encode_pyramid_inter( |
| 1917 | *order, |
| 1918 | picture, |
| 1919 | last_slot, |
| 1920 | LEAF_SLOT, |
| 1921 | altref_slot, |
| 1922 | true, |
| 1923 | Level::Leaf, |
| 1924 | pyramid.leaf_q_offset, |
| 1925 | &tpl_window(i, false), |
| 1926 | )?); |
| 1927 | } |
| 1928 | let packet = show_existing(self, next_anchor_slot, arf_order)?; |
| 1929 | packets.push(packet); |
| 1930 | self.anchor = 1 - self.anchor; |
| 1931 | Ok(packets) |
| 1932 | } |
| 1933 | } |
| 1934 | |
| 1935 | #[cfg(test)] |
| 1936 | mod tests { |
| 1937 | use super::*; |
| 1938 | use std::process::{Command, Stdio}; |
| 1939 | |
| 1940 | |
| 1941 | |
| 1942 | |
| 1943 | |
| 1944 | |
| 1945 | |
| 1946 | |
| 1947 | fn have_ffmpeg() -> bool { |
| 1948 | let present = Command::new("ffmpeg") |
| 1949 | .arg("-version") |
| 1950 | .stdout(Stdio::null()) |
| 1951 | .stderr(Stdio::null()) |
| 1952 | .status() |
| 1953 | .is_ok_and(|s| s.success()); |
| 1954 | assert!( |
| 1955 | present |
| 1956 | || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none() |
| 1957 | && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()), |
| 1958 | "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH" |
| 1959 | ); |
| 1960 | present |
| 1961 | } |
| 1962 | |
| 1963 | fn test_card(width: usize, height: usize, shift: usize) -> Picture { |
| 1964 | let mut picture = Picture::grey(width, height); |
| 1965 | for y in 0..height { |
| 1966 | for x in 0..width { |
| 1967 | let sx = (x + shift) % width; |
| 1968 | picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16; |
| 1969 | } |
| 1970 | } |
| 1971 | for y in 0..height / 2 { |
| 1972 | for x in 0..width / 2 { |
| 1973 | let i = y * (width / 2) + x; |
| 1974 | picture.u[i] = ((100 + shift * 4) % 256) as u16; |
| 1975 | picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16; |
| 1976 | } |
| 1977 | } |
| 1978 | picture |
| 1979 | } |
| 1980 | |
| 1981 | |
| 1982 | |
| 1983 | |
| 1984 | fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> { |
| 1985 | let mut packets = Vec::with_capacity(pictures.len()); |
| 1986 | for (i, picture) in pictures.iter().enumerate() { |
| 1987 | packets.extend( |
| 1988 | enc.encode_frames(picture) |
| 1989 | .unwrap_or_else(|e| panic!("picture {i}: {e}")), |
| 1990 | ); |
| 1991 | } |
| 1992 | packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}"))); |
| 1993 | packets |
| 1994 | } |
| 1995 | |
| 1996 | |
| 1997 | |
| 1998 | |
| 1999 | |
| 2000 | |
| 2001 | |
| 2002 | |
| 2003 | |
| 2004 | #[test] |
| 2005 | fn the_rate_loop_prices_the_frames_the_pyramid_codes() { |
| 2006 | let _knobs = crate::speed::knob_read(); |
| 2007 | let pictures: Vec<Picture> = (0..48).map(|i| test_card(64, 64, i)).collect(); |
| 2008 | let quarters = Pyramid { |
| 2009 | quarter_q_offset: Some(-20), |
| 2010 | ..Pyramid::default() |
| 2011 | }; |
| 2012 | let two_level = Pyramid { |
| 2013 | mid_q_offset: None, |
| 2014 | ..Pyramid::default() |
| 2015 | }; |
| 2016 | for (gop, pyramid) in [ |
| 2017 | (48, Pyramid::default()), |
| 2018 | (12, Pyramid::default()), |
| 2019 | (48, quarters), |
| 2020 | (48, two_level), |
| 2021 | ] { |
| 2022 | let config = EncoderConfig { |
| 2023 | width: 64, |
| 2024 | height: 64, |
| 2025 | base_q_idx: 100, |
| 2026 | gop, |
| 2027 | colour: Colour::Bt709Limited, |
| 2028 | tile_cols_log2: 0, |
| 2029 | tile_rows_log2: 0, |
| 2030 | }; |
| 2031 | let rate = RateTarget::BytesPerFrame(2_000); |
| 2032 | let mut enc = |
| 2033 | Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap(); |
| 2034 | let packets = encode_all(&mut enc, &pictures[..gop]); |
| 2035 | let coded = |level: Level| packets.iter().filter(|p| p.level == level).count(); |
| 2036 | let (hidden, leaves) = gop_shape(pyramid, gop); |
| 2037 | let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum(); |
| 2038 | assert_eq!( |
| 2039 | (hidden_frames, leaves, 1), |
| 2040 | (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)), |
| 2041 | "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves" |
| 2042 | ); |
| 2043 | assert_eq!( |
| 2044 | hidden_frames + leaves + 1, |
| 2045 | gop, |
| 2046 | "gop {gop}: every picture is coded exactly once" |
| 2047 | ); |
| 2048 | |
| 2049 | |
| 2050 | let target_bytes = 2_000.0; |
| 2051 | let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop); |
| 2052 | let planned = loop_.target[0] |
| 2053 | + loop_.target[2] * (leaves as f64 |
| 2054 | + hidden.iter().map(|&(o, n)| n as f64 * loop_.weight(o)).sum::<f64>()); |
| 2055 | assert!( |
| 2056 | (planned - target_bytes * gop as f64).abs() < 1.0, |
| 2057 | "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run", |
| 2058 | target_bytes * gop as f64 |
| 2059 | ); |
| 2060 | } |
| 2061 | } |
| 2062 | |
| 2063 | |
| 2064 | |
| 2065 | |
| 2066 | |
| 2067 | #[test] |
| 2068 | fn the_mini_gop_layout_leaves_no_short_tail() { |
| 2069 | let groups = |remaining: usize, mini_gop: usize, absorb: bool| { |
| 2070 | let (mut left, mut out) = (remaining, Vec::new()); |
| 2071 | while left > 0 { |
| 2072 | let g = group_target(left, mini_gop, absorb).min(left); |
| 2073 | assert!(g > 0); |
| 2074 | out.push(g); |
| 2075 | left -= g; |
| 2076 | } |
| 2077 | out |
| 2078 | }; |
| 2079 | |
| 2080 | assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]); |
| 2081 | assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]); |
| 2082 | |
| 2083 | assert_eq!(groups(11, 8, false), vec![8, 3]); |
| 2084 | assert_eq!(groups(11, 8, true), vec![11]); |
| 2085 | |
| 2086 | |
| 2087 | assert_eq!(groups(3, 8, true), vec![3]); |
| 2088 | |
| 2089 | for mini_gop in 2..=16 { |
| 2090 | for remaining in 1..=64 { |
| 2091 | for g in groups(remaining, mini_gop, true) { |
| 2092 | assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}"); |
| 2093 | assert!( |
| 2094 | g * 2 >= mini_gop || remaining < mini_gop, |
| 2095 | "{remaining}/{mini_gop}: short tail {g}" |
| 2096 | ); |
| 2097 | } |
| 2098 | } |
| 2099 | } |
| 2100 | } |
| 2101 | |
| 2102 | |
| 2103 | |
| 2104 | fn concat(packets: &[Packet]) -> Vec<u8> { |
| 2105 | packets.iter().flat_map(|p| p.data.clone()).collect() |
| 2106 | } |
| 2107 | |
| 2108 | |
| 2109 | |
| 2110 | |
| 2111 | |
| 2112 | |
| 2113 | |
| 2114 | #[test] |
| 2115 | fn one_in_one_out_delayed_by_the_lookahead_depth() { |
| 2116 | let _knobs = crate::speed::knob_read(); |
| 2117 | let config = EncoderConfig { |
| 2118 | width: 64, |
| 2119 | height: 64, |
| 2120 | base_q_idx: 100, |
| 2121 | gop: 2, |
| 2122 | colour: Colour::Bt709Limited, |
| 2123 | tile_cols_log2: 0, |
| 2124 | tile_rows_log2: 0, |
| 2125 | }; |
| 2126 | let delay = crate::encode::tpl_depth() as u64 - 1; |
| 2127 | let pictures = delay + 5; |
| 2128 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2129 | for t in 0..pictures { |
| 2130 | let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); |
| 2131 | if t < delay { |
| 2132 | assert!(packet.data.is_empty(), "call {t} holds its picture back"); |
| 2133 | continue; |
| 2134 | } |
| 2135 | assert!(!packet.data.is_empty(), "picture {t}: empty packet"); |
| 2136 | assert_eq!(packet.order, t - delay, "picture {t}: order"); |
| 2137 | } |
| 2138 | let tail = enc.flush().unwrap(); |
| 2139 | assert_eq!(tail.len() as u64, delay, "flush yields the whole queue"); |
| 2140 | for (i, p) in tail.iter().enumerate() { |
| 2141 | assert_eq!(p.order, pictures - delay + i as u64, "flushed packet {i}: order"); |
| 2142 | assert!(!p.data.is_empty(), "flushed packet {i}: empty"); |
| 2143 | } |
| 2144 | assert!(enc.flush().unwrap().is_empty(), "nothing is held twice"); |
| 2145 | } |
| 2146 | |
| 2147 | |
| 2148 | |
| 2149 | |
| 2150 | |
| 2151 | |
| 2152 | fn screen_card(width: usize, height: usize, shift: usize) -> Picture { |
| 2153 | let mut picture = Picture::grey(width, height); |
| 2154 | for y in 0..height { |
| 2155 | for x in 0..width { |
| 2156 | let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 }; |
| 2157 | let over = y >= height / 2 && (x + shift) % width < width / 3; |
| 2158 | picture.y[y * width + x] = if over { 128 } else { band }; |
| 2159 | } |
| 2160 | } |
| 2161 | picture |
| 2162 | } |
| 2163 | |
| 2164 | |
| 2165 | |
| 2166 | |
| 2167 | |
| 2168 | |
| 2169 | |
| 2170 | |
| 2171 | |
| 2172 | |
| 2173 | |
| 2174 | |
| 2175 | |
| 2176 | |
| 2177 | |
| 2178 | |
| 2179 | |
| 2180 | |
| 2181 | #[test] |
| 2182 | fn the_facade_codes_the_same_bytes_as_encode_sequence() { |
| 2183 | let _knobs = crate::speed::knob_read(); |
| 2184 | let frames = 12usize; |
| 2185 | let film = h264_clip_frames(640, 384, frames).unwrap_or_else(|| { |
| 2186 | eprintln!("no h264 clip: the facade identity gate runs on a synthetic card"); |
| 2187 | (0..frames).map(|t| test_card(64, 64, t)).collect() |
| 2188 | }); |
| 2189 | let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect(); |
| 2190 | let pyramid = Pyramid::from_env().expect("the pyramid is this build's default"); |
| 2191 | for (content, pictures, is_screen) in |
| 2192 | [("film", &film, false), ("screen", &screen, true)] |
| 2193 | { |
| 2194 | let (width, height) = (pictures[0].width, pictures[0].height); |
| 2195 | for q in [150u8, 60] { |
| 2196 | let config = EncoderConfig { |
| 2197 | width, |
| 2198 | height, |
| 2199 | base_q_idx: q, |
| 2200 | |
| 2201 | |
| 2202 | gop: frames, |
| 2203 | |
| 2204 | colour: Colour::Unspecified, |
| 2205 | tile_cols_log2: 0, |
| 2206 | tile_rows_log2: 0, |
| 2207 | }; |
| 2208 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 2209 | let mut packets = Vec::new(); |
| 2210 | for picture in pictures { |
| 2211 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 2212 | } |
| 2213 | packets.extend(enc.flush().unwrap()); |
| 2214 | assert_eq!( |
| 2215 | enc.pyramid().is_none(), |
| 2216 | is_screen, |
| 2217 | "{content} q={q}: the content gate read this clip the other way round" |
| 2218 | ); |
| 2219 | let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap(); |
| 2220 | assert_eq!( |
| 2221 | (packets.iter().map(|p| p.data.len()).sum::<usize>(), concat(&packets)), |
| 2222 | (sequence.stream.len(), sequence.stream.clone()), |
| 2223 | "{content} q={q}: the facade's stream is not the sequence path's" |
| 2224 | ); |
| 2225 | assert_eq!( |
| 2226 | sequence.frames.len(), |
| 2227 | frames, |
| 2228 | "{content} q={q}: one entry per picture, in display order" |
| 2229 | ); |
| 2230 | if is_screen { |
| 2231 | assert_eq!(packets.len(), frames, "{content} q={q}: one packet per picture"); |
| 2232 | for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() { |
| 2233 | let cropped = crate::encode::crop_encoded(coded, width, height); |
| 2234 | assert_eq!( |
| 2235 | (packet.data.len(), packet.data.clone()), |
| 2236 | (cropped.stream.len(), cropped.stream.clone()), |
| 2237 | "{content} q={q} frame {i}: the facade's bytes are not the \ |
| 2238 | sequence path's" |
| 2239 | ); |
| 2240 | } |
| 2241 | } else { |
| 2242 | assert!( |
| 2243 | packets.iter().any(|p| p.level == Level::Arf), |
| 2244 | "{content} q={q}: a non-screen stream coded no hidden frame" |
| 2245 | ); |
| 2246 | } |
| 2247 | } |
| 2248 | } |
| 2249 | } |
| 2250 | |
| 2251 | |
| 2252 | |
| 2253 | |
| 2254 | |
| 2255 | |
| 2256 | |
| 2257 | |
| 2258 | #[test] |
| 2259 | fn the_content_gate_keeps_screen_streams_flat() { |
| 2260 | let _knobs = crate::speed::knob_read(); |
| 2261 | let frames = 8usize; |
| 2262 | let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect(); |
| 2263 | let config = EncoderConfig { |
| 2264 | width: 64, |
| 2265 | height: 64, |
| 2266 | base_q_idx: 120, |
| 2267 | gop: frames, |
| 2268 | colour: Colour::Unspecified, |
| 2269 | tile_cols_log2: 0, |
| 2270 | tile_rows_log2: 0, |
| 2271 | }; |
| 2272 | crate::encode::force_screen(Some(true)); |
| 2273 | let mut flat = Av1Encoder::new(config).unwrap(); |
| 2274 | let flat_packets = encode_all(&mut flat, &pictures); |
| 2275 | let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); |
| 2276 | let gated_packets = encode_all(&mut gated, &pictures); |
| 2277 | assert_eq!(gated.pyramid(), None, "the gate left a screen stream on the pyramid"); |
| 2278 | assert_eq!( |
| 2279 | concat(&gated_packets), |
| 2280 | concat(&flat_packets), |
| 2281 | "a screen stream's bytes are not the flat path's" |
| 2282 | ); |
| 2283 | crate::encode::force_screen(Some(false)); |
| 2284 | let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap(); |
| 2285 | let kept_packets = encode_all(&mut kept, &pictures); |
| 2286 | assert_eq!(kept.pyramid(), Some(Pyramid::default()), "the gate ate a film stream"); |
| 2287 | assert!( |
| 2288 | kept_packets.iter().any(|p| p.level == Level::Arf), |
| 2289 | "a non-screen stream coded no hidden frame" |
| 2290 | ); |
| 2291 | crate::encode::force_screen(None); |
| 2292 | } |
| 2293 | |
| 2294 | |
| 2295 | |
| 2296 | |
| 2297 | #[test] |
| 2298 | fn gop_cadence_is_honored() { |
| 2299 | let _knobs = crate::speed::knob_read(); |
| 2300 | let config = EncoderConfig { |
| 2301 | width: 64, |
| 2302 | height: 64, |
| 2303 | base_q_idx: 100, |
| 2304 | gop: 3, |
| 2305 | colour: Colour::Unspecified, |
| 2306 | tile_cols_log2: 0, |
| 2307 | tile_rows_log2: 0, |
| 2308 | }; |
| 2309 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2310 | let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect(); |
| 2311 | let keys: Vec<bool> = encode_all(&mut enc, &pictures) |
| 2312 | .iter() |
| 2313 | .map(|p| p.key) |
| 2314 | .collect(); |
| 2315 | assert_eq!(keys, vec![true, false, false, true, false, false, true]); |
| 2316 | } |
| 2317 | |
| 2318 | fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { |
| 2319 | let path = std::env::temp_dir().join(format!( |
| 2320 | "ec-av1-facade-probe-{}-{}.obu", |
| 2321 | std::process::id(), |
| 2322 | std::ptr::addr_of!(stream) as usize |
| 2323 | )); |
| 2324 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 2325 | let out = Command::new("ffprobe") |
| 2326 | .args([ |
| 2327 | "-v", |
| 2328 | "error", |
| 2329 | "-f", |
| 2330 | "obu", |
| 2331 | "-select_streams", |
| 2332 | "v:0", |
| 2333 | "-show_entries", |
| 2334 | "frame=key_frame,width,height", |
| 2335 | "-of", |
| 2336 | "csv=p=0", |
| 2337 | ]) |
| 2338 | .arg(&path) |
| 2339 | .output() |
| 2340 | .expect("ffprobe failed to run"); |
| 2341 | let _ = std::fs::remove_file(&path); |
| 2342 | assert!( |
| 2343 | out.status.success(), |
| 2344 | "ffprobe refused the stream: {}", |
| 2345 | String::from_utf8_lossy(&out.stderr) |
| 2346 | ); |
| 2347 | String::from_utf8_lossy(&out.stdout) |
| 2348 | .lines() |
| 2349 | .map(|line| { |
| 2350 | let mut f = line.trim().split(','); |
| 2351 | let key: u32 = f.next().unwrap().parse().unwrap(); |
| 2352 | let width: u32 = f.next().unwrap().parse().unwrap(); |
| 2353 | let height: u32 = f.next().unwrap().parse().unwrap(); |
| 2354 | (key == 1, width, height) |
| 2355 | }) |
| 2356 | .collect() |
| 2357 | } |
| 2358 | |
| 2359 | fn ffprobe_colour(stream: &[u8]) -> String { |
| 2360 | let path = std::env::temp_dir().join(format!( |
| 2361 | "ec-av1-facade-colour-probe-{}-{}.obu", |
| 2362 | std::process::id(), |
| 2363 | std::ptr::addr_of!(stream) as usize |
| 2364 | )); |
| 2365 | std::fs::write(&path, stream).expect("writing the probe stream"); |
| 2366 | let out = Command::new("ffprobe") |
| 2367 | .args([ |
| 2368 | "-v", |
| 2369 | "error", |
| 2370 | "-f", |
| 2371 | "obu", |
| 2372 | "-select_streams", |
| 2373 | "v:0", |
| 2374 | "-show_entries", |
| 2375 | "stream=color_primaries,color_transfer,color_space,color_range", |
| 2376 | "-of", |
| 2377 | "csv=p=0", |
| 2378 | ]) |
| 2379 | .arg(&path) |
| 2380 | .output() |
| 2381 | .expect("ffprobe failed to run"); |
| 2382 | let _ = std::fs::remove_file(&path); |
| 2383 | assert!( |
| 2384 | out.status.success(), |
| 2385 | "ffprobe refused the stream: {}", |
| 2386 | String::from_utf8_lossy(&out.stderr) |
| 2387 | ); |
| 2388 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 2389 | } |
| 2390 | |
| 2391 | |
| 2392 | |
| 2393 | |
| 2394 | |
| 2395 | #[test] |
| 2396 | fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { |
| 2397 | let _knobs = crate::speed::knob_read(); |
| 2398 | if !have_ffmpeg() { |
| 2399 | eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg"); |
| 2400 | return; |
| 2401 | } |
| 2402 | let (width, height) = (96usize, 96usize); |
| 2403 | let config = EncoderConfig { |
| 2404 | width, |
| 2405 | height, |
| 2406 | base_q_idx: 120, |
| 2407 | gop: 15, |
| 2408 | colour: Colour::Bt709Limited, |
| 2409 | tile_cols_log2: 0, |
| 2410 | tile_rows_log2: 0, |
| 2411 | }; |
| 2412 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2413 | assert_eq!(enc.display_size(), (width, height)); |
| 2414 | let (coded_w, coded_h) = enc.coded_size(); |
| 2415 | assert_eq!( |
| 2416 | (coded_w, coded_h), |
| 2417 | ( |
| 2418 | width.next_multiple_of(SUPERBLOCK), |
| 2419 | height.next_multiple_of(SUPERBLOCK) |
| 2420 | ) |
| 2421 | ); |
| 2422 | |
| 2423 | let pictures: Vec<Picture> = (0..30).map(|t| test_card(width, height, t)).collect(); |
| 2424 | let packets: Vec<Packet> = encode_all(&mut enc, &pictures); |
| 2425 | let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect(); |
| 2426 | assert_eq!( |
| 2427 | packets.iter().map(|p| p.key).collect::<Vec<_>>(), |
| 2428 | expect_key, |
| 2429 | "facade's own key/inter flags" |
| 2430 | ); |
| 2431 | |
| 2432 | let stream = concat(&packets); |
| 2433 | let frames = ffprobe_frames(&stream); |
| 2434 | assert_eq!(frames.len(), 30, "ffprobe frame count"); |
| 2435 | for (t, (key, w, h)) in frames.iter().enumerate() { |
| 2436 | assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); |
| 2437 | assert_eq!( |
| 2438 | (*w, *h), |
| 2439 | (width as u32, height as u32), |
| 2440 | "picture {t}: ffprobe reports the true (display) size, not the padded coded one" |
| 2441 | ); |
| 2442 | } |
| 2443 | } |
| 2444 | |
| 2445 | |
| 2446 | |
| 2447 | |
| 2448 | |
| 2449 | |
| 2450 | |
| 2451 | #[test] |
| 2452 | fn bt709_limited_colour_is_reported_by_ffprobe() { |
| 2453 | let _knobs = crate::speed::knob_read(); |
| 2454 | if !have_ffmpeg() { |
| 2455 | eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 2456 | return; |
| 2457 | } |
| 2458 | let config = EncoderConfig { |
| 2459 | width: 64, |
| 2460 | height: 64, |
| 2461 | base_q_idx: 100, |
| 2462 | gop: 4, |
| 2463 | colour: Colour::Bt709Limited, |
| 2464 | tile_cols_log2: 0, |
| 2465 | tile_rows_log2: 0, |
| 2466 | }; |
| 2467 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2468 | let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); |
| 2469 | let colour = ffprobe_colour(&packets[0].data); |
| 2470 | assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); |
| 2471 | } |
| 2472 | |
| 2473 | |
| 2474 | |
| 2475 | |
| 2476 | #[test] |
| 2477 | fn bt601_limited_colour_is_reported_by_ffprobe() { |
| 2478 | let _knobs = crate::speed::knob_read(); |
| 2479 | if !have_ffmpeg() { |
| 2480 | eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg"); |
| 2481 | return; |
| 2482 | } |
| 2483 | let config = EncoderConfig { |
| 2484 | width: 64, |
| 2485 | height: 64, |
| 2486 | base_q_idx: 100, |
| 2487 | gop: 4, |
| 2488 | colour: Colour::Bt601Limited, |
| 2489 | tile_cols_log2: 0, |
| 2490 | tile_rows_log2: 0, |
| 2491 | }; |
| 2492 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2493 | let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]); |
| 2494 | let colour = ffprobe_colour(&packets[0].data); |
| 2495 | assert_eq!( |
| 2496 | colour, "tv,smpte170m,smpte170m,smpte170m", |
| 2497 | "ffprobe colour fields" |
| 2498 | ); |
| 2499 | } |
| 2500 | |
| 2501 | |
| 2502 | |
| 2503 | #[test] |
| 2504 | fn geometry_mismatch_is_refused() { |
| 2505 | let _knobs = crate::speed::knob_read(); |
| 2506 | let config = EncoderConfig { |
| 2507 | width: 64, |
| 2508 | height: 64, |
| 2509 | base_q_idx: 100, |
| 2510 | gop: 4, |
| 2511 | colour: Colour::Bt709Limited, |
| 2512 | tile_cols_log2: 0, |
| 2513 | tile_rows_log2: 0, |
| 2514 | }; |
| 2515 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 2516 | let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); |
| 2517 | assert!(err.to_string().contains("64x64"), "{err}"); |
| 2518 | } |
| 2519 | |
| 2520 | |
| 2521 | #[test] |
| 2522 | fn zero_gop_is_refused() { |
| 2523 | let _knobs = crate::speed::knob_read(); |
| 2524 | let config = EncoderConfig { |
| 2525 | width: 64, |
| 2526 | height: 64, |
| 2527 | base_q_idx: 100, |
| 2528 | gop: 0, |
| 2529 | colour: Colour::Bt709Limited, |
| 2530 | tile_cols_log2: 0, |
| 2531 | tile_rows_log2: 0, |
| 2532 | }; |
| 2533 | let err = Av1Encoder::new(config).unwrap_err(); |
| 2534 | assert!(err.to_string().contains("gop"), "{err}"); |
| 2535 | } |
| 2536 | |
| 2537 | |
| 2538 | |
| 2539 | |
| 2540 | |
| 2541 | |
| 2542 | fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> { |
| 2543 | if !have_ffmpeg() { |
| 2544 | return None; |
| 2545 | } |
| 2546 | |
| 2547 | |
| 2548 | |
| 2549 | |
| 2550 | |
| 2551 | let clip = match std::env::var("EC_AV1_WALL_CLIP") { |
| 2552 | Ok(p) => std::path::PathBuf::from(p), |
| 2553 | Err(_) => std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 2554 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"), |
| 2555 | }; |
| 2556 | if !clip.exists() { |
| 2557 | return None; |
| 2558 | } |
| 2559 | let out = Command::new("ffmpeg") |
| 2560 | .args(["-v", "error", "-i", clip.to_str().unwrap()]) |
| 2561 | .args(["-frames:v", &frames.to_string()]) |
| 2562 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 2563 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 2564 | .output() |
| 2565 | .expect("ffmpeg failed to run"); |
| 2566 | assert!( |
| 2567 | out.status.success(), |
| 2568 | "{}", |
| 2569 | String::from_utf8_lossy(&out.stderr) |
| 2570 | ); |
| 2571 | let (luma, chroma) = (width * height, width * height / 4); |
| 2572 | let frame_len = luma + 2 * chroma; |
| 2573 | assert_eq!( |
| 2574 | out.stdout.len(), |
| 2575 | frame_len * frames, |
| 2576 | "expected {frames} 4:2:0 frames" |
| 2577 | ); |
| 2578 | Some( |
| 2579 | (0..frames) |
| 2580 | .map(|i| { |
| 2581 | let bytes = &out.stdout[i * frame_len..][..frame_len]; |
| 2582 | Picture { |
| 2583 | width, |
| 2584 | height, |
| 2585 | y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(), |
| 2586 | u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(), |
| 2587 | v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(), |
| 2588 | } |
| 2589 | }) |
| 2590 | .collect(), |
| 2591 | ) |
| 2592 | } |
| 2593 | |
| 2594 | |
| 2595 | |
| 2596 | |
| 2597 | |
| 2598 | #[test] |
| 2599 | fn bytes_per_frame_target_settles_within_20_percent() { |
| 2600 | let _knobs = crate::speed::knob_read(); |
| 2601 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 2602 | eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture"); |
| 2603 | return; |
| 2604 | }; |
| 2605 | let target_bytes = 4_000u32; |
| 2606 | let config = EncoderConfig { |
| 2607 | width: 640, |
| 2608 | height: 384, |
| 2609 | base_q_idx: 100, |
| 2610 | gop: 24, |
| 2611 | colour: Colour::Bt709Limited, |
| 2612 | tile_cols_log2: 0, |
| 2613 | tile_rows_log2: 0, |
| 2614 | }; |
| 2615 | let mut enc = |
| 2616 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap(); |
| 2617 | let sizes: Vec<usize> = encode_all(&mut enc, &pictures) |
| 2618 | .iter() |
| 2619 | .map(|p| p.data.len()) |
| 2620 | .collect(); |
| 2621 | |
| 2622 | |
| 2623 | let settled = &sizes[5..]; |
| 2624 | let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64; |
| 2625 | let low = f64::from(target_bytes) * 0.8; |
| 2626 | let high = f64::from(target_bytes) * 1.2; |
| 2627 | assert!( |
| 2628 | mean >= low && mean <= high, |
| 2629 | "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}" |
| 2630 | ); |
| 2631 | } |
| 2632 | |
| 2633 | |
| 2634 | |
| 2635 | |
| 2636 | |
| 2637 | |
| 2638 | |
| 2639 | |
| 2640 | |
| 2641 | |
| 2642 | |
| 2643 | |
| 2644 | |
| 2645 | |
| 2646 | |
| 2647 | |
| 2648 | #[test] |
| 2649 | fn bitrate_target_lands_within_5_percent_over_48_frames() { |
| 2650 | let _knobs = crate::speed::knob_read(); |
| 2651 | let (width, height, frames) = (640usize, 384usize, 48usize); |
| 2652 | let Some(pictures) = h264_clip_frames(width, height, frames) else { |
| 2653 | eprintln!("SKIP bitrate_target_lands_within_5_percent_over_48_frames: no ffmpeg/fixture"); |
| 2654 | return; |
| 2655 | }; |
| 2656 | let fps = 24.0; |
| 2657 | for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] { |
| 2658 | let config = EncoderConfig { |
| 2659 | width, |
| 2660 | height, |
| 2661 | base_q_idx: 100, |
| 2662 | gop: frames, |
| 2663 | colour: Colour::Bt709Limited, |
| 2664 | tile_cols_log2: 0, |
| 2665 | tile_rows_log2: 0, |
| 2666 | }; |
| 2667 | let rate = RateTarget::Bitrate { |
| 2668 | bits_per_second, |
| 2669 | frames_per_second: fps, |
| 2670 | }; |
| 2671 | for pyramid in [None, Some(Pyramid::default())] { |
| 2672 | let mut enc = match pyramid { |
| 2673 | None => Av1Encoder::with_rate_target(config, rate).unwrap(), |
| 2674 | Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(), |
| 2675 | }; |
| 2676 | let targets = enc.rate_loop.as_ref().unwrap().target; |
| 2677 | let mut coded = 0usize; |
| 2678 | |
| 2679 | |
| 2680 | let (mut bytes, mut count) = ([0usize; 4], [0usize; 4]); |
| 2681 | let mut take = |packets: Vec<Packet>| { |
| 2682 | for packet in packets { |
| 2683 | coded += packet.data.len(); |
| 2684 | let i = match packet.level { |
| 2685 | Level::Key => 0, |
| 2686 | Level::Arf => 1, |
| 2687 | Level::Leaf => 2, |
| 2688 | Level::ShowExisting => 3, |
| 2689 | }; |
| 2690 | bytes[i] += packet.data.len(); |
| 2691 | count[i] += 1; |
| 2692 | } |
| 2693 | }; |
| 2694 | for picture in &pictures { |
| 2695 | take(enc.encode_frames(picture).unwrap()); |
| 2696 | } |
| 2697 | take(enc.flush().unwrap()); |
| 2698 | let seconds = frames as f64 / fps; |
| 2699 | let achieved = coded as f64 * 8.0 / seconds; |
| 2700 | let error = achieved / f64::from(bits_per_second) - 1.0; |
| 2701 | let per = |i: usize| match count[i] { |
| 2702 | 0 => "-".to_string(), |
| 2703 | n => format!("{n}x{}", bytes[i] / n), |
| 2704 | }; |
| 2705 | eprintln!( |
| 2706 | "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \ |
| 2707 | = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \ |
| 2708 | coded key {} arf {} leaf {}", |
| 2709 | pyramid.is_some(), |
| 2710 | 100.0 * error, |
| 2711 | targets[0], |
| 2712 | targets[1], |
| 2713 | targets[2], |
| 2714 | per(0), |
| 2715 | per(1), |
| 2716 | per(2), |
| 2717 | ); |
| 2718 | assert!( |
| 2719 | error.abs() <= 0.05, |
| 2720 | "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \ |
| 2721 | (pyramid {})", |
| 2722 | 100.0 * error, |
| 2723 | pyramid.is_some(), |
| 2724 | ); |
| 2725 | } |
| 2726 | } |
| 2727 | } |
| 2728 | |
| 2729 | |
| 2730 | |
| 2731 | |
| 2732 | |
| 2733 | |
| 2734 | |
| 2735 | |
| 2736 | |
| 2737 | |
| 2738 | |
| 2739 | |
| 2740 | #[test] |
| 2741 | fn bytes_per_frame_controller_never_oscillates_past_its_clamp() { |
| 2742 | let _knobs = crate::speed::knob_read(); |
| 2743 | let Some(pictures) = h264_clip_frames(640, 384, 24) else { |
| 2744 | eprintln!( |
| 2745 | "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture" |
| 2746 | ); |
| 2747 | return; |
| 2748 | }; |
| 2749 | let config = EncoderConfig { |
| 2750 | width: 640, |
| 2751 | height: 384, |
| 2752 | base_q_idx: 100, |
| 2753 | gop: 24, |
| 2754 | colour: Colour::Bt709Limited, |
| 2755 | tile_cols_log2: 0, |
| 2756 | tile_rows_log2: 0, |
| 2757 | }; |
| 2758 | let mut enc = |
| 2759 | Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap(); |
| 2760 | let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 2761 | |
| 2762 | |
| 2763 | |
| 2764 | let mut seeded = false; |
| 2765 | let mut seed_frame = None; |
| 2766 | for (frame, picture) in pictures.iter().enumerate() { |
| 2767 | enc.encode_frames(picture).unwrap(); |
| 2768 | let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf); |
| 2769 | let step = (i32::from(q) - i32::from(prev_q)).abs(); |
| 2770 | if step > 0 && !seeded { |
| 2771 | seeded = true; |
| 2772 | seed_frame = Some(frame); |
| 2773 | } else { |
| 2774 | assert!( |
| 2775 | f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, |
| 2776 | "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp", |
| 2777 | RateLoop::STEP_CLAMP |
| 2778 | ); |
| 2779 | } |
| 2780 | prev_q = q; |
| 2781 | } |
| 2782 | assert!( |
| 2783 | seed_frame.is_some(), |
| 2784 | "the controller never steered at all -- the bound below is vacuous" |
| 2785 | ); |
| 2786 | } |
| 2787 | |
| 2788 | fn psnr(a: &[u16], b: &[u16]) -> f64 { |
| 2789 | let squared: f64 = a |
| 2790 | .iter() |
| 2791 | .zip(b) |
| 2792 | .map(|(&x, &y)| { |
| 2793 | let d = f64::from(x) - f64::from(y); |
| 2794 | d * d |
| 2795 | }) |
| 2796 | .sum(); |
| 2797 | if squared == 0.0 { |
| 2798 | return f64::INFINITY; |
| 2799 | } |
| 2800 | 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10() |
| 2801 | } |
| 2802 | |
| 2803 | |
| 2804 | |
| 2805 | |
| 2806 | |
| 2807 | fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> { |
| 2808 | let path = std::env::temp_dir().join(format!( |
| 2809 | "ec-av1-facade-rate-decode-{}-{}.obu", |
| 2810 | std::process::id(), |
| 2811 | std::ptr::addr_of!(stream) as usize |
| 2812 | )); |
| 2813 | std::fs::write(&path, stream).expect("writing the decode probe stream"); |
| 2814 | let out = Command::new("ffmpeg") |
| 2815 | .args(["-v", "error", "-f", "obu", "-i"]) |
| 2816 | .arg(&path) |
| 2817 | .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) |
| 2818 | .output() |
| 2819 | .expect("ffmpeg failed to run"); |
| 2820 | let _ = std::fs::remove_file(&path); |
| 2821 | assert!( |
| 2822 | out.status.success(), |
| 2823 | "{}", |
| 2824 | String::from_utf8_lossy(&out.stderr) |
| 2825 | ); |
| 2826 | let (luma, chroma) = (width * height, width * height / 4); |
| 2827 | let frame_len = luma + 2 * chroma; |
| 2828 | out.stdout |
| 2829 | .chunks_exact(frame_len) |
| 2830 | .map(|f| f[..luma].to_vec()) |
| 2831 | .collect() |
| 2832 | } |
| 2833 | |
| 2834 | |
| 2835 | |
| 2836 | |
| 2837 | |
| 2838 | |
| 2839 | |
| 2840 | |
| 2841 | |
| 2842 | |
| 2843 | |
| 2844 | #[test] |
| 2845 | fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() { |
| 2846 | |
| 2847 | |
| 2848 | |
| 2849 | |
| 2850 | let _knobs = crate::speed::knob_write(); |
| 2851 | pyramid_round_trip(Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() }, 2); |
| 2852 | } |
| 2853 | |
| 2854 | |
| 2855 | |
| 2856 | |
| 2857 | |
| 2858 | |
| 2859 | |
| 2860 | #[test] |
| 2861 | fn a_three_level_pyramid_stream_decodes_in_display_order() { |
| 2862 | let _knobs = crate::speed::knob_write(); |
| 2863 | pyramid_round_trip( |
| 2864 | Pyramid { mini_gop: 8, mid_q_offset: Some(-8), ..Pyramid::default() }, |
| 2865 | 2, |
| 2866 | ); |
| 2867 | } |
| 2868 | |
| 2869 | |
| 2870 | |
| 2871 | |
| 2872 | |
| 2873 | |
| 2874 | |
| 2875 | |
| 2876 | |
| 2877 | #[test] |
| 2878 | fn a_four_level_pyramid_stream_decodes_in_display_order() { |
| 2879 | let _knobs = crate::speed::knob_write(); |
| 2880 | pyramid_round_trip( |
| 2881 | Pyramid { |
| 2882 | mini_gop: 8, |
| 2883 | mid_q_offset: Some(-8), |
| 2884 | quarter_q_offset: Some(4), |
| 2885 | ..Pyramid::default() |
| 2886 | }, |
| 2887 | 4, |
| 2888 | ); |
| 2889 | } |
| 2890 | |
| 2891 | |
| 2892 | |
| 2893 | |
| 2894 | |
| 2895 | #[test] |
| 2896 | fn the_key_q_offset_reaches_the_key_frame() { |
| 2897 | let _knobs = crate::speed::knob_read(); |
| 2898 | crate::encode::force_screen(Some(false)); |
| 2899 | let key_bytes = |offset: i16| { |
| 2900 | let config = EncoderConfig { |
| 2901 | width: 128, |
| 2902 | height: 128, |
| 2903 | base_q_idx: 120, |
| 2904 | gop: 32, |
| 2905 | colour: Colour::Bt709Limited, |
| 2906 | tile_cols_log2: 0, |
| 2907 | tile_rows_log2: 0, |
| 2908 | }; |
| 2909 | let pyramid = Pyramid { key_q_offset: offset, ..Pyramid::default() }; |
| 2910 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 2911 | let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap(); |
| 2912 | let key = packets.iter().find(|p| p.level == Level::Key).expect("key frame"); |
| 2913 | key.data.len() |
| 2914 | }; |
| 2915 | let (base, finer) = (key_bytes(0), key_bytes(-48)); |
| 2916 | eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes"); |
| 2917 | assert!(finer > base, "key_q_offset -48 did not reach the key frame ({finer} <= {base})"); |
| 2918 | } |
| 2919 | |
| 2920 | fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) { |
| 2921 | let (width, height) = (128usize, 128usize); |
| 2922 | let config = EncoderConfig { |
| 2923 | width, |
| 2924 | height, |
| 2925 | base_q_idx: 120, |
| 2926 | gop: 32, |
| 2927 | colour: Colour::Bt709Limited, |
| 2928 | tile_cols_log2: 0, |
| 2929 | tile_rows_log2: 0, |
| 2930 | }; |
| 2931 | |
| 2932 | |
| 2933 | |
| 2934 | |
| 2935 | crate::encode::force_screen(Some(false)); |
| 2936 | let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap(); |
| 2937 | let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect(); |
| 2938 | let _ = crate::encode::take_ref_frame_hits(); |
| 2939 | let mut packets = Vec::new(); |
| 2940 | for picture in &sources { |
| 2941 | packets.extend(enc.encode_frames(picture).unwrap()); |
| 2942 | } |
| 2943 | packets.extend(enc.flush().unwrap()); |
| 2944 | |
| 2945 | |
| 2946 | |
| 2947 | let coded: Vec<u64> = packets |
| 2948 | .iter() |
| 2949 | .filter(|p| p.level != Level::ShowExisting) |
| 2950 | .map(|p| p.order) |
| 2951 | .collect(); |
| 2952 | let mut sorted = coded.clone(); |
| 2953 | sorted.sort_unstable(); |
| 2954 | assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture"); |
| 2955 | assert_ne!(coded, sorted, "the pyramid never reordered anything"); |
| 2956 | let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count(); |
| 2957 | assert_eq!(shown, hidden, "one show_existing_frame per hidden frame"); |
| 2958 | for (i, p) in packets.iter().enumerate() { |
| 2959 | assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position"); |
| 2960 | } |
| 2961 | let hist = |l: Level| packets.iter().filter(|p| p.level == l).count(); |
| 2962 | eprintln!( |
| 2963 | "pyramid levels: key {} arf {} leaf {} show_existing {}", |
| 2964 | hist(Level::Key), |
| 2965 | hist(Level::Arf), |
| 2966 | hist(Level::Leaf), |
| 2967 | hist(Level::ShowExisting), |
| 2968 | ); |
| 2969 | assert_eq!(hist(Level::Arf), hidden, "hidden frames"); |
| 2970 | let refs = crate::encode::take_ref_frame_hits(); |
| 2971 | eprintln!( |
| 2972 | "blocks per reference: LAST {} GOLDEN {} ALTREF {}", |
| 2973 | refs[crate::mvstack::LAST_FRAME as usize], |
| 2974 | refs[crate::mvstack::GOLDEN_FRAME as usize], |
| 2975 | refs[crate::mvstack::ALTREF_FRAME as usize], |
| 2976 | ); |
| 2977 | |
| 2978 | |
| 2979 | |
| 2980 | |
| 2981 | |
| 2982 | assert!( |
| 2983 | refs[crate::mvstack::ALTREF_FRAME as usize] > 0, |
| 2984 | "no block predicted off the hidden ALTREF" |
| 2985 | ); |
| 2986 | |
| 2987 | let stream = concat(&packets); |
| 2988 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 2989 | assert_eq!(ours.len(), sources.len(), "our decoder's display-order count"); |
| 2990 | if !have_ffmpeg() { |
| 2991 | eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg"); |
| 2992 | return; |
| 2993 | } |
| 2994 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 2995 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count"); |
| 2996 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 2997 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 2998 | assert_eq!(got.len(), b.len(), "frame {i}: luma size"); |
| 2999 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 3000 | panic!( |
| 3001 | "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3002 | at % width, |
| 3003 | at / width, |
| 3004 | got[at], |
| 3005 | b[at], |
| 3006 | ); |
| 3007 | } |
| 3008 | } |
| 3009 | } |
| 3010 | |
| 3011 | |
| 3012 | |
| 3013 | |
| 3014 | |
| 3015 | |
| 3016 | |
| 3017 | |
| 3018 | |
| 3019 | |
| 3020 | |
| 3021 | |
| 3022 | |
| 3023 | |
| 3024 | |
| 3025 | |
| 3026 | |
| 3027 | |
| 3028 | |
| 3029 | |
| 3030 | #[test] |
| 3031 | fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() { |
| 3032 | let _knobs = crate::speed::knob_write(); |
| 3033 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3034 | let (width, height) = (256usize, 128usize); |
| 3035 | let still = test_card(width, height, 0); |
| 3036 | let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect(); |
| 3037 | let config = EncoderConfig { |
| 3038 | width, |
| 3039 | height, |
| 3040 | base_q_idx: 120, |
| 3041 | gop: 8, |
| 3042 | colour: Colour::Bt709Limited, |
| 3043 | tile_cols_log2: 0, |
| 3044 | tile_rows_log2: 0, |
| 3045 | }; |
| 3046 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3047 | let mut stream = Vec::new(); |
| 3048 | let _ = crate::encode::take_b64_root_hits(); |
| 3049 | for packet in encode_all(&mut enc, &sources) { |
| 3050 | stream.extend_from_slice(&packet.data); |
| 3051 | } |
| 3052 | let roots = crate::encode::take_b64_root_hits(); |
| 3053 | |
| 3054 | assert!( |
| 3055 | roots > 0, |
| 3056 | "a static clip coded no 64x64 root at all (of 16 inter superblocks)" |
| 3057 | ); |
| 3058 | eprintln!("64x64 roots on a static clip: {roots} of 16 inter superblocks"); |
| 3059 | |
| 3060 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3061 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 3062 | if !have_ffmpeg() { |
| 3063 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 3064 | return; |
| 3065 | } |
| 3066 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 3067 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 3068 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 3069 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 3070 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 3071 | panic!( |
| 3072 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3073 | at % width, |
| 3074 | at / width, |
| 3075 | got[at], |
| 3076 | b[at], |
| 3077 | ); |
| 3078 | } |
| 3079 | } |
| 3080 | } |
| 3081 | |
| 3082 | |
| 3083 | |
| 3084 | |
| 3085 | |
| 3086 | |
| 3087 | |
| 3088 | |
| 3089 | |
| 3090 | |
| 3091 | |
| 3092 | #[test] |
| 3093 | fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() { |
| 3094 | let _knobs = crate::speed::knob_write(); |
| 3095 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3096 | let (width, height) = (256usize, 128usize); |
| 3097 | let still = test_card(width, height, 0); |
| 3098 | let sources: Vec<Picture> = (0..3) |
| 3099 | .map(|t| { |
| 3100 | let mut p = still.clone(); |
| 3101 | let step = (t * 6) as u16; |
| 3102 | for v in &mut p.y { |
| 3103 | *v = (*v + step).min(255); |
| 3104 | } |
| 3105 | p |
| 3106 | }) |
| 3107 | .collect(); |
| 3108 | let config = EncoderConfig { |
| 3109 | width, |
| 3110 | height, |
| 3111 | base_q_idx: 120, |
| 3112 | gop: 8, |
| 3113 | colour: Colour::Bt709Limited, |
| 3114 | tile_cols_log2: 0, |
| 3115 | tile_rows_log2: 0, |
| 3116 | }; |
| 3117 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3118 | let mut stream = Vec::new(); |
| 3119 | let _ = crate::encode::take_b64_residual_hits(); |
| 3120 | for packet in encode_all(&mut enc, &sources) { |
| 3121 | stream.extend_from_slice(&packet.data); |
| 3122 | } |
| 3123 | let residuals = crate::encode::take_b64_residual_hits(); |
| 3124 | assert!( |
| 3125 | residuals > 0, |
| 3126 | "a DC-stepped clip coded no 64x64 root with a residual at all" |
| 3127 | ); |
| 3128 | eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks"); |
| 3129 | |
| 3130 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3131 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 3132 | if !have_ffmpeg() { |
| 3133 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 3134 | return; |
| 3135 | } |
| 3136 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 3137 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 3138 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 3139 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 3140 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 3141 | panic!( |
| 3142 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3143 | at % width, |
| 3144 | at / width, |
| 3145 | got[at], |
| 3146 | b[at], |
| 3147 | ); |
| 3148 | } |
| 3149 | } |
| 3150 | } |
| 3151 | |
| 3152 | |
| 3153 | |
| 3154 | |
| 3155 | |
| 3156 | |
| 3157 | |
| 3158 | |
| 3159 | #[test] |
| 3160 | fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() { |
| 3161 | let _knobs = crate::speed::knob_write(); |
| 3162 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3163 | let (width, height) = (232usize, 168usize); |
| 3164 | let still = test_card(width, height, 0); |
| 3165 | let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect(); |
| 3166 | let config = EncoderConfig { |
| 3167 | width, |
| 3168 | height, |
| 3169 | base_q_idx: 120, |
| 3170 | gop: 8, |
| 3171 | colour: Colour::Bt709Limited, |
| 3172 | tile_cols_log2: 0, |
| 3173 | tile_rows_log2: 0, |
| 3174 | }; |
| 3175 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3176 | let mut stream = Vec::new(); |
| 3177 | let _ = crate::encode::take_b64_edge_hits(); |
| 3178 | for packet in encode_all(&mut enc, &sources) { |
| 3179 | stream.extend_from_slice(&packet.data); |
| 3180 | } |
| 3181 | let edges = crate::encode::take_b64_edge_hits(); |
| 3182 | assert!(edges > 0, "no 64x64 root was taken at a superblock the frame edge cuts"); |
| 3183 | eprintln!("edge 64x64 roots: {edges}"); |
| 3184 | |
| 3185 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3186 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 3187 | if !have_ffmpeg() { |
| 3188 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 3189 | return; |
| 3190 | } |
| 3191 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 3192 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 3193 | for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { |
| 3194 | let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect(); |
| 3195 | if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { |
| 3196 | panic!( |
| 3197 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3198 | at % width, |
| 3199 | at / width, |
| 3200 | got[at], |
| 3201 | theirs_i[at], |
| 3202 | ); |
| 3203 | } |
| 3204 | } |
| 3205 | } |
| 3206 | |
| 3207 | |
| 3208 | |
| 3209 | |
| 3210 | |
| 3211 | |
| 3212 | |
| 3213 | |
| 3214 | |
| 3215 | #[test] |
| 3216 | fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() { |
| 3217 | let _knobs = crate::speed::knob_write(); |
| 3218 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3219 | let (width, height) = (384usize, 216usize); |
| 3220 | let sources: Vec<Picture> = (0..3).map(|i| test_card(width, height, i)).collect(); |
| 3221 | let config = EncoderConfig { |
| 3222 | width, |
| 3223 | height, |
| 3224 | base_q_idx: 120, |
| 3225 | gop: 8, |
| 3226 | colour: Colour::Bt709Limited, |
| 3227 | tile_cols_log2: 0, |
| 3228 | tile_rows_log2: 0, |
| 3229 | }; |
| 3230 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3231 | let mut stream = Vec::new(); |
| 3232 | for packet in encode_all(&mut enc, &sources) { |
| 3233 | stream.extend_from_slice(&packet.data); |
| 3234 | } |
| 3235 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3236 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 3237 | if !have_ffmpeg() { |
| 3238 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 3239 | return; |
| 3240 | } |
| 3241 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 3242 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 3243 | for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { |
| 3244 | let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect(); |
| 3245 | if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { |
| 3246 | panic!( |
| 3247 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3248 | at % width, |
| 3249 | at / width, |
| 3250 | got[at], |
| 3251 | theirs_i[at], |
| 3252 | ); |
| 3253 | } |
| 3254 | } |
| 3255 | } |
| 3256 | |
| 3257 | |
| 3258 | |
| 3259 | |
| 3260 | |
| 3261 | |
| 3262 | |
| 3263 | |
| 3264 | |
| 3265 | #[test] |
| 3266 | fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() { |
| 3267 | let _knobs = crate::speed::knob_write(); |
| 3268 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3269 | let (width, height) = (256usize, 128usize); |
| 3270 | let still = test_card(width, height, 0); |
| 3271 | let sources: Vec<Picture> = (0..4) |
| 3272 | .map(|t| { |
| 3273 | let mut p = still.clone(); |
| 3274 | for (i, v) in p.y.iter_mut().enumerate() { |
| 3275 | let checker = ((i % width) / 4 + (i / width) / 4) % 2; |
| 3276 | let bump = (t * 5 * (checker + 1)) as u16; |
| 3277 | *v = (*v + bump).min(255); |
| 3278 | } |
| 3279 | p |
| 3280 | }) |
| 3281 | .collect(); |
| 3282 | let config = EncoderConfig { |
| 3283 | width, |
| 3284 | height, |
| 3285 | base_q_idx: 90, |
| 3286 | gop: 8, |
| 3287 | colour: Colour::Bt709Limited, |
| 3288 | tile_cols_log2: 0, |
| 3289 | tile_rows_log2: 0, |
| 3290 | }; |
| 3291 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3292 | let mut stream = Vec::new(); |
| 3293 | let _ = crate::encode::take_b64_var_tx_hits(); |
| 3294 | for packet in encode_all(&mut enc, &sources) { |
| 3295 | stream.extend_from_slice(&packet.data); |
| 3296 | } |
| 3297 | let split = crate::encode::take_b64_var_tx_hits(); |
| 3298 | assert!(split > 0, "no 64x64 root split its luma transform at all"); |
| 3299 | eprintln!("64x64 roots with a SPLIT luma transform: {split}"); |
| 3300 | |
| 3301 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3302 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 3303 | if !have_ffmpeg() { |
| 3304 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 3305 | return; |
| 3306 | } |
| 3307 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 3308 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 3309 | for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { |
| 3310 | let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect(); |
| 3311 | if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { |
| 3312 | panic!( |
| 3313 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3314 | at % width, |
| 3315 | at / width, |
| 3316 | got[at], |
| 3317 | theirs_i[at], |
| 3318 | ); |
| 3319 | } |
| 3320 | } |
| 3321 | } |
| 3322 | |
| 3323 | |
| 3324 | |
| 3325 | |
| 3326 | |
| 3327 | |
| 3328 | |
| 3329 | |
| 3330 | |
| 3331 | #[test] |
| 3332 | fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() { |
| 3333 | let _knobs = crate::speed::knob_write(); |
| 3334 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3335 | let (width, height) = (256usize, 128usize); |
| 3336 | let (a, b) = (test_card(width, height, 0), test_card(width, height, 24)); |
| 3337 | let sources: Vec<Picture> = (0..9) |
| 3338 | .map(|t| { |
| 3339 | let mut p = a.clone(); |
| 3340 | let w = t as u32; |
| 3341 | for (v, &other) in p.y.iter_mut().zip(&b.y) { |
| 3342 | *v = ((u32::from(*v) * (8 - w) + u32::from(other) * w) / 8) as u16; |
| 3343 | } |
| 3344 | p |
| 3345 | }) |
| 3346 | .collect(); |
| 3347 | let config = EncoderConfig { |
| 3348 | width, |
| 3349 | height, |
| 3350 | base_q_idx: 120, |
| 3351 | gop: 9, |
| 3352 | colour: Colour::Bt709Limited, |
| 3353 | tile_cols_log2: 0, |
| 3354 | tile_rows_log2: 0, |
| 3355 | }; |
| 3356 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3357 | let mut stream = Vec::new(); |
| 3358 | let _ = crate::encode::take_b64_compound_hits(); |
| 3359 | for packet in encode_all(&mut enc, &sources) { |
| 3360 | stream.extend_from_slice(&packet.data); |
| 3361 | } |
| 3362 | let compound = crate::encode::take_b64_compound_hits(); |
| 3363 | assert!(compound > 0, "a crossfade clip coded no COMPOUND 64x64 root at all"); |
| 3364 | eprintln!("compound 64x64 roots on a crossfade clip: {compound}"); |
| 3365 | |
| 3366 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3367 | assert_eq!(ours.len(), sources.len(), "our decoder's frames"); |
| 3368 | if !have_ffmpeg() { |
| 3369 | eprintln!("SKIP the ffmpeg half: no ffmpeg"); |
| 3370 | return; |
| 3371 | } |
| 3372 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 3373 | assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames"); |
| 3374 | for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() { |
| 3375 | let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect(); |
| 3376 | if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) { |
| 3377 | panic!( |
| 3378 | "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3379 | at % width, |
| 3380 | at / width, |
| 3381 | got[at], |
| 3382 | theirs_i[at], |
| 3383 | ); |
| 3384 | } |
| 3385 | } |
| 3386 | } |
| 3387 | |
| 3388 | #[test] |
| 3389 | fn every_tile_layout_decodes_sample_exact_through_both_decoders() { |
| 3390 | let _knobs = crate::speed::knob_read(); |
| 3391 | let (width, height) = (640usize, 384usize); |
| 3392 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 3393 | let mut sizes = Vec::new(); |
| 3394 | for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] { |
| 3395 | let config = EncoderConfig { |
| 3396 | width, |
| 3397 | height, |
| 3398 | base_q_idx: 120, |
| 3399 | gop: 4, |
| 3400 | colour: Colour::Bt709Limited, |
| 3401 | tile_cols_log2: cols_log2, |
| 3402 | tile_rows_log2: rows_log2, |
| 3403 | }; |
| 3404 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 3405 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3406 | let mut stream = Vec::new(); |
| 3407 | for packet in encode_all(&mut enc, &sources) { |
| 3408 | stream.extend_from_slice(&packet.data); |
| 3409 | } |
| 3410 | sizes.push((layout.clone(), stream.len())); |
| 3411 | |
| 3412 | |
| 3413 | let mut parser = ec_av1_syntax::Av1Parser::new(); |
| 3414 | let mut frames = 0usize; |
| 3415 | let mut offset = 0usize; |
| 3416 | while offset < stream.len() { |
| 3417 | let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap(); |
| 3418 | let unit: usize = obus.iter().map(|o| o.total_size).sum(); |
| 3419 | for obu in &obus { |
| 3420 | if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind { |
| 3421 | assert_eq!( |
| 3422 | (parsed.tile_info.cols, parsed.tile_info.rows), |
| 3423 | (1 << cols_log2, 1 << rows_log2), |
| 3424 | "{layout}: the header's own tile grid" |
| 3425 | ); |
| 3426 | assert_eq!( |
| 3427 | tiles.len(), |
| 3428 | 1 << (cols_log2 + rows_log2), |
| 3429 | "{layout}: tile payloads located in the tile group" |
| 3430 | ); |
| 3431 | frames += 1; |
| 3432 | } |
| 3433 | } |
| 3434 | offset += unit; |
| 3435 | } |
| 3436 | assert_eq!(frames, sources.len(), "{layout}: coded frames"); |
| 3437 | |
| 3438 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3439 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 3440 | if !have_ffmpeg() { |
| 3441 | eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg"); |
| 3442 | continue; |
| 3443 | } |
| 3444 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 3445 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 3446 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 3447 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 3448 | assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size"); |
| 3449 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 3450 | panic!( |
| 3451 | "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}", |
| 3452 | at % width, |
| 3453 | at / width, |
| 3454 | got[at], |
| 3455 | b[at], |
| 3456 | ); |
| 3457 | } |
| 3458 | } |
| 3459 | } |
| 3460 | let base = sizes[0].1 as f64; |
| 3461 | for (layout, bytes) in &sizes { |
| 3462 | eprintln!( |
| 3463 | "{layout}: {bytes} bytes ({:+.2}% vs one tile)", |
| 3464 | (*bytes as f64 / base - 1.0) * 100.0 |
| 3465 | ); |
| 3466 | } |
| 3467 | } |
| 3468 | |
| 3469 | |
| 3470 | |
| 3471 | |
| 3472 | |
| 3473 | |
| 3474 | |
| 3475 | |
| 3476 | |
| 3477 | |
| 3478 | |
| 3479 | |
| 3480 | #[test] |
| 3481 | #[ignore = "sets the process-global speed preset: run it alone"] |
| 3482 | fn every_speed_preset_decodes_sample_exact_through_both_decoders() { |
| 3483 | let _knobs = crate::speed::knob_write(); |
| 3484 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3485 | let (width, height) = (640usize, 384usize); |
| 3486 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 3487 | let mut sizes: Vec<(u8, usize)> = Vec::new(); |
| 3488 | for speed in [0u8, 3, 6, 10] { |
| 3489 | let config = EncoderConfig { |
| 3490 | width, |
| 3491 | height, |
| 3492 | base_q_idx: 120, |
| 3493 | gop: 4, |
| 3494 | colour: Colour::Bt709Limited, |
| 3495 | tile_cols_log2: 1, |
| 3496 | tile_rows_log2: 0, |
| 3497 | }; |
| 3498 | let mut enc = Av1Encoder::with_speed(config, speed).unwrap(); |
| 3499 | let mut stream = Vec::new(); |
| 3500 | for packet in encode_all(&mut enc, &sources) { |
| 3501 | stream.extend_from_slice(&packet.data); |
| 3502 | } |
| 3503 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 3504 | assert_eq!(ours.len(), sources.len(), "speed {speed}: our decoder's frames"); |
| 3505 | if have_ffmpeg() { |
| 3506 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 3507 | assert_eq!(theirs.len(), sources.len(), "speed {speed}: ffmpeg's frames"); |
| 3508 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 3509 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 3510 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 3511 | panic!( |
| 3512 | "speed {speed} frame {i}: luma differs first at ({}, {}): \ |
| 3513 | ours {} vs ffmpeg {}", |
| 3514 | at % width, |
| 3515 | at / width, |
| 3516 | got[at], |
| 3517 | b[at], |
| 3518 | ); |
| 3519 | } |
| 3520 | } |
| 3521 | } else { |
| 3522 | eprintln!("SKIP the ffmpeg half of speed {speed}: no ffmpeg"); |
| 3523 | } |
| 3524 | eprintln!( |
| 3525 | "speed {speed}: {} bytes [{}]", |
| 3526 | stream.len(), |
| 3527 | crate::speed::levers(speed).join(", ") |
| 3528 | ); |
| 3529 | sizes.push((speed, stream.len())); |
| 3530 | } |
| 3531 | crate::speed::set_speed(0); |
| 3532 | for w in sizes.windows(2) { |
| 3533 | assert_ne!( |
| 3534 | w[0].1, w[1].1, |
| 3535 | "speed {} and {} coded the same bytes: the preset changed no decision", |
| 3536 | w[0].0, w[1].0 |
| 3537 | ); |
| 3538 | } |
| 3539 | } |
| 3540 | |
| 3541 | |
| 3542 | |
| 3543 | |
| 3544 | #[test] |
| 3545 | #[ignore = "1080p wall table: minutes, run it with --ignored"] |
| 3546 | fn tile_wall_table_at_1080p() { |
| 3547 | let _knobs = crate::speed::knob_write(); |
| 3548 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3549 | let (width, height) = (1920usize, 1080usize); |
| 3550 | let Some(sources) = h264_clip_frames(width, height, 8) else { |
| 3551 | eprintln!("SKIP tile_wall_table_at_1080p: no fixture"); |
| 3552 | return; |
| 3553 | }; |
| 3554 | let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)]; |
| 3555 | let threadings = [1usize, 2, 4, 8]; |
| 3556 | let mut table: Vec<(String, usize, f64, usize)> = Vec::new(); |
| 3557 | for pass in 0..2 { |
| 3558 | for &(cols_log2, rows_log2) in &layouts { |
| 3559 | for &threads in &threadings { |
| 3560 | crate::par::set_tile_threads(threads); |
| 3561 | let config = EncoderConfig { |
| 3562 | width, |
| 3563 | height, |
| 3564 | base_q_idx: 120, |
| 3565 | gop: 8, |
| 3566 | colour: Colour::Bt709Limited, |
| 3567 | tile_cols_log2: cols_log2, |
| 3568 | tile_rows_log2: rows_log2, |
| 3569 | }; |
| 3570 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3571 | let start = std::time::Instant::now(); |
| 3572 | let mut bytes = 0usize; |
| 3573 | for packet in encode_all(&mut enc, &sources) { |
| 3574 | bytes += packet.data.len(); |
| 3575 | } |
| 3576 | let wall = start.elapsed().as_secs_f64(); |
| 3577 | let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2); |
| 3578 | match table.iter_mut().find(|r| r.0 == name && r.1 == threads) { |
| 3579 | Some(row) => row.2 = row.2.min(wall), |
| 3580 | None => table.push((name, threads, wall, bytes)), |
| 3581 | } |
| 3582 | let _ = pass; |
| 3583 | } |
| 3584 | } |
| 3585 | } |
| 3586 | crate::par::set_tile_threads(1); |
| 3587 | eprintln!("| tiles | threads | wall (s, best of 2) | bytes |"); |
| 3588 | for (name, threads, wall, bytes) in &table { |
| 3589 | eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |"); |
| 3590 | } |
| 3591 | } |
| 3592 | |
| 3593 | |
| 3594 | |
| 3595 | |
| 3596 | #[test] |
| 3597 | fn tile_bytes_do_not_depend_on_the_thread_count() { |
| 3598 | let _knobs = crate::speed::knob_write(); |
| 3599 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3600 | let (width, height) = (320usize, 192usize); |
| 3601 | let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect(); |
| 3602 | let coded = |threads: usize, cols_log2: u32, rows_log2: u32| { |
| 3603 | crate::par::set_tile_threads(threads); |
| 3604 | let config = EncoderConfig { |
| 3605 | width, |
| 3606 | height, |
| 3607 | base_q_idx: 120, |
| 3608 | gop: 3, |
| 3609 | colour: Colour::Bt709Limited, |
| 3610 | tile_cols_log2: cols_log2, |
| 3611 | tile_rows_log2: rows_log2, |
| 3612 | }; |
| 3613 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3614 | let mut stream = Vec::new(); |
| 3615 | for packet in encode_all(&mut enc, &sources) { |
| 3616 | stream.extend_from_slice(&packet.data); |
| 3617 | } |
| 3618 | stream |
| 3619 | }; |
| 3620 | for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] { |
| 3621 | let one = coded(1, cols_log2, rows_log2); |
| 3622 | let four = coded(4, cols_log2, rows_log2); |
| 3623 | assert_eq!( |
| 3624 | one, |
| 3625 | four, |
| 3626 | "{}x{} tiles: {} bytes at one thread, {} at four", |
| 3627 | 1 << cols_log2, |
| 3628 | 1 << rows_log2, |
| 3629 | one.len(), |
| 3630 | four.len() |
| 3631 | ); |
| 3632 | } |
| 3633 | crate::par::set_tile_threads(1); |
| 3634 | } |
| 3635 | |
| 3636 | |
| 3637 | |
| 3638 | |
| 3639 | |
| 3640 | |
| 3641 | |
| 3642 | |
| 3643 | |
| 3644 | |
| 3645 | #[test] |
| 3646 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 3647 | fn tile_search_wall_1080p() { |
| 3648 | let _knobs = crate::speed::knob_write(); |
| 3649 | tile_search_wall(1920, 1080, 12, &[(0, 0), (1, 0), (1, 1), (2, 1)], &[1, 2, 4, 8]); |
| 3650 | } |
| 3651 | |
| 3652 | |
| 3653 | |
| 3654 | #[test] |
| 3655 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 3656 | fn tile_search_wall_4k() { |
| 3657 | let _knobs = crate::speed::knob_write(); |
| 3658 | tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]); |
| 3659 | } |
| 3660 | |
| 3661 | |
| 3662 | |
| 3663 | |
| 3664 | |
| 3665 | |
| 3666 | |
| 3667 | #[test] |
| 3668 | fn filter_stage_bytes_do_not_depend_on_the_thread_count() { |
| 3669 | let _knobs = crate::speed::knob_write(); |
| 3670 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3671 | let (width, height) = (384usize, 288usize); |
| 3672 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 3673 | let coded = |threads: usize| { |
| 3674 | crate::par::set_tile_threads(threads); |
| 3675 | let config = EncoderConfig { |
| 3676 | width, |
| 3677 | height, |
| 3678 | base_q_idx: 120, |
| 3679 | gop: 2, |
| 3680 | colour: Colour::Bt709Limited, |
| 3681 | tile_cols_log2: 0, |
| 3682 | tile_rows_log2: 0, |
| 3683 | }; |
| 3684 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3685 | let mut stream = Vec::new(); |
| 3686 | for packet in encode_all(&mut enc, &sources) { |
| 3687 | stream.extend_from_slice(&packet.data); |
| 3688 | } |
| 3689 | stream |
| 3690 | }; |
| 3691 | |
| 3692 | let one = coded(1); |
| 3693 | for threads in [2usize, 4, 8] { |
| 3694 | assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads"); |
| 3695 | } |
| 3696 | crate::par::set_tile_threads(1); |
| 3697 | } |
| 3698 | |
| 3699 | |
| 3700 | |
| 3701 | |
| 3702 | |
| 3703 | |
| 3704 | |
| 3705 | #[test] |
| 3706 | fn filter_replay_codes_the_same_stream_as_a_full_decode() { |
| 3707 | let _knobs = crate::speed::knob_read(); |
| 3708 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3709 | let run = |width: usize, height: usize, off: bool| { |
| 3710 | let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 3711 | crate::decode::set_filter_replay_disabled(off); |
| 3712 | let config = EncoderConfig { |
| 3713 | width, |
| 3714 | height, |
| 3715 | base_q_idx: 120, |
| 3716 | gop: 2, |
| 3717 | colour: Colour::Bt709Limited, |
| 3718 | tile_cols_log2: 0, |
| 3719 | tile_rows_log2: 0, |
| 3720 | }; |
| 3721 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3722 | let mut stream = Vec::new(); |
| 3723 | for packet in encode_all(&mut enc, &sources) { |
| 3724 | stream.extend_from_slice(&packet.data); |
| 3725 | } |
| 3726 | crate::decode::set_filter_replay_disabled(false); |
| 3727 | stream |
| 3728 | }; |
| 3729 | |
| 3730 | |
| 3731 | |
| 3732 | for (width, height) in [(320usize, 160usize), (320, 192)] { |
| 3733 | let replayed = run(width, height, false); |
| 3734 | let decoded = run(width, height, true); |
| 3735 | assert_eq!( |
| 3736 | replayed, |
| 3737 | decoded, |
| 3738 | "{width}x{height}: the filter replay is not the decode it stands in for \ |
| 3739 | ({} bytes replayed, {} decoded)", |
| 3740 | replayed.len(), |
| 3741 | decoded.len(), |
| 3742 | ); |
| 3743 | } |
| 3744 | } |
| 3745 | |
| 3746 | |
| 3747 | |
| 3748 | |
| 3749 | |
| 3750 | |
| 3751 | #[test] |
| 3752 | fn filter_replay_final_matches_the_capture_decode() { |
| 3753 | let _knobs = crate::speed::knob_read(); |
| 3754 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3755 | let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| { |
| 3756 | let config = EncoderConfig { |
| 3757 | width, |
| 3758 | height, |
| 3759 | base_q_idx: 120, |
| 3760 | gop: 2, |
| 3761 | colour: Colour::Bt709Limited, |
| 3762 | tile_cols_log2: tiles.0, |
| 3763 | tile_rows_log2: tiles.1, |
| 3764 | }; |
| 3765 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3766 | for packet in encode_all(&mut enc, sources) { |
| 3767 | assert!(!packet.data.is_empty()); |
| 3768 | } |
| 3769 | }; |
| 3770 | crate::decode::set_verify_final_replay(true); |
| 3771 | |
| 3772 | |
| 3773 | for (width, height) in [(320usize, 160usize), (320, 192)] { |
| 3774 | let sources: Vec<Picture> = |
| 3775 | (0..4).map(|t| test_card(width, height, t * 3)).collect(); |
| 3776 | run(&sources, width, height, (0, 0)); |
| 3777 | } |
| 3778 | |
| 3779 | |
| 3780 | if let Some(sources) = h264_clip_frames(640, 384, 3) { |
| 3781 | run(&sources, 640, 384, (0, 0)); |
| 3782 | run(&sources, 640, 384, (1, 1)); |
| 3783 | } else { |
| 3784 | eprintln!("SKIP the gate-clip arm: no fixture or no ffmpeg"); |
| 3785 | } |
| 3786 | crate::decode::set_verify_final_replay(false); |
| 3787 | } |
| 3788 | |
| 3789 | |
| 3790 | |
| 3791 | |
| 3792 | |
| 3793 | |
| 3794 | #[test] |
| 3795 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 3796 | fn filter_stage_wall_1080p() { |
| 3797 | let _knobs = crate::speed::knob_write(); |
| 3798 | filter_stage_wall(1920, 1080, 8, (2, 1), &[8]); |
| 3799 | } |
| 3800 | |
| 3801 | #[test] |
| 3802 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 3803 | fn filter_stage_wall_4k() { |
| 3804 | let _knobs = crate::speed::knob_write(); |
| 3805 | filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]); |
| 3806 | } |
| 3807 | |
| 3808 | |
| 3809 | |
| 3810 | |
| 3811 | |
| 3812 | #[test] |
| 3813 | #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"] |
| 3814 | fn filter_stage_wall_film() { |
| 3815 | let _knobs = crate::speed::knob_write(); |
| 3816 | filter_stage_wall(1920, 768, 4, (2, 1), &[8]); |
| 3817 | } |
| 3818 | |
| 3819 | fn filter_stage_wall( |
| 3820 | width: usize, |
| 3821 | height: usize, |
| 3822 | frames: usize, |
| 3823 | (cols_log2, rows_log2): (u32, u32), |
| 3824 | threads: &[usize], |
| 3825 | ) { |
| 3826 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3827 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 3828 | eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg"); |
| 3829 | return; |
| 3830 | }; |
| 3831 | crate::par::set_stage_times(true); |
| 3832 | for &t in threads { |
| 3833 | crate::par::set_tile_threads(t); |
| 3834 | let config = EncoderConfig { |
| 3835 | width, |
| 3836 | height, |
| 3837 | base_q_idx: 120, |
| 3838 | gop: frames, |
| 3839 | colour: Colour::Bt709Limited, |
| 3840 | tile_cols_log2: cols_log2, |
| 3841 | tile_rows_log2: rows_log2, |
| 3842 | }; |
| 3843 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3844 | let _ = crate::par::take_stage_ns(); |
| 3845 | let start = std::time::Instant::now(); |
| 3846 | for packet in encode_all(&mut enc, &sources) { |
| 3847 | assert!(!packet.data.is_empty()); |
| 3848 | } |
| 3849 | let wall = start.elapsed().as_secs_f64(); |
| 3850 | let ns = crate::par::take_stage_ns(); |
| 3851 | let ms = |i: usize| ns[i] as f64 / 1e6; |
| 3852 | eprintln!( |
| 3853 | "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \ |
| 3854 | {wall:.2}s wall, {:.2} fps", |
| 3855 | 1 << cols_log2, |
| 3856 | 1 << rows_log2, |
| 3857 | frames as f64 / wall, |
| 3858 | ); |
| 3859 | eprintln!("| stage | ms | ms/frame | % of wall |"); |
| 3860 | for (i, name) in crate::par::STAGES.iter().enumerate() { |
| 3861 | eprintln!( |
| 3862 | "| {name} | {:.0} | {:.1} | {:.1}% |", |
| 3863 | ms(i), |
| 3864 | ms(i) / frames as f64, |
| 3865 | 100.0 * ms(i) / (wall * 1e3), |
| 3866 | ); |
| 3867 | } |
| 3868 | |
| 3869 | |
| 3870 | |
| 3871 | let top: f64 = [ |
| 3872 | crate::par::S_TILE_SEARCH, |
| 3873 | crate::par::S_TILE_WRITE, |
| 3874 | crate::par::S_FILTER, |
| 3875 | crate::par::S_CAPTURE, |
| 3876 | crate::par::S_LR, |
| 3877 | ] |
| 3878 | .iter() |
| 3879 | .map(|&i| ms(i)) |
| 3880 | .sum(); |
| 3881 | eprintln!( |
| 3882 | "accounted {:.1}% of wall; outside the tile search {:.1}%", |
| 3883 | 100.0 * top / (wall * 1e3), |
| 3884 | 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)), |
| 3885 | ); |
| 3886 | } |
| 3887 | crate::par::set_stage_times(false); |
| 3888 | crate::par::set_tile_threads(1); |
| 3889 | } |
| 3890 | |
| 3891 | fn tile_search_wall( |
| 3892 | width: usize, |
| 3893 | height: usize, |
| 3894 | frames: usize, |
| 3895 | layouts: &[(u32, u32)], |
| 3896 | threads: &[usize], |
| 3897 | ) { |
| 3898 | let _gate_lock = crate::stream::tests::lock_gate_counters(); |
| 3899 | let Some(sources) = h264_clip_frames(width, height, frames) else { |
| 3900 | eprintln!("SKIP the tile-search wall table: no fixture or no ffmpeg"); |
| 3901 | return; |
| 3902 | }; |
| 3903 | let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) { |
| 3904 | crate::par::set_tile_threads(t); |
| 3905 | let config = EncoderConfig { |
| 3906 | width, |
| 3907 | height, |
| 3908 | base_q_idx: 120, |
| 3909 | gop: frames, |
| 3910 | colour: Colour::Bt709Limited, |
| 3911 | tile_cols_log2: cols_log2, |
| 3912 | tile_rows_log2: rows_log2, |
| 3913 | }; |
| 3914 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 3915 | let start = std::time::Instant::now(); |
| 3916 | let mut bytes = 0usize; |
| 3917 | for packet in encode_all(&mut enc, &sources) { |
| 3918 | bytes += packet.data.len(); |
| 3919 | } |
| 3920 | (start.elapsed(), bytes) |
| 3921 | }; |
| 3922 | let cells: Vec<((u32, u32), usize)> = layouts |
| 3923 | .iter() |
| 3924 | .flat_map(|&l| threads.iter().map(move |&t| (l, t))) |
| 3925 | .collect(); |
| 3926 | let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()]; |
| 3927 | for _pass in 0..2 { |
| 3928 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 3929 | let got = run(c, r, t); |
| 3930 | assert!(got.1 > 0, "{}x{} tiles at {t} threads: empty stream", 1 << c, 1 << r); |
| 3931 | if best[i].is_none_or(|(w, _)| got.0 < w) { |
| 3932 | best[i] = Some(got); |
| 3933 | } |
| 3934 | } |
| 3935 | } |
| 3936 | crate::par::set_tile_threads(1); |
| 3937 | eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes"); |
| 3938 | eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |"); |
| 3939 | let base = best[0].expect("the first cell ran").0.as_secs_f64(); |
| 3940 | for (i, &((c, r), t)) in cells.iter().enumerate() { |
| 3941 | let (wall, bytes) = best[i].expect("every cell ran"); |
| 3942 | let secs = wall.as_secs_f64(); |
| 3943 | eprintln!( |
| 3944 | "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |", |
| 3945 | 1 << c, |
| 3946 | 1 << r, |
| 3947 | 1 << (c + r), |
| 3948 | frames as f64 / secs, |
| 3949 | base / secs, |
| 3950 | ); |
| 3951 | } |
| 3952 | |
| 3953 | |
| 3954 | |
| 3955 | for &(c, r) in layouts { |
| 3956 | let one = cells |
| 3957 | .iter() |
| 3958 | .position(|&(l, t)| l == (c, r) && t == threads[0]) |
| 3959 | .map(|i| best[i].expect("cell").0.as_secs_f64()); |
| 3960 | let Some(one) = one else { continue }; |
| 3961 | for &t in &threads[1..] { |
| 3962 | let i = cells.iter().position(|&(l, tt)| l == (c, r) && tt == t).expect("cell"); |
| 3963 | let secs = best[i].expect("cell").0.as_secs_f64(); |
| 3964 | let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64; |
| 3965 | let speedup = one / secs; |
| 3966 | eprintln!( |
| 3967 | "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \ |
| 3968 | idle share {:.0}%", |
| 3969 | 1 << c, |
| 3970 | 1 << r, |
| 3971 | threads[0], |
| 3972 | 100.0 * (1.0 - speedup / workers).max(0.0), |
| 3973 | ); |
| 3974 | } |
| 3975 | } |
| 3976 | rav1e_wall_reference(width, height, frames, layouts, threads); |
| 3977 | } |
| 3978 | |
| 3979 | |
| 3980 | |
| 3981 | fn rav1e_wall_reference( |
| 3982 | width: usize, |
| 3983 | height: usize, |
| 3984 | frames: usize, |
| 3985 | layouts: &[(u32, u32)], |
| 3986 | threads: &[usize], |
| 3987 | ) { |
| 3988 | let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 3989 | .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); |
| 3990 | let listed = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output(); |
| 3991 | let has_rav1e = listed |
| 3992 | .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e")) |
| 3993 | .unwrap_or(false); |
| 3994 | if !has_rav1e || !clip.exists() { |
| 3995 | eprintln!("SKIP the rav1e reference: no librav1e or no fixture"); |
| 3996 | return; |
| 3997 | } |
| 3998 | eprintln!("| rav1e layout | threads | wall | fps | bytes |"); |
| 3999 | for &(c, r) in layouts { |
| 4000 | for &t in threads { |
| 4001 | let out = std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id())); |
| 4002 | let params = format!( |
| 4003 | "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}", |
| 4004 | 1 << c, |
| 4005 | 1 << r |
| 4006 | ); |
| 4007 | let start = std::time::Instant::now(); |
| 4008 | let status = Command::new("ffmpeg") |
| 4009 | .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()]) |
| 4010 | .args(["-frames:v", &frames.to_string()]) |
| 4011 | .args(["-vf", &format!("scale={width}:{height}")]) |
| 4012 | .args(["-c:v", "librav1e", "-rav1e-params", ¶ms]) |
| 4013 | .arg(out.to_str().unwrap()) |
| 4014 | .output() |
| 4015 | .expect("ffmpeg failed to run"); |
| 4016 | let secs = start.elapsed().as_secs_f64(); |
| 4017 | if !status.status.success() { |
| 4018 | eprintln!("| {}x{} | {t} | FAILED: {} |", 1 << c, 1 << r, String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or("")); |
| 4019 | continue; |
| 4020 | } |
| 4021 | let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0); |
| 4022 | let _ = std::fs::remove_file(&out); |
| 4023 | eprintln!( |
| 4024 | "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |", |
| 4025 | 1 << c, |
| 4026 | 1 << r, |
| 4027 | frames as f64 / secs |
| 4028 | ); |
| 4029 | } |
| 4030 | } |
| 4031 | } |
| 4032 | |
| 4033 | |
| 4034 | |
| 4035 | |
| 4036 | |
| 4037 | #[test] |
| 4038 | #[ignore = "1080p encode: minutes, run it with --ignored"] |
| 4039 | fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() { |
| 4040 | let _knobs = crate::speed::knob_read(); |
| 4041 | let (width, height) = (1920usize, 1080usize); |
| 4042 | let Some(sources) = h264_clip_frames(width, height, 3) else { |
| 4043 | eprintln!("SKIP the 1080p tile round trip: no fixture"); |
| 4044 | return; |
| 4045 | }; |
| 4046 | for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] { |
| 4047 | let config = EncoderConfig { |
| 4048 | width, |
| 4049 | height, |
| 4050 | base_q_idx: 120, |
| 4051 | gop: 3, |
| 4052 | colour: Colour::Bt709Limited, |
| 4053 | tile_cols_log2: cols_log2, |
| 4054 | tile_rows_log2: rows_log2, |
| 4055 | }; |
| 4056 | let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2); |
| 4057 | let mut enc = Av1Encoder::new(config).unwrap(); |
| 4058 | let mut stream = Vec::new(); |
| 4059 | for packet in encode_all(&mut enc, &sources) { |
| 4060 | stream.extend_from_slice(&packet.data); |
| 4061 | } |
| 4062 | let ours = crate::stream::decode_stream(&stream).expect("our decoder"); |
| 4063 | assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames"); |
| 4064 | if !have_ffmpeg() { |
| 4065 | eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg"); |
| 4066 | continue; |
| 4067 | } |
| 4068 | let theirs = ffmpeg_decode_luma(&stream, width, height); |
| 4069 | assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames"); |
| 4070 | for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() { |
| 4071 | let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect(); |
| 4072 | if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) { |
| 4073 | panic!( |
| 4074 | "1080p {layout} frame {i}: luma differs first at ({}, {})", |
| 4075 | at % width, |
| 4076 | at / width |
| 4077 | ); |
| 4078 | } |
| 4079 | } |
| 4080 | eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len()); |
| 4081 | } |
| 4082 | } |
| 4083 | |
| 4084 | |
| 4085 | |
| 4086 | |
| 4087 | #[test] |
| 4088 | fn quality_target_is_monotone_in_bytes_and_psnr() { |
| 4089 | let _knobs = crate::speed::knob_read(); |
| 4090 | if !have_ffmpeg() { |
| 4091 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg"); |
| 4092 | return; |
| 4093 | } |
| 4094 | let (width, height) = (640, 384); |
| 4095 | let Some(pictures) = h264_clip_frames(width, height, 8) else { |
| 4096 | eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture"); |
| 4097 | return; |
| 4098 | }; |
| 4099 | let mut prev_bytes = 0usize; |
| 4100 | let mut prev_psnr = 0.0f64; |
| 4101 | for quality in [20u8, 50, 80] { |
| 4102 | let config = EncoderConfig { |
| 4103 | width, |
| 4104 | height, |
| 4105 | base_q_idx: 100, |
| 4106 | gop: 8, |
| 4107 | colour: Colour::Bt709Limited, |
| 4108 | tile_cols_log2: 0, |
| 4109 | tile_rows_log2: 0, |
| 4110 | }; |
| 4111 | let mut enc = |
| 4112 | Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap(); |
| 4113 | let mut stream = Vec::new(); |
| 4114 | let mut total_bytes = 0usize; |
| 4115 | for packet in encode_all(&mut enc, &pictures) { |
| 4116 | total_bytes += packet.data.len(); |
| 4117 | stream.extend_from_slice(&packet.data); |
| 4118 | } |
| 4119 | let decoded = ffmpeg_decode_luma(&stream, width, height); |
| 4120 | assert_eq!( |
| 4121 | decoded.len(), |
| 4122 | pictures.len(), |
| 4123 | "quality {quality}: dav1d frame count" |
| 4124 | ); |
| 4125 | let mean_psnr: f64 = decoded |
| 4126 | .iter() |
| 4127 | .zip(&pictures) |
| 4128 | .map(|(d, p)| { |
| 4129 | let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect(); |
| 4130 | psnr(&d16, &p.y) |
| 4131 | }) |
| 4132 | .sum::<f64>() |
| 4133 | / decoded.len() as f64; |
| 4134 | assert!( |
| 4135 | total_bytes >= prev_bytes, |
| 4136 | "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}" |
| 4137 | ); |
| 4138 | assert!( |
| 4139 | mean_psnr >= prev_psnr - 0.01, |
| 4140 | "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB" |
| 4141 | ); |
| 4142 | prev_bytes = total_bytes; |
| 4143 | prev_psnr = mean_psnr; |
| 4144 | } |
| 4145 | } |
| 4146 | } |