U16: trim tests/gpu.rs to the 8 correctness tests (ffmpeg decode oracle, H.264/HEVC encode round trips, HEVC Main10, AV1 rate control landing); drop reeld, timing, RSS, BD, profile and seek tests
Browse files at this commit11b1d00b5ab9f9ea3405145185d8167f2db83dccParent: a84394a1 changed file +5 -1780
- crates/ec-hw/tests/gpu.rs +5 -1780
crates/ec-hw/tests/gpu.rsmodified+5 -1780
| @@ -8,29 +8,22 @@ | |||
| 8 | 8 | ||
| 9 | use std::io::Read; | 9 | use std::io::Read; |
| 10 | use std::path::{Path, PathBuf}; | 10 | use std::path::{Path, PathBuf}; |
| 11 | -use std::process::{Command, Stdio}; | 11 | +use std::process::Stdio; |
| 12 | use std::rc::Rc; | 12 | use std::rc::Rc; |
| 13 | -use std::time::Instant; | ||
| 14 | 13 | ||
| 15 | use ec_hw::{ | 14 | use ec_hw::{ |
| 16 | - Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, H264Profile, I420, | 15 | + Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, |
| 17 | I420_16, RateControlMode, | 16 | I420_16, RateControlMode, |
| 18 | }; | 17 | }; |
| 19 | use ec_va::Display; | 18 | use ec_va::Display; |
| 20 | 19 | ||
| 20 | +mod common; | ||
| 21 | +use common::display; | ||
| 22 | + | ||
| 21 | /// Frames compared per fixture: enough to cover several GOPs and any | 23 | /// Frames compared per fixture: enough to cover several GOPs and any |
| 22 | /// reordering, few enough to keep the suite under a minute. | 24 | /// reordering, few enough to keep the suite under a minute. |
| 23 | const FRAMES: usize = 24; | 25 | const FRAMES: usize = 24; |
| 24 | 26 | ||
| 25 | -fn display() -> Option<Rc<Display>> { | ||
| 26 | - match ec_va::open() { | ||
| 27 | - Ok(display) => Some(display), | ||
| 28 | - Err(e) => { | ||
| 29 | - eprintln!("skipped: no VA display ({e})"); | ||
| 30 | - None | ||
| 31 | - } | ||
| 32 | - } | ||
| 33 | -} | ||
| 34 | 27 | ||
| 35 | /// The software reference: ffmpeg decoding the same file to raw planes. | 28 | /// The software reference: ffmpeg decoding the same file to raw planes. |
| 36 | struct Reference { | 29 | struct Reference { |
| @@ -378,25 +371,6 @@ fn ten_bit(pattern: &str, codec: &str) -> Vec<PathBuf> { | |||
| 378 | .collect() | 371 | .collect() |
| 379 | } | 372 | } |
| 380 | 373 | ||
| 381 | -/// The selection must not depend on where the repository is checked out. | ||
| 382 | -#[test] | ||
| 383 | -fn fixture_selection_ignores_the_checkout_path() { | ||
| 384 | - for p in eight_bit("ivf", "av1") { | ||
| 385 | - let name = name_of(&p); | ||
| 386 | - assert!( | ||
| 387 | - name.starts_with("av1") && !name.contains("10bit"), | ||
| 388 | - "{name} is not an 8-bit AV1 fixture" | ||
| 389 | - ); | ||
| 390 | - } | ||
| 391 | - for p in ten_bit("ivf", "vp9") { | ||
| 392 | - let name = name_of(&p); | ||
| 393 | - assert!( | ||
| 394 | - name.starts_with("vp9") && name.contains("10bit"), | ||
| 395 | - "{name} is not a 10-bit VP9 fixture" | ||
| 396 | - ); | ||
| 397 | - } | ||
| 398 | -} | ||
| 399 | - | ||
| 400 | #[test] | 374 | #[test] |
| 401 | fn h264_matches_ffmpeg() { | 375 | fn h264_matches_ffmpeg() { |
| 402 | compare_against_ffmpeg(&ec_testkit::fixtures("bitstreams", "264"), Codec::H264, false); | 376 | compare_against_ffmpeg(&ec_testkit::fixtures("bitstreams", "264"), Codec::H264, false); |
| @@ -430,68 +404,11 @@ fn hevc_10bit_decodes_to_p010() { | |||
| 430 | compare_against_ffmpeg(&files, Codec::H265, true); | 404 | compare_against_ffmpeg(&files, Codec::H265, true); |
| 431 | } | 405 | } |
| 432 | 406 | ||
| 433 | -#[test] | ||
| 434 | -fn vp9_matches_ffmpeg() { | ||
| 435 | - compare_against_ffmpeg(&eight_bit("ivf", "vp9"), Codec::Vp9, false); | ||
| 436 | -} | ||
| 437 | - | ||
| 438 | -#[test] | ||
| 439 | -fn vp9_10bit_matches_ffmpeg() { | ||
| 440 | - compare_against_ffmpeg(&ten_bit("ivf", "vp9"), Codec::Vp9, true); | ||
| 441 | -} | ||
| 442 | - | ||
| 443 | #[test] | 407 | #[test] |
| 444 | fn av1_matches_ffmpeg() { | 408 | fn av1_matches_ffmpeg() { |
| 445 | compare_against_ffmpeg(&eight_bit("ivf", "av1"), Codec::Av1, false); | 409 | compare_against_ffmpeg(&eight_bit("ivf", "av1"), Codec::Av1, false); |
| 446 | } | 410 | } |
| 447 | 411 | ||
| 448 | -#[test] | ||
| 449 | -fn av1_10bit_matches_ffmpeg() { | ||
| 450 | - compare_against_ffmpeg(&ten_bit("ivf", "av1"), Codec::Av1, true); | ||
| 451 | -} | ||
| 452 | - | ||
| 453 | -/// Every "not supported" this crate says has to be a fact about the driver, not | ||
| 454 | -/// a string. This GPU decodes VP9 profiles 0 and 2 and AV1 profiles 0 and 2 — | ||
| 455 | -/// so the 4:4:4 fixtures must come back as a typed refusal naming the profile, | ||
| 456 | -/// and the capability report must agree that the profile is absent. | ||
| 457 | -#[test] | ||
| 458 | -fn unsupported_profiles_are_refused_with_a_reason() { | ||
| 459 | - let Some(display) = display() else { return }; | ||
| 460 | - let caps = ec_va::CapReport::probe(&display).expect("caps probe"); | ||
| 461 | - for (file, codec, absent) in [ | ||
| 462 | - ( | ||
| 463 | - "vp9-profile1-444.ivf", | ||
| 464 | - Codec::Vp9, | ||
| 465 | - ec_va::caps::Profile::VP9Profile1, | ||
| 466 | - ), | ||
| 467 | - ( | ||
| 468 | - "av1-profile1-444.ivf", | ||
| 469 | - Codec::Av1, | ||
| 470 | - ec_va::caps::Profile::AV1Profile1, | ||
| 471 | - ), | ||
| 472 | - ] { | ||
| 473 | - let path = ec_testkit::fixture(&format!("bitstreams/{file}")); | ||
| 474 | - assert!( | ||
| 475 | - !caps.supports(absent, ec_va::caps::Entrypoint::VLD), | ||
| 476 | - "{absent:?} is in fact supported — the refusal below would be a bug" | ||
| 477 | - ); | ||
| 478 | - let data = std::fs::read(&path).expect("fixture is readable"); | ||
| 479 | - let mut decoder = Decoder::new(&display, codec).expect("decoder opens"); | ||
| 480 | - let err = decode_stream(&mut decoder, codec, &data, 1, |_| {}) | ||
| 481 | - .expect_err("a 4:4:4 stream must be refused"); | ||
| 482 | - let message = err.to_string(); | ||
| 483 | - assert!( | ||
| 484 | - matches!(err, ec_hw::Error::Unsupported { .. }), | ||
| 485 | - "{file}: expected a typed refusal, got {message}" | ||
| 486 | - ); | ||
| 487 | - println!("{file}: {message}"); | ||
| 488 | - } | ||
| 489 | -} | ||
| 490 | - | ||
| 491 | -// --------------------------------------------------------------------------- | ||
| 492 | -// Encoding | ||
| 493 | -// --------------------------------------------------------------------------- | ||
| 494 | - | ||
| 495 | /// A moving synthetic frame: a gradient with a box that travels, so motion | 412 | /// A moving synthetic frame: a gradient with a box that travels, so motion |
| 496 | /// compensation has something to find and a static-image encoder cannot cheat. | 413 | /// compensation has something to find and a static-image encoder cannot cheat. |
| 497 | fn source_frame(width: u32, height: u32, t: u32) -> I420 { | 414 | fn source_frame(width: u32, height: u32, t: u32) -> I420 { |
| @@ -629,295 +546,11 @@ fn h264_encode_round_trips_through_ffmpeg() { | |||
| 629 | round_trip(EncCodec::H264, 640, 480, 30.0); | 546 | round_trip(EncCodec::H264, 640, 480, 30.0); |
| 630 | } | 547 | } |
| 631 | 548 | ||
| 632 | -/// Each selectable H.264 profile: the driver encodes it, ffprobe reports the | ||
| 633 | -/// profile the SPS signals, and ffmpeg decodes the stream with no error output | ||
| 634 | -/// and the picture matches the source. | ||
| 635 | -fn h264_profile_round_trip(profile: H264Profile, ffprobe_name: &str) { | ||
| 636 | - let Some(display) = display() else { return }; | ||
| 637 | - let (width, height, frames) = (640u32, 480u32, 12u32); | ||
| 638 | - let mut config = EncoderConfig::new(EncCodec::H264, width, height).h264_profile(profile); | ||
| 639 | - config.gop_size = 30; | ||
| 640 | - config.rate_control = RateControlMode::ConstantQp { qp: 26 }; | ||
| 641 | - let mut encoder = Encoder::new(&display, config).expect("encoder"); | ||
| 642 | - let mut stream = Vec::new(); | ||
| 643 | - for t in 0..frames { | ||
| 644 | - let coded = encoder | ||
| 645 | - .encode( | ||
| 646 | - &source_frame(width, height, t), | ||
| 647 | - FrameMetadata { | ||
| 648 | - timestamp: i64::from(t), | ||
| 649 | - force_keyframe: false, | ||
| 650 | - }, | ||
| 651 | - ) | ||
| 652 | - .expect("encode"); | ||
| 653 | - stream.extend_from_slice(&coded.data); | ||
| 654 | - } | ||
| 655 | - | ||
| 656 | - let dir = std::env::temp_dir().join(format!("ec-hw-h264-{profile:?}")); | ||
| 657 | - std::fs::create_dir_all(&dir).expect("temp dir"); | ||
| 658 | - let path = dir.join("out.264"); | ||
| 659 | - std::fs::write(&path, &stream).expect("write bitstream"); | ||
| 660 | - | ||
| 661 | - let probe = ec_testkit::ffprobe() | ||
| 662 | - .args([ | ||
| 663 | - "-v", | ||
| 664 | - "error", | ||
| 665 | - "-select_streams", | ||
| 666 | - "v:0", | ||
| 667 | - "-show_entries", | ||
| 668 | - "stream=profile", | ||
| 669 | - "-of", | ||
| 670 | - "csv=p=0", | ||
| 671 | - ]) | ||
| 672 | - .arg(&path) | ||
| 673 | - .output() | ||
| 674 | - .expect("ffprobe runs"); | ||
| 675 | - let got = String::from_utf8_lossy(&probe.stdout).trim().to_string(); | ||
| 676 | - assert_eq!( | ||
| 677 | - got, ffprobe_name, | ||
| 678 | - "{profile:?}: ffprobe reads the SPS profile" | ||
| 679 | - ); | ||
| 680 | - | ||
| 681 | - // Strict decode: any warning or error on stderr fails the test. | ||
| 682 | - let decode = ec_testkit::ffmpeg() | ||
| 683 | - .args(["-nostdin", "-v", "warning", "-i"]) | ||
| 684 | - .arg(&path) | ||
| 685 | - .args(["-f", "null", "-"]) | ||
| 686 | - .output() | ||
| 687 | - .expect("ffmpeg runs"); | ||
| 688 | - assert!( | ||
| 689 | - decode.status.success() && decode.stderr.is_empty(), | ||
| 690 | - "{profile:?}: ffmpeg reports {}", | ||
| 691 | - String::from_utf8_lossy(&decode.stderr) | ||
| 692 | - ); | ||
| 693 | - | ||
| 694 | - let mut reference = Reference::open(&path, width, height, false).expect("ffmpeg runs"); | ||
| 695 | - let mut worst = f64::INFINITY; | ||
| 696 | - for t in 0..frames { | ||
| 697 | - let got = reference.next(width, height).expect("decoded picture"); | ||
| 698 | - worst = worst.min(psnr( | ||
| 699 | - &got, | ||
| 700 | - &Planes::from_8bit(&source_frame(width, height, t)), | ||
| 701 | - )); | ||
| 702 | - } | ||
| 703 | - println!("{profile:?}: {} bytes, worst {worst:.1} dB", stream.len()); | ||
| 704 | - assert!(worst >= 30.0, "{profile:?}: worst frame {worst:.1} dB"); | ||
| 705 | -} | ||
| 706 | - | ||
| 707 | -#[test] | ||
| 708 | -fn h264_constrained_baseline_encodes_and_decodes() { | ||
| 709 | - h264_profile_round_trip(H264Profile::ConstrainedBaseline, "Constrained Baseline"); | ||
| 710 | -} | ||
| 711 | - | ||
| 712 | -#[test] | ||
| 713 | -fn h264_main_profile_has_no_high_syntax_and_decodes() { | ||
| 714 | - h264_profile_round_trip(H264Profile::Main, "Main"); | ||
| 715 | -} | ||
| 716 | - | ||
| 717 | -#[test] | ||
| 718 | -fn h264_high_profile_still_decodes() { | ||
| 719 | - h264_profile_round_trip(H264Profile::High, "High"); | ||
| 720 | -} | ||
| 721 | - | ||
| 722 | #[test] | 549 | #[test] |
| 723 | fn hevc_encode_round_trips_through_ffmpeg() { | 550 | fn hevc_encode_round_trips_through_ffmpeg() { |
| 724 | round_trip(EncCodec::H265, 640, 480, 30.0); | 551 | round_trip(EncCodec::H265, 640, 480, 30.0); |
| 725 | } | 552 | } |
| 726 | 553 | ||
| 727 | -/// 1916x1080 is the shape that broke the incumbent HEVC encoder: the coded size | ||
| 728 | -/// is 1920x1088, and only the conformance window brings it back. | ||
| 729 | -#[test] | ||
| 730 | -fn hevc_encode_honours_the_conformance_window() { | ||
| 731 | - round_trip(EncCodec::H265, 1916, 1080, 30.0); | ||
| 732 | -} | ||
| 733 | - | ||
| 734 | -/// What this crate encodes, its own hardware decoder must decode. | ||
| 735 | -#[test] | ||
| 736 | -fn our_encoder_and_our_decoder_agree() { | ||
| 737 | - let Some(display) = display() else { return }; | ||
| 738 | - for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { | ||
| 739 | - let stream = encode_stream(&display, enc, 640, 480, 12).expect("encode"); | ||
| 740 | - let mut decoder = Decoder::new(&display, dec).expect("decoder opens"); | ||
| 741 | - let mut worst = f64::INFINITY; | ||
| 742 | - let mut count = 0u32; | ||
| 743 | - decode_stream(&mut decoder, dec, &stream, 12, |frame| { | ||
| 744 | - let got = Planes::from_8bit(&frame.to_i420().expect("readback")); | ||
| 745 | - let want = Planes::from_8bit(&source_frame(640, 480, count)); | ||
| 746 | - worst = worst.min(psnr(&got, &want)); | ||
| 747 | - count += 1; | ||
| 748 | - }) | ||
| 749 | - .expect("decode"); | ||
| 750 | - assert_eq!(count, 12, "{enc:?}: decoded {count} of 12 frames"); | ||
| 751 | - println!("{enc:?} -> our decoder: {count} frames, worst {worst:.1} dB vs source"); | ||
| 752 | - assert!(worst >= 30.0, "{enc:?}: worst {worst:.1} dB"); | ||
| 753 | - } | ||
| 754 | -} | ||
| 755 | - | ||
| 756 | -/// A decoded surface goes straight into an encoder with no `to_i420` | ||
| 757 | -/// read-back, and what comes out is not measurably different from the | ||
| 758 | -/// CPU-path baseline (decode -> `to_i420` -> `encode`) of the same frames. | ||
| 759 | -/// | ||
| 760 | -/// 1920x1080 is the size on purpose: H.264's 16-block and HEVC's 32-block | ||
| 761 | -/// rounding both land on the same 1920x1088 coded size for it, so the | ||
| 762 | -/// decoder's surfaces satisfy `encode_frame`'s coded-size check against | ||
| 763 | -/// either target codec without a second fixture. | ||
| 764 | -/// `EncoderConfig::colour` reaches the VUI of both codecs' packed SPS: an | ||
| 765 | -/// export with a colour description survives ffprobe reading it back, and | ||
| 766 | -/// leaving it unset keeps today's behaviour (no `video_signal_type`, | ||
| 767 | -/// deterministically — two encodes of the same picture with no colour set | ||
| 768 | -/// come back byte for byte identical). | ||
| 769 | -#[test] | ||
| 770 | -fn colour_description_reaches_the_vui() { | ||
| 771 | - let Some(display) = display() else { return }; | ||
| 772 | - let (width, height) = (640u32, 480u32); | ||
| 773 | - let dir = std::env::temp_dir().join("ec-hw-colour-vui"); | ||
| 774 | - std::fs::create_dir_all(&dir).expect("temp dir"); | ||
| 775 | - | ||
| 776 | - let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec<u8>) { | ||
| 777 | - let mut cfg = EncoderConfig::new(EncCodec::H265, width, height); | ||
| 778 | - cfg.rate_control = RateControlMode::ConstantQp { qp: 26 }; | ||
| 779 | - if let Some((primaries, transfer, matrix, full_range)) = colour { | ||
| 780 | - cfg = cfg.colour(primaries, transfer, matrix, full_range); | ||
| 781 | - } | ||
| 782 | - let mut enc = Encoder::new(&display, cfg).expect("encoder opens"); | ||
| 783 | - let coded = enc | ||
| 784 | - .encode( | ||
| 785 | - &source_frame(width, height, 0), | ||
| 786 | - FrameMetadata { | ||
| 787 | - timestamp: 0, | ||
| 788 | - force_keyframe: true, | ||
| 789 | - }, | ||
| 790 | - ) | ||
| 791 | - .expect("encode"); | ||
| 792 | - let path = dir.join(name); | ||
| 793 | - std::fs::write(&path, &coded.data).expect("write bitstream"); | ||
| 794 | - (path, coded.data) | ||
| 795 | - }; | ||
| 796 | - let probe = |path: &Path| -> String { | ||
| 797 | - let out = ec_testkit::ffprobe() | ||
| 798 | - .args([ | ||
| 799 | - "-v", | ||
| 800 | - "error", | ||
| 801 | - "-select_streams", | ||
| 802 | - "v:0", | ||
| 803 | - "-show_entries", | ||
| 804 | - "stream=color_primaries,color_transfer,color_space", | ||
| 805 | - "-of", | ||
| 806 | - "csv=p=0", | ||
| 807 | - ]) | ||
| 808 | - .arg(path) | ||
| 809 | - .output() | ||
| 810 | - .expect("ffprobe runs"); | ||
| 811 | - String::from_utf8_lossy(&out.stdout).trim().to_string() | ||
| 812 | - }; | ||
| 813 | - | ||
| 814 | - // Pinned default case: no colour set, twice, must match exactly. | ||
| 815 | - let (default_path, default_bytes) = encode_one(None, "default-a.265"); | ||
| 816 | - let (_, default_bytes2) = encode_one(None, "default-b.265"); | ||
| 817 | - assert_eq!( | ||
| 818 | - default_bytes, default_bytes2, | ||
| 819 | - "no colour set: two encodes of the same picture must be byte-identical" | ||
| 820 | - ); | ||
| 821 | - let default_probe = probe(&default_path); | ||
| 822 | - println!("no colour set: ffprobe sees `{default_probe}`"); | ||
| 823 | - assert!( | ||
| 824 | - !default_probe.contains("bt2020"), | ||
| 825 | - "no colour set should not read back as BT.2020: `{default_probe}`" | ||
| 826 | - ); | ||
| 827 | - | ||
| 828 | - // BT.2020 / PQ / BT.2020 non-constant luminance (H.273 9/16/9). | ||
| 829 | - let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265"); | ||
| 830 | - // ffprobe's csv reorders these as color_space,color_transfer,color_primaries | ||
| 831 | - // regardless of the -show_entries order given above. | ||
| 832 | - let got = probe(&bt2020_path); | ||
| 833 | - assert_eq!( | ||
| 834 | - got, "bt2020nc,smpte2084,bt2020", | ||
| 835 | - "ffprobe on the BT.2020 stream" | ||
| 836 | - ); | ||
| 837 | -} | ||
| 838 | - | ||
| 839 | -/// AV1 hardware encode, proved by two independent decoders. | ||
| 840 | -/// | ||
| 841 | -/// The reconstruction inside the GPU is not observable from here, so what is | ||
| 842 | -/// asserted is that the coded stream means the same thing to two decoders that | ||
| 843 | -/// share no code: ffmpeg's libdav1d and this family's own `ec-av1`. Every | ||
| 844 | -/// shown frame is compared sample for sample — a header field that disagrees | ||
| 845 | -/// with what the hardware coded shows up as a mismatch in one of them long | ||
| 846 | -/// before it shows up as a quality number. | ||
| 847 | -/// | ||
| 848 | -/// The path was refused in-tree until 2026-09-07: a probe on 2026-08-14 took | ||
| 849 | -/// the GPU down ("the CS has cancelled because the context is lost"). That | ||
| 850 | -/// refusal is retired by measurement, not by opinion — ffmpeg's own | ||
| 851 | -/// `av1_vaapi` encodes on this driver (mesa 26.1.8, gfx1200), and the | ||
| 852 | -/// parameters below are the recipe it uses. | ||
| 853 | -#[test] | ||
| 854 | -fn av1_encode_agrees_between_two_decoders() { | ||
| 855 | - let Some(display) = display() else { return }; | ||
| 856 | - let dir = std::env::temp_dir().join("ec-hw-av1-encode"); | ||
| 857 | - let _ = std::fs::create_dir_all(&dir); | ||
| 858 | - for (width, height, frames) in [(640u32, 384u32, 10u32), (1920, 1080, 10)] { | ||
| 859 | - let data = match encode_stream(&display, EncCodec::Av1, width, height, frames) { | ||
| 860 | - Ok(data) => data, | ||
| 861 | - Err(e) => { | ||
| 862 | - eprintln!("skipped: AV1 encode unavailable ({e})"); | ||
| 863 | - return; | ||
| 864 | - } | ||
| 865 | - }; | ||
| 866 | - let path = dir.join(format!("hw-{width}x{height}.obu")); | ||
| 867 | - std::fs::write(&path, &data).expect("write the coded stream"); | ||
| 868 | - | ||
| 869 | - // Decoder one: this family's software AV1 decoder, on the raw OBUs. | ||
| 870 | - let ours = ec_av1::stream::decode_stream(&data) | ||
| 871 | - .unwrap_or_else(|e| panic!("ec-av1 decodes the {width}x{height} hardware stream: {e}")); | ||
| 872 | - assert_eq!( | ||
| 873 | - ours.len(), | ||
| 874 | - frames as usize, | ||
| 875 | - "{width}x{height}: ec-av1 decoded {} of {frames} shown frames", | ||
| 876 | - ours.len() | ||
| 877 | - ); | ||
| 878 | - | ||
| 879 | - // Decoder two: ffmpeg (libdav1d) on the same bytes. | ||
| 880 | - let mut reference = | ||
| 881 | - Reference::open(&path, width, height, false).expect("ffmpeg opens the stream"); | ||
| 882 | - let mut worst = f64::INFINITY; | ||
| 883 | - for (i, picture) in ours.iter().enumerate() { | ||
| 884 | - let theirs = reference | ||
| 885 | - .next(width, height) | ||
| 886 | - .unwrap_or_else(|| panic!("{width}x{height}: ffmpeg has no frame {i}")); | ||
| 887 | - let mine = Planes { | ||
| 888 | - y: picture.y.clone(), | ||
| 889 | - u: picture.u.clone(), | ||
| 890 | - v: picture.v.clone(), | ||
| 891 | - peak: 255.0, | ||
| 892 | - }; | ||
| 893 | - let db = psnr(&mine, &theirs); | ||
| 894 | - assert!( | ||
| 895 | - db.is_infinite(), | ||
| 896 | - "{width}x{height} frame {i}: the two decoders disagree ({db:.2} dB)" | ||
| 897 | - ); | ||
| 898 | - // Agreement alone would also be satisfied by ten grey frames: the | ||
| 899 | - // coded picture has to be the picture that was submitted. | ||
| 900 | - let source = Planes::from_8bit(&source_frame(width, height, i as u32)); | ||
| 901 | - let fidelity = psnr(&mine, &source); | ||
| 902 | - assert!( | ||
| 903 | - fidelity > 30.0, | ||
| 904 | - "{width}x{height} frame {i}: coded {fidelity:.2} dB from the source" | ||
| 905 | - ); | ||
| 906 | - worst = worst.min(fidelity); | ||
| 907 | - } | ||
| 908 | - println!( | ||
| 909 | - "AV1 encode {width}x{height}: {frames} frames, {} bytes, ec-av1 and libdav1d agree \ | ||
| 910 | - sample for sample, worst frame {worst:.2} dB from the source", | ||
| 911 | - data.len() | ||
| 912 | - ); | ||
| 913 | - } | ||
| 914 | -} | ||
| 915 | - | ||
| 916 | -// --------------------------------------------------------------------------- | ||
| 917 | -// 10-bit hardware AV1: his whole AV1 library is yuv420p10le, so an 8-bit-only | ||
| 918 | -// encoder does not serve his files. | ||
| 919 | -// --------------------------------------------------------------------------- | ||
| 920 | - | ||
| 921 | /// stream is neither flat nor 8-bit content dressed up as 10. | 554 | /// stream is neither flat nor 8-bit content dressed up as 10. |
| 922 | fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { | 555 | fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { |
| 923 | let (w, h) = (width as usize, height as usize); | 556 | let (w, h) = (width as usize, height as usize); |
| @@ -1087,107 +720,6 @@ fn hevc_main10_encode_round_trips() { | |||
| 1087 | ); | 720 | ); |
| 1088 | } | 721 | } |
| 1089 | 722 | ||
| 1090 | -/// 10-bit AV1 hardware encode, proved by two decoders and by two readings of | ||
| 1091 | -/// the stream's bit depth. | ||
| 1092 | -/// | ||
| 1093 | -/// The bit depth is not taken on trust: ffprobe (libdav1d) must call the | ||
| 1094 | -/// stream `yuv420p10le`, which is it reading the `high_bitdepth` bit this | ||
| 1095 | -/// crate packs into the sequence header, and `ec-av1`'s own decode must | ||
| 1096 | -/// produce samples above 255 — an 8-bit stream dressed as 10 fails both. | ||
| 1097 | -#[test] | ||
| 1098 | -fn av1_10bit_encode_agrees_between_two_decoders() { | ||
| 1099 | - let Some(display) = display() else { return }; | ||
| 1100 | - let dir = std::env::temp_dir().join("ec-hw-av1-10bit"); | ||
| 1101 | - let _ = std::fs::create_dir_all(&dir); | ||
| 1102 | - let frames = 10u32; | ||
| 1103 | - let (label, _, planes) = ten_bit_source(&dir, frames); | ||
| 1104 | - let (width, height) = (planes[0].width, planes[0].height); | ||
| 1105 | - let data = match encode_stream_16( | ||
| 1106 | - &display, | ||
| 1107 | - EncCodec::Av1, | ||
| 1108 | - &planes, | ||
| 1109 | - 90, | ||
| 1110 | - RateControlMode::ConstantQp { qp: 90 }, | ||
| 1111 | - ) { | ||
| 1112 | - Ok(data) => data, | ||
| 1113 | - Err(e) => { | ||
| 1114 | - eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); | ||
| 1115 | - return; | ||
| 1116 | - } | ||
| 1117 | - }; | ||
| 1118 | - let path = dir.join("hw-10bit.obu"); | ||
| 1119 | - std::fs::write(&path, &data).expect("write the coded stream"); | ||
| 1120 | - | ||
| 1121 | - assert_eq!( | ||
| 1122 | - ffprobe_pix_fmt(&path, "obu").as_deref(), | ||
| 1123 | - Some("yuv420p10le"), | ||
| 1124 | - "the coded stream's sequence header does not say 10-bit" | ||
| 1125 | - ); | ||
| 1126 | - | ||
| 1127 | - let ten_bit_h264 = EncoderConfig::new(EncCodec::H264, width, height).ten_bit(); | ||
| 1128 | - assert!(Encoder::new(&display, ten_bit_h264).is_err()); | ||
| 1129 | - let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); | ||
| 1130 | - config.rate_control = RateControlMode::ConstantQp { qp: 90 }; | ||
| 1131 | - let mut ten = Encoder::new(&display, config).expect("a 10-bit AV1 encoder"); | ||
| 1132 | - assert!( | ||
| 1133 | - ten.encode(&source_frame(width, height, 0), FrameMetadata::default()) | ||
| 1134 | - .is_err(), | ||
| 1135 | - "8-bit pixels went into a 10-bit encoder" | ||
| 1136 | - ); | ||
| 1137 | - | ||
| 1138 | - let ours = ec_av1::stream::decode_stream(&data) | ||
| 1139 | - .unwrap_or_else(|e| panic!("ec-av1 decodes the 10-bit hardware stream: {e}")); | ||
| 1140 | - assert_eq!( | ||
| 1141 | - ours.len(), | ||
| 1142 | - planes.len(), | ||
| 1143 | - "ec-av1 decoded {} of {frames} frames", | ||
| 1144 | - ours.len() | ||
| 1145 | - ); | ||
| 1146 | - let peak = ours | ||
| 1147 | - .iter() | ||
| 1148 | - .flat_map(|p| p.y.iter()) | ||
| 1149 | - .copied() | ||
| 1150 | - .max() | ||
| 1151 | - .unwrap_or(0); | ||
| 1152 | - assert!( | ||
| 1153 | - peak > 255, | ||
| 1154 | - "every decoded luma sample fits in 8 bits (peak {peak})" | ||
| 1155 | - ); | ||
| 1156 | - | ||
| 1157 | - let mut reference = | ||
| 1158 | - Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); | ||
| 1159 | - let mut worst = f64::INFINITY; | ||
| 1160 | - for (i, picture) in ours.iter().enumerate() { | ||
| 1161 | - let theirs = reference | ||
| 1162 | - .next(width, height) | ||
| 1163 | - .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); | ||
| 1164 | - let mine = Planes { | ||
| 1165 | - y: picture.y.clone(), | ||
| 1166 | - u: picture.u.clone(), | ||
| 1167 | - v: picture.v.clone(), | ||
| 1168 | - peak: 1023.0, | ||
| 1169 | - }; | ||
| 1170 | - let db = psnr(&mine, &theirs); | ||
| 1171 | - assert!( | ||
| 1172 | - db.is_infinite(), | ||
| 1173 | - "frame {i}: the two decoders disagree ({db:.2} dB)" | ||
| 1174 | - ); | ||
| 1175 | - let source = Planes::from_16bit(&planes[i]); | ||
| 1176 | - let fidelity = psnr(&mine, &source); | ||
| 1177 | - assert!( | ||
| 1178 | - fidelity > 30.0, | ||
| 1179 | - "frame {i}: coded {fidelity:.2} dB from the 10-bit source" | ||
| 1180 | - ); | ||
| 1181 | - worst = worst.min(fidelity); | ||
| 1182 | - } | ||
| 1183 | - println!( | ||
| 1184 | - "AV1 10-bit encode {width}x{height} ({label}): {frames} frames, {} bytes, pix_fmt \ | ||
| 1185 | - yuv420p10le, CQP 90, decoded peak luma {peak}, ec-av1 and libdav1d agree sample for \ | ||
| 1186 | - sample, worst frame {worst:.2} dB from the source (10-bit domain)", | ||
| 1187 | - data.len() | ||
| 1188 | - ); | ||
| 1189 | -} | ||
| 1190 | - | ||
| 1191 | /// Rate control: does an asked-for bitrate come back? | 723 | /// Rate control: does an asked-for bitrate come back? |
| 1192 | /// | 724 | /// |
| 1193 | /// CQP was the only mode the AV1 path had ever measured, because the config | 725 | /// CQP was the only mode the AV1 path had ever measured, because the config |
| @@ -1328,194 +860,7 @@ fn ffmpeg_psnr_at(coded: &Path, source: &Path, fps: u32) -> Option<f64> { | |||
| 1328 | .filter(|v| v.is_finite()) | 860 | .filter(|v| v.is_finite()) |
| 1329 | } | 861 | } |
| 1330 | 862 | ||
| 1331 | -/// What the GPU's AV1 costs against software, on his own content. | ||
| 1332 | -/// | ||
| 1333 | -/// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen | ||
| 1334 | -/// capture, PSNR from ffmpeg, BD-rate over the overlapping quality range | ||
| 1335 | -/// against librav1e speed 6 and libaom cpu-used 6. Nothing is asserted about | ||
| 1336 | -/// the number — a fixed-function encoder is not a search — but it is measured | ||
| 1337 | -/// and printed rather than assumed, and the ladder itself is asserted to be | ||
| 1338 | -/// monotone, which is the part a broken parameter set would break. | ||
| 1339 | -#[test] | ||
| 1340 | -fn av1_encode_bd_row_vs_software() { | ||
| 1341 | - let Some(display) = display() else { return }; | ||
| 1342 | - // A ladder compared with itself saves nothing: the check on the metric. | ||
| 1343 | - let same = [(100.0, 30.0), (200.0, 35.0), (400.0, 40.0)]; | ||
| 1344 | - assert!( | ||
| 1345 | - bd_rate(&same, &same).abs() < 1e-9, | ||
| 1346 | - "bd_rate is not self-zero" | ||
| 1347 | - ); | ||
| 1348 | - | ||
| 1349 | - let dir = std::env::temp_dir().join("ec-hw-av1-bd"); | ||
| 1350 | - let _ = std::fs::create_dir_all(&dir); | ||
| 1351 | - for (label, source) in real_clips() { | ||
| 1352 | - let y4m = dir.join(format!("{label}.y4m")); | ||
| 1353 | - let (width, height, frames) = (1920u32, 1080u32, 12u32); | ||
| 1354 | - assert!( | ||
| 1355 | - extract_y4m(&source, &y4m, width, height, frames), | ||
| 1356 | - "{label}: extraction failed" | ||
| 1357 | - ); | ||
| 1358 | - let planes = raw_frames(&y4m, width, height, frames).expect("frames of the trailer"); | ||
| 1359 | - | ||
| 1360 | - let mut ours = Vec::new(); | ||
| 1361 | - // Descending quantiser: every ladder here is ordered by rising rate. | ||
| 1362 | - for qp in [180u32, 140, 100, 60] { | ||
| 1363 | - let mut config = EncoderConfig::new(EncCodec::Av1, width, height); | ||
| 1364 | - config.framerate = (24, 1); | ||
| 1365 | - config.gop_size = 60; | ||
| 1366 | - config.rate_control = RateControlMode::ConstantQp { qp }; | ||
| 1367 | - let mut encoder = match Encoder::new(&display, config) { | ||
| 1368 | - Ok(encoder) => encoder, | ||
| 1369 | - Err(e) => { | ||
| 1370 | - eprintln!("skipped: AV1 encode unavailable ({e})"); | ||
| 1371 | - return; | ||
| 1372 | - } | ||
| 1373 | - }; | ||
| 1374 | - let mut bytes = Vec::new(); | ||
| 1375 | - for (i, frame) in planes.iter().enumerate() { | ||
| 1376 | - let coded = encoder | ||
| 1377 | - .encode( | ||
| 1378 | - frame, | ||
| 1379 | - FrameMetadata { | ||
| 1380 | - timestamp: i as i64, | ||
| 1381 | - force_keyframe: false, | ||
| 1382 | - }, | ||
| 1383 | - ) | ||
| 1384 | - .expect("hardware AV1 encode"); | ||
| 1385 | - bytes.extend_from_slice(&coded.data); | ||
| 1386 | - } | ||
| 1387 | - let path = dir.join(format!("{label}-hw-{qp}.obu")); | ||
| 1388 | - std::fs::write(&path, &bytes).expect("write"); | ||
| 1389 | - if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { | ||
| 1390 | - ours.push((bytes.len() as f64 * 8.0 / f64::from(frames), db)); | ||
| 1391 | - } | ||
| 1392 | - } | ||
| 1393 | - let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] | ||
| 1394 | - .iter() | ||
| 1395 | - .filter_map(|q| { | ||
| 1396 | - software_point( | ||
| 1397 | - &dir, | ||
| 1398 | - &y4m, | ||
| 1399 | - label, | ||
| 1400 | - "librav1e", | ||
| 1401 | - &[ | ||
| 1402 | - "-rav1e-params", | ||
| 1403 | - &format!("speed=6:quantizer={q}"), | ||
| 1404 | - "-g", | ||
| 1405 | - "60", | ||
| 1406 | - ], | ||
| 1407 | - *q, | ||
| 1408 | - frames, | ||
| 1409 | - ) | ||
| 1410 | - }) | ||
| 1411 | - .collect(); | ||
| 1412 | - let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] | ||
| 1413 | - .iter() | ||
| 1414 | - .filter_map(|crf| { | ||
| 1415 | - software_point( | ||
| 1416 | - &dir, | ||
| 1417 | - &y4m, | ||
| 1418 | - label, | ||
| 1419 | - "libaom-av1", | ||
| 1420 | - &[ | ||
| 1421 | - "-cpu-used", | ||
| 1422 | - "6", | ||
| 1423 | - "-crf", | ||
| 1424 | - &crf.to_string(), | ||
| 1425 | - "-b:v", | ||
| 1426 | - "0", | ||
| 1427 | - "-g", | ||
| 1428 | - "60", | ||
| 1429 | - ], | ||
| 1430 | - *crf, | ||
| 1431 | - frames, | ||
| 1432 | - ) | ||
| 1433 | - }) | ||
| 1434 | - .collect(); | ||
| 1435 | - | ||
| 1436 | - for (name, ladder) in [("hw AV1", &ours), ("librav1e", &rav1e), ("libaom", &libaom)] { | ||
| 1437 | - println!("{label} {name}: {ladder:?}"); | ||
| 1438 | - for pair in ladder.windows(2) { | ||
| 1439 | - assert!( | ||
| 1440 | - pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, | ||
| 1441 | - "{label} {name}: ladder is not monotone at {pair:?}" | ||
| 1442 | - ); | ||
| 1443 | - } | ||
| 1444 | - } | ||
| 1445 | - if ours.len() >= 3 && rav1e.len() >= 3 { | ||
| 1446 | - println!( | ||
| 1447 | - "BD-rate row: {label}, hw AV1 vs librav1e speed 6: {:+.1}%", | ||
| 1448 | - bd_rate(&rav1e, &ours) * 100.0 | ||
| 1449 | - ); | ||
| 1450 | - } | ||
| 1451 | - if ours.len() >= 3 && libaom.len() >= 3 { | ||
| 1452 | - println!( | ||
| 1453 | - "BD-rate row: {label}, hw AV1 vs libaom cpu-used 6: {:+.1}%", | ||
| 1454 | - bd_rate(&libaom, &ours) * 100.0 | ||
| 1455 | - ); | ||
| 1456 | - } | ||
| 1457 | - } | ||
| 1458 | -} | ||
| 1459 | - | ||
| 1460 | -/// One software encoder's rate/PSNR point, or `None` when that encoder is not | ||
| 1461 | -/// built into this ffmpeg. | ||
| 1462 | -fn software_point( | ||
| 1463 | - dir: &Path, | ||
| 1464 | - y4m: &Path, | ||
| 1465 | - label: &str, | ||
| 1466 | - encoder: &str, | ||
| 1467 | - args: &[&str], | ||
| 1468 | - point: u32, | ||
| 1469 | - frames: u32, | ||
| 1470 | -) -> Option<(f64, f64)> { | ||
| 1471 | - let out = dir.join(format!("{label}-{encoder}-{point}.ivf")); | ||
| 1472 | - let _ = std::fs::remove_file(&out); | ||
| 1473 | - let status = ec_testkit::ffmpeg() | ||
| 1474 | - .args(["-nostdin", "-v", "error", "-y", "-i"]) | ||
| 1475 | - .arg(y4m) | ||
| 1476 | - .args(["-c:v", encoder]) | ||
| 1477 | - .args(args) | ||
| 1478 | - .arg(&out) | ||
| 1479 | - .status() | ||
| 1480 | - .ok()?; | ||
| 1481 | - if !status.success() { | ||
| 1482 | - return None; | ||
| 1483 | - } | ||
| 1484 | - let bytes = std::fs::metadata(&out).ok()?.len() as f64; | ||
| 1485 | - let db = ffmpeg_psnr(&out, y4m, false)?; | ||
| 1486 | - Some((bytes * 8.0 / f64::from(frames), db)) | ||
| 1487 | -} | ||
| 1488 | - | ||
| 1489 | /// PSNR of a coded stream against the source, from ffmpeg's own filter. | 863 | /// PSNR of a coded stream against the source, from ffmpeg's own filter. |
| 1490 | -fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option<f64> { | ||
| 1491 | - let mut cmd = ec_testkit::ffmpeg(); | ||
| 1492 | - cmd.args(["-nostdin", "-v", "info"]); | ||
| 1493 | - if raw_obu { | ||
| 1494 | - cmd.args(["-f", "obu"]); | ||
| 1495 | - } | ||
| 1496 | - // Both inputs are pinned to the same rate: a raw OBU stream carries no | ||
| 1497 | - // timing, so ffmpeg would otherwise call it 25 fps against a 24 fps | ||
| 1498 | - // source and the filter would compare frame i with frame i+k. | ||
| 1499 | - let out = cmd | ||
| 1500 | - .args(["-r", "24"]) | ||
| 1501 | - .arg("-i") | ||
| 1502 | - .arg(coded) | ||
| 1503 | - .args(["-r", "24"]) | ||
| 1504 | - .arg("-i") | ||
| 1505 | - .arg(source) | ||
| 1506 | - .args(["-lavfi", "psnr", "-f", "null", "-"]) | ||
| 1507 | - .output() | ||
| 1508 | - .ok()?; | ||
| 1509 | - let text = String::from_utf8_lossy(&out.stderr); | ||
| 1510 | - let field = text.split("average:").nth(1)?; | ||
| 1511 | - field | ||
| 1512 | - .split_whitespace() | ||
| 1513 | - .next()? | ||
| 1514 | - .parse::<f64>() | ||
| 1515 | - .ok() | ||
| 1516 | - .filter(|v| v.is_finite()) | ||
| 1517 | -} | ||
| 1518 | - | ||
| 1519 | /// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. | 864 | /// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. |
| 1520 | fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { | 865 | fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { |
| 1521 | let _ = std::fs::remove_file(out); | 866 | let _ = std::fs::remove_file(out); |
| @@ -1568,1123 +913,3 @@ fn real_clips() -> Vec<(&'static str, PathBuf)> { | |||
| 1568 | ("sintel 720p", ec_testkit::fixture("open/sintel_trailer-720p.mp4")), | 913 | ("sintel 720p", ec_testkit::fixture("open/sintel_trailer-720p.mp4")), |
| 1569 | ] | 914 | ] |
| 1570 | } | 915 | } |
| 1571 | - | ||
| 1572 | -/// BD-rate of `test` against `reference`, as a fraction (negative = fewer | ||
| 1573 | -/// bits for the same quality), integrated piecewise-linearly in | ||
| 1574 | -/// `log10(bits per frame)` over the PSNR range the two ladders share. | ||
| 1575 | -/// | ||
| 1576 | -/// The cubic fit of the original method needs four well-spread points and | ||
| 1577 | -/// misbehaves outside them; a trapezoid over the overlap is the honest | ||
| 1578 | -/// version of the same integral for ladders this short. | ||
| 1579 | -fn bd_rate(reference: &[(f64, f64)], test: &[(f64, f64)]) -> f64 { | ||
| 1580 | - let low = reference[0].1.max(test[0].1); | ||
| 1581 | - let high = reference[reference.len() - 1].1.min(test[test.len() - 1].1); | ||
| 1582 | - if high <= low { | ||
| 1583 | - return f64::NAN; | ||
| 1584 | - } | ||
| 1585 | - // log-rate at a PSNR, linearly interpolated inside the ladder. | ||
| 1586 | - let at = |ladder: &[(f64, f64)], db: f64| -> f64 { | ||
| 1587 | - for pair in ladder.windows(2) { | ||
| 1588 | - let ((r0, d0), (r1, d1)) = (pair[0], pair[1]); | ||
| 1589 | - if db >= d0 && db <= d1 { | ||
| 1590 | - let t = if (d1 - d0).abs() < f64::EPSILON { | ||
| 1591 | - 0.0 | ||
| 1592 | - } else { | ||
| 1593 | - (db - d0) / (d1 - d0) | ||
| 1594 | - }; | ||
| 1595 | - return r0.log10() + t * (r1.log10() - r0.log10()); | ||
| 1596 | - } | ||
| 1597 | - } | ||
| 1598 | - if db < ladder[0].1 { | ||
| 1599 | - ladder[0].0.log10() | ||
| 1600 | - } else { | ||
| 1601 | - ladder[ladder.len() - 1].0.log10() | ||
| 1602 | - } | ||
| 1603 | - }; | ||
| 1604 | - let steps = 100; | ||
| 1605 | - let mut integral = 0.0; | ||
| 1606 | - for i in 0..steps { | ||
| 1607 | - let a = low + (high - low) * f64::from(i) / f64::from(steps); | ||
| 1608 | - let b = low + (high - low) * f64::from(i + 1) / f64::from(steps); | ||
| 1609 | - let da = at(test, a) - at(reference, a); | ||
| 1610 | - let db = at(test, b) - at(reference, b); | ||
| 1611 | - integral += (da + db) / 2.0 * (b - a); | ||
| 1612 | - } | ||
| 1613 | - 10f64.powf(integral / (high - low)) - 1.0 | ||
| 1614 | -} | ||
| 1615 | - | ||
| 1616 | -/// Hardware AV1 encode speed at the two sizes his library is in, in frames per | ||
| 1617 | -/// second. Real time is 24 fps; the number is printed rather than asserted, | ||
| 1618 | -/// since a busy GPU is not a failing encoder. | ||
| 1619 | -#[test] | ||
| 1620 | -fn av1_encode_speed() { | ||
| 1621 | - let Some(display) = display() else { return }; | ||
| 1622 | - for (width, height) in [(1920u32, 1080u32), (3840, 1608)] { | ||
| 1623 | - let frames = 30u32; | ||
| 1624 | - let start = Instant::now(); | ||
| 1625 | - match encode_stream(&display, EncCodec::Av1, width, height, frames) { | ||
| 1626 | - Ok(data) => { | ||
| 1627 | - let secs = start.elapsed().as_secs_f64(); | ||
| 1628 | - println!( | ||
| 1629 | - "AV1 encode {width}x{height}: {:.1} fps ({frames} frames in {secs:.2} s), {} kbit/frame", | ||
| 1630 | - f64::from(frames) / secs, | ||
| 1631 | - data.len() * 8 / frames as usize / 1000 | ||
| 1632 | - ); | ||
| 1633 | - } | ||
| 1634 | - Err(e) => { | ||
| 1635 | - eprintln!("skipped: AV1 encode unavailable ({e})"); | ||
| 1636 | - return; | ||
| 1637 | - } | ||
| 1638 | - } | ||
| 1639 | - } | ||
| 1640 | - // 10-bit at the size his own films are in: the depth his library is | ||
| 1641 | - // actually stored at, so the fps that matters for a real export. | ||
| 1642 | - let planes: Vec<I420_16> = (0..30).map(|t| source_frame_16(3840, 1608, t)).collect(); | ||
| 1643 | - let start = Instant::now(); | ||
| 1644 | - match encode_stream_16( | ||
| 1645 | - &display, | ||
| 1646 | - EncCodec::Av1, | ||
| 1647 | - &planes, | ||
| 1648 | - 90, | ||
| 1649 | - RateControlMode::ConstantQp { qp: 90 }, | ||
| 1650 | - ) { | ||
| 1651 | - Ok(data) => { | ||
| 1652 | - let secs = start.elapsed().as_secs_f64(); | ||
| 1653 | - println!( | ||
| 1654 | - "AV1 encode 3840x1608 10-bit: {:.1} fps ({} frames in {secs:.2} s), {} kbit/frame", | ||
| 1655 | - planes.len() as f64 / secs, | ||
| 1656 | - planes.len(), | ||
| 1657 | - data.len() * 8 / planes.len() / 1000 | ||
| 1658 | - ); | ||
| 1659 | - } | ||
| 1660 | - Err(e) => eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"), | ||
| 1661 | - } | ||
| 1662 | -} | ||
| 1663 | - | ||
| 1664 | -// --------------------------------------------------------------------------- | ||
| 1665 | -// The four incumbent defects, as tests | ||
| 1666 | -// --------------------------------------------------------------------------- | ||
| 1667 | - | ||
| 1668 | -/// A `frame_num` gap is normal, not corruption. | ||
| 1669 | -/// | ||
| 1670 | -/// Dropping a reference picture from the middle of a GOP is what a seek, a lost | ||
| 1671 | -/// packet or an encoder that skipped a picture all look like. The incumbent | ||
| 1672 | -/// stack treated it as an error and fell back to software for the rest of the | ||
| 1673 | -/// timeline; here the missing pictures are inferred (8.2.5.2) and decoding | ||
| 1674 | -/// carries on in hardware. | ||
| 1675 | -#[test] | ||
| 1676 | -fn h264_frame_num_gaps_are_synthesised() { | ||
| 1677 | - let Some(display) = display() else { return }; | ||
| 1678 | - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); | ||
| 1679 | - let data = std::fs::read(&path).expect("fixture is readable"); | ||
| 1680 | - let units = split_access_units(&data, Codec::H264); | ||
| 1681 | - assert!( | ||
| 1682 | - units.len() > 8, | ||
| 1683 | - "fixture is too short to drop a picture from" | ||
| 1684 | - ); | ||
| 1685 | - | ||
| 1686 | - // Drop two reference pictures from the middle of the first GOP. | ||
| 1687 | - let mut kept: Vec<&[u8]> = Vec::new(); | ||
| 1688 | - for (i, unit) in units.iter().enumerate() { | ||
| 1689 | - if (3..=5).contains(&i) { | ||
| 1690 | - continue; | ||
| 1691 | - } | ||
| 1692 | - kept.push(unit); | ||
| 1693 | - } | ||
| 1694 | - | ||
| 1695 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | ||
| 1696 | - let mut frames = 0usize; | ||
| 1697 | - for (i, unit) in kept.iter().enumerate().take(20) { | ||
| 1698 | - if let Err(e) = decoder.decode(unit, i as i64) { | ||
| 1699 | - panic!( | ||
| 1700 | - "unit {i} failed after {} gap frames: {e}", | ||
| 1701 | - decoder.gap_frames_synthesized() | ||
| 1702 | - ); | ||
| 1703 | - } | ||
| 1704 | - while let Some(frame) = decoder.next_frame() { | ||
| 1705 | - // The frame is real: reading it back must work, not just arrive. | ||
| 1706 | - let planes = frame.to_i420().expect("readback"); | ||
| 1707 | - assert_eq!(planes.y.len(), 1920 * 1080); | ||
| 1708 | - frames += 1; | ||
| 1709 | - } | ||
| 1710 | - } | ||
| 1711 | - decoder.flush().expect("flush"); | ||
| 1712 | - while decoder.next_frame().is_some() { | ||
| 1713 | - frames += 1; | ||
| 1714 | - } | ||
| 1715 | - let synthesised = decoder.gap_frames_synthesized(); | ||
| 1716 | - println!("frame_num gap: {frames} frames decoded, {synthesised} pictures inferred"); | ||
| 1717 | - assert!(synthesised > 0, "the gap was not detected"); | ||
| 1718 | - assert!(frames >= 10, "only {frames} frames survived the gap"); | ||
| 1719 | -} | ||
| 1720 | - | ||
| 1721 | -/// VmRSS in kilobytes, from `/proc/self/status`. | ||
| 1722 | -fn rss_kb() -> u64 { | ||
| 1723 | - let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); | ||
| 1724 | - status | ||
| 1725 | - .lines() | ||
| 1726 | - .find_map(|line| line.strip_prefix("VmRSS:")) | ||
| 1727 | - .and_then(|v| v.split_whitespace().next().map(|n| n.to_string())) | ||
| 1728 | - .and_then(|n| n.parse().ok()) | ||
| 1729 | - .unwrap_or(0) | ||
| 1730 | -} | ||
| 1731 | - | ||
| 1732 | -/// Decode and read back for longer than any export, and watch the resident set. | ||
| 1733 | -/// | ||
| 1734 | -/// The incumbent leaked ~3 MB per frame by mapping a VA image and never | ||
| 1735 | -/// unmapping it: a 719-frame export lost 2 GB. Every mapping here is a guard | ||
| 1736 | -/// that unmaps on drop, and this is the test that says so out loud. | ||
| 1737 | -#[test] | ||
| 1738 | -fn long_decode_does_not_grow_the_resident_set() { | ||
| 1739 | - // VmRSS is a process-wide number and the harness runs every test in this | ||
| 1740 | - // binary as a thread of one process: a sibling allocating between the | ||
| 1741 | - // baseline and the end reading shows up here as a 200 MB "leak". The | ||
| 1742 | - // measurement therefore runs in a child process holding only this test. | ||
| 1743 | - if std::env::var_os("EC_HW_RSS_CHILD").is_none() { | ||
| 1744 | - let status = Command::new(std::env::current_exe().expect("test binary path")) | ||
| 1745 | - .args(["--exact", "long_decode_does_not_grow_the_resident_set"]) | ||
| 1746 | - .env("EC_HW_RSS_CHILD", "1") | ||
| 1747 | - .status() | ||
| 1748 | - .expect("re-run this test in its own process"); | ||
| 1749 | - assert!(status.success(), "isolated RSS run failed"); | ||
| 1750 | - return; | ||
| 1751 | - } | ||
| 1752 | - let Some(display) = display() else { return }; | ||
| 1753 | - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); | ||
| 1754 | - let data = std::fs::read(&path).expect("fixture is readable"); | ||
| 1755 | - let units = split_access_units(&data, Codec::H264); | ||
| 1756 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | ||
| 1757 | - | ||
| 1758 | - // Warm up first: the first pictures allocate the surface pool and the | ||
| 1759 | - // readback image, and that growth is not a leak. | ||
| 1760 | - let mut decoded = 0usize; | ||
| 1761 | - let mut baseline = 0u64; | ||
| 1762 | - let mut readback_ms = 0f64; | ||
| 1763 | - let mut pending: Vec<Frame> = Vec::new(); | ||
| 1764 | - let target = 719usize; | ||
| 1765 | - 'outer: for pass in 0..16 { | ||
| 1766 | - if pass > 0 { | ||
| 1767 | - decoder.reset(); | ||
| 1768 | - } | ||
| 1769 | - for (i, unit) in units.iter().enumerate() { | ||
| 1770 | - decoder.decode(unit, i as i64).expect("decode"); | ||
| 1771 | - while let Some(frame) = decoder.next_frame() { | ||
| 1772 | - // Hold a few frames before reading any back: a decoder that is | ||
| 1773 | - // read one frame per submission spends its time waiting for the | ||
| 1774 | - // GPU, which measures latency rather than throughput. | ||
| 1775 | - pending.push(frame); | ||
| 1776 | - if pending.len() < 4 { | ||
| 1777 | - continue; | ||
| 1778 | - } | ||
| 1779 | - let start = std::time::Instant::now(); | ||
| 1780 | - for frame in pending.drain(..) { | ||
| 1781 | - let planes = frame.to_i420().expect("readback"); | ||
| 1782 | - std::hint::black_box(&planes); | ||
| 1783 | - decoded += 1; | ||
| 1784 | - } | ||
| 1785 | - readback_ms += start.elapsed().as_secs_f64() * 1000.0; | ||
| 1786 | - if decoded == 60 { | ||
| 1787 | - baseline = rss_kb(); | ||
| 1788 | - } | ||
| 1789 | - if decoded >= target { | ||
| 1790 | - break 'outer; | ||
| 1791 | - } | ||
| 1792 | - } | ||
| 1793 | - } | ||
| 1794 | - } | ||
| 1795 | - decoder.flush().expect("flush"); | ||
| 1796 | - let end = rss_kb(); | ||
| 1797 | - let delta_mb = (end.saturating_sub(baseline)) as f64 / 1024.0; | ||
| 1798 | - println!( | ||
| 1799 | - "{decoded} frames decoded and read back: RSS {baseline} -> {end} kB (delta {delta_mb:.1} MB), \ | ||
| 1800 | - decode and read back {:.2} ms/frame at 1920x1080", | ||
| 1801 | - readback_ms / decoded as f64 | ||
| 1802 | - ); | ||
| 1803 | - assert!(decoded >= target, "only {decoded} frames decoded"); | ||
| 1804 | - assert!( | ||
| 1805 | - delta_mb < 50.0, | ||
| 1806 | - "resident set grew {delta_mb:.1} MB over {decoded} frames" | ||
| 1807 | - ); | ||
| 1808 | -} | ||
| 1809 | - | ||
| 1810 | -/// The zero-copy path: a decoded surface exports as DRM PRIME file descriptors. | ||
| 1811 | -/// | ||
| 1812 | -/// This is what edith's `engine-hw` imports into gbm, so the fds and the plane | ||
| 1813 | -/// layout matter as much as the pixels do. | ||
| 1814 | -#[test] | ||
| 1815 | -fn frames_export_as_dma_buf() { | ||
| 1816 | - let Some(display) = display() else { return }; | ||
| 1817 | - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); | ||
| 1818 | - let data = std::fs::read(&path).expect("fixture is readable"); | ||
| 1819 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | ||
| 1820 | - let mut exported = 0usize; | ||
| 1821 | - decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { | ||
| 1822 | - let prime = frame.export_prime().expect("export"); | ||
| 1823 | - assert_eq!(prime.fourcc, ec_va::va::VA_FOURCC_NV12); | ||
| 1824 | - assert_eq!((prime.width, prime.height), frame.coded_size); | ||
| 1825 | - assert!(!prime.objects.is_empty(), "no DRM objects exported"); | ||
| 1826 | - assert!(!prime.layers.is_empty(), "no layers exported"); | ||
| 1827 | - let planes: usize = prime.layers.iter().map(|l| l.planes.len()).sum(); | ||
| 1828 | - assert!( | ||
| 1829 | - planes >= 2, | ||
| 1830 | - "NV12 needs a luma and a chroma plane, got {planes}" | ||
| 1831 | - ); | ||
| 1832 | - exported += 1; | ||
| 1833 | - }) | ||
| 1834 | - .expect("decode"); | ||
| 1835 | - assert!(exported >= 1, "nothing was exported"); | ||
| 1836 | - println!("DRM PRIME export: {exported} frames"); | ||
| 1837 | -} | ||
| 1838 | - | ||
| 1839 | -// --------------------------------------------------------------------------- | ||
| 1840 | -// His library | ||
| 1841 | -// --------------------------------------------------------------------------- | ||
| 1842 | - | ||
| 1843 | -/// Turn any container into an elementary stream ffmpeg and this crate agree on. | ||
| 1844 | -/// | ||
| 1845 | -/// `frames` bounds the extraction: piping a two-hour 4K film through memory to | ||
| 1846 | -/// compare its first five hundred pictures is several gigabytes of nothing. | ||
| 1847 | -fn elementary(path: &Path, codec: Codec, frames: usize) -> Option<Vec<u8>> { | ||
| 1848 | - let args: &[&str] = match codec { | ||
| 1849 | - Codec::H264 => &["-bsf:v", "h264_mp4toannexb", "-f", "h264"], | ||
| 1850 | - Codec::H265 => &["-bsf:v", "hevc_mp4toannexb", "-f", "hevc"], | ||
| 1851 | - Codec::Vp9 | Codec::Av1 => &["-f", "ivf"], | ||
| 1852 | - }; | ||
| 1853 | - let out = ec_testkit::ffmpeg() | ||
| 1854 | - .args(["-nostdin", "-v", "error", "-i"]) | ||
| 1855 | - .arg(path) | ||
| 1856 | - .args(["-map", "0:v:0", "-c:v", "copy"]) | ||
| 1857 | - // A few more coded pictures than frames wanted: reordering means the | ||
| 1858 | - // last few packets have not been shown yet. | ||
| 1859 | - .args(["-frames:v", &(frames + 16).to_string()]) | ||
| 1860 | - .args(args) | ||
| 1861 | - .arg("-") | ||
| 1862 | - .stderr(Stdio::null()) | ||
| 1863 | - .output() | ||
| 1864 | - .ok()?; | ||
| 1865 | - (!out.stdout.is_empty()).then_some(out.stdout) | ||
| 1866 | -} | ||
| 1867 | - | ||
| 1868 | -#[test] | ||
| 1869 | -fn real_library_spot_check() { | ||
| 1870 | - let Some(display) = display() else { return }; | ||
| 1871 | - let wanted: Vec<(PathBuf, Codec, bool)> = [ | ||
| 1872 | - ("open/sintel_trailer-480p.mp4", Codec::H264, false), | ||
| 1873 | - ("open/sintel_trailer-1080p.mp4", Codec::H264, false), | ||
| 1874 | - ("derived/sintel720-x265-main10.mp4", Codec::H265, true), | ||
| 1875 | - ] | ||
| 1876 | - .into_iter() | ||
| 1877 | - .map(|(rel, codec, ten_bit)| (ec_testkit::fixture(rel), codec, ten_bit)) | ||
| 1878 | - .collect(); | ||
| 1879 | - | ||
| 1880 | - // 500 frames per file by default; a diagnostic run can ask for fewer. | ||
| 1881 | - let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES") | ||
| 1882 | - .ok() | ||
| 1883 | - .and_then(|v| v.parse().ok()) | ||
| 1884 | - .unwrap_or(500); | ||
| 1885 | - let mut table = Vec::new(); | ||
| 1886 | - for (path, codec, ten_bit) in &wanted { | ||
| 1887 | - let path = Path::new(path); | ||
| 1888 | - let data = elementary(path, *codec, limit).expect("elementary stream"); | ||
| 1889 | - let mut decoder = Decoder::new(&display, *codec).expect("decoder opens"); | ||
| 1890 | - let mut reference: Option<Reference> = None; | ||
| 1891 | - let mut worst = f64::INFINITY; | ||
| 1892 | - let mut compared = 0usize; | ||
| 1893 | - let mut failed: Option<String> = None; | ||
| 1894 | - let result = decode_stream(&mut decoder, *codec, &data, limit, |frame| { | ||
| 1895 | - let (w, h) = frame.display_size; | ||
| 1896 | - let reference = reference | ||
| 1897 | - .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs")); | ||
| 1898 | - let Some(want) = reference.next(w, h) else { | ||
| 1899 | - return; | ||
| 1900 | - }; | ||
| 1901 | - let got = if *ten_bit { | ||
| 1902 | - Planes::from_16bit(&frame.to_i420_16().expect("readback")) | ||
| 1903 | - } else { | ||
| 1904 | - Planes::from_8bit(&frame.to_i420().expect("readback")) | ||
| 1905 | - }; | ||
| 1906 | - if got.y.len() != want.y.len() { | ||
| 1907 | - failed = Some("frame size disagrees with ffmpeg".to_string()); | ||
| 1908 | - return; | ||
| 1909 | - } | ||
| 1910 | - let db = psnr(&got, &want); | ||
| 1911 | - if std::env::var_os("EC_HW_DEBUG").is_some() { | ||
| 1912 | - eprintln!(" {} frame {compared}: {db:.1} dB", short(path)); | ||
| 1913 | - } | ||
| 1914 | - worst = worst.min(db); | ||
| 1915 | - compared += 1; | ||
| 1916 | - }); | ||
| 1917 | - match result { | ||
| 1918 | - Ok(decoded) => table.push(format!( | ||
| 1919 | - "{:<52} {decoded:>4} frames, {compared} compared, worst {}", | ||
| 1920 | - short(path), | ||
| 1921 | - if worst.is_infinite() { | ||
| 1922 | - "exact".to_string() | ||
| 1923 | - } else { | ||
| 1924 | - format!("{worst:.1} dB") | ||
| 1925 | - } | ||
| 1926 | - )), | ||
| 1927 | - Err(e) => failed = Some(e.to_string()), | ||
| 1928 | - } | ||
| 1929 | - if let Some(reason) = failed { | ||
| 1930 | - table.push(format!("{:<52} FAIL {reason}", short(path))); | ||
| 1931 | - } | ||
| 1932 | - assert!(compared > 0, "{}: nothing decoded", short(path)); | ||
| 1933 | - assert!( | ||
| 1934 | - worst >= 40.0, | ||
| 1935 | - "{}: worst frame {worst:.1} dB against ffmpeg", | ||
| 1936 | - short(path) | ||
| 1937 | - ); | ||
| 1938 | - } | ||
| 1939 | - for row in table { | ||
| 1940 | - println!("{row}"); | ||
| 1941 | - } | ||
| 1942 | -} | ||
| 1943 | - | ||
| 1944 | -/// A library path without the directory tree, so a report can carry it. | ||
| 1945 | -fn short(path: &Path) -> String { | ||
| 1946 | - path.file_name() | ||
| 1947 | - .map(|n| n.to_string_lossy().to_string()) | ||
| 1948 | - .unwrap_or_default() | ||
| 1949 | -} | ||
| 1950 | - | ||
| 1951 | -/// PSNR of one plane, in dB (`f64::INFINITY` for an exact match). | ||
| 1952 | -fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 { | ||
| 1953 | - let n = a.len().min(b.len()); | ||
| 1954 | - let mse: f64 = a[..n] | ||
| 1955 | - .iter() | ||
| 1956 | - .zip(&b[..n]) | ||
| 1957 | - .map(|(&p, &q)| { | ||
| 1958 | - let d = f64::from(p) - f64::from(q); | ||
| 1959 | - d * d | ||
| 1960 | - }) | ||
| 1961 | - .sum::<f64>() | ||
| 1962 | - / n as f64; | ||
| 1963 | - if mse == 0.0 { | ||
| 1964 | - f64::INFINITY | ||
| 1965 | - } else { | ||
| 1966 | - 10.0 * (peak * peak / mse).log10() | ||
| 1967 | - } | ||
| 1968 | -} | ||
| 1969 | - | ||
| 1970 | -/// | ||
| 1971 | -/// `real_library_spot_check` already pins the whole-frame PSNR at >= 40 dB | ||
| 1972 | -/// for a mix of files; this isolates Y from U/V on this specific 10-bit film, | ||
| 1973 | -/// against both `yuv420p10le` (the lossless comparison) and `yuv420p` (the | ||
| 1974 | -/// truncating `to_i420` path, which rounds ffmpeg's dithered 8-bit output | ||
| 1975 | -/// against this crate's un-dithered right-shift -- a real but small gap, not | ||
| 1976 | -/// a bug). A collapsed U/V PSNR here (a grey frame) would mean the chroma | ||
| 1977 | -/// plane is being read at the wrong stride/offset; it is not, on this file. | ||
| 1978 | -#[test] | ||
| 1979 | -fn ten_bit_chroma_is_not_grey() { | ||
| 1980 | - let Some(display) = display() else { return }; | ||
| 1981 | - let path = &ec_testkit::fixture("derived/sintel720-x265-main10.mp4"); | ||
| 1982 | - let frames = 3usize; | ||
| 1983 | - let data = elementary(path, Codec::H265, frames).expect("elementary stream"); | ||
| 1984 | - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); | ||
| 1985 | - let mut ref10: Option<Reference> = None; | ||
| 1986 | - let mut ref8: Option<Reference> = None; | ||
| 1987 | - let mut compared = 0usize; | ||
| 1988 | - decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { | ||
| 1989 | - let (w, h) = frame.display_size; | ||
| 1990 | - let ref10 = | ||
| 1991 | - ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs")); | ||
| 1992 | - let want10 = ref10.next(w, h).expect("ffmpeg has a frame"); | ||
| 1993 | - let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback")); | ||
| 1994 | - let y_db = plane_psnr(&got16.y, &want10.y, 1023.0); | ||
| 1995 | - let uv_db = plane_psnr( | ||
| 1996 | - &[got16.u.as_slice(), got16.v.as_slice()].concat(), | ||
| 1997 | - &[want10.u.as_slice(), want10.v.as_slice()].concat(), | ||
| 1998 | - 1023.0, | ||
| 1999 | - ); | ||
| 2000 | - println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB"); | ||
| 2001 | - assert!( | ||
| 2002 | - y_db >= 50.0, | ||
| 2003 | - "frame {compared}: Y PSNR collapsed to {y_db:.1} dB" | ||
| 2004 | - ); | ||
| 2005 | - assert!( | ||
| 2006 | - uv_db >= 50.0, | ||
| 2007 | - "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)" | ||
| 2008 | - ); | ||
| 2009 | - | ||
| 2010 | - let ref8 = | ||
| 2011 | - ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs")); | ||
| 2012 | - let want8 = ref8.next(w, h).expect("ffmpeg has a frame"); | ||
| 2013 | - let got8 = Planes::from_8bit(&frame.to_i420().expect("readback")); | ||
| 2014 | - let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0); | ||
| 2015 | - let uv_db8 = plane_psnr( | ||
| 2016 | - &[got8.u.as_slice(), got8.v.as_slice()].concat(), | ||
| 2017 | - &[want8.u.as_slice(), want8.v.as_slice()].concat(), | ||
| 2018 | - 255.0, | ||
| 2019 | - ); | ||
| 2020 | - println!("frame {compared} to_i420 vs yuv420p: Y {y_db8:.1} dB, UV {uv_db8:.1} dB"); | ||
| 2021 | - // ffmpeg dithers its 8-bit downconversion; this crate truncates. Both | ||
| 2022 | - // are legitimate 10-to-8 roundings, so the floor here is the | ||
| 2023 | - // dithering noise floor, not the lossless bound above. | ||
| 2024 | - assert!( | ||
| 2025 | - y_db8 >= 30.0, | ||
| 2026 | - "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB" | ||
| 2027 | - ); | ||
| 2028 | - assert!( | ||
| 2029 | - uv_db8 >= 30.0, | ||
| 2030 | - "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)" | ||
| 2031 | - ); | ||
| 2032 | - compared += 1; | ||
| 2033 | - }) | ||
| 2034 | - .expect("decode"); | ||
| 2035 | - assert_eq!(compared, frames, "not all frames were compared"); | ||
| 2036 | -} | ||
| 2037 | - | ||
| 2038 | -/// An SDR H.264 stream, which carries no HDR SEI at all: `Frame::colour` | ||
| 2039 | -/// either resolves from the VUI or answers [`None`], but never panics. | ||
| 2040 | -#[test] | ||
| 2041 | -fn sdr_h264_colour_never_panics() { | ||
| 2042 | - let Some(display) = display() else { return }; | ||
| 2043 | - let paths = ec_testkit::fixtures("bitstreams", "264"); | ||
| 2044 | - let path = &paths[0]; | ||
| 2045 | - let data = std::fs::read(path).expect("fixture is readable"); | ||
| 2046 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | ||
| 2047 | - let mut seen = 0usize; | ||
| 2048 | - decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { | ||
| 2049 | - seen += 1; | ||
| 2050 | - // No SEI parsing on this codec: content light is always absent. | ||
| 2051 | - if let Some(colour) = frame.colour() { | ||
| 2052 | - assert_eq!(colour.light.max_cll, None); | ||
| 2053 | - } | ||
| 2054 | - }) | ||
| 2055 | - .expect("decode"); | ||
| 2056 | - assert!(seen > 0, "{}: nothing decoded", short(path)); | ||
| 2057 | -} | ||
| 2058 | - | ||
| 2059 | -/// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in | ||
| 2060 | -/// decode order, even though they display before it (they predict from | ||
| 2061 | -/// pictures the CRA's own random-access point does not have). A decoder | ||
| 2062 | -/// started fresh at that CRA — what a seek does — must therefore drop those | ||
| 2063 | -/// RASL pictures per H.265 8.1.3's `NoRaslOutputFlag`, or its output shifts by | ||
| 2064 | -/// however many RASL pictures the GOP has, handing back the wrong picture for | ||
| 2065 | -/// every display index at or after the seek target. | ||
| 2066 | -#[test] | ||
| 2067 | -fn hevc_seek_matches_linear_mkv() { | ||
| 2068 | - let Some(display) = display() else { return }; | ||
| 2069 | - let path = ec_testkit::fixture("video/hevc-open-gop.mkv"); | ||
| 2070 | - let data = elementary(&path, Codec::H265, 45).expect("elementary stream"); | ||
| 2071 | - let units = split_access_units(&data, Codec::H265); | ||
| 2072 | - | ||
| 2073 | - // Linear decode: every picture from the start, frame 30 kept for | ||
| 2074 | - // comparison (the file's second CRA, per `test_hevc.mkv`'s 30-picture | ||
| 2075 | - // GOPs). | ||
| 2076 | - const TARGET: usize = 30; | ||
| 2077 | - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); | ||
| 2078 | - let mut linear_frame_30 = None; | ||
| 2079 | - let mut index = 0usize; | ||
| 2080 | - decode_stream(&mut decoder, Codec::H265, &data, 45, |frame| { | ||
| 2081 | - if index == TARGET { | ||
| 2082 | - linear_frame_30 = Some(frame.to_i420().expect("readback")); | ||
| 2083 | - } | ||
| 2084 | - index += 1; | ||
| 2085 | - }) | ||
| 2086 | - .expect("linear decode"); | ||
| 2087 | - let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); | ||
| 2088 | - | ||
| 2089 | - // Find the access unit whose first VCL NAL is the CRA at this GOP | ||
| 2090 | - // boundary, and feed the decoder from there on, exactly as a seek would: | ||
| 2091 | - // nothing from before it goes in. | ||
| 2092 | - let cra_at = units | ||
| 2093 | - .iter() | ||
| 2094 | - .position(|au| starts_with_cra(au)) | ||
| 2095 | - .expect("a CRA access unit exists"); | ||
| 2096 | - | ||
| 2097 | - // A seek reuses the parameter sets a decoder already learned; a fresh one | ||
| 2098 | - // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a | ||
| 2099 | - // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown | ||
| 2100 | - // away) and reset picture state before feeding the seek target. | ||
| 2101 | - let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); | ||
| 2102 | - seek_decoder | ||
| 2103 | - .decode(units[0], 0) | ||
| 2104 | - .expect("prime parameter sets"); | ||
| 2105 | - seek_decoder.reset(); | ||
| 2106 | - let mut seeked_frame = None; | ||
| 2107 | - for (i, unit) in units[cra_at..].iter().enumerate() { | ||
| 2108 | - seek_decoder.decode(unit, i as i64).expect("seek decode"); | ||
| 2109 | - if let Some(frame) = seek_decoder.next_frame() { | ||
| 2110 | - seeked_frame = Some(frame.to_i420().expect("readback")); | ||
| 2111 | - break; | ||
| 2112 | - } | ||
| 2113 | - } | ||
| 2114 | - if seeked_frame.is_none() { | ||
| 2115 | - seek_decoder.flush().expect("flush"); | ||
| 2116 | - seeked_frame = seek_decoder | ||
| 2117 | - .next_frame() | ||
| 2118 | - .map(|f| f.to_i420().expect("readback")); | ||
| 2119 | - } | ||
| 2120 | - let seeked_frame = seeked_frame.expect("a frame came out after the seek"); | ||
| 2121 | - | ||
| 2122 | - assert_eq!( | ||
| 2123 | - seeked_frame, linear_frame_30, | ||
| 2124 | - "seeking to the CRA before frame 30 handed back a different picture \ | ||
| 2125 | - than a linear decode of frame 30 — RASL pictures were not dropped" | ||
| 2126 | - ); | ||
| 2127 | -} | ||
| 2128 | - | ||
| 2129 | -/// An H.264 open-GOP I picture is not an IDR: it is a plain I slice | ||
| 2130 | -/// (`nal_unit_type` 1) whose predecessors in decode order can still hold | ||
| 2131 | -/// references from before it, so leading pictures between it and the next | ||
| 2132 | -/// IDR may predict from a picture never decoded since a fresh start there — | ||
| 2133 | -/// exactly what a seek does. A decoder started at that I must drop those | ||
| 2134 | -/// leading pictures per D.2.8's recovery point default, or its output shifts | ||
| 2135 | -/// by however many leading pictures the GOP has. | ||
| 2136 | -#[test] | ||
| 2137 | -fn h264_seek_matches_linear_open_gop() { | ||
| 2138 | - let Some(display) = display() else { return }; | ||
| 2139 | - let path = ec_testkit::fixture("video/h264-open-gop.mp4"); | ||
| 2140 | - let data = elementary(&path, Codec::H264, 60).expect("elementary stream"); | ||
| 2141 | - let units = split_access_units(&data, Codec::H264); | ||
| 2142 | - | ||
| 2143 | - // Linear decode: every picture from the start, frame 30 kept for | ||
| 2144 | - // comparison (the fixture's second I picture, `keyint=30`). | ||
| 2145 | - const TARGET: usize = 30; | ||
| 2146 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | ||
| 2147 | - let mut linear_frame_30 = None; | ||
| 2148 | - let mut index = 0usize; | ||
| 2149 | - decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| { | ||
| 2150 | - if index == TARGET { | ||
| 2151 | - linear_frame_30 = Some(frame.to_i420().expect("readback")); | ||
| 2152 | - } | ||
| 2153 | - index += 1; | ||
| 2154 | - }) | ||
| 2155 | - .expect("linear decode"); | ||
| 2156 | - let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); | ||
| 2157 | - | ||
| 2158 | - // Find the access unit whose first VCL NAL is the open-GOP I picture at | ||
| 2159 | - // this GOP boundary, and feed the decoder from there on, exactly as a | ||
| 2160 | - // seek would: nothing from before it goes in. | ||
| 2161 | - let open_gop_at = units | ||
| 2162 | - .iter() | ||
| 2163 | - .position(|au| is_open_gop_i(au)) | ||
| 2164 | - .expect("an open-GOP I access unit exists"); | ||
| 2165 | - | ||
| 2166 | - // A seek reuses the parameter sets a decoder already learned; a fresh one | ||
| 2167 | - // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a | ||
| 2168 | - // caller to: decode the leading IDR (its picture is thrown away) and | ||
| 2169 | - // reset picture state before feeding the seek target. | ||
| 2170 | - let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); | ||
| 2171 | - seek_decoder | ||
| 2172 | - .decode(units[0], 0) | ||
| 2173 | - .expect("prime parameter sets"); | ||
| 2174 | - seek_decoder.reset(); | ||
| 2175 | - let mut seeked_frame = None; | ||
| 2176 | - for (i, unit) in units[open_gop_at..].iter().enumerate() { | ||
| 2177 | - seek_decoder.decode(unit, i as i64).expect("seek decode"); | ||
| 2178 | - if let Some(frame) = seek_decoder.next_frame() { | ||
| 2179 | - seeked_frame = Some(frame.to_i420().expect("readback")); | ||
| 2180 | - break; | ||
| 2181 | - } | ||
| 2182 | - } | ||
| 2183 | - if seeked_frame.is_none() { | ||
| 2184 | - seek_decoder.flush().expect("flush"); | ||
| 2185 | - seeked_frame = seek_decoder | ||
| 2186 | - .next_frame() | ||
| 2187 | - .map(|f| f.to_i420().expect("readback")); | ||
| 2188 | - } | ||
| 2189 | - let seeked_frame = seeked_frame.expect("a frame came out after the seek"); | ||
| 2190 | - | ||
| 2191 | - assert_eq!( | ||
| 2192 | - seeked_frame, linear_frame_30, | ||
| 2193 | - "seeking to the open-GOP I before frame 30 handed back a different \ | ||
| 2194 | - picture than a linear decode of frame 30 — leading pictures with \ | ||
| 2195 | - missing references were not dropped" | ||
| 2196 | - ); | ||
| 2197 | -} | ||
| 2198 | - | ||
| 2199 | -/// True when an access unit's first VCL NAL is an H.264 open-GOP I slice | ||
| 2200 | -/// (`nal_unit_type` 1, `slice_type % 5 == 2`), found by scanning for the | ||
| 2201 | -/// access unit's first start code rather than assuming a fixed prefix length. | ||
| 2202 | -fn is_open_gop_i(au: &[u8]) -> bool { | ||
| 2203 | - let mut i = 0usize; | ||
| 2204 | - while i + 3 < au.len() { | ||
| 2205 | - if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 { | ||
| 2206 | - i += 1; | ||
| 2207 | - continue; | ||
| 2208 | - } | ||
| 2209 | - let header = au[i + 3]; | ||
| 2210 | - if header & 0x1f != 1 { | ||
| 2211 | - return false; | ||
| 2212 | - } | ||
| 2213 | - let mut r = ec_core::BitReader::new(&au[i + 4..]); | ||
| 2214 | - if r.read_ue().is_err() { | ||
| 2215 | - return false; | ||
| 2216 | - } | ||
| 2217 | - return matches!(r.read_ue(), Ok(code) if code % 5 == 2); | ||
| 2218 | - } | ||
| 2219 | - false | ||
| 2220 | -} | ||
| 2221 | - | ||
| 2222 | -/// True when an access unit's first VCL NAL is an HEVC CRA (`nal_type` 21). | ||
| 2223 | -/// A CRA's access unit may open with its own VPS/SPS/PPS, so this skips past | ||
| 2224 | -/// non-VCL NALs to the first one that carries a slice. | ||
| 2225 | -fn starts_with_cra(au: &[u8]) -> bool { | ||
| 2226 | - let mut i = 0usize; | ||
| 2227 | - while i + 3 < au.len() { | ||
| 2228 | - if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { | ||
| 2229 | - let t = (au[i + 3] >> 1) & 0x3f; | ||
| 2230 | - if t <= 31 { | ||
| 2231 | - return t == 21; | ||
| 2232 | - } | ||
| 2233 | - i += 3; | ||
| 2234 | - continue; | ||
| 2235 | - } | ||
| 2236 | - i += 1; | ||
| 2237 | - } | ||
| 2238 | - false | ||
| 2239 | -} | ||
| 2240 | - | ||
| 2241 | -/// `ffmpeg -bsf:v trace_headers` over a bitstream, returning every | ||
| 2242 | -/// `name = value` line it prints — the slice header fields the driver wrote. | ||
| 2243 | -fn trace_headers(path: &Path, codec: &str) -> Vec<(String, i64)> { | ||
| 2244 | - let out = ec_testkit::ffmpeg() | ||
| 2245 | - .args(["-v", "trace", "-hide_banner", "-nostats", "-f", codec, "-i"]) | ||
| 2246 | - .arg(path) | ||
| 2247 | - .args(["-c:v", "copy", "-bsf:v", "trace_headers", "-f", "null", "-"]) | ||
| 2248 | - .output() | ||
| 2249 | - .expect("ffmpeg runs"); | ||
| 2250 | - let text = String::from_utf8_lossy(&out.stderr); | ||
| 2251 | - text.lines() | ||
| 2252 | - .filter_map(|line| { | ||
| 2253 | - // "[trace_headers @ 0x...] 16 frame_num 0000 = 0" | ||
| 2254 | - let (lhs, value) = line.rsplit_once(" = ")?; | ||
| 2255 | - let mut words = lhs.split_whitespace().rev(); | ||
| 2256 | - let _bits = words.next()?; | ||
| 2257 | - let name = words.next()?; | ||
| 2258 | - Some((name.to_string(), value.trim().parse().ok()?)) | ||
| 2259 | - }) | ||
| 2260 | - .collect() | ||
| 2261 | -} | ||
| 2262 | - | ||
| 2263 | -/// Phone-class stateful decoders order output from `frame_num` and the POC | ||
| 2264 | -/// fields, so a stream whose every slice says 0/0 judders there even though | ||
| 2265 | -/// desktop decoders (which re-derive from decode order) play it cleanly. | ||
| 2266 | -/// Encode a long P-run and read the fields back the way such a decoder does. | ||
| 2267 | -fn slice_counters( | ||
| 2268 | - codec: EncCodec, | ||
| 2269 | - width: u32, | ||
| 2270 | - height: u32, | ||
| 2271 | - frames: u32, | ||
| 2272 | -) -> (PathBuf, Vec<(String, i64)>) { | ||
| 2273 | - let Some(display) = display() else { | ||
| 2274 | - return (PathBuf::new(), Vec::new()); | ||
| 2275 | - }; | ||
| 2276 | - let mut config = EncoderConfig::new(codec, width, height); | ||
| 2277 | - config.gop_size = frames * 2; | ||
| 2278 | - config.framerate = (30, 1); | ||
| 2279 | - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; | ||
| 2280 | - let mut encoder = Encoder::new(&display, config).expect("encoder"); | ||
| 2281 | - let mut out = Vec::new(); | ||
| 2282 | - for t in 0..frames { | ||
| 2283 | - let coded = encoder | ||
| 2284 | - .encode( | ||
| 2285 | - &source_frame(width, height, t), | ||
| 2286 | - FrameMetadata { | ||
| 2287 | - timestamp: i64::from(t), | ||
| 2288 | - force_keyframe: false, | ||
| 2289 | - }, | ||
| 2290 | - ) | ||
| 2291 | - .expect("encode"); | ||
| 2292 | - assert_eq!(coded.is_keyframe, t == 0, "one IDR then P-frames at {t}"); | ||
| 2293 | - out.extend_from_slice(&coded.data); | ||
| 2294 | - } | ||
| 2295 | - let dir = std::env::temp_dir().join(format!("ec-hw-counters-{codec:?}")); | ||
| 2296 | - std::fs::create_dir_all(&dir).expect("temp dir"); | ||
| 2297 | - let (name, fmt) = match codec { | ||
| 2298 | - EncCodec::H264 => ("out.264", "h264"), | ||
| 2299 | - EncCodec::H265 => ("out.265", "hevc"), | ||
| 2300 | - EncCodec::Av1 => unreachable!(), | ||
| 2301 | - }; | ||
| 2302 | - let path = dir.join(name); | ||
| 2303 | - std::fs::write(&path, &out).expect("write"); | ||
| 2304 | - let fields = trace_headers(&path, fmt); | ||
| 2305 | - (path, fields) | ||
| 2306 | -} | ||
| 2307 | - | ||
| 2308 | -fn values(fields: &[(String, i64)], name: &str) -> Vec<i64> { | ||
| 2309 | - fields | ||
| 2310 | - .iter() | ||
| 2311 | - .filter(|(n, _)| n == name) | ||
| 2312 | - .map(|(_, v)| *v) | ||
| 2313 | - .collect() | ||
| 2314 | -} | ||
| 2315 | - | ||
| 2316 | -#[test] | ||
| 2317 | -fn h264_slice_headers_count_frames_for_stateful_decoders() { | ||
| 2318 | - let frames = 64u32; | ||
| 2319 | - let (path, fields) = slice_counters(EncCodec::H264, 640, 360, frames); | ||
| 2320 | - if fields.is_empty() { | ||
| 2321 | - return; | ||
| 2322 | - } | ||
| 2323 | - let frame_num = values(&fields, "frame_num"); | ||
| 2324 | - assert_eq!( | ||
| 2325 | - frame_num.len(), | ||
| 2326 | - frames as usize, | ||
| 2327 | - "one slice per picture in {}", | ||
| 2328 | - path.display() | ||
| 2329 | - ); | ||
| 2330 | - let log2_max = values(&fields, "log2_max_frame_num_minus4")[0] + 4; | ||
| 2331 | - let max_frame_num = 1i64 << log2_max; | ||
| 2332 | - let expected: Vec<i64> = (0..frames as i64).map(|n| n % max_frame_num).collect(); | ||
| 2333 | - assert_eq!( | ||
| 2334 | - frame_num, expected, | ||
| 2335 | - "frame_num steps +1 mod {max_frame_num}" | ||
| 2336 | - ); | ||
| 2337 | - // pic_order_cnt_type 2: POC = 2 * FrameNumOffset-adjusted frame_num, no lsb is | ||
| 2338 | - // written — the decoder's output order is the decode order by construction. | ||
| 2339 | - let poc_type = values(&fields, "pic_order_cnt_type"); | ||
| 2340 | - assert!( | ||
| 2341 | - !poc_type.is_empty() && poc_type.iter().all(|&t| t == 2), | ||
| 2342 | - "POC type 2 in the SPS: {poc_type:?}" | ||
| 2343 | - ); | ||
| 2344 | - assert!( | ||
| 2345 | - values(&fields, "pic_order_cnt_lsb").is_empty(), | ||
| 2346 | - "no POC lsb under type 2" | ||
| 2347 | - ); | ||
| 2348 | - assert!( | ||
| 2349 | - values(&fields, "level_idc").iter().all(|&l| l == 30), | ||
| 2350 | - "640x360@30 is level 3.0" | ||
| 2351 | - ); | ||
| 2352 | -} | ||
| 2353 | - | ||
| 2354 | -#[test] | ||
| 2355 | -fn hevc_slice_headers_count_pocs_for_stateful_decoders() { | ||
| 2356 | - let frames = 64u32; | ||
| 2357 | - let (path, fields) = slice_counters(EncCodec::H265, 640, 360, frames); | ||
| 2358 | - if fields.is_empty() { | ||
| 2359 | - return; | ||
| 2360 | - } | ||
| 2361 | - let lsb = values(&fields, "slice_pic_order_cnt_lsb"); | ||
| 2362 | - assert_eq!( | ||
| 2363 | - lsb.len(), | ||
| 2364 | - frames as usize - 1, | ||
| 2365 | - "every non-IDR slice carries a POC lsb in {}", | ||
| 2366 | - path.display() | ||
| 2367 | - ); | ||
| 2368 | - let log2_max = values(&fields, "log2_max_pic_order_cnt_lsb_minus4")[0] + 4; | ||
| 2369 | - let max_lsb = 1i64 << log2_max; | ||
| 2370 | - let expected: Vec<i64> = (1..frames as i64).map(|n| n % max_lsb).collect(); | ||
| 2371 | - assert_eq!(lsb, expected, "POC lsb steps +1 mod {max_lsb}"); | ||
| 2372 | -} | ||
| 2373 | - | ||
| 2374 | -// --------------------------------------------------------------------------- | ||
| 2375 | -// Rate control: achieved bitrate against the request, and PSNR at that rate | ||
| 2376 | -// --------------------------------------------------------------------------- | ||
| 2377 | - | ||
| 2378 | -/// Write 8-bit 4:2:0 frames as a y4m file, the reference ffmpeg compares with. | ||
| 2379 | -fn write_y4m_8(path: &Path, frames: &[I420], fps: u32) -> bool { | ||
| 2380 | - use std::io::Write; | ||
| 2381 | - let Some(first) = frames.first() else { | ||
| 2382 | - return false; | ||
| 2383 | - }; | ||
| 2384 | - let Ok(file) = std::fs::File::create(path) else { | ||
| 2385 | - return false; | ||
| 2386 | - }; | ||
| 2387 | - let mut out = std::io::BufWriter::new(file); | ||
| 2388 | - let header = format!( | ||
| 2389 | - "YUV4MPEG2 W{} H{} F{fps}:1 Ip A1:1 C420jpeg\n", | ||
| 2390 | - first.width, first.height | ||
| 2391 | - ); | ||
| 2392 | - if out.write_all(header.as_bytes()).is_err() { | ||
| 2393 | - return false; | ||
| 2394 | - } | ||
| 2395 | - for f in frames { | ||
| 2396 | - if out.write_all(b"FRAME\n").is_err() | ||
| 2397 | - || out.write_all(&f.y).is_err() | ||
| 2398 | - || out.write_all(&f.u).is_err() | ||
| 2399 | - || out.write_all(&f.v).is_err() | ||
| 2400 | - { | ||
| 2401 | - return false; | ||
| 2402 | - } | ||
| 2403 | - } | ||
| 2404 | - out.flush().is_ok() | ||
| 2405 | -} | ||
| 2406 | - | ||
| 2407 | -/// Average PSNR (dB) of a raw elementary stream against its source y4m. | ||
| 2408 | -fn psnr_of_elementary(coded: &Path, format: &str, source: &Path, fps: u32) -> Option<f64> { | ||
| 2409 | - let rate = fps.to_string(); | ||
| 2410 | - let out = ec_testkit::ffmpeg() | ||
| 2411 | - .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"]) | ||
| 2412 | - .arg(coded) | ||
| 2413 | - .args(["-r", &rate, "-i"]) | ||
| 2414 | - .arg(source) | ||
| 2415 | - .args(["-lavfi", "psnr", "-f", "null", "-"]) | ||
| 2416 | - .output() | ||
| 2417 | - .ok()?; | ||
| 2418 | - let text = String::from_utf8_lossy(&out.stderr); | ||
| 2419 | - let field = text.split("average:").nth(1)?; | ||
| 2420 | - field | ||
| 2421 | - .split_whitespace() | ||
| 2422 | - .next()? | ||
| 2423 | - .parse::<f64>() | ||
| 2424 | - .ok() | ||
| 2425 | - .filter(|v| v.is_finite()) | ||
| 2426 | -} | ||
| 2427 | - | ||
| 2428 | -/// One CBR encode of `frames` at `bitrate`: the stream, and the bits per second | ||
| 2429 | -/// it actually spent over the clip. | ||
| 2430 | -fn cbr_encode( | ||
| 2431 | - display: &Rc<Display>, | ||
| 2432 | - codec: EncCodec, | ||
| 2433 | - (width, height, fps): (u32, u32, u32), | ||
| 2434 | - bitrate: u32, | ||
| 2435 | - frames: &[I420], | ||
| 2436 | -) -> Result<(Vec<u8>, f64), ec_hw::Error> { | ||
| 2437 | - let mut config = EncoderConfig::new(codec, width, height); | ||
| 2438 | - config.framerate = (fps, 1); | ||
| 2439 | - config.gop_size = 30; | ||
| 2440 | - config.bitrate = bitrate; | ||
| 2441 | - config.rate_control = RateControlMode::ConstantBitrate; | ||
| 2442 | - let mut encoder = Encoder::new(display, config)?; | ||
| 2443 | - let mut out = Vec::new(); | ||
| 2444 | - for (t, frame) in frames.iter().enumerate() { | ||
| 2445 | - let coded = encoder.encode( | ||
| 2446 | - frame, | ||
| 2447 | - FrameMetadata { | ||
| 2448 | - timestamp: t as i64, | ||
| 2449 | - force_keyframe: false, | ||
| 2450 | - }, | ||
| 2451 | - )?; | ||
| 2452 | - out.extend_from_slice(&coded.data); | ||
| 2453 | - } | ||
| 2454 | - let delivered = out.len() as f64 * 8.0 * f64::from(fps) / frames.len() as f64; | ||
| 2455 | - Ok((out, delivered)) | ||
| 2456 | -} | ||
| 2457 | - | ||
| 2458 | -/// CBR must land within +/-5% of the request on every codec, clip and rate, | ||
| 2459 | -/// and the PSNR it reaches at that rate is printed for the report. | ||
| 2460 | -#[test] | ||
| 2461 | -fn cbr_lands_within_five_percent_of_the_request() { | ||
| 2462 | - let Some(display) = display() else { return }; | ||
| 2463 | - // 8 s: a 2 s clip also carries the start-up of the rate controller, which | ||
| 2464 | - // is measured apart from the steady-state rate the request is about. | ||
| 2465 | - let (width, height, fps, frames) = (1280u32, 720u32, 30u32, 240u32); | ||
| 2466 | - let dir = std::env::temp_dir().join("ec-hw-rc-measure"); | ||
| 2467 | - std::fs::create_dir_all(&dir).expect("temp dir"); | ||
| 2468 | - | ||
| 2469 | - // Two clips: a synthetic moving box, and ffmpeg's testsrc2 (the content the | ||
| 2470 | - // edith measurements used), both generated here so nothing depends on a | ||
| 2471 | - // personal library. | ||
| 2472 | - let synthetic: Vec<I420> = (0..frames) | ||
| 2473 | - .map(|t| source_frame(width, height, t)) | ||
| 2474 | - .collect(); | ||
| 2475 | - let synthetic_y4m = dir.join("cbr-synthetic.y4m"); | ||
| 2476 | - assert!(write_y4m_8(&synthetic_y4m, &synthetic, fps), "write source"); | ||
| 2477 | - let testsrc_y4m = dir.join("cbr-testsrc2.y4m"); | ||
| 2478 | - let generated = ec_testkit::ffmpeg() | ||
| 2479 | - .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) | ||
| 2480 | - .arg(format!("testsrc2=size={width}x{height}:rate={fps}")) | ||
| 2481 | - .args(["-frames:v", &frames.to_string(), "-pix_fmt", "yuv420p"]) | ||
| 2482 | - .arg(&testsrc_y4m) | ||
| 2483 | - .status() | ||
| 2484 | - .is_ok_and(|s| s.success()); | ||
| 2485 | - let testsrc = generated | ||
| 2486 | - .then(|| raw_frames(&testsrc_y4m, width, height, frames)) | ||
| 2487 | - .flatten() | ||
| 2488 | - .expect("ffmpeg generates testsrc2"); | ||
| 2489 | - let clips: [(&str, Vec<I420>, PathBuf); 2] = [ | ||
| 2490 | - ("moving box", synthetic, synthetic_y4m), | ||
| 2491 | - ("testsrc2", testsrc, testsrc_y4m), | ||
| 2492 | - ]; | ||
| 2493 | - let mut failures = Vec::new(); | ||
| 2494 | - println!("CBR, {width}x{height} {fps} fps, {frames} frames:"); | ||
| 2495 | - for (codec, name, format) in [ | ||
| 2496 | - (EncCodec::H264, "H.264", "h264"), | ||
| 2497 | - (EncCodec::H265, "HEVC", "hevc"), | ||
| 2498 | - (EncCodec::Av1, "AV1", "obu"), | ||
| 2499 | - ] { | ||
| 2500 | - for (clip_name, pictures, source) in &clips { | ||
| 2501 | - for target in [1_000_000u32, 3_000_000, 8_000_000] { | ||
| 2502 | - let (stream, delivered) = | ||
| 2503 | - match cbr_encode(&display, codec, (width, height, fps), target, pictures) { | ||
| 2504 | - Ok(encoded) => encoded, | ||
| 2505 | - Err(e) => panic!("{name} {clip_name} at {target} bps: encode failed ({e})"), | ||
| 2506 | - }; | ||
| 2507 | - let coded = dir.join(format!( | ||
| 2508 | - "{name}-{}-{target}.{format}", | ||
| 2509 | - clip_name.replace(' ', "-") | ||
| 2510 | - )); | ||
| 2511 | - std::fs::write(&coded, &stream).expect("write stream"); | ||
| 2512 | - let db = psnr_of_elementary(&coded, format, source, fps).unwrap_or(f64::NAN); | ||
| 2513 | - let error = delivered / f64::from(target) - 1.0; | ||
| 2514 | - println!( | ||
| 2515 | - " {name:<6} {clip_name:<12} target {:>5} kbps -> {:>6.0} kbps ({:+5.1}%), {db:.2} dB", | ||
| 2516 | - target / 1000, | ||
| 2517 | - delivered / 1000.0, | ||
| 2518 | - error * 100.0 | ||
| 2519 | - ); | ||
| 2520 | - if error.abs() > 0.05 { | ||
| 2521 | - failures.push(format!( | ||
| 2522 | - "{name} {clip_name} at {target} bps: {:+.1}%", | ||
| 2523 | - error * 100.0 | ||
| 2524 | - )); | ||
| 2525 | - } | ||
| 2526 | - } | ||
| 2527 | - } | ||
| 2528 | - } | ||
| 2529 | - assert!(failures.is_empty(), "outside +/-5%: {failures:?}"); | ||
| 2530 | -} | ||
| 2531 | - | ||
| 2532 | -/// Encoding an imported DMA-BUF must give the bytes the CPU path gives for the | ||
| 2533 | -/// same pixels: the import is only a different way of handing over the source. | ||
| 2534 | -// --------------------------------------------------------------------------- | ||
| 2535 | -// Broken streams: an inter picture whose references were never decoded | ||
| 2536 | -// --------------------------------------------------------------------------- | ||
| 2537 | - | ||
| 2538 | -/// The OBUs of an AV1 temporal unit, as whole byte slices (each with its header). | ||
| 2539 | -fn av1_obus(tu: &[u8]) -> Vec<&[u8]> { | ||
| 2540 | - let mut out = Vec::new(); | ||
| 2541 | - let mut i = 0usize; | ||
| 2542 | - while i < tu.len() { | ||
| 2543 | - let header = tu[i]; | ||
| 2544 | - let ext = usize::from((header >> 2) & 1); | ||
| 2545 | - if (header >> 1) & 1 == 0 { | ||
| 2546 | - break; // no obu_size: the rest of the unit is one OBU | ||
| 2547 | - } | ||
| 2548 | - let mut size = 0usize; | ||
| 2549 | - let mut pos = i + 1 + ext; | ||
| 2550 | - for shift in (0..64).step_by(7) { | ||
| 2551 | - let Some(&byte) = tu.get(pos) else { return out }; | ||
| 2552 | - pos += 1; | ||
| 2553 | - size |= usize::from(byte & 0x7f) << shift; | ||
| 2554 | - if byte & 0x80 == 0 { | ||
| 2555 | - break; | ||
| 2556 | - } | ||
| 2557 | - } | ||
| 2558 | - let end = (pos + size).min(tu.len()); | ||
| 2559 | - out.push(&tu[i..end]); | ||
| 2560 | - i = end; | ||
| 2561 | - } | ||
| 2562 | - out | ||
| 2563 | -} | ||
| 2564 | - | ||
| 2565 | -/// The Annex B NAL units of an access unit, without their start codes. | ||
| 2566 | -fn annexb_nals(au: &[u8]) -> Vec<&[u8]> { | ||
| 2567 | - let mut starts = Vec::new(); | ||
| 2568 | - let mut i = 0usize; | ||
| 2569 | - while i + 3 <= au.len() { | ||
| 2570 | - if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { | ||
| 2571 | - starts.push(i + 3); | ||
| 2572 | - i += 3; | ||
| 2573 | - } else { | ||
| 2574 | - i += 1; | ||
| 2575 | - } | ||
| 2576 | - } | ||
| 2577 | - starts | ||
| 2578 | - .iter() | ||
| 2579 | - .enumerate() | ||
| 2580 | - .map(|(n, &start)| { | ||
| 2581 | - let end = starts.get(n + 1).map_or(au.len(), |&next| next - 3); | ||
| 2582 | - let mut nal = &au[start..end]; | ||
| 2583 | - while let [rest @ .., 0] = nal { | ||
| 2584 | - nal = rest; // trailing zeros belong to the next start code | ||
| 2585 | - } | ||
| 2586 | - nal | ||
| 2587 | - }) | ||
| 2588 | - .collect() | ||
| 2589 | -} | ||
| 2590 | - | ||
| 2591 | -/// A stream that starts at an inter picture: the parameter sets of the first | ||
| 2592 | -/// access unit, then the access unit that follows it, with the picture that | ||
| 2593 | -/// would have filled its references (the first access unit) left out. | ||
| 2594 | -fn broken_gop(codec: Codec, data: &[u8]) -> Option<Vec<u8>> { | ||
| 2595 | - let mut stream = Vec::new(); | ||
| 2596 | - match codec { | ||
| 2597 | - Codec::Av1 => { | ||
| 2598 | - let units = split_ivf(data); | ||
| 2599 | - // The sequence header OBU, which the first temporal unit carries. | ||
| 2600 | - let seq = av1_obus(units.first()?) | ||
| 2601 | - .into_iter() | ||
| 2602 | - .find(|obu| (obu[0] >> 3) & 0xf == 1)?; | ||
| 2603 | - stream.extend_from_slice(seq); | ||
| 2604 | - stream.extend_from_slice(units.get(1)?); | ||
| 2605 | - } | ||
| 2606 | - Codec::Vp9 => { | ||
| 2607 | - // VP9 carries its parameters in the frame header: the inter frame | ||
| 2608 | - // alone is the broken stream. | ||
| 2609 | - stream.extend_from_slice(split_ivf(data).get(1)?); | ||
| 2610 | - } | ||
| 2611 | - Codec::H264 | Codec::H265 => { | ||
| 2612 | - let units = split_access_units(data, codec); | ||
| 2613 | - let is_parameter_set = |nal: &[u8]| { | ||
| 2614 | - let t = match codec { | ||
| 2615 | - Codec::H264 => nal[0] & 0x1f, | ||
| 2616 | - _ => (nal[0] >> 1) & 0x3f, | ||
| 2617 | - }; | ||
| 2618 | - match codec { | ||
| 2619 | - Codec::H264 => t == 7 || t == 8, | ||
| 2620 | - _ => (32..=34).contains(&t), | ||
| 2621 | - } | ||
| 2622 | - }; | ||
| 2623 | - for nal in annexb_nals(units.first()?) { | ||
| 2624 | - if is_parameter_set(nal) { | ||
| 2625 | - stream.extend_from_slice(&[0, 0, 0, 1]); | ||
| 2626 | - stream.extend_from_slice(nal); | ||
| 2627 | - } | ||
| 2628 | - } | ||
| 2629 | - stream.extend_from_slice(units.get(1)?); | ||
| 2630 | - } | ||
| 2631 | - } | ||
| 2632 | - Some(stream) | ||
| 2633 | -} | ||
| 2634 | - | ||
| 2635 | -/// Each codec's broken GOP is refused with an error at the first access unit | ||
| 2636 | -/// that needs the missing picture, and never produces a picture. Refusing an | ||
| 2637 | -/// inter frame whose references were never filled is what the software | ||
| 2638 | -/// decoders do (ec-av1: "no saved CDF state"). | ||
| 2639 | -#[test] | ||
| 2640 | -fn a_broken_gop_is_refused_on_every_codec() { | ||
| 2641 | - let Some(display) = display() else { return }; | ||
| 2642 | - let cases = [ | ||
| 2643 | - (Codec::Av1, "av1-1080p-23.976-8bit.ivf"), | ||
| 2644 | - (Codec::Vp9, "vp9-1080p-23.976-8bit.ivf"), | ||
| 2645 | - (Codec::H264, "h264-bframes-320.264"), | ||
| 2646 | - (Codec::H265, "hevc-bframes-320.265"), | ||
| 2647 | - ]; | ||
| 2648 | - for (codec, name) in cases { | ||
| 2649 | - let path = ec_testkit::fixture(&format!("bitstreams/{name}")); | ||
| 2650 | - let data = std::fs::read(&path).expect("fixture is readable"); | ||
| 2651 | - let stream = broken_gop(codec, &data).expect("the fixture has a second access unit"); | ||
| 2652 | - let mut decoder = Decoder::new(&display, codec).expect("decoder"); | ||
| 2653 | - let refusal = decoder.decode(&stream, 0).err().map(|e| e.to_string()); | ||
| 2654 | - let mut pictures = 0usize; | ||
| 2655 | - while decoder.next_frame().is_some() { | ||
| 2656 | - pictures += 1; | ||
| 2657 | - } | ||
| 2658 | - assert!( | ||
| 2659 | - refusal.is_some(), | ||
| 2660 | - "{codec:?} {name}: the broken GOP decoded without an error ({pictures} pictures)" | ||
| 2661 | - ); | ||
| 2662 | - assert_eq!( | ||
| 2663 | - pictures, 0, | ||
| 2664 | - "{codec:?} {name}: a picture came out of a broken GOP" | ||
| 2665 | - ); | ||
| 2666 | - println!("{codec:?} {name}: refused: {}", refusal.unwrap_or_default()); | ||
| 2667 | - } | ||
| 2668 | -} | ||
| 2669 | - | ||
| 2670 | -#[test] | ||
| 2671 | -fn h264_encode_decodes_with_no_reorder_delay() { | ||
| 2672 | - let Some(display) = display() else { return }; | ||
| 2673 | - let mut config = EncoderConfig::new(EncCodec::H264, 1280, 720); | ||
| 2674 | - config.framerate = (30, 1); | ||
| 2675 | - config.gop_size = 30; | ||
| 2676 | - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; | ||
| 2677 | - let mut encoder = Encoder::new(&display, config).expect("encoder"); | ||
| 2678 | - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder"); | ||
| 2679 | - for t in 0..10 { | ||
| 2680 | - let meta = FrameMetadata { | ||
| 2681 | - timestamp: i64::from(t), | ||
| 2682 | - force_keyframe: false, | ||
| 2683 | - }; | ||
| 2684 | - let unit = encoder | ||
| 2685 | - .encode(&source_frame(1280, 720, t), meta) | ||
| 2686 | - .expect("encode"); | ||
| 2687 | - decoder.decode(&unit.data, i64::from(t)).expect("decode"); | ||
| 2688 | - assert!(decoder.next_frame().is_some(), "frame {t} held back"); | ||
| 2689 | - } | ||
| 2690 | -} | ||