diff --git a/crates/ec-hw/tests/gpu.rs b/crates/ec-hw/tests/gpu.rs index da5d467c..f1605654 100644 --- a/crates/ec-hw/tests/gpu.rs +++ b/crates/ec-hw/tests/gpu.rs @@ -8,29 +8,22 @@ use std::io::Read; use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::process::Stdio; use std::rc::Rc; -use std::time::Instant; use ec_hw::{ - Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, H264Profile, I420, + Codec, Decoder, EncCodec, Encoder, EncoderConfig, Frame, FrameMetadata, I420, I420_16, RateControlMode, }; use ec_va::Display; +mod common; +use common::display; + /// Frames compared per fixture: enough to cover several GOPs and any /// reordering, few enough to keep the suite under a minute. const FRAMES: usize = 24; -fn display() -> Option> { - match ec_va::open() { - Ok(display) => Some(display), - Err(e) => { - eprintln!("skipped: no VA display ({e})"); - None - } - } -} /// The software reference: ffmpeg decoding the same file to raw planes. struct Reference { @@ -378,25 +371,6 @@ fn ten_bit(pattern: &str, codec: &str) -> Vec { .collect() } -/// The selection must not depend on where the repository is checked out. -#[test] -fn fixture_selection_ignores_the_checkout_path() { - for p in eight_bit("ivf", "av1") { - let name = name_of(&p); - assert!( - name.starts_with("av1") && !name.contains("10bit"), - "{name} is not an 8-bit AV1 fixture" - ); - } - for p in ten_bit("ivf", "vp9") { - let name = name_of(&p); - assert!( - name.starts_with("vp9") && name.contains("10bit"), - "{name} is not a 10-bit VP9 fixture" - ); - } -} - #[test] fn h264_matches_ffmpeg() { compare_against_ffmpeg(&ec_testkit::fixtures("bitstreams", "264"), Codec::H264, false); @@ -430,68 +404,11 @@ fn hevc_10bit_decodes_to_p010() { compare_against_ffmpeg(&files, Codec::H265, true); } -#[test] -fn vp9_matches_ffmpeg() { - compare_against_ffmpeg(&eight_bit("ivf", "vp9"), Codec::Vp9, false); -} - -#[test] -fn vp9_10bit_matches_ffmpeg() { - compare_against_ffmpeg(&ten_bit("ivf", "vp9"), Codec::Vp9, true); -} - #[test] fn av1_matches_ffmpeg() { compare_against_ffmpeg(&eight_bit("ivf", "av1"), Codec::Av1, false); } -#[test] -fn av1_10bit_matches_ffmpeg() { - compare_against_ffmpeg(&ten_bit("ivf", "av1"), Codec::Av1, true); -} - -/// Every "not supported" this crate says has to be a fact about the driver, not -/// a string. This GPU decodes VP9 profiles 0 and 2 and AV1 profiles 0 and 2 — -/// so the 4:4:4 fixtures must come back as a typed refusal naming the profile, -/// and the capability report must agree that the profile is absent. -#[test] -fn unsupported_profiles_are_refused_with_a_reason() { - let Some(display) = display() else { return }; - let caps = ec_va::CapReport::probe(&display).expect("caps probe"); - for (file, codec, absent) in [ - ( - "vp9-profile1-444.ivf", - Codec::Vp9, - ec_va::caps::Profile::VP9Profile1, - ), - ( - "av1-profile1-444.ivf", - Codec::Av1, - ec_va::caps::Profile::AV1Profile1, - ), - ] { - let path = ec_testkit::fixture(&format!("bitstreams/{file}")); - assert!( - !caps.supports(absent, ec_va::caps::Entrypoint::VLD), - "{absent:?} is in fact supported — the refusal below would be a bug" - ); - let data = std::fs::read(&path).expect("fixture is readable"); - let mut decoder = Decoder::new(&display, codec).expect("decoder opens"); - let err = decode_stream(&mut decoder, codec, &data, 1, |_| {}) - .expect_err("a 4:4:4 stream must be refused"); - let message = err.to_string(); - assert!( - matches!(err, ec_hw::Error::Unsupported { .. }), - "{file}: expected a typed refusal, got {message}" - ); - println!("{file}: {message}"); - } -} - -// --------------------------------------------------------------------------- -// Encoding -// --------------------------------------------------------------------------- - /// A moving synthetic frame: a gradient with a box that travels, so motion /// compensation has something to find and a static-image encoder cannot cheat. fn source_frame(width: u32, height: u32, t: u32) -> I420 { @@ -629,295 +546,11 @@ fn h264_encode_round_trips_through_ffmpeg() { round_trip(EncCodec::H264, 640, 480, 30.0); } -/// Each selectable H.264 profile: the driver encodes it, ffprobe reports the -/// profile the SPS signals, and ffmpeg decodes the stream with no error output -/// and the picture matches the source. -fn h264_profile_round_trip(profile: H264Profile, ffprobe_name: &str) { - let Some(display) = display() else { return }; - let (width, height, frames) = (640u32, 480u32, 12u32); - let mut config = EncoderConfig::new(EncCodec::H264, width, height).h264_profile(profile); - config.gop_size = 30; - config.rate_control = RateControlMode::ConstantQp { qp: 26 }; - let mut encoder = Encoder::new(&display, config).expect("encoder"); - let mut stream = Vec::new(); - for t in 0..frames { - let coded = encoder - .encode( - &source_frame(width, height, t), - FrameMetadata { - timestamp: i64::from(t), - force_keyframe: false, - }, - ) - .expect("encode"); - stream.extend_from_slice(&coded.data); - } - - let dir = std::env::temp_dir().join(format!("ec-hw-h264-{profile:?}")); - std::fs::create_dir_all(&dir).expect("temp dir"); - let path = dir.join("out.264"); - std::fs::write(&path, &stream).expect("write bitstream"); - - let probe = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "v:0", - "-show_entries", - "stream=profile", - "-of", - "csv=p=0", - ]) - .arg(&path) - .output() - .expect("ffprobe runs"); - let got = String::from_utf8_lossy(&probe.stdout).trim().to_string(); - assert_eq!( - got, ffprobe_name, - "{profile:?}: ffprobe reads the SPS profile" - ); - - // Strict decode: any warning or error on stderr fails the test. - let decode = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "warning", "-i"]) - .arg(&path) - .args(["-f", "null", "-"]) - .output() - .expect("ffmpeg runs"); - assert!( - decode.status.success() && decode.stderr.is_empty(), - "{profile:?}: ffmpeg reports {}", - String::from_utf8_lossy(&decode.stderr) - ); - - let mut reference = Reference::open(&path, width, height, false).expect("ffmpeg runs"); - let mut worst = f64::INFINITY; - for t in 0..frames { - let got = reference.next(width, height).expect("decoded picture"); - worst = worst.min(psnr( - &got, - &Planes::from_8bit(&source_frame(width, height, t)), - )); - } - println!("{profile:?}: {} bytes, worst {worst:.1} dB", stream.len()); - assert!(worst >= 30.0, "{profile:?}: worst frame {worst:.1} dB"); -} - -#[test] -fn h264_constrained_baseline_encodes_and_decodes() { - h264_profile_round_trip(H264Profile::ConstrainedBaseline, "Constrained Baseline"); -} - -#[test] -fn h264_main_profile_has_no_high_syntax_and_decodes() { - h264_profile_round_trip(H264Profile::Main, "Main"); -} - -#[test] -fn h264_high_profile_still_decodes() { - h264_profile_round_trip(H264Profile::High, "High"); -} - #[test] fn hevc_encode_round_trips_through_ffmpeg() { round_trip(EncCodec::H265, 640, 480, 30.0); } -/// 1916x1080 is the shape that broke the incumbent HEVC encoder: the coded size -/// is 1920x1088, and only the conformance window brings it back. -#[test] -fn hevc_encode_honours_the_conformance_window() { - round_trip(EncCodec::H265, 1916, 1080, 30.0); -} - -/// What this crate encodes, its own hardware decoder must decode. -#[test] -fn our_encoder_and_our_decoder_agree() { - let Some(display) = display() else { return }; - for (enc, dec) in [(EncCodec::H264, Codec::H264), (EncCodec::H265, Codec::H265)] { - let stream = encode_stream(&display, enc, 640, 480, 12).expect("encode"); - let mut decoder = Decoder::new(&display, dec).expect("decoder opens"); - let mut worst = f64::INFINITY; - let mut count = 0u32; - decode_stream(&mut decoder, dec, &stream, 12, |frame| { - let got = Planes::from_8bit(&frame.to_i420().expect("readback")); - let want = Planes::from_8bit(&source_frame(640, 480, count)); - worst = worst.min(psnr(&got, &want)); - count += 1; - }) - .expect("decode"); - assert_eq!(count, 12, "{enc:?}: decoded {count} of 12 frames"); - println!("{enc:?} -> our decoder: {count} frames, worst {worst:.1} dB vs source"); - assert!(worst >= 30.0, "{enc:?}: worst {worst:.1} dB"); - } -} - -/// A decoded surface goes straight into an encoder with no `to_i420` -/// read-back, and what comes out is not measurably different from the -/// CPU-path baseline (decode -> `to_i420` -> `encode`) of the same frames. -/// -/// 1920x1080 is the size on purpose: H.264's 16-block and HEVC's 32-block -/// rounding both land on the same 1920x1088 coded size for it, so the -/// decoder's surfaces satisfy `encode_frame`'s coded-size check against -/// either target codec without a second fixture. -/// `EncoderConfig::colour` reaches the VUI of both codecs' packed SPS: an -/// export with a colour description survives ffprobe reading it back, and -/// leaving it unset keeps today's behaviour (no `video_signal_type`, -/// deterministically — two encodes of the same picture with no colour set -/// come back byte for byte identical). -#[test] -fn colour_description_reaches_the_vui() { - let Some(display) = display() else { return }; - let (width, height) = (640u32, 480u32); - let dir = std::env::temp_dir().join("ec-hw-colour-vui"); - std::fs::create_dir_all(&dir).expect("temp dir"); - - let encode_one = |colour: Option<(u8, u8, u8, bool)>, name: &str| -> (PathBuf, Vec) { - let mut cfg = EncoderConfig::new(EncCodec::H265, width, height); - cfg.rate_control = RateControlMode::ConstantQp { qp: 26 }; - if let Some((primaries, transfer, matrix, full_range)) = colour { - cfg = cfg.colour(primaries, transfer, matrix, full_range); - } - let mut enc = Encoder::new(&display, cfg).expect("encoder opens"); - let coded = enc - .encode( - &source_frame(width, height, 0), - FrameMetadata { - timestamp: 0, - force_keyframe: true, - }, - ) - .expect("encode"); - let path = dir.join(name); - std::fs::write(&path, &coded.data).expect("write bitstream"); - (path, coded.data) - }; - let probe = |path: &Path| -> String { - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "v:0", - "-show_entries", - "stream=color_primaries,color_transfer,color_space", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .expect("ffprobe runs"); - String::from_utf8_lossy(&out.stdout).trim().to_string() - }; - - // Pinned default case: no colour set, twice, must match exactly. - let (default_path, default_bytes) = encode_one(None, "default-a.265"); - let (_, default_bytes2) = encode_one(None, "default-b.265"); - assert_eq!( - default_bytes, default_bytes2, - "no colour set: two encodes of the same picture must be byte-identical" - ); - let default_probe = probe(&default_path); - println!("no colour set: ffprobe sees `{default_probe}`"); - assert!( - !default_probe.contains("bt2020"), - "no colour set should not read back as BT.2020: `{default_probe}`" - ); - - // BT.2020 / PQ / BT.2020 non-constant luminance (H.273 9/16/9). - let (bt2020_path, _) = encode_one(Some((9, 16, 9, false)), "bt2020.265"); - // ffprobe's csv reorders these as color_space,color_transfer,color_primaries - // regardless of the -show_entries order given above. - let got = probe(&bt2020_path); - assert_eq!( - got, "bt2020nc,smpte2084,bt2020", - "ffprobe on the BT.2020 stream" - ); -} - -/// AV1 hardware encode, proved by two independent decoders. -/// -/// The reconstruction inside the GPU is not observable from here, so what is -/// asserted is that the coded stream means the same thing to two decoders that -/// share no code: ffmpeg's libdav1d and this family's own `ec-av1`. Every -/// shown frame is compared sample for sample — a header field that disagrees -/// with what the hardware coded shows up as a mismatch in one of them long -/// before it shows up as a quality number. -/// -/// The path was refused in-tree until 2026-09-07: a probe on 2026-08-14 took -/// the GPU down ("the CS has cancelled because the context is lost"). That -/// refusal is retired by measurement, not by opinion — ffmpeg's own -/// `av1_vaapi` encodes on this driver (mesa 26.1.8, gfx1200), and the -/// parameters below are the recipe it uses. -#[test] -fn av1_encode_agrees_between_two_decoders() { - let Some(display) = display() else { return }; - let dir = std::env::temp_dir().join("ec-hw-av1-encode"); - let _ = std::fs::create_dir_all(&dir); - for (width, height, frames) in [(640u32, 384u32, 10u32), (1920, 1080, 10)] { - let data = match encode_stream(&display, EncCodec::Av1, width, height, frames) { - Ok(data) => data, - Err(e) => { - eprintln!("skipped: AV1 encode unavailable ({e})"); - return; - } - }; - let path = dir.join(format!("hw-{width}x{height}.obu")); - std::fs::write(&path, &data).expect("write the coded stream"); - - // Decoder one: this family's software AV1 decoder, on the raw OBUs. - let ours = ec_av1::stream::decode_stream(&data) - .unwrap_or_else(|e| panic!("ec-av1 decodes the {width}x{height} hardware stream: {e}")); - assert_eq!( - ours.len(), - frames as usize, - "{width}x{height}: ec-av1 decoded {} of {frames} shown frames", - ours.len() - ); - - // Decoder two: ffmpeg (libdav1d) on the same bytes. - let mut reference = - Reference::open(&path, width, height, false).expect("ffmpeg opens the stream"); - let mut worst = f64::INFINITY; - for (i, picture) in ours.iter().enumerate() { - let theirs = reference - .next(width, height) - .unwrap_or_else(|| panic!("{width}x{height}: ffmpeg has no frame {i}")); - let mine = Planes { - y: picture.y.clone(), - u: picture.u.clone(), - v: picture.v.clone(), - peak: 255.0, - }; - let db = psnr(&mine, &theirs); - assert!( - db.is_infinite(), - "{width}x{height} frame {i}: the two decoders disagree ({db:.2} dB)" - ); - // Agreement alone would also be satisfied by ten grey frames: the - // coded picture has to be the picture that was submitted. - let source = Planes::from_8bit(&source_frame(width, height, i as u32)); - let fidelity = psnr(&mine, &source); - assert!( - fidelity > 30.0, - "{width}x{height} frame {i}: coded {fidelity:.2} dB from the source" - ); - worst = worst.min(fidelity); - } - println!( - "AV1 encode {width}x{height}: {frames} frames, {} bytes, ec-av1 and libdav1d agree \ - sample for sample, worst frame {worst:.2} dB from the source", - data.len() - ); - } -} - -// --------------------------------------------------------------------------- -// 10-bit hardware AV1: his whole AV1 library is yuv420p10le, so an 8-bit-only -// encoder does not serve his files. -// --------------------------------------------------------------------------- - /// stream is neither flat nor 8-bit content dressed up as 10. fn source_frame_16(width: u32, height: u32, t: u32) -> I420_16 { let (w, h) = (width as usize, height as usize); @@ -1087,107 +720,6 @@ fn hevc_main10_encode_round_trips() { ); } -/// 10-bit AV1 hardware encode, proved by two decoders and by two readings of -/// the stream's bit depth. -/// -/// The bit depth is not taken on trust: ffprobe (libdav1d) must call the -/// stream `yuv420p10le`, which is it reading the `high_bitdepth` bit this -/// crate packs into the sequence header, and `ec-av1`'s own decode must -/// produce samples above 255 — an 8-bit stream dressed as 10 fails both. -#[test] -fn av1_10bit_encode_agrees_between_two_decoders() { - let Some(display) = display() else { return }; - let dir = std::env::temp_dir().join("ec-hw-av1-10bit"); - let _ = std::fs::create_dir_all(&dir); - let frames = 10u32; - let (label, _, planes) = ten_bit_source(&dir, frames); - let (width, height) = (planes[0].width, planes[0].height); - let data = match encode_stream_16( - &display, - EncCodec::Av1, - &planes, - 90, - RateControlMode::ConstantQp { qp: 90 }, - ) { - Ok(data) => data, - Err(e) => { - eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"); - return; - } - }; - let path = dir.join("hw-10bit.obu"); - std::fs::write(&path, &data).expect("write the coded stream"); - - assert_eq!( - ffprobe_pix_fmt(&path, "obu").as_deref(), - Some("yuv420p10le"), - "the coded stream's sequence header does not say 10-bit" - ); - - let ten_bit_h264 = EncoderConfig::new(EncCodec::H264, width, height).ten_bit(); - assert!(Encoder::new(&display, ten_bit_h264).is_err()); - let mut config = EncoderConfig::new(EncCodec::Av1, width, height).ten_bit(); - config.rate_control = RateControlMode::ConstantQp { qp: 90 }; - let mut ten = Encoder::new(&display, config).expect("a 10-bit AV1 encoder"); - assert!( - ten.encode(&source_frame(width, height, 0), FrameMetadata::default()) - .is_err(), - "8-bit pixels went into a 10-bit encoder" - ); - - let ours = ec_av1::stream::decode_stream(&data) - .unwrap_or_else(|e| panic!("ec-av1 decodes the 10-bit hardware stream: {e}")); - assert_eq!( - ours.len(), - planes.len(), - "ec-av1 decoded {} of {frames} frames", - ours.len() - ); - let peak = ours - .iter() - .flat_map(|p| p.y.iter()) - .copied() - .max() - .unwrap_or(0); - assert!( - peak > 255, - "every decoded luma sample fits in 8 bits (peak {peak})" - ); - - let mut reference = - Reference::open(&path, width, height, true).expect("ffmpeg opens the stream"); - let mut worst = f64::INFINITY; - for (i, picture) in ours.iter().enumerate() { - let theirs = reference - .next(width, height) - .unwrap_or_else(|| panic!("ffmpeg has no frame {i}")); - let mine = Planes { - y: picture.y.clone(), - u: picture.u.clone(), - v: picture.v.clone(), - peak: 1023.0, - }; - let db = psnr(&mine, &theirs); - assert!( - db.is_infinite(), - "frame {i}: the two decoders disagree ({db:.2} dB)" - ); - let source = Planes::from_16bit(&planes[i]); - let fidelity = psnr(&mine, &source); - assert!( - fidelity > 30.0, - "frame {i}: coded {fidelity:.2} dB from the 10-bit source" - ); - worst = worst.min(fidelity); - } - println!( - "AV1 10-bit encode {width}x{height} ({label}): {frames} frames, {} bytes, pix_fmt \ - yuv420p10le, CQP 90, decoded peak luma {peak}, ec-av1 and libdav1d agree sample for \ - sample, worst frame {worst:.2} dB from the source (10-bit domain)", - data.len() - ); -} - /// Rate control: does an asked-for bitrate come back? /// /// 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 { .filter(|v| v.is_finite()) } -/// What the GPU's AV1 costs against software, on his own content. -/// -/// Four quantisers per encoder on a 1920x1080 crop of a film and of a screen -/// capture, PSNR from ffmpeg, BD-rate over the overlapping quality range -/// against librav1e speed 6 and libaom cpu-used 6. Nothing is asserted about -/// the number — a fixed-function encoder is not a search — but it is measured -/// and printed rather than assumed, and the ladder itself is asserted to be -/// monotone, which is the part a broken parameter set would break. -#[test] -fn av1_encode_bd_row_vs_software() { - let Some(display) = display() else { return }; - // A ladder compared with itself saves nothing: the check on the metric. - let same = [(100.0, 30.0), (200.0, 35.0), (400.0, 40.0)]; - assert!( - bd_rate(&same, &same).abs() < 1e-9, - "bd_rate is not self-zero" - ); - - let dir = std::env::temp_dir().join("ec-hw-av1-bd"); - let _ = std::fs::create_dir_all(&dir); - for (label, source) in real_clips() { - let y4m = dir.join(format!("{label}.y4m")); - let (width, height, frames) = (1920u32, 1080u32, 12u32); - assert!( - extract_y4m(&source, &y4m, width, height, frames), - "{label}: extraction failed" - ); - let planes = raw_frames(&y4m, width, height, frames).expect("frames of the trailer"); - - let mut ours = Vec::new(); - // Descending quantiser: every ladder here is ordered by rising rate. - for qp in [180u32, 140, 100, 60] { - let mut config = EncoderConfig::new(EncCodec::Av1, width, height); - config.framerate = (24, 1); - config.gop_size = 60; - config.rate_control = RateControlMode::ConstantQp { qp }; - let mut encoder = match Encoder::new(&display, config) { - Ok(encoder) => encoder, - Err(e) => { - eprintln!("skipped: AV1 encode unavailable ({e})"); - return; - } - }; - let mut bytes = Vec::new(); - for (i, frame) in planes.iter().enumerate() { - let coded = encoder - .encode( - frame, - FrameMetadata { - timestamp: i as i64, - force_keyframe: false, - }, - ) - .expect("hardware AV1 encode"); - bytes.extend_from_slice(&coded.data); - } - let path = dir.join(format!("{label}-hw-{qp}.obu")); - std::fs::write(&path, &bytes).expect("write"); - if let Some(db) = ffmpeg_psnr(&path, &y4m, true) { - ours.push((bytes.len() as f64 * 8.0 / f64::from(frames), db)); - } - } - let rav1e: Vec<(f64, f64)> = [180u32, 140, 100, 60] - .iter() - .filter_map(|q| { - software_point( - &dir, - &y4m, - label, - "librav1e", - &[ - "-rav1e-params", - &format!("speed=6:quantizer={q}"), - "-g", - "60", - ], - *q, - frames, - ) - }) - .collect(); - let libaom: Vec<(f64, f64)> = [56u32, 44, 32, 20] - .iter() - .filter_map(|crf| { - software_point( - &dir, - &y4m, - label, - "libaom-av1", - &[ - "-cpu-used", - "6", - "-crf", - &crf.to_string(), - "-b:v", - "0", - "-g", - "60", - ], - *crf, - frames, - ) - }) - .collect(); - - for (name, ladder) in [("hw AV1", &ours), ("librav1e", &rav1e), ("libaom", &libaom)] { - println!("{label} {name}: {ladder:?}"); - for pair in ladder.windows(2) { - assert!( - pair[1].0 > pair[0].0 && pair[1].1 > pair[0].1, - "{label} {name}: ladder is not monotone at {pair:?}" - ); - } - } - if ours.len() >= 3 && rav1e.len() >= 3 { - println!( - "BD-rate row: {label}, hw AV1 vs librav1e speed 6: {:+.1}%", - bd_rate(&rav1e, &ours) * 100.0 - ); - } - if ours.len() >= 3 && libaom.len() >= 3 { - println!( - "BD-rate row: {label}, hw AV1 vs libaom cpu-used 6: {:+.1}%", - bd_rate(&libaom, &ours) * 100.0 - ); - } - } -} - -/// One software encoder's rate/PSNR point, or `None` when that encoder is not -/// built into this ffmpeg. -fn software_point( - dir: &Path, - y4m: &Path, - label: &str, - encoder: &str, - args: &[&str], - point: u32, - frames: u32, -) -> Option<(f64, f64)> { - let out = dir.join(format!("{label}-{encoder}-{point}.ivf")); - let _ = std::fs::remove_file(&out); - let status = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "error", "-y", "-i"]) - .arg(y4m) - .args(["-c:v", encoder]) - .args(args) - .arg(&out) - .status() - .ok()?; - if !status.success() { - return None; - } - let bytes = std::fs::metadata(&out).ok()?.len() as f64; - let db = ffmpeg_psnr(&out, y4m, false)?; - Some((bytes * 8.0 / f64::from(frames), db)) -} - /// PSNR of a coded stream against the source, from ffmpeg's own filter. -fn ffmpeg_psnr(coded: &Path, source: &Path, raw_obu: bool) -> Option { - let mut cmd = ec_testkit::ffmpeg(); - cmd.args(["-nostdin", "-v", "info"]); - if raw_obu { - cmd.args(["-f", "obu"]); - } - // Both inputs are pinned to the same rate: a raw OBU stream carries no - // timing, so ffmpeg would otherwise call it 25 fps against a 24 fps - // source and the filter would compare frame i with frame i+k. - let out = cmd - .args(["-r", "24"]) - .arg("-i") - .arg(coded) - .args(["-r", "24"]) - .arg("-i") - .arg(source) - .args(["-lavfi", "psnr", "-f", "null", "-"]) - .output() - .ok()?; - let text = String::from_utf8_lossy(&out.stderr); - let field = text.split("average:").nth(1)?; - field - .split_whitespace() - .next()? - .parse::() - .ok() - .filter(|v| v.is_finite()) -} - /// A 1920x1080 crop of `frames` pictures, as a y4m file the encoders share. fn extract_y4m(source: &Path, out: &Path, width: u32, height: u32, frames: u32) -> bool { let _ = std::fs::remove_file(out); @@ -1568,1123 +913,3 @@ fn real_clips() -> Vec<(&'static str, PathBuf)> { ("sintel 720p", ec_testkit::fixture("open/sintel_trailer-720p.mp4")), ] } - -/// BD-rate of `test` against `reference`, as a fraction (negative = fewer -/// bits for the same quality), integrated piecewise-linearly in -/// `log10(bits per frame)` over the PSNR range the two ladders share. -/// -/// The cubic fit of the original method needs four well-spread points and -/// misbehaves outside them; a trapezoid over the overlap is the honest -/// version of the same integral for ladders this short. -fn bd_rate(reference: &[(f64, f64)], test: &[(f64, f64)]) -> f64 { - let low = reference[0].1.max(test[0].1); - let high = reference[reference.len() - 1].1.min(test[test.len() - 1].1); - if high <= low { - return f64::NAN; - } - // log-rate at a PSNR, linearly interpolated inside the ladder. - let at = |ladder: &[(f64, f64)], db: f64| -> f64 { - for pair in ladder.windows(2) { - let ((r0, d0), (r1, d1)) = (pair[0], pair[1]); - if db >= d0 && db <= d1 { - let t = if (d1 - d0).abs() < f64::EPSILON { - 0.0 - } else { - (db - d0) / (d1 - d0) - }; - return r0.log10() + t * (r1.log10() - r0.log10()); - } - } - if db < ladder[0].1 { - ladder[0].0.log10() - } else { - ladder[ladder.len() - 1].0.log10() - } - }; - let steps = 100; - let mut integral = 0.0; - for i in 0..steps { - let a = low + (high - low) * f64::from(i) / f64::from(steps); - let b = low + (high - low) * f64::from(i + 1) / f64::from(steps); - let da = at(test, a) - at(reference, a); - let db = at(test, b) - at(reference, b); - integral += (da + db) / 2.0 * (b - a); - } - 10f64.powf(integral / (high - low)) - 1.0 -} - -/// Hardware AV1 encode speed at the two sizes his library is in, in frames per -/// second. Real time is 24 fps; the number is printed rather than asserted, -/// since a busy GPU is not a failing encoder. -#[test] -fn av1_encode_speed() { - let Some(display) = display() else { return }; - for (width, height) in [(1920u32, 1080u32), (3840, 1608)] { - let frames = 30u32; - let start = Instant::now(); - match encode_stream(&display, EncCodec::Av1, width, height, frames) { - Ok(data) => { - let secs = start.elapsed().as_secs_f64(); - println!( - "AV1 encode {width}x{height}: {:.1} fps ({frames} frames in {secs:.2} s), {} kbit/frame", - f64::from(frames) / secs, - data.len() * 8 / frames as usize / 1000 - ); - } - Err(e) => { - eprintln!("skipped: AV1 encode unavailable ({e})"); - return; - } - } - } - // 10-bit at the size his own films are in: the depth his library is - // actually stored at, so the fps that matters for a real export. - let planes: Vec = (0..30).map(|t| source_frame_16(3840, 1608, t)).collect(); - let start = Instant::now(); - match encode_stream_16( - &display, - EncCodec::Av1, - &planes, - 90, - RateControlMode::ConstantQp { qp: 90 }, - ) { - Ok(data) => { - let secs = start.elapsed().as_secs_f64(); - println!( - "AV1 encode 3840x1608 10-bit: {:.1} fps ({} frames in {secs:.2} s), {} kbit/frame", - planes.len() as f64 / secs, - planes.len(), - data.len() * 8 / planes.len() / 1000 - ); - } - Err(e) => eprintln!("skipped: 10-bit AV1 encode unavailable ({e})"), - } -} - -// --------------------------------------------------------------------------- -// The four incumbent defects, as tests -// --------------------------------------------------------------------------- - -/// A `frame_num` gap is normal, not corruption. -/// -/// Dropping a reference picture from the middle of a GOP is what a seek, a lost -/// packet or an encoder that skipped a picture all look like. The incumbent -/// stack treated it as an error and fell back to software for the rest of the -/// timeline; here the missing pictures are inferred (8.2.5.2) and decoding -/// carries on in hardware. -#[test] -fn h264_frame_num_gaps_are_synthesised() { - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); - let data = std::fs::read(&path).expect("fixture is readable"); - let units = split_access_units(&data, Codec::H264); - assert!( - units.len() > 8, - "fixture is too short to drop a picture from" - ); - - // Drop two reference pictures from the middle of the first GOP. - let mut kept: Vec<&[u8]> = Vec::new(); - for (i, unit) in units.iter().enumerate() { - if (3..=5).contains(&i) { - continue; - } - kept.push(unit); - } - - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - let mut frames = 0usize; - for (i, unit) in kept.iter().enumerate().take(20) { - if let Err(e) = decoder.decode(unit, i as i64) { - panic!( - "unit {i} failed after {} gap frames: {e}", - decoder.gap_frames_synthesized() - ); - } - while let Some(frame) = decoder.next_frame() { - // The frame is real: reading it back must work, not just arrive. - let planes = frame.to_i420().expect("readback"); - assert_eq!(planes.y.len(), 1920 * 1080); - frames += 1; - } - } - decoder.flush().expect("flush"); - while decoder.next_frame().is_some() { - frames += 1; - } - let synthesised = decoder.gap_frames_synthesized(); - println!("frame_num gap: {frames} frames decoded, {synthesised} pictures inferred"); - assert!(synthesised > 0, "the gap was not detected"); - assert!(frames >= 10, "only {frames} frames survived the gap"); -} - -/// VmRSS in kilobytes, from `/proc/self/status`. -fn rss_kb() -> u64 { - let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); - status - .lines() - .find_map(|line| line.strip_prefix("VmRSS:")) - .and_then(|v| v.split_whitespace().next().map(|n| n.to_string())) - .and_then(|n| n.parse().ok()) - .unwrap_or(0) -} - -/// Decode and read back for longer than any export, and watch the resident set. -/// -/// The incumbent leaked ~3 MB per frame by mapping a VA image and never -/// unmapping it: a 719-frame export lost 2 GB. Every mapping here is a guard -/// that unmaps on drop, and this is the test that says so out loud. -#[test] -fn long_decode_does_not_grow_the_resident_set() { - // VmRSS is a process-wide number and the harness runs every test in this - // binary as a thread of one process: a sibling allocating between the - // baseline and the end reading shows up here as a 200 MB "leak". The - // measurement therefore runs in a child process holding only this test. - if std::env::var_os("EC_HW_RSS_CHILD").is_none() { - let status = Command::new(std::env::current_exe().expect("test binary path")) - .args(["--exact", "long_decode_does_not_grow_the_resident_set"]) - .env("EC_HW_RSS_CHILD", "1") - .status() - .expect("re-run this test in its own process"); - assert!(status.success(), "isolated RSS run failed"); - return; - } - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); - let data = std::fs::read(&path).expect("fixture is readable"); - let units = split_access_units(&data, Codec::H264); - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - - // Warm up first: the first pictures allocate the surface pool and the - // readback image, and that growth is not a leak. - let mut decoded = 0usize; - let mut baseline = 0u64; - let mut readback_ms = 0f64; - let mut pending: Vec = Vec::new(); - let target = 719usize; - 'outer: for pass in 0..16 { - if pass > 0 { - decoder.reset(); - } - for (i, unit) in units.iter().enumerate() { - decoder.decode(unit, i as i64).expect("decode"); - while let Some(frame) = decoder.next_frame() { - // Hold a few frames before reading any back: a decoder that is - // read one frame per submission spends its time waiting for the - // GPU, which measures latency rather than throughput. - pending.push(frame); - if pending.len() < 4 { - continue; - } - let start = std::time::Instant::now(); - for frame in pending.drain(..) { - let planes = frame.to_i420().expect("readback"); - std::hint::black_box(&planes); - decoded += 1; - } - readback_ms += start.elapsed().as_secs_f64() * 1000.0; - if decoded == 60 { - baseline = rss_kb(); - } - if decoded >= target { - break 'outer; - } - } - } - } - decoder.flush().expect("flush"); - let end = rss_kb(); - let delta_mb = (end.saturating_sub(baseline)) as f64 / 1024.0; - println!( - "{decoded} frames decoded and read back: RSS {baseline} -> {end} kB (delta {delta_mb:.1} MB), \ - decode and read back {:.2} ms/frame at 1920x1080", - readback_ms / decoded as f64 - ); - assert!(decoded >= target, "only {decoded} frames decoded"); - assert!( - delta_mb < 50.0, - "resident set grew {delta_mb:.1} MB over {decoded} frames" - ); -} - -/// The zero-copy path: a decoded surface exports as DRM PRIME file descriptors. -/// -/// This is what edith's `engine-hw` imports into gbm, so the fds and the plane -/// layout matter as much as the pixels do. -#[test] -fn frames_export_as_dma_buf() { - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("bitstreams/h264-1080p-23.976-8bit.264"); - let data = std::fs::read(&path).expect("fixture is readable"); - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - let mut exported = 0usize; - decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { - let prime = frame.export_prime().expect("export"); - assert_eq!(prime.fourcc, ec_va::va::VA_FOURCC_NV12); - assert_eq!((prime.width, prime.height), frame.coded_size); - assert!(!prime.objects.is_empty(), "no DRM objects exported"); - assert!(!prime.layers.is_empty(), "no layers exported"); - let planes: usize = prime.layers.iter().map(|l| l.planes.len()).sum(); - assert!( - planes >= 2, - "NV12 needs a luma and a chroma plane, got {planes}" - ); - exported += 1; - }) - .expect("decode"); - assert!(exported >= 1, "nothing was exported"); - println!("DRM PRIME export: {exported} frames"); -} - -// --------------------------------------------------------------------------- -// His library -// --------------------------------------------------------------------------- - -/// Turn any container into an elementary stream ffmpeg and this crate agree on. -/// -/// `frames` bounds the extraction: piping a two-hour 4K film through memory to -/// compare its first five hundred pictures is several gigabytes of nothing. -fn elementary(path: &Path, codec: Codec, frames: usize) -> Option> { - let args: &[&str] = match codec { - Codec::H264 => &["-bsf:v", "h264_mp4toannexb", "-f", "h264"], - Codec::H265 => &["-bsf:v", "hevc_mp4toannexb", "-f", "hevc"], - Codec::Vp9 | Codec::Av1 => &["-f", "ivf"], - }; - let out = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "error", "-i"]) - .arg(path) - .args(["-map", "0:v:0", "-c:v", "copy"]) - // A few more coded pictures than frames wanted: reordering means the - // last few packets have not been shown yet. - .args(["-frames:v", &(frames + 16).to_string()]) - .args(args) - .arg("-") - .stderr(Stdio::null()) - .output() - .ok()?; - (!out.stdout.is_empty()).then_some(out.stdout) -} - -#[test] -fn real_library_spot_check() { - let Some(display) = display() else { return }; - let wanted: Vec<(PathBuf, Codec, bool)> = [ - ("open/sintel_trailer-480p.mp4", Codec::H264, false), - ("open/sintel_trailer-1080p.mp4", Codec::H264, false), - ("derived/sintel720-x265-main10.mp4", Codec::H265, true), - ] - .into_iter() - .map(|(rel, codec, ten_bit)| (ec_testkit::fixture(rel), codec, ten_bit)) - .collect(); - - // 500 frames per file by default; a diagnostic run can ask for fewer. - let limit: usize = std::env::var("EC_HW_SWEEP_FRAMES") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(500); - let mut table = Vec::new(); - for (path, codec, ten_bit) in &wanted { - let path = Path::new(path); - let data = elementary(path, *codec, limit).expect("elementary stream"); - let mut decoder = Decoder::new(&display, *codec).expect("decoder opens"); - let mut reference: Option = None; - let mut worst = f64::INFINITY; - let mut compared = 0usize; - let mut failed: Option = None; - let result = decode_stream(&mut decoder, *codec, &data, limit, |frame| { - let (w, h) = frame.display_size; - let reference = reference - .get_or_insert_with(|| Reference::open(path, w, h, *ten_bit).expect("ffmpeg runs")); - let Some(want) = reference.next(w, h) else { - return; - }; - let got = if *ten_bit { - Planes::from_16bit(&frame.to_i420_16().expect("readback")) - } else { - Planes::from_8bit(&frame.to_i420().expect("readback")) - }; - if got.y.len() != want.y.len() { - failed = Some("frame size disagrees with ffmpeg".to_string()); - return; - } - let db = psnr(&got, &want); - if std::env::var_os("EC_HW_DEBUG").is_some() { - eprintln!(" {} frame {compared}: {db:.1} dB", short(path)); - } - worst = worst.min(db); - compared += 1; - }); - match result { - Ok(decoded) => table.push(format!( - "{:<52} {decoded:>4} frames, {compared} compared, worst {}", - short(path), - if worst.is_infinite() { - "exact".to_string() - } else { - format!("{worst:.1} dB") - } - )), - Err(e) => failed = Some(e.to_string()), - } - if let Some(reason) = failed { - table.push(format!("{:<52} FAIL {reason}", short(path))); - } - assert!(compared > 0, "{}: nothing decoded", short(path)); - assert!( - worst >= 40.0, - "{}: worst frame {worst:.1} dB against ffmpeg", - short(path) - ); - } - for row in table { - println!("{row}"); - } -} - -/// A library path without the directory tree, so a report can carry it. -fn short(path: &Path) -> String { - path.file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_default() -} - -/// PSNR of one plane, in dB (`f64::INFINITY` for an exact match). -fn plane_psnr(a: &[u16], b: &[u16], peak: f64) -> f64 { - let n = a.len().min(b.len()); - let mse: f64 = a[..n] - .iter() - .zip(&b[..n]) - .map(|(&p, &q)| { - let d = f64::from(p) - f64::from(q); - d * d - }) - .sum::() - / n as f64; - if mse == 0.0 { - f64::INFINITY - } else { - 10.0 * (peak * peak / mse).log10() - } -} - -/// -/// `real_library_spot_check` already pins the whole-frame PSNR at >= 40 dB -/// for a mix of files; this isolates Y from U/V on this specific 10-bit film, -/// against both `yuv420p10le` (the lossless comparison) and `yuv420p` (the -/// truncating `to_i420` path, which rounds ffmpeg's dithered 8-bit output -/// against this crate's un-dithered right-shift -- a real but small gap, not -/// a bug). A collapsed U/V PSNR here (a grey frame) would mean the chroma -/// plane is being read at the wrong stride/offset; it is not, on this file. -#[test] -fn ten_bit_chroma_is_not_grey() { - let Some(display) = display() else { return }; - let path = &ec_testkit::fixture("derived/sintel720-x265-main10.mp4"); - let frames = 3usize; - let data = elementary(path, Codec::H265, frames).expect("elementary stream"); - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut ref10: Option = None; - let mut ref8: Option = None; - let mut compared = 0usize; - decode_stream(&mut decoder, Codec::H265, &data, frames, |frame| { - let (w, h) = frame.display_size; - let ref10 = - ref10.get_or_insert_with(|| Reference::open(path, w, h, true).expect("ffmpeg runs")); - let want10 = ref10.next(w, h).expect("ffmpeg has a frame"); - let got16 = Planes::from_16bit(&frame.to_i420_16().expect("readback")); - let y_db = plane_psnr(&got16.y, &want10.y, 1023.0); - let uv_db = plane_psnr( - &[got16.u.as_slice(), got16.v.as_slice()].concat(), - &[want10.u.as_slice(), want10.v.as_slice()].concat(), - 1023.0, - ); - println!("frame {compared} to_i420_16 vs yuv420p10le: Y {y_db:.1} dB, UV {uv_db:.1} dB"); - assert!( - y_db >= 50.0, - "frame {compared}: Y PSNR collapsed to {y_db:.1} dB" - ); - assert!( - uv_db >= 50.0, - "frame {compared}: chroma PSNR collapsed to {uv_db:.1} dB (grey frame)" - ); - - let ref8 = - ref8.get_or_insert_with(|| Reference::open(path, w, h, false).expect("ffmpeg runs")); - let want8 = ref8.next(w, h).expect("ffmpeg has a frame"); - let got8 = Planes::from_8bit(&frame.to_i420().expect("readback")); - let y_db8 = plane_psnr(&got8.y, &want8.y, 255.0); - let uv_db8 = plane_psnr( - &[got8.u.as_slice(), got8.v.as_slice()].concat(), - &[want8.u.as_slice(), want8.v.as_slice()].concat(), - 255.0, - ); - println!("frame {compared} to_i420 vs yuv420p: Y {y_db8:.1} dB, UV {uv_db8:.1} dB"); - // ffmpeg dithers its 8-bit downconversion; this crate truncates. Both - // are legitimate 10-to-8 roundings, so the floor here is the - // dithering noise floor, not the lossless bound above. - assert!( - y_db8 >= 30.0, - "frame {compared}: 8-bit Y PSNR {y_db8:.1} dB" - ); - assert!( - uv_db8 >= 30.0, - "frame {compared}: 8-bit chroma PSNR collapsed to {uv_db8:.1} dB (grey frame)" - ); - compared += 1; - }) - .expect("decode"); - assert_eq!(compared, frames, "not all frames were compared"); -} - -/// An SDR H.264 stream, which carries no HDR SEI at all: `Frame::colour` -/// either resolves from the VUI or answers [`None`], but never panics. -#[test] -fn sdr_h264_colour_never_panics() { - let Some(display) = display() else { return }; - let paths = ec_testkit::fixtures("bitstreams", "264"); - let path = &paths[0]; - let data = std::fs::read(path).expect("fixture is readable"); - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - let mut seen = 0usize; - decode_stream(&mut decoder, Codec::H264, &data, 2, |frame| { - seen += 1; - // No SEI parsing on this codec: content light is always absent. - if let Some(colour) = frame.colour() { - assert_eq!(colour.light.max_cll, None); - } - }) - .expect("decode"); - assert!(seen > 0, "{}: nothing decoded", short(path)); -} - -/// A CRA GOP boundary stores its RASL leading pictures *after* the CRA in -/// decode order, even though they display before it (they predict from -/// pictures the CRA's own random-access point does not have). A decoder -/// started fresh at that CRA — what a seek does — must therefore drop those -/// RASL pictures per H.265 8.1.3's `NoRaslOutputFlag`, or its output shifts by -/// however many RASL pictures the GOP has, handing back the wrong picture for -/// every display index at or after the seek target. -#[test] -fn hevc_seek_matches_linear_mkv() { - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("video/hevc-open-gop.mkv"); - let data = elementary(&path, Codec::H265, 45).expect("elementary stream"); - let units = split_access_units(&data, Codec::H265); - - // Linear decode: every picture from the start, frame 30 kept for - // comparison (the file's second CRA, per `test_hevc.mkv`'s 30-picture - // GOPs). - const TARGET: usize = 30; - let mut decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - let mut linear_frame_30 = None; - let mut index = 0usize; - decode_stream(&mut decoder, Codec::H265, &data, 45, |frame| { - if index == TARGET { - linear_frame_30 = Some(frame.to_i420().expect("readback")); - } - index += 1; - }) - .expect("linear decode"); - let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); - - // Find the access unit whose first VCL NAL is the CRA at this GOP - // boundary, and feed the decoder from there on, exactly as a seek would: - // nothing from before it goes in. - let cra_at = units - .iter() - .position(|au| starts_with_cra(au)) - .expect("a CRA access unit exists"); - - // A seek reuses the parameter sets a decoder already learned; a fresh one - // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a - // caller to: decode the leading VPS/SPS/PPS (their IDR picture is thrown - // away) and reset picture state before feeding the seek target. - let mut seek_decoder = Decoder::new(&display, Codec::H265).expect("decoder opens"); - seek_decoder - .decode(units[0], 0) - .expect("prime parameter sets"); - seek_decoder.reset(); - let mut seeked_frame = None; - for (i, unit) in units[cra_at..].iter().enumerate() { - seek_decoder.decode(unit, i as i64).expect("seek decode"); - if let Some(frame) = seek_decoder.next_frame() { - seeked_frame = Some(frame.to_i420().expect("readback")); - break; - } - } - if seeked_frame.is_none() { - seek_decoder.flush().expect("flush"); - seeked_frame = seek_decoder - .next_frame() - .map(|f| f.to_i420().expect("readback")); - } - let seeked_frame = seeked_frame.expect("a frame came out after the seek"); - - assert_eq!( - seeked_frame, linear_frame_30, - "seeking to the CRA before frame 30 handed back a different picture \ - than a linear decode of frame 30 — RASL pictures were not dropped" - ); -} - -/// An H.264 open-GOP I picture is not an IDR: it is a plain I slice -/// (`nal_unit_type` 1) whose predecessors in decode order can still hold -/// references from before it, so leading pictures between it and the next -/// IDR may predict from a picture never decoded since a fresh start there — -/// exactly what a seek does. A decoder started at that I must drop those -/// leading pictures per D.2.8's recovery point default, or its output shifts -/// by however many leading pictures the GOP has. -#[test] -fn h264_seek_matches_linear_open_gop() { - let Some(display) = display() else { return }; - let path = ec_testkit::fixture("video/h264-open-gop.mp4"); - let data = elementary(&path, Codec::H264, 60).expect("elementary stream"); - let units = split_access_units(&data, Codec::H264); - - // Linear decode: every picture from the start, frame 30 kept for - // comparison (the fixture's second I picture, `keyint=30`). - const TARGET: usize = 30; - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - let mut linear_frame_30 = None; - let mut index = 0usize; - decode_stream(&mut decoder, Codec::H264, &data, 60, |frame| { - if index == TARGET { - linear_frame_30 = Some(frame.to_i420().expect("readback")); - } - index += 1; - }) - .expect("linear decode"); - let linear_frame_30 = linear_frame_30.expect("linear decode reached frame 30"); - - // Find the access unit whose first VCL NAL is the open-GOP I picture at - // this GOP boundary, and feed the decoder from there on, exactly as a - // seek would: nothing from before it goes in. - let open_gop_at = units - .iter() - .position(|au| is_open_gop_i(au)) - .expect("an open-GOP I access unit exists"); - - // A seek reuses the parameter sets a decoder already learned; a fresh one - // has none, so it is primed the same way `ec_hw::Decoder::reset` expects a - // caller to: decode the leading IDR (its picture is thrown away) and - // reset picture state before feeding the seek target. - let mut seek_decoder = Decoder::new(&display, Codec::H264).expect("decoder opens"); - seek_decoder - .decode(units[0], 0) - .expect("prime parameter sets"); - seek_decoder.reset(); - let mut seeked_frame = None; - for (i, unit) in units[open_gop_at..].iter().enumerate() { - seek_decoder.decode(unit, i as i64).expect("seek decode"); - if let Some(frame) = seek_decoder.next_frame() { - seeked_frame = Some(frame.to_i420().expect("readback")); - break; - } - } - if seeked_frame.is_none() { - seek_decoder.flush().expect("flush"); - seeked_frame = seek_decoder - .next_frame() - .map(|f| f.to_i420().expect("readback")); - } - let seeked_frame = seeked_frame.expect("a frame came out after the seek"); - - assert_eq!( - seeked_frame, linear_frame_30, - "seeking to the open-GOP I before frame 30 handed back a different \ - picture than a linear decode of frame 30 — leading pictures with \ - missing references were not dropped" - ); -} - -/// True when an access unit's first VCL NAL is an H.264 open-GOP I slice -/// (`nal_unit_type` 1, `slice_type % 5 == 2`), found by scanning for the -/// access unit's first start code rather than assuming a fixed prefix length. -fn is_open_gop_i(au: &[u8]) -> bool { - let mut i = 0usize; - while i + 3 < au.len() { - if au[i] != 0 || au[i + 1] != 0 || au[i + 2] != 1 { - i += 1; - continue; - } - let header = au[i + 3]; - if header & 0x1f != 1 { - return false; - } - let mut r = ec_core::BitReader::new(&au[i + 4..]); - if r.read_ue().is_err() { - return false; - } - return matches!(r.read_ue(), Ok(code) if code % 5 == 2); - } - false -} - -/// True when an access unit's first VCL NAL is an HEVC CRA (`nal_type` 21). -/// A CRA's access unit may open with its own VPS/SPS/PPS, so this skips past -/// non-VCL NALs to the first one that carries a slice. -fn starts_with_cra(au: &[u8]) -> bool { - let mut i = 0usize; - while i + 3 < au.len() { - if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { - let t = (au[i + 3] >> 1) & 0x3f; - if t <= 31 { - return t == 21; - } - i += 3; - continue; - } - i += 1; - } - false -} - -/// `ffmpeg -bsf:v trace_headers` over a bitstream, returning every -/// `name = value` line it prints — the slice header fields the driver wrote. -fn trace_headers(path: &Path, codec: &str) -> Vec<(String, i64)> { - let out = ec_testkit::ffmpeg() - .args(["-v", "trace", "-hide_banner", "-nostats", "-f", codec, "-i"]) - .arg(path) - .args(["-c:v", "copy", "-bsf:v", "trace_headers", "-f", "null", "-"]) - .output() - .expect("ffmpeg runs"); - let text = String::from_utf8_lossy(&out.stderr); - text.lines() - .filter_map(|line| { - // "[trace_headers @ 0x...] 16 frame_num 0000 = 0" - let (lhs, value) = line.rsplit_once(" = ")?; - let mut words = lhs.split_whitespace().rev(); - let _bits = words.next()?; - let name = words.next()?; - Some((name.to_string(), value.trim().parse().ok()?)) - }) - .collect() -} - -/// Phone-class stateful decoders order output from `frame_num` and the POC -/// fields, so a stream whose every slice says 0/0 judders there even though -/// desktop decoders (which re-derive from decode order) play it cleanly. -/// Encode a long P-run and read the fields back the way such a decoder does. -fn slice_counters( - codec: EncCodec, - width: u32, - height: u32, - frames: u32, -) -> (PathBuf, Vec<(String, i64)>) { - let Some(display) = display() else { - return (PathBuf::new(), Vec::new()); - }; - let mut config = EncoderConfig::new(codec, width, height); - config.gop_size = frames * 2; - config.framerate = (30, 1); - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; - let mut encoder = Encoder::new(&display, config).expect("encoder"); - let mut out = Vec::new(); - for t in 0..frames { - let coded = encoder - .encode( - &source_frame(width, height, t), - FrameMetadata { - timestamp: i64::from(t), - force_keyframe: false, - }, - ) - .expect("encode"); - assert_eq!(coded.is_keyframe, t == 0, "one IDR then P-frames at {t}"); - out.extend_from_slice(&coded.data); - } - let dir = std::env::temp_dir().join(format!("ec-hw-counters-{codec:?}")); - std::fs::create_dir_all(&dir).expect("temp dir"); - let (name, fmt) = match codec { - EncCodec::H264 => ("out.264", "h264"), - EncCodec::H265 => ("out.265", "hevc"), - EncCodec::Av1 => unreachable!(), - }; - let path = dir.join(name); - std::fs::write(&path, &out).expect("write"); - let fields = trace_headers(&path, fmt); - (path, fields) -} - -fn values(fields: &[(String, i64)], name: &str) -> Vec { - fields - .iter() - .filter(|(n, _)| n == name) - .map(|(_, v)| *v) - .collect() -} - -#[test] -fn h264_slice_headers_count_frames_for_stateful_decoders() { - let frames = 64u32; - let (path, fields) = slice_counters(EncCodec::H264, 640, 360, frames); - if fields.is_empty() { - return; - } - let frame_num = values(&fields, "frame_num"); - assert_eq!( - frame_num.len(), - frames as usize, - "one slice per picture in {}", - path.display() - ); - let log2_max = values(&fields, "log2_max_frame_num_minus4")[0] + 4; - let max_frame_num = 1i64 << log2_max; - let expected: Vec = (0..frames as i64).map(|n| n % max_frame_num).collect(); - assert_eq!( - frame_num, expected, - "frame_num steps +1 mod {max_frame_num}" - ); - // pic_order_cnt_type 2: POC = 2 * FrameNumOffset-adjusted frame_num, no lsb is - // written — the decoder's output order is the decode order by construction. - let poc_type = values(&fields, "pic_order_cnt_type"); - assert!( - !poc_type.is_empty() && poc_type.iter().all(|&t| t == 2), - "POC type 2 in the SPS: {poc_type:?}" - ); - assert!( - values(&fields, "pic_order_cnt_lsb").is_empty(), - "no POC lsb under type 2" - ); - assert!( - values(&fields, "level_idc").iter().all(|&l| l == 30), - "640x360@30 is level 3.0" - ); -} - -#[test] -fn hevc_slice_headers_count_pocs_for_stateful_decoders() { - let frames = 64u32; - let (path, fields) = slice_counters(EncCodec::H265, 640, 360, frames); - if fields.is_empty() { - return; - } - let lsb = values(&fields, "slice_pic_order_cnt_lsb"); - assert_eq!( - lsb.len(), - frames as usize - 1, - "every non-IDR slice carries a POC lsb in {}", - path.display() - ); - let log2_max = values(&fields, "log2_max_pic_order_cnt_lsb_minus4")[0] + 4; - let max_lsb = 1i64 << log2_max; - let expected: Vec = (1..frames as i64).map(|n| n % max_lsb).collect(); - assert_eq!(lsb, expected, "POC lsb steps +1 mod {max_lsb}"); -} - -// --------------------------------------------------------------------------- -// Rate control: achieved bitrate against the request, and PSNR at that rate -// --------------------------------------------------------------------------- - -/// Write 8-bit 4:2:0 frames as a y4m file, the reference ffmpeg compares with. -fn write_y4m_8(path: &Path, frames: &[I420], fps: u32) -> bool { - use std::io::Write; - let Some(first) = frames.first() else { - return false; - }; - let Ok(file) = std::fs::File::create(path) else { - return false; - }; - let mut out = std::io::BufWriter::new(file); - let header = format!( - "YUV4MPEG2 W{} H{} F{fps}:1 Ip A1:1 C420jpeg\n", - first.width, first.height - ); - if out.write_all(header.as_bytes()).is_err() { - return false; - } - for f in frames { - if out.write_all(b"FRAME\n").is_err() - || out.write_all(&f.y).is_err() - || out.write_all(&f.u).is_err() - || out.write_all(&f.v).is_err() - { - return false; - } - } - out.flush().is_ok() -} - -/// Average PSNR (dB) of a raw elementary stream against its source y4m. -fn psnr_of_elementary(coded: &Path, format: &str, source: &Path, fps: u32) -> Option { - let rate = fps.to_string(); - let out = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "info", "-f", format, "-r", &rate, "-i"]) - .arg(coded) - .args(["-r", &rate, "-i"]) - .arg(source) - .args(["-lavfi", "psnr", "-f", "null", "-"]) - .output() - .ok()?; - let text = String::from_utf8_lossy(&out.stderr); - let field = text.split("average:").nth(1)?; - field - .split_whitespace() - .next()? - .parse::() - .ok() - .filter(|v| v.is_finite()) -} - -/// One CBR encode of `frames` at `bitrate`: the stream, and the bits per second -/// it actually spent over the clip. -fn cbr_encode( - display: &Rc, - codec: EncCodec, - (width, height, fps): (u32, u32, u32), - bitrate: u32, - frames: &[I420], -) -> Result<(Vec, f64), ec_hw::Error> { - let mut config = EncoderConfig::new(codec, width, height); - config.framerate = (fps, 1); - config.gop_size = 30; - config.bitrate = bitrate; - config.rate_control = RateControlMode::ConstantBitrate; - let mut encoder = Encoder::new(display, config)?; - let mut out = Vec::new(); - for (t, frame) in frames.iter().enumerate() { - let coded = encoder.encode( - frame, - FrameMetadata { - timestamp: t as i64, - force_keyframe: false, - }, - )?; - out.extend_from_slice(&coded.data); - } - let delivered = out.len() as f64 * 8.0 * f64::from(fps) / frames.len() as f64; - Ok((out, delivered)) -} - -/// CBR must land within +/-5% of the request on every codec, clip and rate, -/// and the PSNR it reaches at that rate is printed for the report. -#[test] -fn cbr_lands_within_five_percent_of_the_request() { - let Some(display) = display() else { return }; - // 8 s: a 2 s clip also carries the start-up of the rate controller, which - // is measured apart from the steady-state rate the request is about. - let (width, height, fps, frames) = (1280u32, 720u32, 30u32, 240u32); - let dir = std::env::temp_dir().join("ec-hw-rc-measure"); - std::fs::create_dir_all(&dir).expect("temp dir"); - - // Two clips: a synthetic moving box, and ffmpeg's testsrc2 (the content the - // edith measurements used), both generated here so nothing depends on a - // personal library. - let synthetic: Vec = (0..frames) - .map(|t| source_frame(width, height, t)) - .collect(); - let synthetic_y4m = dir.join("cbr-synthetic.y4m"); - assert!(write_y4m_8(&synthetic_y4m, &synthetic, fps), "write source"); - let testsrc_y4m = dir.join("cbr-testsrc2.y4m"); - let generated = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) - .arg(format!("testsrc2=size={width}x{height}:rate={fps}")) - .args(["-frames:v", &frames.to_string(), "-pix_fmt", "yuv420p"]) - .arg(&testsrc_y4m) - .status() - .is_ok_and(|s| s.success()); - let testsrc = generated - .then(|| raw_frames(&testsrc_y4m, width, height, frames)) - .flatten() - .expect("ffmpeg generates testsrc2"); - let clips: [(&str, Vec, PathBuf); 2] = [ - ("moving box", synthetic, synthetic_y4m), - ("testsrc2", testsrc, testsrc_y4m), - ]; - let mut failures = Vec::new(); - println!("CBR, {width}x{height} {fps} fps, {frames} frames:"); - for (codec, name, format) in [ - (EncCodec::H264, "H.264", "h264"), - (EncCodec::H265, "HEVC", "hevc"), - (EncCodec::Av1, "AV1", "obu"), - ] { - for (clip_name, pictures, source) in &clips { - for target in [1_000_000u32, 3_000_000, 8_000_000] { - let (stream, delivered) = - match cbr_encode(&display, codec, (width, height, fps), target, pictures) { - Ok(encoded) => encoded, - Err(e) => panic!("{name} {clip_name} at {target} bps: encode failed ({e})"), - }; - let coded = dir.join(format!( - "{name}-{}-{target}.{format}", - clip_name.replace(' ', "-") - )); - std::fs::write(&coded, &stream).expect("write stream"); - let db = psnr_of_elementary(&coded, format, source, fps).unwrap_or(f64::NAN); - let error = delivered / f64::from(target) - 1.0; - println!( - " {name:<6} {clip_name:<12} target {:>5} kbps -> {:>6.0} kbps ({:+5.1}%), {db:.2} dB", - target / 1000, - delivered / 1000.0, - error * 100.0 - ); - if error.abs() > 0.05 { - failures.push(format!( - "{name} {clip_name} at {target} bps: {:+.1}%", - error * 100.0 - )); - } - } - } - } - assert!(failures.is_empty(), "outside +/-5%: {failures:?}"); -} - -/// Encoding an imported DMA-BUF must give the bytes the CPU path gives for the -/// same pixels: the import is only a different way of handing over the source. -// --------------------------------------------------------------------------- -// Broken streams: an inter picture whose references were never decoded -// --------------------------------------------------------------------------- - -/// The OBUs of an AV1 temporal unit, as whole byte slices (each with its header). -fn av1_obus(tu: &[u8]) -> Vec<&[u8]> { - let mut out = Vec::new(); - let mut i = 0usize; - while i < tu.len() { - let header = tu[i]; - let ext = usize::from((header >> 2) & 1); - if (header >> 1) & 1 == 0 { - break; // no obu_size: the rest of the unit is one OBU - } - let mut size = 0usize; - let mut pos = i + 1 + ext; - for shift in (0..64).step_by(7) { - let Some(&byte) = tu.get(pos) else { return out }; - pos += 1; - size |= usize::from(byte & 0x7f) << shift; - if byte & 0x80 == 0 { - break; - } - } - let end = (pos + size).min(tu.len()); - out.push(&tu[i..end]); - i = end; - } - out -} - -/// The Annex B NAL units of an access unit, without their start codes. -fn annexb_nals(au: &[u8]) -> Vec<&[u8]> { - let mut starts = Vec::new(); - let mut i = 0usize; - while i + 3 <= au.len() { - if au[i] == 0 && au[i + 1] == 0 && au[i + 2] == 1 { - starts.push(i + 3); - i += 3; - } else { - i += 1; - } - } - starts - .iter() - .enumerate() - .map(|(n, &start)| { - let end = starts.get(n + 1).map_or(au.len(), |&next| next - 3); - let mut nal = &au[start..end]; - while let [rest @ .., 0] = nal { - nal = rest; // trailing zeros belong to the next start code - } - nal - }) - .collect() -} - -/// A stream that starts at an inter picture: the parameter sets of the first -/// access unit, then the access unit that follows it, with the picture that -/// would have filled its references (the first access unit) left out. -fn broken_gop(codec: Codec, data: &[u8]) -> Option> { - let mut stream = Vec::new(); - match codec { - Codec::Av1 => { - let units = split_ivf(data); - // The sequence header OBU, which the first temporal unit carries. - let seq = av1_obus(units.first()?) - .into_iter() - .find(|obu| (obu[0] >> 3) & 0xf == 1)?; - stream.extend_from_slice(seq); - stream.extend_from_slice(units.get(1)?); - } - Codec::Vp9 => { - // VP9 carries its parameters in the frame header: the inter frame - // alone is the broken stream. - stream.extend_from_slice(split_ivf(data).get(1)?); - } - Codec::H264 | Codec::H265 => { - let units = split_access_units(data, codec); - let is_parameter_set = |nal: &[u8]| { - let t = match codec { - Codec::H264 => nal[0] & 0x1f, - _ => (nal[0] >> 1) & 0x3f, - }; - match codec { - Codec::H264 => t == 7 || t == 8, - _ => (32..=34).contains(&t), - } - }; - for nal in annexb_nals(units.first()?) { - if is_parameter_set(nal) { - stream.extend_from_slice(&[0, 0, 0, 1]); - stream.extend_from_slice(nal); - } - } - stream.extend_from_slice(units.get(1)?); - } - } - Some(stream) -} - -/// Each codec's broken GOP is refused with an error at the first access unit -/// that needs the missing picture, and never produces a picture. Refusing an -/// inter frame whose references were never filled is what the software -/// decoders do (ec-av1: "no saved CDF state"). -#[test] -fn a_broken_gop_is_refused_on_every_codec() { - let Some(display) = display() else { return }; - let cases = [ - (Codec::Av1, "av1-1080p-23.976-8bit.ivf"), - (Codec::Vp9, "vp9-1080p-23.976-8bit.ivf"), - (Codec::H264, "h264-bframes-320.264"), - (Codec::H265, "hevc-bframes-320.265"), - ]; - for (codec, name) in cases { - let path = ec_testkit::fixture(&format!("bitstreams/{name}")); - let data = std::fs::read(&path).expect("fixture is readable"); - let stream = broken_gop(codec, &data).expect("the fixture has a second access unit"); - let mut decoder = Decoder::new(&display, codec).expect("decoder"); - let refusal = decoder.decode(&stream, 0).err().map(|e| e.to_string()); - let mut pictures = 0usize; - while decoder.next_frame().is_some() { - pictures += 1; - } - assert!( - refusal.is_some(), - "{codec:?} {name}: the broken GOP decoded without an error ({pictures} pictures)" - ); - assert_eq!( - pictures, 0, - "{codec:?} {name}: a picture came out of a broken GOP" - ); - println!("{codec:?} {name}: refused: {}", refusal.unwrap_or_default()); - } -} - -#[test] -fn h264_encode_decodes_with_no_reorder_delay() { - let Some(display) = display() else { return }; - let mut config = EncoderConfig::new(EncCodec::H264, 1280, 720); - config.framerate = (30, 1); - config.gop_size = 30; - config.rate_control = RateControlMode::ConstantQp { qp: 30 }; - let mut encoder = Encoder::new(&display, config).expect("encoder"); - let mut decoder = Decoder::new(&display, Codec::H264).expect("decoder"); - for t in 0..10 { - let meta = FrameMetadata { - timestamp: i64::from(t), - force_keyframe: false, - }; - let unit = encoder - .encode(&source_frame(1280, 720, t), meta) - .expect("encode"); - decoder.decode(&unit.data, i64::from(t)).expect("decode"); - assert!(decoder.next_frame().is_some(), "frame {t} held back"); - } -}